3 { This file contains the JPEG system-independent memory management
4 routines. This code is usable across a wide variety of machines; most
5 of the system dependencies have been isolated in a separate file.
6 The major functions provided here are:
7 * pool-based allocation and freeing of memory;
8 * policy decisions about how to divide available memory among the
9 virtual arrays;
10 * control logic for swapping virtual arrays between main memory and
11 backing storage.
12 The separate system-dependent file provides the actual backing-storage
13 access code, and it contains the policy decision about how much total
14 main memory to use.
15 This file is system-dependent in the sense that some of its functions
16 are unnecessary in some systems. For example, if there is enough virtual
17 memory so that backing storage will never be used, much of the virtual
18 array control logic could be removed. (Of course, if you have that much
19 memory then you shouldn't care about a little bit of unused code...) }
21 { Original : jmemmgr.c ; Copyright (C) 1991-1997, Thomas G. Lane. }
23 interface
25 {$I imjconfig.inc}
27 uses
28 imjmorecfg,
29 imjinclude,
30 imjdeferr,
31 imjerror,
32 imjpeglib,
33 imjutils,
34 {$IFDEF VER70}
35 {$ifndef NO_GETENV}
37 { function GetEnv(name : string) : string; }
38 {$endif}
40 {$ELSE}
41 imjmemnobs;
42 {$DEFINE NO_GETENV}
43 {$ENDIF}
45 { Memory manager initialization.
46 When this is called, only the error manager pointer is valid in cinfo! }
48 {GLOBAL}
51 implementation
54 { Some important notes:
55 The allocation routines provided here must never return NIL.
56 They should exit to error_exit if unsuccessful.
58 It's not a good idea to try to merge the sarray and barray routines,
59 even though they are textually almost the same, because samples are
60 usually stored as bytes while coefficients are shorts or ints. Thus,
61 in machines where byte pointers have a different representation from
62 word pointers, the resulting machine code could not be the same. }
65 { Many machines require storage alignment: longs must start on 4-byte
66 boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
67 always returns pointers that are multiples of the worst-case alignment
68 requirement, and we had better do so too.
69 There isn't any really portable way to determine the worst-case alignment
70 requirement. This module assumes that the alignment requirement is
71 multiples of sizeof(ALIGN_TYPE).
72 By default, we define ALIGN_TYPE as double. This is necessary on some
73 workstations (where doubles really do need 8-byte alignment) and will work
74 fine on nearly everything. If your machine has lesser alignment needs,
75 you can save a few bytes by making ALIGN_TYPE smaller.
76 The only place I know of where this will NOT work is certain Macintosh
77 680x0 compilers that define double as a 10-byte IEEE extended float.
78 Doing 10-byte alignment is counterproductive because longwords won't be
79 aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
80 such a compiler. }
83 type
85 {$endif}
88 { We allocate objects from "pools", where each pool is gotten with a single
89 request to jpeg_get_small() or jpeg_get_large(). There is no per-object
90 overhead within a pool, except for alignment padding. Each pool has a
91 header with a link to the next pool of the same class.
92 Small and large pool headers are identical except that the latter's
93 link pointer must be FAR on 80x86 machines.
94 Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
95 field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
96 of the alignment requirement of ALIGN_TYPE. }
98 type
110 type
123 { Here is the full definition of a memory manager object. }
125 type
130 { Each pool identifier (lifetime class) names a linked list of pools. }
134 { Since we only have one lifetime class of virtual arrays, only one
135 linked list is necessary (for each datatype). Note that the virtual
136 array control blocks being linked together are actually stored somewhere
137 in the small-pool list. }
142 { This counts total space obtained from jpeg_get_small/large }
145 { alloc_sarray and alloc_barray set this value for use by virtual
146 array routines. }
153 { The control blocks for virtual arrays.
154 Note that these blocks are allocated in the "small" pool area.
155 System-dependent info for the associated backing store (if any) is hidden
156 inside the backing_store_info struct. }
157 type
193 {LOCAL}
195 var
199 begin
202 { Since this is only a debugging stub, we can cheat a little by using
203 fprintf directly rather than going through the trace message code.
204 This is helpful because message parm array can't handle longs. }
211 begin
220 begin
231 {LOCAL}
233 { Report an out-of-memory error and stop execution }
234 { If we compiled MEM_STATS support, report alloc requests before dying }
235 begin
236 {$ifdef MEM_STATS}
238 {$endif}
243 { Allocation of "small" objects.
245 For these, we use pooled storage. When a new pool must be created,
246 we try to get enough space for the current request plus a "slop" factor,
247 where the slop will be the amount of leftover space in the new pool.
248 The speed vs. space tradeoff is largely determined by the slop values.
249 A different slop value is provided for each pool class (lifetime),
250 and we also distinguish the first pool of a class from later ones.
251 NOTE: the values given work fairly well on both 16- and 32-bit-int
252 machines, but may be too small if longs are 64 bits or more. }
254 const
259 const
264 const
268 {METHODDEF}
272 type
274 { Allocate a "small" object }
275 var
280 begin
283 { Check for unsatisfiable request (do now to ensure no overflow below) }
287 { Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) }
292 { See if space is available in any existing pool }
298 begin
305 { Time to make a new pool? }
307 begin
308 { min_request is what we need now, slop is what will be leftover }
312 else
314 { Don't ask for more than MAX_ALLOC_CHUNK }
317 { Try to get space, if fail reduce slop and try again }
319 begin
322 break;
328 { Success, initialize the new pool header and add to end of list }
334 else
338 { OK, allocate the object from the current pool }
349 { Allocation of "large" objects.
351 The external semantics of these are the same as "small" objects,
352 except that FAR pointers are used on 80x86. However the pool
353 management heuristics are quite different. We assume that each
354 request is large enough that it may as well be passed directly to
355 jpeg_get_large; the pool management just links everything together
356 so that we can free it all on demand.
357 Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
358 structures. The routines that create these structures (see below)
359 deliberately bunch rows together to ensure a large request size. }
361 {METHODDEF}
365 { Allocate a "large" object }
366 var
370 var
372 begin
375 { Check for unsatisfiable request (do now to ensure no overflow below) }
379 { Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) }
384 { Always make a new pool }
394 { Success, initialize the new pool header and add to list }
396 { We maintain space counts in each pool header for statistical purposes,
397 even though they are not needed for allocation. }
403 {alloc_large := pointerFAR (hdr_ptr + 1); - point to first data byte in pool }
410 { Creation of 2-D sample arrays.
411 The pointers are in near heap, the samples themselves in FAR heap.
413 To minimize allocation overhead and to allow I/O of large contiguous
414 blocks, we allocate the sample rows in groups of as many rows as possible
415 without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
416 NB: the virtual array control routines, later in this file, know about
417 this chunking of rows. The rowsperchunk value is left in the mem manager
418 object so that it can be saved away if this sarray is the workspace for
419 a virtual array. }
421 {METHODDEF}
426 { Allocate a 2-D sample array }
427 var
433 begin
436 { Calculate max # of rows allowed in one allocation chunk }
443 else
447 { Get space for row pointers (small object) }
451 { Get the rows themselves (large objects) }
454 begin
455 {rowsperchunk := MIN(rowsperchunk, numrows - currow);}
463 begin
474 { Creation of 2-D coefficient-block arrays.
475 This is essentially the same as the code for sample arrays, above. }
477 {METHODDEF}
482 { Allocate a 2-D coefficient-block array }
483 var
489 begin
492 { Calculate max # of rows allowed in one allocation chunk }
500 else
504 { Get space for row pointers (small object) }
508 { Get the rows themselves (large objects) }
511 begin
512 {rowsperchunk := MIN(rowsperchunk, numrows - currow);}
520 begin
531 { About virtual array management:
533 The above "normal" array routines are only used to allocate strip buffers
534 (as wide as the image, but just a few rows high). Full-image-sized buffers
535 are handled as "virtual" arrays. The array is still accessed a strip at a
536 time, but the memory manager must save the whole array for repeated
537 accesses. The intended implementation is that there is a strip buffer in
538 memory (as high as is possible given the desired memory limit), plus a
539 backing file that holds the rest of the array.
541 The request_virt_array routines are told the total size of the image and
542 the maximum number of rows that will be accessed at once. The in-memory
543 buffer must be at least as large as the maxaccess value.
545 The request routines create control blocks but not the in-memory buffers.
546 That is postponed until realize_virt_arrays is called. At that time the
547 total amount of space needed is known (approximately, anyway), so free
548 memory can be divided up fairly.
550 The access_virt_array routines are responsible for making a specific strip
551 area accessible (after reading or writing the backing file, if necessary).
552 Note that the access routines are told whether the caller intends to modify
553 the accessed strip; during a read-only pass this saves having to rewrite
554 data to disk. The access routines are also responsible for pre-zeroing
555 any newly accessed rows, if pre-zeroing was requested.
557 In current usage, the access requests are usually for nonoverlapping
558 strips; that is, successive access start_row numbers differ by exactly
559 num_rows := maxaccess. This means we can get good performance with simple
560 buffer dump/reload logic, by making the in-memory buffer be a multiple
561 of the access height; then there will never be accesses across bufferload
562 boundaries. The code will still work with overlapping access requests,
563 but it doesn't handle bufferload overlaps very efficiently. }
566 {METHODDEF}
573 { Request a virtual 2-D sample array }
574 var
577 begin
580 { Only IMAGE-lifetime virtual arrays are currently supported }
584 { get control block }
601 {METHODDEF}
608 { Request a virtual 2-D coefficient-block array }
609 var
612 begin
615 { Only IMAGE-lifetime virtual arrays are currently supported }
619 { get control block }
636 {METHODDEF}
638 { Allocate the in-memory buffers for any unrealized virtual arrays }
639 var
645 begin
647 { Compute the minimum space needed (maxaccess rows in each buffer)
648 and the maximum space needed (full image height in each buffer).
649 These may be of use to the system-dependent jpeg_mem_available routine. }
655 begin
667 begin
681 { Determine amount of memory to actually use; this is system-dependent. }
685 { If the maximum space needed is available, make all the buffers full
686 height; otherwise parcel it out with the same number of minheights
687 in each buffer. }
691 else
692 begin
694 { If there doesn't seem to be enough space, try to get the minimum
695 anyway. This allows a "stub" implementation of jpeg_mem_available(). }
700 { Allocate the in-memory buffers and initialize backing store as needed. }
704 begin
709 begin
710 { This buffer fits in memory }
712 end
713 else
714 begin
715 { It doesn't fit in memory, create backing store. }
736 begin
741 begin
742 { This buffer fits in memory }
744 end
745 else
746 begin
747 { It doesn't fit in memory, create backing store. }
768 {LOCAL}
772 { Do backing store read or write of a virtual sample array }
773 var
775 begin
779 { Loop to read or write each allocation chunk in mem_buffer }
782 begin
784 { One chunk, but check for short chunk at end of buffer }
785 {rows := MIN(long(ptr^.rowsperchunk), long(ptr^.rows_in_mem - i));}
789 { Transfer no more than is currently defined }
791 {rows := MIN(rows, long(ptr^.first_undef_row) - thisrow);}
794 { Transfer no more than fits in file }
795 {rows := MIN(rows, long(ptr^.rows_in_array) - thisrow);}
800 break;
807 else
818 {LOCAL}
822 { Do backing store read or write of a virtual coefficient-block array }
823 var
825 begin
828 { Loop to read or write each allocation chunk in mem_buffer }
831 begin
832 { One chunk, but check for short chunk at end of buffer }
833 {rows := MIN(long(ptr^.rowsperchunk), long(ptr^.rows_in_mem - i));}
837 { Transfer no more than is currently defined }
839 {rows := MIN(rows, long(ptr^.first_undef_row - thisrow));}
842 { Transfer no more than fits in file }
843 {rows := MIN(rows, long (ptr^.rows_in_array - thisrow));}
848 break;
855 else
866 {METHODDEF}
872 { Access the part of a virtual sample array starting at start_row }
873 { and extending for num_rows rows. writable is true if }
874 { caller intends to modify the accessed area. }
875 var
878 var
880 var
882 begin
884 { debugging check }
889 { Make the desired part of the virtual array accessible }
892 begin
895 { Flush old buffer contents if necessary }
897 begin
901 { Decide what part of virtual array to access.
902 Algorithm: if target address > current window, assume forward scan,
903 load starting at target address. If target address < current window,
904 assume backward scan, load so that target area is top of window.
905 Note that when switching from forward write to forward read, will have
906 start_row := 0, so the limiting case applies and we load from 0 anyway. }
908 begin
910 end
911 else
912 begin
913 { use long arithmetic here to avoid overflow & unsigned problems }
921 { Read in the selected part of the array.
922 During the initial write pass, we will do no actual read
923 because the selected part is all undefined. }
927 { Ensure the accessed part of the array is defined; prezero if needed.
928 To improve locality of access, we only prezero the part of the array
929 that the caller is about to access, not the entire in-memory array. }
931 begin
933 begin
937 end
938 else
939 begin
945 begin
950 begin
954 end
955 else
956 begin
961 { Flag the buffer dirty if caller will write in it }
964 { Return address of proper part of the buffer }
969 {METHODDEF}
975 { Access the part of a virtual block array starting at start_row }
976 { and extending for num_rows rows. writable is true if }
977 { caller intends to modify the accessed area. }
978 var
982 var
984 begin
987 { debugging check }
992 { Make the desired part of the virtual array accessible }
995 begin
998 { Flush old buffer contents if necessary }
1000 begin
1004 { Decide what part of virtual array to access.
1005 Algorithm: if target address > current window, assume forward scan,
1006 load starting at target address. If target address < current window,
1007 assume backward scan, load so that target area is top of window.
1008 Note that when switching from forward write to forward read, will have
1009 start_row := 0, so the limiting case applies and we load from 0 anyway. }
1012 begin
1014 end
1015 else
1016 begin
1017 { use long arithmetic here to avoid overflow & unsigned problems }
1024 { Read in the selected part of the array.
1025 During the initial write pass, we will do no actual read
1026 because the selected part is all undefined. }
1030 { Ensure the accessed part of the array is defined; prezero if needed.
1031 To improve locality of access, we only prezero the part of the array
1032 that the caller is about to access, not the entire in-memory array. }
1035 begin
1037 begin
1041 end
1042 else
1043 begin
1049 begin
1054 begin
1058 end
1059 else
1060 begin
1065 { Flag the buffer dirty if caller will write in it }
1068 { Return address of proper part of the buffer }
1073 { Release all objects belonging to a specified pool. }
1075 {METHODDEF}
1077 var
1082 var
1085 var
1088 begin
1094 {$ifdef MEM_STATS}
1097 {$endif}
1099 { If freeing IMAGE pool, close any virtual arrays first }
1101 begin
1104 begin
1115 begin
1126 { Release large objects }
1131 begin
1141 { Release small objects }
1146 begin
1158 { Close up shop entirely.
1159 Note that this cannot be called unless cinfo^.mem is non-NIL. }
1161 {METHODDEF}
1163 var
1165 begin
1166 { Close all backing store, release all memory.
1167 Releasing pools in reverse order might help avoid fragmentation
1168 with some (brain-damaged) malloc libraries. }
1171 begin
1175 { Release the memory manager control block too. }
1183 { Memory manager initialization.
1184 When this is called, only the error manager pointer is valid in cinfo! }
1186 {GLOBAL}
1188 var
1193 {$ifndef NO_GETENV}
1194 var
1197 {$endif}
1198 begin
1201 { Check for configuration errors.
1202 SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
1203 doesn't reflect any real hardware alignment requirement.
1204 The test is a little tricky: for X>0, X and X-1 have no one-bits
1205 in common if and only if X is a power of 2, ie has only one one-bit.
1206 Some compilers may give an "unreachable code" warning here; ignore it. }
1209 { MAX_ALLOC_CHUNK must be representable as type size_t, and must be
1210 a multiple of SIZEOF(ALIGN_TYPE).
1211 Again, an "unreachable code" warning may be ignored here.
1212 But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK. }
1221 { Attempt to allocate memory manager's control block }
1225 begin
1230 { OK, fill in the method pointers }
1243 { Make MAX_ALLOC_CHUNK accessible to other modules }
1246 { Initialize working state }
1250 begin
1259 { Declare ourselves open for business }
1262 { Check for an environment variable JPEGMEM; if found, override the
1263 default max_memory setting from jpeg_mem_init. Note that the
1264 surrounding application may again override this value.
1265 If your system doesn't support getenv(), define NO_GETENV to disable
1266 this feature. }
1268 {$ifndef NO_GETENV}
1271 begin
1274 begin
1279 {$endif}