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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 478e243 was b2fa1204, checked in by Martin Sucha <sucha14@…>, 12 years ago

Cherrypick usage of kernel logger

  • 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#ifdef CONFIG_DEBUG
904 size_t avail = frame_total_free_get_internal();
905#endif
906
907 irq_spinlock_unlock(&zones.lock, true);
908
909 if (!THREAD)
910 panic("Cannot wait for %zu frames to become available "
911 "(%zu available).", count, avail);
912
913 /*
914 * Sleep until some frames are available again.
915 */
916
917#ifdef CONFIG_DEBUG
918 log(LF_OTHER, LVL_DEBUG,
919 "Thread %" PRIu64 " waiting for %zu frames "
920 "%zu available.", THREAD->tid, count, avail);
921#endif
922
923 /*
924 * Since the mem_avail_mtx is an active mutex, we need to
925 * disable interrupts to prevent deadlock with TLB shootdown.
926 */
927 ipl_t ipl = interrupts_disable();
928 mutex_lock(&mem_avail_mtx);
929
930 if (mem_avail_req > 0)
931 mem_avail_req = min(mem_avail_req, count);
932 else
933 mem_avail_req = count;
934
935 size_t gen = mem_avail_gen;
936
937 while (gen == mem_avail_gen)
938 condvar_wait(&mem_avail_cv, &mem_avail_mtx);
939
940 mutex_unlock(&mem_avail_mtx);
941 interrupts_restore(ipl);
942
943#ifdef CONFIG_DEBUG
944 log(LF_OTHER, LVL_DEBUG, "Thread %" PRIu64 " woken up.",
945 THREAD->tid);
946#endif
947
948 goto loop;
949 }
950
951 pfn_t pfn = zone_frame_alloc(&zones.info[znum], count,
952 frame_constraint) + zones.info[znum].base;
953
954 irq_spinlock_unlock(&zones.lock, true);
955
956 if (pzone)
957 *pzone = znum;
958
959 return PFN2ADDR(pfn);
960}
961
962uintptr_t frame_alloc(size_t count, frame_flags_t flags, uintptr_t constraint)
963{
964 return frame_alloc_generic(count, flags, constraint, NULL);
965}
966
967/** Free frames of physical memory.
968 *
969 * Find respective frame structures for supplied physical frames.
970 * Decrement each frame reference count. If it drops to zero, mark
971 * the frames as available.
972 *
973 * @param start Physical Address of the first frame to be freed.
974 * @param count Number of frames to free.
975 * @param flags Flags to control memory reservation.
976 *
977 */
978void frame_free_generic(uintptr_t start, size_t count, frame_flags_t flags)
979{
980 size_t freed = 0;
981
982 irq_spinlock_lock(&zones.lock, true);
983
984 for (size_t i = 0; i < count; i++) {
985 /*
986 * First, find host frame zone for addr.
987 */
988 pfn_t pfn = ADDR2PFN(start) + i;
989 size_t znum = find_zone(pfn, 1, 0);
990
991 ASSERT(znum != (size_t) -1);
992
993 freed += zone_frame_free(&zones.info[znum],
994 pfn - zones.info[znum].base);
995 }
996
997 irq_spinlock_unlock(&zones.lock, true);
998
999 /*
1000 * Signal that some memory has been freed.
1001 * Since the mem_avail_mtx is an active mutex,
1002 * we need to disable interruptsto prevent deadlock
1003 * with TLB shootdown.
1004 */
1005
1006 ipl_t ipl = interrupts_disable();
1007 mutex_lock(&mem_avail_mtx);
1008
1009 if (mem_avail_req > 0)
1010 mem_avail_req -= min(mem_avail_req, freed);
1011
1012 if (mem_avail_req == 0) {
1013 mem_avail_gen++;
1014 condvar_broadcast(&mem_avail_cv);
1015 }
1016
1017 mutex_unlock(&mem_avail_mtx);
1018 interrupts_restore(ipl);
1019
1020 if (!(flags & FRAME_NO_RESERVE))
1021 reserve_free(freed);
1022}
1023
1024void frame_free(uintptr_t frame, size_t count)
1025{
1026 frame_free_generic(frame, count, 0);
1027}
1028
1029void frame_free_noreserve(uintptr_t frame, size_t count)
1030{
1031 frame_free_generic(frame, count, FRAME_NO_RESERVE);
1032}
1033
1034/** Add reference to frame.
1035 *
1036 * Find respective frame structure for supplied PFN and
1037 * increment frame reference count.
1038 *
1039 * @param pfn Frame number of the frame to be freed.
1040 *
1041 */
1042NO_TRACE void frame_reference_add(pfn_t pfn)
1043{
1044 irq_spinlock_lock(&zones.lock, true);
1045
1046 /*
1047 * First, find host frame zone for addr.
1048 */
1049 size_t znum = find_zone(pfn, 1, 0);
1050
1051 ASSERT(znum != (size_t) -1);
1052
1053 zones.info[znum].frames[pfn - zones.info[znum].base].refcount++;
1054
1055 irq_spinlock_unlock(&zones.lock, true);
1056}
1057
1058/** Mark given range unavailable in frame zones.
1059 *
1060 */
1061NO_TRACE void frame_mark_unavailable(pfn_t start, size_t count)
1062{
1063 irq_spinlock_lock(&zones.lock, true);
1064
1065 for (size_t i = 0; i < count; i++) {
1066 size_t znum = find_zone(start + i, 1, 0);
1067
1068 if (znum == (size_t) -1) /* PFN not found */
1069 continue;
1070
1071 zone_mark_unavailable(&zones.info[znum],
1072 start + i - zones.info[znum].base);
1073 }
1074
1075 irq_spinlock_unlock(&zones.lock, true);
1076}
1077
1078/** Initialize physical memory management.
1079 *
1080 */
1081void frame_init(void)
1082{
1083 if (config.cpu_active == 1) {
1084 zones.count = 0;
1085 irq_spinlock_initialize(&zones.lock, "frame.zones.lock");
1086 mutex_initialize(&mem_avail_mtx, MUTEX_ACTIVE);
1087 condvar_initialize(&mem_avail_cv);
1088 }
1089
1090 /* Tell the architecture to create some memory */
1091 frame_low_arch_init();
1092
1093 if (config.cpu_active == 1) {
1094 frame_mark_unavailable(ADDR2PFN(KA2PA(config.base)),
1095 SIZE2FRAMES(config.kernel_size));
1096 frame_mark_unavailable(ADDR2PFN(KA2PA(config.stack_base)),
1097 SIZE2FRAMES(config.stack_size));
1098
1099 for (size_t i = 0; i < init.cnt; i++)
1100 frame_mark_unavailable(ADDR2PFN(init.tasks[i].paddr),
1101 SIZE2FRAMES(init.tasks[i].size));
1102
1103 if (ballocs.size)
1104 frame_mark_unavailable(ADDR2PFN(KA2PA(ballocs.base)),
1105 SIZE2FRAMES(ballocs.size));
1106
1107 /*
1108 * Blacklist first frame, as allocating NULL would
1109 * fail in some places
1110 */
1111 frame_mark_unavailable(0, 1);
1112 }
1113
1114 frame_high_arch_init();
1115}
1116
1117/** Adjust bounds of physical memory region according to low/high memory split.
1118 *
1119 * @param low[in] If true, the adjustment is performed to make the region
1120 * fit in the low memory. Otherwise the adjustment is
1121 * performed to make the region fit in the high memory.
1122 * @param basep[inout] Pointer to a variable which contains the region's base
1123 * address and which may receive the adjusted base address.
1124 * @param sizep[inout] Pointer to a variable which contains the region's size
1125 * and which may receive the adjusted size.
1126 *
1127 * @return True if the region still exists even after the adjustment.
1128 * @return False otherwise.
1129 *
1130 */
1131bool frame_adjust_zone_bounds(bool low, uintptr_t *basep, size_t *sizep)
1132{
1133 uintptr_t limit = KA2PA(config.identity_base) + config.identity_size;
1134
1135 if (low) {
1136 if (*basep > limit)
1137 return false;
1138
1139 if (*basep + *sizep > limit)
1140 *sizep = limit - *basep;
1141 } else {
1142 if (*basep + *sizep <= limit)
1143 return false;
1144
1145 if (*basep <= limit) {
1146 *sizep -= limit - *basep;
1147 *basep = limit;
1148 }
1149 }
1150
1151 return true;
1152}
1153
1154/** Return total size of all zones.
1155 *
1156 */
1157uint64_t zones_total_size(void)
1158{
1159 irq_spinlock_lock(&zones.lock, true);
1160
1161 uint64_t total = 0;
1162
1163 for (size_t i = 0; i < zones.count; i++)
1164 total += (uint64_t) FRAMES2SIZE(zones.info[i].count);
1165
1166 irq_spinlock_unlock(&zones.lock, true);
1167
1168 return total;
1169}
1170
1171void zones_stats(uint64_t *total, uint64_t *unavail, uint64_t *busy,
1172 uint64_t *free)
1173{
1174 ASSERT(total != NULL);
1175 ASSERT(unavail != NULL);
1176 ASSERT(busy != NULL);
1177 ASSERT(free != NULL);
1178
1179 irq_spinlock_lock(&zones.lock, true);
1180
1181 *total = 0;
1182 *unavail = 0;
1183 *busy = 0;
1184 *free = 0;
1185
1186 for (size_t i = 0; i < zones.count; i++) {
1187 *total += (uint64_t) FRAMES2SIZE(zones.info[i].count);
1188
1189 if (zones.info[i].flags & ZONE_AVAILABLE) {
1190 *busy += (uint64_t) FRAMES2SIZE(zones.info[i].busy_count);
1191 *free += (uint64_t) FRAMES2SIZE(zones.info[i].free_count);
1192 } else
1193 *unavail += (uint64_t) FRAMES2SIZE(zones.info[i].count);
1194 }
1195
1196 irq_spinlock_unlock(&zones.lock, true);
1197}
1198
1199/** Prints list of zones.
1200 *
1201 */
1202void zones_print_list(void)
1203{
1204#ifdef __32_BITS__
1205 printf("[nr] [base addr] [frames ] [flags ] [free frames ] [busy frames ]\n");
1206#endif
1207
1208#ifdef __64_BITS__
1209 printf("[nr] [base address ] [frames ] [flags ] [free frames ] [busy frames ]\n");
1210#endif
1211
1212 /*
1213 * Because printing may require allocation of memory, we may not hold
1214 * the frame allocator locks when printing zone statistics. Therefore,
1215 * we simply gather the statistics under the protection of the locks and
1216 * print the statistics when the locks have been released.
1217 *
1218 * When someone adds/removes zones while we are printing the statistics,
1219 * we may end up with inaccurate output (e.g. a zone being skipped from
1220 * the listing).
1221 */
1222
1223 size_t free_lowmem = 0;
1224 size_t free_highmem = 0;
1225 size_t free_highprio = 0;
1226
1227 for (size_t i = 0;; i++) {
1228 irq_spinlock_lock(&zones.lock, true);
1229
1230 if (i >= zones.count) {
1231 irq_spinlock_unlock(&zones.lock, true);
1232 break;
1233 }
1234
1235 pfn_t fbase = zones.info[i].base;
1236 uintptr_t base = PFN2ADDR(fbase);
1237 size_t count = zones.info[i].count;
1238 zone_flags_t flags = zones.info[i].flags;
1239 size_t free_count = zones.info[i].free_count;
1240 size_t busy_count = zones.info[i].busy_count;
1241
1242 bool available = ((flags & ZONE_AVAILABLE) != 0);
1243 bool lowmem = ((flags & ZONE_LOWMEM) != 0);
1244 bool highmem = ((flags & ZONE_HIGHMEM) != 0);
1245 bool highprio = is_high_priority(fbase, count);
1246
1247 if (available) {
1248 if (lowmem)
1249 free_lowmem += free_count;
1250
1251 if (highmem)
1252 free_highmem += free_count;
1253
1254 if (highprio) {
1255 free_highprio += free_count;
1256 } else {
1257 /*
1258 * Walk all frames of the zone and examine
1259 * all high priority memory to get accurate
1260 * statistics.
1261 */
1262
1263 for (size_t index = 0; index < count; index++) {
1264 if (is_high_priority(fbase + index, 0)) {
1265 if (!bitmap_get(&zones.info[i].bitmap, index))
1266 free_highprio++;
1267 } else
1268 break;
1269 }
1270 }
1271 }
1272
1273 irq_spinlock_unlock(&zones.lock, true);
1274
1275 printf("%-4zu", i);
1276
1277#ifdef __32_BITS__
1278 printf(" %p", (void *) base);
1279#endif
1280
1281#ifdef __64_BITS__
1282 printf(" %p", (void *) base);
1283#endif
1284
1285 printf(" %12zu %c%c%c%c%c ", count,
1286 available ? 'A' : '-',
1287 (flags & ZONE_RESERVED) ? 'R' : '-',
1288 (flags & ZONE_FIRMWARE) ? 'F' : '-',
1289 (flags & ZONE_LOWMEM) ? 'L' : '-',
1290 (flags & ZONE_HIGHMEM) ? 'H' : '-');
1291
1292 if (available)
1293 printf("%14zu %14zu",
1294 free_count, busy_count);
1295
1296 printf("\n");
1297 }
1298
1299 printf("\n");
1300
1301 uint64_t size;
1302 const char *size_suffix;
1303
1304 bin_order_suffix(FRAMES2SIZE(free_lowmem), &size, &size_suffix,
1305 false);
1306 printf("Available low memory: %zu frames (%" PRIu64 " %s)\n",
1307 free_lowmem, size, size_suffix);
1308
1309 bin_order_suffix(FRAMES2SIZE(free_highmem), &size, &size_suffix,
1310 false);
1311 printf("Available high memory: %zu frames (%" PRIu64 " %s)\n",
1312 free_highmem, size, size_suffix);
1313
1314 bin_order_suffix(FRAMES2SIZE(free_highprio), &size, &size_suffix,
1315 false);
1316 printf("Available high priority: %zu frames (%" PRIu64 " %s)\n",
1317 free_highprio, size, size_suffix);
1318}
1319
1320/** Prints zone details.
1321 *
1322 * @param num Zone base address or zone number.
1323 *
1324 */
1325void zone_print_one(size_t num)
1326{
1327 irq_spinlock_lock(&zones.lock, true);
1328 size_t znum = (size_t) -1;
1329
1330 for (size_t i = 0; i < zones.count; i++) {
1331 if ((i == num) || (PFN2ADDR(zones.info[i].base) == num)) {
1332 znum = i;
1333 break;
1334 }
1335 }
1336
1337 if (znum == (size_t) -1) {
1338 irq_spinlock_unlock(&zones.lock, true);
1339 printf("Zone not found.\n");
1340 return;
1341 }
1342
1343 size_t free_lowmem = 0;
1344 size_t free_highmem = 0;
1345 size_t free_highprio = 0;
1346
1347 pfn_t fbase = zones.info[znum].base;
1348 uintptr_t base = PFN2ADDR(fbase);
1349 zone_flags_t flags = zones.info[znum].flags;
1350 size_t count = zones.info[znum].count;
1351 size_t free_count = zones.info[znum].free_count;
1352 size_t busy_count = zones.info[znum].busy_count;
1353
1354 bool available = ((flags & ZONE_AVAILABLE) != 0);
1355 bool lowmem = ((flags & ZONE_LOWMEM) != 0);
1356 bool highmem = ((flags & ZONE_HIGHMEM) != 0);
1357 bool highprio = is_high_priority(fbase, count);
1358
1359 if (available) {
1360 if (lowmem)
1361 free_lowmem = free_count;
1362
1363 if (highmem)
1364 free_highmem = free_count;
1365
1366 if (highprio) {
1367 free_highprio = free_count;
1368 } else {
1369 /*
1370 * Walk all frames of the zone and examine
1371 * all high priority memory to get accurate
1372 * statistics.
1373 */
1374
1375 for (size_t index = 0; index < count; index++) {
1376 if (is_high_priority(fbase + index, 0)) {
1377 if (!bitmap_get(&zones.info[znum].bitmap, index))
1378 free_highprio++;
1379 } else
1380 break;
1381 }
1382 }
1383 }
1384
1385 irq_spinlock_unlock(&zones.lock, true);
1386
1387 uint64_t size;
1388 const char *size_suffix;
1389
1390 bin_order_suffix(FRAMES2SIZE(count), &size, &size_suffix, false);
1391
1392 printf("Zone number: %zu\n", znum);
1393 printf("Zone base address: %p\n", (void *) base);
1394 printf("Zone size: %zu frames (%" PRIu64 " %s)\n", count,
1395 size, size_suffix);
1396 printf("Zone flags: %c%c%c%c%c\n",
1397 available ? 'A' : '-',
1398 (flags & ZONE_RESERVED) ? 'R' : '-',
1399 (flags & ZONE_FIRMWARE) ? 'F' : '-',
1400 (flags & ZONE_LOWMEM) ? 'L' : '-',
1401 (flags & ZONE_HIGHMEM) ? 'H' : '-');
1402
1403 if (available) {
1404 bin_order_suffix(FRAMES2SIZE(busy_count), &size, &size_suffix,
1405 false);
1406 printf("Allocated space: %zu frames (%" PRIu64 " %s)\n",
1407 busy_count, size, size_suffix);
1408
1409 bin_order_suffix(FRAMES2SIZE(free_count), &size, &size_suffix,
1410 false);
1411 printf("Available space: %zu frames (%" PRIu64 " %s)\n",
1412 free_count, size, size_suffix);
1413
1414 bin_order_suffix(FRAMES2SIZE(free_lowmem), &size, &size_suffix,
1415 false);
1416 printf("Available low memory: %zu frames (%" PRIu64 " %s)\n",
1417 free_lowmem, size, size_suffix);
1418
1419 bin_order_suffix(FRAMES2SIZE(free_highmem), &size, &size_suffix,
1420 false);
1421 printf("Available high memory: %zu frames (%" PRIu64 " %s)\n",
1422 free_highmem, size, size_suffix);
1423
1424 bin_order_suffix(FRAMES2SIZE(free_highprio), &size, &size_suffix,
1425 false);
1426 printf("Available high priority: %zu frames (%" PRIu64 " %s)\n",
1427 free_highprio, size, size_suffix);
1428 }
1429}
1430
1431/** @}
1432 */
Note: See TracBrowser for help on using the repository browser.