malloc.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <limits.h>
  4. #include <stdint.h>
  5. #include <errno.h>
  6. #include <sys/mman.h>
  7. #include "libc.h"
  8. #include "atomic.h"
  9. #include "pthread_impl.h"
  10. uintptr_t __brk(uintptr_t);
  11. void *__mmap(void *, size_t, int, int, int, off_t);
  12. int __munmap(void *, size_t);
  13. void *__mremap(void *, size_t, size_t, int, ...);
  14. int __madvise(void *, size_t, int);
  15. struct chunk {
  16. size_t data[1];
  17. struct chunk *next;
  18. struct chunk *prev;
  19. };
  20. struct bin {
  21. int lock[2];
  22. struct chunk *head;
  23. struct chunk *tail;
  24. };
  25. static struct {
  26. uintptr_t brk;
  27. size_t *heap;
  28. uint64_t binmap;
  29. struct bin bins[64];
  30. int brk_lock[2];
  31. int free_lock[2];
  32. } mal;
  33. #define SIZE_ALIGN (4*sizeof(size_t))
  34. #define SIZE_MASK (-SIZE_ALIGN)
  35. #define OVERHEAD (2*sizeof(size_t))
  36. #define MMAP_THRESHOLD (0x1c00*SIZE_ALIGN)
  37. #define DONTCARE 16
  38. #define RECLAIM 163840
  39. #define CHUNK_SIZE(c) ((c)->data[0] & SIZE_MASK)
  40. #define CHUNK_PSIZE(c) ((c)->data[-1] & SIZE_MASK)
  41. #define PREV_CHUNK(c) ((struct chunk *)((char *)(c) - CHUNK_PSIZE(c)))
  42. #define NEXT_CHUNK(c) ((struct chunk *)((char *)(c) + CHUNK_SIZE(c)))
  43. #define MEM_TO_CHUNK(p) (struct chunk *)((size_t *)p - 1)
  44. #define CHUNK_TO_MEM(c) (void *)((c)->data+1)
  45. #define BIN_TO_CHUNK(i) (MEM_TO_CHUNK(&mal.bins[i].head))
  46. #define C_INUSE ((size_t)1)
  47. #define C_FLAGS ((size_t)3)
  48. #define C_SIZE SIZE_MASK
  49. #define IS_MMAPPED(c) !((c)->data[0] & (C_INUSE))
  50. /* Synchronization tools */
  51. static void lock(volatile int *lk)
  52. {
  53. if (!libc.threads_minus_1) return;
  54. while(a_swap(lk, 1)) __wait(lk, lk+1, 1, 1);
  55. }
  56. static void unlock(volatile int *lk)
  57. {
  58. if (!libc.threads_minus_1) return;
  59. a_store(lk, 0);
  60. if (lk[1]) __wake(lk, 1, 1);
  61. }
  62. static void lock_bin(int i)
  63. {
  64. if (libc.threads_minus_1)
  65. lock(mal.bins[i].lock);
  66. if (!mal.bins[i].head)
  67. mal.bins[i].head = mal.bins[i].tail = BIN_TO_CHUNK(i);
  68. }
  69. static void unlock_bin(int i)
  70. {
  71. if (!libc.threads_minus_1) return;
  72. unlock(mal.bins[i].lock);
  73. }
  74. static int first_set(uint64_t x)
  75. {
  76. #if 1
  77. return a_ctz_64(x);
  78. #else
  79. static const char debruijn64[64] = {
  80. 0, 1, 2, 53, 3, 7, 54, 27, 4, 38, 41, 8, 34, 55, 48, 28,
  81. 62, 5, 39, 46, 44, 42, 22, 9, 24, 35, 59, 56, 49, 18, 29, 11,
  82. 63, 52, 6, 26, 37, 40, 33, 47, 61, 45, 43, 21, 23, 58, 17, 10,
  83. 51, 25, 36, 32, 60, 20, 57, 16, 50, 31, 19, 15, 30, 14, 13, 12
  84. };
  85. static const char debruijn32[32] = {
  86. 0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13,
  87. 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14
  88. };
  89. if (sizeof(long) < 8) {
  90. uint32_t y = x;
  91. if (!y) {
  92. y = x>>32;
  93. return 32 + debruijn32[(y&-y)*0x076be629 >> 27];
  94. }
  95. return debruijn32[(y&-y)*0x076be629 >> 27];
  96. }
  97. return debruijn64[(x&-x)*0x022fdd63cc95386dull >> 58];
  98. #endif
  99. }
  100. static int bin_index(size_t x)
  101. {
  102. x = x / SIZE_ALIGN - 1;
  103. if (x <= 32) return x;
  104. if (x > 0x1c00) return 63;
  105. return ((union { float v; uint32_t r; }){ x }.r>>21) - 496;
  106. }
  107. static int bin_index_up(size_t x)
  108. {
  109. x = x / SIZE_ALIGN - 1;
  110. if (x <= 32) return x;
  111. return ((union { float v; uint32_t r; }){ x }.r+0x1fffff>>21) - 496;
  112. }
  113. #if 0
  114. void __dump_heap(int x)
  115. {
  116. struct chunk *c;
  117. int i;
  118. for (c = (void *)mal.heap; CHUNK_SIZE(c); c = NEXT_CHUNK(c))
  119. fprintf(stderr, "base %p size %zu (%d) flags %d/%d\n",
  120. c, CHUNK_SIZE(c), bin_index(CHUNK_SIZE(c)),
  121. c->data[0] & 15,
  122. NEXT_CHUNK(c)->data[-1] & 15);
  123. for (i=0; i<64; i++) {
  124. if (mal.bins[i].head != BIN_TO_CHUNK(i) && mal.bins[i].head) {
  125. fprintf(stderr, "bin %d: %p\n", i, mal.bins[i].head);
  126. if (!(mal.binmap & 1ULL<<i))
  127. fprintf(stderr, "missing from binmap!\n");
  128. } else if (mal.binmap & 1ULL<<i)
  129. fprintf(stderr, "binmap wrongly contains %d!\n", i);
  130. }
  131. }
  132. #endif
  133. static struct chunk *expand_heap(size_t n)
  134. {
  135. struct chunk *w;
  136. uintptr_t new;
  137. lock(mal.brk_lock);
  138. if (n > SIZE_MAX - mal.brk - 2*PAGE_SIZE) goto fail;
  139. new = mal.brk + n + SIZE_ALIGN + PAGE_SIZE - 1 & -PAGE_SIZE;
  140. n = new - mal.brk;
  141. if (__brk(new) != new) goto fail;
  142. w = MEM_TO_CHUNK(new);
  143. w->data[-1] = n | C_INUSE;
  144. w->data[0] = 0 | C_INUSE;
  145. w = MEM_TO_CHUNK(mal.brk);
  146. w->data[0] = n | C_INUSE;
  147. mal.brk = new;
  148. unlock(mal.brk_lock);
  149. return w;
  150. fail:
  151. unlock(mal.brk_lock);
  152. return 0;
  153. }
  154. static int init_malloc()
  155. {
  156. static int init, waiters;
  157. int state;
  158. struct chunk *c;
  159. if (init == 2) return 0;
  160. while ((state=a_swap(&init, 1)) == 1)
  161. __wait(&init, &waiters, 1, 1);
  162. if (state) {
  163. a_store(&init, 2);
  164. return 0;
  165. }
  166. mal.brk = __brk(0) + 2*SIZE_ALIGN-1 & -SIZE_ALIGN;
  167. c = expand_heap(1);
  168. if (!c) {
  169. a_store(&init, 0);
  170. if (waiters) __wake(&init, 1, 1);
  171. return -1;
  172. }
  173. mal.heap = (void *)c;
  174. c->data[-1] = 0 | C_INUSE;
  175. free(CHUNK_TO_MEM(c));
  176. a_store(&init, 2);
  177. if (waiters) __wake(&init, -1, 1);
  178. return 0;
  179. }
  180. static int adjust_size(size_t *n)
  181. {
  182. /* Result of pointer difference must fit in ptrdiff_t. */
  183. if (*n-1 > PTRDIFF_MAX - SIZE_ALIGN - PAGE_SIZE) {
  184. if (*n) {
  185. errno = ENOMEM;
  186. return -1;
  187. } else {
  188. *n = SIZE_ALIGN;
  189. return 0;
  190. }
  191. }
  192. *n = (*n + OVERHEAD + SIZE_ALIGN - 1) & SIZE_MASK;
  193. return 0;
  194. }
  195. static void unbin(struct chunk *c, int i)
  196. {
  197. if (c->prev == c->next)
  198. a_and_64(&mal.binmap, ~(1ULL<<i));
  199. c->prev->next = c->next;
  200. c->next->prev = c->prev;
  201. c->data[0] |= C_INUSE;
  202. NEXT_CHUNK(c)->data[-1] |= C_INUSE;
  203. }
  204. static int alloc_fwd(struct chunk *c)
  205. {
  206. int i;
  207. size_t k;
  208. while (!((k=c->data[0]) & C_INUSE)) {
  209. i = bin_index(k);
  210. lock_bin(i);
  211. if (c->data[0] == k) {
  212. unbin(c, i);
  213. unlock_bin(i);
  214. return 1;
  215. }
  216. unlock_bin(i);
  217. }
  218. return 0;
  219. }
  220. static int alloc_rev(struct chunk *c)
  221. {
  222. int i;
  223. size_t k;
  224. while (!((k=c->data[-1]) & C_INUSE)) {
  225. i = bin_index(k);
  226. lock_bin(i);
  227. if (c->data[-1] == k) {
  228. unbin(PREV_CHUNK(c), i);
  229. unlock_bin(i);
  230. return 1;
  231. }
  232. unlock_bin(i);
  233. }
  234. return 0;
  235. }
  236. /* pretrim - trims a chunk _prior_ to removing it from its bin.
  237. * Must be called with i as the ideal bin for size n, j the bin
  238. * for the _free_ chunk self, and bin j locked. */
  239. static int pretrim(struct chunk *self, size_t n, int i, int j)
  240. {
  241. size_t n1;
  242. struct chunk *next, *split;
  243. /* We cannot pretrim if it would require re-binning. */
  244. if (j < 40) return 0;
  245. if (j < i+3) {
  246. if (j != 63) return 0;
  247. n1 = CHUNK_SIZE(self);
  248. if (n1-n <= MMAP_THRESHOLD) return 0;
  249. } else {
  250. n1 = CHUNK_SIZE(self);
  251. }
  252. if (bin_index(n1-n) != j) return 0;
  253. next = NEXT_CHUNK(self);
  254. split = (void *)((char *)self + n);
  255. split->prev = self->prev;
  256. split->next = self->next;
  257. split->prev->next = split;
  258. split->next->prev = split;
  259. split->data[-1] = n | C_INUSE;
  260. split->data[0] = n1-n;
  261. next->data[-1] = n1-n;
  262. self->data[0] = n | C_INUSE;
  263. return 1;
  264. }
  265. static void trim(struct chunk *self, size_t n)
  266. {
  267. size_t n1 = CHUNK_SIZE(self);
  268. struct chunk *next, *split;
  269. if (n >= n1 - DONTCARE) return;
  270. next = NEXT_CHUNK(self);
  271. split = (void *)((char *)self + n);
  272. split->data[-1] = n | C_INUSE;
  273. split->data[0] = n1-n | C_INUSE;
  274. next->data[-1] = n1-n | C_INUSE;
  275. self->data[0] = n | C_INUSE;
  276. free(CHUNK_TO_MEM(split));
  277. }
  278. void *malloc(size_t n)
  279. {
  280. struct chunk *c;
  281. int i, j;
  282. if (adjust_size(&n) < 0) return 0;
  283. if (n > MMAP_THRESHOLD) {
  284. size_t len = n + PAGE_SIZE - 1 & -PAGE_SIZE;
  285. char *base = __mmap(0, len, PROT_READ|PROT_WRITE,
  286. MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
  287. if (base == (void *)-1) return 0;
  288. c = (void *)(base + SIZE_ALIGN - sizeof(size_t));
  289. c->data[0] = len - (SIZE_ALIGN - sizeof(size_t));
  290. c->data[-1] = SIZE_ALIGN - sizeof(size_t);
  291. return CHUNK_TO_MEM(c);
  292. }
  293. i = bin_index_up(n);
  294. for (;;) {
  295. uint64_t mask = mal.binmap & -(1ULL<<i);
  296. if (!mask) {
  297. init_malloc();
  298. c = expand_heap(n);
  299. if (!c) return 0;
  300. if (alloc_rev(c)) {
  301. struct chunk *x = c;
  302. c = PREV_CHUNK(c);
  303. NEXT_CHUNK(x)->data[-1] = c->data[0] =
  304. x->data[0] + CHUNK_SIZE(c);
  305. }
  306. break;
  307. }
  308. j = first_set(mask);
  309. lock_bin(j);
  310. c = mal.bins[j].head;
  311. if (c != BIN_TO_CHUNK(j) && j == bin_index(c->data[0])) {
  312. if (!pretrim(c, n, i, j)) unbin(c, j);
  313. unlock_bin(j);
  314. break;
  315. }
  316. unlock_bin(j);
  317. }
  318. /* Now patch up in case we over-allocated */
  319. trim(c, n);
  320. return CHUNK_TO_MEM(c);
  321. }
  322. void *realloc(void *p, size_t n)
  323. {
  324. struct chunk *self, *next;
  325. size_t n0, n1;
  326. void *new;
  327. if (!p) return malloc(n);
  328. if (adjust_size(&n) < 0) return 0;
  329. self = MEM_TO_CHUNK(p);
  330. n1 = n0 = CHUNK_SIZE(self);
  331. if (IS_MMAPPED(self)) {
  332. size_t extra = self->data[-1];
  333. char *base = (char *)self - extra;
  334. size_t oldlen = n0 + extra;
  335. size_t newlen = n + extra;
  336. if (newlen < PAGE_SIZE && (new = malloc(n))) {
  337. memcpy(new, p, n-OVERHEAD);
  338. free(p);
  339. return new;
  340. }
  341. newlen = (newlen + PAGE_SIZE-1) & -PAGE_SIZE;
  342. if (oldlen == newlen) return p;
  343. base = __mremap(base, oldlen, newlen, MREMAP_MAYMOVE);
  344. if (base == (void *)-1)
  345. return newlen < oldlen ? p : 0;
  346. self = (void *)(base + extra);
  347. self->data[0] = newlen - extra;
  348. return CHUNK_TO_MEM(self);
  349. }
  350. next = NEXT_CHUNK(self);
  351. /* Merge adjacent chunks if we need more space. This is not
  352. * a waste of time even if we fail to get enough space, because our
  353. * subsequent call to free would otherwise have to do the merge. */
  354. if (n > n1 && alloc_fwd(next)) {
  355. n1 += CHUNK_SIZE(next);
  356. next = NEXT_CHUNK(next);
  357. }
  358. /* FIXME: find what's wrong here and reenable it..? */
  359. if (0 && n > n1 && alloc_rev(self)) {
  360. self = PREV_CHUNK(self);
  361. n1 += CHUNK_SIZE(self);
  362. }
  363. self->data[0] = n1 | C_INUSE;
  364. next->data[-1] = n1 | C_INUSE;
  365. /* If we got enough space, split off the excess and return */
  366. if (n <= n1) {
  367. //memmove(CHUNK_TO_MEM(self), p, n0-OVERHEAD);
  368. trim(self, n);
  369. return CHUNK_TO_MEM(self);
  370. }
  371. /* As a last resort, allocate a new chunk and copy to it. */
  372. new = malloc(n-OVERHEAD);
  373. if (!new) return 0;
  374. memcpy(new, p, n0-OVERHEAD);
  375. free(CHUNK_TO_MEM(self));
  376. return new;
  377. }
  378. void free(void *p)
  379. {
  380. struct chunk *self = MEM_TO_CHUNK(p);
  381. struct chunk *next;
  382. size_t final_size, new_size, size;
  383. int reclaim=0;
  384. int i;
  385. if (!p) return;
  386. if (IS_MMAPPED(self)) {
  387. size_t extra = self->data[-1];
  388. char *base = (char *)self - extra;
  389. size_t len = CHUNK_SIZE(self) + extra;
  390. __munmap(base, len);
  391. return;
  392. }
  393. final_size = new_size = CHUNK_SIZE(self);
  394. next = NEXT_CHUNK(self);
  395. for (;;) {
  396. /* Replace middle of large chunks with fresh zero pages */
  397. if (reclaim && (self->data[-1] & next->data[0] & C_INUSE)) {
  398. uintptr_t a = (uintptr_t)self + SIZE_ALIGN+PAGE_SIZE-1 & -PAGE_SIZE;
  399. uintptr_t b = (uintptr_t)next - SIZE_ALIGN & -PAGE_SIZE;
  400. #if 1
  401. __madvise((void *)a, b-a, MADV_DONTNEED);
  402. #else
  403. __mmap((void *)a, b-a, PROT_READ|PROT_WRITE,
  404. MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, -1, 0);
  405. #endif
  406. }
  407. if (self->data[-1] & next->data[0] & C_INUSE) {
  408. self->data[0] = final_size | C_INUSE;
  409. next->data[-1] = final_size | C_INUSE;
  410. i = bin_index(final_size);
  411. lock_bin(i);
  412. lock(mal.free_lock);
  413. if (self->data[-1] & next->data[0] & C_INUSE)
  414. break;
  415. unlock(mal.free_lock);
  416. unlock_bin(i);
  417. }
  418. if (alloc_rev(self)) {
  419. self = PREV_CHUNK(self);
  420. size = CHUNK_SIZE(self);
  421. final_size += size;
  422. if (new_size+size > RECLAIM && (new_size+size^size) > size)
  423. reclaim = 1;
  424. }
  425. if (alloc_fwd(next)) {
  426. size = CHUNK_SIZE(next);
  427. final_size += size;
  428. if (new_size+size > RECLAIM && (new_size+size^size) > size)
  429. reclaim = 1;
  430. next = NEXT_CHUNK(next);
  431. }
  432. }
  433. self->data[0] = final_size;
  434. next->data[-1] = final_size;
  435. unlock(mal.free_lock);
  436. self->next = BIN_TO_CHUNK(i);
  437. self->prev = mal.bins[i].tail;
  438. self->next->prev = self;
  439. self->prev->next = self;
  440. if (!(mal.binmap & 1ULL<<i))
  441. a_or_64(&mal.binmap, 1ULL<<i);
  442. unlock_bin(i);
  443. }