source: mainline/kernel/generic/src/mm/frame.c@ 9a5abb78

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 9a5abb78 was 9a5abb78, checked in by Vojtech Horky <vojtechhorky@…>, 11 years ago

Unbreak non-debug builds (thx Wolf Ramovsky)

  • Property mode set to 100644
File size: 36.6 KB
Line 
1/*
2 * Copyright (c) 2001-2005 Jakub Jermar
3 * Copyright (c) 2005 Sergey Bondari
4 * Copyright (c) 2009 Martin Decky
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * - Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * - The name of the author may not be used to endorse or promote products
17 * derived from this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31/** @addtogroup genericmm
32 * @{
33 */
34
35/**
36 * @file
37 * @brief Physical frame allocator.
38 *
39 * This file contains the physical frame allocator and memory zone management.
40 * The frame allocator is built on top of the two-level bitmap structure.
41 *
42 */
43
44#include <typedefs.h>
45#include <mm/frame.h>
46#include <mm/reserve.h>
47#include <mm/as.h>
48#include <panic.h>
49#include <debug.h>
50#include <adt/list.h>
51#include <synch/mutex.h>
52#include <synch/condvar.h>
53#include <arch/asm.h>
54#include <arch.h>
55#include <print.h>
56#include <log.h>
57#include <align.h>
58#include <mm/slab.h>
59#include <bitops.h>
60#include <macros.h>
61#include <config.h>
62#include <str.h>
63
64zones_t zones;
65
66/*
67 * Synchronization primitives used to sleep when there is no memory
68 * available.
69 */
70static mutex_t mem_avail_mtx;
71static condvar_t mem_avail_cv;
72static size_t mem_avail_req = 0; /**< Number of frames requested. */
73static size_t mem_avail_gen = 0; /**< Generation counter. */
74
75/********************/
76/* Helper functions */
77/********************/
78
79NO_TRACE static inline size_t frame_index(zone_t *zone, frame_t *frame)
80{
81 return (size_t) (frame - zone->frames);
82}
83
84NO_TRACE static inline size_t frame_index_abs(zone_t *zone, frame_t *frame)
85{
86 return (size_t) (frame - zone->frames) + zone->base;
87}
88
89NO_TRACE static inline bool frame_index_valid(zone_t *zone, size_t index)
90{
91 return (index < zone->count);
92}
93
94/** Initialize frame structure.
95 *
96 * @param frame Frame structure to be initialized.
97 *
98 */
99NO_TRACE static void frame_initialize(frame_t *frame)
100{
101 frame->refcount = 0;
102 frame->parent = NULL;
103}
104
105/*******************/
106/* Zones functions */
107/*******************/
108
109/** Insert-sort zone into zones list.
110 *
111 * Assume interrupts are disabled and zones lock is
112 * locked.
113 *
114 * @param base Base frame of the newly inserted zone.
115 * @param count Number of frames of the newly inserted zone.
116 *
117 * @return Zone number on success, -1 on error.
118 *
119 */
120NO_TRACE static size_t zones_insert_zone(pfn_t base, size_t count,
121 zone_flags_t flags)
122{
123 if (zones.count + 1 == ZONES_MAX) {
124 log(LF_OTHER, LVL_ERROR, "Maximum zone count %u exceeded!",
125 ZONES_MAX);
126 return (size_t) -1;
127 }
128
129 size_t i;
130 for (i = 0; i < zones.count; i++) {
131 /* Check for overlap */
132 if (overlaps(zones.info[i].base, zones.info[i].count,
133 base, count)) {
134
135 /*
136 * If the overlaping zones are of the same type
137 * and the new zone is completely within the previous
138 * one, then quietly ignore the new zone.
139 *
140 */
141
142 if ((zones.info[i].flags != flags) ||
143 (!iswithin(zones.info[i].base, zones.info[i].count,
144 base, count))) {
145 log(LF_OTHER, LVL_WARN,
146 "Zone (%p, %p) overlaps "
147 "with previous zone (%p %p)!",
148 (void *) PFN2ADDR(base), (void *) PFN2ADDR(count),
149 (void *) PFN2ADDR(zones.info[i].base),
150 (void *) PFN2ADDR(zones.info[i].count));
151 }
152
153 return (size_t) -1;
154 }
155 if (base < zones.info[i].base)
156 break;
157 }
158
159 /* Move other zones up */
160 for (size_t j = zones.count; j > i; j--)
161 zones.info[j] = zones.info[j - 1];
162
163 zones.count++;
164
165 return i;
166}
167
168/** Get total available frames.
169 *
170 * Assume interrupts are disabled and zones lock is
171 * locked.
172 *
173 * @return Total number of available frames.
174 *
175 */
176NO_TRACE static size_t frame_total_free_get_internal(void)
177{
178 size_t total = 0;
179 size_t i;
180
181 for (i = 0; i < zones.count; i++)
182 total += zones.info[i].free_count;
183
184 return total;
185}
186
187NO_TRACE size_t frame_total_free_get(void)
188{
189 size_t total;
190
191 irq_spinlock_lock(&zones.lock, true);
192 total = frame_total_free_get_internal();
193 irq_spinlock_unlock(&zones.lock, true);
194
195 return total;
196}
197
198
199/** Find a zone with a given frames.
200 *
201 * Assume interrupts are disabled and zones lock is
202 * locked.
203 *
204 * @param frame Frame number contained in zone.
205 * @param count Number of frames to look for.
206 * @param hint Used as zone hint.
207 *
208 * @return Zone index or -1 if not found.
209 *
210 */
211NO_TRACE size_t find_zone(pfn_t frame, size_t count, size_t hint)
212{
213 if (hint >= zones.count)
214 hint = 0;
215
216 size_t i = hint;
217 do {
218 if ((zones.info[i].base <= frame)
219 && (zones.info[i].base + zones.info[i].count >= frame + count))
220 return i;
221
222 i++;
223 if (i >= zones.count)
224 i = 0;
225
226 } while (i != hint);
227
228 return (size_t) -1;
229}
230
231/** @return True if zone can allocate specified number of frames */
232NO_TRACE static bool zone_can_alloc(zone_t *zone, size_t count,
233 pfn_t constraint)
234{
235 /*
236 * The function bitmap_allocate_range() does not modify
237 * the bitmap if the last argument is NULL.
238 */
239
240 return ((zone->flags & ZONE_AVAILABLE) &&
241 bitmap_allocate_range(&zone->bitmap, count, zone->base,
242 FRAME_LOWPRIO, constraint, NULL));
243}
244
245/** Find a zone that can allocate specified number of frames
246 *
247 * This function searches among all zones. Assume interrupts are
248 * disabled and zones lock is locked.
249 *
250 * @param count Number of free frames we are trying to find.
251 * @param flags Required flags of the zone.
252 * @param constraint Indication of bits that cannot be set in the
253 * physical frame number of the first allocated frame.
254 * @param hint Preferred zone.
255 *
256 * @return Zone that can allocate specified number of frames.
257 * @return -1 if no zone can satisfy the request.
258 *
259 */
260NO_TRACE static size_t find_free_zone_all(size_t count, zone_flags_t flags,
261 pfn_t constraint, size_t hint)
262{
263 for (size_t pos = 0; pos < zones.count; pos++) {
264 size_t i = (pos + hint) % zones.count;
265
266 /* Check whether the zone meets the search criteria. */
267 if (!ZONE_FLAGS_MATCH(zones.info[i].flags, flags))
268 continue;
269
270 /* Check if the zone can satisfy the allocation request. */
271 if (zone_can_alloc(&zones.info[i], count, constraint))
272 return i;
273 }
274
275 return (size_t) -1;
276}
277
278/** Check if frame range priority memory
279 *
280 * @param pfn Starting frame.
281 * @param count Number of frames.
282 *
283 * @return True if the range contains only priority memory.
284 *
285 */
286NO_TRACE static bool is_high_priority(pfn_t base, size_t count)
287{
288 return (base + count <= FRAME_LOWPRIO);
289}
290
291/** Find a zone that can allocate specified number of frames
292 *
293 * This function ignores zones that contain only high-priority
294 * memory. Assume interrupts are disabled and zones lock is locked.
295 *
296 * @param count Number of free frames we are trying to find.
297 * @param flags Required flags of the zone.
298 * @param constraint Indication of bits that cannot be set in the
299 * physical frame number of the first allocated frame.
300 * @param hint Preferred zone.
301 *
302 * @return Zone that can allocate specified number of frames.
303 * @return -1 if no low-priority zone can satisfy the request.
304 *
305 */
306NO_TRACE static size_t find_free_zone_lowprio(size_t count, zone_flags_t flags,
307 pfn_t constraint, size_t hint)
308{
309 for (size_t pos = 0; pos < zones.count; pos++) {
310 size_t i = (pos + hint) % zones.count;
311
312 /* Skip zones containing only high-priority memory. */
313 if (is_high_priority(zones.info[i].base, zones.info[i].count))
314 continue;
315
316 /* Check whether the zone meets the search criteria. */
317 if (!ZONE_FLAGS_MATCH(zones.info[i].flags, flags))
318 continue;
319
320 /* Check if the zone can satisfy the allocation request. */
321 if (zone_can_alloc(&zones.info[i], count, constraint))
322 return i;
323 }
324
325 return (size_t) -1;
326}
327
328/** Find a zone that can allocate specified number of frames
329 *
330 * Assume interrupts are disabled and zones lock is
331 * locked.
332 *
333 * @param count Number of free frames we are trying to find.
334 * @param flags Required flags of the target zone.
335 * @param constraint Indication of bits that cannot be set in the
336 * physical frame number of the first allocated frame.
337 * @param hint Preferred zone.
338 *
339 * @return Zone that can allocate specified number of frames.
340 * @return -1 if no zone can satisfy the request.
341 *
342 */
343NO_TRACE static size_t find_free_zone(size_t count, zone_flags_t flags,
344 pfn_t constraint, size_t hint)
345{
346 if (hint >= zones.count)
347 hint = 0;
348
349 /*
350 * Prefer zones with low-priority memory over
351 * zones with high-priority memory.
352 */
353
354 size_t znum = find_free_zone_lowprio(count, flags, constraint, hint);
355 if (znum != (size_t) -1)
356 return znum;
357
358 /* Take all zones into account */
359 return find_free_zone_all(count, flags, constraint, hint);
360}
361
362/******************/
363/* Zone functions */
364/******************/
365
366/** Return frame from zone. */
367NO_TRACE static frame_t *zone_get_frame(zone_t *zone, size_t index)
368{
369 ASSERT(index < zone->count);
370
371 return &zone->frames[index];
372}
373
374/** Allocate frame in particular zone.
375 *
376 * Assume zone is locked and is available for allocation.
377 * Panics if allocation is impossible.
378 *
379 * @param zone Zone to allocate from.
380 * @param count Number of frames to allocate
381 * @param constraint Indication of bits that cannot be set in the
382 * physical frame number of the first allocated frame.
383 *
384 * @return Frame index in zone.
385 *
386 */
387NO_TRACE static size_t zone_frame_alloc(zone_t *zone, size_t count,
388 pfn_t constraint)
389{
390 ASSERT(zone->flags & ZONE_AVAILABLE);
391
392 /* Allocate frames from zone */
393 size_t index;
394 int avail = bitmap_allocate_range(&zone->bitmap, count, zone->base,
395 FRAME_LOWPRIO, constraint, &index);
396
397 ASSERT(avail);
398
399 /* Update frame reference count */
400 for (size_t i = 0; i < count; i++) {
401 frame_t *frame = zone_get_frame(zone, index + i);
402
403 ASSERT(frame->refcount == 0);
404 frame->refcount = 1;
405 }
406
407 /* Update zone information. */
408 zone->free_count -= count;
409 zone->busy_count += count;
410
411 return index;
412}
413
414/** Free frame from zone.
415 *
416 * Assume zone is locked and is available for deallocation.
417 *
418 * @param zone Pointer to zone from which the frame is to be freed.
419 * @param index Frame index relative to zone.
420 *
421 * @return Number of freed frames.
422 *
423 */
424NO_TRACE static size_t zone_frame_free(zone_t *zone, size_t index)
425{
426 ASSERT(zone->flags & ZONE_AVAILABLE);
427
428 frame_t *frame = zone_get_frame(zone, index);
429
430 ASSERT(frame->refcount > 0);
431
432 if (!--frame->refcount) {
433 bitmap_set(&zone->bitmap, index, 0);
434
435 /* Update zone information. */
436 zone->free_count++;
437 zone->busy_count--;
438
439 return 1;
440 }
441
442 return 0;
443}
444
445/** Mark frame in zone unavailable to allocation. */
446NO_TRACE static void zone_mark_unavailable(zone_t *zone, size_t index)
447{
448 ASSERT(zone->flags & ZONE_AVAILABLE);
449
450 frame_t *frame = zone_get_frame(zone, index);
451 if (frame->refcount > 0)
452 return;
453
454 frame->refcount = 1;
455 bitmap_set_range(&zone->bitmap, index, 1);
456
457 zone->free_count--;
458 reserve_force_alloc(1);
459}
460
461/** Merge two zones.
462 *
463 * Assume z1 & z2 are locked and compatible and zones lock is
464 * locked.
465 *
466 * @param z1 First zone to merge.
467 * @param z2 Second zone to merge.
468 * @param old_z1 Original data of the first zone.
469 * @param confdata Merged zone configuration data.
470 *
471 */
472NO_TRACE static void zone_merge_internal(size_t z1, size_t z2, zone_t *old_z1,
473 void *confdata)
474{
475 ASSERT(zones.info[z1].flags & ZONE_AVAILABLE);
476 ASSERT(zones.info[z2].flags & ZONE_AVAILABLE);
477 ASSERT(zones.info[z1].flags == zones.info[z2].flags);
478 ASSERT(zones.info[z1].base < zones.info[z2].base);
479 ASSERT(!overlaps(zones.info[z1].base, zones.info[z1].count,
480 zones.info[z2].base, zones.info[z2].count));
481
482 /* Difference between zone bases */
483 pfn_t base_diff = zones.info[z2].base - zones.info[z1].base;
484
485 zones.info[z1].count = base_diff + zones.info[z2].count;
486 zones.info[z1].free_count += zones.info[z2].free_count;
487 zones.info[z1].busy_count += zones.info[z2].busy_count;
488
489 bitmap_initialize(&zones.info[z1].bitmap, zones.info[z1].count,
490 confdata + (sizeof(frame_t) * zones.info[z1].count));
491 bitmap_clear_range(&zones.info[z1].bitmap, 0, zones.info[z1].count);
492
493 zones.info[z1].frames = (frame_t *) confdata;
494
495 /*
496 * Copy frames and bits from both zones to preserve parents, etc.
497 */
498
499 for (size_t i = 0; i < old_z1->count; i++) {
500 bitmap_set(&zones.info[z1].bitmap, i,
501 bitmap_get(&old_z1->bitmap, i));
502 zones.info[z1].frames[i] = old_z1->frames[i];
503 }
504
505 for (size_t i = 0; i < zones.info[z2].count; i++) {
506 bitmap_set(&zones.info[z1].bitmap, base_diff + i,
507 bitmap_get(&zones.info[z2].bitmap, i));
508 zones.info[z1].frames[base_diff + i] =
509 zones.info[z2].frames[i];
510 }
511}
512
513/** Return old configuration frames into the zone.
514 *
515 * We have two cases:
516 * - The configuration data is outside the zone
517 * -> do nothing (perhaps call frame_free?)
518 * - The configuration data was created by zone_create
519 * or updated by reduce_region -> free every frame
520 *
521 * @param znum The actual zone where freeing should occur.
522 * @param pfn Old zone configuration frame.
523 * @param count Old zone frame count.
524 *
525 */
526NO_TRACE static void return_config_frames(size_t znum, pfn_t pfn, size_t count)
527{
528 ASSERT(zones.info[znum].flags & ZONE_AVAILABLE);
529
530 size_t cframes = SIZE2FRAMES(zone_conf_size(count));
531
532 if ((pfn < zones.info[znum].base) ||
533 (pfn >= zones.info[znum].base + zones.info[znum].count))
534 return;
535
536 for (size_t i = 0; i < cframes; i++)
537 (void) zone_frame_free(&zones.info[znum],
538 pfn - zones.info[znum].base + i);
539}
540
541/** Merge zones z1 and z2.
542 *
543 * The merged zones must be 2 zones with no zone existing in between
544 * (which means that z2 = z1 + 1). Both zones must be available zones
545 * with the same flags.
546 *
547 * When you create a new zone, the frame allocator configuration does
548 * not to be 2^order size. Once the allocator is running it is no longer
549 * possible, merged configuration data occupies more space :-/
550 *
551 */
552bool zone_merge(size_t z1, size_t z2)
553{
554 irq_spinlock_lock(&zones.lock, true);
555
556 bool ret = true;
557
558 /*
559 * We can join only 2 zones with none existing inbetween,
560 * the zones have to be available and with the same
561 * set of flags
562 */
563 if ((z1 >= zones.count) || (z2 >= zones.count) || (z2 - z1 != 1) ||
564 (zones.info[z1].flags != zones.info[z2].flags)) {
565 ret = false;
566 goto errout;
567 }
568
569 pfn_t cframes = SIZE2FRAMES(zone_conf_size(
570 zones.info[z2].base - zones.info[z1].base
571 + zones.info[z2].count));
572
573 /* Allocate merged zone data inside one of the zones */
574 pfn_t pfn;
575 if (zone_can_alloc(&zones.info[z1], cframes, 0)) {
576 pfn = zones.info[z1].base +
577 zone_frame_alloc(&zones.info[z1], cframes, 0);
578 } else if (zone_can_alloc(&zones.info[z2], cframes, 0)) {
579 pfn = zones.info[z2].base +
580 zone_frame_alloc(&zones.info[z2], cframes, 0);
581 } else {
582 ret = false;
583 goto errout;
584 }
585
586 /* Preserve original data from z1 */
587 zone_t old_z1 = zones.info[z1];
588
589 /* Do zone merging */
590 zone_merge_internal(z1, z2, &old_z1, (void *) PA2KA(PFN2ADDR(pfn)));
591
592 /* Subtract zone information from busy frames */
593 zones.info[z1].busy_count -= cframes;
594
595 /* Free old zone information */
596 return_config_frames(z1,
597 ADDR2PFN(KA2PA((uintptr_t) old_z1.frames)), old_z1.count);
598 return_config_frames(z1,
599 ADDR2PFN(KA2PA((uintptr_t) zones.info[z2].frames)),
600 zones.info[z2].count);
601
602 /* Move zones down */
603 for (size_t i = z2 + 1; i < zones.count; i++)
604 zones.info[i - 1] = zones.info[i];
605
606 zones.count--;
607
608errout:
609 irq_spinlock_unlock(&zones.lock, true);
610
611 return ret;
612}
613
614/** Merge all mergeable zones into one big zone.
615 *
616 * It is reasonable to do this on systems where
617 * BIOS reports parts in chunks, so that we could
618 * have 1 zone (it's faster).
619 *
620 */
621void zone_merge_all(void)
622{
623 size_t i = 1;
624
625 while (i < zones.count) {
626 if (!zone_merge(i - 1, i))
627 i++;
628 }
629}
630
631/** Create new frame zone.
632 *
633 * @param zone Zone to construct.
634 * @param start Physical address of the first frame within the zone.
635 * @param count Count of frames in zone.
636 * @param flags Zone flags.
637 * @param confdata Configuration data of the zone.
638 *
639 * @return Initialized zone.
640 *
641 */
642NO_TRACE static void zone_construct(zone_t *zone, pfn_t start, size_t count,
643 zone_flags_t flags, void *confdata)
644{
645 zone->base = start;
646 zone->count = count;
647 zone->flags = flags;
648 zone->free_count = count;
649 zone->busy_count = 0;
650
651 if (flags & ZONE_AVAILABLE) {
652 /*
653 * Initialize frame bitmap (located after the array of
654 * frame_t structures in the configuration space).
655 */
656
657 bitmap_initialize(&zone->bitmap, count, confdata +
658 (sizeof(frame_t) * count));
659 bitmap_clear_range(&zone->bitmap, 0, count);
660
661 /*
662 * Initialize the array of frame_t structures.
663 */
664
665 zone->frames = (frame_t *) confdata;
666
667 for (size_t i = 0; i < count; i++)
668 frame_initialize(&zone->frames[i]);
669 } else {
670 bitmap_initialize(&zone->bitmap, 0, NULL);
671 zone->frames = NULL;
672 }
673}
674
675/** Compute configuration data size for zone.
676 *
677 * @param count Size of zone in frames.
678 *
679 * @return Size of zone configuration info (in bytes).
680 *
681 */
682size_t zone_conf_size(size_t count)
683{
684 return (count * sizeof(frame_t) + bitmap_size(count));
685}
686
687/** Allocate external configuration frames from low memory. */
688pfn_t zone_external_conf_alloc(size_t count)
689{
690 size_t frames = SIZE2FRAMES(zone_conf_size(count));
691
692 return ADDR2PFN((uintptr_t)
693 frame_alloc(frames, FRAME_LOWMEM | FRAME_ATOMIC, 0));
694}
695
696/** Create and add zone to system.
697 *
698 * @param start First frame number (absolute).
699 * @param count Size of zone in frames.
700 * @param confframe Where configuration frames are supposed to be.
701 * Automatically checks that we will not disturb the
702 * kernel and possibly init. If confframe is given
703 * _outside_ this zone, it is expected, that the area is
704 * already marked BUSY and big enough to contain
705 * zone_conf_size() amount of data. If the confframe is
706 * inside the area, the zone free frame information is
707 * modified not to include it.
708 *
709 * @return Zone number or -1 on error.
710 *
711 */
712size_t zone_create(pfn_t start, size_t count, pfn_t confframe,
713 zone_flags_t flags)
714{
715 irq_spinlock_lock(&zones.lock, true);
716
717 if (flags & ZONE_AVAILABLE) { /* Create available zone */
718 /*
719 * Theoretically we could have NULL here, practically make sure
720 * nobody tries to do that. If some platform requires, remove
721 * the assert
722 */
723 ASSERT(confframe != ADDR2PFN((uintptr_t ) NULL));
724
725 /* Update the known end of physical memory. */
726 config.physmem_end = max(config.physmem_end, PFN2ADDR(start + count));
727
728 /*
729 * If confframe is supposed to be inside our zone, then make sure
730 * it does not span kernel & init
731 */
732 size_t confcount = SIZE2FRAMES(zone_conf_size(count));
733
734 if ((confframe >= start) && (confframe < start + count)) {
735 for (; confframe < start + count; confframe++) {
736 uintptr_t addr = PFN2ADDR(confframe);
737 if (overlaps(addr, PFN2ADDR(confcount),
738 KA2PA(config.base), config.kernel_size))
739 continue;
740
741 if (overlaps(addr, PFN2ADDR(confcount),
742 KA2PA(config.stack_base), config.stack_size))
743 continue;
744
745 bool overlap = false;
746 for (size_t i = 0; i < init.cnt; i++) {
747 if (overlaps(addr, PFN2ADDR(confcount),
748 init.tasks[i].paddr,
749 init.tasks[i].size)) {
750 overlap = true;
751 break;
752 }
753 }
754
755 if (overlap)
756 continue;
757
758 break;
759 }
760
761 if (confframe >= start + count)
762 panic("Cannot find configuration data for zone.");
763 }
764
765 size_t znum = zones_insert_zone(start, count, flags);
766 if (znum == (size_t) -1) {
767 irq_spinlock_unlock(&zones.lock, true);
768 return (size_t) -1;
769 }
770
771 void *confdata = (void *) PA2KA(PFN2ADDR(confframe));
772 zone_construct(&zones.info[znum], start, count, flags, confdata);
773
774 /* If confdata in zone, mark as unavailable */
775 if ((confframe >= start) && (confframe < start + count)) {
776 for (size_t i = confframe; i < confframe + confcount; i++)
777 zone_mark_unavailable(&zones.info[znum],
778 i - zones.info[znum].base);
779 }
780
781 irq_spinlock_unlock(&zones.lock, true);
782
783 return znum;
784 }
785
786 /* Non-available zone */
787 size_t znum = zones_insert_zone(start, count, flags);
788 if (znum == (size_t) -1) {
789 irq_spinlock_unlock(&zones.lock, true);
790 return (size_t) -1;
791 }
792
793 zone_construct(&zones.info[znum], start, count, flags, NULL);
794
795 irq_spinlock_unlock(&zones.lock, true);
796
797 return znum;
798}
799
800/*******************/
801/* Frame functions */
802/*******************/
803
804/** Set parent of frame. */
805void frame_set_parent(pfn_t pfn, void *data, size_t hint)
806{
807 irq_spinlock_lock(&zones.lock, true);
808
809 size_t znum = find_zone(pfn, 1, hint);
810
811 ASSERT(znum != (size_t) -1);
812
813 zone_get_frame(&zones.info[znum],
814 pfn - zones.info[znum].base)->parent = data;
815
816 irq_spinlock_unlock(&zones.lock, true);
817}
818
819void *frame_get_parent(pfn_t pfn, size_t hint)
820{
821 irq_spinlock_lock(&zones.lock, true);
822
823 size_t znum = find_zone(pfn, 1, hint);
824
825 ASSERT(znum != (size_t) -1);
826
827 void *res = zone_get_frame(&zones.info[znum],
828 pfn - zones.info[znum].base)->parent;
829
830 irq_spinlock_unlock(&zones.lock, true);
831
832 return res;
833}
834
835/** Allocate frames of physical memory.
836 *
837 * @param count Number of continuous frames to allocate.
838 * @param flags Flags for host zone selection and address processing.
839 * @param constraint Indication of physical address bits that cannot be
840 * set in the address of the first allocated frame.
841 * @param pzone Preferred zone.
842 *
843 * @return Physical address of the allocated frame.
844 *
845 */
846uintptr_t frame_alloc_generic(size_t count, frame_flags_t flags,
847 uintptr_t constraint, size_t *pzone)
848{
849 ASSERT(count > 0);
850
851 size_t hint = pzone ? (*pzone) : 0;
852 pfn_t frame_constraint = ADDR2PFN(constraint);
853
854 /*
855 * If not told otherwise, we must first reserve the memory.
856 */
857 if (!(flags & FRAME_NO_RESERVE))
858 reserve_force_alloc(count);
859
860loop:
861 irq_spinlock_lock(&zones.lock, true);
862
863 /*
864 * First, find suitable frame zone.
865 */
866 size_t znum = find_free_zone(count, FRAME_TO_ZONE_FLAGS(flags),
867 frame_constraint, hint);
868
869 /*
870 * If no memory, reclaim some slab memory,
871 * if it does not help, reclaim all.
872 */
873 if ((znum == (size_t) -1) && (!(flags & FRAME_NO_RECLAIM))) {
874 irq_spinlock_unlock(&zones.lock, true);
875 size_t freed = slab_reclaim(0);
876 irq_spinlock_lock(&zones.lock, true);
877
878 if (freed > 0)
879 znum = find_free_zone(count, FRAME_TO_ZONE_FLAGS(flags),
880 frame_constraint, hint);
881
882 if (znum == (size_t) -1) {
883 irq_spinlock_unlock(&zones.lock, true);
884 freed = slab_reclaim(SLAB_RECLAIM_ALL);
885 irq_spinlock_lock(&zones.lock, true);
886
887 if (freed > 0)
888 znum = find_free_zone(count, FRAME_TO_ZONE_FLAGS(flags),
889 frame_constraint, hint);
890 }
891 }
892
893 if (znum == (size_t) -1) {
894 if (flags & FRAME_ATOMIC) {
895 irq_spinlock_unlock(&zones.lock, true);
896
897 if (!(flags & FRAME_NO_RESERVE))
898 reserve_free(count);
899
900 return 0;
901 }
902
903 size_t avail = frame_total_free_get_internal();
904
905 irq_spinlock_unlock(&zones.lock, true);
906
907 if (!THREAD)
908 panic("Cannot wait for %zu frames to become available "
909 "(%zu available).", count, avail);
910
911 /*
912 * Sleep until some frames are available again.
913 */
914
915#ifdef CONFIG_DEBUG
916 log(LF_OTHER, LVL_DEBUG,
917 "Thread %" PRIu64 " waiting for %zu frames "
918 "%zu available.", THREAD->tid, count, avail);
919#endif
920
921 /*
922 * Since the mem_avail_mtx is an active mutex, we need to
923 * disable interrupts to prevent deadlock with TLB shootdown.
924 */
925 ipl_t ipl = interrupts_disable();
926 mutex_lock(&mem_avail_mtx);
927
928 if (mem_avail_req > 0)
929 mem_avail_req = min(mem_avail_req, count);
930 else
931 mem_avail_req = count;
932
933 size_t gen = mem_avail_gen;
934
935 while (gen == mem_avail_gen)
936 condvar_wait(&mem_avail_cv, &mem_avail_mtx);
937
938 mutex_unlock(&mem_avail_mtx);
939 interrupts_restore(ipl);
940
941#ifdef CONFIG_DEBUG
942 log(LF_OTHER, LVL_DEBUG, "Thread %" PRIu64 " woken up.",
943 THREAD->tid);
944#endif
945
946 goto loop;
947 }
948
949 pfn_t pfn = zone_frame_alloc(&zones.info[znum], count,
950 frame_constraint) + zones.info[znum].base;
951
952 irq_spinlock_unlock(&zones.lock, true);
953
954 if (pzone)
955 *pzone = znum;
956
957 return PFN2ADDR(pfn);
958}
959
960uintptr_t frame_alloc(size_t count, frame_flags_t flags, uintptr_t constraint)
961{
962 return frame_alloc_generic(count, flags, constraint, NULL);
963}
964
965/** Free frames of physical memory.
966 *
967 * Find respective frame structures for supplied physical frames.
968 * Decrement each frame reference count. If it drops to zero, mark
969 * the frames as available.
970 *
971 * @param start Physical Address of the first frame to be freed.
972 * @param count Number of frames to free.
973 * @param flags Flags to control memory reservation.
974 *
975 */
976void frame_free_generic(uintptr_t start, size_t count, frame_flags_t flags)
977{
978 size_t freed = 0;
979
980 irq_spinlock_lock(&zones.lock, true);
981
982 for (size_t i = 0; i < count; i++) {
983 /*
984 * First, find host frame zone for addr.
985 */
986 pfn_t pfn = ADDR2PFN(start) + i;
987 size_t znum = find_zone(pfn, 1, 0);
988
989 ASSERT(znum != (size_t) -1);
990
991 freed += zone_frame_free(&zones.info[znum],
992 pfn - zones.info[znum].base);
993 }
994
995 irq_spinlock_unlock(&zones.lock, true);
996
997 /*
998 * Signal that some memory has been freed.
999 * Since the mem_avail_mtx is an active mutex,
1000 * we need to disable interruptsto prevent deadlock
1001 * with TLB shootdown.
1002 */
1003
1004 ipl_t ipl = interrupts_disable();
1005 mutex_lock(&mem_avail_mtx);
1006
1007 if (mem_avail_req > 0)
1008 mem_avail_req -= min(mem_avail_req, freed);
1009
1010 if (mem_avail_req == 0) {
1011 mem_avail_gen++;
1012 condvar_broadcast(&mem_avail_cv);
1013 }
1014
1015 mutex_unlock(&mem_avail_mtx);
1016 interrupts_restore(ipl);
1017
1018 if (!(flags & FRAME_NO_RESERVE))
1019 reserve_free(freed);
1020}
1021
1022void frame_free(uintptr_t frame, size_t count)
1023{
1024 frame_free_generic(frame, count, 0);
1025}
1026
1027void frame_free_noreserve(uintptr_t frame, size_t count)
1028{
1029 frame_free_generic(frame, count, FRAME_NO_RESERVE);
1030}
1031
1032/** Add reference to frame.
1033 *
1034 * Find respective frame structure for supplied PFN and
1035 * increment frame reference count.
1036 *
1037 * @param pfn Frame number of the frame to be freed.
1038 *
1039 */
1040NO_TRACE void frame_reference_add(pfn_t pfn)
1041{
1042 irq_spinlock_lock(&zones.lock, true);
1043
1044 /*
1045 * First, find host frame zone for addr.
1046 */
1047 size_t znum = find_zone(pfn, 1, 0);
1048
1049 ASSERT(znum != (size_t) -1);
1050
1051 zones.info[znum].frames[pfn - zones.info[znum].base].refcount++;
1052
1053 irq_spinlock_unlock(&zones.lock, true);
1054}
1055
1056/** Mark given range unavailable in frame zones.
1057 *
1058 */
1059NO_TRACE void frame_mark_unavailable(pfn_t start, size_t count)
1060{
1061 irq_spinlock_lock(&zones.lock, true);
1062
1063 for (size_t i = 0; i < count; i++) {
1064 size_t znum = find_zone(start + i, 1, 0);
1065
1066 if (znum == (size_t) -1) /* PFN not found */
1067 continue;
1068
1069 zone_mark_unavailable(&zones.info[znum],
1070 start + i - zones.info[znum].base);
1071 }
1072
1073 irq_spinlock_unlock(&zones.lock, true);
1074}
1075
1076/** Initialize physical memory management.
1077 *
1078 */
1079void frame_init(void)
1080{
1081 if (config.cpu_active == 1) {
1082 zones.count = 0;
1083 irq_spinlock_initialize(&zones.lock, "frame.zones.lock");
1084 mutex_initialize(&mem_avail_mtx, MUTEX_ACTIVE);
1085 condvar_initialize(&mem_avail_cv);
1086 }
1087
1088 /* Tell the architecture to create some memory */
1089 frame_low_arch_init();
1090
1091 if (config.cpu_active == 1) {
1092 frame_mark_unavailable(ADDR2PFN(KA2PA(config.base)),
1093 SIZE2FRAMES(config.kernel_size));
1094 frame_mark_unavailable(ADDR2PFN(KA2PA(config.stack_base)),
1095 SIZE2FRAMES(config.stack_size));
1096
1097 for (size_t i = 0; i < init.cnt; i++)
1098 frame_mark_unavailable(ADDR2PFN(init.tasks[i].paddr),
1099 SIZE2FRAMES(init.tasks[i].size));
1100
1101 if (ballocs.size)
1102 frame_mark_unavailable(ADDR2PFN(KA2PA(ballocs.base)),
1103 SIZE2FRAMES(ballocs.size));
1104
1105 /*
1106 * Blacklist first frame, as allocating NULL would
1107 * fail in some places
1108 */
1109 frame_mark_unavailable(0, 1);
1110 }
1111
1112 frame_high_arch_init();
1113}
1114
1115/** Adjust bounds of physical memory region according to low/high memory split.
1116 *
1117 * @param low[in] If true, the adjustment is performed to make the region
1118 * fit in the low memory. Otherwise the adjustment is
1119 * performed to make the region fit in the high memory.
1120 * @param basep[inout] Pointer to a variable which contains the region's base
1121 * address and which may receive the adjusted base address.
1122 * @param sizep[inout] Pointer to a variable which contains the region's size
1123 * and which may receive the adjusted size.
1124 *
1125 * @return True if the region still exists even after the adjustment.
1126 * @return False otherwise.
1127 *
1128 */
1129bool frame_adjust_zone_bounds(bool low, uintptr_t *basep, size_t *sizep)
1130{
1131 uintptr_t limit = KA2PA(config.identity_base) + config.identity_size;
1132
1133 if (low) {
1134 if (*basep > limit)
1135 return false;
1136
1137 if (*basep + *sizep > limit)
1138 *sizep = limit - *basep;
1139 } else {
1140 if (*basep + *sizep <= limit)
1141 return false;
1142
1143 if (*basep <= limit) {
1144 *sizep -= limit - *basep;
1145 *basep = limit;
1146 }
1147 }
1148
1149 return true;
1150}
1151
1152/** Return total size of all zones.
1153 *
1154 */
1155uint64_t zones_total_size(void)
1156{
1157 irq_spinlock_lock(&zones.lock, true);
1158
1159 uint64_t total = 0;
1160
1161 for (size_t i = 0; i < zones.count; i++)
1162 total += (uint64_t) FRAMES2SIZE(zones.info[i].count);
1163
1164 irq_spinlock_unlock(&zones.lock, true);
1165
1166 return total;
1167}
1168
1169void zones_stats(uint64_t *total, uint64_t *unavail, uint64_t *busy,
1170 uint64_t *free)
1171{
1172 ASSERT(total != NULL);
1173 ASSERT(unavail != NULL);
1174 ASSERT(busy != NULL);
1175 ASSERT(free != NULL);
1176
1177 irq_spinlock_lock(&zones.lock, true);
1178
1179 *total = 0;
1180 *unavail = 0;
1181 *busy = 0;
1182 *free = 0;
1183
1184 for (size_t i = 0; i < zones.count; i++) {
1185 *total += (uint64_t) FRAMES2SIZE(zones.info[i].count);
1186
1187 if (zones.info[i].flags & ZONE_AVAILABLE) {
1188 *busy += (uint64_t) FRAMES2SIZE(zones.info[i].busy_count);
1189 *free += (uint64_t) FRAMES2SIZE(zones.info[i].free_count);
1190 } else
1191 *unavail += (uint64_t) FRAMES2SIZE(zones.info[i].count);
1192 }
1193
1194 irq_spinlock_unlock(&zones.lock, true);
1195}
1196
1197/** Prints list of zones.
1198 *
1199 */
1200void zones_print_list(void)
1201{
1202#ifdef __32_BITS__
1203 printf("[nr] [base addr] [frames ] [flags ] [free frames ] [busy frames ]\n");
1204#endif
1205
1206#ifdef __64_BITS__
1207 printf("[nr] [base address ] [frames ] [flags ] [free frames ] [busy frames ]\n");
1208#endif
1209
1210 /*
1211 * Because printing may require allocation of memory, we may not hold
1212 * the frame allocator locks when printing zone statistics. Therefore,
1213 * we simply gather the statistics under the protection of the locks and
1214 * print the statistics when the locks have been released.
1215 *
1216 * When someone adds/removes zones while we are printing the statistics,
1217 * we may end up with inaccurate output (e.g. a zone being skipped from
1218 * the listing).
1219 */
1220
1221 size_t free_lowmem = 0;
1222 size_t free_highmem = 0;
1223 size_t free_highprio = 0;
1224
1225 for (size_t i = 0;; i++) {
1226 irq_spinlock_lock(&zones.lock, true);
1227
1228 if (i >= zones.count) {
1229 irq_spinlock_unlock(&zones.lock, true);
1230 break;
1231 }
1232
1233 pfn_t fbase = zones.info[i].base;
1234 uintptr_t base = PFN2ADDR(fbase);
1235 size_t count = zones.info[i].count;
1236 zone_flags_t flags = zones.info[i].flags;
1237 size_t free_count = zones.info[i].free_count;
1238 size_t busy_count = zones.info[i].busy_count;
1239
1240 bool available = ((flags & ZONE_AVAILABLE) != 0);
1241 bool lowmem = ((flags & ZONE_LOWMEM) != 0);
1242 bool highmem = ((flags & ZONE_HIGHMEM) != 0);
1243 bool highprio = is_high_priority(fbase, count);
1244
1245 if (available) {
1246 if (lowmem)
1247 free_lowmem += free_count;
1248
1249 if (highmem)
1250 free_highmem += free_count;
1251
1252 if (highprio) {
1253 free_highprio += free_count;
1254 } else {
1255 /*
1256 * Walk all frames of the zone and examine
1257 * all high priority memory to get accurate
1258 * statistics.
1259 */
1260
1261 for (size_t index = 0; index < count; index++) {
1262 if (is_high_priority(fbase + index, 0)) {
1263 if (!bitmap_get(&zones.info[i].bitmap, index))
1264 free_highprio++;
1265 } else
1266 break;
1267 }
1268 }
1269 }
1270
1271 irq_spinlock_unlock(&zones.lock, true);
1272
1273 printf("%-4zu", i);
1274
1275#ifdef __32_BITS__
1276 printf(" %p", (void *) base);
1277#endif
1278
1279#ifdef __64_BITS__
1280 printf(" %p", (void *) base);
1281#endif
1282
1283 printf(" %12zu %c%c%c%c%c ", count,
1284 available ? 'A' : '-',
1285 (flags & ZONE_RESERVED) ? 'R' : '-',
1286 (flags & ZONE_FIRMWARE) ? 'F' : '-',
1287 (flags & ZONE_LOWMEM) ? 'L' : '-',
1288 (flags & ZONE_HIGHMEM) ? 'H' : '-');
1289
1290 if (available)
1291 printf("%14zu %14zu",
1292 free_count, busy_count);
1293
1294 printf("\n");
1295 }
1296
1297 printf("\n");
1298
1299 uint64_t size;
1300 const char *size_suffix;
1301
1302 bin_order_suffix(FRAMES2SIZE(free_lowmem), &size, &size_suffix,
1303 false);
1304 printf("Available low memory: %zu frames (%" PRIu64 " %s)\n",
1305 free_lowmem, size, size_suffix);
1306
1307 bin_order_suffix(FRAMES2SIZE(free_highmem), &size, &size_suffix,
1308 false);
1309 printf("Available high memory: %zu frames (%" PRIu64 " %s)\n",
1310 free_highmem, size, size_suffix);
1311
1312 bin_order_suffix(FRAMES2SIZE(free_highprio), &size, &size_suffix,
1313 false);
1314 printf("Available high priority: %zu frames (%" PRIu64 " %s)\n",
1315 free_highprio, size, size_suffix);
1316}
1317
1318/** Prints zone details.
1319 *
1320 * @param num Zone base address or zone number.
1321 *
1322 */
1323void zone_print_one(size_t num)
1324{
1325 irq_spinlock_lock(&zones.lock, true);
1326 size_t znum = (size_t) -1;
1327
1328 for (size_t i = 0; i < zones.count; i++) {
1329 if ((i == num) || (PFN2ADDR(zones.info[i].base) == num)) {
1330 znum = i;
1331 break;
1332 }
1333 }
1334
1335 if (znum == (size_t) -1) {
1336 irq_spinlock_unlock(&zones.lock, true);
1337 printf("Zone not found.\n");
1338 return;
1339 }
1340
1341 size_t free_lowmem = 0;
1342 size_t free_highmem = 0;
1343 size_t free_highprio = 0;
1344
1345 pfn_t fbase = zones.info[znum].base;
1346 uintptr_t base = PFN2ADDR(fbase);
1347 zone_flags_t flags = zones.info[znum].flags;
1348 size_t count = zones.info[znum].count;
1349 size_t free_count = zones.info[znum].free_count;
1350 size_t busy_count = zones.info[znum].busy_count;
1351
1352 bool available = ((flags & ZONE_AVAILABLE) != 0);
1353 bool lowmem = ((flags & ZONE_LOWMEM) != 0);
1354 bool highmem = ((flags & ZONE_HIGHMEM) != 0);
1355 bool highprio = is_high_priority(fbase, count);
1356
1357 if (available) {
1358 if (lowmem)
1359 free_lowmem = free_count;
1360
1361 if (highmem)
1362 free_highmem = free_count;
1363
1364 if (highprio) {
1365 free_highprio = free_count;
1366 } else {
1367 /*
1368 * Walk all frames of the zone and examine
1369 * all high priority memory to get accurate
1370 * statistics.
1371 */
1372
1373 for (size_t index = 0; index < count; index++) {
1374 if (is_high_priority(fbase + index, 0)) {
1375 if (!bitmap_get(&zones.info[znum].bitmap, index))
1376 free_highprio++;
1377 } else
1378 break;
1379 }
1380 }
1381 }
1382
1383 irq_spinlock_unlock(&zones.lock, true);
1384
1385 uint64_t size;
1386 const char *size_suffix;
1387
1388 bin_order_suffix(FRAMES2SIZE(count), &size, &size_suffix, false);
1389
1390 printf("Zone number: %zu\n", znum);
1391 printf("Zone base address: %p\n", (void *) base);
1392 printf("Zone size: %zu frames (%" PRIu64 " %s)\n", count,
1393 size, size_suffix);
1394 printf("Zone flags: %c%c%c%c%c\n",
1395 available ? 'A' : '-',
1396 (flags & ZONE_RESERVED) ? 'R' : '-',
1397 (flags & ZONE_FIRMWARE) ? 'F' : '-',
1398 (flags & ZONE_LOWMEM) ? 'L' : '-',
1399 (flags & ZONE_HIGHMEM) ? 'H' : '-');
1400
1401 if (available) {
1402 bin_order_suffix(FRAMES2SIZE(busy_count), &size, &size_suffix,
1403 false);
1404 printf("Allocated space: %zu frames (%" PRIu64 " %s)\n",
1405 busy_count, size, size_suffix);
1406
1407 bin_order_suffix(FRAMES2SIZE(free_count), &size, &size_suffix,
1408 false);
1409 printf("Available space: %zu frames (%" PRIu64 " %s)\n",
1410 free_count, size, size_suffix);
1411
1412 bin_order_suffix(FRAMES2SIZE(free_lowmem), &size, &size_suffix,
1413 false);
1414 printf("Available low memory: %zu frames (%" PRIu64 " %s)\n",
1415 free_lowmem, size, size_suffix);
1416
1417 bin_order_suffix(FRAMES2SIZE(free_highmem), &size, &size_suffix,
1418 false);
1419 printf("Available high memory: %zu frames (%" PRIu64 " %s)\n",
1420 free_highmem, size, size_suffix);
1421
1422 bin_order_suffix(FRAMES2SIZE(free_highprio), &size, &size_suffix,
1423 false);
1424 printf("Available high priority: %zu frames (%" PRIu64 " %s)\n",
1425 free_highprio, size, size_suffix);
1426 }
1427}
1428
1429/** @}
1430 */
Note: See TracBrowser for help on using the repository browser.