mm.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. /* mm.c - functions for memory manager */
  2. /*
  3. * GRUB -- GRand Unified Bootloader
  4. * Copyright (C) 2002,2005,2007,2008,2009 Free Software Foundation, Inc.
  5. *
  6. * GRUB is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * GRUB is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with GRUB. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. /*
  20. The design of this memory manager.
  21. This is a simple implementation of malloc with a few extensions. These are
  22. the extensions:
  23. - memalign is implemented efficiently.
  24. - multiple regions may be used as free space. They may not be
  25. contiguous.
  26. - if existing regions are insufficient to satisfy an allocation, a new
  27. region can be requested from firmware.
  28. Regions are managed by a singly linked list, and the meta information is
  29. stored in the beginning of each region. Space after the meta information
  30. is used to allocate memory.
  31. The memory space is used as cells instead of bytes for simplicity. This
  32. is important for some CPUs which may not access multiple bytes at a time
  33. when the first byte is not aligned at a certain boundary (typically,
  34. 4-byte or 8-byte). The size of each cell is equal to the size of struct
  35. grub_mm_header, so the header of each allocated/free block fits into one
  36. cell precisely. One cell is 16 bytes on 32-bit platforms and 32 bytes
  37. on 64-bit platforms.
  38. There are two types of blocks: allocated blocks and free blocks.
  39. In allocated blocks, the header of each block has only its size. Note that
  40. this size is based on cells but not on bytes. The header is located right
  41. before the returned pointer, that is, the header resides at the previous
  42. cell.
  43. Free blocks constitutes a ring, using a singly linked list. The first free
  44. block is pointed to by the meta information of a region. The allocator
  45. attempts to pick up the second block instead of the first one. This is
  46. a typical optimization against defragmentation, and makes the
  47. implementation a bit easier.
  48. For safety, both allocated blocks and free ones are marked by magic
  49. numbers. Whenever anything unexpected is detected, GRUB aborts the
  50. operation.
  51. */
  52. #include <config.h>
  53. #include <grub/mm.h>
  54. #include <grub/misc.h>
  55. #include <grub/err.h>
  56. #include <grub/types.h>
  57. #include <grub/disk.h>
  58. #include <grub/dl.h>
  59. #include <grub/i18n.h>
  60. #include <grub/mm_private.h>
  61. #include <grub/safemath.h>
  62. #ifdef MM_DEBUG
  63. # undef grub_calloc
  64. # undef grub_malloc
  65. # undef grub_zalloc
  66. # undef grub_realloc
  67. # undef grub_free
  68. # undef grub_memalign
  69. #endif
  70. /*
  71. * GRUB_MM_MGMT_OVERHEAD is an upper bound of management overhead of
  72. * each region, with any possible padding taken into account.
  73. *
  74. * The value must be large enough to make sure grub_memalign(align, size)
  75. * always succeeds after a successful call to
  76. * grub_mm_init_region(addr, size + align + GRUB_MM_MGMT_OVERHEAD),
  77. * for any given addr, align and size (assuming no interger overflow).
  78. *
  79. * The worst case which has maximum overhead is shown in the figure below:
  80. *
  81. * +-- addr
  82. * v |<- size + align ->|
  83. * +---------+----------------+----------------+------------------+---------+
  84. * | padding | grub_mm_region | grub_mm_header | usable bytes | padding |
  85. * +---------+----------------+----------------+------------------+---------+
  86. * |<- a ->|<- b ->|<- c ->|<- d ->|<- e ->|
  87. * ^
  88. * b == sizeof (struct grub_mm_region) | / Assuming no other suitable
  89. * c == sizeof (struct grub_mm_header) | | block is available, then:
  90. * d == size + align +-| If align == 0, this will be
  91. * | the pointer returned by next
  92. * Assuming addr % GRUB_MM_ALIGN == 1, then: | grub_memalign(align, size).
  93. * a == GRUB_MM_ALIGN - 1 | If align > 0, this chunk may
  94. * | need to be split to fulfill
  95. * Assuming d % GRUB_MM_ALIGN == 1, then: | alignment requirements, and
  96. * e == GRUB_MM_ALIGN - 1 | the returned pointer may be
  97. * \ inside these usable bytes.
  98. * Therefore, the maximum overhead is:
  99. * a + b + c + e == (GRUB_MM_ALIGN - 1) + sizeof (struct grub_mm_region)
  100. * + sizeof (struct grub_mm_header) + (GRUB_MM_ALIGN - 1)
  101. */
  102. #define GRUB_MM_MGMT_OVERHEAD ((GRUB_MM_ALIGN - 1) \
  103. + sizeof (struct grub_mm_region) \
  104. + sizeof (struct grub_mm_header) \
  105. + (GRUB_MM_ALIGN - 1))
  106. /* The size passed to grub_mm_add_region_fn() is aligned up by this value. */
  107. #define GRUB_MM_HEAP_GROW_ALIGN 4096
  108. /* Minimal heap growth granularity when existing heap space is exhausted. */
  109. #define GRUB_MM_HEAP_GROW_EXTRA 0x100000
  110. grub_mm_region_t grub_mm_base;
  111. grub_mm_add_region_func_t grub_mm_add_region_fn;
  112. /* Get a header from the pointer PTR, and set *P and *R to a pointer
  113. to the header and a pointer to its region, respectively. PTR must
  114. be allocated. */
  115. static void
  116. get_header_from_pointer (void *ptr, grub_mm_header_t *p, grub_mm_region_t *r)
  117. {
  118. if ((grub_addr_t) ptr & (GRUB_MM_ALIGN - 1))
  119. grub_fatal ("unaligned pointer %p", ptr);
  120. for (*r = grub_mm_base; *r; *r = (*r)->next)
  121. if ((grub_addr_t) ptr > (grub_addr_t) ((*r) + 1)
  122. && (grub_addr_t) ptr <= (grub_addr_t) ((*r) + 1) + (*r)->size)
  123. break;
  124. if (! *r)
  125. grub_fatal ("out of range pointer %p", ptr);
  126. *p = (grub_mm_header_t) ptr - 1;
  127. if ((*p)->magic == GRUB_MM_FREE_MAGIC)
  128. grub_fatal ("double free at %p", *p);
  129. if ((*p)->magic != GRUB_MM_ALLOC_MAGIC)
  130. grub_fatal ("alloc magic is broken at %p: %lx", *p,
  131. (unsigned long) (*p)->magic);
  132. }
  133. /* Initialize a region starting from ADDR and whose size is SIZE,
  134. to use it as free space. */
  135. void
  136. grub_mm_init_region (void *addr, grub_size_t size)
  137. {
  138. grub_mm_header_t h;
  139. grub_mm_region_t r, *p, q;
  140. grub_dprintf ("regions", "Using memory for heap: start=%p, end=%p\n",
  141. addr, (char *) addr + (unsigned int) size);
  142. /* Exclude last 4K to avoid overflows. */
  143. /* If addr + 0x1000 overflows then whole region is in excluded zone. */
  144. if ((grub_addr_t) addr > ~((grub_addr_t) 0x1000))
  145. return;
  146. /* If addr + 0x1000 + size overflows then decrease size. */
  147. if (((grub_addr_t) addr + 0x1000) > ~(grub_addr_t) size)
  148. size = ((grub_addr_t) -0x1000) - (grub_addr_t) addr;
  149. /* Attempt to merge this region with every existing region */
  150. for (p = &grub_mm_base, q = *p; q; p = &(q->next), q = *p)
  151. {
  152. /*
  153. * Is the new region immediately below an existing region? That
  154. * is, is the address of the memory we're adding now (addr) + size
  155. * of the memory we're adding (size) + the bytes we couldn't use
  156. * at the start of the region we're considering (q->pre_size)
  157. * equal to the address of q? In other words, does the memory
  158. * looks like this?
  159. *
  160. * addr q
  161. * |----size-----|-q->pre_size-|<q region>|
  162. */
  163. grub_dprintf ("regions", "Can we extend into region above?"
  164. " %p + %" PRIxGRUB_SIZE " + %" PRIxGRUB_SIZE " ?=? %p\n",
  165. (grub_uint8_t *) addr, size, q->pre_size, (grub_uint8_t *) q);
  166. if ((grub_uint8_t *) addr + size + q->pre_size == (grub_uint8_t *) q)
  167. {
  168. grub_dprintf ("regions", "Yes: extending a region: (%p -> %p) -> (%p -> %p)\n",
  169. q, (grub_uint8_t *) q + sizeof (*q) + q->size,
  170. addr, (grub_uint8_t *) q + sizeof (*q) + q->size);
  171. /*
  172. * Yes, we can merge the memory starting at addr into the
  173. * existing region from below. Align up addr to GRUB_MM_ALIGN
  174. * so that our new region has proper alignment.
  175. */
  176. r = (grub_mm_region_t) ALIGN_UP ((grub_addr_t) addr, GRUB_MM_ALIGN);
  177. /* Copy the region data across */
  178. *r = *q;
  179. /* Consider all the new size as pre-size */
  180. r->pre_size += size;
  181. /*
  182. * If we have enough pre-size to create a block, create a
  183. * block with it. Mark it as allocated and pass it to
  184. * grub_free (), which will sort out getting it into the free
  185. * list.
  186. */
  187. if (r->pre_size >> GRUB_MM_ALIGN_LOG2)
  188. {
  189. h = (grub_mm_header_t) (r + 1);
  190. /* block size is pre-size converted to cells */
  191. h->size = (r->pre_size >> GRUB_MM_ALIGN_LOG2);
  192. h->magic = GRUB_MM_ALLOC_MAGIC;
  193. /* region size grows by block size converted back to bytes */
  194. r->size += h->size << GRUB_MM_ALIGN_LOG2;
  195. /* adjust pre_size to be accurate */
  196. r->pre_size &= (GRUB_MM_ALIGN - 1);
  197. *p = r;
  198. grub_free (h + 1);
  199. }
  200. /* Replace the old region with the new region */
  201. *p = r;
  202. return;
  203. }
  204. /*
  205. * Is the new region immediately above an existing region? That
  206. * is:
  207. * q addr
  208. * |<q region>|-q->post_size-|----size-----|
  209. */
  210. grub_dprintf ("regions", "Can we extend into region below?"
  211. " %p + %x + %" PRIxGRUB_SIZE " + %" PRIxGRUB_SIZE " ?=? %p\n",
  212. (grub_uint8_t *) q, (int) sizeof (*q), q->size, q->post_size, (grub_uint8_t *) addr);
  213. if ((grub_uint8_t *) q + sizeof (*q) + q->size + q->post_size ==
  214. (grub_uint8_t *) addr)
  215. {
  216. grub_dprintf ("regions", "Yes: extending a region: (%p -> %p) -> (%p -> %p)\n",
  217. q, (grub_uint8_t *) q + sizeof (*q) + q->size,
  218. q, (grub_uint8_t *) addr + size);
  219. /*
  220. * Yes! Follow a similar pattern to above, but simpler.
  221. * Our header starts at address - post_size, which should align us
  222. * to a cell boundary.
  223. *
  224. * Cast to (void *) first to avoid the following build error:
  225. * kern/mm.c: In function ‘grub_mm_init_region’:
  226. * kern/mm.c:211:15: error: cast increases required alignment of target type [-Werror=cast-align]
  227. * 211 | h = (grub_mm_header_t) ((grub_uint8_t *) addr - q->post_size);
  228. * | ^
  229. * It is safe to do that because proper alignment is enforced in grub_mm_size_sanity_check().
  230. */
  231. h = (grub_mm_header_t)(void *) ((grub_uint8_t *) addr - q->post_size);
  232. /* our size is the allocated size plus post_size, in cells */
  233. h->size = (size + q->post_size) >> GRUB_MM_ALIGN_LOG2;
  234. h->magic = GRUB_MM_ALLOC_MAGIC;
  235. /* region size grows by block size converted back to bytes */
  236. q->size += h->size << GRUB_MM_ALIGN_LOG2;
  237. /* adjust new post_size to be accurate */
  238. q->post_size = (q->post_size + size) & (GRUB_MM_ALIGN - 1);
  239. grub_free (h + 1);
  240. return;
  241. }
  242. }
  243. grub_dprintf ("regions", "No: considering a new region at %p of size %" PRIxGRUB_SIZE "\n",
  244. addr, size);
  245. /*
  246. * If you want to modify the code below, please also take a look at
  247. * GRUB_MM_MGMT_OVERHEAD and make sure it is synchronized with the code.
  248. */
  249. /* Allocate a region from the head. */
  250. r = (grub_mm_region_t) ALIGN_UP ((grub_addr_t) addr, GRUB_MM_ALIGN);
  251. /* If this region is too small, ignore it. */
  252. if (size < GRUB_MM_ALIGN + (char *) r - (char *) addr + sizeof (*r))
  253. return;
  254. size -= (char *) r - (char *) addr + sizeof (*r);
  255. h = (grub_mm_header_t) (r + 1);
  256. h->next = h;
  257. h->magic = GRUB_MM_FREE_MAGIC;
  258. h->size = (size >> GRUB_MM_ALIGN_LOG2);
  259. r->first = h;
  260. r->pre_size = (grub_addr_t) r - (grub_addr_t) addr;
  261. r->size = (h->size << GRUB_MM_ALIGN_LOG2);
  262. r->post_size = size - r->size;
  263. /* Find where to insert this region. Put a smaller one before bigger ones,
  264. to prevent fragmentation. */
  265. for (p = &grub_mm_base, q = *p; q; p = &(q->next), q = *p)
  266. if (q->size > r->size)
  267. break;
  268. *p = r;
  269. r->next = q;
  270. }
  271. /* Allocate the number of units N with the alignment ALIGN from the ring
  272. * buffer given in *FIRST. ALIGN must be a power of two. Both N and
  273. * ALIGN are in units of GRUB_MM_ALIGN. Return a non-NULL if successful,
  274. * otherwise return NULL.
  275. *
  276. * Note: because in certain circumstances we need to adjust the ->next
  277. * pointer of the previous block, we iterate over the singly linked
  278. * list with the pair (prev, cur). *FIRST is our initial previous, and
  279. * *FIRST->next is our initial current pointer. So we will actually
  280. * allocate from *FIRST->next first and *FIRST itself last.
  281. */
  282. static void *
  283. grub_real_malloc (grub_mm_header_t *first, grub_size_t n, grub_size_t align)
  284. {
  285. grub_mm_header_t cur, prev;
  286. /* When everything is allocated side effect is that *first will have alloc
  287. magic marked, meaning that there is no room in this region. */
  288. if ((*first)->magic == GRUB_MM_ALLOC_MAGIC)
  289. return 0;
  290. /* Try to search free slot for allocation in this memory region. */
  291. for (prev = *first, cur = prev->next; ; prev = cur, cur = cur->next)
  292. {
  293. grub_off_t extra;
  294. extra = ((grub_addr_t) (cur + 1) >> GRUB_MM_ALIGN_LOG2) & (align - 1);
  295. if (extra)
  296. extra = align - extra;
  297. if (! cur)
  298. grub_fatal ("null in the ring");
  299. if (cur->magic != GRUB_MM_FREE_MAGIC)
  300. grub_fatal ("free magic is broken at %p: 0x%x", cur, cur->magic);
  301. if (cur->size >= n + extra)
  302. {
  303. extra += (cur->size - extra - n) & (~(align - 1));
  304. if (extra == 0 && cur->size == n)
  305. {
  306. /* There is no special alignment requirement and memory block
  307. is complete match.
  308. 1. Just mark memory block as allocated and remove it from
  309. free list.
  310. Result:
  311. +---------------+ previous block's next
  312. | alloc, size=n | |
  313. +---------------+ v
  314. */
  315. prev->next = cur->next;
  316. }
  317. else if (align == 1 || cur->size == n + extra)
  318. {
  319. /* There might be alignment requirement, when taking it into
  320. account memory block fits in.
  321. 1. Allocate new area at end of memory block.
  322. 2. Reduce size of available blocks from original node.
  323. 3. Mark new area as allocated and "remove" it from free
  324. list.
  325. Result:
  326. +---------------+
  327. | free, size-=n | next --+
  328. +---------------+ |
  329. | alloc, size=n | |
  330. +---------------+ v
  331. */
  332. cur->size -= n;
  333. cur += cur->size;
  334. }
  335. else if (extra == 0)
  336. {
  337. grub_mm_header_t r;
  338. r = cur + extra + n;
  339. r->magic = GRUB_MM_FREE_MAGIC;
  340. r->size = cur->size - extra - n;
  341. r->next = cur->next;
  342. prev->next = r;
  343. if (prev == cur)
  344. {
  345. prev = r;
  346. r->next = r;
  347. }
  348. }
  349. else
  350. {
  351. /* There is alignment requirement and there is room in memory
  352. block. Split memory block to three pieces.
  353. 1. Create new memory block right after section being
  354. allocated. Mark it as free.
  355. 2. Add new memory block to free chain.
  356. 3. Mark current memory block having only extra blocks.
  357. 4. Advance to aligned block and mark that as allocated and
  358. "remove" it from free list.
  359. Result:
  360. +------------------------------+
  361. | free, size=extra | next --+
  362. +------------------------------+ |
  363. | alloc, size=n | |
  364. +------------------------------+ |
  365. | free, size=orig.size-extra-n | <------+, next --+
  366. +------------------------------+ v
  367. */
  368. grub_mm_header_t r;
  369. r = cur + extra + n;
  370. r->magic = GRUB_MM_FREE_MAGIC;
  371. r->size = cur->size - extra - n;
  372. r->next = cur;
  373. cur->size = extra;
  374. prev->next = r;
  375. cur += extra;
  376. }
  377. cur->magic = GRUB_MM_ALLOC_MAGIC;
  378. cur->size = n;
  379. /* Mark find as a start marker for next allocation to fasten it.
  380. This will have side effect of fragmenting memory as small
  381. pieces before this will be un-used. */
  382. /* So do it only for chunks under 32K. */
  383. if (n < (0x8000 >> GRUB_MM_ALIGN_LOG2)
  384. || *first == cur)
  385. *first = prev;
  386. return cur + 1;
  387. }
  388. /* Search was completed without result. */
  389. if (cur == *first)
  390. break;
  391. }
  392. return 0;
  393. }
  394. /* Allocate SIZE bytes with the alignment ALIGN and return the pointer. */
  395. void *
  396. grub_memalign (grub_size_t align, grub_size_t size)
  397. {
  398. grub_mm_region_t r;
  399. grub_size_t n = ((size + GRUB_MM_ALIGN - 1) >> GRUB_MM_ALIGN_LOG2) + 1;
  400. grub_size_t grow;
  401. int count = 0;
  402. if (!grub_mm_base)
  403. goto fail;
  404. if (size > ~(grub_size_t) align)
  405. goto fail;
  406. grow = size + align;
  407. /* We currently assume at least a 32-bit grub_size_t,
  408. so limiting allocations to <adress space size> - 1MiB
  409. in name of sanity is beneficial. */
  410. if (grow > ~(grub_size_t) 0x100000)
  411. goto fail;
  412. align = (align >> GRUB_MM_ALIGN_LOG2);
  413. if (align == 0)
  414. align = 1;
  415. again:
  416. for (r = grub_mm_base; r; r = r->next)
  417. {
  418. void *p;
  419. p = grub_real_malloc (&(r->first), n, align);
  420. if (p)
  421. return p;
  422. }
  423. /* If failed, increase free memory somehow. */
  424. switch (count)
  425. {
  426. case 0:
  427. /* Request additional pages, contiguous */
  428. count++;
  429. /*
  430. * Calculate the necessary size of heap growth (if applicable),
  431. * with region management overhead taken into account.
  432. */
  433. if (grub_add (grow, GRUB_MM_MGMT_OVERHEAD, &grow))
  434. goto fail;
  435. /* Preallocate some extra space if heap growth is small. */
  436. grow = grub_max (grow, GRUB_MM_HEAP_GROW_EXTRA);
  437. /* Align up heap growth to make it friendly to CPU/MMU. */
  438. if (grow > ~(grub_size_t) (GRUB_MM_HEAP_GROW_ALIGN - 1))
  439. goto fail;
  440. grow = ALIGN_UP (grow, GRUB_MM_HEAP_GROW_ALIGN);
  441. /* Do the same sanity check again. */
  442. if (grow > ~(grub_size_t) 0x100000)
  443. goto fail;
  444. if (grub_mm_add_region_fn != NULL &&
  445. grub_mm_add_region_fn (grow, GRUB_MM_ADD_REGION_CONSECUTIVE) == GRUB_ERR_NONE)
  446. goto again;
  447. /* fallthrough */
  448. case 1:
  449. /* Request additional pages, anything at all */
  450. count++;
  451. if (grub_mm_add_region_fn != NULL)
  452. {
  453. /*
  454. * Try again even if this fails, in case it was able to partially
  455. * satisfy the request
  456. */
  457. grub_mm_add_region_fn (grow, GRUB_MM_ADD_REGION_NONE);
  458. goto again;
  459. }
  460. /* fallthrough */
  461. case 2:
  462. /* Invalidate disk caches. */
  463. grub_disk_cache_invalidate_all ();
  464. count++;
  465. goto again;
  466. default:
  467. break;
  468. }
  469. fail:
  470. grub_error (GRUB_ERR_OUT_OF_MEMORY, N_("out of memory"));
  471. return 0;
  472. }
  473. /*
  474. * Allocate NMEMB instances of SIZE bytes and return the pointer, or error on
  475. * integer overflow.
  476. */
  477. void *
  478. grub_calloc (grub_size_t nmemb, grub_size_t size)
  479. {
  480. void *ret;
  481. grub_size_t sz = 0;
  482. if (grub_mul (nmemb, size, &sz))
  483. {
  484. grub_error (GRUB_ERR_OUT_OF_RANGE, N_("overflow is detected"));
  485. return NULL;
  486. }
  487. ret = grub_memalign (0, sz);
  488. if (!ret)
  489. return NULL;
  490. grub_memset (ret, 0, sz);
  491. return ret;
  492. }
  493. /* Allocate SIZE bytes and return the pointer. */
  494. void *
  495. grub_malloc (grub_size_t size)
  496. {
  497. return grub_memalign (0, size);
  498. }
  499. /* Allocate SIZE bytes, clear them and return the pointer. */
  500. void *
  501. grub_zalloc (grub_size_t size)
  502. {
  503. void *ret;
  504. ret = grub_memalign (0, size);
  505. if (ret)
  506. grub_memset (ret, 0, size);
  507. return ret;
  508. }
  509. /* Deallocate the pointer PTR. */
  510. void
  511. grub_free (void *ptr)
  512. {
  513. grub_mm_header_t p;
  514. grub_mm_region_t r;
  515. if (! ptr)
  516. return;
  517. get_header_from_pointer (ptr, &p, &r);
  518. if (r->first->magic == GRUB_MM_ALLOC_MAGIC)
  519. {
  520. p->magic = GRUB_MM_FREE_MAGIC;
  521. r->first = p->next = p;
  522. }
  523. else
  524. {
  525. grub_mm_header_t cur, prev;
  526. #if 0
  527. cur = r->first;
  528. do
  529. {
  530. grub_printf ("%s:%d: q=%p, q->size=0x%x, q->magic=0x%x\n",
  531. GRUB_FILE, __LINE__, cur, cur->size, cur->magic);
  532. cur = cur->next;
  533. }
  534. while (cur != r->first);
  535. #endif
  536. /* Iterate over all blocks in the free ring.
  537. *
  538. * The free ring is arranged from high addresses to low
  539. * addresses, modulo wraparound.
  540. *
  541. * We are looking for a block with a higher address than p or
  542. * whose next address is lower than p.
  543. */
  544. for (prev = r->first, cur = prev->next; cur <= p || cur->next >= p;
  545. prev = cur, cur = prev->next)
  546. {
  547. if (cur->magic != GRUB_MM_FREE_MAGIC)
  548. grub_fatal ("free magic is broken at %p: 0x%x", cur, cur->magic);
  549. /* Deal with wrap-around */
  550. if (cur <= cur->next && (cur > p || cur->next < p))
  551. break;
  552. }
  553. /* mark p as free and insert it between cur and cur->next */
  554. p->magic = GRUB_MM_FREE_MAGIC;
  555. p->next = cur->next;
  556. cur->next = p;
  557. /*
  558. * If the block we are freeing can be merged with the next
  559. * free block, do that.
  560. */
  561. if (p->next + p->next->size == p)
  562. {
  563. p->magic = 0;
  564. p->next->size += p->size;
  565. cur->next = p->next;
  566. p = p->next;
  567. }
  568. r->first = cur;
  569. /* Likewise if can be merged with the preceeding free block */
  570. if (cur == p + p->size)
  571. {
  572. cur->magic = 0;
  573. p->size += cur->size;
  574. if (cur == prev)
  575. prev = p;
  576. prev->next = p;
  577. cur = prev;
  578. }
  579. /*
  580. * Set r->first such that the just free()d block is tried first.
  581. * (An allocation is tried from *first->next, and cur->next == p.)
  582. */
  583. r->first = cur;
  584. }
  585. }
  586. /* Reallocate SIZE bytes and return the pointer. The contents will be
  587. the same as that of PTR. */
  588. void *
  589. grub_realloc (void *ptr, grub_size_t size)
  590. {
  591. grub_mm_header_t p;
  592. grub_mm_region_t r;
  593. void *q;
  594. grub_size_t n;
  595. if (! ptr)
  596. return grub_malloc (size);
  597. if (! size)
  598. {
  599. grub_free (ptr);
  600. return 0;
  601. }
  602. /* FIXME: Not optimal. */
  603. n = ((size + GRUB_MM_ALIGN - 1) >> GRUB_MM_ALIGN_LOG2) + 1;
  604. get_header_from_pointer (ptr, &p, &r);
  605. if (p->size >= n)
  606. return ptr;
  607. q = grub_malloc (size);
  608. if (! q)
  609. return q;
  610. /* We've already checked that p->size < n. */
  611. grub_memcpy (q, ptr, p->size << GRUB_MM_ALIGN_LOG2);
  612. grub_free (ptr);
  613. return q;
  614. }
  615. #ifdef MM_DEBUG
  616. int grub_mm_debug = 0;
  617. void
  618. grub_mm_dump_free (void)
  619. {
  620. grub_mm_region_t r;
  621. for (r = grub_mm_base; r; r = r->next)
  622. {
  623. grub_mm_header_t p;
  624. grub_printf ("Region %p (size %" PRIuGRUB_SIZE ")\n\n", r, r->size);
  625. /* Follow the free list. */
  626. p = r->first;
  627. do
  628. {
  629. if (p->magic != GRUB_MM_FREE_MAGIC)
  630. grub_fatal ("free magic is broken at %p: 0x%x", p, p->magic);
  631. grub_printf ("F:%p:%u:%p\n",
  632. p, (unsigned int) p->size << GRUB_MM_ALIGN_LOG2, p->next);
  633. p = p->next;
  634. }
  635. while (p != r->first);
  636. }
  637. grub_printf ("\n");
  638. }
  639. void
  640. grub_mm_dump (unsigned lineno)
  641. {
  642. grub_mm_region_t r;
  643. grub_printf ("called at line %u\n", lineno);
  644. for (r = grub_mm_base; r; r = r->next)
  645. {
  646. grub_mm_header_t p;
  647. grub_printf ("Region %p (size %" PRIuGRUB_SIZE ")\n\n", r, r->size);
  648. for (p = (grub_mm_header_t) ALIGN_UP ((grub_addr_t) (r + 1),
  649. GRUB_MM_ALIGN);
  650. (grub_addr_t) p < (grub_addr_t) (r+1) + r->size;
  651. p++)
  652. {
  653. switch (p->magic)
  654. {
  655. case GRUB_MM_FREE_MAGIC:
  656. grub_printf ("F:%p:%u:%p\n",
  657. p, (unsigned int) p->size << GRUB_MM_ALIGN_LOG2, p->next);
  658. break;
  659. case GRUB_MM_ALLOC_MAGIC:
  660. grub_printf ("A:%p:%u\n", p, (unsigned int) p->size << GRUB_MM_ALIGN_LOG2);
  661. break;
  662. }
  663. }
  664. }
  665. grub_printf ("\n");
  666. }
  667. void *
  668. grub_debug_calloc (const char *file, int line, grub_size_t nmemb, grub_size_t size)
  669. {
  670. void *ptr;
  671. if (grub_mm_debug)
  672. grub_printf ("%s:%d: calloc (0x%" PRIxGRUB_SIZE ", 0x%" PRIxGRUB_SIZE ") = ",
  673. file, line, nmemb, size);
  674. ptr = grub_calloc (nmemb, size);
  675. if (grub_mm_debug)
  676. grub_printf ("%p\n", ptr);
  677. return ptr;
  678. }
  679. void *
  680. grub_debug_malloc (const char *file, int line, grub_size_t size)
  681. {
  682. void *ptr;
  683. if (grub_mm_debug)
  684. grub_printf ("%s:%d: malloc (0x%" PRIxGRUB_SIZE ") = ", file, line, size);
  685. ptr = grub_malloc (size);
  686. if (grub_mm_debug)
  687. grub_printf ("%p\n", ptr);
  688. return ptr;
  689. }
  690. void *
  691. grub_debug_zalloc (const char *file, int line, grub_size_t size)
  692. {
  693. void *ptr;
  694. if (grub_mm_debug)
  695. grub_printf ("%s:%d: zalloc (0x%" PRIxGRUB_SIZE ") = ", file, line, size);
  696. ptr = grub_zalloc (size);
  697. if (grub_mm_debug)
  698. grub_printf ("%p\n", ptr);
  699. return ptr;
  700. }
  701. void
  702. grub_debug_free (const char *file, int line, void *ptr)
  703. {
  704. if (grub_mm_debug)
  705. grub_printf ("%s:%d: free (%p)\n", file, line, ptr);
  706. grub_free (ptr);
  707. }
  708. void *
  709. grub_debug_realloc (const char *file, int line, void *ptr, grub_size_t size)
  710. {
  711. if (grub_mm_debug)
  712. grub_printf ("%s:%d: realloc (%p, 0x%" PRIxGRUB_SIZE ") = ", file, line, ptr, size);
  713. ptr = grub_realloc (ptr, size);
  714. if (grub_mm_debug)
  715. grub_printf ("%p\n", ptr);
  716. return ptr;
  717. }
  718. void *
  719. grub_debug_memalign (const char *file, int line, grub_size_t align,
  720. grub_size_t size)
  721. {
  722. void *ptr;
  723. if (grub_mm_debug)
  724. grub_printf ("%s:%d: memalign (0x%" PRIxGRUB_SIZE ", 0x%" PRIxGRUB_SIZE
  725. ") = ", file, line, align, size);
  726. ptr = grub_memalign (align, size);
  727. if (grub_mm_debug)
  728. grub_printf ("%p\n", ptr);
  729. return ptr;
  730. }
  731. #endif /* MM_DEBUG */