malloc.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. /* $NetBSD: malloc.c,v 1.4 2004/12/14 00:21:01 nathanw Exp $ */
  2. /*
  3. * Copyright (c) 1983, 1993
  4. * The Regents of the University of California. All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of the University nor the names of its contributors
  15. * may be used to endorse or promote products derived from this software
  16. * without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  20. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  21. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  22. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  23. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  24. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  25. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  26. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  27. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  28. * SUCH DAMAGE.
  29. */
  30. #include <sys/cdefs.h>
  31. #if defined(LIBC_SCCS) && !defined(lint)
  32. #if 0
  33. static char sccsid[] = "@(#)malloc.c 8.1 (Berkeley) 6/4/93";
  34. #else
  35. __RCSID("$NetBSD: malloc.c,v 1.4 2004/12/14 00:21:01 nathanw Exp $");
  36. #endif
  37. #endif /* LIBC_SCCS and not lint */
  38. /*
  39. * malloc.c (Caltech) 2/21/82
  40. * Chris Kingsley, kingsley@cit-20.
  41. *
  42. * This is a very fast storage allocator. It allocates blocks of a small
  43. * number of different sizes, and keeps free lists of each size. Blocks that
  44. * don't exactly fit are passed up to the next larger size. In this
  45. * implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long.
  46. * This is designed for use in a virtual memory environment.
  47. */
  48. #include <sys/types.h>
  49. #if defined(DEBUG) || defined(RCHECK)
  50. #include <sys/uio.h>
  51. #endif
  52. #if defined(RCHECK) || defined(MSTATS)
  53. #include <stdio.h>
  54. #endif
  55. #include <stdlib.h>
  56. #include <string.h>
  57. #include <unistd.h>
  58. #include <pthread.h>
  59. /*
  60. * The overhead on a block is at least 4 bytes. When free, this space
  61. * contains a pointer to the next free block, and the bottom two bits must
  62. * be zero. When in use, the first byte is set to MAGIC, and the second
  63. * byte is the size index. The remaining bytes are for alignment.
  64. * If range checking is enabled then a second word holds the size of the
  65. * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC).
  66. * The order of elements is critical: ov_magic must overlay the low order
  67. * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern.
  68. */
  69. union overhead {
  70. union overhead *ov_next; /* when free */
  71. struct {
  72. u_char ovu_magic; /* magic number */
  73. u_char ovu_index; /* bucket # */
  74. #ifdef RCHECK
  75. u_short ovu_rmagic; /* range magic number */
  76. u_long ovu_size; /* actual block size */
  77. #endif
  78. } ovu;
  79. #define ov_magic ovu.ovu_magic
  80. #define ov_index ovu.ovu_index
  81. #define ov_rmagic ovu.ovu_rmagic
  82. #define ov_size ovu.ovu_size
  83. };
  84. #define MAGIC 0xef /* magic # on accounting info */
  85. #ifdef RCHECK
  86. #define RMAGIC 0x5555 /* magic # on range info */
  87. #endif
  88. #ifdef RCHECK
  89. #define RSLOP sizeof (u_short)
  90. #else
  91. #define RSLOP 0
  92. #endif
  93. /*
  94. * nextf[i] is the pointer to the next free block of size 2^(i+3). The
  95. * smallest allocatable block is 8 bytes. The overhead information
  96. * precedes the data area returned to the user.
  97. */
  98. #define NBUCKETS 30
  99. static union overhead *nextf[NBUCKETS];
  100. static long pagesz; /* page size */
  101. static int pagebucket; /* page size bucket */
  102. #ifdef MSTATS
  103. /*
  104. * nmalloc[i] is the difference between the number of mallocs and frees
  105. * for a given block size.
  106. */
  107. static u_int nmalloc[NBUCKETS];
  108. #endif
  109. static pthread_mutex_t malloc_mutex = PTHREAD_MUTEX_INITIALIZER;
  110. static void morecore(int);
  111. static int findbucket(union overhead *, int);
  112. #ifdef MSTATS
  113. void mstats(const char *);
  114. #endif
  115. #if defined(DEBUG) || defined(RCHECK)
  116. #define ASSERT(p) if (!(p)) botch(__STRING(p))
  117. static void botch(const char *);
  118. /*
  119. * NOTE: since this may be called while malloc_mutex is locked, stdio must not
  120. * be used in this function.
  121. */
  122. static void
  123. botch(s)
  124. const char *s;
  125. {
  126. struct iovec iov[3];
  127. iov[0].iov_base = "\nassertion botched: ";
  128. iov[0].iov_len = 20;
  129. iov[1].iov_base = (void *)s;
  130. iov[1].iov_len = strlen(s);
  131. iov[2].iov_base = "\n";
  132. iov[2].iov_len = 1;
  133. /*
  134. * This place deserves a word of warning: a cancellation point will
  135. * occur when executing writev(), and we might be still owning
  136. * malloc_mutex. At this point we need to disable cancellation
  137. * until `after' abort() because i) establishing a cancellation handler
  138. * might, depending on the implementation, result in another malloc()
  139. * to be executed, and ii) it is really not desirable to let execution
  140. * continue. `Fix me.'
  141. *
  142. * Note that holding mutex_lock during abort() is safe.
  143. */
  144. (void)writev(STDERR_FILENO, iov, 3);
  145. abort();
  146. }
  147. #else
  148. #define ASSERT(p)
  149. #endif
  150. void *
  151. malloc(nbytes)
  152. size_t nbytes;
  153. {
  154. union overhead *op;
  155. int bucket;
  156. long n;
  157. unsigned amt;
  158. pthread_mutex_lock(&malloc_mutex);
  159. /*
  160. * First time malloc is called, setup page size and
  161. * align break pointer so all data will be page aligned.
  162. */
  163. if (pagesz == 0) {
  164. pagesz = n = getpagesize();
  165. ASSERT(pagesz > 0);
  166. op = (union overhead *)(void *)sbrk(0);
  167. n = n - sizeof (*op) - ((long)op & (n - 1));
  168. if (n < 0)
  169. n += pagesz;
  170. if (n) {
  171. if (sbrk((int)n) == (void *)-1) {
  172. pthread_mutex_unlock(&malloc_mutex);
  173. return (NULL);
  174. }
  175. }
  176. bucket = 0;
  177. amt = 8;
  178. while (pagesz > amt) {
  179. amt <<= 1;
  180. bucket++;
  181. }
  182. pagebucket = bucket;
  183. }
  184. /*
  185. * Convert amount of memory requested into closest block size
  186. * stored in hash buckets which satisfies request.
  187. * Account for space used per block for accounting.
  188. */
  189. if (nbytes <= (n = pagesz - sizeof (*op) - RSLOP)) {
  190. #ifndef RCHECK
  191. amt = 8; /* size of first bucket */
  192. bucket = 0;
  193. #else
  194. amt = 16; /* size of first bucket */
  195. bucket = 1;
  196. #endif
  197. n = -((long)sizeof (*op) + RSLOP);
  198. } else {
  199. amt = (unsigned)pagesz;
  200. bucket = pagebucket;
  201. }
  202. while (nbytes > amt + n) {
  203. amt <<= 1;
  204. if (amt == 0)
  205. return (NULL);
  206. bucket++;
  207. }
  208. /*
  209. * If nothing in hash bucket right now,
  210. * request more memory from the system.
  211. */
  212. if ((op = nextf[bucket]) == NULL) {
  213. morecore(bucket);
  214. if ((op = nextf[bucket]) == NULL) {
  215. pthread_mutex_unlock(&malloc_mutex);
  216. return (NULL);
  217. }
  218. }
  219. /* remove from linked list */
  220. nextf[bucket] = op->ov_next;
  221. op->ov_magic = MAGIC;
  222. op->ov_index = bucket;
  223. #ifdef MSTATS
  224. nmalloc[bucket]++;
  225. #endif
  226. pthread_mutex_unlock(&malloc_mutex);
  227. #ifdef RCHECK
  228. /*
  229. * Record allocated size of block and
  230. * bound space with magic numbers.
  231. */
  232. op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
  233. op->ov_rmagic = RMAGIC;
  234. *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
  235. #endif
  236. return ((void *)(op + 1));
  237. }
  238. /*
  239. * Allocate more memory to the indicated bucket.
  240. */
  241. static void
  242. morecore(bucket)
  243. int bucket;
  244. {
  245. union overhead *op;
  246. long sz; /* size of desired block */
  247. long amt; /* amount to allocate */
  248. long nblks; /* how many blocks we get */
  249. /*
  250. * sbrk_size <= 0 only for big, FLUFFY, requests (about
  251. * 2^30 bytes on a VAX, I think) or for a negative arg.
  252. */
  253. sz = 1 << (bucket + 3);
  254. #ifdef DEBUG
  255. ASSERT(sz > 0);
  256. #else
  257. if (sz <= 0)
  258. return;
  259. #endif
  260. if (sz < pagesz) {
  261. amt = pagesz;
  262. nblks = amt / sz;
  263. } else {
  264. amt = sz + pagesz;
  265. nblks = 1;
  266. }
  267. op = (union overhead *)(void *)sbrk((int)amt);
  268. /* no more room! */
  269. if ((long)op == -1)
  270. return;
  271. /*
  272. * Add new memory allocated to that on
  273. * free list for this hash bucket.
  274. */
  275. nextf[bucket] = op;
  276. while (--nblks > 0) {
  277. op->ov_next =
  278. (union overhead *)(void *)((caddr_t)(void *)op+(size_t)sz);
  279. op = op->ov_next;
  280. }
  281. }
  282. void
  283. free(cp)
  284. void *cp;
  285. {
  286. long size;
  287. union overhead *op;
  288. if (cp == NULL)
  289. return;
  290. op = (union overhead *)(void *)((caddr_t)cp - sizeof (union overhead));
  291. #ifdef DEBUG
  292. ASSERT(op->ov_magic == MAGIC); /* make sure it was in use */
  293. #else
  294. if (op->ov_magic != MAGIC)
  295. return; /* sanity */
  296. #endif
  297. #ifdef RCHECK
  298. ASSERT(op->ov_rmagic == RMAGIC);
  299. ASSERT(*(u_short *)((caddr_t)(op + 1) + op->ov_size) == RMAGIC);
  300. #endif
  301. size = op->ov_index;
  302. ASSERT(size < NBUCKETS);
  303. pthread_mutex_lock(&malloc_mutex);
  304. op->ov_next = nextf[(unsigned int)size];/* also clobbers ov_magic */
  305. nextf[(unsigned int)size] = op;
  306. #ifdef MSTATS
  307. nmalloc[(size_t)size]--;
  308. #endif
  309. pthread_mutex_unlock(&malloc_mutex);
  310. }
  311. /*
  312. * When a program attempts "storage compaction" as mentioned in the
  313. * old malloc man page, it realloc's an already freed block. Usually
  314. * this is the last block it freed; occasionally it might be farther
  315. * back. We have to search all the free lists for the block in order
  316. * to determine its bucket: 1st we make one pass thru the lists
  317. * checking only the first block in each; if that fails we search
  318. * ``__realloc_srchlen'' blocks in each list for a match (the variable
  319. * is extern so the caller can modify it). If that fails we just copy
  320. * however many bytes was given to realloc() and hope it's not huge.
  321. */
  322. int __realloc_srchlen = 4; /* 4 should be plenty, -1 =>'s whole list */
  323. void *
  324. realloc(cp, nbytes)
  325. void *cp;
  326. size_t nbytes;
  327. {
  328. u_long onb;
  329. long i;
  330. union overhead *op;
  331. char *res;
  332. int was_alloced = 0;
  333. if (cp == NULL)
  334. return (malloc(nbytes));
  335. if (nbytes == 0) {
  336. free (cp);
  337. return (NULL);
  338. }
  339. op = (union overhead *)(void *)((caddr_t)cp - sizeof (union overhead));
  340. pthread_mutex_lock(&malloc_mutex);
  341. if (op->ov_magic == MAGIC) {
  342. was_alloced++;
  343. i = op->ov_index;
  344. } else {
  345. /*
  346. * Already free, doing "compaction".
  347. *
  348. * Search for the old block of memory on the
  349. * free list. First, check the most common
  350. * case (last element free'd), then (this failing)
  351. * the last ``__realloc_srchlen'' items free'd.
  352. * If all lookups fail, then assume the size of
  353. * the memory block being realloc'd is the
  354. * largest possible (so that all "nbytes" of new
  355. * memory are copied into). Note that this could cause
  356. * a memory fault if the old area was tiny, and the moon
  357. * is gibbous. However, that is very unlikely.
  358. */
  359. if ((i = findbucket(op, 1)) < 0 &&
  360. (i = findbucket(op, __realloc_srchlen)) < 0)
  361. i = NBUCKETS;
  362. }
  363. onb = (u_long)1 << (u_long)(i + 3);
  364. if (onb < pagesz)
  365. onb -= sizeof (*op) + RSLOP;
  366. else
  367. onb += pagesz - sizeof (*op) - RSLOP;
  368. /* avoid the copy if same size block */
  369. if (was_alloced) {
  370. if (i) {
  371. i = (long)1 << (long)(i + 2);
  372. if (i < pagesz)
  373. i -= sizeof (*op) + RSLOP;
  374. else
  375. i += pagesz - sizeof (*op) - RSLOP;
  376. }
  377. if (nbytes <= onb && nbytes > i) {
  378. #ifdef RCHECK
  379. op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
  380. *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
  381. #endif
  382. pthread_mutex_unlock(&malloc_mutex);
  383. return (cp);
  384. }
  385. #ifndef _REENT
  386. else
  387. free(cp);
  388. #endif
  389. }
  390. pthread_mutex_unlock(&malloc_mutex);
  391. if ((res = malloc(nbytes)) == NULL) {
  392. #ifdef _REENT
  393. free(cp);
  394. #endif
  395. return (NULL);
  396. }
  397. #ifndef _REENT
  398. if (cp != res) /* common optimization if "compacting" */
  399. (void)memmove(res, cp, (size_t)((nbytes < onb) ? nbytes : onb));
  400. #else
  401. (void)memmove(res, cp, (size_t)((nbytes < onb) ? nbytes : onb));
  402. free(cp);
  403. #endif
  404. return (res);
  405. }
  406. /*
  407. * Search ``srchlen'' elements of each free list for a block whose
  408. * header starts at ``freep''. If srchlen is -1 search the whole list.
  409. * Return bucket number, or -1 if not found.
  410. */
  411. static int
  412. findbucket(freep, srchlen)
  413. union overhead *freep;
  414. int srchlen;
  415. {
  416. union overhead *p;
  417. int i, j;
  418. for (i = 0; i < NBUCKETS; i++) {
  419. j = 0;
  420. for (p = nextf[i]; p && j != srchlen; p = p->ov_next) {
  421. if (p == freep)
  422. return (i);
  423. j++;
  424. }
  425. }
  426. return (-1);
  427. }
  428. #ifdef MSTATS
  429. /*
  430. * mstats - print out statistics about malloc
  431. *
  432. * Prints two lines of numbers, one showing the length of the free list
  433. * for each size category, the second showing the number of mallocs -
  434. * frees for each size category.
  435. */
  436. void
  437. mstats(s)
  438. char *s;
  439. {
  440. int i, j;
  441. union overhead *p;
  442. int totfree = 0,
  443. totused = 0;
  444. fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s);
  445. for (i = 0; i < NBUCKETS; i++) {
  446. for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
  447. ;
  448. fprintf(stderr, " %d", j);
  449. totfree += j * (1 << (i + 3));
  450. }
  451. fprintf(stderr, "\nused:\t");
  452. for (i = 0; i < NBUCKETS; i++) {
  453. fprintf(stderr, " %d", nmalloc[i]);
  454. totused += nmalloc[i] * (1 << (i + 3));
  455. }
  456. fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n",
  457. totused, totfree);
  458. }
  459. #endif