1/*
2 * jmemmgr.c
3 *
4 * Copyright (C) 1991-1997, Thomas G. Lane.
5 * This file is part of the Independent JPEG Group's software.
6 * For conditions of distribution and use, see the accompanying README file.
7 *
8 * This file contains the JPEG system-independent memory management
9 * routines.  This code is usable across a wide variety of machines; most
10 * of the system dependencies have been isolated in a separate file.
11 * The major functions provided here are:
12 *   * pool-based allocation and freeing of memory;
13 *   * policy decisions about how to divide available memory among the
14 *     virtual arrays;
15 *   * control logic for swapping virtual arrays between main memory and
16 *     backing storage.
17 * The separate system-dependent file provides the actual backing-storage
18 * access code, and it contains the policy decision about how much total
19 * main memory to use.
20 * This file is system-dependent in the sense that some of its functions
21 * are unnecessary in some systems.  For example, if there is enough virtual
22 * memory so that backing storage will never be used, much of the virtual
23 * array control logic could be removed.  (Of course, if you have that much
24 * memory then you shouldn't care about a little bit of unused code...)
25 */
26
27#define JPEG_INTERNALS
28#define AM_MEMORY_MANAGER	/* we define jvirt_Xarray_control structs */
29#include "jinclude.h"
30#include "jpeglib.h"
31#include "jmemsys.h"		/* import the system-dependent declarations */
32
33#define NO_GETENV	/* XYQ: 2007-5-22 Don't use it */
34
35#ifndef NO_GETENV
36#ifndef HAVE_STDLIB_H		/* <stdlib.h> should declare getenv() */
37extern char * getenv JPP((const char * name));
38#endif
39#endif
40
41
42/*
43 * Some important notes:
44 *   The allocation routines provided here must never return NULL.
45 *   They should exit to error_exit if unsuccessful.
46 *
47 *   It's not a good idea to try to merge the sarray and barray routines,
48 *   even though they are textually almost the same, because samples are
49 *   usually stored as bytes while coefficients are shorts or ints.  Thus,
50 *   in machines where byte pointers have a different representation from
51 *   word pointers, the resulting machine code could not be the same.
52 */
53
54
55/*
56 * Many machines require storage alignment: longs must start on 4-byte
57 * boundaries, doubles on 8-byte boundaries, etc.  On such machines, malloc()
58 * always returns pointers that are multiples of the worst-case alignment
59 * requirement, and we had better do so too.
60 * There isn't any really portable way to determine the worst-case alignment
61 * requirement.  This module assumes that the alignment requirement is
62 * multiples of sizeof(ALIGN_TYPE).
63 * By default, we define ALIGN_TYPE as double.  This is necessary on some
64 * workstations (where doubles really do need 8-byte alignment) and will work
65 * fine on nearly everything.  If your machine has lesser alignment needs,
66 * you can save a few bytes by making ALIGN_TYPE smaller.
67 * The only place I know of where this will NOT work is certain Macintosh
68 * 680x0 compilers that define double as a 10-byte IEEE extended float.
69 * Doing 10-byte alignment is counterproductive because longwords won't be
70 * aligned well.  Put "#define ALIGN_TYPE long" in jconfig.h if you have
71 * such a compiler.
72 */
73
74#ifndef ALIGN_TYPE		/* so can override from jconfig.h */
75#define ALIGN_TYPE  double
76#endif
77
78
79/*
80 * We allocate objects from "pools", where each pool is gotten with a single
81 * request to jpeg_get_small() or jpeg_get_large().  There is no per-object
82 * overhead within a pool, except for alignment padding.  Each pool has a
83 * header with a link to the next pool of the same class.
84 * Small and large pool headers are identical except that the latter's
85 * link pointer must be FAR on 80x86 machines.
86 * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
87 * field.  This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
88 * of the alignment requirement of ALIGN_TYPE.
89 */
90
91typedef union small_pool_struct * small_pool_ptr;
92
93typedef union small_pool_struct {
94  struct {
95    small_pool_ptr next;	/* next in list of pools */
96    size_t bytes_used;		/* how many bytes already used within pool */
97    size_t bytes_left;		/* bytes still available in this pool */
98  } hdr;
99  ALIGN_TYPE dummy;		/* included in union to ensure alignment */
100} small_pool_hdr;
101
102typedef union large_pool_struct FAR * large_pool_ptr;
103
104typedef union large_pool_struct {
105  struct {
106    large_pool_ptr next;	/* next in list of pools */
107    size_t bytes_used;		/* how many bytes already used within pool */
108    size_t bytes_left;		/* bytes still available in this pool */
109  } hdr;
110  ALIGN_TYPE dummy;		/* included in union to ensure alignment */
111} large_pool_hdr;
112
113
114/*
115 * Here is the full definition of a memory manager object.
116 */
117
118typedef struct {
119  struct jpeg_memory_mgr pub;	/* public fields */
120
121  /* Each pool identifier (lifetime class) names a linked list of pools. */
122  small_pool_ptr small_list[JPOOL_NUMPOOLS];
123  large_pool_ptr large_list[JPOOL_NUMPOOLS];
124
125  /* Since we only have one lifetime class of virtual arrays, only one
126   * linked list is necessary (for each datatype).  Note that the virtual
127   * array control blocks being linked together are actually stored somewhere
128   * in the small-pool list.
129   */
130  jvirt_sarray_ptr virt_sarray_list;
131  jvirt_barray_ptr virt_barray_list;
132
133  /* This counts total space obtained from jpeg_get_small/large */
134  long total_space_allocated;
135
136  /* alloc_sarray and alloc_barray set this value for use by virtual
137   * array routines.
138   */
139  JDIMENSION last_rowsperchunk;	/* from most recent alloc_sarray/barray */
140} my_memory_mgr;
141
142typedef my_memory_mgr * my_mem_ptr;
143
144
145/*
146 * The control blocks for virtual arrays.
147 * Note that these blocks are allocated in the "small" pool area.
148 * System-dependent info for the associated backing store (if any) is hidden
149 * inside the backing_store_info struct.
150 */
151
152struct jvirt_sarray_control {
153  JSAMPARRAY mem_buffer;	/* => the in-memory buffer */
154  JDIMENSION rows_in_array;	/* total virtual array height */
155  JDIMENSION samplesperrow;	/* width of array (and of memory buffer) */
156  JDIMENSION maxaccess;		/* max rows accessed by access_virt_sarray */
157  JDIMENSION rows_in_mem;	/* height of memory buffer */
158  JDIMENSION rowsperchunk;	/* allocation chunk size in mem_buffer */
159  JDIMENSION cur_start_row;	/* first logical row # in the buffer */
160  JDIMENSION first_undef_row;	/* row # of first uninitialized row */
161  boolean pre_zero;		/* pre-zero mode requested? */
162  boolean dirty;		/* do current buffer contents need written? */
163  boolean b_s_open;		/* is backing-store data valid? */
164  jvirt_sarray_ptr next;	/* link to next virtual sarray control block */
165  backing_store_info b_s_info;	/* System-dependent control info */
166};
167
168struct jvirt_barray_control {
169  JBLOCKARRAY mem_buffer;	/* => the in-memory buffer */
170  JDIMENSION rows_in_array;	/* total virtual array height */
171  JDIMENSION blocksperrow;	/* width of array (and of memory buffer) */
172  JDIMENSION maxaccess;		/* max rows accessed by access_virt_barray */
173  JDIMENSION rows_in_mem;	/* height of memory buffer */
174  JDIMENSION rowsperchunk;	/* allocation chunk size in mem_buffer */
175  JDIMENSION cur_start_row;	/* first logical row # in the buffer */
176  JDIMENSION first_undef_row;	/* row # of first uninitialized row */
177  boolean pre_zero;		/* pre-zero mode requested? */
178  boolean dirty;		/* do current buffer contents need written? */
179  boolean b_s_open;		/* is backing-store data valid? */
180  jvirt_barray_ptr next;	/* link to next virtual barray control block */
181  backing_store_info b_s_info;	/* System-dependent control info */
182};
183
184
185#ifdef MEM_STATS		/* optional extra stuff for statistics */
186
187LOCAL(void)
188print_mem_stats (j_common_ptr cinfo, int pool_id)
189{
190  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
191  small_pool_ptr shdr_ptr;
192  large_pool_ptr lhdr_ptr;
193
194  /* Since this is only a debugging stub, we can cheat a little by using
195   * fprintf directly rather than going through the trace message code.
196   * This is helpful because message parm array can't handle longs.
197   */
198  FXSYS_fprintf(stderr, "Freeing pool %d, total space = %ld\n",
199	  pool_id, mem->total_space_allocated);
200
201  for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
202       lhdr_ptr = lhdr_ptr->hdr.next) {
203    FXSYS_fprintf(stderr, "  Large chunk used %ld\n",
204	    (long) lhdr_ptr->hdr.bytes_used);
205  }
206
207  for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
208       shdr_ptr = shdr_ptr->hdr.next) {
209    FXSYS_fprintf(stderr, "  Small chunk used %ld free %ld\n",
210	    (long) shdr_ptr->hdr.bytes_used,
211	    (long) shdr_ptr->hdr.bytes_left);
212  }
213}
214
215#endif /* MEM_STATS */
216
217
218LOCAL(void)
219out_of_memory (j_common_ptr cinfo, int which)
220/* Report an out-of-memory error and stop execution */
221/* If we compiled MEM_STATS support, report alloc requests before dying */
222{
223#ifdef MEM_STATS
224  cinfo->err->trace_level = 2;	/* force self_destruct to report stats */
225#endif
226  ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
227}
228
229
230/*
231 * Allocation of "small" objects.
232 *
233 * For these, we use pooled storage.  When a new pool must be created,
234 * we try to get enough space for the current request plus a "slop" factor,
235 * where the slop will be the amount of leftover space in the new pool.
236 * The speed vs. space tradeoff is largely determined by the slop values.
237 * A different slop value is provided for each pool class (lifetime),
238 * and we also distinguish the first pool of a class from later ones.
239 * NOTE: the values given work fairly well on both 16- and 32-bit-int
240 * machines, but may be too small if longs are 64 bits or more.
241 */
242
243static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
244{
245	1600,			/* first PERMANENT pool */
246	16000			/* first IMAGE pool */
247};
248
249static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
250{
251	0,			/* additional PERMANENT pools */
252	5000			/* additional IMAGE pools */
253};
254
255#define MIN_SLOP  50		/* greater than 0 to avoid futile looping */
256
257
258METHODDEF(void *)
259alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
260/* Allocate a "small" object */
261{
262  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
263  small_pool_ptr hdr_ptr, prev_hdr_ptr;
264  char * data_ptr;
265  size_t odd_bytes, min_request, slop;
266
267  /* Check for unsatisfiable request (do now to ensure no overflow below) */
268  if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
269    out_of_memory(cinfo, 1);	/* request exceeds malloc's ability */
270
271  /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
272  odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
273  if (odd_bytes > 0)
274    sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
275
276  /* See if space is available in any existing pool */
277  if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
278    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
279  prev_hdr_ptr = NULL;
280  hdr_ptr = mem->small_list[pool_id];
281  while (hdr_ptr != NULL) {
282    if (hdr_ptr->hdr.bytes_left >= sizeofobject)
283      break;			/* found pool with enough space */
284    prev_hdr_ptr = hdr_ptr;
285    hdr_ptr = hdr_ptr->hdr.next;
286  }
287
288  /* Time to make a new pool? */
289  if (hdr_ptr == NULL) {
290    /* min_request is what we need now, slop is what will be leftover */
291    min_request = sizeofobject + SIZEOF(small_pool_hdr);
292    if (prev_hdr_ptr == NULL)	/* first pool in class? */
293      slop = first_pool_slop[pool_id];
294    else
295      slop = extra_pool_slop[pool_id];
296    /* Don't ask for more than MAX_ALLOC_CHUNK */
297    if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
298      slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
299    /* Try to get space, if fail reduce slop and try again */
300    for (;;) {
301      hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
302      if (hdr_ptr != NULL)
303	break;
304      slop /= 2;
305      if (slop < MIN_SLOP)	/* give up when it gets real small */
306	out_of_memory(cinfo, 2); /* jpeg_get_small failed */
307    }
308    mem->total_space_allocated += min_request + slop;
309    /* Success, initialize the new pool header and add to end of list */
310    hdr_ptr->hdr.next = NULL;
311    hdr_ptr->hdr.bytes_used = 0;
312    hdr_ptr->hdr.bytes_left = sizeofobject + slop;
313    if (prev_hdr_ptr == NULL)	/* first pool in class? */
314      mem->small_list[pool_id] = hdr_ptr;
315    else
316      prev_hdr_ptr->hdr.next = hdr_ptr;
317  }
318
319  /* OK, allocate the object from the current pool */
320  data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
321  data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
322  hdr_ptr->hdr.bytes_used += sizeofobject;
323  hdr_ptr->hdr.bytes_left -= sizeofobject;
324
325  return (void *) data_ptr;
326}
327
328
329/*
330 * Allocation of "large" objects.
331 *
332 * The external semantics of these are the same as "small" objects,
333 * except that FAR pointers are used on 80x86.  However the pool
334 * management heuristics are quite different.  We assume that each
335 * request is large enough that it may as well be passed directly to
336 * jpeg_get_large; the pool management just links everything together
337 * so that we can free it all on demand.
338 * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
339 * structures.  The routines that create these structures (see below)
340 * deliberately bunch rows together to ensure a large request size.
341 */
342
343METHODDEF(void FAR *)
344alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
345/* Allocate a "large" object */
346{
347  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
348  large_pool_ptr hdr_ptr;
349  size_t odd_bytes;
350
351  /* Check for unsatisfiable request (do now to ensure no overflow below) */
352  if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
353    out_of_memory(cinfo, 3);	/* request exceeds malloc's ability */
354
355  /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
356  odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
357  if (odd_bytes > 0)
358    sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
359
360  /* Always make a new pool */
361  if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
362    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
363
364  hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
365					    SIZEOF(large_pool_hdr));
366  if (hdr_ptr == NULL)
367    out_of_memory(cinfo, 4);	/* jpeg_get_large failed */
368  mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
369
370  /* Success, initialize the new pool header and add to list */
371  hdr_ptr->hdr.next = mem->large_list[pool_id];
372  /* We maintain space counts in each pool header for statistical purposes,
373   * even though they are not needed for allocation.
374   */
375  hdr_ptr->hdr.bytes_used = sizeofobject;
376  hdr_ptr->hdr.bytes_left = 0;
377  mem->large_list[pool_id] = hdr_ptr;
378
379  return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
380}
381
382
383/*
384 * Creation of 2-D sample arrays.
385 * The pointers are in near heap, the samples themselves in FAR heap.
386 *
387 * To minimize allocation overhead and to allow I/O of large contiguous
388 * blocks, we allocate the sample rows in groups of as many rows as possible
389 * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
390 * NB: the virtual array control routines, later in this file, know about
391 * this chunking of rows.  The rowsperchunk value is left in the mem manager
392 * object so that it can be saved away if this sarray is the workspace for
393 * a virtual array.
394 */
395
396METHODDEF(JSAMPARRAY)
397alloc_sarray (j_common_ptr cinfo, int pool_id,
398	      JDIMENSION samplesperrow, JDIMENSION numrows)
399/* Allocate a 2-D sample array */
400{
401  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
402  JSAMPARRAY result;
403  JSAMPROW workspace;
404  JDIMENSION rowsperchunk, currow, i;
405  long ltemp;
406
407  /* Calculate max # of rows allowed in one allocation chunk */
408  ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
409	  ((long) samplesperrow * SIZEOF(JSAMPLE));
410  if (ltemp <= 0)
411    ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
412  if (ltemp < (long) numrows)
413    rowsperchunk = (JDIMENSION) ltemp;
414  else
415    rowsperchunk = numrows;
416  mem->last_rowsperchunk = rowsperchunk;
417
418  /* Get space for row pointers (small object) */
419  result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
420				    (size_t) (numrows * SIZEOF(JSAMPROW)));
421
422  /* Get the rows themselves (large objects) */
423  currow = 0;
424  while (currow < numrows) {
425    rowsperchunk = MIN(rowsperchunk, numrows - currow);
426    workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
427	(size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
428		  * SIZEOF(JSAMPLE)));
429    for (i = rowsperchunk; i > 0; i--) {
430      result[currow++] = workspace;
431      workspace += samplesperrow;
432    }
433  }
434
435  return result;
436}
437
438
439/*
440 * Creation of 2-D coefficient-block arrays.
441 * This is essentially the same as the code for sample arrays, above.
442 */
443
444METHODDEF(JBLOCKARRAY)
445alloc_barray (j_common_ptr cinfo, int pool_id,
446	      JDIMENSION blocksperrow, JDIMENSION numrows)
447/* Allocate a 2-D coefficient-block array */
448{
449  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
450  JBLOCKARRAY result;
451  JBLOCKROW workspace;
452  JDIMENSION rowsperchunk, currow, i;
453  long ltemp;
454
455  /* Calculate max # of rows allowed in one allocation chunk */
456  ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
457	  ((long) blocksperrow * SIZEOF(JBLOCK));
458  if (ltemp <= 0)
459    ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
460  if (ltemp < (long) numrows)
461    rowsperchunk = (JDIMENSION) ltemp;
462  else
463    rowsperchunk = numrows;
464  mem->last_rowsperchunk = rowsperchunk;
465
466  /* Get space for row pointers (small object) */
467  result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
468				     (size_t) (numrows * SIZEOF(JBLOCKROW)));
469
470  /* Get the rows themselves (large objects) */
471  currow = 0;
472  while (currow < numrows) {
473    rowsperchunk = MIN(rowsperchunk, numrows - currow);
474    workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
475	(size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
476		  * SIZEOF(JBLOCK)));
477    for (i = rowsperchunk; i > 0; i--) {
478      result[currow++] = workspace;
479      workspace += blocksperrow;
480    }
481  }
482
483  return result;
484}
485
486
487/*
488 * About virtual array management:
489 *
490 * The above "normal" array routines are only used to allocate strip buffers
491 * (as wide as the image, but just a few rows high).  Full-image-sized buffers
492 * are handled as "virtual" arrays.  The array is still accessed a strip at a
493 * time, but the memory manager must save the whole array for repeated
494 * accesses.  The intended implementation is that there is a strip buffer in
495 * memory (as high as is possible given the desired memory limit), plus a
496 * backing file that holds the rest of the array.
497 *
498 * The request_virt_array routines are told the total size of the image and
499 * the maximum number of rows that will be accessed at once.  The in-memory
500 * buffer must be at least as large as the maxaccess value.
501 *
502 * The request routines create control blocks but not the in-memory buffers.
503 * That is postponed until realize_virt_arrays is called.  At that time the
504 * total amount of space needed is known (approximately, anyway), so free
505 * memory can be divided up fairly.
506 *
507 * The access_virt_array routines are responsible for making a specific strip
508 * area accessible (after reading or writing the backing file, if necessary).
509 * Note that the access routines are told whether the caller intends to modify
510 * the accessed strip; during a read-only pass this saves having to rewrite
511 * data to disk.  The access routines are also responsible for pre-zeroing
512 * any newly accessed rows, if pre-zeroing was requested.
513 *
514 * In current usage, the access requests are usually for nonoverlapping
515 * strips; that is, successive access start_row numbers differ by exactly
516 * num_rows = maxaccess.  This means we can get good performance with simple
517 * buffer dump/reload logic, by making the in-memory buffer be a multiple
518 * of the access height; then there will never be accesses across bufferload
519 * boundaries.  The code will still work with overlapping access requests,
520 * but it doesn't handle bufferload overlaps very efficiently.
521 */
522
523
524METHODDEF(jvirt_sarray_ptr)
525request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
526		     JDIMENSION samplesperrow, JDIMENSION numrows,
527		     JDIMENSION maxaccess)
528/* Request a virtual 2-D sample array */
529{
530  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
531  jvirt_sarray_ptr result;
532
533  /* Only IMAGE-lifetime virtual arrays are currently supported */
534  if (pool_id != JPOOL_IMAGE)
535    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
536
537  /* get control block */
538  result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
539					  SIZEOF(struct jvirt_sarray_control));
540
541  result->mem_buffer = NULL;	/* marks array not yet realized */
542  result->rows_in_array = numrows;
543  result->samplesperrow = samplesperrow;
544  result->maxaccess = maxaccess;
545  result->pre_zero = pre_zero;
546  result->b_s_open = FALSE;	/* no associated backing-store object */
547  result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
548  mem->virt_sarray_list = result;
549
550  return result;
551}
552
553
554METHODDEF(jvirt_barray_ptr)
555request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
556		     JDIMENSION blocksperrow, JDIMENSION numrows,
557		     JDIMENSION maxaccess)
558/* Request a virtual 2-D coefficient-block array */
559{
560  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
561  jvirt_barray_ptr result;
562
563  /* Only IMAGE-lifetime virtual arrays are currently supported */
564  if (pool_id != JPOOL_IMAGE)
565    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
566
567  /* get control block */
568  result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
569					  SIZEOF(struct jvirt_barray_control));
570
571  result->mem_buffer = NULL;	/* marks array not yet realized */
572  result->rows_in_array = numrows;
573  result->blocksperrow = blocksperrow;
574  result->maxaccess = maxaccess;
575  result->pre_zero = pre_zero;
576  result->b_s_open = FALSE;	/* no associated backing-store object */
577  result->next = mem->virt_barray_list; /* add to list of virtual arrays */
578  mem->virt_barray_list = result;
579
580  return result;
581}
582
583
584METHODDEF(void)
585realize_virt_arrays (j_common_ptr cinfo)
586/* Allocate the in-memory buffers for any unrealized virtual arrays */
587{
588  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
589  long space_per_minheight, maximum_space, avail_mem;
590  long minheights, max_minheights;
591  jvirt_sarray_ptr sptr;
592  jvirt_barray_ptr bptr;
593
594  /* Compute the minimum space needed (maxaccess rows in each buffer)
595   * and the maximum space needed (full image height in each buffer).
596   * These may be of use to the system-dependent jpeg_mem_available routine.
597   */
598  space_per_minheight = 0;
599  maximum_space = 0;
600  for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
601    if (sptr->mem_buffer == NULL) { /* if not realized yet */
602      space_per_minheight += (long) sptr->maxaccess *
603			     (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
604      maximum_space += (long) sptr->rows_in_array *
605		       (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
606    }
607  }
608  for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
609    if (bptr->mem_buffer == NULL) { /* if not realized yet */
610      space_per_minheight += (long) bptr->maxaccess *
611			     (long) bptr->blocksperrow * SIZEOF(JBLOCK);
612      maximum_space += (long) bptr->rows_in_array *
613		       (long) bptr->blocksperrow * SIZEOF(JBLOCK);
614    }
615  }
616
617  if (space_per_minheight <= 0)
618    return;			/* no unrealized arrays, no work */
619
620  /* Determine amount of memory to actually use; this is system-dependent. */
621  avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
622				 mem->total_space_allocated);
623
624  /* If the maximum space needed is available, make all the buffers full
625   * height; otherwise parcel it out with the same number of minheights
626   * in each buffer.
627   */
628  if (avail_mem >= maximum_space)
629    max_minheights = 1000000000L;
630  else {
631    max_minheights = avail_mem / space_per_minheight;
632    /* If there doesn't seem to be enough space, try to get the minimum
633     * anyway.  This allows a "stub" implementation of jpeg_mem_available().
634     */
635    if (max_minheights <= 0)
636      max_minheights = 1;
637  }
638
639  /* Allocate the in-memory buffers and initialize backing store as needed. */
640
641  for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
642    if (sptr->mem_buffer == NULL) { /* if not realized yet */
643      minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
644      if (minheights <= max_minheights) {
645	/* This buffer fits in memory */
646	sptr->rows_in_mem = sptr->rows_in_array;
647      } else {
648	/* It doesn't fit in memory, create backing store. */
649	sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
650	jpeg_open_backing_store(cinfo, & sptr->b_s_info,
651				(long) sptr->rows_in_array *
652				(long) sptr->samplesperrow *
653				(long) SIZEOF(JSAMPLE));
654	sptr->b_s_open = TRUE;
655      }
656      sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
657				      sptr->samplesperrow, sptr->rows_in_mem);
658      sptr->rowsperchunk = mem->last_rowsperchunk;
659      sptr->cur_start_row = 0;
660      sptr->first_undef_row = 0;
661      sptr->dirty = FALSE;
662    }
663  }
664
665  for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
666    if (bptr->mem_buffer == NULL) { /* if not realized yet */
667      minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
668      if (minheights <= max_minheights) {
669	/* This buffer fits in memory */
670	bptr->rows_in_mem = bptr->rows_in_array;
671      } else {
672	/* It doesn't fit in memory, create backing store. */
673	bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
674	jpeg_open_backing_store(cinfo, & bptr->b_s_info,
675				(long) bptr->rows_in_array *
676				(long) bptr->blocksperrow *
677				(long) SIZEOF(JBLOCK));
678	bptr->b_s_open = TRUE;
679      }
680      bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
681				      bptr->blocksperrow, bptr->rows_in_mem);
682      bptr->rowsperchunk = mem->last_rowsperchunk;
683      bptr->cur_start_row = 0;
684      bptr->first_undef_row = 0;
685      bptr->dirty = FALSE;
686    }
687  }
688}
689
690
691LOCAL(void)
692do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
693/* Do backing store read or write of a virtual sample array */
694{
695  long bytesperrow, file_offset, byte_count, rows, thisrow, i;
696
697  bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
698  file_offset = ptr->cur_start_row * bytesperrow;
699  /* Loop to read or write each allocation chunk in mem_buffer */
700  for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
701    /* One chunk, but check for short chunk at end of buffer */
702    rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
703    /* Transfer no more than is currently defined */
704    thisrow = (long) ptr->cur_start_row + i;
705    rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
706    /* Transfer no more than fits in file */
707    rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
708    if (rows <= 0)		/* this chunk might be past end of file! */
709      break;
710    byte_count = rows * bytesperrow;
711    if (writing)
712      (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
713					    (void FAR *) ptr->mem_buffer[i],
714					    file_offset, byte_count);
715    else
716      (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
717					   (void FAR *) ptr->mem_buffer[i],
718					   file_offset, byte_count);
719    file_offset += byte_count;
720  }
721}
722
723
724LOCAL(void)
725do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
726/* Do backing store read or write of a virtual coefficient-block array */
727{
728  long bytesperrow, file_offset, byte_count, rows, thisrow, i;
729
730  bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
731  file_offset = ptr->cur_start_row * bytesperrow;
732  /* Loop to read or write each allocation chunk in mem_buffer */
733  for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
734    /* One chunk, but check for short chunk at end of buffer */
735    rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
736    /* Transfer no more than is currently defined */
737    thisrow = (long) ptr->cur_start_row + i;
738    rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
739    /* Transfer no more than fits in file */
740    rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
741    if (rows <= 0)		/* this chunk might be past end of file! */
742      break;
743    byte_count = rows * bytesperrow;
744    if (writing)
745      (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
746					    (void FAR *) ptr->mem_buffer[i],
747					    file_offset, byte_count);
748    else
749      (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
750					   (void FAR *) ptr->mem_buffer[i],
751					   file_offset, byte_count);
752    file_offset += byte_count;
753  }
754}
755
756
757METHODDEF(JSAMPARRAY)
758access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
759		    JDIMENSION start_row, JDIMENSION num_rows,
760		    boolean writable)
761/* Access the part of a virtual sample array starting at start_row */
762/* and extending for num_rows rows.  writable is true if  */
763/* caller intends to modify the accessed area. */
764{
765  JDIMENSION end_row = start_row + num_rows;
766  JDIMENSION undef_row;
767
768  /* debugging check */
769  if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
770      ptr->mem_buffer == NULL)
771    ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
772
773  /* Make the desired part of the virtual array accessible */
774  if (start_row < ptr->cur_start_row ||
775      end_row > ptr->cur_start_row+ptr->rows_in_mem) {
776    if (! ptr->b_s_open)
777      ERREXIT(cinfo, JERR_VIRTUAL_BUG);
778    /* Flush old buffer contents if necessary */
779    if (ptr->dirty) {
780      do_sarray_io(cinfo, ptr, TRUE);
781      ptr->dirty = FALSE;
782    }
783    /* Decide what part of virtual array to access.
784     * Algorithm: if target address > current window, assume forward scan,
785     * load starting at target address.  If target address < current window,
786     * assume backward scan, load so that target area is top of window.
787     * Note that when switching from forward write to forward read, will have
788     * start_row = 0, so the limiting case applies and we load from 0 anyway.
789     */
790    if (start_row > ptr->cur_start_row) {
791      ptr->cur_start_row = start_row;
792    } else {
793      /* use long arithmetic here to avoid overflow & unsigned problems */
794      long ltemp;
795
796      ltemp = (long) end_row - (long) ptr->rows_in_mem;
797      if (ltemp < 0)
798	ltemp = 0;		/* don't fall off front end of file */
799      ptr->cur_start_row = (JDIMENSION) ltemp;
800    }
801    /* Read in the selected part of the array.
802     * During the initial write pass, we will do no actual read
803     * because the selected part is all undefined.
804     */
805    do_sarray_io(cinfo, ptr, FALSE);
806  }
807  /* Ensure the accessed part of the array is defined; prezero if needed.
808   * To improve locality of access, we only prezero the part of the array
809   * that the caller is about to access, not the entire in-memory array.
810   */
811  if (ptr->first_undef_row < end_row) {
812    if (ptr->first_undef_row < start_row) {
813      if (writable)		/* writer skipped over a section of array */
814	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
815      undef_row = start_row;	/* but reader is allowed to read ahead */
816    } else {
817      undef_row = ptr->first_undef_row;
818    }
819    if (writable)
820      ptr->first_undef_row = end_row;
821    if (ptr->pre_zero) {
822      size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
823      undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
824      end_row -= ptr->cur_start_row;
825      while (undef_row < end_row) {
826	jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
827	undef_row++;
828      }
829    } else {
830      if (! writable)		/* reader looking at undefined data */
831	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
832    }
833  }
834  /* Flag the buffer dirty if caller will write in it */
835  if (writable)
836    ptr->dirty = TRUE;
837  /* Return address of proper part of the buffer */
838  return ptr->mem_buffer + (start_row - ptr->cur_start_row);
839}
840
841
842METHODDEF(JBLOCKARRAY)
843access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
844		    JDIMENSION start_row, JDIMENSION num_rows,
845		    boolean writable)
846/* Access the part of a virtual block array starting at start_row */
847/* and extending for num_rows rows.  writable is true if  */
848/* caller intends to modify the accessed area. */
849{
850  JDIMENSION end_row = start_row + num_rows;
851  JDIMENSION undef_row;
852
853  /* debugging check */
854  if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
855      ptr->mem_buffer == NULL)
856    ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
857
858  /* Make the desired part of the virtual array accessible */
859  if (start_row < ptr->cur_start_row ||
860      end_row > ptr->cur_start_row+ptr->rows_in_mem) {
861    if (! ptr->b_s_open)
862      ERREXIT(cinfo, JERR_VIRTUAL_BUG);
863    /* Flush old buffer contents if necessary */
864    if (ptr->dirty) {
865      do_barray_io(cinfo, ptr, TRUE);
866      ptr->dirty = FALSE;
867    }
868    /* Decide what part of virtual array to access.
869     * Algorithm: if target address > current window, assume forward scan,
870     * load starting at target address.  If target address < current window,
871     * assume backward scan, load so that target area is top of window.
872     * Note that when switching from forward write to forward read, will have
873     * start_row = 0, so the limiting case applies and we load from 0 anyway.
874     */
875    if (start_row > ptr->cur_start_row) {
876      ptr->cur_start_row = start_row;
877    } else {
878      /* use long arithmetic here to avoid overflow & unsigned problems */
879      long ltemp;
880
881      ltemp = (long) end_row - (long) ptr->rows_in_mem;
882      if (ltemp < 0)
883	ltemp = 0;		/* don't fall off front end of file */
884      ptr->cur_start_row = (JDIMENSION) ltemp;
885    }
886    /* Read in the selected part of the array.
887     * During the initial write pass, we will do no actual read
888     * because the selected part is all undefined.
889     */
890    do_barray_io(cinfo, ptr, FALSE);
891  }
892  /* Ensure the accessed part of the array is defined; prezero if needed.
893   * To improve locality of access, we only prezero the part of the array
894   * that the caller is about to access, not the entire in-memory array.
895   */
896  if (ptr->first_undef_row < end_row) {
897    if (ptr->first_undef_row < start_row) {
898      if (writable)		/* writer skipped over a section of array */
899	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
900      undef_row = start_row;	/* but reader is allowed to read ahead */
901    } else {
902      undef_row = ptr->first_undef_row;
903    }
904    if (writable)
905      ptr->first_undef_row = end_row;
906    if (ptr->pre_zero) {
907      size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
908      undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
909      end_row -= ptr->cur_start_row;
910      while (undef_row < end_row) {
911	jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
912	undef_row++;
913      }
914    } else {
915      if (! writable)		/* reader looking at undefined data */
916	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
917    }
918  }
919  /* Flag the buffer dirty if caller will write in it */
920  if (writable)
921    ptr->dirty = TRUE;
922  /* Return address of proper part of the buffer */
923  return ptr->mem_buffer + (start_row - ptr->cur_start_row);
924}
925
926
927/*
928 * Release all objects belonging to a specified pool.
929 */
930
931METHODDEF(void)
932free_pool (j_common_ptr cinfo, int pool_id)
933{
934  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
935  small_pool_ptr shdr_ptr;
936  large_pool_ptr lhdr_ptr;
937  size_t space_freed;
938
939  if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
940    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
941
942#ifdef MEM_STATS
943  if (cinfo->err->trace_level > 1)
944    print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
945#endif
946
947  /* If freeing IMAGE pool, close any virtual arrays first */
948  if (pool_id == JPOOL_IMAGE) {
949    jvirt_sarray_ptr sptr;
950    jvirt_barray_ptr bptr;
951
952    for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
953      if (sptr->b_s_open) {	/* there may be no backing store */
954	sptr->b_s_open = FALSE;	/* prevent recursive close if error */
955	(*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
956      }
957    }
958    mem->virt_sarray_list = NULL;
959    for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
960      if (bptr->b_s_open) {	/* there may be no backing store */
961	bptr->b_s_open = FALSE;	/* prevent recursive close if error */
962	(*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
963      }
964    }
965    mem->virt_barray_list = NULL;
966  }
967
968  /* Release large objects */
969  lhdr_ptr = mem->large_list[pool_id];
970  mem->large_list[pool_id] = NULL;
971
972  while (lhdr_ptr != NULL) {
973    large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
974    space_freed = lhdr_ptr->hdr.bytes_used +
975		  lhdr_ptr->hdr.bytes_left +
976		  SIZEOF(large_pool_hdr);
977    jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
978    mem->total_space_allocated -= space_freed;
979    lhdr_ptr = next_lhdr_ptr;
980  }
981
982  /* Release small objects */
983  shdr_ptr = mem->small_list[pool_id];
984  mem->small_list[pool_id] = NULL;
985
986  while (shdr_ptr != NULL) {
987    small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
988    space_freed = shdr_ptr->hdr.bytes_used +
989		  shdr_ptr->hdr.bytes_left +
990		  SIZEOF(small_pool_hdr);
991    jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
992    mem->total_space_allocated -= space_freed;
993    shdr_ptr = next_shdr_ptr;
994  }
995}
996
997
998/*
999 * Close up shop entirely.
1000 * Note that this cannot be called unless cinfo->mem is non-NULL.
1001 */
1002
1003METHODDEF(void)
1004self_destruct (j_common_ptr cinfo)
1005{
1006  int pool;
1007
1008  /* Close all backing store, release all memory.
1009   * Releasing pools in reverse order might help avoid fragmentation
1010   * with some (brain-damaged) malloc libraries.
1011   */
1012  for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
1013    free_pool(cinfo, pool);
1014  }
1015
1016  /* Release the memory manager control block too. */
1017  jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
1018  cinfo->mem = NULL;		/* ensures I will be called only once */
1019
1020  jpeg_mem_term(cinfo);		/* system-dependent cleanup */
1021}
1022
1023
1024/*
1025 * Memory manager initialization.
1026 * When this is called, only the error manager pointer is valid in cinfo!
1027 */
1028
1029GLOBAL(void)
1030jinit_memory_mgr (j_common_ptr cinfo)
1031{
1032  my_mem_ptr mem;
1033  long max_to_use;
1034  int pool;
1035  size_t test_mac;
1036
1037  cinfo->mem = NULL;		/* for safety if init fails */
1038
1039  /* Check for configuration errors.
1040   * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
1041   * doesn't reflect any real hardware alignment requirement.
1042   * The test is a little tricky: for X>0, X and X-1 have no one-bits
1043   * in common if and only if X is a power of 2, ie has only one one-bit.
1044   * Some compilers may give an "unreachable code" warning here; ignore it.
1045   */
1046  if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
1047    ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
1048  /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
1049   * a multiple of SIZEOF(ALIGN_TYPE).
1050   * Again, an "unreachable code" warning may be ignored here.
1051   * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
1052   */
1053  test_mac = (size_t) MAX_ALLOC_CHUNK;
1054  if ((long) test_mac != MAX_ALLOC_CHUNK ||
1055      (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
1056    ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
1057
1058  max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
1059
1060  /* Attempt to allocate memory manager's control block */
1061  mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
1062
1063  if (mem == NULL) {
1064    jpeg_mem_term(cinfo);	/* system-dependent cleanup */
1065    ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
1066  }
1067
1068  /* OK, fill in the method pointers */
1069  mem->pub.alloc_small = alloc_small;
1070  mem->pub.alloc_large = alloc_large;
1071  mem->pub.alloc_sarray = alloc_sarray;
1072  mem->pub.alloc_barray = alloc_barray;
1073  mem->pub.request_virt_sarray = request_virt_sarray;
1074  mem->pub.request_virt_barray = request_virt_barray;
1075  mem->pub.realize_virt_arrays = realize_virt_arrays;
1076  mem->pub.access_virt_sarray = access_virt_sarray;
1077  mem->pub.access_virt_barray = access_virt_barray;
1078  mem->pub.free_pool = free_pool;
1079  mem->pub.self_destruct = self_destruct;
1080
1081  /* Make MAX_ALLOC_CHUNK accessible to other modules */
1082  mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
1083
1084  /* Initialize working state */
1085  mem->pub.max_memory_to_use = max_to_use;
1086
1087  for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
1088    mem->small_list[pool] = NULL;
1089    mem->large_list[pool] = NULL;
1090  }
1091  mem->virt_sarray_list = NULL;
1092  mem->virt_barray_list = NULL;
1093
1094  mem->total_space_allocated = SIZEOF(my_memory_mgr);
1095
1096  /* Declare ourselves open for business */
1097  cinfo->mem = & mem->pub;
1098
1099  /* Check for an environment variable JPEGMEM; if found, override the
1100   * default max_memory setting from jpeg_mem_init.  Note that the
1101   * surrounding application may again override this value.
1102   * If your system doesn't support getenv(), define NO_GETENV to disable
1103   * this feature.
1104   */
1105#ifndef NO_GETENV
1106  { char * memenv;
1107
1108    if ((memenv = getenv("JPEGMEM")) != NULL) {
1109      char ch = 'x';
1110
1111      if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
1112	if (ch == 'm' || ch == 'M')
1113	  max_to_use *= 1000L;
1114	mem->pub.max_memory_to_use = max_to_use * 1000L;
1115      }
1116    }
1117  }
1118#endif
1119
1120}
1121