Line data Source code
1 : /*
2 : * SPDX-License-Identifier: MPL-2.0
3 : *
4 : * This Source Code Form is subject to the terms of the Mozilla Public
5 : * License, v. 2.0. If a copy of the MPL was not distributed with this
6 : * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 : *
8 : * Copyright 2024, 2025 MonetDB Foundation;
9 : * Copyright August 2008 - 2023 MonetDB B.V.;
10 : * Copyright 1997 - July 2008 CWI.
11 : */
12 :
13 : /*
14 : * @f gdk_heap
15 : * @a Peter Boncz, Wilko Quak
16 : * @+ Atom Heaps
17 : * Heaps are the basic mass storage structure of Monet. A heap is a
18 : * handle to a large, possibly huge, contiguous area of main memory,
19 : * that can be allocated in various ways (discriminated by the
20 : * heap->storage field):
21 : *
22 : * @table @code
23 : * @item STORE_MEM: malloc-ed memory
24 : * small (or rather: not huge) heaps are allocated with GDKmalloc.
25 : * Notice that GDKmalloc may redirect big requests to anonymous
26 : * virtual memory to prevent @emph{memory fragmentation} in the malloc
27 : * library (see gdk_utils.c).
28 : *
29 : * @item STORE_MMAP: read-only mapped region
30 : * this is a file on disk that is mapped into virtual memory. This is
31 : * normally done MAP_SHARED, so we can use msync() to commit dirty
32 : * data using the OS virtual memory management.
33 : *
34 : * @item STORE_PRIV: read-write mapped region
35 : * in order to preserve ACID properties, we use a different memory
36 : * mapping on virtual memory that is writable. This is because in case
37 : * of a crash on a dirty STORE_MMAP heap, the OS may have written some
38 : * of the dirty pages to disk and other not (but it is impossible to
39 : * determine which). The OS MAP_PRIVATE mode does not modify the file
40 : * on which is being mapped, rather creates substitute pages
41 : * dynamically taken from the swap file when modifications occur. This
42 : * is the only way to make writing to mmap()-ed regions safe. To save
43 : * changes, we created a new file X.new; as some OS-es do not allow to
44 : * write into a file that has a mmap open on it (e.g. Windows). Such
45 : * X.new files take preference over X files when opening them.
46 : * @end table
47 : * Read also the discussion in BATsetaccess (gdk_bat.c).
48 : */
49 : #include "monetdb_config.h"
50 : #include "gdk.h"
51 : #include "gdk_private.h"
52 : #include "mutils.h"
53 :
54 : static void *
55 1560 : HEAPcreatefile(int farmid, size_t *maxsz, const char *fn)
56 : {
57 1560 : void *base = NULL;
58 1560 : char path[MAXPATH];
59 1560 : int fd;
60 :
61 1560 : if (farmid != NOFARM) {
62 : /* call GDKfilepath once here instead of twice inside
63 : * the calls to GDKfdlocate and GDKload */
64 1024 : if (GDKfilepath(path, sizeof(path), farmid, BATDIR, fn, NULL) != GDK_SUCCEED)
65 : return NULL;
66 : fn = path;
67 : }
68 : /* round up to multiple of GDK_mmap_pagesize */
69 1601 : fd = GDKfdlocate(NOFARM, fn, "wb", NULL);
70 1615 : if (fd >= 0) {
71 1615 : close(fd);
72 1615 : base = GDKload(NOFARM, fn, NULL, *maxsz, maxsz, STORE_MMAP);
73 : }
74 : return base;
75 : }
76 :
77 : static char *
78 53792 : decompose_filename(str nme)
79 : {
80 53792 : char *ext;
81 :
82 53792 : ext = strchr(nme, '.'); /* extract base and ext from heap file name */
83 53792 : if (ext) {
84 53792 : *ext++ = 0;
85 : }
86 53792 : return ext;
87 : }
88 :
89 : /* this function is called with the theaplock held */
90 : gdk_return
91 52053 : HEAPgrow(Heap **hp, size_t size, bool mayshare)
92 : {
93 52053 : Heap *new;
94 :
95 52053 : ATOMIC_BASE_TYPE refs = ATOMIC_GET(&(*hp)->refs);
96 52053 : if ((refs & HEAPREFS) == 1) {
97 51985 : return HEAPextend(*hp, size, mayshare);
98 : }
99 68 : new = GDKmalloc(sizeof(Heap));
100 68 : if (new != NULL) {
101 68 : Heap *old = *hp;
102 68 : *new = (Heap) {
103 68 : .farmid = old->farmid,
104 : .dirty = true,
105 68 : .parentid = old->parentid,
106 68 : .wasempty = old->wasempty,
107 68 : .hasfile = old->hasfile,
108 68 : .refs = ATOMIC_VAR_INIT(1 | (refs & HEAPREMOVE)),
109 : };
110 68 : memcpy(new->filename, old->filename, sizeof(new->filename));
111 68 : if (HEAPalloc(new, size, 1) == GDK_SUCCEED) {
112 68 : new->free = old->free;
113 68 : new->cleanhash = old->cleanhash;
114 68 : if (old->free > 0 &&
115 63 : (new->storage == STORE_MEM || old->storage == STORE_MEM))
116 41 : memcpy(new->base, old->base, old->free);
117 : /* else both are STORE_MMAP and refer to the
118 : * same file and so we don't need to copy */
119 :
120 : /* replace old heap with new */
121 68 : HEAPdecref(*hp, false);
122 68 : *hp = new;
123 : } else {
124 0 : GDKfree(new);
125 0 : new = NULL;
126 : }
127 : }
128 68 : return new ? GDK_SUCCEED : GDK_FAIL;
129 : }
130 :
131 : /*
132 : * @- HEAPalloc
133 : *
134 : * Normally, we use GDKmalloc for creating a new heap. Huge heaps,
135 : * though, come from memory mapped files that we create with a large
136 : * fallocate. This is fast, and leads to files-with-holes on Unixes (on
137 : * Windows, it actually always performs I/O which is not nice).
138 : */
139 : gdk_return
140 9171208 : HEAPalloc(Heap *h, size_t nitems, size_t itemsize)
141 : {
142 9171208 : size_t size = 0;
143 9171208 : QryCtx *qc = h->farmid == 1 ? MT_thread_get_qry_ctx() : NULL;
144 :
145 9213070 : h->base = NULL;
146 9213070 : h->size = 1;
147 9213070 : if (itemsize) {
148 : /* check for overflow */
149 9213070 : if (nitems > BUN_NONE / itemsize) {
150 0 : GDKerror("allocating more than heap can accommodate\n");
151 0 : return GDK_FAIL;
152 : }
153 9213070 : h->size = MAX(1, nitems) * itemsize;
154 : }
155 9213070 : h->free = 0;
156 9213070 : h->cleanhash = false;
157 :
158 : #ifdef SIZE_CHECK_IN_HEAPS_ONLY
159 9213070 : if (GDKvm_cursize() + h->size >= GDK_vm_maxsize &&
160 0 : !MT_thread_override_limits()) {
161 0 : GDKerror("allocating too much memory (current: %zu, requested: %zu, limit: %zu)\n", GDKvm_cursize(), h->size, GDK_vm_maxsize);
162 0 : return GDK_FAIL;
163 : }
164 : #endif
165 :
166 9160181 : size_t allocated;
167 9160181 : if (GDKinmemory(h->farmid) ||
168 18339363 : ((allocated = GDKmem_cursize()) + h->size < GDK_mem_maxsize &&
169 9177566 : h->size < (h->farmid == 0 ? GDK_mmap_minsize_persistent : GDK_mmap_minsize_transient) &&
170 9179889 : h->size < ((GDK_mem_maxsize - allocated) >> 6))) {
171 9211106 : h->storage = STORE_MEM;
172 9211106 : size = h->size;
173 9211106 : if (qc != NULL) {
174 5941186 : ATOMIC_BASE_TYPE sz = ATOMIC_ADD(&qc->datasize, size);
175 5941186 : sz += size;
176 5941186 : if (qc->maxmem > 0 && sz > qc->maxmem) {
177 0 : ATOMIC_SUB(&qc->datasize, size);
178 0 : GDKerror("Query using too much memory.\n");
179 0 : return GDK_FAIL;
180 : }
181 : }
182 9211106 : h->base = GDKmalloc(size);
183 9241059 : TRC_DEBUG(HEAP, "%s %zu %p\n", h->filename, size, h->base);
184 9241059 : if (h->base == NULL && qc != NULL)
185 0 : ATOMIC_SUB(&qc->datasize, size);
186 : }
187 :
188 9201899 : if (h->base == NULL && !GDKinmemory(h->farmid)) {
189 537 : char nme[MAXPATH];
190 537 : if (GDKfilepath(nme, sizeof(nme), h->farmid, BATDIR, h->filename, NULL) != GDK_SUCCEED)
191 0 : return GDK_FAIL;
192 540 : h->storage = STORE_MMAP;
193 540 : h->size = (h->size + GDK_mmap_pagesize - 1) & ~(GDK_mmap_pagesize - 1);
194 540 : size = h->size;
195 540 : if (qc != NULL) {
196 1 : ATOMIC_BASE_TYPE sz = ATOMIC_ADD(&qc->datasize, size);
197 1 : sz += size;
198 1 : if (qc->maxmem > 0 && sz > qc->maxmem) {
199 0 : ATOMIC_SUB(&qc->datasize, size);
200 0 : GDKerror("Query using too much memory.\n");
201 0 : return GDK_FAIL;
202 : }
203 : }
204 540 : h->base = HEAPcreatefile(NOFARM, &h->size, nme);
205 540 : h->hasfile = true;
206 540 : if (h->base == NULL) {
207 0 : if (qc != NULL)
208 0 : ATOMIC_SUB(&qc->datasize, size);
209 : /* remove file we may just have created
210 : * it may or may not exist, depending on what
211 : * failed */
212 0 : (void) MT_remove(nme);
213 0 : h->hasfile = false; /* just removed it */
214 0 : GDKerror("Insufficient space for HEAP of %zu bytes.", h->size);
215 0 : return GDK_FAIL;
216 : }
217 540 : TRC_DEBUG(HEAP, "%s %zu %p (mmap)\n", h->filename, size, h->base);
218 : }
219 9201902 : h->newstorage = h->storage;
220 9201902 : return GDK_SUCCEED;
221 : }
222 :
223 : /* Extend the allocated space of the heap H to be at least SIZE bytes.
224 : * If the heap grows beyond a threshold and a filename is known, the
225 : * heap is converted from allocated memory to a memory-mapped file.
226 : * When switching from allocated to memory mapped, if MAYSHARE is set,
227 : * the heap does not have to be copy-on-write.
228 : *
229 : * The function returns 0 on success, -1 on failure.
230 : *
231 : * When extending a memory-mapped heap, we use the function MT_mremap
232 : * (which see). When extending an allocated heap, we use GDKrealloc.
233 : * If that fails, we switch to memory mapped, even when the size is
234 : * below the threshold.
235 : *
236 : * When converting from allocated to memory mapped, we try several
237 : * strategies. First we try to create the memory map, and if that
238 : * works, copy the data and free the old memory. If this fails, we
239 : * first write the data to disk, free the memory, and then try to
240 : * memory map the saved data. */
241 : gdk_return
242 69479 : HEAPextend(Heap *h, size_t size, bool mayshare)
243 : {
244 69479 : size_t osize = h->size;
245 69479 : size_t xsize;
246 69479 : QryCtx *qc = h->farmid == 1 ? MT_thread_get_qry_ctx() : NULL;
247 :
248 69488 : if (size <= h->size)
249 : return GDK_SUCCEED; /* nothing to do */
250 :
251 53817 : char nme[sizeof(h->filename)], *ext;
252 53817 : const char *failure = "None";
253 :
254 53817 : if (GDKinmemory(h->farmid)) {
255 47 : strcpy_len(nme, ":memory:", sizeof(nme));
256 47 : ext = "ext";
257 : } else {
258 53696 : strcpy_len(nme, h->filename, sizeof(nme));
259 53846 : ext = decompose_filename(nme);
260 : }
261 53838 : failure = "size > h->size";
262 :
263 : #ifdef SIZE_CHECK_IN_HEAPS_ONLY
264 53838 : if (GDKvm_cursize() + size - h->size >= GDK_vm_maxsize &&
265 0 : !MT_thread_override_limits()) {
266 0 : GDKerror("allocating too much memory (current: %zu, requested: %zu, limit: %zu)\n", GDKvm_cursize(), size - h->size, GDK_vm_maxsize);
267 0 : return GDK_FAIL;
268 : }
269 : #endif
270 :
271 53790 : if (h->storage != STORE_MEM) {
272 465 : char *p;
273 465 : char path[MAXPATH];
274 :
275 465 : assert(h->hasfile);
276 465 : TRC_DEBUG(HEAP, "Extending %s mmapped heap (%s)\n", h->storage == STORE_MMAP ? "shared" : "privately", h->filename);
277 : /* extend memory mapped file */
278 465 : if (GDKfilepath(path, sizeof(path), h->farmid, BATDIR, nme, ext) != GDK_SUCCEED) {
279 465 : return GDK_FAIL;
280 : }
281 465 : size = (size + GDK_mmap_pagesize - 1) & ~(GDK_mmap_pagesize - 1);
282 465 : if (size == 0)
283 0 : size = GDK_mmap_pagesize;
284 :
285 465 : xsize = size - osize;
286 :
287 465 : if (qc != NULL) {
288 43 : ATOMIC_BASE_TYPE sz = ATOMIC_ADD(&qc->datasize, xsize);
289 43 : sz += size - osize;
290 43 : if (qc->maxmem > 0 && sz > qc->maxmem) {
291 0 : GDKerror("Query using too much memory.\n");
292 0 : ATOMIC_SUB(&qc->datasize, xsize);
293 0 : return GDK_FAIL;
294 : }
295 : }
296 930 : p = GDKmremap(path,
297 : h->storage == STORE_PRIV ?
298 : MMAP_COPY | MMAP_READ | MMAP_WRITE :
299 : MMAP_READ | MMAP_WRITE,
300 : h->base, h->size, &size);
301 465 : if (p) {
302 465 : h->size = size;
303 465 : h->base = p;
304 465 : return GDK_SUCCEED; /* success */
305 : }
306 0 : if (qc != NULL)
307 0 : ATOMIC_SUB(&qc->datasize, xsize);
308 0 : failure = "GDKmremap() failed";
309 : } else {
310 : /* extend a malloced heap, possibly switching over to
311 : * file-mapped storage */
312 53325 : Heap bak = *h;
313 53325 : size_t allocated;
314 53325 : bool must_mmap = (!GDKinmemory(h->farmid) &&
315 53343 : (h->newstorage != STORE_MEM ||
316 106516 : (allocated = GDKmem_cursize()) + size >= GDK_mem_maxsize ||
317 53265 : size >= (h->farmid == 0 ? GDK_mmap_minsize_persistent : GDK_mmap_minsize_transient) ||
318 52246 : size >= ((GDK_mem_maxsize - allocated) >> 6)));
319 :
320 53344 : h->size = size;
321 53344 : xsize = size - osize;
322 :
323 : /* try GDKrealloc if the heap size stays within
324 : * reasonable limits */
325 53344 : if (!must_mmap) {
326 52230 : if (qc != NULL) {
327 24682 : ATOMIC_BASE_TYPE sz = ATOMIC_ADD(&qc->datasize, xsize);
328 24682 : sz += xsize;
329 24682 : if (qc->maxmem > 0 && sz > qc->maxmem) {
330 0 : GDKerror("Query using too much memory.\n");
331 0 : ATOMIC_SUB(&qc->datasize, xsize);
332 0 : *h = bak;
333 53545 : return GDK_FAIL;
334 : }
335 : }
336 52230 : h->newstorage = h->storage = STORE_MEM;
337 52230 : h->base = GDKrealloc(h->base, size);
338 52429 : TRC_DEBUG(HEAP, "Extending malloced heap %s %zu->%zu %p->%p\n", h->filename, bak.size, size, bak.base, h->base);
339 52429 : if (h->base) {
340 : return GDK_SUCCEED; /* success */
341 : }
342 : /* bak.base is still valid and may get restored */
343 0 : failure = "h->storage == STORE_MEM && !must_map && !h->base";
344 0 : if (qc != NULL)
345 0 : ATOMIC_SUB(&qc->datasize, xsize);
346 : }
347 :
348 1114 : if (!GDKinmemory(h->farmid)) {
349 : /* too big: convert it to a disk-based temporary heap */
350 :
351 1075 : assert(h->storage == STORE_MEM);
352 1075 : assert(ext != NULL);
353 : /* if the heap file already exists, we want to switch
354 : * to STORE_PRIV (copy-on-write memory mapped files),
355 : * but if the heap file doesn't exist yet, the BAT is
356 : * new and we can use STORE_MMAP */
357 1075 : int fd = GDKfdlocate(h->farmid, nme, "rb", ext);
358 1079 : if (fd >= 0) {
359 35 : assert(h->hasfile);
360 35 : close(fd);
361 35 : fd = GDKfdlocate(h->farmid, nme, "wb", ext);
362 35 : if (fd >= 0) {
363 35 : gdk_return rc = GDKextendf(fd, size, nme);
364 35 : close(fd);
365 35 : if (rc != GDK_SUCCEED) {
366 0 : failure = "h->storage == STORE_MEM && can_map && fd >= 0 && GDKextendf() != GDK_SUCCEED";
367 0 : goto failed;
368 : }
369 35 : h->storage = h->newstorage == STORE_MMAP && !mayshare ? STORE_PRIV : h->newstorage;
370 : /* make sure we really MMAP */
371 35 : if (must_mmap && h->newstorage == STORE_MEM)
372 35 : h->storage = STORE_MMAP;
373 35 : h->newstorage = h->storage;
374 :
375 35 : h->base = NULL;
376 35 : TRC_DEBUG(HEAP, "Converting malloced to %s mmapped heap %s\n", h->newstorage == STORE_MMAP ? "shared" : "privately", h->filename);
377 : /* try to allocate a memory-mapped based
378 : * heap */
379 35 : if (HEAPload(h, nme, ext, false) == GDK_SUCCEED) {
380 : /* copy data to heap and free old
381 : * memory */
382 35 : memcpy(h->base, bak.base, bak.free);
383 35 : HEAPfree(&bak, false);
384 35 : return GDK_SUCCEED;
385 : }
386 : failure = "h->storage == STORE_MEM && can_map && fd >= 0 && HEAPload() != GDK_SUCCEED";
387 : /* we failed */
388 : } else {
389 : failure = "h->storage == STORE_MEM && can_map && fd < 0";
390 : }
391 : } else {
392 : /* no pre-existing heap file, so create a new
393 : * one */
394 1044 : if (qc != NULL) {
395 3 : h->size = (h->size + GDK_mmap_pagesize - 1) & ~(GDK_mmap_pagesize - 1);
396 3 : xsize = h->size;
397 3 : ATOMIC_BASE_TYPE sz = ATOMIC_ADD(&qc->datasize, xsize);
398 3 : sz += h->size;
399 3 : if (qc->maxmem > 0 && sz > qc->maxmem) {
400 0 : GDKerror("Query using too much memory.\n");
401 0 : sz = ATOMIC_ADD(&qc->datasize, xsize);
402 0 : *h = bak;
403 0 : return GDK_FAIL;
404 : }
405 : }
406 1044 : h->base = HEAPcreatefile(h->farmid, &h->size, h->filename);
407 1081 : h->hasfile = true;
408 1081 : if (h->base) {
409 1081 : h->newstorage = h->storage = STORE_MMAP;
410 1081 : if (bak.free > 0)
411 35 : memcpy(h->base, bak.base, bak.free);
412 1081 : HEAPfree(&bak, false);
413 1081 : return GDK_SUCCEED;
414 : }
415 0 : failure = "h->storage == STORE_MEM && can_map && fd >= 0 && HEAPcreatefile() == NULL";
416 0 : if (qc != NULL)
417 0 : ATOMIC_SUB(&qc->datasize, xsize);
418 : }
419 : }
420 0 : failed:
421 0 : if (h->hasfile && !bak.hasfile) {
422 0 : char path[MAXPATH];
423 :
424 0 : if (GDKfilepath(path, sizeof(path), h->farmid, BATDIR, nme, ext) == GDK_SUCCEED) {
425 0 : MT_remove(path);
426 : } else {
427 : /* couldn't remove, so now we have a file */
428 0 : bak.hasfile = true;
429 : }
430 : }
431 0 : *h = bak;
432 : }
433 0 : GDKerror("failed to extend to %zu for %s%s%s: %s\n",
434 : size, nme, ext ? "." : "", ext ? ext : "", failure);
435 0 : return GDK_FAIL;
436 : }
437 :
438 : /* grow the string offset heap so that the value v fits (i.e. wide
439 : * enough to fit the value), and it has space for at least cap elements;
440 : * copy ncopy BUNs, or up to the heap size, whichever is smaller */
441 : gdk_return
442 100407 : GDKupgradevarheap(BAT *b, var_t v, BUN cap, BUN ncopy)
443 : {
444 100407 : uint8_t shift = b->tshift;
445 100407 : uint16_t width = b->twidth;
446 100407 : uint8_t *pc;
447 100407 : uint16_t *ps;
448 100407 : uint32_t *pi;
449 : #if SIZEOF_VAR_T == 8
450 100407 : uint64_t *pl;
451 : #endif
452 100407 : size_t i, n;
453 100407 : size_t newsize;
454 100407 : bat bid = b->batCacheid;
455 100407 : Heap *old, *new;
456 :
457 100407 : old = b->theap;
458 : // assert(old->storage == STORE_MEM);
459 100407 : assert(old->parentid == b->batCacheid);
460 100407 : assert(b->tbaseoff == 0);
461 100407 : assert(width != 0);
462 100407 : assert(v >= GDK_VAROFFSET);
463 :
464 130512 : while (width < SIZEOF_VAR_T && (width <= 2 ? v - GDK_VAROFFSET : v) >= ((var_t) 1 << (8 * width))) {
465 30105 : width <<= 1;
466 30105 : shift++;
467 : }
468 : /* if cap(acity) given (we check whether it is larger than the
469 : * old), then grow to cap */
470 100407 : if (cap > (old->size >> b->tshift))
471 6429 : newsize = cap << shift;
472 : else
473 93978 : newsize = (old->size >> b->tshift) << shift;
474 100407 : if (b->twidth == width) {
475 72104 : if (newsize <= old->size) {
476 : /* nothing to do */
477 67086 : if (cap > b->batCapacity)
478 0 : BATsetcapacity(b, cap);
479 67086 : return GDK_SUCCEED;
480 : }
481 5018 : return BATextend(b, newsize >> shift);
482 : }
483 :
484 28303 : n = MIN(ncopy, old->size >> b->tshift);
485 :
486 42404 : MT_thread_setalgorithm(n ? "widen offset heap" : "widen empty offset heap");
487 :
488 28486 : new = GDKmalloc(sizeof(Heap));
489 28551 : if (new == NULL)
490 : return GDK_FAIL;
491 28551 : *new = (Heap) {
492 28551 : .farmid = old->farmid,
493 : .dirty = true,
494 28551 : .parentid = old->parentid,
495 28551 : .wasempty = old->wasempty,
496 28551 : .refs = ATOMIC_VAR_INIT(1 | (ATOMIC_GET(&old->refs) & HEAPREMOVE)),
497 : };
498 28551 : settailname(new, BBP_physical(b->batCacheid), b->ttype, width);
499 28485 : if (HEAPalloc(new, newsize, 1) != GDK_SUCCEED) {
500 0 : GDKfree(new);
501 0 : return GDK_FAIL;
502 : }
503 : /* HEAPalloc initialized .free, so we need to set it after */
504 28545 : new->free = old->free << (shift - b->tshift);
505 : /* per the above, width > b->twidth, so certain combinations are
506 : * impossible */
507 28545 : switch (width) {
508 25691 : case 2:
509 25691 : ps = (uint16_t *) new->base;
510 25691 : switch (b->twidth) {
511 25691 : case 1:
512 25691 : pc = (uint8_t *) old->base;
513 1266361 : for (i = 0; i < n; i++)
514 1240670 : ps[i] = pc[i];
515 25691 : break;
516 : default:
517 0 : MT_UNREACHABLE();
518 : }
519 : #ifndef NDEBUG
520 : /* valgrind */
521 25691 : memset(ps + n, 0, new->size - n * 2);
522 : #endif
523 25691 : break;
524 2854 : case 4:
525 2854 : pi = (uint32_t *) new->base;
526 2854 : switch (b->twidth) {
527 1666 : case 1:
528 1666 : pc = (uint8_t *) old->base;
529 1670 : for (i = 0; i < n; i++)
530 4 : pi[i] = pc[i] + GDK_VAROFFSET;
531 : break;
532 1188 : case 2:
533 1188 : ps = (uint16_t *) old->base;
534 1580534 : for (i = 0; i < n; i++)
535 1579346 : pi[i] = ps[i] + GDK_VAROFFSET;
536 : break;
537 : default:
538 0 : MT_UNREACHABLE();
539 : }
540 : #ifndef NDEBUG
541 : /* valgrind */
542 2854 : memset(pi + n, 0, new->size - n * 4);
543 : #endif
544 2854 : break;
545 : #if SIZEOF_VAR_T == 8
546 0 : case 8:
547 0 : pl = (uint64_t *) new->base;
548 0 : switch (b->twidth) {
549 0 : case 1:
550 0 : pc = (uint8_t *) old->base;
551 0 : for (i = 0; i < n; i++)
552 0 : pl[i] = pc[i] + GDK_VAROFFSET;
553 : break;
554 0 : case 2:
555 0 : ps = (uint16_t *) old->base;
556 0 : for (i = 0; i < n; i++)
557 0 : pl[i] = ps[i] + GDK_VAROFFSET;
558 : break;
559 0 : case 4:
560 0 : pi = (uint32_t *) old->base;
561 0 : for (i = 0; i < n; i++)
562 0 : pl[i] = pi[i];
563 : break;
564 : default:
565 0 : MT_UNREACHABLE();
566 : }
567 : #ifndef NDEBUG
568 : /* valgrind */
569 0 : memset(pl + n, 0, new->size - n * 8);
570 : #endif
571 0 : break;
572 : #endif
573 : default:
574 0 : MT_UNREACHABLE();
575 : }
576 28545 : MT_lock_set(&b->theaplock);
577 28512 : b->tshift = shift;
578 28512 : b->twidth = width;
579 28512 : if (cap > BATcapacity(b))
580 1402 : BATsetcapacity(b, cap);
581 28512 : b->theap = new;
582 28512 : if (BBP_status(bid) & (BBPEXISTING|BBPDELETED) && b->oldtail == NULL) {
583 2123 : b->oldtail = old;
584 2123 : if ((ATOMIC_OR(&old->refs, DELAYEDREMOVE) & HEAPREFS) == 1) {
585 : /* we have the only reference, we can free the
586 : * memory */
587 2123 : HEAPfree(old, false);
588 : }
589 : } else {
590 26389 : ValPtr p = BATgetprop_nolock(b, (enum prop_t) 20);
591 52750 : HEAPdecref(old, p == NULL || strcmp(((Heap*) p->val.pval)->filename, old->filename) != 0);
592 : }
593 28548 : MT_lock_unset(&b->theaplock);
594 28458 : return GDK_SUCCEED;
595 : }
596 :
597 : /*
598 : * @- HEAPcopy
599 : * simple: alloc and copy. Notice that we suppose a preallocated
600 : * dst->filename (or NULL), which might be used in HEAPalloc().
601 : */
602 : gdk_return
603 4880 : HEAPcopy(Heap *dst, Heap *src, size_t offset)
604 : {
605 4880 : if (offset > src->free)
606 : offset = src->free;
607 4880 : if (HEAPalloc(dst, src->free - offset, 1) == GDK_SUCCEED) {
608 4897 : dst->free = src->free - offset;
609 4897 : memcpy(dst->base, src->base + offset, src->free - offset);
610 4897 : dst->cleanhash = src->cleanhash;
611 4897 : dst->dirty = true;
612 4897 : return GDK_SUCCEED;
613 : }
614 : return GDK_FAIL;
615 : }
616 :
617 : /* Free the memory associated with the heap H.
618 : * Unlinks (removes) the associated file if the rmheap flag is set. */
619 : void
620 16869810 : HEAPfree(Heap *h, bool rmheap)
621 : {
622 16869810 : if (h->base) {
623 9307356 : if (h->farmid == 1 && (h->storage == STORE_MEM || h->storage == STORE_MMAP || h->storage == STORE_PRIV)) {
624 8708954 : QryCtx *qc = MT_thread_get_qry_ctx();
625 8719210 : if (qc)
626 6014729 : ATOMIC_SUB(&qc->datasize, h->size);
627 : }
628 9317612 : if (h->storage == STORE_MEM) { /* plain memory */
629 9314948 : TRC_DEBUG(HEAP, "HEAPfree %s %zu %p\n", h->filename, h->size, h->base);
630 9314948 : GDKfree(h->base);
631 2664 : } else if (h->storage == STORE_CMEM) {
632 : //heap is stored in regular C memory rather than GDK memory,so we call free()
633 47 : free(h->base);
634 2617 : } else if (h->storage != STORE_NOWN) { /* mapped file, or STORE_PRIV */
635 5234 : gdk_return ret = GDKmunmap(h->base,
636 : h->storage == STORE_PRIV ?
637 : MMAP_COPY | MMAP_READ | MMAP_WRITE :
638 : MMAP_READ | MMAP_WRITE,
639 : h->size);
640 :
641 2622 : if (ret != GDK_SUCCEED) {
642 0 : GDKsyserror("HEAPfree: %s was not mapped\n",
643 : h->filename);
644 0 : assert(0);
645 : }
646 2622 : TRC_DEBUG(HEAP, "munmap(base=%p, size=%zu) = %d\n",
647 : (void *)h->base, h->size, (int) ret);
648 : }
649 : }
650 16877929 : h->base = NULL;
651 16877929 : if (rmheap && !GDKinmemory(h->farmid)) {
652 16184483 : char path[MAXPATH];
653 :
654 16184483 : if (h->hasfile) {
655 56957 : if (GDKfilepath(path, sizeof(path), h->farmid, BATDIR, h->filename, NULL) == GDK_SUCCEED) {
656 56957 : int ret = MT_remove(path);
657 56956 : if (ret == -1) {
658 : /* unexpectedly not present */
659 0 : perror(path);
660 : }
661 56956 : assert(ret == 0);
662 56956 : h->hasfile = false;
663 : }
664 56956 : if (GDKfilepath(path, sizeof(path), h->farmid, BATDIR, h->filename, "new") == GDK_SUCCEED) {
665 : /* in practice, should never be present */
666 56956 : int ret = MT_remove(path);
667 56956 : if (ret == -1 && errno != ENOENT)
668 0 : perror(path);
669 56956 : assert(ret == -1 && errno == ENOENT);
670 : }
671 : #ifndef NDEBUG
672 16127526 : } else if (GDKfilepath(path, sizeof(path), h->farmid, BATDIR, h->filename, NULL) == GDK_SUCCEED) {
673 : /* should not be present */
674 16100330 : struct stat st;
675 16100330 : assert(stat(path, &st) == -1 && errno == ENOENT);
676 : #endif
677 : }
678 : }
679 16748002 : }
680 :
681 : void
682 80869147 : HEAPdecref(Heap *h, bool remove)
683 : {
684 80869147 : if (remove)
685 13230322 : ATOMIC_OR(&h->refs, HEAPREMOVE);
686 80869147 : ATOMIC_BASE_TYPE refs = ATOMIC_DEC(&h->refs);
687 : //printf("dec ref(%d) %p %d\n", (int)h->refs, h, h->parentid);
688 80869147 : switch (refs & HEAPREFS) {
689 13291144 : case 0:
690 13291144 : HEAPfree(h, (bool) (refs & HEAPREMOVE));
691 13126666 : GDKfree(h);
692 13126666 : break;
693 30837154 : case 1:
694 30837154 : if (refs & DELAYEDREMOVE) {
695 : /* only reference left is b->oldtail */
696 1740 : HEAPfree(h, false);
697 : }
698 : break;
699 : default:
700 : break;
701 : }
702 80867553 : }
703 :
704 : void
705 67373711 : HEAPincref(Heap *h)
706 : {
707 : //printf("inc ref(%d) %p %d\n", (int)h->refs, h, h->parentid);
708 67373711 : ATOMIC_INC(&h->refs);
709 67373711 : }
710 :
711 : /*
712 : * @- HEAPload
713 : *
714 : * If we find file X.new, we move it over X (if present) and open it.
715 : */
716 : gdk_return
717 26471 : HEAPload(Heap *h, const char *nme, const char *ext, bool trunc)
718 : {
719 26471 : size_t minsize;
720 26471 : int ret = 0;
721 26471 : char srcpath[MAXPATH], dstpath[MAXPATH];
722 26471 : lng t0;
723 26471 : const char suffix[] = ".new";
724 :
725 26471 : if (h->storage == STORE_INVALID || h->newstorage == STORE_INVALID) {
726 26436 : size_t allocated;
727 52872 : h->storage = h->newstorage = h->size < (h->farmid == 0 ? GDK_mmap_minsize_persistent : GDK_mmap_minsize_transient) &&
728 25470 : (allocated = GDKmem_cursize()) < GDK_mem_maxsize &&
729 51906 : h->size < ((GDK_mem_maxsize - allocated) >> 6) ? STORE_MEM : STORE_MMAP;
730 : }
731 :
732 26471 : minsize = (h->size + GDK_mmap_pagesize - 1) & ~(GDK_mmap_pagesize - 1);
733 26471 : if (h->storage != STORE_MEM && minsize != h->size)
734 124 : h->size = minsize;
735 :
736 : /* when a bat is made read-only, we can truncate any unused
737 : * space at the end of the heap */
738 26471 : if (trunc) {
739 : /* round up mmap heap sizes to GDK_mmap_pagesize
740 : * segments, also add some slack */
741 25280 : int fd;
742 :
743 25280 : if (minsize == 0)
744 0 : minsize = GDK_mmap_pagesize; /* minimum of one page */
745 25280 : if ((fd = GDKfdlocate(h->farmid, nme, "rb+", ext)) >= 0) {
746 25278 : struct stat stb;
747 25278 : if (fstat(fd, &stb) == 0 &&
748 25279 : stb.st_size > (off_t) minsize) {
749 0 : ret = ftruncate(fd, minsize);
750 0 : TRC_DEBUG(HEAP,
751 : "ftruncate(file=%s.%s, size=%zu) = %d\n",
752 : nme, ext, minsize, ret);
753 0 : if (ret == 0) {
754 0 : h->size = minsize;
755 : }
756 : }
757 25279 : close(fd);
758 : }
759 : }
760 :
761 26467 : TRC_DEBUG(HEAP, "%s%s%s,storage=%d,free=%zu,size=%zu\n",
762 : nme, ext ? "." : "", ext ? ext : "",
763 : (int) h->storage, h->free, h->size);
764 :
765 : /* On some OSs (WIN32,Solaris), it is prohibited to write to a
766 : * file that is open in MAP_PRIVATE (FILE_MAP_COPY) solution:
767 : * we write to a file named .ext.new. This file, if present,
768 : * takes precedence. */
769 26467 : if (GDKfilepath(dstpath, sizeof(dstpath), h->farmid, BATDIR, nme, ext) != GDK_SUCCEED)
770 : return GDK_FAIL;
771 26471 : strconcat_len(srcpath, sizeof(srcpath), dstpath, suffix, NULL);
772 :
773 26471 : t0 = GDKusec();
774 26471 : ret = MT_rename(srcpath, dstpath);
775 26472 : TRC_DEBUG(HEAP, "rename %s %s = %d %s ("LLFMT"usec)\n",
776 : srcpath, dstpath, ret, ret < 0 ? GDKstrerror(errno, (char[128]){0}, 128) : "",
777 : GDKusec() - t0);
778 :
779 : #ifdef SIZE_CHECK_IN_HEAPS_ONLY
780 26472 : if (GDKvm_cursize() + h->size >= GDK_vm_maxsize &&
781 0 : !MT_thread_override_limits()) {
782 0 : GDKerror("allocating too much memory (current: %zu, requested: %zu, limit: %zu)\n", GDKvm_cursize(), h->size, GDK_vm_maxsize);
783 0 : return GDK_FAIL;
784 : }
785 : #endif
786 :
787 26472 : size_t size = h->size;
788 26472 : QryCtx *qc = NULL;
789 26472 : if (h->storage != STORE_MEM)
790 1001 : size = (size + GDK_mmap_pagesize - 1) & ~(GDK_mmap_pagesize - 1);
791 26472 : if (h->farmid == 1 && (qc = MT_thread_get_qry_ctx()) != NULL) {
792 0 : ATOMIC_BASE_TYPE sz = 0;
793 0 : sz = ATOMIC_ADD(&qc->datasize, size);
794 0 : sz += h->size;
795 0 : if (qc->maxmem > 0 && sz > qc->maxmem) {
796 0 : ATOMIC_SUB(&qc->datasize, size);
797 0 : GDKerror("Query using too much memory.\n");
798 0 : return GDK_FAIL;
799 : }
800 : }
801 26472 : h->dirty = false; /* we're about to read it, so it's clean */
802 26472 : if (h->storage == STORE_MEM && h->free == 0) {
803 0 : h->base = GDKmalloc(h->size);
804 0 : h->wasempty = true;
805 : } else {
806 26472 : if (h->free == 0) {
807 0 : int fd = GDKfdlocate(h->farmid, nme, "wb", ext);
808 0 : if (fd >= 0)
809 0 : close(fd);
810 0 : h->wasempty = true;
811 : }
812 26472 : h->base = GDKload(h->farmid, nme, ext, h->free, &h->size, h->storage);
813 : }
814 26472 : if (h->base == NULL) {
815 0 : if (qc != NULL)
816 0 : ATOMIC_SUB(&qc->datasize, size);
817 0 : return GDK_FAIL; /* file could not be read satisfactorily */
818 : }
819 :
820 : return GDK_SUCCEED;
821 : }
822 :
823 : /*
824 : * @- HEAPsave
825 : *
826 : * Saving STORE_MEM will do a write(fd, buf, size) in GDKsave
827 : * (explicit IO).
828 : *
829 : * Saving a STORE_PRIV heap X means that we must actually write to
830 : * X.new, thus we convert the mode passed to GDKsave to STORE_MEM.
831 : *
832 : * Saving STORE_MMAP will do a msync(buf, MSSYNC) in GDKsave (implicit
833 : * IO).
834 : *
835 : * After GDKsave returns successfully (>=0), we assume the heaps are
836 : * safe on stable storage.
837 : */
838 : gdk_return
839 366039 : HEAPsave(Heap *h, const char *nme, const char *ext, bool dosync, BUN free, MT_Lock *lock)
840 : {
841 366039 : storage_t store = h->newstorage;
842 366039 : long_str extension;
843 366039 : gdk_return rc;
844 366039 : const char suffix[] = ".new";
845 :
846 366039 : if (h->base == NULL) {
847 0 : GDKerror("no heap to save\n");
848 0 : return GDK_FAIL;
849 : }
850 366039 : if (free == 0) {
851 : /* nothing to see, please move on */
852 616 : if (lock)
853 616 : MT_lock_set(lock);
854 616 : h->wasempty = true;
855 0 : if (lock)
856 616 : MT_lock_unset(lock);
857 616 : TRC_DEBUG(HEAP,
858 : "not saving: "
859 : "(%s.%s,storage=%d,free=%zu,size=%zu,dosync=%s)\n",
860 : nme?nme:"", ext, (int) h->newstorage, free, h->size,
861 : dosync?"true":"false");
862 616 : return GDK_SUCCEED;
863 : }
864 365423 : if (h->storage != STORE_MEM && store == STORE_PRIV) {
865 : /* anonymous or private VM is saved as if it were malloced */
866 0 : store = STORE_MEM;
867 0 : assert(strlen(ext) + strlen(suffix) < sizeof(extension));
868 0 : strconcat_len(extension, sizeof(extension), ext, suffix, NULL);
869 0 : ext = extension;
870 365423 : } else if (store != STORE_MEM) {
871 1077 : store = h->storage;
872 : }
873 365423 : TRC_DEBUG(HEAP,
874 : "(%s.%s,storage=%d,free=%zu,size=%zu,dosync=%s)\n",
875 : nme?nme:"", ext, (int) h->newstorage, free, h->size,
876 : dosync?"true":"false");
877 365423 : if (lock)
878 337636 : MT_lock_set(lock);
879 365423 : if (free == h->free)
880 365417 : h->dirty = false;
881 365423 : if (lock)
882 337636 : MT_lock_unset(lock);
883 365423 : rc = GDKsave(h->farmid, nme, ext, h->base, free, store, dosync);
884 365423 : if (lock)
885 337636 : MT_lock_set(lock);
886 365423 : if (rc == GDK_SUCCEED) {
887 365423 : h->hasfile = true;
888 365423 : h->wasempty = false;
889 : } else {
890 0 : h->dirty = true;
891 0 : if (store != STORE_MMAP)
892 0 : h->hasfile = false;
893 : }
894 365423 : if (lock)
895 337636 : MT_lock_unset(lock);
896 : return rc;
897 : }
898 :
899 :
900 : /* Return the (virtual) size of the heap. */
901 : size_t
902 334756 : HEAPvmsize(Heap *h)
903 : {
904 334756 : if (h && h->base && h->free)
905 41475 : return h->size;
906 : return 0;
907 : }
908 :
909 : /* Return the allocated size of the heap, i.e. if the heap is memory
910 : * mapped and not copy-on-write (privately mapped), return 0. */
911 : size_t
912 334756 : HEAPmemsize(Heap *h)
913 : {
914 334756 : if (h && h->base && h->free && h->storage != STORE_MMAP)
915 41217 : return h->size;
916 : return 0;
917 : }
918 :
919 :
920 : /*
921 : * @+ Standard Heap Library
922 : * This library contains some routines which implement a @emph{
923 : * malloc} and @emph{ free} function on the Monet @emph{Heap}
924 : * structure. They are useful when implementing a new @emph{
925 : * variable-size} atomic data type, or for implementing new search
926 : * accelerators. All functions start with the prefix @emph{HEAP_}. T
927 : *
928 : * Due to non-careful design, the HEADER field was found to be
929 : * 32/64-bit dependent. As we do not (yet) want to change the BAT
930 : * image on disk, This is now fixed by switching on-the-fly between
931 : * two representations. We ensure that the 64-bit memory
932 : * representation is just as long as the 32-bits version (20 bytes) so
933 : * the rest of the heap never needs to shift. The function
934 : * HEAP_checkformat converts at load time dynamically between the
935 : * layout found on disk and the memory format. Recognition of the
936 : * header mode is done by looking at the first two ints: alignment
937 : * must be 4 or 8, and head can never be 4 or eight.
938 : *
939 : * TODO: user HEADER64 for both 32 and 64 bits (requires BAT format
940 : * change)
941 : */
942 :
943 : #define HEAPVERSION 20030408
944 :
945 : typedef struct heapheader {
946 : size_t head; /* index to first free block */
947 : int alignment; /* alignment of objects on heap */
948 : size_t firstblock; /* first block in heap */
949 : int version;
950 : int (*sizefcn)(const void *); /* ADT function to ask length */
951 : } HEADER32;
952 :
953 : typedef struct {
954 : int version;
955 : int alignment;
956 : size_t head;
957 : size_t firstblock;
958 : int (*sizefcn)(const void *);
959 : } HEADER64;
960 :
961 : #if SIZEOF_SIZE_T==8
962 : typedef HEADER64 HEADER;
963 : typedef HEADER32 HEADER_OTHER;
964 : #else
965 : typedef HEADER32 HEADER;
966 : typedef HEADER64 HEADER_OTHER;
967 : #endif
968 : typedef struct hfblock {
969 : size_t size; /* Size of this block in freelist */
970 : size_t next; /* index of next block */
971 : } CHUNK;
972 :
973 : #define roundup_8(x) (((x)+7)&~7)
974 : #define roundup_4(x) (((x)+3)&~3)
975 : #define blocksize(h,p) ((p)->size)
976 :
977 : static inline size_t
978 2030 : roundup_num(size_t number, int alignment)
979 : {
980 2030 : size_t rval;
981 :
982 2030 : rval = number + (size_t) alignment - 1;
983 2030 : rval -= (rval % (size_t) alignment);
984 2030 : return rval;
985 : }
986 :
987 : #define HEAP_index(HEAP,INDEX,TYPE) ((TYPE *)((char *) (HEAP)->base + (INDEX)))
988 :
989 :
990 : static void
991 2030 : HEAP_empty(Heap *heap, size_t nprivate, int alignment)
992 : {
993 : /* Find position of header block. */
994 2030 : HEADER *hheader = HEAP_index(heap, 0, HEADER);
995 :
996 : /* Calculate position of first and only free block. */
997 2030 : size_t head = roundup_num((size_t) (roundup_8(sizeof(HEADER)) + roundup_8(nprivate)), alignment);
998 2030 : CHUNK *headp = HEAP_index(heap, head, CHUNK);
999 :
1000 2030 : assert(roundup_8(sizeof(HEADER)) + roundup_8(nprivate) <= VAR_MAX);
1001 :
1002 : /* Fill header block. */
1003 2030 : hheader->head = head;
1004 2030 : hheader->sizefcn = NULL;
1005 2030 : hheader->alignment = alignment;
1006 2030 : hheader->firstblock = head;
1007 2030 : hheader->version = HEAPVERSION;
1008 :
1009 : /* Fill first free block. */
1010 2030 : assert(heap->size - head <= VAR_MAX);
1011 2030 : headp->size = (size_t) (heap->size - head);
1012 2030 : headp->next = 0;
1013 :
1014 2030 : heap->dirty = true;
1015 2030 : }
1016 :
1017 : gdk_return
1018 2025 : HEAP_initialize(Heap *heap, size_t nbytes, size_t nprivate, int alignment)
1019 : {
1020 : /* For now we know about two alignments. */
1021 2025 : if (alignment != 8) {
1022 : alignment = 4;
1023 : }
1024 2025 : if ((size_t) alignment < sizeof(size_t))
1025 : alignment = (int) sizeof(size_t);
1026 :
1027 : /* Calculate number of bytes needed for heap + structures. */
1028 : {
1029 2025 : size_t total = 100 + nbytes + nprivate + sizeof(HEADER) + sizeof(CHUNK);
1030 :
1031 2025 : total = roundup_8(total);
1032 2025 : if (HEAPalloc(heap, total, 1) != GDK_SUCCEED)
1033 : return GDK_FAIL;
1034 2030 : heap->free = heap->size;
1035 : }
1036 :
1037 : /* initialize heap as empty */
1038 2030 : HEAP_empty(heap, nprivate, alignment);
1039 2030 : return GDK_SUCCEED;
1040 : }
1041 :
1042 :
1043 : var_t
1044 7380369 : HEAP_malloc(BAT *b, size_t nbytes)
1045 : {
1046 7380369 : Heap *heap = b->tvheap;
1047 7380369 : size_t block, trail, ttrail;
1048 7380369 : CHUNK *blockp;
1049 7380369 : CHUNK *trailp;
1050 7380369 : HEADER *hheader = HEAP_index(heap, 0, HEADER);
1051 :
1052 : /* add space for size field */
1053 7380369 : nbytes += hheader->alignment;
1054 7380369 : nbytes = roundup_8(nbytes);
1055 7380369 : if (nbytes < sizeof(CHUNK))
1056 : nbytes = (size_t) sizeof(CHUNK);
1057 :
1058 : /* block -- points to block with acceptable size (if available).
1059 : * trail -- points to predecessor of block.
1060 : * ttrail -- points to predecessor of trail.
1061 : */
1062 7380369 : ttrail = 0;
1063 7380369 : trail = 0;
1064 7380504 : for (block = hheader->head; block != 0; block = blockp->next) {
1065 7380454 : blockp = HEAP_index(heap, block, CHUNK);
1066 :
1067 7380454 : assert(trail == 0 || block > trail);
1068 7380454 : if (trail != 0 && block <= trail) {
1069 0 : GDKerror("Free list is not orderered\n");
1070 0 : return (var_t) -1;
1071 : }
1072 :
1073 7380454 : if (blockp->size >= nbytes)
1074 : break;
1075 135 : ttrail = trail;
1076 135 : trail = block;
1077 : }
1078 :
1079 : /* If no block of acceptable size is found we try to enlarge
1080 : * the heap. */
1081 7380369 : if (block == 0) {
1082 170 : size_t newsize;
1083 :
1084 170 : assert(heap->free + MAX(heap->free, nbytes) <= VAR_MAX);
1085 : #if SIZEOF_SIZE_T == 4
1086 : newsize = MIN(heap->free, (size_t) 1 << 20);
1087 : #else
1088 170 : newsize = MIN(heap->free, (size_t) 1 << 30);
1089 : #endif
1090 170 : newsize = (size_t) roundup_8(heap->free + MAX(newsize, nbytes));
1091 170 : assert(heap->free <= VAR_MAX);
1092 170 : block = (size_t) heap->free; /* current end-of-heap */
1093 :
1094 : /* Increase the size of the heap. */
1095 170 : TRC_DEBUG(HEAP, "HEAPextend in HEAP_malloc %s %zu %zu\n", heap->filename, heap->size, newsize);
1096 170 : if (HEAPgrow(&b->tvheap, newsize, false) != GDK_SUCCEED) {
1097 : return (var_t) -1;
1098 : }
1099 170 : heap = b->tvheap;
1100 170 : heap->free = newsize;
1101 170 : hheader = HEAP_index(heap, 0, HEADER);
1102 :
1103 170 : blockp = HEAP_index(heap, block, CHUNK);
1104 170 : trailp = HEAP_index(heap, trail, CHUNK);
1105 :
1106 170 : blockp->next = 0;
1107 170 : assert(heap->free - block <= VAR_MAX);
1108 170 : blockp->size = (size_t) (heap->free - block); /* determine size of allocated block */
1109 :
1110 : /* Try to join the last block in the freelist and the
1111 : * newly allocated memory */
1112 170 : if ((trail != 0) && (trail + trailp->size == block)) {
1113 135 : trailp->size += blockp->size;
1114 135 : trailp->next = blockp->next;
1115 :
1116 135 : block = trail;
1117 135 : trail = ttrail;
1118 : }
1119 : }
1120 :
1121 : /* Now we have found a block which is big enough in block.
1122 : * The predecessor of this block is in trail. */
1123 7380369 : blockp = HEAP_index(heap, block, CHUNK);
1124 :
1125 : /* If selected block is bigger than block needed split block
1126 : * in two.
1127 : * TUNE: use different amount than 2*sizeof(CHUNK) */
1128 7380369 : if (blockp->size >= nbytes + 2 * sizeof(CHUNK)) {
1129 7380472 : size_t newblock = block + nbytes;
1130 7380472 : CHUNK *newblockp = HEAP_index(heap, newblock, CHUNK);
1131 :
1132 7380472 : newblockp->size = blockp->size - nbytes;
1133 7380472 : newblockp->next = blockp->next;
1134 :
1135 7380472 : blockp->next = newblock;
1136 7380472 : blockp->size = nbytes;
1137 : }
1138 :
1139 : /* Delete block from freelist */
1140 7380369 : if (trail == 0) {
1141 7380369 : hheader->head = blockp->next;
1142 : } else {
1143 0 : trailp = HEAP_index(heap, trail, CHUNK);
1144 :
1145 0 : trailp->next = blockp->next;
1146 : }
1147 :
1148 7380369 : heap->dirty = true;
1149 :
1150 7380369 : block += hheader->alignment;
1151 7380369 : return (var_t) block;
1152 : }
1153 :
1154 : void
1155 35 : HEAP_free(Heap *heap, var_t mem)
1156 : {
1157 : /* we cannot free pieces of the heap because we may have used
1158 : * append_varsized_bat to create the heap; if we did, there may be
1159 : * multiple locations in the offset heap that refer to the same entry in
1160 : * the vheap, so we cannot free any until we free all */
1161 35 : (void) heap;
1162 35 : (void) mem;
1163 : #if 0
1164 : HEADER *hheader = HEAP_index(heap, 0, HEADER);
1165 : CHUNK *beforep;
1166 : CHUNK *blockp;
1167 : CHUNK *afterp;
1168 : size_t after, before, block = mem;
1169 :
1170 : assert(hheader->alignment == 8 || hheader->alignment == 4);
1171 : if (hheader->alignment != 8 && hheader->alignment != 4) {
1172 : GDKerror("Heap structure corrupt\n");
1173 : return;
1174 : }
1175 :
1176 : block -= hheader->alignment;
1177 : blockp = HEAP_index(heap, block, CHUNK);
1178 :
1179 : /* block -- block which we want to free
1180 : * before -- first free block before block
1181 : * after -- first free block after block
1182 : */
1183 :
1184 : before = 0;
1185 : for (after = hheader->head; after != 0; after = HEAP_index(heap, after, CHUNK)->next) {
1186 : if (after > block)
1187 : break;
1188 : before = after;
1189 : }
1190 :
1191 : beforep = HEAP_index(heap, before, CHUNK);
1192 : afterp = HEAP_index(heap, after, CHUNK);
1193 :
1194 : /* If it is not the last free block. */
1195 : if (after != 0) {
1196 : /*
1197 : * If this block and the block after are consecutive.
1198 : */
1199 : if (block + blockp->size == after) {
1200 : /*
1201 : * We unite them.
1202 : */
1203 : blockp->size += afterp->size;
1204 : blockp->next = afterp->next;
1205 : } else
1206 : blockp->next = after;
1207 : } else {
1208 : /*
1209 : * It is the last block in the freelist.
1210 : */
1211 : blockp->next = 0;
1212 : }
1213 :
1214 : /*
1215 : * If it is not the first block in the list.
1216 : */
1217 : if (before != 0) {
1218 : /*
1219 : * If the before block and this block are consecutive.
1220 : */
1221 : if (before + beforep->size == block) {
1222 : /*
1223 : * We unite them.
1224 : */
1225 : beforep->size += blockp->size;
1226 : beforep->next = blockp->next;
1227 : } else
1228 : beforep->next = block;
1229 : } else {
1230 : /*
1231 : * Add block at head of free list.
1232 : */
1233 : hheader->head = block;
1234 : }
1235 : #endif
1236 35 : }
1237 :
1238 : void
1239 136 : HEAP_recover(Heap *h, const var_t *offsets, BUN noffsets)
1240 : {
1241 136 : HEADER *hheader;
1242 136 : CHUNK *blockp;
1243 136 : size_t dirty = 0;
1244 136 : var_t maxoff = 0;
1245 136 : BUN i;
1246 :
1247 136 : if (!h->cleanhash)
1248 : return;
1249 135 : hheader = HEAP_index(h, 0, HEADER);
1250 135 : assert(h->free >= sizeof(HEADER));
1251 135 : assert(hheader->version == HEAPVERSION);
1252 135 : assert(h->size >= hheader->firstblock);
1253 414 : for (i = 0; i < noffsets; i++)
1254 279 : if (offsets[i] > maxoff)
1255 : maxoff = offsets[i];
1256 135 : assert(maxoff < h->free);
1257 135 : if (maxoff == 0) {
1258 0 : if (hheader->head != hheader->firstblock) {
1259 0 : hheader->head = hheader->firstblock;
1260 0 : dirty = sizeof(HEADER);
1261 : }
1262 0 : blockp = HEAP_index(h, hheader->firstblock, CHUNK);
1263 0 : if (blockp->next != 0 ||
1264 0 : blockp->size != h->size - hheader->head) {
1265 0 : blockp->size = (size_t) (h->size - hheader->head);
1266 0 : blockp->next = 0;
1267 0 : dirty = hheader->firstblock + sizeof(CHUNK);
1268 : }
1269 : } else {
1270 135 : size_t block = maxoff - hheader->alignment;
1271 135 : size_t end = block + *HEAP_index(h, block, size_t);
1272 135 : size_t trail;
1273 :
1274 135 : assert(end <= h->free);
1275 135 : if (end + sizeof(CHUNK) <= h->free) {
1276 135 : blockp = HEAP_index(h, end, CHUNK);
1277 135 : if (hheader->head <= end &&
1278 135 : blockp->next == 0 &&
1279 135 : blockp->size == h->free - end)
1280 : return;
1281 0 : } else if (hheader->head == 0) {
1282 : /* no free space after last allocated block
1283 : * and no free list */
1284 : return;
1285 : }
1286 0 : block = hheader->head;
1287 0 : trail = 0;
1288 0 : while (block < maxoff && block != 0) {
1289 0 : blockp = HEAP_index(h, block, CHUNK);
1290 0 : trail = block;
1291 0 : block = blockp->next;
1292 : }
1293 0 : if (trail == 0) {
1294 : /* no free list */
1295 0 : if (end + sizeof(CHUNK) > h->free) {
1296 : /* no free space after last allocated
1297 : * block */
1298 0 : if (hheader->head != 0) {
1299 0 : hheader->head = 0;
1300 0 : dirty = sizeof(HEADER);
1301 : }
1302 : } else {
1303 : /* there is free space after last
1304 : * allocated block */
1305 0 : if (hheader->head != end) {
1306 0 : hheader->head = end;
1307 0 : dirty = sizeof(HEADER);
1308 : }
1309 0 : blockp = HEAP_index(h, end, CHUNK);
1310 0 : if (blockp->next != 0 ||
1311 0 : blockp->size != h->free - end) {
1312 0 : blockp->next = 0;
1313 0 : blockp->size = h->free - end;
1314 0 : dirty = end + sizeof(CHUNK);
1315 : }
1316 : }
1317 : } else {
1318 : /* there is a free list */
1319 0 : blockp = HEAP_index(h, trail, CHUNK);
1320 0 : if (end + sizeof(CHUNK) > h->free) {
1321 : /* no free space after last allocated
1322 : * block */
1323 0 : if (blockp->next != 0) {
1324 0 : blockp->next = 0;
1325 0 : dirty = trail + sizeof(CHUNK);
1326 : }
1327 : } else {
1328 : /* there is free space after last
1329 : * allocated block */
1330 0 : if (blockp->next != end) {
1331 0 : blockp->next = end;
1332 0 : dirty = trail + sizeof(CHUNK);
1333 : }
1334 0 : blockp = HEAP_index(h, end, CHUNK);
1335 0 : if (blockp->next != 0 ||
1336 0 : blockp->size != h->free - end) {
1337 0 : blockp->next = 0;
1338 0 : blockp->size = h->free - end;
1339 0 : dirty = end + sizeof(CHUNK);
1340 : }
1341 : }
1342 : }
1343 : }
1344 0 : h->cleanhash = false;
1345 0 : if (dirty) {
1346 0 : if (h->storage == STORE_MMAP) {
1347 0 : if (!(ATOMIC_GET(&GDKdebug) & NOSYNCMASK))
1348 0 : (void) MT_msync(h->base, dirty);
1349 : else
1350 0 : h->dirty = true;
1351 : } else
1352 0 : h->dirty = true;
1353 : }
1354 : }
|