:: limine / common / mm / pmm.s2.c 25.7 KB raw

1
#include <stddef.h>
2
#include <stdint.h>
3
#include <stdbool.h>
4
#include <mm/pmm.h>
5
#include <sys/e820.h>
6
#include <lib/acpi.h>
7
#include <lib/misc.h>
8
#include <lib/libc.h>
9
#include <lib/print.h>
10
#if defined (UEFI)
11
#  include <efi.h>
12
#endif
13
14
#define PAGE_SIZE   4096
15
16
#if defined (BIOS)
17
extern symbol bss_end;
18
#endif
19
20
bool allocations_disallowed = true;
21
22
void *conv_mem_alloc(uint64_t count) {
23
    static uint64_t base = 4096;
24
25
    if (allocations_disallowed)
26
        panic(false, "Memory allocations disallowed");
27
28
    count = ALIGN_UP(count, 4096, panic(false, "Alignment overflow"));
29
30
    for (;;) {
31
        if (base + count > 0x100000)
32
            panic(false, "Conventional memory allocation failed");
33
34
        if (memmap_alloc_range(base, count, MEMMAP_BOOTLOADER_RECLAIMABLE, MEMMAP_USABLE, false, false, false)) {
35
            void *ret = (void *)(uintptr_t)base;
36
            // Zero out allocated space
37
            memset(ret, 0, count);
38
            base += count;
39
40
            pmm_sanitise_entries(memmap, &memmap_entries, false);
41
42
            return ret;
43
        }
44
45
        base += 4096;
46
    }
47
}
48
49
#if defined (BIOS)
50
#define memmap_max_entries ((size_t)512)
51
52
struct memmap_entry memmap[memmap_max_entries];
53
size_t memmap_entries = 0;
54
#endif
55
56
#if defined (UEFI)
57
static size_t memmap_max_entries;
58
59
struct memmap_entry *memmap;
60
size_t memmap_entries = 0;
61
62
struct memmap_entry *untouched_memmap;
63
size_t untouched_memmap_entries = 0;
64
#endif
65
66
static const char *memmap_type(uint32_t type) {
67
    switch (type) {
68
        case MEMMAP_USABLE:
69
            return "Usable RAM";
70
        case MEMMAP_RESERVED:
71
            return "Reserved";
72
        case MEMMAP_RESERVED_MAPPED:
73
            return "Reserved (Mapped)";
74
        case MEMMAP_ACPI_RECLAIMABLE:
75
            return "ACPI reclaimable";
76
        case MEMMAP_ACPI_NVS:
77
            return "ACPI NVS";
78
        case MEMMAP_BAD_MEMORY:
79
            return "Bad memory";
80
        case MEMMAP_FRAMEBUFFER:
81
            return "Framebuffer";
82
        case MEMMAP_BOOTLOADER_RECLAIMABLE:
83
            return "Bootloader reclaimable";
84
        case MEMMAP_KERNEL_AND_MODULES:
85
            return "Kernel/Modules";
86
        case MEMMAP_EFI_RECLAIMABLE:
87
            return "EFI reclaimable";
88
        default:
89
            return "???";
90
    }
91
}
92
93
void print_memmap(struct memmap_entry *mm, size_t size) {
94
    for (size_t i = 0; i < size; i++) {
95
        print("[%X -> %X] : %X  <%s (%x)>\n",
96
              mm[i].base,
97
              mm[i].base + mm[i].length,
98
              mm[i].length,
99
              memmap_type(mm[i].type), mm[i].type);
100
    }
101
}
102
103
static bool align_entry(uint64_t *base, uint64_t *length) {
104
    if (*length < PAGE_SIZE)
105
        return false;
106
107
    uint64_t orig_base = *base;
108
109
    *base = ALIGN_UP(*base, PAGE_SIZE, return false);
110
111
    *length -= (*base - orig_base);
112
    *length =  ALIGN_DOWN(*length, PAGE_SIZE);
113
114
    if (*length == 0)
115
        return false;
116
117
    return true;
118
}
119
120
#if defined (BIOS)
121
bool pmm_sanitiser_keep_first_page = false;
122
#else
123
bool pmm_sanitiser_keep_first_page = true;
124
#endif
125
126
void pmm_sanitise_entries(struct memmap_entry *m, size_t *_count, bool align_entries) {
127
    size_t count = *_count;
128
129
    for (size_t i = 0; i < count; i++) {
130
        if (m[i].type != MEMMAP_USABLE)
131
            continue;
132
133
        // Check if the entry overlaps other entries
134
        for (size_t j = 0; j < count; j++) {
135
            if (j == i)
136
                continue;
137
138
            uint64_t base   = m[i].base;
139
            uint64_t length = m[i].length;
140
            uint64_t top    = CHECKED_ADD(base, length, goto del_mm0);
141
142
            uint64_t res_base   = m[j].base;
143
            uint64_t res_length = m[j].length;
144
            uint64_t res_top    = CHECKED_ADD(res_base, res_length, continue);
145
146
            // Non-usable entry fully contains usable entry
147
            if (res_base <= base && res_top >= top) {
148
                m[i].base   = top;
149
                m[i].length = 0;
150
                break;
151
            }
152
153
            if ( (res_base >= base && res_base < top)
154
              && (res_top  >= base && res_top  < top) ) {
155
                // TODO actually handle splitting off usable chunks
156
                panic(false, "A non-usable memory map entry is inside a usable section.");
157
            }
158
159
            if (res_base >= base && res_base < top) {
160
                top = res_base;
161
            }
162
163
            if (res_top  >= base && res_top  < top) {
164
                base = res_top;
165
            }
166
167
            m[i].base   = base;
168
            m[i].length = top - base;
169
        }
170
171
        if (!m[i].length
172
         || (align_entries && !align_entry(&m[i].base, &m[i].length))) {
173
del_mm0:
174
            // Remove i from memmap
175
            if (i < count - 1) {
176
                m[i] = m[count - 1];
177
            }
178
            count--; i = (size_t)-1; // restart outer loop
179
        }
180
    }
181
182
    // Remove 0 length entries (any type) and clip usable entries below 0x1000
183
    for (size_t i = 0; i < count; i++) {
184
        if (m[i].type == MEMMAP_USABLE
185
         && !pmm_sanitiser_keep_first_page && m[i].base < 0x1000) {
186
            uint64_t entry_top = CHECKED_ADD(m[i].base, m[i].length, goto del_mm1);
187
            if (entry_top <= 0x1000) {
188
                goto del_mm1;
189
            }
190
191
            m[i].length -= 0x1000 - m[i].base;
192
            m[i].base = 0x1000;
193
        }
194
195
        if (m[i].length == 0) {
196
del_mm1:
197
            // Remove i from memmap
198
            if (i < count - 1) {
199
                m[i] = m[count - 1];
200
            }
201
            count--; i--;
202
        }
203
    }
204
205
    // Sort the entries
206
    for (size_t p = 0; p + 1 < count; p++) {
207
        uint64_t min = m[p].base;
208
        size_t min_index = p;
209
        for (size_t i = p; i < count; i++) {
210
            if (m[i].base < min) {
211
                min = m[i].base;
212
                min_index = i;
213
            }
214
        }
215
        struct memmap_entry min_e = m[min_index];
216
        m[min_index] = m[p];
217
        m[p] = min_e;
218
    }
219
220
    // Merge contiguous bootloader-reclaimable, reserved (mapped), usable entries
221
    for (size_t i = 0; i + 1 < count; i++) {
222
        if (m[i].type != MEMMAP_BOOTLOADER_RECLAIMABLE
223
         && m[i].type != MEMMAP_RESERVED_MAPPED
224
         && m[i].type != MEMMAP_USABLE)
225
            continue;
226
227
        uint64_t merge_top = CHECKED_ADD(m[i].base, m[i].length, continue);
228
        if (m[i+1].type == m[i].type
229
         && m[i+1].base == merge_top) {
230
            m[i].length = CHECKED_ADD(m[i].length, m[i+1].length, continue);
231
232
            // Eradicate from memmap
233
            for (size_t j = i + 2; j < count; j++) {
234
                m[j - 1] = m[j];
235
            }
236
            count--;
237
            i--;
238
        }
239
    }
240
241
    *_count = count;
242
}
243
244
#if defined (UEFI)
245
static void pmm_reclaim_uefi_mem(struct memmap_entry *m, size_t *_count, bool raw);
246
#endif
247
248
struct memmap_entry *get_memmap(size_t *entries) {
249
#if defined (UEFI)
250
    if (efi_boot_services_exited == false) {
251
        panic(true, "get_memmap called whilst in boot services");
252
    }
253
254
    pmm_reclaim_uefi_mem(memmap, &memmap_entries, false);
255
#endif
256
257
    pmm_sanitise_entries(memmap, &memmap_entries, true);
258
259
    *entries = memmap_entries;
260
261
    allocations_disallowed = true;
262
263
    return memmap;
264
}
265
266
#if defined (BIOS)
267
void init_memmap(void) {
268
    for (size_t i = 0; i < e820_entries; i++) {
269
        if (memmap_entries == memmap_max_entries) {
270
            panic(false, "Memory map exhausted.");
271
        }
272
273
        memmap[memmap_entries] = e820_map[i];
274
275
        uint64_t top = CHECKED_ADD(memmap[memmap_entries].base, memmap[memmap_entries].length, continue);
276
277
        if (memmap[memmap_entries].type == MEMMAP_USABLE) {
278
            if (memmap[memmap_entries].base >= EBDA && memmap[memmap_entries].base < 0x100000) {
279
                if (top <= 0x100000)
280
                    continue;
281
282
                memmap[memmap_entries].length -= 0x100000 - memmap[memmap_entries].base;
283
                memmap[memmap_entries].base = 0x100000;
284
            }
285
286
            if (top > EBDA && top <= 0x100000) {
287
                memmap[memmap_entries].length -= top - EBDA;
288
            }
289
        }
290
291
        memmap_entries++;
292
    }
293
294
    pmm_sanitise_entries(memmap, &memmap_entries, false);
295
296
    // Allocate bootloader itself
297
    memmap_alloc_range(4096,
298
        ALIGN_UP((uintptr_t)bss_end, 4096, panic(false, "Alignment overflow")) - 4096, MEMMAP_BOOTLOADER_RECLAIMABLE, 0, true, false, false);
299
300
    pmm_sanitise_entries(memmap, &memmap_entries, false);
301
302
    allocations_disallowed = false;
303
}
304
#endif
305
306
#if defined (UEFI)
307
static struct memmap_entry *recl;
308
309
extern symbol __slide, __image_base, __image_end;
310
311
void init_memmap(void) {
312
    EFI_STATUS status;
313
314
    EFI_MEMORY_DESCRIPTOR tmp_mmap[1];
315
    efi_mmap_size = sizeof(tmp_mmap);
316
    UINTN mmap_key = 0;
317
318
    gBS->GetMemoryMap(&efi_mmap_size, tmp_mmap, &mmap_key, &efi_desc_size, &efi_desc_ver);
319
320
    memmap_max_entries = (efi_mmap_size / efi_desc_size) + 512;
321
322
    efi_mmap_size += 4096;
323
324
    status = gBS->AllocatePool(EfiLoaderData, efi_mmap_size, (void **)&efi_mmap);
325
    if (status) {
326
        goto fail;
327
    }
328
329
    size_t memmap_alloc_size = CHECKED_MUL(memmap_max_entries, sizeof(struct memmap_entry), goto fail);
330
331
    status = gBS->AllocatePool(EfiLoaderData, memmap_alloc_size, (void **)&memmap);
332
    if (status) {
333
        gBS->FreePool(efi_mmap);
334
        goto fail;
335
    }
336
337
    status = gBS->AllocatePool(EfiLoaderData, memmap_alloc_size, (void **)&untouched_memmap);
338
    if (status) {
339
        gBS->FreePool(efi_mmap);
340
        gBS->FreePool(memmap);
341
        goto fail;
342
    }
343
344
    status = gBS->GetMemoryMap(&efi_mmap_size, efi_mmap, &mmap_key, &efi_desc_size, &efi_desc_ver);
345
    if (status) {
346
        gBS->FreePool(efi_mmap);
347
        gBS->FreePool(memmap);
348
        gBS->FreePool(untouched_memmap);
349
        goto fail;
350
    }
351
352
    size_t entry_count = efi_mmap_size / efi_desc_size;
353
354
    for (size_t i = 0; i < entry_count; i++) {
355
        EFI_MEMORY_DESCRIPTOR *entry = (void *)efi_mmap + i * efi_desc_size;
356
357
        if (entry->NumberOfPages == 0) {
358
            continue;
359
        }
360
361
        uint32_t our_type;
362
        switch (entry->Type) {
363
            case EfiReservedMemoryType:
364
            case EfiRuntimeServicesCode:
365
            case EfiRuntimeServicesData:
366
            case EfiUnusableMemory:
367
            case EfiMemoryMappedIO:
368
            case EfiMemoryMappedIOPortSpace:
369
            case EfiPalCode:
370
            default:
371
                our_type = MEMMAP_RESERVED; break;
372
            case EfiLoaderCode:
373
            case EfiLoaderData:
374
            case EfiBootServicesCode:
375
            case EfiBootServicesData:
376
                our_type = MEMMAP_EFI_RECLAIMABLE; break;
377
            case EfiACPIReclaimMemory:
378
                our_type = MEMMAP_ACPI_RECLAIMABLE; break;
379
            case EfiACPIMemoryNVS:
380
                our_type = MEMMAP_ACPI_NVS; break;
381
            case EfiConventionalMemory:
382
                our_type = MEMMAP_USABLE; break;
383
        }
384
385
        uint64_t base = entry->PhysicalStart;
386
        uint64_t length = CHECKED_MUL(entry->NumberOfPages, 4096, continue);
387
388
        if (memmap_entries == memmap_max_entries) {
389
            panic(false, "Memory map exhausted.");
390
        }
391
392
        memmap[memmap_entries].base = base;
393
        memmap[memmap_entries].length = length;
394
        memmap[memmap_entries].type = our_type;
395
396
        memmap_entries++;
397
    }
398
399
    pmm_sanitise_entries(memmap, &memmap_entries, false);
400
401
    allocations_disallowed = false;
402
403
    // Let's leave 64MiB to the firmware below 4GiB
404
    for (size_t i = 0; i < 64; i++) {
405
        ext_mem_alloc_type(0x100000, MEMMAP_EFI_RECLAIMABLE);
406
    }
407
408
    memcpy(untouched_memmap, memmap, memmap_entries * sizeof(struct memmap_entry));
409
    untouched_memmap_entries = memmap_entries;
410
411
    // Now own all the usable entries
412
    for (size_t i = 0; i < untouched_memmap_entries; i++) {
413
        if (untouched_memmap[i].type != MEMMAP_USABLE)
414
            continue;
415
416
        EFI_PHYSICAL_ADDRESS base = untouched_memmap[i].base;
417
418
#if defined (__i386__)
419
        if (CHECKED_ADD(untouched_memmap[i].base, untouched_memmap[i].length, continue) > 0x100000000) {
420
            continue;
421
        }
422
#endif
423
424
        status = gBS->AllocatePages(AllocateAddress, EfiLoaderCode,
425
                                    untouched_memmap[i].length / 4096, &base);
426
427
        if (status) {
428
            for (size_t j = 0; j < untouched_memmap[i].length; j += 4096) {
429
                base = untouched_memmap[i].base + j;
430
                status = gBS->AllocatePages(AllocateAddress, EfiLoaderCode, 1, &base);
431
                if (status) {
432
                    memmap_alloc_range(base, 4096, MEMMAP_EFI_RECLAIMABLE, MEMMAP_USABLE, true, false, false);
433
                }
434
            }
435
        }
436
    }
437
438
    memcpy(untouched_memmap, memmap, memmap_entries * sizeof(struct memmap_entry));
439
    untouched_memmap_entries = memmap_entries;
440
441
    // Allocate bootloader itself
442
    size_t image_size = ALIGN_UP((uintptr_t)__image_end - (uintptr_t)__image_base, 4096, panic(false, "Alignment overflow"));
443
444
    memmap_alloc_range((uintptr_t)__slide, (uintptr_t)image_size,
445
                       MEMMAP_BOOTLOADER_RECLAIMABLE, 0, true, false, true);
446
447
    pmm_sanitise_entries(memmap, &memmap_entries, false);
448
449
    recl = ext_mem_alloc_counted(1024, sizeof(struct memmap_entry));
450
451
    return;
452
453
fail:
454
    panic(false, "pmm: Failure initialising memory map");
455
}
456
457
static void pmm_reclaim_uefi_mem(struct memmap_entry *m, size_t *_count, bool raw) {
458
    size_t count = *_count;
459
460
    size_t recl_i = 0;
461
462
    for (size_t i = 0; i < count; i++) {
463
        if (m[i].type == MEMMAP_EFI_RECLAIMABLE) {
464
            if (recl_i >= 1024) {
465
                panic(false, "pmm: Too many EFI reclaimable entries");
466
            }
467
            recl[recl_i++] = m[i];
468
        }
469
    }
470
471
    for (size_t ri = 0; ri < recl_i; ri++) {
472
        struct memmap_entry *r = &recl[ri];
473
474
        // Punch holes in our EFI reclaimable entry for every EFI area which is
475
        // boot services or conventional that fits within
476
        size_t efi_mmap_entry_count = efi_mmap_size / efi_desc_size;
477
        for (size_t i = 0; i < efi_mmap_entry_count; i++) {
478
            EFI_MEMORY_DESCRIPTOR *entry = (void *)efi_mmap + i * efi_desc_size;
479
480
            uint64_t base = r->base;
481
            uint64_t top = CHECKED_ADD(base, r->length, continue);
482
            uint64_t efi_base = entry->PhysicalStart;
483
            uint64_t efi_size = CHECKED_MUL(entry->NumberOfPages, 4096, continue);
484
485
            if (efi_base < base) {
486
                if (efi_size <= base - efi_base)
487
                    continue;
488
                efi_size -= base - efi_base;
489
                efi_base = base;
490
            }
491
492
            uint64_t efi_top = CHECKED_ADD(efi_base, efi_size, continue);
493
494
            if (efi_top > top) {
495
                if (efi_size <= efi_top - top)
496
                    continue;
497
                efi_size -= efi_top - top;
498
                efi_top = top;
499
            }
500
501
            // Sanity check
502
            if (!(efi_base >= base && efi_base <  top
503
               && efi_top  >  base && efi_top  <= top))
504
                continue;
505
506
            uint32_t our_type;
507
            switch (entry->Type) {
508
                case EfiLoaderCode:
509
                case EfiLoaderData:
510
                case EfiBootServicesCode:
511
                case EfiBootServicesData:
512
                    if (raw) {
513
                        our_type = MEMMAP_USABLE;
514
                    } else {
515
                        our_type = MEMMAP_BOOTLOADER_RECLAIMABLE;
516
                    }
517
                    break;
518
                case EfiConventionalMemory:
519
                    our_type = MEMMAP_USABLE; break;
520
                case EfiACPIReclaimMemory:
521
                    our_type = MEMMAP_ACPI_RECLAIMABLE; break;
522
                case EfiACPIMemoryNVS:
523
                    our_type = MEMMAP_ACPI_NVS; break;
524
                default:
525
                    our_type = MEMMAP_RESERVED; break;
526
            }
527
528
            memmap_alloc_range_in(m, &count, efi_base, efi_size, our_type, 0, true, false, false);
529
        }
530
    }
531
532
    allocations_disallowed = true;
533
534
    pmm_sanitise_entries(m, &count, false);
535
536
    *_count = count;
537
}
538
539
void pmm_release_uefi_mem(void) {
540
    EFI_STATUS status;
541
542
    for (size_t i = 0; i < untouched_memmap_entries; i++) {
543
        if (untouched_memmap[i].type != MEMMAP_USABLE
544
         && untouched_memmap[i].type != MEMMAP_BOOTLOADER_RECLAIMABLE) {
545
            continue;
546
        }
547
548
        status = gBS->FreePages(untouched_memmap[i].base, untouched_memmap[i].length / 4096);
549
550
        if (status) {
551
            panic(false, "pmm: FreePages failure (%X)", (uint64_t)status);
552
        }
553
    }
554
555
    allocations_disallowed = true;
556
}
557
#endif
558
559
#if defined (BIOS)
560
struct memmap_entry *get_raw_memmap(size_t *entry_count) {
561
    *entry_count = e820_entries;
562
    return e820_map;
563
}
564
#endif
565
566
#if defined (UEFI)
567
struct memmap_entry *get_raw_memmap(size_t *entry_count) {
568
    if (efi_boot_services_exited == false) {
569
        panic(true, "get_raw_memmap called whilst in boot services");
570
    }
571
572
    bool old_skfp = pmm_sanitiser_keep_first_page;
573
    pmm_sanitiser_keep_first_page = true;
574
    pmm_reclaim_uefi_mem(untouched_memmap, &untouched_memmap_entries, true);
575
    pmm_sanitiser_keep_first_page = old_skfp;
576
577
    *entry_count = untouched_memmap_entries;
578
    return untouched_memmap;
579
}
580
#endif
581
582
void pmm_free_size_t(void *ptr, size_t length) {
583
    pmm_free(ptr, length);
584
}
585
586
void pmm_free(void *ptr, uint64_t count) {
587
    if ((uintptr_t)ptr % 4096 != 0)
588
        panic(false, "pmm_free: Unaligned pointer %p", ptr);
589
    count = ALIGN_UP(count, 4096, panic(false, "Alignment overflow"));
590
    if (allocations_disallowed)
591
        panic(false, "Memory allocations disallowed");
592
    memmap_alloc_range((uintptr_t)ptr, count, MEMMAP_USABLE, 0, false, false, true);
593
}
594
595
void *pmm_realloc(void *old_ptr, uint64_t old_size, uint64_t new_size) {
596
    if (new_size == 0) {
597
        if (old_ptr != NULL) {
598
            pmm_free(old_ptr, old_size);
599
        }
600
        return NULL;
601
    }
602
    if (old_ptr == NULL) {
603
        return ext_mem_alloc(new_size);
604
    }
605
606
    void *new_ptr = ext_mem_alloc(new_size);
607
608
    memcpy(new_ptr, old_ptr, MIN(new_size, old_size));
609
610
    pmm_free(old_ptr, old_size);
611
612
    return new_ptr;
613
}
614
615
void *ext_mem_alloc_size_t(size_t count) {
616
    return ext_mem_alloc(count);
617
}
618
619
void *ext_mem_alloc(uint64_t count) {
620
    return ext_mem_alloc_type(count, MEMMAP_BOOTLOADER_RECLAIMABLE);
621
}
622
623
void *ext_mem_alloc_counted(uint64_t count, uint64_t elem_size) {
624
    return ext_mem_alloc(CHECKED_MUL(count, elem_size,
625
        panic(false, "ext_mem_alloc_counted: allocation size overflow")));
626
}
627
628
void *ext_mem_alloc_type(uint64_t count, uint32_t type) {
629
    return ext_mem_alloc_type_aligned(count, type, 4096);
630
}
631
632
void *ext_mem_alloc_type_aligned(uint64_t count, uint32_t type, size_t alignment) {
633
    return ext_mem_alloc_type_aligned_mode(count, type, alignment, false);
634
}
635
636
// Allocate memory top down.
637
void *ext_mem_alloc_type_aligned_mode(uint64_t count, uint32_t type, size_t alignment, bool allow_high_allocs) {
638
#if !defined (__x86_64__) && !defined (__i386__)
639
    (void)allow_high_allocs;
640
#endif
641
642
    count = CHECKED_ADD(count, alignment - 1,
643
        panic(false, "ext_mem_alloc: count overflows when aligning"));
644
    count = ALIGN_DOWN(count, alignment);
645
646
    if (allocations_disallowed)
647
        panic(false, "Memory allocations disallowed");
648
649
#if defined(__x86_64__) || defined(__i386__)
650
    // Try below 4GiB first to avoid relying on firmware identity-mapping
651
    // memory above 4GiB (some buggy UEFI implementations don't).
652
    uint64_t limit = 0x100000000;
653
654
again:
655
#else
656
    uint64_t limit = UINT64_MAX;
657
#endif
658
659
    for (int i = memmap_entries - 1; i >= 0; i--) {
660
        if (memmap[i].type != 1)
661
            continue;
662
663
        uint64_t entry_base = memmap[i].base;
664
        uint64_t entry_top  = CHECKED_ADD(memmap[i].base, memmap[i].length, continue);
665
666
        if (entry_top > limit) {
667
            entry_top = limit;
668
            if (entry_base >= entry_top)
669
                continue;
670
        }
671
672
        // Check if entry is too small before subtracting.
673
        if (entry_top - entry_base < count)
674
            continue;
675
676
        uint64_t alloc_base = ALIGN_DOWN(entry_top - count, alignment);
677
678
        if (alloc_base < entry_base)
679
            continue;
680
681
        // We now reserve the range we need.
682
        uint64_t aligned_length = entry_top - alloc_base;
683
        memmap_alloc_range(alloc_base, aligned_length, type, MEMMAP_USABLE, true, false, false);
684
685
        void *ret;
686
687
#if defined (__i386__)
688
        if (!allow_high_allocs) {
689
#endif
690
        ret = (void *)(size_t)alloc_base;
691
692
        // Zero out allocated space
693
        memset(ret, 0, count);
694
#if defined (__i386__)
695
        } else {
696
            static uint64_t above64_ret;
697
            above64_ret = alloc_base;
698
            ret = &above64_ret;
699
        }
700
#endif
701
702
        pmm_sanitise_entries(memmap, &memmap_entries, false);
703
704
        return ret;
705
    }
706
707
#if defined(__x86_64__) || defined(__i386__)
708
    if (allow_high_allocs && limit < UINT64_MAX) {
709
        limit = UINT64_MAX;
710
        goto again;
711
    }
712
#endif
713
714
    panic(false, "High memory allocator: Out of memory");
715
}
716
717
/// Compute and returns the amount of upper and lower memory till
718
/// the first hole.
719
struct meminfo mmap_get_info(size_t mmap_count, struct memmap_entry *mmap) {
720
    struct meminfo info = {0};
721
722
    // Find contiguous usable memory from address 0 (lower) and 1 MiB (upper)
723
    // by iteratively extending a frontier. Handles unsorted entries.
724
    uint64_t lower_end = 0;
725
    uint64_t upper_end = 0x100000;
726
    bool progress;
727
728
    do {
729
        progress = false;
730
        for (size_t i = 0; i < mmap_count; i++) {
731
            if (mmap[i].type != MEMMAP_USABLE)
732
                continue;
733
            uint64_t base = mmap[i].base;
734
            uint64_t top = CHECKED_ADD(base, mmap[i].length, continue);
735
            if (base <= lower_end && top > lower_end) {
736
                lower_end = top;
737
                progress = true;
738
            }
739
            if (base <= upper_end && top > upper_end) {
740
                upper_end = top;
741
                progress = true;
742
            }
743
        }
744
    } while (progress);
745
746
    if (lower_end > 0x100000)
747
        lower_end = 0x100000;
748
749
    info.lowermem = lower_end;
750
    info.uppermem = upper_end - 0x100000;
751
752
    return info;
753
}
754
755
static bool pmm_new_entry(struct memmap_entry *m, size_t *_count,
756
                          uint64_t base, uint64_t length, uint32_t type) {
757
    size_t count = *_count;
758
759
    uint64_t top = CHECKED_ADD(base, length, panic(false, "pmm: Integer overflow in memory range calculation"));
760
761
    // Handle overlapping new entries.
762
    for (size_t i = 0; i < count; i++) {
763
        uint64_t entry_base = m[i].base;
764
        uint64_t entry_top = CHECKED_ADD(m[i].base, m[i].length, continue);
765
766
        // Full overlap
767
        if (base <= entry_base && top >= entry_top) {
768
            // Remove overlapped entry
769
            if (i < count - 1) {
770
                m[i] = m[count - 1];
771
            }
772
            count--;
773
            i--;
774
            continue;
775
        }
776
777
        // Partial overlap (bottom)
778
        if (base <= entry_base && top < entry_top && top > entry_base) {
779
            // Entry gets bottom shaved off
780
            m[i].base += top - entry_base;
781
            m[i].length -= top - entry_base;
782
            continue;
783
        }
784
785
        // Partial overlap (top)
786
        if (base > entry_base && base < entry_top && top >= entry_top) {
787
            // Entry gets top shaved off
788
            m[i].length -= entry_top - base;
789
            continue;
790
        }
791
792
        // Nested (pain)
793
        if (base > entry_base && top < entry_top) {
794
            // Entry gets top shaved off first
795
            m[i].length -= entry_top - base;
796
797
            // Now we need to create a new entry
798
            if (count >= memmap_max_entries)
799
                panic(false, "Memory map exhausted.");
800
801
            struct memmap_entry *new_entry = &m[count++];
802
803
            new_entry->type = m[i].type;
804
            new_entry->base = top;
805
            new_entry->length = entry_top - top;
806
807
            continue;
808
        }
809
    }
810
811
    if (count >= memmap_max_entries)
812
        panic(false, "Memory map exhausted.");
813
814
    struct memmap_entry *target = &m[count++];
815
816
    target->type = type;
817
    target->base = base;
818
    target->length = length;
819
820
    *_count = count;
821
    return true;
822
}
823
824
uint64_t pmm_check_type(uint64_t addr) {
825
    for (size_t i = 0; i < memmap_entries; i++) {
826
        uint64_t entry_base = memmap[i].base;
827
        uint64_t entry_top  = CHECKED_ADD(memmap[i].base, memmap[i].length, continue);
828
829
        if (addr >= entry_base && addr < entry_top) {
830
            return memmap[i].type;
831
        }
832
    }
833
834
    return (uint64_t)-1;
835
}
836
837
bool memmap_alloc_range_in(struct memmap_entry *m, size_t *_count,
838
                           uint64_t base, uint64_t length, uint32_t type, uint32_t overlay_type, bool do_panic, bool simulation, bool new_entry) {
839
    size_t count = *_count;
840
841
    if (length == 0)
842
        return true;
843
844
    if (simulation && new_entry) {
845
        return true;
846
    }
847
848
    uint64_t top = CHECKED_ADD(base, length, ({
849
        if (do_panic)
850
            panic(false, "Memory allocation overflow.");
851
        return false;
852
    }));
853
854
    for (size_t i = 0; i < count; i++) {
855
        if (overlay_type != 0 && m[i].type != overlay_type)
856
            continue;
857
858
        uint64_t entry_base = m[i].base;
859
        uint64_t entry_top = CHECKED_ADD(m[i].base, m[i].length, continue);
860
861
        if (base >= entry_base && base < entry_top && top <= entry_top) {
862
            if (simulation)
863
                return true;
864
865
            if (pmm_new_entry(m, &count, base, length, type) == true) {
866
                goto success;
867
            }
868
        }
869
    }
870
871
    if (!new_entry && do_panic)
872
        panic(false, "Memory allocation failure.");
873
874
    if (!new_entry) {
875
        return false;
876
    }
877
878
    if (pmm_new_entry(m, &count, base, length, type) == false) {
879
        return false;
880
    }
881
882
success:
883
    pmm_sanitise_entries(m, &count, false);
884
    *_count = count;
885
    return true;
886
}
887
888
bool memmap_alloc_range(uint64_t base, uint64_t length, uint32_t type, uint32_t overlay_type, bool do_panic, bool simulation, bool new_entry) {
889
    return memmap_alloc_range_in(memmap, &memmap_entries, base, length, type, overlay_type, do_panic, simulation, new_entry);
890
}
tab: 248 wrap: offon