gxclmem.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  1. /* Copyright (C) 1995, 1996, 1997, 1998 Aladdin Enterprises. All rights reserved.
  2. This file is part of AFPL Ghostscript.
  3. AFPL Ghostscript is distributed with NO WARRANTY OF ANY KIND. No author or
  4. distributor accepts any responsibility for the consequences of using it, or
  5. for whether it serves any particular purpose or works at all, unless he or
  6. she says so in writing. Refer to the Aladdin Free Public License (the
  7. "License") for full details.
  8. Every copy of AFPL Ghostscript must include a copy of the License, normally
  9. in a plain ASCII text file named PUBLIC. The License grants you the right
  10. to copy, modify and redistribute AFPL Ghostscript, but only under certain
  11. conditions described in the License. Among other things, the License
  12. requires that the copyright notice and this notice be preserved on all
  13. copies.
  14. */
  15. /*$Id: gxclmem.c,v 1.2 2000/09/19 19:00:34 lpd Exp $ */
  16. /* RAM-based command list implementation */
  17. #include "memory_.h"
  18. #include "gx.h"
  19. #include "gserrors.h"
  20. #include "gxclmem.h"
  21. /*
  22. * Based on: memfile.c Version: 1.4 3/21/95 14:59:33 by Ray Johnston.
  23. * Copyright assigned to Aladdin Enterprises.
  24. */
  25. /*****************************************************************************
  26. This package is more or less optimal for use by the clist routines, with
  27. a couple of the more likely to change "tuning" parameters given in the
  28. two macros below -- NEED_TO_COMPRESS and GET_NUM_RAW_BUFFERS. Usually
  29. the NEED_TO_COMPRESS decision will be deferred as long as possible based
  30. on some total system free RAM space remaining.
  31. The data structures are in "memfile.h", and the primary 'tuning' parameter
  32. is MEMFILE_DATA_SIZE. This should not be too small to keep the overhead
  33. ratio of the block structures to the clist data small. A value of 16384
  34. is probably in the ballpark.
  35. The concept is that a memory based "file" is created initially without
  36. compression, with index blocks every MEMFILE_DATA_SIZE of the file. The
  37. primary blocks (used by the memfile_fseek logic) for indexing into the
  38. file are called 'logical' (LOG_MEMFILE_BLK) and the data in stored in a
  39. different block called a 'physical' block (PHYS_MEMFILE_BLK). When the
  40. file is not yet compressed, indicated by (f->phys_curr==NULL), then there
  41. is one physical block for each logical block. The physical block also has
  42. the 'data_limit' set to NULL if the data is not compressed. Thus when a
  43. file is not compressed there is one physical block for each logical block.
  44. COMPRESSION.
  45. When compression is triggered for a file then all of the blocks except
  46. the last are compressed. Compression will result in a physical block
  47. that holds data for more than one logical block. Each logical block now
  48. points to the start of compressed data in a physical block with the
  49. 'phys_pdata' pointer. The 'data_limit' pointer in the physical block is
  50. where the compression logic stopped storing data (as stream data
  51. compressors are allowed to do). The data for the logical block may span
  52. to the next physical block. Once physical blocks are compressed, they are
  53. chained together using the 'link' field.
  54. The 'f->phys_curr' points to the block being filled by compression, with
  55. the 'f->wt.ptr' pointing to the last byte filled in the block. These are
  56. used during subsequent compression when the last logical block of the
  57. file fills the physical block.
  58. DECOMPRESSION.
  59. During reading the clist, if the logical block points to an uncompressed
  60. physical block, then 'memfile_get_pdata' simply sets the 'pdata' and the
  61. 'pdata_end' pointers. If the logical block was compressed, then it may
  62. still be resident in a cache of decompression buffers. The number of these
  63. decompression buffers is not critical -- even one is enough, but having
  64. more may prevent decompressing blocks more than once (a cache_miss). The
  65. number of decompression buffers, called "raw" buffers, that are attempted
  66. to allocate can be changed with the GET_NUM_RAW_BUFFERS macro, but no
  67. error occurs if less than that number can be allocated.
  68. If the logical block still resides in a decompression cache buffer, then
  69. the 'raw_block' will identify the block. If the data for a logical block
  70. only exists in compressed form, then the "tail" of the list of decompression
  71. buffers is re-used, marking the 'raw_block' of the logical block that was
  72. previously associated with this data to NULL.
  73. Whichever raw decompression buffer is accessed is moved to the head of the
  74. decompression buffer list in order to keep the tail of the list as the
  75. "least recently used".
  76. There are some DEBUG global static variables used to count the number of
  77. cache hits "tot_cache_hits" and the number of times a logical block is
  78. decompressed "tot_cache_miss". Note that the actual number of cache miss
  79. events is 'f->log_length/MEMFILE_DATA_SIZE - tot_cache_miss' since we
  80. assume that every logical block must be decmpressed at least once.
  81. Empirical results so far indicate that if one cache raw buffer for every
  82. 32 logical blocks, then the hit/miss ratio exceeds 99%. Of course, the
  83. number of raw buffers should be more than 1 if possible, and in many
  84. implementations (single threaded), the memory usage does not increase
  85. during the page output step so almost all of memory can be used for
  86. these raw buffers to prevent the likelihood of a cache miss.
  87. Of course, this is dependent on reasonably efficient clist blocking
  88. during writing which is dependent on the data and on the BufferSpace
  89. value which determines the number of clist band data buffers available.
  90. Empirical testing shows that the overall efficiency is best if the
  91. BufferSpace value is 1,000,000 (as in the original Ghostscript source).
  92. [Note: I expected to be able to use smaller buffer sizes for some cases,
  93. but this resulted in a high level of thrashing...RJJ]
  94. LIMITATIONS.
  95. The most serious limitation is caused by the way 'memfile_fwrite' decides
  96. to free up and re-initialize a file. If memfile_fwrite is called after
  97. a seek to any location except the start of the file, then an error is
  98. issued since logic is not present to properly free up on a partial file.
  99. This is not a problem as used by the 'clist' logic since rewind is used
  100. to position to the start of a file when re-using it after an 'erasepage'.
  101. Since the 'clist' logic always traverses the clist using fseek's to ever
  102. increasing locations, no optimizations of backward seeks was implemented.
  103. This would be relatively easy with back chain links or bi-directional
  104. "X-OR" pointer information to link the logical block chain. The rewind
  105. function is optimal and moves directly to the start of the file.
  106. ********************************************************************************/
  107. /*
  108. The need to compress should be conditional on the amount of available
  109. memory, but we don't have a way to communicate this to these routines.
  110. Instead, we simply start compressing when we've allocated more than
  111. COMPRESSION_THRESHOLD amount of data. The threshold should be at
  112. least as large as the fixed overhead of the compressor plus the
  113. decompressor, plus the expected compressed size of a block that size.
  114. */
  115. private const long COMPRESSION_THRESHOLD = 300000;
  116. #define NEED_TO_COMPRESS(f)\
  117. ((f)->ok_to_compress && (f)->total_space > COMPRESSION_THRESHOLD)
  118. /* FOR NOW ALLOCATE 1 raw buffer for every 32 blocks (at least 8) */
  119. #define GET_NUM_RAW_BUFFERS( f ) \
  120. max(f->log_length/MEMFILE_DATA_SIZE/32, 8)
  121. #define MALLOC(f, siz, cname)\
  122. (void *)gs_alloc_bytes((f)->data_memory, siz, cname)
  123. #define FREE(f, obj, cname)\
  124. (gs_free_object((f)->data_memory, obj, cname),\
  125. (f)->total_space -= sizeof(*(obj)))
  126. /* Structure descriptor for GC */
  127. private_st_MEMFILE();
  128. /* forward references */
  129. private void memfile_free_mem(P1(MEMFILE * f));
  130. private int memfile_init_empty(P1(MEMFILE * f));
  131. /************************************************/
  132. /* #define DEBUG /- force statistics -/ */
  133. /************************************************/
  134. #ifdef DEBUG
  135. long tot_compressed;
  136. long tot_raw;
  137. long tot_cache_miss;
  138. long tot_cache_hits;
  139. long tot_swap_out;
  140. /*
  141. The following pointers are here only for helping with a dumb debugger
  142. that can't inspect local variables!
  143. */
  144. byte *decomp_wt_ptr0, *decomp_wt_limit0;
  145. const byte *decomp_rd_ptr0, *decomp_rd_limit0;
  146. byte *decomp_wt_ptr1, *decomp_wt_limit1;
  147. const byte *decomp_rd_ptr1, *decomp_rd_limit1;
  148. #endif
  149. /* ----------------------------- Memory Allocation --------------------- */
  150. void * /* allocated memory's address, 0 if failure */
  151. allocateWithReserve(
  152. MEMFILE *f, /* file to allocate mem to */
  153. int sizeofBlock, /* size of block to allocate */
  154. int *return_code, /* RET 0 ok, -ve GS-style error, or +1 if OK but low memory */
  155. const char *allocName, /* name to allocate by */
  156. const char *errorMessage /* error message to print */
  157. )
  158. {
  159. int code = 0; /* assume success */
  160. void *block = MALLOC(f, sizeofBlock, allocName);
  161. if (block == NULL) {
  162. /* Try to recover block from reserve */
  163. if (sizeofBlock == sizeof(LOG_MEMFILE_BLK)) {
  164. if (f->reserveLogBlockCount > 0) {
  165. block = f->reserveLogBlockChain;
  166. f->reserveLogBlockChain = f->reserveLogBlockChain->link;
  167. --f->reserveLogBlockCount;
  168. }
  169. } else if (sizeofBlock == sizeof(PHYS_MEMFILE_BLK) ||
  170. sizeofBlock == sizeof(RAW_BUFFER)
  171. ) {
  172. if (f->reservePhysBlockCount > 0) {
  173. block = f->reservePhysBlockChain;
  174. f->reservePhysBlockChain = f->reservePhysBlockChain->link;
  175. --f->reservePhysBlockCount;
  176. }
  177. }
  178. if (block != NULL)
  179. code = 1; /* successful, but allocated from reserve */
  180. }
  181. if (block != NULL)
  182. f->total_space += sizeofBlock;
  183. else
  184. code = gs_note_error(gs_error_VMerror);
  185. *return_code = code;
  186. return block;
  187. }
  188. /* ---------------- Open/close/unlink ---------------- */
  189. int
  190. memfile_fopen(char fname[gp_file_name_sizeof], const char *fmode,
  191. clist_file_ptr /*MEMFILE * */ * pf,
  192. gs_memory_t *mem, gs_memory_t *data_mem, bool ok_to_compress)
  193. {
  194. MEMFILE *f = 0;
  195. int code = 0;
  196. /* We don't implement reopening an existing file. */
  197. if (fname[0] != 0 || fmode[0] != 'w') {
  198. code = gs_note_error(gs_error_invalidfileaccess);
  199. goto finish;
  200. }
  201. /* There is no need to set fname in this implementation, */
  202. /* but we do it anyway. */
  203. fname[0] = (ok_to_compress ? 'a' : 'b');
  204. fname[1] = 0;
  205. f = gs_alloc_struct(mem, MEMFILE, &st_MEMFILE,
  206. "memfile_open_scratch(MEMFILE)");
  207. if (f == NULL) {
  208. eprintf1("memfile_open_scratch(%s): gs_alloc_struct failed\n", fname);
  209. code = gs_note_error(gs_error_VMerror);
  210. goto finish;
  211. }
  212. f->memory = mem;
  213. f->data_memory = data_mem;
  214. /* init an empty file, BEFORE allocating de/compress state */
  215. f->compress_state = 0; /* make clean for GC, or alloc'n failure */
  216. f->decompress_state = 0;
  217. f->total_space = 0;
  218. f->reservePhysBlockChain = NULL;
  219. f->reservePhysBlockCount = 0;
  220. f->reserveLogBlockChain = NULL;
  221. f->reserveLogBlockCount = 0;
  222. /* init an empty file */
  223. if ((code = memfile_init_empty(f)) < 0)
  224. goto finish;
  225. if ((code = memfile_set_memory_warning(f, 0)) < 0)
  226. goto finish;
  227. /*
  228. * Disregard the ok_to_compress flag, since the size threshold gives us
  229. * a much better criterion for deciding when compression is appropriate.
  230. */
  231. f->ok_to_compress = /*ok_to_compress */ true;
  232. f->compress_state = 0; /* make clean for GC */
  233. f->decompress_state = 0;
  234. if (f->ok_to_compress) {
  235. const stream_state *compress_proto = clist_compressor_state(NULL);
  236. const stream_state *decompress_proto = clist_decompressor_state(NULL);
  237. const stream_template *compress_template = compress_proto->template;
  238. const stream_template *decompress_template = decompress_proto->template;
  239. f->compress_state =
  240. gs_alloc_struct(mem, stream_state, compress_template->stype,
  241. "memfile_open_scratch(compress_state)");
  242. f->decompress_state =
  243. gs_alloc_struct(mem, stream_state, decompress_template->stype,
  244. "memfile_open_scratch(decompress_state)");
  245. if (f->compress_state == 0 || f->decompress_state == 0) {
  246. eprintf1("memfile_open_scratch(%s): gs_alloc_struct failed\n", fname);
  247. code = gs_note_error(gs_error_VMerror);
  248. goto finish;
  249. }
  250. memcpy(f->compress_state, compress_proto,
  251. gs_struct_type_size(compress_template->stype));
  252. f->compress_state->memory = mem;
  253. memcpy(f->decompress_state, decompress_proto,
  254. gs_struct_type_size(decompress_template->stype));
  255. f->decompress_state->memory = mem;
  256. if (compress_template->set_defaults)
  257. (*compress_template->set_defaults) (f->compress_state);
  258. if (decompress_template->set_defaults)
  259. (*decompress_template->set_defaults) (f->decompress_state);
  260. }
  261. f->total_space = 0;
  262. #ifdef DEBUG
  263. /* If this is the start, init some statistics. */
  264. /* Hack: we know the 'a' file is opened first. */
  265. if (*fname == 'a') {
  266. tot_compressed = 0;
  267. tot_raw = 0;
  268. tot_cache_miss = 0;
  269. tot_cache_hits = 0;
  270. tot_swap_out = 0;
  271. }
  272. #endif
  273. finish:
  274. if (code < 0) {
  275. /* return failure, clean up memory before leaving */
  276. if (f != NULL)
  277. memfile_fclose((clist_file_ptr)f, fname, true);
  278. } else {
  279. /* return success */
  280. *pf = f;
  281. }
  282. return code;
  283. }
  284. int
  285. memfile_fclose(clist_file_ptr cf, const char *fname, bool delete)
  286. {
  287. MEMFILE *const f = (MEMFILE *)cf;
  288. /* We don't implement closing without deletion. */
  289. if (!delete)
  290. return_error(gs_error_invalidfileaccess);
  291. memfile_free_mem(f);
  292. /* Free reserve blocks; don't do it in memfile_free_mem because */
  293. /* that routine gets called to reinit file */
  294. while (f->reserveLogBlockChain != NULL) {
  295. LOG_MEMFILE_BLK *block = f->reserveLogBlockChain;
  296. f->reserveLogBlockChain = block->link;
  297. FREE(f, block, "memfile_set_block_size");
  298. }
  299. while (f->reservePhysBlockChain != NULL) {
  300. PHYS_MEMFILE_BLK *block = f->reservePhysBlockChain;
  301. f->reservePhysBlockChain = block->link;
  302. FREE(f, block, "memfile_set_block_size");
  303. }
  304. /* deallocate de/compress state */
  305. gs_free_object(f->memory, f->decompress_state,
  306. "memfile_close_and_unlink(decompress_state)");
  307. gs_free_object(f->memory, f->compress_state,
  308. "memfile_close_and_unlink(compress_state)");
  309. /* deallocate the memfile object proper */
  310. gs_free_object(f->memory, f, "memfile_close_and_unlink(MEMFILE)");
  311. return 0;
  312. }
  313. int
  314. memfile_unlink(const char *fname)
  315. {
  316. /*
  317. * Since we have no way to represent a memfile other than by the
  318. * pointer, we don't (can't) implement unlinking.
  319. */
  320. return_error(gs_error_invalidfileaccess);
  321. }
  322. /* ---------------- Writing ---------------- */
  323. /* Pre-alloc enough reserve mem blox to guarantee a write of N bytes will succeed */
  324. int /* returns 0 ok, gs_error_VMerror if insufficient */
  325. memfile_set_memory_warning(clist_file_ptr cf, int bytes_left)
  326. {
  327. MEMFILE *const f = (MEMFILE *)cf;
  328. int code = 0;
  329. /*
  330. * Determine req'd memory block count from bytes_left.
  331. * Allocate enough phys & log blocks to hold bytes_left
  332. * + 1 phys blk for compress_log_blk + 1 phys blk for decompress.
  333. */
  334. int logNeeded =
  335. (bytes_left + MEMFILE_DATA_SIZE - 1) / MEMFILE_DATA_SIZE;
  336. int physNeeded = logNeeded;
  337. if (bytes_left > 0)
  338. ++physNeeded;
  339. if (f->raw_head == NULL)
  340. ++physNeeded; /* have yet to allocate read buffers */
  341. /* Allocate or free memory depending on need */
  342. while (logNeeded > f->reserveLogBlockCount) {
  343. LOG_MEMFILE_BLK *block =
  344. MALLOC( f, sizeof(LOG_MEMFILE_BLK), "memfile_set_block_size" );
  345. if (block == NULL) {
  346. code = gs_note_error(gs_error_VMerror);
  347. goto finish;
  348. }
  349. block->link = f->reserveLogBlockChain;
  350. f->reserveLogBlockChain = block;
  351. ++f->reserveLogBlockCount;
  352. }
  353. while (logNeeded < f->reserveLogBlockCount) {
  354. LOG_MEMFILE_BLK *block = f->reserveLogBlockChain;
  355. f->reserveLogBlockChain = block->link;
  356. FREE(f, block, "memfile_set_block_size");
  357. --f->reserveLogBlockCount;
  358. }
  359. while (physNeeded > f->reservePhysBlockCount) {
  360. PHYS_MEMFILE_BLK *block =
  361. MALLOC( f,
  362. max( sizeof(PHYS_MEMFILE_BLK), sizeof(RAW_BUFFER) ),
  363. "memfile_set_block_size");
  364. if (block == NULL) {
  365. code = gs_note_error(gs_error_VMerror);
  366. goto finish;
  367. }
  368. block->link = f->reservePhysBlockChain;
  369. f->reservePhysBlockChain = block;
  370. ++f->reservePhysBlockCount;
  371. }
  372. while (physNeeded < f->reservePhysBlockCount) {
  373. PHYS_MEMFILE_BLK *block = f->reservePhysBlockChain;
  374. f->reservePhysBlockChain = block->link;
  375. FREE(f, block, "memfile_set_block_size");
  376. --f->reservePhysBlockCount;
  377. }
  378. f->error_code = 0; /* memfile_set_block_size is how user resets this */
  379. finish:
  380. return code;
  381. }
  382. private int
  383. compress_log_blk(MEMFILE * f, LOG_MEMFILE_BLK * bp)
  384. {
  385. int status;
  386. int ecode = 0; /* accumulate low-memory warnings */
  387. int code;
  388. long compressed_size;
  389. byte *start_ptr;
  390. PHYS_MEMFILE_BLK *newphys;
  391. /* compress this block */
  392. f->rd.ptr = (const byte *)(bp->phys_blk->data) - 1;
  393. f->rd.limit = f->rd.ptr + MEMFILE_DATA_SIZE;
  394. bp->phys_blk = f->phys_curr;
  395. bp->phys_pdata = (char *)(f->wt.ptr) + 1;
  396. if (f->compress_state->template->reinit != 0)
  397. (*f->compress_state->template->reinit)(f->compress_state);
  398. compressed_size = 0;
  399. start_ptr = f->wt.ptr;
  400. status = (*f->compress_state->template->process)(f->compress_state,
  401. &(f->rd), &(f->wt), true);
  402. bp->phys_blk->data_limit = (char *)(f->wt.ptr);
  403. if (status == 1) { /* More output space needed (see strimpl.h) */
  404. /* allocate another physical block, then compress remainder */
  405. compressed_size = f->wt.limit - start_ptr;
  406. newphys =
  407. allocateWithReserve(f, sizeof(*newphys), &code, "memfile newphys",
  408. "compress_log_blk : MALLOC for 'newphys' failed\n");
  409. if (code < 0)
  410. return code;
  411. ecode |= code; /* accumulate any low-memory warnings */
  412. newphys->link = NULL;
  413. bp->phys_blk->link = newphys;
  414. f->phys_curr = newphys;
  415. f->wt.ptr = (byte *) (newphys->data) - 1;
  416. f->wt.limit = f->wt.ptr + MEMFILE_DATA_SIZE;
  417. start_ptr = f->wt.ptr;
  418. status =
  419. (*f->compress_state->template->process)(f->compress_state,
  420. &(f->rd), &(f->wt), true);
  421. if (status != 0) {
  422. /*
  423. * You'd think the above line is a bug, but in real life 1 src
  424. * block never ends up getting split across 3 dest blocks.
  425. */
  426. /* CHANGE memfile_set_memory_warning if this assumption changes. */
  427. eprintf("Compression required more than one full block!\n");
  428. return_error(gs_error_Fatal);
  429. }
  430. newphys->data_limit = (char *)(f->wt.ptr);
  431. }
  432. compressed_size += f->wt.ptr - start_ptr;
  433. if (compressed_size > MEMFILE_DATA_SIZE) {
  434. eprintf2("\nCompression didn't - raw=%d, compressed=%ld\n",
  435. MEMFILE_DATA_SIZE, compressed_size);
  436. }
  437. #ifdef DEBUG
  438. tot_compressed += compressed_size;
  439. #endif
  440. return (status < 0 ? gs_note_error(gs_error_ioerror) : ecode);
  441. } /* end "compress_log_blk()" */
  442. /* Internal (private) routine to handle end of logical block */
  443. private int /* ret 0 ok, -ve error, or +ve low-memory warning */
  444. memfile_next_blk(MEMFILE * f)
  445. {
  446. LOG_MEMFILE_BLK *bp = f->log_curr_blk;
  447. LOG_MEMFILE_BLK *newbp;
  448. PHYS_MEMFILE_BLK *newphys, *oldphys;
  449. int ecode = 0; /* accumulate low-memory warnings */
  450. int code;
  451. if (f->phys_curr == NULL) { /* means NOT compressing */
  452. /* allocate a new block */
  453. newphys =
  454. allocateWithReserve(f, sizeof(*newphys), &code, "memfile newphys",
  455. "memfile_next_blk: MALLOC 1 for 'newphys' failed\n");
  456. if (code < 0)
  457. return code;
  458. ecode |= code; /* accumulate low-mem warnings */
  459. newphys->link = NULL;
  460. newphys->data_limit = NULL; /* raw */
  461. newbp =
  462. allocateWithReserve(f, sizeof(*newbp), &code, "memfile newbp",
  463. "memfile_next_blk: MALLOC 1 for 'newbp' failed\n");
  464. if (code < 0) {
  465. FREE(f, newphys, "memfile newphys");
  466. return code;
  467. }
  468. ecode |= code; /* accumulate low-mem warnings */
  469. bp->link = newbp;
  470. newbp->link = NULL;
  471. newbp->raw_block = NULL;
  472. f->log_curr_blk = newbp;
  473. /* check if need to start compressing */
  474. if (NEED_TO_COMPRESS(f)) {
  475. if_debug0(':', "[:]Beginning compression\n");
  476. /* compress the entire file up to this point */
  477. if (!f->compressor_initialized) {
  478. int code = 0;
  479. if (f->compress_state->template->init != 0)
  480. code = (*f->compress_state->template->init) (f->compress_state);
  481. if (code < 0)
  482. return_error(gs_error_VMerror); /****** BOGUS ******/
  483. if (f->decompress_state->template->init != 0)
  484. code = (*f->decompress_state->template->init)
  485. (f->decompress_state);
  486. if (code < 0)
  487. return_error(gs_error_VMerror); /****** BOGUS ******/
  488. f->compressor_initialized = true;
  489. }
  490. /* Write into the new physical block we just allocated, */
  491. /* replace it after the loop (after some blocks are freed) */
  492. f->phys_curr = newphys;
  493. f->wt.ptr = (byte *) (newphys->data) - 1;
  494. f->wt.limit = f->wt.ptr + MEMFILE_DATA_SIZE;
  495. bp = f->log_head;
  496. while (bp != newbp) { /* don't compress last block */
  497. int code;
  498. oldphys = bp->phys_blk;
  499. if ((code = compress_log_blk(f, bp)) < 0)
  500. return code;
  501. ecode |= code;
  502. FREE(f, oldphys, "memfile_next_blk(oldphys)");
  503. bp = bp->link;
  504. } /* end while( ) compress loop */
  505. /* Allocate a physical block for this (last) logical block */
  506. newphys =
  507. allocateWithReserve(f, sizeof(*newphys), &code,
  508. "memfile newphys",
  509. "memfile_next_blk: MALLOC 2 for 'newphys' failed\n");
  510. if (code < 0)
  511. return code;
  512. ecode |= code; /* accumulate low-mem warnings */
  513. newphys->link = NULL;
  514. newphys->data_limit = NULL; /* raw */
  515. } /* end convert file to compressed */
  516. newbp->phys_blk = newphys;
  517. f->pdata = newphys->data;
  518. f->pdata_end = newphys->data + MEMFILE_DATA_SIZE;
  519. } /* end if NOT compressing */
  520. /* File IS being compressed */
  521. else {
  522. int code;
  523. oldphys = bp->phys_blk; /* save raw phys block ID */
  524. /* compresses bp on phys list */
  525. if ((code = compress_log_blk(f, bp)) < 0)
  526. return code;
  527. ecode |= code;
  528. newbp =
  529. allocateWithReserve(f, sizeof(*newbp), &code, "memfile newbp",
  530. "memfile_next_blk: MALLOC 2 for 'newbp' failed\n");
  531. if (code < 0)
  532. return code;
  533. ecode |= code;
  534. bp->link = newbp;
  535. newbp->link = NULL;
  536. newbp->raw_block = NULL;
  537. /* Re-use the raw phys block for this new logical blk */
  538. newbp->phys_blk = oldphys;
  539. f->pdata = oldphys->data;
  540. f->pdata_end = f->pdata + MEMFILE_DATA_SIZE;
  541. f->log_curr_blk = newbp;
  542. } /* end else (when we are compressing) */
  543. return (ecode);
  544. }
  545. int /* returns # of chars actually written */
  546. memfile_fwrite_chars(const void *data, uint len, clist_file_ptr cf)
  547. {
  548. const char *str = (const char *)data;
  549. MEMFILE *f = (MEMFILE *) cf;
  550. uint count = len;
  551. int ecode;
  552. /* check if we are writing to the start of the file. If so, then */
  553. /* free the file memory and re-initialize it (frees memory) */
  554. if (f->log_curr_pos == 0) {
  555. int code;
  556. memfile_free_mem(f);
  557. if ((code = memfile_init_empty(f)) < 0) {
  558. f->error_code = code;
  559. return 0;
  560. }
  561. }
  562. if (f->log_curr_blk->link != 0) {
  563. eprintf(" Write file truncate -- need to free physical blocks.\n");
  564. }
  565. while (count) {
  566. uint move_count = f->pdata_end - f->pdata;
  567. if (move_count == 0) {
  568. if ((ecode = memfile_next_blk(f)) != 0) {
  569. f->error_code = ecode;
  570. if (ecode < 0)
  571. return 0;
  572. }
  573. } else {
  574. if (move_count > count)
  575. move_count = count;
  576. memmove(f->pdata, str, move_count);
  577. f->pdata += move_count;
  578. str += move_count;
  579. count -= move_count;
  580. }
  581. }
  582. f->log_curr_pos += len;
  583. f->log_length = f->log_curr_pos; /* truncate length to here */
  584. #ifdef DEBUG
  585. tot_raw += len;
  586. #endif
  587. return (len);
  588. }
  589. /* */
  590. /* Internal routine to set the f->pdata and f->pdata_end pointers */
  591. /* for the current logical block f->log_curr_blk */
  592. /* */
  593. /* If data only exists in compressed form, allocate a raw buffer */
  594. /* and decompress it. */
  595. /* */
  596. private int
  597. memfile_get_pdata(MEMFILE * f)
  598. {
  599. int i, num_raw_buffers, status;
  600. LOG_MEMFILE_BLK *bp = f->log_curr_blk;
  601. if (bp->phys_blk->data_limit == NULL) {
  602. /* Not compressed, return this data pointer */
  603. f->pdata = (bp->phys_blk)->data;
  604. i = f->log_curr_pos % MEMFILE_DATA_SIZE; /* pos within block */
  605. i = f->log_curr_pos - i; /* base of block */
  606. if (i + MEMFILE_DATA_SIZE > f->log_length)
  607. f->pdata_end = f->pdata + f->log_length - i;
  608. else
  609. f->pdata_end = f->pdata + MEMFILE_DATA_SIZE;
  610. } else {
  611. /* data was compressed */
  612. if (f->raw_head == NULL) {
  613. /* need to allocate the raw buffer pool */
  614. num_raw_buffers = GET_NUM_RAW_BUFFERS(f);
  615. if (f->reservePhysBlockCount) {
  616. /* HACK: allocate reserve block that's been reserved for
  617. * decompression. This buffer's block was pre-allocated to make
  618. * sure we won't come up short here. Take from chain instead of
  619. * allocateWithReserve() since this buf would just be wasted if
  620. * allowed to remain preallocated. */
  621. f->raw_head = (RAW_BUFFER *)f->reservePhysBlockChain;
  622. f->reservePhysBlockChain = f->reservePhysBlockChain->link;
  623. --f->reservePhysBlockCount;
  624. } else {
  625. int code;
  626. f->raw_head =
  627. allocateWithReserve(f, sizeof(*f->raw_head), &code,
  628. "memfile raw buffer",
  629. "memfile_get_pdata: MALLOC for 'raw_head' failed\n");
  630. if (code < 0)
  631. return code;
  632. }
  633. f->raw_head->back = NULL;
  634. f->raw_tail = f->raw_head;
  635. f->raw_tail->log_blk = NULL;
  636. for (i = 0; i < num_raw_buffers; i++) {
  637. f->raw_tail->fwd = (RAW_BUFFER *) MALLOC(f, sizeof(RAW_BUFFER),
  638. "memfile raw buffer");
  639. /* if MALLOC fails, then just stop allocating */
  640. if (!f->raw_tail->fwd)
  641. break;
  642. f->total_space += sizeof(RAW_BUFFER);
  643. f->raw_tail->fwd->back = f->raw_tail;
  644. f->raw_tail = f->raw_tail->fwd;
  645. f->raw_tail->log_blk = NULL;
  646. }
  647. f->raw_tail->fwd = NULL;
  648. num_raw_buffers = i + 1; /* if MALLOC failed, then OK */
  649. if_debug1(':', "[:]Number of raw buffers allocated=%d\n",
  650. num_raw_buffers);
  651. } /* end allocating the raw buffer pool (first time only) */
  652. if (bp->raw_block == NULL) {
  653. #ifdef DEBUG
  654. tot_cache_miss++; /* count every decompress */
  655. #endif
  656. /* find a raw buffer and decompress */
  657. if (f->raw_tail->log_blk != NULL) {
  658. /* This block was in use, grab it */
  659. #ifdef DEBUG
  660. tot_swap_out++;
  661. #endif
  662. f->raw_tail->log_blk->raw_block = NULL; /* data no longer here */
  663. f->raw_tail->log_blk = NULL;
  664. }
  665. /* Use the last raw block in the chain (the oldest) */
  666. f->raw_tail->back->fwd = NULL; /* disconnect from tail */
  667. f->raw_tail->fwd = f->raw_head; /* new head */
  668. f->raw_head->back = f->raw_tail;
  669. f->raw_tail = f->raw_tail->back;
  670. f->raw_head = f->raw_head->back;
  671. f->raw_head->back = NULL;
  672. f->raw_head->log_blk = bp;
  673. /* Decompress the data into this raw block */
  674. /* Initialize the decompressor */
  675. if (f->decompress_state->template->reinit != 0)
  676. (*f->decompress_state->template->reinit) (f->decompress_state);
  677. /* Set pointers and call the decompress routine */
  678. f->wt.ptr = (byte *) (f->raw_head->data) - 1;
  679. f->wt.limit = f->wt.ptr + MEMFILE_DATA_SIZE;
  680. f->rd.ptr = (const byte *)(bp->phys_pdata) - 1;
  681. f->rd.limit = (const byte *)bp->phys_blk->data_limit;
  682. #ifdef DEBUG
  683. decomp_wt_ptr0 = f->wt.ptr;
  684. decomp_wt_limit0 = f->wt.limit;
  685. decomp_rd_ptr0 = f->rd.ptr;
  686. decomp_rd_limit0 = f->rd.limit;
  687. #endif
  688. status = (*f->decompress_state->template->process)
  689. (f->decompress_state, &(f->rd), &(f->wt), true);
  690. if (status == 0) { /* More input data needed */
  691. /* switch to next block and continue decompress */
  692. int back_up = 0; /* adjust pointer backwards */
  693. if (f->rd.ptr != f->rd.limit) {
  694. /* transfer remainder bytes from the previous block */
  695. back_up = f->rd.limit - f->rd.ptr;
  696. for (i = 0; i < back_up; i++)
  697. *(bp->phys_blk->link->data - back_up + i) = *++f->rd.ptr;
  698. }
  699. f->rd.ptr = (const byte *)bp->phys_blk->link->data - back_up - 1;
  700. f->rd.limit = (const byte *)bp->phys_blk->link->data_limit;
  701. #ifdef DEBUG
  702. decomp_wt_ptr1 = f->wt.ptr;
  703. decomp_wt_limit1 = f->wt.limit;
  704. decomp_rd_ptr1 = f->rd.ptr;
  705. decomp_rd_limit1 = f->rd.limit;
  706. #endif
  707. status = (*f->decompress_state->template->process)
  708. (f->decompress_state, &(f->rd), &(f->wt), true);
  709. if (status == 0) {
  710. eprintf("Decompression required more than one full block!\n");
  711. return_error(gs_error_Fatal);
  712. }
  713. }
  714. bp->raw_block = f->raw_head; /* point to raw block */
  715. }
  716. /* end if( raw_block == NULL ) meaning need to decompress data */
  717. else {
  718. /* data exists in the raw data cache, if not raw_head, move it */
  719. if (bp->raw_block != f->raw_head) {
  720. /* move to raw_head */
  721. /* prev.fwd = this.fwd */
  722. bp->raw_block->back->fwd = bp->raw_block->fwd;
  723. if (bp->raw_block->fwd != NULL)
  724. /* next.back = this.back */
  725. bp->raw_block->fwd->back = bp->raw_block->back;
  726. else
  727. f->raw_tail = bp->raw_block->back; /* tail = prev */
  728. f->raw_head->back = bp->raw_block; /* head.back = this */
  729. bp->raw_block->fwd = f->raw_head; /* this.fwd = orig head */
  730. f->raw_head = bp->raw_block; /* head = this */
  731. f->raw_head->back = NULL; /* this.back = NULL */
  732. #ifdef DEBUG
  733. tot_cache_hits++; /* counting here prevents repeats since */
  734. /* won't count if already at head */
  735. #endif
  736. }
  737. }
  738. f->pdata = bp->raw_block->data;
  739. f->pdata_end = f->pdata + MEMFILE_DATA_SIZE;
  740. /* NOTE: last block is never compressed, so a compressed block */
  741. /* is always full size. */
  742. } /* end else (when data was compressed) */
  743. return (0);
  744. }
  745. /* ---------------- Reading ---------------- */
  746. int
  747. memfile_fread_chars(void *data, uint len, clist_file_ptr cf)
  748. {
  749. char *str = (char *)data;
  750. MEMFILE *f = (MEMFILE *) cf;
  751. uint count = len, num_read, move_count;
  752. num_read = f->log_length - f->log_curr_pos;
  753. if (count > num_read)
  754. count = num_read;
  755. num_read = count;
  756. while (count) {
  757. f->log_curr_pos++; /* move into next byte */
  758. if (f->pdata == f->pdata_end) {
  759. f->log_curr_blk = (f->log_curr_blk)->link;
  760. memfile_get_pdata(f);
  761. }
  762. move_count = f->pdata_end - f->pdata;
  763. if (move_count > count)
  764. move_count = count;
  765. f->log_curr_pos += move_count - 1; /* new position */
  766. memmove(str, f->pdata, move_count);
  767. str += move_count;
  768. f->pdata += move_count;
  769. count -= move_count;
  770. }
  771. return (num_read);
  772. }
  773. /* ---------------- Position/status ---------------- */
  774. int
  775. memfile_ferror_code(clist_file_ptr cf)
  776. {
  777. return (((MEMFILE *) cf)->error_code); /* errors stored here */
  778. }
  779. long
  780. memfile_ftell(clist_file_ptr cf)
  781. {
  782. return (((MEMFILE *) cf)->log_curr_pos);
  783. }
  784. void
  785. memfile_rewind(clist_file_ptr cf, bool discard_data, const char *ignore_fname)
  786. {
  787. MEMFILE *f = (MEMFILE *) cf;
  788. if (discard_data) {
  789. memfile_free_mem(f);
  790. /* We have to call memfile_init_empty to preserve invariants. */
  791. memfile_init_empty(f);
  792. } else {
  793. f->log_curr_blk = f->log_head;
  794. f->log_curr_pos = 0;
  795. memfile_get_pdata(f);
  796. }
  797. }
  798. int
  799. memfile_fseek(clist_file_ptr cf, long offset, int mode, const char *ignore_fname)
  800. {
  801. MEMFILE *f = (MEMFILE *) cf;
  802. long i, block_num, new_pos;
  803. switch (mode) {
  804. case SEEK_SET: /* offset from the beginning of the file */
  805. new_pos = offset;
  806. break;
  807. case SEEK_CUR: /* offset from the current position in the file */
  808. new_pos = offset + f->log_curr_pos;
  809. break;
  810. case SEEK_END: /* offset back from the end of the file */
  811. new_pos = f->log_length - offset;
  812. break;
  813. default:
  814. return (-1);
  815. }
  816. if (new_pos < 0 || new_pos > f->log_length)
  817. return -1;
  818. if ((f->pdata == f->pdata_end) && (f->log_curr_blk->link != NULL)) {
  819. /* log_curr_blk is actually one block behind log_curr_pos */
  820. f->log_curr_blk = f->log_curr_blk->link;
  821. }
  822. block_num = new_pos / MEMFILE_DATA_SIZE;
  823. i = f->log_curr_pos / MEMFILE_DATA_SIZE;
  824. if (block_num < i) { /* if moving backwards, start at beginning */
  825. f->log_curr_blk = f->log_head;
  826. i = 0;
  827. }
  828. for (; i < block_num; i++) {
  829. f->log_curr_blk = f->log_curr_blk->link;
  830. }
  831. f->log_curr_pos = new_pos;
  832. memfile_get_pdata(f); /* pointers to start of block */
  833. f->pdata += new_pos - (block_num * MEMFILE_DATA_SIZE);
  834. return 0; /* return "normal" status */
  835. }
  836. /* ---------------- Internal routines ---------------- */
  837. private void
  838. memfile_free_mem(MEMFILE * f)
  839. {
  840. LOG_MEMFILE_BLK *bp, *tmpbp;
  841. #ifdef DEBUG
  842. /* output some diagnostics about the effectiveness */
  843. if (tot_raw > 100) {
  844. if_debug2(':', "[:]tot_raw=%ld, tot_compressed=%ld\n",
  845. tot_raw, tot_compressed);
  846. }
  847. if (tot_cache_hits != 0) {
  848. if_debug3(':', "[:]Cache hits=%ld, cache misses=%ld, swapouts=%ld\n",
  849. tot_cache_hits,
  850. tot_cache_miss - (f->log_length / MEMFILE_DATA_SIZE),
  851. tot_swap_out);
  852. }
  853. tot_raw = 0;
  854. tot_compressed = 0;
  855. tot_cache_hits = 0;
  856. tot_cache_miss = 0;
  857. tot_swap_out = 0;
  858. #endif
  859. /* Free up memory that was allocated for the memfile */
  860. bp = f->log_head;
  861. /******************************************************************
  862. * The following was the original algorithm here. This algorithm has a bug:
  863. * the second loop references the physical blocks again after they have been
  864. * freed.
  865. ******************************************************************/
  866. #if 0 /**************** *************** */
  867. if (bp != NULL) {
  868. /* Free the physical blocks that make up the compressed data */
  869. PHYS_MEMFILE_BLK *pphys = (f->log_head)->phys_blk;
  870. if (pphys->data_limit != NULL) {
  871. /* the data was compressed, free the chain of blocks */
  872. while (pphys != NULL) {
  873. PHYS_MEMFILE_BLK *tmpphys = pphys->link;
  874. FREE(f, pphys, "memfile_free_mem(pphys)");
  875. pphys = tmpphys;
  876. }
  877. }
  878. }
  879. /* free the logical blocks */
  880. while (bp != NULL) {
  881. /* if this logical block was not compressed, free the phys_blk */
  882. if (bp->phys_blk->data_limit == NULL) {
  883. FREE(f, bp->phys_blk, "memfile_free_mem(phys_blk)");
  884. }
  885. tmpbp = bp->link;
  886. FREE(f, bp, "memfile_free_mem(log_blk)");
  887. bp = tmpbp;
  888. }
  889. #else /**************** *************** */
  890. # if 1 /**************** *************** */
  891. /****************************************************************
  892. * This algorithm is correct (we think).
  893. ****************************************************************/
  894. if (bp != NULL) {
  895. /* Null out phys_blk pointers to compressed data. */
  896. PHYS_MEMFILE_BLK *pphys = bp->phys_blk;
  897. {
  898. for (tmpbp = bp; tmpbp != NULL; tmpbp = tmpbp->link)
  899. if (tmpbp->phys_blk->data_limit != NULL)
  900. tmpbp->phys_blk = 0;
  901. }
  902. /* Free the physical blocks that make up the compressed data */
  903. if (pphys->data_limit != NULL) {
  904. /* the data was compressed, free the chain of blocks */
  905. while (pphys != NULL) {
  906. PHYS_MEMFILE_BLK *tmpphys = pphys->link;
  907. FREE(f, pphys, "memfile_free_mem(pphys)");
  908. pphys = tmpphys;
  909. }
  910. }
  911. }
  912. /* Now free the logical blocks, and any uncompressed physical blocks. */
  913. while (bp != NULL) {
  914. if (bp->phys_blk != NULL) {
  915. FREE(f, bp->phys_blk, "memfile_free_mem(phys_blk)");
  916. }
  917. tmpbp = bp->link;
  918. FREE(f, bp, "memfile_free_mem(log_blk)");
  919. bp = tmpbp;
  920. }
  921. /***********************************************************************
  922. * This algorithm appears to be both simpler and free of the bug that
  923. * occasionally causes the older one to reference freed blocks; but in
  924. * fact it can miss blocks, because the very last compressed logical block
  925. * can have spill into a second physical block, which is not referenced by
  926. * any logical block.
  927. ***********************************************************************/
  928. # else /**************** *************** */
  929. {
  930. PHYS_MEMFILE_BLK *prev_phys = 0;
  931. while (bp != NULL) {
  932. PHYS_MEMFILE_BLK *phys = bp->phys_blk;
  933. if (phys != prev_phys) {
  934. FREE(f, phys, "memfile_free_mem(phys_blk)");
  935. prev_phys = phys;
  936. }
  937. tmpbp = bp->link;
  938. FREE(f, bp, "memfile_free_mem(log_blk)");
  939. bp = tmpbp;
  940. }
  941. }
  942. # endif /**************** *************** */
  943. #endif /**************** *************** */
  944. f->log_head = NULL;
  945. /* Free any internal compressor state. */
  946. if (f->compressor_initialized) {
  947. if (f->decompress_state->template->release != 0)
  948. (*f->decompress_state->template->release) (f->decompress_state);
  949. if (f->compress_state->template->release != 0)
  950. (*f->compress_state->template->release) (f->compress_state);
  951. f->compressor_initialized = false;
  952. }
  953. /* free the raw buffers */
  954. while (f->raw_head != NULL) {
  955. RAW_BUFFER *tmpraw = f->raw_head->fwd;
  956. FREE(f, f->raw_head, "memfile_free_mem(raw)");
  957. f->raw_head = tmpraw;
  958. }
  959. }
  960. private int
  961. memfile_init_empty(MEMFILE * f)
  962. {
  963. PHYS_MEMFILE_BLK *pphys;
  964. LOG_MEMFILE_BLK *plog;
  965. /* Zero out key fields so that allocation failure will be unwindable */
  966. f->phys_curr = NULL; /* flag as file not compressed */
  967. f->log_head = NULL;
  968. f->log_curr_blk = NULL;
  969. f->log_curr_pos = 0;
  970. f->log_length = 0;
  971. f->raw_head = NULL;
  972. f->compressor_initialized = false;
  973. f->total_space = 0;
  974. /* File empty - get a physical mem block (includes the buffer area) */
  975. pphys = MALLOC(f, sizeof(*pphys), "memfile pphys");
  976. if (!pphys) {
  977. eprintf("memfile_init_empty: MALLOC for 'pphys' failed\n");
  978. return_error(gs_error_VMerror);
  979. }
  980. f->total_space += sizeof(*pphys);
  981. pphys->data_limit = NULL; /* raw data for now */
  982. /* Get logical mem block to go with physical one */
  983. plog = (LOG_MEMFILE_BLK *)MALLOC( f, sizeof(*plog), "memfile_init_empty" );
  984. if (plog == NULL) {
  985. FREE(f, pphys, "memfile_init_empty");
  986. eprintf("memfile_init_empty: MALLOC for log_curr_blk failed\n");
  987. return_error(gs_error_VMerror);
  988. }
  989. f->total_space += sizeof(*plog);
  990. f->log_head = f->log_curr_blk = plog;
  991. f->log_curr_blk->link = NULL;
  992. f->log_curr_blk->phys_blk = pphys;
  993. f->log_curr_blk->phys_pdata = NULL;
  994. f->log_curr_blk->raw_block = NULL;
  995. f->pdata = pphys->data;
  996. f->pdata_end = f->pdata + MEMFILE_DATA_SIZE;
  997. f->error_code = 0;
  998. return 0;
  999. }