bget.c 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601
  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 minimize
  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, long *nget, 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, long *npool,
  304. long *npget, long *nprel,
  305. long *ndget, 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. #define SizeQuant 4 /* Buffer allocation size quantum:
  341. all buffers allocated are a
  342. multiple of this size. This
  343. MUST be a power of two. */
  344. #if 0
  345. #define BufDump 1 /* Define this symbol to enable the
  346. bpoold() function which dumps the
  347. buffers in a buffer pool. */
  348. #define BufValid 1 /* Define this symbol to enable the
  349. bpoolv() function for validating
  350. a buffer pool. */
  351. #define DumpData 1 /* Define this symbol to enable the
  352. bufdump() function which allows
  353. dumping the contents of an allocated
  354. or free buffer. */
  355. #define BufStats 1 /* Define this symbol to enable the
  356. bstats() function which calculates
  357. the total free space in the buffer
  358. pool, the largest available
  359. buffer, and the total space
  360. currently allocated. */
  361. #define FreeWipe 1 /* Wipe free buffers to a guaranteed
  362. pattern of garbage to trip up
  363. miscreants who attempt to use
  364. pointers into released buffers. */
  365. #define BestFit 1 /* Use a best fit algorithm when
  366. searching for space for an
  367. allocation request. This uses
  368. memory more efficiently, but
  369. allocation will be much slower. */
  370. #endif
  371. #define BECtl 1 /* Define this symbol to enable the
  372. bectl() function for automatic
  373. pool space control. */
  374. #include <stdio.h>
  375. #ifdef lint
  376. #define NDEBUG /* Exits in asserts confuse lint */
  377. /* LINTLIBRARY */ /* Don't complain about def, no ref */
  378. extern char *sprintf(); /* Sun includes don't define sprintf */
  379. #endif
  380. #include <assert.h>
  381. #include <memory.h>
  382. #ifdef BufDump /* BufDump implies DumpData */
  383. #ifndef DumpData
  384. #define DumpData 1
  385. #endif
  386. #endif
  387. #ifdef DumpData
  388. #include <ctype.h>
  389. #endif
  390. /* Declare the interface, including the requested buffer size type,
  391. bufsize. */
  392. #include "bget.h"
  393. #define MemSize int /* Type for size arguments to memxxx()
  394. functions such as memcmp(). */
  395. /* Queue links */
  396. struct qlinks {
  397. struct bfhead *flink; /* Forward link */
  398. struct bfhead *blink; /* Backward link */
  399. };
  400. /* Header in allocated and free buffers */
  401. struct bhead {
  402. bufsize prevfree; /* Relative link back to previous
  403. free buffer in memory or 0 if
  404. previous buffer is allocated. */
  405. bufsize bsize; /* Buffer size: positive if free,
  406. negative if allocated. */
  407. };
  408. #define BH(p) ((struct bhead *) (p))
  409. /* Header in directly allocated buffers (by acqfcn) */
  410. struct bdhead {
  411. bufsize tsize; /* Total size, including overhead */
  412. struct bhead bh; /* Common header */
  413. };
  414. #define BDH(p) ((struct bdhead *) (p))
  415. /* Header in free buffers */
  416. struct bfhead {
  417. struct bhead bh; /* Common allocated/free header */
  418. struct qlinks ql; /* Links on free list */
  419. };
  420. #define BFH(p) ((struct bfhead *) (p))
  421. static struct bfhead freelist = { /* List of free buffers */
  422. {0, 0},
  423. {&freelist, &freelist}
  424. };
  425. #ifdef BufStats
  426. static bufsize totalloc = 0; /* Total space currently allocated */
  427. static long numget = 0, numrel = 0; /* Number of bget() and brel() calls */
  428. #ifdef BECtl
  429. static long numpblk = 0; /* Number of pool blocks */
  430. static long numpget = 0, numprel = 0; /* Number of block gets and rels */
  431. static long numdget = 0, numdrel = 0; /* Number of direct gets and rels */
  432. #endif /* BECtl */
  433. #endif /* BufStats */
  434. #ifdef BECtl
  435. /* Automatic expansion block management functions */
  436. static int (*compfcn) _((bufsize sizereq, int sequence)) = NULL;
  437. static void *(*acqfcn) _((bufsize size)) = NULL;
  438. static void (*relfcn) _((void *buf)) = NULL;
  439. static bufsize exp_incr = 0; /* Expansion block size */
  440. static bufsize pool_len = 0; /* 0: no bpool calls have been made
  441. * -1: not all pool blocks are
  442. * the same size
  443. * >0: (common) block size for all
  444. * bpool calls made so far
  445. */
  446. #endif
  447. /* Minimum allocation quantum: */
  448. #define QLSize (sizeof(struct qlinks))
  449. #define SizeQ ((SizeQuant > QLSize) ? SizeQuant : QLSize)
  450. #define V (void) /* To denote unwanted returned values */
  451. /* End sentinel: value placed in bsize field of dummy block delimiting
  452. end of pool block. The most negative number which will fit in a
  453. bufsize, defined in a way that the compiler will accept. */
  454. #define ESent ((bufsize) (-(((1L << (sizeof(bufsize) * 8 - 2)) - 1) * 2) - 2))
  455. /* BGET -- Allocate a buffer. */
  456. void *bget(requested_size)
  457. bufsize requested_size;
  458. {
  459. bufsize size = requested_size;
  460. struct bfhead *b;
  461. #ifdef BestFit
  462. struct bfhead *best;
  463. #endif
  464. void *buf;
  465. #ifdef BECtl
  466. int compactseq = 0;
  467. #endif
  468. assert(size > 0);
  469. if (size < (bufsize)SizeQ) { /* Need at least room for the */
  470. size = SizeQ; /* queue links. */
  471. }
  472. #ifdef SizeQuant
  473. #if SizeQuant > 1
  474. size = (size + (SizeQuant - 1)) & (~(SizeQuant - 1));
  475. #endif
  476. #endif
  477. size += sizeof(struct bhead); /* Add overhead in allocated buffer
  478. * to size required.
  479. */
  480. #ifdef BECtl
  481. /* If a compact function was provided in the call to bectl(), wrap
  482. * a loop around the allocation process to allow compaction to
  483. * intervene in case we don't find a suitable buffer in the chain.
  484. */
  485. while (1) {
  486. #endif
  487. b = freelist.ql.flink;
  488. #ifdef BestFit
  489. best = &freelist;
  490. #endif
  491. /* Scan the free list searching for the first buffer big enough
  492. to hold the requested size buffer. */
  493. #ifdef BestFit
  494. while (b != &freelist) {
  495. if (b->bh.bsize >= size) {
  496. if ((best == &freelist) || (b->bh.bsize < best->bh.bsize)) {
  497. best = b;
  498. }
  499. }
  500. b = b->ql.flink; /* Link to next buffer */
  501. }
  502. b = best;
  503. #endif /* BestFit */
  504. while (b != &freelist) {
  505. if ((bufsize) b->bh.bsize >= size) {
  506. /* Buffer is big enough to satisfy the request. Allocate it
  507. * to the caller. We must decide whether the buffer is large
  508. * enough to split into the part given to the caller and a
  509. * free buffer that remains on the free list, or whether the
  510. * entire buffer should be removed from the free list and
  511. * given to the caller in its entirety. We only split the
  512. * buffer if enough room remains for a header plus the minimum
  513. * quantum of allocation.
  514. */
  515. if ((b->bh.bsize - size) > (bufsize)(SizeQ + (sizeof(struct bhead)))) {
  516. struct bhead *ba, *bn;
  517. ba = BH(((char *) b) + (b->bh.bsize - size));
  518. bn = BH(((char *) ba) + size);
  519. assert(bn->prevfree == b->bh.bsize);
  520. /* Subtract size from length of free block. */
  521. b->bh.bsize -= size;
  522. /* Link allocated buffer to the previous free buffer. */
  523. ba->prevfree = b->bh.bsize;
  524. /* Plug negative size into user buffer. */
  525. ba->bsize = -(bufsize) size;
  526. /* Mark buffer after this one not preceded by free block. */
  527. bn->prevfree = 0;
  528. #ifdef BufStats
  529. totalloc += size;
  530. numget++; /* Increment number of bget() calls */
  531. #endif
  532. buf = (void *) ((((char *) ba) + sizeof(struct bhead)));
  533. return buf;
  534. } else {
  535. struct bhead *ba;
  536. ba = BH(((char *) b) + b->bh.bsize);
  537. assert(ba->prevfree == b->bh.bsize);
  538. /* The buffer isn't big enough to split. Give the whole
  539. * shebang to the caller and remove it from the free list.
  540. */
  541. assert(b->ql.blink->ql.flink == b);
  542. assert(b->ql.flink->ql.blink == b);
  543. b->ql.blink->ql.flink = b->ql.flink;
  544. b->ql.flink->ql.blink = b->ql.blink;
  545. #ifdef BufStats
  546. totalloc += b->bh.bsize;
  547. numget++; /* Increment number of bget() calls */
  548. #endif
  549. /* Negate size to mark buffer allocated. */
  550. b->bh.bsize = -(b->bh.bsize);
  551. /* Zero the back pointer in the next buffer in memory
  552. * to indicate that this buffer is allocated.
  553. */
  554. ba->prevfree = 0;
  555. /* Give user buffer starting at queue links. */
  556. buf = (void *) &(b->ql);
  557. return buf;
  558. }
  559. }
  560. b = b->ql.flink; /* Link to next buffer */
  561. }
  562. #ifdef BECtl
  563. /* We failed to find a buffer. If there's a compact function
  564. * defined, notify it of the size requested. If it returns
  565. * TRUE, try the allocation again.
  566. */
  567. if ((compfcn == NULL) || (!(*compfcn)(size, ++compactseq))) {
  568. break;
  569. }
  570. }
  571. /* No buffer available with requested size free. */
  572. /* Don't give up yet -- look in the reserve supply. */
  573. if (acqfcn != NULL) {
  574. if (size > (bufsize)(exp_incr - sizeof(struct bhead))) {
  575. /* Request is too large to fit in a single expansion
  576. * block. Try to satisy it by a direct buffer acquisition.
  577. */
  578. struct bdhead *bdh;
  579. size += sizeof(struct bdhead) - sizeof(struct bhead);
  580. if ((bdh = BDH((*acqfcn)((bufsize) size))) != NULL) {
  581. /* Mark the buffer special by setting the size field
  582. * of its header to zero.
  583. */
  584. bdh->bh.bsize = 0;
  585. bdh->bh.prevfree = 0;
  586. bdh->tsize = size;
  587. #ifdef BufStats
  588. totalloc += size;
  589. numget++; /* Increment number of bget() calls */
  590. numdget++; /* Direct bget() call count */
  591. #endif
  592. buf = (void *) (bdh + 1);
  593. return buf;
  594. }
  595. } else {
  596. /* Try to obtain a new expansion block */
  597. void *newpool;
  598. if ((newpool = (*acqfcn)((bufsize) exp_incr)) != NULL) {
  599. bpool(newpool, exp_incr);
  600. buf = bget(requested_size); /* This can't, I say, can't
  601. * get into a loop.
  602. */
  603. return buf;
  604. }
  605. }
  606. }
  607. /* Still no buffer available */
  608. #endif /* BECtl */
  609. return NULL;
  610. }
  611. /* BGETZ -- Allocate a buffer and clear its contents to zero. We clear
  612. the entire contents of the buffer to zero, not just the
  613. region requested by the caller. */
  614. void *bgetz(size)
  615. bufsize size;
  616. {
  617. char *buf = (char *) bget(size);
  618. if (buf != NULL) {
  619. struct bhead *b;
  620. bufsize rsize;
  621. b = BH(buf - sizeof(struct bhead));
  622. rsize = -(b->bsize);
  623. if (rsize == 0) {
  624. struct bdhead *bd;
  625. bd = BDH(buf - sizeof(struct bdhead));
  626. rsize = bd->tsize - sizeof(struct bdhead);
  627. } else {
  628. rsize -= sizeof(struct bhead);
  629. }
  630. assert(rsize >= size);
  631. V memset(buf, 0, (MemSize) rsize);
  632. }
  633. return ((void *) buf);
  634. }
  635. /* BGETR -- Reallocate a buffer. This is a minimal implementation,
  636. simply in terms of brel() and bget(). It could be
  637. enhanced to allow the buffer to grow into adjacent free
  638. blocks and to avoid moving data unnecessarily. */
  639. void *bgetr(buf, size)
  640. void *buf;
  641. bufsize size;
  642. {
  643. void *nbuf;
  644. bufsize osize; /* Old size of buffer */
  645. struct bhead *b;
  646. if ((nbuf = bget(size)) == NULL) { /* Acquire new buffer */
  647. return NULL;
  648. }
  649. if (buf == NULL) {
  650. return nbuf;
  651. }
  652. b = BH(((char *) buf) - sizeof(struct bhead));
  653. osize = -b->bsize;
  654. #ifdef BECtl
  655. if (osize == 0) {
  656. /* Buffer acquired directly through acqfcn. */
  657. struct bdhead *bd;
  658. bd = BDH(((char *) buf) - sizeof(struct bdhead));
  659. osize = bd->tsize - sizeof(struct bdhead);
  660. } else
  661. #endif
  662. osize -= sizeof(struct bhead);
  663. assert(osize > 0);
  664. V memcpy((char *) nbuf, (char *) buf, /* Copy the data */
  665. (MemSize) ((size < osize) ? size : osize));
  666. brel(buf);
  667. return nbuf;
  668. }
  669. /* BREL -- Release a buffer. */
  670. void brel(buf)
  671. void *buf;
  672. {
  673. struct bfhead *b, *bn;
  674. assert(buf != NULL);
  675. b = BFH(((char *) buf) - sizeof(struct bhead));
  676. #ifdef BufStats
  677. numrel++; /* Increment number of brel() calls */
  678. #endif
  679. #ifdef BECtl
  680. if (b->bh.bsize == 0) { /* Directly-acquired buffer? */
  681. struct bdhead *bdh;
  682. bdh = BDH(((char *) buf) - sizeof(struct bdhead));
  683. assert(b->bh.prevfree == 0);
  684. #ifdef BufStats
  685. totalloc -= bdh->tsize;
  686. assert(totalloc >= 0);
  687. numdrel++; /* Number of direct releases */
  688. #endif /* BufStats */
  689. #ifdef FreeWipe
  690. V memset((char *) buf, 0x55,
  691. (MemSize) (bdh->tsize - sizeof(struct bdhead)));
  692. #endif /* FreeWipe */
  693. assert(relfcn != NULL);
  694. (*relfcn)((void *) bdh); /* Release it directly. */
  695. return;
  696. }
  697. #endif /* BECtl */
  698. /* Buffer size must be negative, indicating that the buffer is
  699. allocated. */
  700. if (b->bh.bsize >= 0) {
  701. bn = NULL;
  702. }
  703. assert(b->bh.bsize < 0);
  704. /* Back pointer in next buffer must be zero, indicating the
  705. same thing: */
  706. assert(BH((char *) b - b->bh.bsize)->prevfree == 0);
  707. #ifdef BufStats
  708. totalloc += b->bh.bsize;
  709. assert(totalloc >= 0);
  710. #endif
  711. /* If the back link is nonzero, the previous buffer is free. */
  712. if (b->bh.prevfree != 0) {
  713. /* The previous buffer is free. Consolidate this buffer with it
  714. by adding the length of this buffer to the previous free
  715. buffer. Note that we subtract the size in the buffer being
  716. released, since it's negative to indicate that the buffer is
  717. allocated. */
  718. register bufsize size = b->bh.bsize;
  719. /* Make the previous buffer the one we're working on. */
  720. assert(BH((char *) b - b->bh.prevfree)->bsize == b->bh.prevfree);
  721. b = BFH(((char *) b) - b->bh.prevfree);
  722. b->bh.bsize -= size;
  723. } else {
  724. /* The previous buffer isn't allocated. Insert this buffer
  725. on the free list as an isolated free block. */
  726. assert(freelist.ql.blink->ql.flink == &freelist);
  727. assert(freelist.ql.flink->ql.blink == &freelist);
  728. b->ql.flink = &freelist;
  729. b->ql.blink = freelist.ql.blink;
  730. freelist.ql.blink = b;
  731. b->ql.blink->ql.flink = b;
  732. b->bh.bsize = -b->bh.bsize;
  733. }
  734. /* Now we look at the next buffer in memory, located by advancing from
  735. the start of this buffer by its size, to see if that buffer is
  736. free. If it is, we combine this buffer with the next one in
  737. memory, dechaining the second buffer from the free list. */
  738. bn = BFH(((char *) b) + b->bh.bsize);
  739. if (bn->bh.bsize > 0) {
  740. /* The buffer is free. Remove it from the free list and add
  741. its size to that of our buffer. */
  742. assert(BH((char *) bn + bn->bh.bsize)->prevfree == bn->bh.bsize);
  743. assert(bn->ql.blink->ql.flink == bn);
  744. assert(bn->ql.flink->ql.blink == bn);
  745. bn->ql.blink->ql.flink = bn->ql.flink;
  746. bn->ql.flink->ql.blink = bn->ql.blink;
  747. b->bh.bsize += bn->bh.bsize;
  748. /* Finally, advance to the buffer that follows the newly
  749. consolidated free block. We must set its backpointer to the
  750. head of the consolidated free block. We know the next block
  751. must be an allocated block because the process of recombination
  752. guarantees that two free blocks will never be contiguous in
  753. memory. */
  754. bn = BFH(((char *) b) + b->bh.bsize);
  755. }
  756. #ifdef FreeWipe
  757. V memset(((char *) b) + sizeof(struct bfhead), 0x55,
  758. (MemSize) (b->bh.bsize - sizeof(struct bfhead)));
  759. #endif
  760. assert(bn->bh.bsize < 0);
  761. /* The next buffer is allocated. Set the backpointer in it to point
  762. to this buffer; the previous free buffer in memory. */
  763. bn->bh.prevfree = b->bh.bsize;
  764. #ifdef BECtl
  765. /* If a block-release function is defined, and this free buffer
  766. constitutes the entire block, release it. Note that pool_len
  767. is defined in such a way that the test will fail unless all
  768. pool blocks are the same size. */
  769. if (relfcn != NULL &&
  770. b->bh.bsize == (bufsize)(pool_len - sizeof(struct bhead))) {
  771. assert(b->bh.prevfree == 0);
  772. assert(BH((char *) b + b->bh.bsize)->bsize == ESent);
  773. assert(BH((char *) b + b->bh.bsize)->prevfree == b->bh.bsize);
  774. /* Unlink the buffer from the free list */
  775. b->ql.blink->ql.flink = b->ql.flink;
  776. b->ql.flink->ql.blink = b->ql.blink;
  777. (*relfcn)(b);
  778. #ifdef BufStats
  779. numprel++; /* Nr of expansion block releases */
  780. numpblk--; /* Total number of blocks */
  781. assert(numpblk == numpget - numprel);
  782. #endif /* BufStats */
  783. }
  784. #endif /* BECtl */
  785. }
  786. #ifdef BECtl
  787. /* BECTL -- Establish automatic pool expansion control */
  788. void bectl(compact, acquire, release, pool_incr)
  789. int (*compact) _((bufsize sizereq, int sequence));
  790. void *(*acquire) _((bufsize size));
  791. void (*release) _((void *buf));
  792. bufsize pool_incr;
  793. {
  794. compfcn = compact;
  795. acqfcn = acquire;
  796. relfcn = release;
  797. exp_incr = pool_incr;
  798. }
  799. #endif
  800. /* BPOOL -- Add a region of memory to the buffer pool. */
  801. void bpool(buf, len)
  802. void *buf;
  803. bufsize len;
  804. {
  805. struct bfhead *b = BFH(buf);
  806. struct bhead *bn;
  807. #ifdef SizeQuant
  808. len &= ~(SizeQuant - 1);
  809. #endif
  810. #ifdef BECtl
  811. if (pool_len == 0) {
  812. pool_len = len;
  813. } else if (len != pool_len) {
  814. pool_len = -1;
  815. }
  816. #ifdef BufStats
  817. numpget++; /* Number of block acquisitions */
  818. numpblk++; /* Number of blocks total */
  819. assert(numpblk == numpget - numprel);
  820. #endif /* BufStats */
  821. #endif /* BECtl */
  822. /* Since the block is initially occupied by a single free buffer,
  823. it had better not be (much) larger than the largest buffer
  824. whose size we can store in bhead.bsize. */
  825. assert(len - sizeof(struct bhead) <= -((bufsize) ESent + 1));
  826. /* Clear the backpointer at the start of the block to indicate that
  827. there is no free block prior to this one. That blocks
  828. recombination when the first block in memory is released. */
  829. b->bh.prevfree = 0;
  830. /* Chain the new block to the free list. */
  831. assert(freelist.ql.blink->ql.flink == &freelist);
  832. assert(freelist.ql.flink->ql.blink == &freelist);
  833. b->ql.flink = &freelist;
  834. b->ql.blink = freelist.ql.blink;
  835. freelist.ql.blink = b;
  836. b->ql.blink->ql.flink = b;
  837. /* Create a dummy allocated buffer at the end of the pool. This dummy
  838. buffer is seen when a buffer at the end of the pool is released and
  839. blocks recombination of the last buffer with the dummy buffer at
  840. the end. The length in the dummy buffer is set to the largest
  841. negative number to denote the end of the pool for diagnostic
  842. routines (this specific value is not counted on by the actual
  843. allocation and release functions). */
  844. len -= sizeof(struct bhead);
  845. b->bh.bsize = (bufsize) len;
  846. #ifdef FreeWipe
  847. V memset(((char *) b) + sizeof(struct bfhead), 0x55,
  848. (MemSize) (len - sizeof(struct bfhead)));
  849. #endif
  850. bn = BH(((char *) b) + len);
  851. bn->prevfree = (bufsize) len;
  852. /* Definition of ESent assumes two's complement! */
  853. assert((~0) == -1);
  854. bn->bsize = ESent;
  855. }
  856. #ifdef BufStats
  857. /* BSTATS -- Return buffer allocation free space statistics. */
  858. void bstats(curalloc, totfree, maxfree, nget, nrel)
  859. bufsize *curalloc, *totfree, *maxfree;
  860. long *nget, *nrel;
  861. {
  862. struct bfhead *b = freelist.ql.flink;
  863. *nget = numget;
  864. *nrel = numrel;
  865. *curalloc = totalloc;
  866. *totfree = 0;
  867. *maxfree = -1;
  868. while (b != &freelist) {
  869. assert(b->bh.bsize > 0);
  870. *totfree += b->bh.bsize;
  871. if (b->bh.bsize > *maxfree) {
  872. *maxfree = b->bh.bsize;
  873. }
  874. b = b->ql.flink; /* Link to next buffer */
  875. }
  876. }
  877. #ifdef BECtl
  878. /* BSTATSE -- Return extended statistics */
  879. void bstatse(pool_incr, npool, npget, nprel, ndget, ndrel)
  880. bufsize *pool_incr;
  881. long *npool, *npget, *nprel, *ndget, *ndrel;
  882. {
  883. *pool_incr = (pool_len < 0) ? -exp_incr : exp_incr;
  884. *npool = numpblk;
  885. *npget = numpget;
  886. *nprel = numprel;
  887. *ndget = numdget;
  888. *ndrel = numdrel;
  889. }
  890. #endif /* BECtl */
  891. #endif /* BufStats */
  892. #ifdef DumpData
  893. /* BUFDUMP -- Dump the data in a buffer. This is called with the user
  894. data pointer, and backs up to the buffer header. It will
  895. dump either a free block or an allocated one. */
  896. void bufdump(buf)
  897. void *buf;
  898. {
  899. struct bfhead *b;
  900. unsigned char *bdump;
  901. bufsize bdlen;
  902. b = BFH(((char *) buf) - sizeof(struct bhead));
  903. assert(b->bh.bsize != 0);
  904. if (b->bh.bsize < 0) {
  905. bdump = (unsigned char *) buf;
  906. bdlen = (-b->bh.bsize) - sizeof(struct bhead);
  907. } else {
  908. bdump = (unsigned char *) (((char *) b) + sizeof(struct bfhead));
  909. bdlen = b->bh.bsize - sizeof(struct bfhead);
  910. }
  911. while (bdlen > 0) {
  912. int i, dupes = 0;
  913. bufsize l = bdlen;
  914. char bhex[50], bascii[20];
  915. if (l > 16) {
  916. l = 16;
  917. }
  918. for (i = 0; i < l; i++) {
  919. V sprintf(bhex + i * 3, "%02X ", bdump[i]);
  920. bascii[i] = isprint(bdump[i]) ? bdump[i] : ' ';
  921. }
  922. bascii[i] = 0;
  923. V printf("%-48s %s\n", bhex, bascii);
  924. bdump += l;
  925. bdlen -= l;
  926. while ((bdlen > 16) && (memcmp((char *) (bdump - 16),
  927. (char *) bdump, 16) == 0)) {
  928. dupes++;
  929. bdump += 16;
  930. bdlen -= 16;
  931. }
  932. if (dupes > 1) {
  933. V printf(
  934. " (%d lines [%d bytes] identical to above line skipped)\n",
  935. dupes, dupes * 16);
  936. } else if (dupes == 1) {
  937. bdump -= 16;
  938. bdlen += 16;
  939. }
  940. }
  941. }
  942. #endif
  943. #ifdef BufDump
  944. /* BPOOLD -- Dump a buffer pool. The buffer headers are always listed.
  945. If DUMPALLOC is nonzero, the contents of allocated buffers
  946. are dumped. If DUMPFREE is nonzero, free blocks are
  947. dumped as well. If FreeWipe checking is enabled, free
  948. blocks which have been clobbered will always be dumped. */
  949. void bpoold(buf, dumpalloc, dumpfree)
  950. void *buf;
  951. int dumpalloc, dumpfree;
  952. {
  953. struct bfhead *b = BFH(buf);
  954. while (b->bh.bsize != ESent) {
  955. bufsize bs = b->bh.bsize;
  956. if (bs < 0) {
  957. bs = -bs;
  958. V printf("Allocated buffer: size %6ld bytes.\n", (long) bs);
  959. if (dumpalloc) {
  960. bufdump((void *) (((char *) b) + sizeof(struct bhead)));
  961. }
  962. } else {
  963. char *lerr = "";
  964. assert(bs > 0);
  965. if ((b->ql.blink->ql.flink != b) ||
  966. (b->ql.flink->ql.blink != b)) {
  967. lerr = " (Bad free list links)";
  968. }
  969. V printf("Free block: size %6ld bytes.%s\n",
  970. (long) bs, lerr);
  971. #ifdef FreeWipe
  972. lerr = ((char *) b) + sizeof(struct bfhead);
  973. if ((bs > sizeof(struct bfhead)) && ((*lerr != 0x55) ||
  974. (memcmp(lerr, lerr + 1,
  975. (MemSize) (bs - (sizeof(struct bfhead) + 1))) != 0))) {
  976. V printf(
  977. "(Contents of above free block have been overstored.)\n");
  978. bufdump((void *) (((char *) b) + sizeof(struct bhead)));
  979. } else
  980. #endif
  981. if (dumpfree) {
  982. bufdump((void *) (((char *) b) + sizeof(struct bhead)));
  983. }
  984. }
  985. b = BFH(((char *) b) + bs);
  986. }
  987. }
  988. #endif /* BufDump */
  989. #ifdef BufValid
  990. /* BPOOLV -- Validate a buffer pool. If NDEBUG isn't defined,
  991. any error generates an assertion failure. */
  992. int bpoolv(buf)
  993. void *buf;
  994. {
  995. struct bfhead *b = BFH(buf);
  996. while (b->bh.bsize != ESent) {
  997. bufsize bs = b->bh.bsize;
  998. if (bs < 0) {
  999. bs = -bs;
  1000. } else {
  1001. char *lerr = "";
  1002. assert(bs > 0);
  1003. if (bs <= 0) {
  1004. return 0;
  1005. }
  1006. if ((b->ql.blink->ql.flink != b) ||
  1007. (b->ql.flink->ql.blink != b)) {
  1008. V printf("Free block: size %6ld bytes. (Bad free list links)\n",
  1009. (long) bs);
  1010. assert(0);
  1011. return 0;
  1012. }
  1013. #ifdef FreeWipe
  1014. lerr = ((char *) b) + sizeof(struct bfhead);
  1015. if ((bs > sizeof(struct bfhead)) && ((*lerr != 0x55) ||
  1016. (memcmp(lerr, lerr + 1,
  1017. (MemSize) (bs - (sizeof(struct bfhead) + 1))) != 0))) {
  1018. V printf(
  1019. "(Contents of above free block have been overstored.)\n");
  1020. bufdump((void *) (((char *) b) + sizeof(struct bhead)));
  1021. assert(0);
  1022. return 0;
  1023. }
  1024. #endif
  1025. }
  1026. b = BFH(((char *) b) + bs);
  1027. }
  1028. return 1;
  1029. }
  1030. #endif /* BufValid */
  1031. /***********************\
  1032. * *
  1033. * Built-in test program *
  1034. * *
  1035. \***********************/
  1036. #ifdef TestProg
  1037. #define Repeatable 1 /* Repeatable pseudorandom sequence */
  1038. /* If Repeatable is not defined, a
  1039. time-seeded pseudorandom sequence
  1040. is generated, exercising BGET with
  1041. a different pattern of calls on each
  1042. run. */
  1043. #define OUR_RAND /* Use our own built-in version of
  1044. rand() to guarantee the test is
  1045. 100% repeatable. */
  1046. #ifdef BECtl
  1047. #define PoolSize 300000 /* Test buffer pool size */
  1048. #else
  1049. #define PoolSize 50000 /* Test buffer pool size */
  1050. #endif
  1051. #define ExpIncr 32768 /* Test expansion block size */
  1052. #define CompactTries 10 /* Maximum tries at compacting */
  1053. #define dumpAlloc 0 /* Dump allocated buffers ? */
  1054. #define dumpFree 0 /* Dump free buffers ? */
  1055. #ifndef Repeatable
  1056. extern long time();
  1057. #endif
  1058. extern char *malloc();
  1059. extern int free _((char *));
  1060. static char *bchain = NULL; /* Our private buffer chain */
  1061. static char *bp = NULL; /* Our initial buffer pool */
  1062. #include <math.h>
  1063. #ifdef OUR_RAND
  1064. static unsigned long int next = 1;
  1065. /* Return next random integer */
  1066. int rand()
  1067. {
  1068. next = next * 1103515245L + 12345;
  1069. return (unsigned int) (next / 65536L) % 32768L;
  1070. }
  1071. /* Set seed for random generator */
  1072. void srand(seed)
  1073. unsigned int seed;
  1074. {
  1075. next = seed;
  1076. }
  1077. #endif
  1078. /* STATS -- Edit statistics returned by bstats() or bstatse(). */
  1079. static void stats(when)
  1080. char *when;
  1081. {
  1082. bufsize cural, totfree, maxfree;
  1083. long nget, nfree;
  1084. #ifdef BECtl
  1085. bufsize pincr;
  1086. long totblocks, npget, nprel, ndget, ndrel;
  1087. #endif
  1088. bstats(&cural, &totfree, &maxfree, &nget, &nfree);
  1089. V printf(
  1090. "%s: %ld gets, %ld releases. %ld in use, %ld free, largest = %ld\n",
  1091. when, nget, nfree, (long) cural, (long) totfree, (long) maxfree);
  1092. #ifdef BECtl
  1093. bstatse(&pincr, &totblocks, &npget, &nprel, &ndget, &ndrel);
  1094. V printf(
  1095. " Blocks: size = %ld, %ld (%ld bytes) in use, %ld gets, %ld frees\n",
  1096. (long)pincr, totblocks, pincr * totblocks, npget, nprel);
  1097. V printf(" %ld direct gets, %ld direct frees\n", ndget, ndrel);
  1098. #endif /* BECtl */
  1099. }
  1100. #ifdef BECtl
  1101. static int protect = 0; /* Disable compaction during bgetr() */
  1102. /* BCOMPACT -- Compaction call-back function. */
  1103. static int bcompact(bsize, seq)
  1104. bufsize bsize;
  1105. int seq;
  1106. {
  1107. #ifdef CompactTries
  1108. char *bc = bchain;
  1109. int i = rand() & 0x3;
  1110. #ifdef COMPACTRACE
  1111. V printf("Compaction requested. %ld bytes needed, sequence %d.\n",
  1112. (long) bsize, seq);
  1113. #endif
  1114. if (protect || (seq > CompactTries)) {
  1115. #ifdef COMPACTRACE
  1116. V printf("Compaction gave up.\n");
  1117. #endif
  1118. return 0;
  1119. }
  1120. /* Based on a random cast, release a random buffer in the list
  1121. of allocated buffers. */
  1122. while (i > 0 && bc != NULL) {
  1123. bc = *((char **) bc);
  1124. i--;
  1125. }
  1126. if (bc != NULL) {
  1127. char *fb;
  1128. fb = *((char **) bc);
  1129. if (fb != NULL) {
  1130. *((char **) bc) = *((char **) fb);
  1131. brel((void *) fb);
  1132. return 1;
  1133. }
  1134. }
  1135. #ifdef COMPACTRACE
  1136. V printf("Compaction bailed out.\n");
  1137. #endif
  1138. #endif /* CompactTries */
  1139. return 0;
  1140. }
  1141. /* BEXPAND -- Expand pool call-back function. */
  1142. static void *bexpand(size)
  1143. bufsize size;
  1144. {
  1145. void *np = NULL;
  1146. bufsize cural, totfree, maxfree;
  1147. long nget, nfree;
  1148. /* Don't expand beyond the total allocated size given by PoolSize. */
  1149. bstats(&cural, &totfree, &maxfree, &nget, &nfree);
  1150. if (cural < PoolSize) {
  1151. np = (void *) malloc((unsigned) size);
  1152. }
  1153. #ifdef EXPTRACE
  1154. V printf("Expand pool by %ld -- %s.\n", (long) size,
  1155. np == NULL ? "failed" : "succeeded");
  1156. #endif
  1157. return np;
  1158. }
  1159. /* BSHRINK -- Shrink buffer pool call-back function. */
  1160. static void bshrink(buf)
  1161. void *buf;
  1162. {
  1163. if (((char *) buf) == bp) {
  1164. #ifdef EXPTRACE
  1165. V printf("Initial pool released.\n");
  1166. #endif
  1167. bp = NULL;
  1168. }
  1169. #ifdef EXPTRACE
  1170. V printf("Shrink pool.\n");
  1171. #endif
  1172. free((char *) buf);
  1173. }
  1174. #endif /* BECtl */
  1175. /* Restrict buffer requests to those large enough to contain our pointer and
  1176. small enough for the CPU architecture. */
  1177. static bufsize blimit(bs)
  1178. bufsize bs;
  1179. {
  1180. if (bs < sizeof(char *)) {
  1181. bs = sizeof(char *);
  1182. }
  1183. /* This is written out in this ugly fashion because the
  1184. cool expression in sizeof(int) that auto-configured
  1185. to any length int befuddled some compilers. */
  1186. if (sizeof(int) == 2) {
  1187. if (bs > 32767) {
  1188. bs = 32767;
  1189. }
  1190. } else {
  1191. if (bs > 200000) {
  1192. bs = 200000;
  1193. }
  1194. }
  1195. return bs;
  1196. }
  1197. int main()
  1198. {
  1199. int i;
  1200. double x;
  1201. /* Seed the random number generator. If Repeatable is defined, we
  1202. always use the same seed. Otherwise, we seed from the clock to
  1203. shake things up from run to run. */
  1204. #ifdef Repeatable
  1205. V srand(1234);
  1206. #else
  1207. V srand((int) time((long *) NULL));
  1208. #endif
  1209. /* Compute x such that pow(x, p) ranges between 1 and 4*ExpIncr as
  1210. p ranges from 0 to ExpIncr-1, with a concentration in the lower
  1211. numbers. */
  1212. x = 4.0 * ExpIncr;
  1213. x = log(x);
  1214. x = exp(log(4.0 * ExpIncr) / (ExpIncr - 1.0));
  1215. #ifdef BECtl
  1216. bectl(bcompact, bexpand, bshrink, (bufsize) ExpIncr);
  1217. bp = malloc(ExpIncr);
  1218. assert(bp != NULL);
  1219. bpool((void *) bp, (bufsize) ExpIncr);
  1220. #else
  1221. bp = malloc(PoolSize);
  1222. assert(bp != NULL);
  1223. bpool((void *) bp, (bufsize) PoolSize);
  1224. #endif
  1225. stats("Create pool");
  1226. V bpoolv((void *) bp);
  1227. bpoold((void *) bp, dumpAlloc, dumpFree);
  1228. for (i = 0; i < TestProg; i++) {
  1229. char *cb;
  1230. bufsize bs = pow(x, (double) (rand() & (ExpIncr - 1)));
  1231. assert(bs <= (((bufsize) 4) * ExpIncr));
  1232. bs = blimit(bs);
  1233. if (rand() & 0x400) {
  1234. cb = (char *) bgetz(bs);
  1235. } else {
  1236. cb = (char *) bget(bs);
  1237. }
  1238. if (cb == NULL) {
  1239. #ifdef EasyOut
  1240. break;
  1241. #else
  1242. char *bc = bchain;
  1243. if (bc != NULL) {
  1244. char *fb;
  1245. fb = *((char **) bc);
  1246. if (fb != NULL) {
  1247. *((char **) bc) = *((char **) fb);
  1248. brel((void *) fb);
  1249. }
  1250. continue;
  1251. }
  1252. #endif
  1253. }
  1254. *((char **) cb) = (char *) bchain;
  1255. bchain = cb;
  1256. /* Based on a random cast, release a random buffer in the list
  1257. of allocated buffers. */
  1258. if ((rand() & 0x10) == 0) {
  1259. char *bc = bchain;
  1260. int i = rand() & 0x3;
  1261. while (i > 0 && bc != NULL) {
  1262. bc = *((char **) bc);
  1263. i--;
  1264. }
  1265. if (bc != NULL) {
  1266. char *fb;
  1267. fb = *((char **) bc);
  1268. if (fb != NULL) {
  1269. *((char **) bc) = *((char **) fb);
  1270. brel((void *) fb);
  1271. }
  1272. }
  1273. }
  1274. /* Based on a random cast, reallocate a random buffer in the list
  1275. to a random size */
  1276. if ((rand() & 0x20) == 0) {
  1277. char *bc = bchain;
  1278. int i = rand() & 0x3;
  1279. while (i > 0 && bc != NULL) {
  1280. bc = *((char **) bc);
  1281. i--;
  1282. }
  1283. if (bc != NULL) {
  1284. char *fb;
  1285. fb = *((char **) bc);
  1286. if (fb != NULL) {
  1287. char *newb;
  1288. bs = pow(x, (double) (rand() & (ExpIncr - 1)));
  1289. bs = blimit(bs);
  1290. #ifdef BECtl
  1291. protect = 1; /* Protect against compaction */
  1292. #endif
  1293. newb = (char *) bgetr((void *) fb, bs);
  1294. #ifdef BECtl
  1295. protect = 0;
  1296. #endif
  1297. if (newb != NULL) {
  1298. *((char **) bc) = newb;
  1299. }
  1300. }
  1301. }
  1302. }
  1303. }
  1304. stats("\nAfter allocation");
  1305. if (bp != NULL) {
  1306. V bpoolv((void *) bp);
  1307. bpoold((void *) bp, dumpAlloc, dumpFree);
  1308. }
  1309. while (bchain != NULL) {
  1310. char *buf = bchain;
  1311. bchain = *((char **) buf);
  1312. brel((void *) buf);
  1313. }
  1314. stats("\nAfter release");
  1315. #ifndef BECtl
  1316. if (bp != NULL) {
  1317. V bpoolv((void *) bp);
  1318. bpoold((void *) bp, dumpAlloc, dumpFree);
  1319. }
  1320. #endif
  1321. return 0;
  1322. }
  1323. #endif