luat_bget.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. /*
  2. B G E T
  3. Buffer allocator
  4. Designed and implemented in April of 1972 by John Walker, based on the
  5. Case Algol OPRO$ algorithm implemented in 1966.
  6. Reimplemented in 1975 by John Walker for the Interdata 70.
  7. Reimplemented in 1977 by John Walker for the Marinchip 9900.
  8. Reimplemented in 1982 by Duff Kurland for the Intel 8080.
  9. Portable C version implemented in September of 1990 by an older, wiser
  10. instance of the original implementor.
  11. Souped up and/or weighed down slightly shortly thereafter by Greg
  12. Lutz.
  13. AMIX edition, including the new compaction call-back option, prepared
  14. by John Walker in July of 1992.
  15. Bug in built-in test program fixed, ANSI compiler warnings eradicated,
  16. buffer pool validator implemented, and guaranteed repeatable test
  17. added by John Walker in October of 1995.
  18. This program is in the public domain.
  19. 1. This is the book of the generations of Adam. In the day that God
  20. created man, in the likeness of God made he him;
  21. 2. Male and female created he them; and blessed them, and called
  22. their name Adam, in the day when they were created.
  23. 3. And Adam lived an hundred and thirty years, and begat a son in
  24. his own likeness, and after his image; and called his name Seth:
  25. 4. And the days of Adam after he had begotten Seth were eight
  26. hundred years: and he begat sons and daughters:
  27. 5. And all the days that Adam lived were nine hundred and thirty
  28. years: and he died.
  29. 6. And Seth lived an hundred and five years, and begat Enos:
  30. 7. And Seth lived after he begat Enos eight hundred and seven years,
  31. and begat sons and daughters:
  32. 8. And all the days of Seth were nine hundred and twelve years: and
  33. he died.
  34. 9. And Enos lived ninety years, and begat Cainan:
  35. 10. And Enos lived after he begat Cainan eight hundred and fifteen
  36. years, and begat sons and daughters:
  37. 11. And all the days of Enos were nine hundred and five years: and
  38. he died.
  39. 12. And Cainan lived seventy years and begat Mahalaleel:
  40. 13. And Cainan lived after he begat Mahalaleel eight hundred and
  41. forty years, and begat sons and daughters:
  42. 14. And all the days of Cainan were nine hundred and ten years: and
  43. he died.
  44. 15. And Mahalaleel lived sixty and five years, and begat Jared:
  45. 16. And Mahalaleel lived after he begat Jared eight hundred and
  46. thirty years, and begat sons and daughters:
  47. 17. And all the days of Mahalaleel were eight hundred ninety and
  48. five years: and he died.
  49. 18. And Jared lived an hundred sixty and two years, and he begat
  50. Enoch:
  51. 19. And Jared lived after he begat Enoch eight hundred years, and
  52. begat sons and daughters:
  53. 20. And all the days of Jared were nine hundred sixty and two years:
  54. and he died.
  55. 21. And Enoch lived sixty and five years, and begat Methuselah:
  56. 22. And Enoch walked with God after he begat Methuselah three
  57. hundred years, and begat sons and daughters:
  58. 23. And all the days of Enoch were three hundred sixty and five
  59. years:
  60. 24. And Enoch walked with God: and he was not; for God took him.
  61. 25. And Methuselah lived an hundred eighty and seven years, and
  62. begat Lamech.
  63. 26. And Methuselah lived after he begat Lamech seven hundred eighty
  64. and two years, and begat sons and daughters:
  65. 27. And all the days of Methuselah were nine hundred sixty and nine
  66. years: and he died.
  67. 28. And Lamech lived an hundred eighty and two years, and begat a
  68. son:
  69. 29. And he called his name Noah, saying, This same shall comfort us
  70. concerning our work and toil of our hands, because of the ground
  71. which the LORD hath cursed.
  72. 30. And Lamech lived after he begat Noah five hundred ninety and
  73. five years, and begat sons and daughters:
  74. 31. And all the days of Lamech were seven hundred seventy and seven
  75. years: and he died.
  76. 32. And Noah was five hundred years old: and Noah begat Shem, Ham,
  77. and Japheth.
  78. And buffers begat buffers, and links begat links, and buffer pools
  79. begat links to chains of buffer pools containing buffers, and lo the
  80. buffers and links and pools of buffers and pools of links to chains of
  81. pools of buffers were fruitful and they multiplied and the Operating
  82. System looked down upon them and said that it was Good.
  83. INTRODUCTION
  84. ============
  85. BGET is a comprehensive memory allocation package which is easily
  86. configured to the needs of an application. BGET is efficient in
  87. both the time needed to allocate and release buffers and in the
  88. memory overhead required for buffer pool management. It
  89. automatically consolidates contiguous space to minimise
  90. fragmentation. BGET is configured by compile-time definitions,
  91. Major options include:
  92. * A built-in test program to exercise BGET and
  93. demonstrate how the various functions are used.
  94. * Allocation by either the "first fit" or "best fit"
  95. method.
  96. * Wiping buffers at release time to catch code which
  97. references previously released storage.
  98. * Built-in routines to dump individual buffers or the
  99. entire buffer pool.
  100. * Retrieval of allocation and pool size statistics.
  101. * Quantisation of buffer sizes to a power of two to
  102. satisfy hardware alignment constraints.
  103. * Automatic pool compaction, growth, and shrinkage by
  104. means of call-backs to user defined functions.
  105. Applications of BGET can range from storage management in
  106. ROM-based embedded programs to providing the framework upon which
  107. a multitasking system incorporating garbage collection is
  108. constructed. BGET incorporates extensive internal consistency
  109. checking using the <assert.h> mechanism; all these checks can be
  110. turned off by compiling with NDEBUG defined, yielding a version of
  111. BGET with minimal size and maximum speed.
  112. The basic algorithm underlying BGET has withstood the test of
  113. time; more than 25 years have passed since the first
  114. implementation of this code. And yet, it is substantially more
  115. efficient than the native allocation schemes of many operating
  116. systems: the Macintosh and Microsoft Windows to name two, on which
  117. programs have obtained substantial speed-ups by layering BGET as
  118. an application level memory manager atop the underlying system's.
  119. BGET has been implemented on the largest mainframes and the lowest
  120. of microprocessors. It has served as the core for multitasking
  121. operating systems, multi-thread applications, embedded software in
  122. data network switching processors, and a host of C programs. And
  123. while it has accreted flexibility and additional options over the
  124. years, it remains fast, memory efficient, portable, and easy to
  125. integrate into your program.
  126. BGET IMPLEMENTATION ASSUMPTIONS
  127. ===============================
  128. BGET is written in as portable a dialect of C as possible. The
  129. only fundamental assumption about the underlying hardware
  130. architecture is that memory is allocated is a linear array which
  131. can be addressed as a vector of C "char" objects. On segmented
  132. address space architectures, this generally means that BGET should
  133. be used to allocate storage within a single segment (although some
  134. compilers simulate linear address spaces on segmented
  135. architectures). On segmented architectures, then, BGET buffer
  136. pools may not be larger than a segment, but since BGET allows any
  137. number of separate buffer pools, there is no limit on the total
  138. storage which can be managed, only on the largest individual
  139. object which can be allocated. Machines with a linear address
  140. architecture, such as the VAX, 680x0, Sparc, MIPS, or the Intel
  141. 80386 and above in native mode, may use BGET without restriction.
  142. GETTING STARTED WITH BGET
  143. =========================
  144. Although BGET can be configured in a multitude of fashions, there
  145. are three basic ways of working with BGET. The functions
  146. mentioned below are documented in the following section. Please
  147. excuse the forward references which are made in the interest of
  148. providing a roadmap to guide you to the BGET functions you're
  149. likely to need.
  150. Embedded Applications
  151. ---------------------
  152. Embedded applications typically have a fixed area of memory
  153. dedicated to buffer allocation (often in a separate RAM address
  154. space distinct from the ROM that contains the executable code).
  155. To use BGET in such an environment, simply call bpool() with the
  156. start address and length of the buffer pool area in RAM, then
  157. allocate buffers with bget() and release them with brel().
  158. Embedded applications with very limited RAM but abundant CPU speed
  159. may benefit by configuring BGET for BestFit allocation (which is
  160. usually not worth it in other environments).
  161. Malloc() Emulation
  162. ------------------
  163. If the C library malloc() function is too slow, not present in
  164. your development environment (for example, an a native Windows or
  165. Macintosh program), or otherwise unsuitable, you can replace it
  166. with BGET. Initially define a buffer pool of an appropriate size
  167. with bpool()--usually obtained by making a call to the operating
  168. system's low-level memory allocator. Then allocate buffers with
  169. bget(), bgetz(), and bgetr() (the last two permit the allocation
  170. of buffers initialised to zero and [inefficient] re-allocation of
  171. existing buffers for compatibility with C library functions).
  172. Release buffers by calling brel(). If a buffer allocation request
  173. fails, obtain more storage from the underlying operating system,
  174. add it to the buffer pool by another call to bpool(), and continue
  175. execution.
  176. Automatic Storage Management
  177. ----------------------------
  178. You can use BGET as your application's native memory manager and
  179. implement automatic storage pool expansion, contraction, and
  180. optionally application-specific memory compaction by compiling
  181. BGET with the BECtl variable defined, then calling bectl() and
  182. supplying functions for storage compaction, acquisition, and
  183. release, as well as a standard pool expansion increment. All of
  184. these functions are optional (although it doesn't make much sense
  185. to provide a release function without an acquisition function,
  186. does it?). Once the call-back functions have been defined with
  187. bectl(), you simply use bget() and brel() to allocate and release
  188. storage as before. You can supply an initial buffer pool with
  189. bpool() or rely on automatic allocation to acquire the entire
  190. pool. When a call on bget() cannot be satisfied, BGET first
  191. checks if a compaction function has been supplied. If so, it is
  192. called (with the space required to satisfy the allocation request
  193. and a sequence number to allow the compaction routine to be called
  194. successively without looping). If the compaction function is able
  195. to free any storage (it needn't know whether the storage it freed
  196. was adequate) it should return a nonzero value, whereupon BGET
  197. will retry the allocation request and, if it fails again, call the
  198. compaction function again with the next-higher sequence number.
  199. If the compaction function returns zero, indicating failure to
  200. free space, or no compaction function is defined, BGET next tests
  201. whether a non-NULL allocation function was supplied to bectl().
  202. If so, that function is called with an argument indicating how
  203. many bytes of additional space are required. This will be the
  204. standard pool expansion increment supplied in the call to bectl()
  205. unless the original bget() call requested a buffer larger than
  206. this; buffers larger than the standard pool block can be managed
  207. "off the books" by BGET in this mode. If the allocation function
  208. succeeds in obtaining the storage, it returns a pointer to the new
  209. block and BGET expands the buffer pool; if it fails, the
  210. allocation request fails and returns NULL to the caller. If a
  211. non-NULL release function is supplied, expansion blocks which
  212. become totally empty are released to the global free pool by
  213. passing their addresses to the release function.
  214. Equipped with appropriate allocation, release, and compaction
  215. functions, BGET can be used as part of very sophisticated memory
  216. management strategies, including garbage collection. (Note,
  217. however, that BGET is *not* a garbage collector by itself, and
  218. that developing such a system requires much additional logic and
  219. careful design of the application's memory allocation strategy.)
  220. BGET FUNCTION DESCRIPTIONS
  221. ==========================
  222. Functions implemented in this file (some are enabled by certain of
  223. the optional settings below):
  224. void bpool(void *buffer, bufsize len);
  225. Create a buffer pool of <len> bytes, using the storage starting at
  226. <buffer>. You can call bpool() subsequently to contribute
  227. additional storage to the overall buffer pool.
  228. void *bget(bufsize size);
  229. Allocate a buffer of <size> bytes. The address of the buffer is
  230. returned, or NULL if insufficient memory was available to allocate
  231. the buffer.
  232. void *bgetz(bufsize size);
  233. Allocate a buffer of <size> bytes and clear it to all zeroes. The
  234. address of the buffer is returned, or NULL if insufficient memory
  235. was available to allocate the buffer.
  236. void *bgetr(void *buffer, bufsize newsize);
  237. Reallocate a buffer previously allocated by bget(), changing its
  238. size to <newsize> and preserving all existing data. NULL is
  239. returned if insufficient memory is available to reallocate the
  240. buffer, in which case the original buffer remains intact.
  241. void brel(void *buf);
  242. Return the buffer <buf>, previously allocated by bget(), to the
  243. free space pool.
  244. void bectl(int (*compact)(bufsize sizereq, int sequence),
  245. void *(*acquire)(bufsize size),
  246. void (*release)(void *buf),
  247. bufsize pool_incr);
  248. Expansion control: specify functions through which the package may
  249. compact storage (or take other appropriate action) when an
  250. allocation request fails, and optionally automatically acquire
  251. storage for expansion blocks when necessary, and release such
  252. blocks when they become empty. If <compact> is non-NULL, whenever
  253. a buffer allocation request fails, the <compact> function will be
  254. called with arguments specifying the number of bytes (total buffer
  255. size, including header overhead) required to satisfy the
  256. allocation request, and a sequence number indicating the number of
  257. consecutive calls on <compact> attempting to satisfy this
  258. allocation request. The sequence number is 1 for the first call
  259. on <compact> for a given allocation request, and increments on
  260. subsequent calls, permitting the <compact> function to take
  261. increasingly dire measures in an attempt to free up storage. If
  262. the <compact> function returns a nonzero value, the allocation
  263. attempt is re-tried. If <compact> returns 0 (as it must if it
  264. isn't able to release any space or add storage to the buffer
  265. pool), the allocation request fails, which can trigger automatic
  266. pool expansion if the <acquire> argument is non-NULL. At the time
  267. the <compact> function is called, the state of the buffer
  268. allocator is identical to that at the moment the allocation
  269. request was made; consequently, the <compact> function may call
  270. brel(), bpool(), bstats(), and/or directly manipulate the buffer
  271. pool in any manner which would be valid were the application in
  272. control. This does not, however, relieve the <compact> function
  273. of the need to ensure that whatever actions it takes do not change
  274. things underneath the application that made the allocation
  275. request. For example, a <compact> function that released a buffer
  276. in the process of being reallocated with bgetr() would lead to
  277. disaster. Implementing a safe and effective <compact> mechanism
  278. requires careful design of an application's memory architecture,
  279. and cannot generally be easily retrofitted into existing code.
  280. If <acquire> is non-NULL, that function will be called whenever an
  281. allocation request fails. If the <acquire> function succeeds in
  282. allocating the requested space and returns a pointer to the new
  283. area, allocation will proceed using the expanded buffer pool. If
  284. <acquire> cannot obtain the requested space, it should return NULL
  285. and the entire allocation process will fail. <pool_incr>
  286. specifies the normal expansion block size. Providing an <acquire>
  287. function will cause subsequent bget() requests for buffers too
  288. large to be managed in the linked-block scheme (in other words,
  289. larger than <pool_incr> minus the buffer overhead) to be satisfied
  290. directly by calls to the <acquire> function. Automatic release of
  291. empty pool blocks will occur only if all pool blocks in the system
  292. are the size given by <pool_incr>.
  293. void bstats(bufsize *curalloc, bufsize *totfree,
  294. bufsize *maxfree, unsigned long *nget, unsigned long *nrel);
  295. The amount of space currently allocated is stored into the
  296. variable pointed to by <curalloc>. The total free space (sum of
  297. all free blocks in the pool) is stored into the variable pointed
  298. to by <totfree>, and the size of the largest single block in the
  299. free space pool is stored into the variable pointed to by
  300. <maxfree>. The variables pointed to by <nget> and <nrel> are
  301. filled, respectively, with the number of successful (non-NULL
  302. return) bget() calls and the number of brel() calls.
  303. void bstatse(bufsize *pool_incr, unsigned long *npool,
  304. unsigned long *npget, unsigned long *nprel,
  305. unsigned long *ndget, unsigned long *ndrel);
  306. Extended statistics: The expansion block size will be stored into
  307. the variable pointed to by <pool_incr>, or the negative thereof if
  308. automatic expansion block releases are disabled. The number of
  309. currently active pool blocks will be stored into the variable
  310. pointed to by <npool>. The variables pointed to by <npget> and
  311. <nprel> will be filled with, respectively, the number of expansion
  312. block acquisitions and releases which have occurred. The
  313. variables pointed to by <ndget> and <ndrel> will be filled with
  314. the number of bget() and brel() calls, respectively, managed
  315. through blocks directly allocated by the acquisition and release
  316. functions.
  317. void bufdump(void *buf);
  318. The buffer pointed to by <buf> is dumped on standard output.
  319. void bpoold(void *pool, int dumpalloc, int dumpfree);
  320. All buffers in the buffer pool <pool>, previously initialised by a
  321. call on bpool(), are listed in ascending memory address order. If
  322. <dumpalloc> is nonzero, the contents of allocated buffers are
  323. dumped; if <dumpfree> is nonzero, the contents of free blocks are
  324. dumped.
  325. int bpoolv(void *pool);
  326. The named buffer pool, previously initialised by a call on
  327. bpool(), is validated for bad pointers, overwritten data, etc. If
  328. compiled with NDEBUG not defined, any error generates an assertion
  329. failure. Otherwise 1 is returned if the pool is valid, 0 if an
  330. error is found.
  331. BGET CONFIGURATION
  332. ==================
  333. */
  334. #if 0
  335. #define TestProg 20000 /* Generate built-in test program
  336. if defined. The value specifies
  337. how many buffer allocation attempts
  338. the test program should make. */
  339. #endif
  340. /* Declare the interface, including the requested buffer size type,
  341. bufsize. */
  342. #include "luat_bget.h"
  343. void luat_bget_init(luat_bget_t* bg) {
  344. memset(bg, 0 , sizeof(luat_bget_t));
  345. //bg->freelist.bh.prevfree = 0;
  346. //bg->freelist.bh.bsize = 0;
  347. bg->freelist.ql.blink = &bg->freelist;
  348. bg->freelist.ql.flink = &bg->freelist;
  349. }
  350. /* Minimum allocation quantum: */
  351. #define QLSize (sizeof(struct qlinks))
  352. #define SizeQ ((SizeQuant > QLSize) ? SizeQuant : QLSize)
  353. #define V (void) /* To denote unwanted returned values */
  354. /* End sentinel: value placed in bsize field of dummy block delimiting
  355. end of pool block. The most negative number which will fit in a
  356. bufsize, defined in a way that the compiler will accept. */
  357. #define ESent ((bufsize) (-(((1L << (sizeof(bufsize) * 8 - 2)) - 1) * 2) - 2))
  358. #define _assert_(x)
  359. /* BGET -- Allocate a buffer. */
  360. void *luat_bget(luat_bget_t* bg, bufsize requested_size)
  361. {
  362. bufsize size = requested_size;
  363. struct bfhead *b;
  364. #ifdef BestFit
  365. struct bfhead *best;
  366. #endif
  367. void *buf;
  368. #ifdef BECtl
  369. int compactseq = 0;
  370. #endif
  371. _assert_(size >= 0);
  372. if (!size)
  373. {
  374. return NULL;
  375. }
  376. if (size < (bufsize)SizeQ) { /* Need at least room for the */
  377. size = SizeQ; /* queue links. */
  378. }
  379. #ifdef SizeQuant
  380. #if SizeQuant > 1
  381. size = (size + (SizeQuant - 1)) & (~(SizeQuant - 1));
  382. #endif
  383. #endif
  384. size += sizeof(struct bhead); /* Add overhead in allocated buffer
  385. to size required. */
  386. #ifdef BECtl
  387. /* If a compact function was provided in the call to bectl(), wrap
  388. a loop around the allocation process to allow compaction to
  389. intervene in case we don't find a suitable buffer in the chain. */
  390. while (1) {
  391. #endif
  392. b = bg->freelist.ql.flink;
  393. #ifdef BestFit
  394. best = &bg->freelist;
  395. #endif
  396. /* Scan the free list searching for the first buffer big enough
  397. to hold the requested size buffer. */
  398. #ifdef BestFit
  399. while (b != &bg->freelist) {
  400. if (b->bh.bsize >= size) {
  401. if ((best == &bg->freelist) || (b->bh.bsize < best->bh.bsize)) {
  402. best = b;
  403. }
  404. }
  405. b = b->ql.flink; /* Link to next buffer */
  406. }
  407. b = best;
  408. #endif /* BestFit */
  409. while (b != &bg->freelist) {
  410. if ((bufsize) b->bh.bsize >= size) {
  411. /* Buffer is big enough to satisfy the request. Allocate it
  412. to the caller. We must decide whether the buffer is large
  413. enough to split into the part given to the caller and a
  414. free buffer that remains on the free list, or whether the
  415. entire buffer should be removed from the free list and
  416. given to the caller in its entirety. We only split the
  417. buffer if enough room remains for a header plus the minimum
  418. quantum of allocation. */
  419. if ((b->bh.bsize - size) > (bufsize)(SizeQ + (sizeof(struct bhead)))) {
  420. struct bhead *ba, *bn;
  421. ba = BH(((char *) b) + (b->bh.bsize - size));
  422. bn = BH(((char *) ba) + size);
  423. _assert_(bn->prevfree == b->bh.bsize);
  424. /* Subtract size from length of free block. */
  425. b->bh.bsize -= size;
  426. /* Link allocated buffer to the previous free buffer. */
  427. ba->prevfree = b->bh.bsize;
  428. /* Plug negative size into user buffer. */
  429. ba->bsize = -(bufsize) size;
  430. /* Mark buffer after this one not preceded by free block. */
  431. bn->prevfree = 0;
  432. #ifdef BufStats
  433. bg->totalloc += size;
  434. if (bg->totalloc > bg->maxalloc)
  435. {
  436. bg->maxalloc = bg->totalloc;
  437. }
  438. bg->numget++; /* Increment number of bget() calls */
  439. #endif
  440. buf = (void *) ((((char *) ba) + sizeof(struct bhead)));
  441. return buf;
  442. } else {
  443. struct bhead *ba;
  444. ba = BH(((char *) b) + b->bh.bsize);
  445. _assert_(ba->prevfree == b->bh.bsize);
  446. /* The buffer isn't big enough to split. Give the whole
  447. shebang to the caller and remove it from the free list. */
  448. _assert_(b->ql.blink->ql.flink == b);
  449. _assert_(b->ql.flink->ql.blink == b);
  450. b->ql.blink->ql.flink = b->ql.flink;
  451. b->ql.flink->ql.blink = b->ql.blink;
  452. #ifdef BufStats
  453. bg->totalloc += b->bh.bsize;
  454. if (bg->totalloc > bg->maxalloc)
  455. {
  456. bg->maxalloc = bg->totalloc;
  457. }
  458. bg->numget++; /* Increment number of bget() calls */
  459. #endif
  460. /* Negate size to mark buffer allocated. */
  461. b->bh.bsize = -(b->bh.bsize);
  462. /* Zero the back pointer in the next buffer in memory
  463. to indicate that this buffer is allocated. */
  464. ba->prevfree = 0;
  465. /* Give user buffer starting at queue links. */
  466. buf = (void *) &(b->ql);
  467. return buf;
  468. }
  469. }
  470. b = b->ql.flink; /* Link to next buffer */
  471. }
  472. return NULL;
  473. }
  474. /* BGETZ -- Allocate a buffer and clear its contents to zero. We clear
  475. the entire contents of the buffer to zero, not just the
  476. region requested by the caller. */
  477. void *luat_bgetz(luat_bget_t* bg, bufsize size)
  478. {
  479. char *buf = (char *) luat_bget(bg, size);
  480. if (buf != NULL) {
  481. struct bhead *b;
  482. bufsize rsize;
  483. b = BH(buf - sizeof(struct bhead));
  484. rsize = -(b->bsize);
  485. if (rsize == 0) {
  486. struct bdhead *bd;
  487. bd = BDH(buf - sizeof(struct bdhead));
  488. rsize = bd->tsize - sizeof(struct bdhead);
  489. } else {
  490. rsize -= sizeof(struct bhead);
  491. }
  492. _assert_(rsize >= size);
  493. memset(buf, 0, (MemSize) rsize);
  494. }
  495. return ((void *) buf);
  496. }
  497. /* BGETR -- Reallocate a buffer. This is a minimal implementation,
  498. simply in terms of brel() and bget(). It could be
  499. enhanced to allow the buffer to grow into adjacent free
  500. blocks and to avoid moving data unnecessarily. */
  501. void *luat_bgetr(luat_bget_t* bg, void *buf, bufsize size)
  502. {
  503. void *nbuf;
  504. bufsize osize; /* Old size of buffer */
  505. struct bhead *b;
  506. if ((nbuf = luat_bget(bg, size)) == NULL) { /* Acquire new buffer */
  507. return NULL;
  508. }
  509. if (buf == NULL) {
  510. return nbuf;
  511. }
  512. b = BH(((char *) buf) - sizeof(struct bhead));
  513. osize = -b->bsize;
  514. osize -= sizeof(struct bhead);
  515. _assert_(osize > 0);
  516. V memcpy((char *) nbuf, (char *) buf, /* Copy the data */
  517. (MemSize) ((size < osize) ? size : osize));
  518. luat_brel(bg, buf);
  519. return nbuf;
  520. }
  521. /* BREL -- Release a buffer. */
  522. void luat_brel(luat_bget_t* bg, void *buf)
  523. {
  524. struct bfhead *b, *bn;
  525. b = BFH(((char *) buf) - sizeof(struct bhead));
  526. #ifdef BufStats
  527. bg->numrel++; /* Increment number of brel() calls */
  528. #endif
  529. _assert_(buf != NULL);
  530. if (!buf)
  531. {
  532. return;
  533. }
  534. /* Buffer size must be negative, indicating that the buffer is
  535. allocated. */
  536. if (b->bh.bsize >= 0) {
  537. bn = NULL;
  538. }
  539. _assert_(b->bh.bsize < 0);
  540. /* Back pointer in next buffer must be zero, indicating the
  541. same thing: */
  542. _assert_(BH((char *) b - b->bh.bsize)->prevfree == 0);
  543. #ifdef BufStats
  544. bg->totalloc += b->bh.bsize;
  545. _assert_(bg->totalloc >= 0);
  546. #endif
  547. /* If the back link is nonzero, the previous buffer is free. */
  548. if (b->bh.prevfree != 0) {
  549. /* The previous buffer is free. Consolidate this buffer with it
  550. by adding the length of this buffer to the previous free
  551. buffer. Note that we subtract the size in the buffer being
  552. released, since it's negative to indicate that the buffer is
  553. allocated. */
  554. register bufsize size = b->bh.bsize;
  555. /* Make the previous buffer the one we're working on. */
  556. _assert_(BH((char *) b - b->bh.prevfree)->bsize == b->bh.prevfree);
  557. b = BFH(((char *) b) - b->bh.prevfree);
  558. b->bh.bsize -= size;
  559. } else {
  560. /* The previous buffer isn't allocated. Insert this buffer
  561. on the free list as an isolated free block. */
  562. _assert_(bg->freelist.ql.blink->ql.flink == &bg->freelist);
  563. _assert_(bg->freelist.ql.flink->ql.blink == &bg->freelist);
  564. b->ql.flink = &bg->freelist;
  565. b->ql.blink = bg->freelist.ql.blink;
  566. bg->freelist.ql.blink = b;
  567. b->ql.blink->ql.flink = b;
  568. b->bh.bsize = -b->bh.bsize;
  569. }
  570. /* Now we look at the next buffer in memory, located by advancing from
  571. the start of this buffer by its size, to see if that buffer is
  572. free. If it is, we combine this buffer with the next one in
  573. memory, dechaining the second buffer from the free list. */
  574. bn = BFH(((char *) b) + b->bh.bsize);
  575. if (bn->bh.bsize > 0) {
  576. /* The buffer is free. Remove it from the free list and add
  577. its size to that of our buffer. */
  578. _assert_(BH((char *) bn + bn->bh.bsize)->prevfree == bn->bh.bsize);
  579. _assert_(bn->ql.blink->ql.flink == bn);
  580. _assert_(bn->ql.flink->ql.blink == bn);
  581. bn->ql.blink->ql.flink = bn->ql.flink;
  582. bn->ql.flink->ql.blink = bn->ql.blink;
  583. b->bh.bsize += bn->bh.bsize;
  584. /* Finally, advance to the buffer that follows the newly
  585. consolidated free block. We must set its backpointer to the
  586. head of the consolidated free block. We know the next block
  587. must be an allocated block because the process of recombination
  588. guarantees that two free blocks will never be contiguous in
  589. memory. */
  590. bn = BFH(((char *) b) + b->bh.bsize);
  591. }
  592. #ifdef FreeWipe
  593. V memset(((char *) b) + sizeof(struct bfhead), 0x55,
  594. (MemSize) (b->bh.bsize - sizeof(struct bfhead)));
  595. #endif
  596. _assert_(bn->bh.bsize < 0);
  597. /* The next buffer is allocated. Set the backpointer in it to point
  598. to this buffer; the previous free buffer in memory. */
  599. bn->bh.prevfree = b->bh.bsize;
  600. }
  601. /* BPOOL -- Add a region of memory to the buffer pool. */
  602. void luat_bpool(luat_bget_t* bg, void *buf, bufsize len)
  603. {
  604. struct bfhead *b = BFH(buf);
  605. struct bhead *bn;
  606. #ifdef SizeQuant
  607. len &= ~(SizeQuant - 1);
  608. #endif
  609. /* Since the block is initially occupied by a single free buffer,
  610. it had better not be (much) larger than the largest buffer
  611. whose size we can store in bhead.bsize. */
  612. _assert_(len - sizeof(struct bhead) <= -((bufsize) ESent + 1));
  613. /* Clear the backpointer at the start of the block to indicate that
  614. there is no free block prior to this one. That blocks
  615. recombination when the first block in memory is released. */
  616. b->bh.prevfree = 0;
  617. /* Chain the new block to the free list. */
  618. _assert_(bg->freelist.ql.blink->ql.flink == &bg->freelist);
  619. _assert_(bg->freelist.ql.flink->ql.blink == &bg->freelist);
  620. b->ql.flink = &bg->freelist;
  621. b->ql.blink = bg->freelist.ql.blink;
  622. bg->freelist.ql.blink = b;
  623. b->ql.blink->ql.flink = b;
  624. /* Create a dummy allocated buffer at the end of the pool. This dummy
  625. buffer is seen when a buffer at the end of the pool is released and
  626. blocks recombination of the last buffer with the dummy buffer at
  627. the end. The length in the dummy buffer is set to the largest
  628. negative number to denote the end of the pool for diagnostic
  629. routines (this specific value is not counted on by the actual
  630. allocation and release functions). */
  631. len -= sizeof(struct bhead);
  632. b->bh.bsize = (bufsize) len;
  633. #ifdef FreeWipe
  634. V memset(((char *) b) + sizeof(struct bfhead), 0x55,
  635. (MemSize) (len - sizeof(struct bfhead)));
  636. #endif
  637. bn = BH(((char *) b) + len);
  638. bn->prevfree = (bufsize) len;
  639. /* Definition of ESent assumes two's complement! */
  640. _assert_((~0) == -1);
  641. bn->bsize = ESent;
  642. }
  643. #ifdef BufStats
  644. /* BSTATS -- Return buffer allocation free space statistics. */
  645. void luat_bstats(luat_bget_t* bg, bufsize *curalloc, bufsize *totfree, bufsize *maxfree, unsigned long *nget, unsigned long *nrel)
  646. {
  647. struct bfhead *b = bg->freelist.ql.flink;
  648. *nget = bg->numget;
  649. *nrel = bg->numrel;
  650. *curalloc = bg->totalloc;
  651. *totfree = 0;
  652. *maxfree = -1;
  653. while (b != &bg->freelist) {
  654. _assert_(b->bh.bsize > 0);
  655. *totfree += b->bh.bsize;
  656. if (b->bh.bsize > *maxfree) {
  657. *maxfree = b->bh.bsize;
  658. }
  659. b = b->ql.flink; /* Link to next buffer */
  660. }
  661. }
  662. bufsize luat_bstatsmaxget(luat_bget_t* bg)
  663. {
  664. return bg->maxalloc;
  665. }
  666. #endif /* BufStats */