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

Last change on this file since eec201d was 174156fd, checked in by Jakub Jermar <jakub@…>, 7 years ago

Disambiguate doxygroup generic*

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