Enable optionroms to use freed space due to CONFIG_RELOCATE_INIT.
[seabios.git] / src / pmm.c
1 // Post memory manager (PMM) calls
2 //
3 // Copyright (C) 2009  Kevin O'Connor <kevin@koconnor.net>
4 //
5 // This file may be distributed under the terms of the GNU LGPLv3 license.
6
7 #include "util.h" // checksum
8 #include "config.h" // BUILD_BIOS_ADDR
9 #include "memmap.h" // struct e820entry
10 #include "farptr.h" // GET_FARVAR
11 #include "biosvar.h" // GET_BDA
12
13
14 #if MODESEGMENT
15 // The 16bit pmm entry points runs in "big real" mode, and can
16 // therefore read/write to the 32bit malloc variables.
17 #define GET_PMMVAR(var) ({                      \
18             SET_SEG(ES, 0);                     \
19             __GET_VAR("addr32 ", ES, (var)); })
20 #define SET_PMMVAR(var, val) do {               \
21         SET_SEG(ES, 0);                         \
22         __SET_VAR("addr32 ", ES, (var), (val)); \
23     } while (0)
24 #else
25 #define GET_PMMVAR(var) (var)
26 #define SET_PMMVAR(var, val) do { (var) = (val); } while (0)
27 #endif
28
29 // Information on a reserved area.
30 struct allocinfo_s {
31     struct allocinfo_s *next, **pprev;
32     void *data, *dataend, *allocend;
33 };
34
35 // Information on a tracked memory allocation.
36 struct allocdetail_s {
37     struct allocinfo_s detailinfo;
38     struct allocinfo_s datainfo;
39     u32 handle;
40 };
41
42 // The various memory zones.
43 struct zone_s {
44     struct allocinfo_s *info;
45 };
46
47 struct zone_s ZoneLow VAR32FLATVISIBLE;
48 struct zone_s ZoneHigh VAR32FLATVISIBLE;
49 struct zone_s ZoneFSeg VAR32FLATVISIBLE;
50 struct zone_s ZoneTmpLow VAR32FLATVISIBLE;
51 struct zone_s ZoneTmpHigh VAR32FLATVISIBLE;
52
53 struct zone_s *Zones[] VAR32FLATVISIBLE = {
54     &ZoneTmpLow, &ZoneLow, &ZoneFSeg, &ZoneTmpHigh, &ZoneHigh
55 };
56
57
58 /****************************************************************
59  * low-level memory reservations
60  ****************************************************************/
61
62 // Find and reserve space from a given zone
63 static void *
64 allocSpace(struct zone_s *zone, u32 size, u32 align, struct allocinfo_s *fill)
65 {
66     struct allocinfo_s *info;
67     for (info = GET_PMMVAR(zone->info); info; info = GET_PMMVAR(info->next)) {
68         void *dataend = GET_PMMVAR(info->dataend);
69         void *allocend = GET_PMMVAR(info->allocend);
70         void *newallocend = (void*)ALIGN_DOWN((u32)allocend - size, align);
71         if (newallocend >= dataend && newallocend <= allocend) {
72             // Found space - now reserve it.
73             struct allocinfo_s **pprev = GET_PMMVAR(info->pprev);
74             if (!fill)
75                 fill = newallocend;
76             SET_PMMVAR(fill->next, info);
77             SET_PMMVAR(fill->pprev, pprev);
78             SET_PMMVAR(fill->data, newallocend);
79             SET_PMMVAR(fill->dataend, newallocend + size);
80             SET_PMMVAR(fill->allocend, allocend);
81
82             SET_PMMVAR(info->allocend, newallocend);
83             SET_PMMVAR(info->pprev, &fill->next);
84             SET_PMMVAR(*pprev, fill);
85             return newallocend;
86         }
87     }
88     return NULL;
89 }
90
91 // Release space allocated with allocSpace()
92 static void
93 freeSpace(struct allocinfo_s *info)
94 {
95     struct allocinfo_s *next = GET_PMMVAR(info->next);
96     struct allocinfo_s **pprev = GET_PMMVAR(info->pprev);
97     SET_PMMVAR(*pprev, next);
98     if (next) {
99         if (GET_PMMVAR(next->allocend) == GET_PMMVAR(info->data))
100             SET_PMMVAR(next->allocend, GET_PMMVAR(info->allocend));
101         SET_PMMVAR(next->pprev, pprev);
102     }
103 }
104
105 // Add new memory to a zone
106 static void
107 addSpace(struct zone_s *zone, void *start, void *end)
108 {
109     // Find position to add space
110     struct allocinfo_s **pprev = &zone->info, *info;
111     for (;;) {
112         info = GET_PMMVAR(*pprev);
113         if (!info || GET_PMMVAR(info->data) < start)
114             break;
115         pprev = &info->next;
116     }
117
118     // Add space using temporary allocation info.
119     struct allocdetail_s tempdetail;
120     tempdetail.datainfo.next = info;
121     tempdetail.datainfo.pprev = pprev;
122     tempdetail.datainfo.data = tempdetail.datainfo.dataend = start;
123     tempdetail.datainfo.allocend = end;
124     struct allocdetail_s *tempdetailp = MAKE_FLATPTR(GET_SEG(SS), &tempdetail);
125     SET_PMMVAR(*pprev, &tempdetailp->datainfo);
126     if (info)
127         SET_PMMVAR(info->pprev, &tempdetailp->datainfo.next);
128
129     // Allocate final allocation info.
130     struct allocdetail_s *detail = allocSpace(
131         &ZoneTmpHigh, sizeof(*detail), MALLOC_MIN_ALIGN, NULL);
132     if (!detail) {
133         detail = allocSpace(&ZoneTmpLow, sizeof(*detail)
134                             , MALLOC_MIN_ALIGN, NULL);
135         if (!detail) {
136             SET_PMMVAR(*tempdetail.datainfo.pprev, tempdetail.datainfo.next);
137             if (tempdetail.datainfo.next)
138                 SET_PMMVAR(tempdetail.datainfo.next->pprev
139                            , tempdetail.datainfo.pprev);
140             warn_noalloc();
141             return;
142         }
143     }
144
145     // Replace temp alloc space with final alloc space
146     memcpy_fl(&detail->datainfo, &tempdetailp->datainfo
147               , sizeof(detail->datainfo));
148     SET_PMMVAR(detail->handle, PMM_DEFAULT_HANDLE);
149
150     SET_PMMVAR(*tempdetail.datainfo.pprev, &detail->datainfo);
151     if (tempdetail.datainfo.next)
152         SET_PMMVAR(tempdetail.datainfo.next->pprev, &detail->datainfo.next);
153 }
154
155 // Search all zones for an allocation obtained from allocSpace()
156 static struct allocinfo_s *
157 findAlloc(void *data)
158 {
159     int i;
160     for (i=0; i<ARRAY_SIZE(Zones); i++) {
161         struct zone_s *zone = GET_PMMVAR(Zones[i]);
162         struct allocinfo_s *info;
163         for (info = GET_PMMVAR(zone->info); info; info = GET_PMMVAR(info->next))
164             if (GET_PMMVAR(info->data) == data)
165                 return info;
166     }
167     return NULL;
168 }
169
170 // Return the last sentinal node of a zone
171 static struct allocinfo_s *
172 findLast(struct zone_s *zone)
173 {
174     struct allocinfo_s *info = GET_PMMVAR(zone->info);
175     if (!info)
176         return NULL;
177     for (;;) {
178         struct allocinfo_s *next = GET_PMMVAR(info->next);
179         if (!next)
180             return info;
181         info = next;
182     }
183 }
184
185
186 /****************************************************************
187  * Setup
188  ****************************************************************/
189
190 void
191 malloc_setup(void)
192 {
193     ASSERT32FLAT();
194     dprintf(3, "malloc setup\n");
195
196     ZoneLow.info = ZoneHigh.info = ZoneFSeg.info = NULL;
197     ZoneTmpLow.info = ZoneTmpHigh.info = NULL;
198
199     // Clear memory in 0xf0000 area.
200     memset(BiosTableSpace, 0, CONFIG_MAX_BIOSTABLE);
201
202     // Populate temp high ram
203     u32 highram = 0;
204     int i;
205     for (i=e820_count-1; i>=0; i--) {
206         struct e820entry *en = &e820_list[i];
207         u64 end = en->start + en->size;
208         if (end < 1024*1024)
209             break;
210         if (en->type != E820_RAM || end > 0xffffffff)
211             continue;
212         u32 s = en->start, e = end;
213         if (!highram) {
214             u32 newe = ALIGN_DOWN(e - CONFIG_MAX_HIGHTABLE, MALLOC_MIN_ALIGN);
215             if (newe <= e && newe >= s) {
216                 highram = newe;
217                 e = newe;
218             }
219         }
220         addSpace(&ZoneTmpHigh, (void*)s, (void*)e);
221     }
222
223     // Populate other regions
224     addSpace(&ZoneTmpLow, (void*)BUILD_STACK_ADDR, (void*)BUILD_EBDA_MINIMUM);
225     addSpace(&ZoneFSeg, BiosTableSpace, &BiosTableSpace[CONFIG_MAX_BIOSTABLE]);
226     addSpace(&ZoneLow, (void*)BUILD_LOWRAM_END, (void*)BUILD_LOWRAM_END);
227     if (highram) {
228         addSpace(&ZoneHigh, (void*)highram
229                  , (void*)highram + CONFIG_MAX_HIGHTABLE);
230         add_e820(highram, CONFIG_MAX_HIGHTABLE, E820_RESERVED);
231     }
232 }
233
234 void
235 malloc_finalize(void)
236 {
237     dprintf(3, "malloc finalize\n");
238
239     // Reserve more low-mem if needed.
240     u32 endlow = GET_BDA(mem_size_kb)*1024;
241     add_e820(endlow, BUILD_LOWRAM_END-endlow, E820_RESERVED);
242
243     // Give back unused high ram.
244     struct allocinfo_s *info = findLast(&ZoneHigh);
245     if (info) {
246         u32 giveback = ALIGN_DOWN(info->allocend - info->dataend, PAGE_SIZE);
247         add_e820((u32)info->dataend, giveback, E820_RAM);
248         dprintf(1, "Returned %d bytes of ZoneHigh\n", giveback);
249     }
250 }
251
252
253 /****************************************************************
254  * ebda movement
255  ****************************************************************/
256
257 // Move ebda
258 static int
259 relocate_ebda(u32 newebda, u32 oldebda, u8 ebda_size)
260 {
261     u32 lowram = GET_BDA(mem_size_kb) * 1024;
262     if (oldebda != lowram)
263         // EBDA isn't at end of ram - give up.
264         return -1;
265
266     // Do copy (this assumes memcpy copies forward - otherwise memmove
267     // is needed)
268     memcpy_fl((void*)newebda, (void*)oldebda, ebda_size * 1024);
269
270     // Update indexes
271     dprintf(1, "ebda moved from %x to %x\n", oldebda, newebda);
272     SET_BDA(mem_size_kb, newebda / 1024);
273     SET_BDA(ebda_seg, FLATPTR_TO_SEG(newebda));
274     return 0;
275 }
276
277 // Support expanding the ZoneLow dynamically.
278 static void
279 zonelow_expand(u32 size, u32 align)
280 {
281     struct allocinfo_s *info = findLast(&ZoneLow);
282     if (!info)
283         return;
284     u32 oldpos = (u32)GET_PMMVAR(info->allocend);
285     u32 newpos = ALIGN_DOWN(oldpos - size, align);
286     u32 bottom = (u32)GET_PMMVAR(info->dataend);
287     if (newpos >= bottom && newpos <= oldpos)
288         // Space already present.
289         return;
290     u16 ebda_seg = get_ebda_seg();
291     u32 ebda_pos = (u32)MAKE_FLATPTR(ebda_seg, 0);
292     u8 ebda_size = GET_EBDA2(ebda_seg, size);
293     u32 ebda_end = ebda_pos + ebda_size * 1024;
294     if (ebda_end != bottom)
295         // Something else is after ebda - can't use any existing space.
296         newpos = ALIGN_DOWN(ebda_end - size, align);
297     u32 newbottom = ALIGN_DOWN(newpos, 1024);
298     u32 newebda = ALIGN_DOWN(newbottom - ebda_size * 1024, 1024);
299     if (newebda < BUILD_EBDA_MINIMUM)
300         // Not enough space.
301         return;
302
303     // Move ebda
304     int ret = relocate_ebda(newebda, ebda_pos, ebda_size);
305     if (ret)
306         return;
307
308     // Update zone
309     if (ebda_end == bottom) {
310         SET_PMMVAR(info->data, (void*)newbottom);
311         SET_PMMVAR(info->dataend, (void*)newbottom);
312     } else
313         addSpace(&ZoneLow, (void*)newbottom, (void*)ebda_end);
314 }
315
316 // Check if can expand the given zone to fulfill an allocation
317 static void *
318 allocExpandSpace(struct zone_s *zone, u32 size, u32 align
319                  , struct allocinfo_s *fill)
320 {
321     void *data = allocSpace(zone, size, align, fill);
322     if (data || zone != &ZoneLow)
323         return data;
324
325     // Make sure to not move ebda while an optionrom is running.
326     if (unlikely(wait_preempt())) {
327         data = allocSpace(zone, size, align, fill);
328         if (data)
329             return data;
330     }
331
332     zonelow_expand(size, align);
333     return allocSpace(zone, size, align, fill);
334 }
335
336
337 /****************************************************************
338  * tracked memory allocations
339  ****************************************************************/
340
341 // Allocate memory from the given zone and track it as a PMM allocation
342 void * __malloc
343 pmm_malloc(struct zone_s *zone, u32 handle, u32 size, u32 align)
344 {
345     if (!size)
346         return NULL;
347
348     // Find and reserve space for bookkeeping.
349     struct allocdetail_s *detail = allocSpace(
350         &ZoneTmpHigh, sizeof(*detail), MALLOC_MIN_ALIGN, NULL);
351     if (!detail) {
352         detail = allocSpace(&ZoneTmpLow, sizeof(*detail)
353                             , MALLOC_MIN_ALIGN, NULL);
354         if (!detail)
355             return NULL;
356     }
357
358     // Find and reserve space for main allocation
359     void *data = allocExpandSpace(zone, size, align, &detail->datainfo);
360     if (!data) {
361         freeSpace(&detail->detailinfo);
362         return NULL;
363     }
364
365     dprintf(8, "pmm_malloc zone=%p handle=%x size=%d align=%x"
366             " ret=%p (detail=%p)\n"
367             , zone, handle, size, align
368             , data, detail);
369     SET_PMMVAR(detail->handle, handle);
370
371     return data;
372 }
373
374 // Free a data block allocated with pmm_malloc
375 int
376 pmm_free(void *data)
377 {
378     struct allocinfo_s *info = findAlloc(data);
379     if (!info || data == (void*)info || data == GET_PMMVAR(info->dataend))
380         return -1;
381     struct allocdetail_s *detail = container_of(
382         info, struct allocdetail_s, datainfo);
383     dprintf(8, "pmm_free %p (detail=%p)\n", data, detail);
384     freeSpace(info);
385     freeSpace(&detail->detailinfo);
386     return 0;
387 }
388
389 // Find the amount of free space in a given zone.
390 static u32
391 pmm_getspace(struct zone_s *zone)
392 {
393     // XXX - doesn't account for ZoneLow being able to grow.
394     // XXX - results not reliable when CONFIG_THREAD_OPTIONROMS
395     u32 maxspace = 0;
396     struct allocinfo_s *info;
397     for (info = GET_PMMVAR(zone->info); info; info = GET_PMMVAR(info->next)) {
398         u32 space = GET_PMMVAR(info->allocend) - GET_PMMVAR(info->dataend);
399         if (space > maxspace)
400             maxspace = space;
401     }
402
403     if (zone != &ZoneTmpHigh && zone != &ZoneTmpLow)
404         return maxspace;
405     // Account for space needed for PMM tracking.
406     u32 reserve = ALIGN(sizeof(struct allocdetail_s), MALLOC_MIN_ALIGN);
407     if (maxspace <= reserve)
408         return 0;
409     return maxspace - reserve;
410 }
411
412 // Find the data block allocated with pmm_malloc with a given handle.
413 static void *
414 pmm_find(u32 handle)
415 {
416     int i;
417     for (i=0; i<ARRAY_SIZE(Zones); i++) {
418         struct zone_s *zone = GET_PMMVAR(Zones[i]);
419         struct allocinfo_s *info;
420         for (info = GET_PMMVAR(zone->info); info
421                  ; info = GET_PMMVAR(info->next)) {
422             if (GET_PMMVAR(info->data) != (void*)info)
423                 continue;
424             struct allocdetail_s *detail = container_of(
425                 info, struct allocdetail_s, detailinfo);
426             if (GET_PMMVAR(detail->handle) == handle)
427                 return GET_PMMVAR(detail->datainfo.data);
428         }
429     }
430     return NULL;
431 }
432
433
434 /****************************************************************
435  * pmm interface
436  ****************************************************************/
437
438 struct pmmheader {
439     u32 signature;
440     u8 version;
441     u8 length;
442     u8 checksum;
443     u16 entry_offset;
444     u16 entry_seg;
445     u8 reserved[5];
446 } PACKED;
447
448 extern struct pmmheader PMMHEADER;
449
450 #define PMM_SIGNATURE 0x4d4d5024 // $PMM
451
452 #if CONFIG_PMM
453 struct pmmheader PMMHEADER __aligned(16) VAR16EXPORT = {
454     .version = 0x01,
455     .length = sizeof(PMMHEADER),
456     .entry_seg = SEG_BIOS,
457 };
458 #endif
459
460 #define PMM_FUNCTION_NOT_SUPPORTED 0xffffffff
461
462 // PMM - allocate
463 static u32
464 handle_pmm00(u16 *args)
465 {
466     u32 length = *(u32*)&args[1], handle = *(u32*)&args[3];
467     u16 flags = args[5];
468     dprintf(3, "pmm00: length=%x handle=%x flags=%x\n"
469             , length, handle, flags);
470     struct zone_s *lowzone = &ZoneTmpLow, *highzone = &ZoneTmpHigh;
471     if (flags & 8) {
472         // Permanent memory request.
473         lowzone = &ZoneLow;
474         highzone = &ZoneHigh;
475     }
476     if (!length) {
477         // Memory size request
478         switch (flags & 3) {
479         default:
480         case 0:
481             return 0;
482         case 1:
483             return pmm_getspace(lowzone);
484         case 2:
485             return pmm_getspace(highzone);
486         case 3: {
487             u32 spacelow = pmm_getspace(lowzone);
488             u32 spacehigh = pmm_getspace(highzone);
489             if (spacelow > spacehigh)
490                 return spacelow;
491             return spacehigh;
492         }
493         }
494     }
495     u32 size = length * 16;
496     if ((s32)size <= 0)
497         return 0;
498     u32 align = MALLOC_MIN_ALIGN;
499     if (flags & 4) {
500         align = 1<<__ffs(size);
501         if (align < MALLOC_MIN_ALIGN)
502             align = MALLOC_MIN_ALIGN;
503     }
504     switch (flags & 3) {
505     default:
506     case 0:
507         return 0;
508     case 1:
509         return (u32)pmm_malloc(lowzone, handle, size, align);
510     case 2:
511         return (u32)pmm_malloc(highzone, handle, size, align);
512     case 3: {
513         void *data = pmm_malloc(lowzone, handle, size, align);
514         if (data)
515             return (u32)data;
516         return (u32)pmm_malloc(highzone, handle, size, align);
517     }
518     }
519 }
520
521 // PMM - find
522 static u32
523 handle_pmm01(u16 *args)
524 {
525     u32 handle = *(u32*)&args[1];
526     dprintf(3, "pmm01: handle=%x\n", handle);
527     if (handle == PMM_DEFAULT_HANDLE)
528         return 0;
529     return (u32)pmm_find(handle);
530 }
531
532 // PMM - deallocate
533 static u32
534 handle_pmm02(u16 *args)
535 {
536     u32 buffer = *(u32*)&args[1];
537     dprintf(3, "pmm02: buffer=%x\n", buffer);
538     int ret = pmm_free((void*)buffer);
539     if (ret)
540         // Error
541         return 1;
542     return 0;
543 }
544
545 static u32
546 handle_pmmXX(u16 *args)
547 {
548     return PMM_FUNCTION_NOT_SUPPORTED;
549 }
550
551 u32 VISIBLE16
552 handle_pmm(u16 *args)
553 {
554     if (! CONFIG_PMM)
555         return PMM_FUNCTION_NOT_SUPPORTED;
556
557     u16 arg1 = args[0];
558     dprintf(DEBUG_HDL_pmm, "pmm call arg1=%x\n", arg1);
559
560     switch (arg1) {
561     case 0x00: return handle_pmm00(args);
562     case 0x01: return handle_pmm01(args);
563     case 0x02: return handle_pmm02(args);
564     default:   return handle_pmmXX(args);
565     }
566 }
567
568 // romlayout.S
569 extern void entry_pmm(void);
570
571 void
572 pmm_setup(void)
573 {
574     if (! CONFIG_PMM)
575         return;
576
577     dprintf(3, "init PMM\n");
578
579     PMMHEADER.signature = PMM_SIGNATURE;
580     PMMHEADER.entry_offset = (u32)entry_pmm - BUILD_BIOS_ADDR;
581     PMMHEADER.checksum -= checksum(&PMMHEADER, sizeof(PMMHEADER));
582 }
583
584 void
585 pmm_finalize(void)
586 {
587     if (! CONFIG_PMM)
588         return;
589
590     dprintf(3, "finalize PMM\n");
591
592     PMMHEADER.signature = 0;
593     PMMHEADER.entry_offset = 0;
594 }