LCOV - code coverage report
Current view: top level - gdk - gdk_heap.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 484 656 73.8 %
Date: 2024-12-19 23:10:26 Functions: 19 19 100.0 %

          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 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        1574 : HEAPcreatefile(int farmid, size_t *maxsz, const char *fn)
      56             : {
      57        1574 :         void *base = NULL;
      58        1574 :         char path[MAXPATH];
      59        1574 :         int fd;
      60             : 
      61        1574 :         if (farmid != NOFARM) {
      62             :                 /* call GDKfilepath once here instead of twice inside
      63             :                  * the calls to GDKfdlocate and GDKload */
      64        1038 :                 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        1598 :         fd = GDKfdlocate(NOFARM, fn, "wb", NULL);
      70        1611 :         if (fd >= 0) {
      71        1611 :                 close(fd);
      72        1613 :                 base = GDKload(NOFARM, fn, NULL, *maxsz, maxsz, STORE_MMAP);
      73             :         }
      74             :         return base;
      75             : }
      76             : 
      77             : static char *
      78       50167 : decompose_filename(str nme)
      79             : {
      80       50167 :         char *ext;
      81             : 
      82       50167 :         ext = strchr(nme, '.'); /* extract base and ext from heap file name */
      83       50167 :         if (ext) {
      84       50167 :                 *ext++ = 0;
      85             :         }
      86       50167 :         return ext;
      87             : }
      88             : 
      89             : /* this function is called with the theaplock held */
      90             : gdk_return
      91       49658 : HEAPgrow(Heap **hp, size_t size, bool mayshare)
      92             : {
      93       49658 :         Heap *new;
      94             : 
      95       49658 :         ATOMIC_BASE_TYPE refs = ATOMIC_GET(&(*hp)->refs);
      96       49658 :         if ((refs & HEAPREFS) == 1) {
      97       49587 :                 return HEAPextend(*hp, size, mayshare);
      98             :         }
      99          71 :         new = GDKmalloc(sizeof(Heap));
     100          71 :         if (new != NULL) {
     101          71 :                 Heap *old = *hp;
     102          71 :                 *new = (Heap) {
     103          71 :                         .farmid = old->farmid,
     104             :                         .dirty = true,
     105          71 :                         .parentid = old->parentid,
     106          71 :                         .wasempty = old->wasempty,
     107          71 :                         .hasfile = old->hasfile,
     108          71 :                         .refs = ATOMIC_VAR_INIT(1 | (refs & HEAPREMOVE)),
     109             :                 };
     110          71 :                 memcpy(new->filename, old->filename, sizeof(new->filename));
     111          71 :                 if (HEAPalloc(new, size, 1) == GDK_SUCCEED) {
     112          71 :                         new->free = old->free;
     113          71 :                         new->cleanhash = old->cleanhash;
     114          71 :                         if (old->free > 0 &&
     115          66 :                             (new->storage == STORE_MEM || old->storage == STORE_MEM))
     116          44 :                                 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          71 :                         HEAPdecref(*hp, false);
     122          71 :                         *hp = new;
     123             :                 } else {
     124           0 :                         GDKfree(new);
     125           0 :                         new = NULL;
     126             :                 }
     127             :         }
     128          71 :         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     9035048 : HEAPalloc(Heap *h, size_t nitems, size_t itemsize)
     141             : {
     142     9035048 :         size_t size = 0;
     143     9035048 :         QryCtx *qc = h->farmid == 1 ? MT_thread_get_qry_ctx() : NULL;
     144             : 
     145     9056795 :         h->base = NULL;
     146     9056795 :         h->size = 1;
     147     9056795 :         if (itemsize) {
     148             :                 /* check for overflow */
     149     9056795 :                 if (nitems > BUN_NONE / itemsize) {
     150           0 :                         GDKerror("allocating more than heap can accommodate\n");
     151           0 :                         return GDK_FAIL;
     152             :                 }
     153     9056795 :                 h->size = MAX(1, nitems) * itemsize;
     154             :         }
     155     9056795 :         h->free = 0;
     156     9056795 :         h->cleanhash = false;
     157             : 
     158             : #ifdef SIZE_CHECK_IN_HEAPS_ONLY
     159     9056795 :         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     9041111 :         size_t allocated;
     167     9041111 :         if (GDKinmemory(h->farmid) ||
     168    18102968 :             ((allocated = GDKmem_cursize()) + h->size < GDK_mem_maxsize &&
     169     9056795 :              h->size < (h->farmid == 0 ? GDK_mmap_minsize_persistent : GDK_mmap_minsize_transient) &&
     170     9076403 :              h->size < ((GDK_mem_maxsize - allocated) >> 6))) {
     171     9103518 :                 h->storage = STORE_MEM;
     172     9103518 :                 size = h->size;
     173     9103518 :                 if (qc != NULL) {
     174     5890599 :                         ATOMIC_BASE_TYPE sz = ATOMIC_ADD(&qc->datasize, size);
     175     5890599 :                         sz += size;
     176     5890599 :                         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     9103518 :                 h->base = GDKmalloc(size);
     183     9103350 :                 TRC_DEBUG(HEAP, "%s %zu %p\n", h->filename, size, h->base);
     184     9103350 :                 if (h->base == NULL && qc != NULL)
     185           0 :                         ATOMIC_SUB(&qc->datasize, size);
     186             :         }
     187             : 
     188     9060375 :         if (h->base == NULL && !GDKinmemory(h->farmid)) {
     189         538 :                 char nme[MAXPATH];
     190         538 :                 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         542 :                 h->hasfile = true;
     206         542 :                 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         542 :                 TRC_DEBUG(HEAP, "%s %zu %p (mmap)\n", h->filename, size, h->base);
     218             :         }
     219     9060379 :         h->newstorage = h->storage;
     220     9060379 :         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       65608 : HEAPextend(Heap *h, size_t size, bool mayshare)
     243             : {
     244       65608 :         size_t osize = h->size;
     245       65608 :         size_t xsize;
     246       65608 :         QryCtx *qc = h->farmid == 1 ? MT_thread_get_qry_ctx() : NULL;
     247             : 
     248       65625 :         if (size <= h->size)
     249             :                 return GDK_SUCCEED;     /* nothing to do */
     250             : 
     251       50115 :         char nme[sizeof(h->filename)], *ext;
     252       50115 :         const char *failure = "None";
     253             : 
     254       50115 :         if (GDKinmemory(h->farmid)) {
     255          44 :                 strcpy_len(nme, ":memory:", sizeof(nme));
     256          44 :                 ext = "ext";
     257             :         } else {
     258       50014 :                 strcpy_len(nme, h->filename, sizeof(nme));
     259       50154 :                 ext = decompose_filename(nme);
     260             :         }
     261       50211 :         failure = "size > h->size";
     262             : 
     263             : #ifdef SIZE_CHECK_IN_HEAPS_ONLY
     264       50211 :         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       50106 :         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       49641 :                 Heap bak = *h;
     313       49641 :                 size_t allocated;
     314       49641 :                 bool must_mmap = (!GDKinmemory(h->farmid) &&
     315       49618 :                                    (h->newstorage != STORE_MEM ||
     316       99107 :                                     (allocated = GDKmem_cursize()) + size >= GDK_mem_maxsize ||
     317       49561 :                                     size >= (h->farmid == 0 ? GDK_mmap_minsize_persistent : GDK_mmap_minsize_transient) ||
     318       48536 :                                     size >= ((GDK_mem_maxsize - allocated) >> 6)));
     319             : 
     320       49661 :                 h->size = size;
     321       49661 :                 xsize = size - osize;
     322             : 
     323             :                 /* try GDKrealloc if the heap size stays within
     324             :                  * reasonable limits */
     325       49661 :                 if (!must_mmap) {
     326       48560 :                         if (qc != NULL) {
     327       24578 :                                 ATOMIC_BASE_TYPE sz = ATOMIC_ADD(&qc->datasize, xsize);
     328       24578 :                                 sz += xsize;
     329       24578 :                                 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       49847 :                                         return GDK_FAIL;
     334             :                                 }
     335             :                         }
     336       48560 :                         h->newstorage = h->storage = STORE_MEM;
     337       48560 :                         h->base = GDKrealloc(h->base, size);
     338       48736 :                         TRC_DEBUG(HEAP, "Extending malloced heap %s %zu->%zu %p->%p\n", h->filename, bak.size, size, bak.base, h->base);
     339       48736 :                         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        1101 :                 if (!GDKinmemory(h->farmid)) {
     349             :                         /* too big: convert it to a disk-based temporary heap */
     350             : 
     351        1067 :                         assert(h->storage == STORE_MEM);
     352        1067 :                         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        1067 :                         int fd = GDKfdlocate(h->farmid, nme, "rb", ext);
     358        1081 :                         if (fd >= 0) {
     359          36 :                                 assert(h->hasfile);
     360          36 :                                 close(fd);
     361          36 :                                 fd = GDKfdlocate(h->farmid, nme, "wb", ext);
     362          36 :                                 if (fd >= 0) {
     363          36 :                                         gdk_return rc = GDKextendf(fd, size, nme);
     364          36 :                                         close(fd);
     365          36 :                                         if (rc != GDK_SUCCEED) {
     366           0 :                                                 failure = "h->storage == STORE_MEM && can_map && fd >= 0 && GDKextendf() != GDK_SUCCEED";
     367           0 :                                                 goto failed;
     368             :                                         }
     369          36 :                                         h->storage = h->newstorage == STORE_MMAP && !mayshare ? STORE_PRIV : h->newstorage;
     370             :                                         /* make sure we really MMAP */
     371          36 :                                         if (must_mmap && h->newstorage == STORE_MEM)
     372          36 :                                                 h->storage = STORE_MMAP;
     373          36 :                                         h->newstorage = h->storage;
     374             : 
     375          36 :                                         h->base = NULL;
     376          36 :                                         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          36 :                                         if (HEAPload(h, nme, ext, false) == GDK_SUCCEED) {
     380             :                                                 /* copy data to heap and free old
     381             :                                                  * memory */
     382          36 :                                                 memcpy(h->base, bak.base, bak.free);
     383          36 :                                                 HEAPfree(&bak, false);
     384          36 :                                                 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        1045 :                                 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        1045 :                                 h->base = HEAPcreatefile(h->farmid, &h->size, h->filename);
     407        1075 :                                 h->hasfile = true;
     408        1075 :                                 if (h->base) {
     409        1075 :                                         h->newstorage = h->storage = STORE_MMAP;
     410        1075 :                                         if (bak.free > 0)
     411          35 :                                                 memcpy(h->base, bak.base, bak.free);
     412        1075 :                                         HEAPfree(&bak, false);
     413        1075 :                                         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       99841 : GDKupgradevarheap(BAT *b, var_t v, BUN cap, BUN ncopy)
     443             : {
     444       99841 :         uint8_t shift = b->tshift;
     445       99841 :         uint16_t width = b->twidth;
     446       99841 :         uint8_t *pc;
     447       99841 :         uint16_t *ps;
     448       99841 :         uint32_t *pi;
     449             : #if SIZEOF_VAR_T == 8
     450       99841 :         uint64_t *pl;
     451             : #endif
     452       99841 :         size_t i, n;
     453       99841 :         size_t newsize;
     454       99841 :         bat bid = b->batCacheid;
     455       99841 :         Heap *old, *new;
     456             : 
     457       99841 :         old = b->theap;
     458             : //      assert(old->storage == STORE_MEM);
     459       99841 :         assert(old->parentid == b->batCacheid);
     460       99841 :         assert(b->tbaseoff == 0);
     461       99841 :         assert(width != 0);
     462       99841 :         assert(v >= GDK_VAROFFSET);
     463             : 
     464      129691 :         while (width < SIZEOF_VAR_T && (width <= 2 ? v - GDK_VAROFFSET : v) >= ((var_t) 1 << (8 * width))) {
     465       29850 :                 width <<= 1;
     466       29850 :                 shift++;
     467             :         }
     468             :         /* if cap(acity) given (we check whether it is larger than the
     469             :          * old), then grow to cap */
     470       99841 :         if (cap > (old->size >> b->tshift))
     471        6381 :                 newsize = cap << shift;
     472             :         else
     473       93460 :                 newsize = (old->size >> b->tshift) << shift;
     474       99841 :         if (b->twidth == width) {
     475       71710 :                 if (newsize <= old->size) {
     476             :                         /* nothing to do */
     477       66713 :                         if (cap > b->batCapacity)
     478           0 :                                 BATsetcapacity(b, cap);
     479       66713 :                         return GDK_SUCCEED;
     480             :                 }
     481        4997 :                 return BATextend(b, newsize >> shift);
     482             :         }
     483             : 
     484       28131 :         n = MIN(ncopy, old->size >> b->tshift);
     485             : 
     486       42179 :         MT_thread_setalgorithm(n ? "widen offset heap" : "widen empty offset heap");
     487             : 
     488       28279 :         new = GDKmalloc(sizeof(Heap));
     489       28286 :         if (new == NULL)
     490             :                 return GDK_FAIL;
     491       28286 :         *new = (Heap) {
     492       28286 :                 .farmid = old->farmid,
     493             :                 .dirty = true,
     494       28286 :                 .parentid = old->parentid,
     495       28286 :                 .wasempty = old->wasempty,
     496       28286 :                 .refs = ATOMIC_VAR_INIT(1 | (ATOMIC_GET(&old->refs) & HEAPREMOVE)),
     497             :         };
     498       28286 :         settailname(new, BBP_physical(b->batCacheid), b->ttype, width);
     499       28269 :         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       28292 :         new->free = old->free << (shift - b->tshift);
     505             :         /* per the above, width > b->twidth, so certain combinations are
     506             :          * impossible */
     507       28292 :         switch (width) {
     508       25453 :         case 2:
     509       25453 :                 ps = (uint16_t *) new->base;
     510       25453 :                 switch (b->twidth) {
     511       25453 :                 case 1:
     512       25453 :                         pc = (uint8_t *) old->base;
     513     1248027 :                         for (i = 0; i < n; i++)
     514     1222574 :                                 ps[i] = pc[i];
     515       25453 :                         break;
     516             :                 default:
     517           0 :                         MT_UNREACHABLE();
     518             :                 }
     519             : #ifndef NDEBUG
     520             :                 /* valgrind */
     521       25453 :                 memset(ps + n, 0, new->size - n * 2);
     522             : #endif
     523       25453 :                 break;
     524        2839 :         case 4:
     525        2839 :                 pi = (uint32_t *) new->base;
     526        2839 :                 switch (b->twidth) {
     527        1661 :                 case 1:
     528        1661 :                         pc = (uint8_t *) old->base;
     529        1665 :                         for (i = 0; i < n; i++)
     530           4 :                                 pi[i] = pc[i] + GDK_VAROFFSET;
     531             :                         break;
     532        1178 :                 case 2:
     533        1178 :                         ps = (uint16_t *) old->base;
     534     1571181 :                         for (i = 0; i < n; i++)
     535     1570003 :                                 pi[i] = ps[i] + GDK_VAROFFSET;
     536             :                         break;
     537             :                 default:
     538           0 :                         MT_UNREACHABLE();
     539             :                 }
     540             : #ifndef NDEBUG
     541             :                 /* valgrind */
     542        2839 :                 memset(pi + n, 0, new->size - n * 4);
     543             : #endif
     544        2839 :                 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       28292 :         MT_lock_set(&b->theaplock);
     577       28275 :         b->tshift = shift;
     578       28275 :         b->twidth = width;
     579       28275 :         if (cap > BATcapacity(b))
     580        1374 :                 BATsetcapacity(b, cap);
     581       28273 :         b->theap = new;
     582       28273 :         if (BBP_status(bid) & (BBPEXISTING|BBPDELETED) && b->oldtail == NULL) {
     583        2099 :                 b->oldtail = old;
     584        2099 :                 if ((ATOMIC_OR(&old->refs, DELAYEDREMOVE) & HEAPREFS) == 1) {
     585             :                         /* we have the only reference, we can free the
     586             :                          * memory */
     587        2101 :                         HEAPfree(old, false);
     588             :                 }
     589             :         } else {
     590       26174 :                 ValPtr p = BATgetprop_nolock(b, (enum prop_t) 20);
     591       52329 :                 HEAPdecref(old, p == NULL || strcmp(((Heap*) p->val.pval)->filename, old->filename) != 0);
     592             :         }
     593       28271 :         MT_lock_unset(&b->theaplock);
     594       28221 :         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        4871 : HEAPcopy(Heap *dst, Heap *src, size_t offset)
     604             : {
     605        4871 :         if (offset > src->free)
     606             :                 offset = src->free;
     607        4871 :         if (HEAPalloc(dst, src->free - offset, 1) == GDK_SUCCEED) {
     608        4881 :                 dst->free = src->free - offset;
     609        4881 :                 memcpy(dst->base, src->base + offset, src->free - offset);
     610        4881 :                 dst->cleanhash = src->cleanhash;
     611        4881 :                 dst->dirty = true;
     612        4881 :                 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    16640409 : HEAPfree(Heap *h, bool rmheap)
     621             : {
     622    16640409 :         if (h->base) {
     623     9171889 :                 if (h->farmid == 1 && (h->storage == STORE_MEM || h->storage == STORE_MMAP || h->storage == STORE_PRIV)) {
     624     8580545 :                         QryCtx *qc = MT_thread_get_qry_ctx();
     625     8585397 :                         if (qc)
     626     5929914 :                                 ATOMIC_SUB(&qc->datasize, h->size);
     627             :                 }
     628     9176741 :                 if (h->storage == STORE_MEM) {       /* plain memory */
     629     9174083 :                         TRC_DEBUG(HEAP, "HEAPfree %s %zu %p\n", h->filename, h->size, h->base);
     630     9174083 :                         GDKfree(h->base);
     631        2658 :                 } 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        2611 :                 } else if (h->storage != STORE_NOWN) {       /* mapped file, or STORE_PRIV */
     635        5222 :                         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        2615 :                         if (ret != GDK_SUCCEED) {
     642           0 :                                 GDKsyserror("HEAPfree: %s was not mapped\n",
     643             :                                             h->filename);
     644           0 :                                 assert(0);
     645             :                         }
     646        2615 :                         TRC_DEBUG(HEAP, "munmap(base=%p, size=%zu) = %d\n",
     647             :                                   (void *)h->base, h->size, (int) ret);
     648             :                 }
     649             :         }
     650    16646577 :         h->base = NULL;
     651    16646577 :         if (rmheap && !GDKinmemory(h->farmid)) {
     652    15953965 :                 char path[MAXPATH];
     653             : 
     654    15953965 :                 if (h->hasfile) {
     655       36484 :                         if (GDKfilepath(path, sizeof(path), h->farmid, BATDIR, h->filename, NULL) == GDK_SUCCEED) {
     656       36484 :                                 int ret = MT_remove(path);
     657       36483 :                                 if (ret == -1) {
     658             :                                         /* unexpectedly not present */
     659           0 :                                         perror(path);
     660             :                                 }
     661       36483 :                                 assert(ret == 0);
     662       36483 :                                 h->hasfile = false;
     663             :                         }
     664       36483 :                         if (GDKfilepath(path, sizeof(path), h->farmid, BATDIR, h->filename, "new") == GDK_SUCCEED) {
     665             :                                 /* in practice, should never be present */
     666       36483 :                                 int ret = MT_remove(path);
     667       36484 :                                 if (ret == -1 && errno != ENOENT)
     668           0 :                                         perror(path);
     669       36484 :                                 assert(ret == -1 && errno == ENOENT);
     670             :                         }
     671             : #ifndef NDEBUG
     672    15917481 :                 } else if (GDKfilepath(path, sizeof(path), h->farmid, BATDIR, h->filename, NULL) == GDK_SUCCEED) {
     673             :                         /* should not be present */
     674    15901335 :                         struct stat st;
     675    15901335 :                         assert(stat(path, &st) == -1 && errno == ENOENT);
     676             : #endif
     677             :                 }
     678             :         }
     679    16502866 : }
     680             : 
     681             : void
     682    78497929 : HEAPdecref(Heap *h, bool remove)
     683             : {
     684    78497929 :         if (remove)
     685    13032063 :                 ATOMIC_OR(&h->refs, HEAPREMOVE);
     686    78497929 :         ATOMIC_BASE_TYPE refs = ATOMIC_DEC(&h->refs);
     687             :         //printf("dec ref(%d) %p %d\n", (int)h->refs, h, h->parentid);
     688    78497929 :         switch (refs & HEAPREFS) {
     689    13094987 :         case 0:
     690    13094987 :                 HEAPfree(h, (bool) (refs & HEAPREMOVE));
     691    12945446 :                 GDKfree(h);
     692    12945446 :                 break;
     693    29658570 :         case 1:
     694    29658570 :                 if (refs & DELAYEDREMOVE) {
     695             :                         /* only reference left is b->oldtail */
     696        1719 :                         HEAPfree(h, false);
     697             :                 }
     698             :                 break;
     699             :         default:
     700             :                 break;
     701             :         }
     702    78486871 : }
     703             : 
     704             : void
     705    65166198 : HEAPincref(Heap *h)
     706             : {
     707             :         //printf("inc ref(%d) %p %d\n", (int)h->refs, h, h->parentid);
     708    65166198 :         ATOMIC_INC(&h->refs);
     709    65166198 : }
     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       25450 : HEAPload(Heap *h, const char *nme, const char *ext, bool trunc)
     718             : {
     719       25450 :         size_t minsize;
     720       25450 :         int ret = 0;
     721       25450 :         char srcpath[MAXPATH], dstpath[MAXPATH];
     722       25450 :         lng t0;
     723       25450 :         const char suffix[] = ".new";
     724             : 
     725       25450 :         if (h->storage == STORE_INVALID || h->newstorage == STORE_INVALID) {
     726       25414 :                 size_t allocated;
     727       50828 :                 h->storage = h->newstorage = h->size < (h->farmid == 0 ? GDK_mmap_minsize_persistent : GDK_mmap_minsize_transient) &&
     728       24453 :                         (allocated = GDKmem_cursize()) < GDK_mem_maxsize &&
     729       49867 :                         h->size < ((GDK_mem_maxsize - allocated) >> 6) ? STORE_MEM : STORE_MMAP;
     730             :         }
     731             : 
     732       25450 :         minsize = (h->size + GDK_mmap_pagesize - 1) & ~(GDK_mmap_pagesize - 1);
     733       25450 :         if (h->storage != STORE_MEM && minsize != h->size)
     734         127 :                 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       25450 :         if (trunc) {
     739             :                 /* round up mmap heap sizes to GDK_mmap_pagesize
     740             :                  * segments, also add some slack */
     741       24271 :                 int fd;
     742             : 
     743       24271 :                 if (minsize == 0)
     744           0 :                         minsize = GDK_mmap_pagesize; /* minimum of one page */
     745       24271 :                 if ((fd = GDKfdlocate(h->farmid, nme, "rb+", ext)) >= 0) {
     746       24271 :                         struct stat stb;
     747       24271 :                         if (fstat(fd, &stb) == 0 &&
     748       24272 :                             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       24271 :                         close(fd);
     758             :                 }
     759             :         }
     760             : 
     761       25449 :         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       25449 :         if (GDKfilepath(dstpath, sizeof(dstpath), h->farmid, BATDIR, nme, ext) != GDK_SUCCEED)
     770             :                 return GDK_FAIL;
     771       25450 :         strconcat_len(srcpath, sizeof(srcpath), dstpath, suffix, NULL);
     772             : 
     773       25451 :         t0 = GDKusec();
     774       25450 :         ret = MT_rename(srcpath, dstpath);
     775       25451 :         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       25451 :         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       25451 :         size_t size = h->size;
     788       25451 :         QryCtx *qc = NULL;
     789       25451 :         if (h->storage != STORE_MEM)
     790         998 :                 size = (size + GDK_mmap_pagesize - 1) & ~(GDK_mmap_pagesize - 1);
     791       25451 :         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       25451 :         if (h->storage == STORE_MEM && h->free == 0) {
     802           0 :                 h->base = GDKmalloc(h->size);
     803           0 :                 h->wasempty = true;
     804             :         } else {
     805       25451 :                 if (h->free == 0) {
     806           0 :                         int fd = GDKfdlocate(h->farmid, nme, "wb", ext);
     807           0 :                         if (fd >= 0)
     808           0 :                                 close(fd);
     809           0 :                         h->wasempty = true;
     810             :                 }
     811       25451 :                 h->base = GDKload(h->farmid, nme, ext, h->free, &h->size, h->storage);
     812             :         }
     813       25451 :         if (h->base == NULL) {
     814           0 :                 if (qc != NULL)
     815           0 :                         ATOMIC_SUB(&qc->datasize, size);
     816           0 :                 return GDK_FAIL; /* file could  not be read satisfactorily */
     817             :         }
     818             : 
     819       25451 :         h->dirty = false;    /* we just read it, so it's clean */
     820       25451 :         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      341537 : HEAPsave(Heap *h, const char *nme, const char *ext, bool dosync, BUN free, MT_Lock *lock)
     840             : {
     841      341537 :         storage_t store = h->newstorage;
     842      341537 :         long_str extension;
     843      341537 :         gdk_return rc;
     844      341537 :         const char suffix[] = ".new";
     845             : 
     846      341537 :         if (h->base == NULL) {
     847           0 :                 GDKerror("no heap to save\n");
     848           0 :                 return GDK_FAIL;
     849             :         }
     850      341537 :         if (free == 0) {
     851             :                 /* nothing to see, please move on */
     852       10625 :                 if (lock)
     853       10625 :                         MT_lock_set(lock);
     854       10625 :                 h->wasempty = true;
     855           0 :                 if (lock)
     856       10625 :                         MT_lock_unset(lock);
     857       10625 :                 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       10625 :                 return GDK_SUCCEED;
     863             :         }
     864      330912 :         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      330912 :         } else if (store != STORE_MEM) {
     871        1077 :                 store = h->storage;
     872             :         }
     873      330912 :         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      330912 :         rc = GDKsave(h->farmid, nme, ext, h->base, free, store, dosync);
     878      330912 :         if (lock)
     879      303593 :                 MT_lock_set(lock);
     880      330912 :         if (rc == GDK_SUCCEED) {
     881      330912 :                 h->hasfile = true;
     882      330912 :                 h->dirty = free != h->free;
     883      330912 :                 h->wasempty = false;
     884             :         } else {
     885           0 :                 h->dirty = true;
     886           0 :                 if (store != STORE_MMAP)
     887           0 :                         h->hasfile = false;
     888             :         }
     889      330912 :         if (lock)
     890      303593 :                 MT_lock_unset(lock);
     891             :         return rc;
     892             : }
     893             : 
     894             : 
     895             : /* Return the (virtual) size of the heap. */
     896             : size_t
     897      355178 : HEAPvmsize(Heap *h)
     898             : {
     899      355178 :         if (h && h->base && h->free)
     900       56685 :                 return h->size;
     901             :         return 0;
     902             : }
     903             : 
     904             : /* Return the allocated size of the heap, i.e. if the heap is memory
     905             :  * mapped and not copy-on-write (privately mapped), return 0. */
     906             : size_t
     907      355178 : HEAPmemsize(Heap *h)
     908             : {
     909      355178 :         if (h && h->base && h->free && h->storage != STORE_MMAP)
     910       56425 :                 return h->size;
     911             :         return 0;
     912             : }
     913             : 
     914             : 
     915             : /*
     916             :  * @+ Standard Heap Library
     917             :  * This library contains some routines which implement a @emph{
     918             :  * malloc} and @emph{ free} function on the Monet @emph{Heap}
     919             :  * structure. They are useful when implementing a new @emph{
     920             :  * variable-size} atomic data type, or for implementing new search
     921             :  * accelerators.  All functions start with the prefix @emph{HEAP_}. T
     922             :  *
     923             :  * Due to non-careful design, the HEADER field was found to be
     924             :  * 32/64-bit dependent.  As we do not (yet) want to change the BAT
     925             :  * image on disk, This is now fixed by switching on-the-fly between
     926             :  * two representations. We ensure that the 64-bit memory
     927             :  * representation is just as long as the 32-bits version (20 bytes) so
     928             :  * the rest of the heap never needs to shift. The function
     929             :  * HEAP_checkformat converts at load time dynamically between the
     930             :  * layout found on disk and the memory format.  Recognition of the
     931             :  * header mode is done by looking at the first two ints: alignment
     932             :  * must be 4 or 8, and head can never be 4 or eight.
     933             :  *
     934             :  * TODO: user HEADER64 for both 32 and 64 bits (requires BAT format
     935             :  * change)
     936             :  */
     937             : 
     938             : #define HEAPVERSION     20030408
     939             : 
     940             : typedef struct heapheader {
     941             :         size_t head;            /* index to first free block */
     942             :         int alignment;          /* alignment of objects on heap */
     943             :         size_t firstblock;      /* first block in heap */
     944             :         int version;
     945             :         int (*sizefcn)(const void *);   /* ADT function to ask length */
     946             : } HEADER32;
     947             : 
     948             : typedef struct {
     949             :         int version;
     950             :         int alignment;
     951             :         size_t head;
     952             :         size_t firstblock;
     953             :         int (*sizefcn)(const void *);
     954             : } HEADER64;
     955             : 
     956             : #if SIZEOF_SIZE_T==8
     957             : typedef HEADER64 HEADER;
     958             : typedef HEADER32 HEADER_OTHER;
     959             : #else
     960             : typedef HEADER32 HEADER;
     961             : typedef HEADER64 HEADER_OTHER;
     962             : #endif
     963             : typedef struct hfblock {
     964             :         size_t size;            /* Size of this block in freelist */
     965             :         size_t next;            /* index of next block */
     966             : } CHUNK;
     967             : 
     968             : #define roundup_8(x)    (((x)+7)&~7)
     969             : #define roundup_4(x)    (((x)+3)&~3)
     970             : #define blocksize(h,p)  ((p)->size)
     971             : 
     972             : static inline size_t
     973        2002 : roundup_num(size_t number, int alignment)
     974             : {
     975        2002 :         size_t rval;
     976             : 
     977        2002 :         rval = number + (size_t) alignment - 1;
     978        2002 :         rval -= (rval % (size_t) alignment);
     979        2002 :         return rval;
     980             : }
     981             : 
     982             : #define HEAP_index(HEAP,INDEX,TYPE)     ((TYPE *)((char *) (HEAP)->base + (INDEX)))
     983             : 
     984             : 
     985             : static void
     986        2002 : HEAP_empty(Heap *heap, size_t nprivate, int alignment)
     987             : {
     988             :         /* Find position of header block. */
     989        2002 :         HEADER *hheader = HEAP_index(heap, 0, HEADER);
     990             : 
     991             :         /* Calculate position of first and only free block. */
     992        2002 :         size_t head = roundup_num((size_t) (roundup_8(sizeof(HEADER)) + roundup_8(nprivate)), alignment);
     993        2002 :         CHUNK *headp = HEAP_index(heap, head, CHUNK);
     994             : 
     995        2002 :         assert(roundup_8(sizeof(HEADER)) + roundup_8(nprivate) <= VAR_MAX);
     996             : 
     997             :         /* Fill header block. */
     998        2002 :         hheader->head = head;
     999        2002 :         hheader->sizefcn = NULL;
    1000        2002 :         hheader->alignment = alignment;
    1001        2002 :         hheader->firstblock = head;
    1002        2002 :         hheader->version = HEAPVERSION;
    1003             : 
    1004             :         /* Fill first free block. */
    1005        2002 :         assert(heap->size - head <= VAR_MAX);
    1006        2002 :         headp->size = (size_t) (heap->size - head);
    1007        2002 :         headp->next = 0;
    1008             : 
    1009        2002 :         heap->dirty = true;
    1010        2002 : }
    1011             : 
    1012             : gdk_return
    1013        1993 : HEAP_initialize(Heap *heap, size_t nbytes, size_t nprivate, int alignment)
    1014             : {
    1015             :         /* For now we know about two alignments. */
    1016        1993 :         if (alignment != 8) {
    1017             :                 alignment = 4;
    1018             :         }
    1019        1993 :         if ((size_t) alignment < sizeof(size_t))
    1020             :                 alignment = (int) sizeof(size_t);
    1021             : 
    1022             :         /* Calculate number of bytes needed for heap + structures. */
    1023             :         {
    1024        1993 :                 size_t total = 100 + nbytes + nprivate + sizeof(HEADER) + sizeof(CHUNK);
    1025             : 
    1026        1993 :                 total = roundup_8(total);
    1027        1993 :                 if (HEAPalloc(heap, total, 1) != GDK_SUCCEED)
    1028             :                         return GDK_FAIL;
    1029        2004 :                 heap->free = heap->size;
    1030             :         }
    1031             : 
    1032             :         /* initialize heap as empty */
    1033        2004 :         HEAP_empty(heap, nprivate, alignment);
    1034        2004 :         return GDK_SUCCEED;
    1035             : }
    1036             : 
    1037             : 
    1038             : var_t
    1039     7387678 : HEAP_malloc(BAT *b, size_t nbytes)
    1040             : {
    1041     7387678 :         Heap *heap = b->tvheap;
    1042     7387678 :         size_t block, trail, ttrail;
    1043     7387678 :         CHUNK *blockp;
    1044     7387678 :         CHUNK *trailp;
    1045     7387678 :         HEADER *hheader = HEAP_index(heap, 0, HEADER);
    1046             : 
    1047             :         /* add space for size field */
    1048     7387678 :         nbytes += hheader->alignment;
    1049     7387678 :         nbytes = roundup_8(nbytes);
    1050     7387678 :         if (nbytes < sizeof(CHUNK))
    1051             :                 nbytes = (size_t) sizeof(CHUNK);
    1052             : 
    1053             :         /* block  -- points to block with acceptable size (if available).
    1054             :          * trail  -- points to predecessor of block.
    1055             :          * ttrail -- points to predecessor of trail.
    1056             :          */
    1057     7387678 :         ttrail = 0;
    1058     7387678 :         trail = 0;
    1059     7387812 :         for (block = hheader->head; block != 0; block = blockp->next) {
    1060     7387834 :                 blockp = HEAP_index(heap, block, CHUNK);
    1061             : 
    1062     7387834 :                 assert(trail == 0 || block > trail);
    1063     7387834 :                 if (trail != 0 && block <= trail) {
    1064           0 :                         GDKerror("Free list is not orderered\n");
    1065           0 :                         return (var_t) -1;
    1066             :                 }
    1067             : 
    1068     7387834 :                 if (blockp->size >= nbytes)
    1069             :                         break;
    1070         134 :                 ttrail = trail;
    1071         134 :                 trail = block;
    1072             :         }
    1073             : 
    1074             :         /* If no block of acceptable size is found we try to enlarge
    1075             :          * the heap. */
    1076     7387678 :         if (block == 0) {
    1077         169 :                 size_t newsize;
    1078             : 
    1079         169 :                 assert(heap->free + MAX(heap->free, nbytes) <= VAR_MAX);
    1080             : #if SIZEOF_SIZE_T == 4
    1081             :                 newsize = MIN(heap->free, (size_t) 1 << 20);
    1082             : #else
    1083         169 :                 newsize = MIN(heap->free, (size_t) 1 << 30);
    1084             : #endif
    1085         169 :                 newsize = (size_t) roundup_8(heap->free + MAX(newsize, nbytes));
    1086         169 :                 assert(heap->free <= VAR_MAX);
    1087         169 :                 block = (size_t) heap->free; /* current end-of-heap */
    1088             : 
    1089             :                 /* Increase the size of the heap. */
    1090         169 :                 TRC_DEBUG(HEAP, "HEAPextend in HEAP_malloc %s %zu %zu\n", heap->filename, heap->size, newsize);
    1091         169 :                 if (HEAPgrow(&b->tvheap, newsize, false) != GDK_SUCCEED) {
    1092             :                         return (var_t) -1;
    1093             :                 }
    1094         170 :                 heap = b->tvheap;
    1095         170 :                 heap->free = newsize;
    1096         170 :                 heap->dirty = true;
    1097         170 :                 hheader = HEAP_index(heap, 0, HEADER);
    1098             : 
    1099         170 :                 blockp = HEAP_index(heap, block, CHUNK);
    1100         170 :                 trailp = HEAP_index(heap, trail, CHUNK);
    1101             : 
    1102         170 :                 blockp->next = 0;
    1103         170 :                 assert(heap->free - block <= VAR_MAX);
    1104         170 :                 blockp->size = (size_t) (heap->free - block);     /* determine size of allocated block */
    1105             : 
    1106             :                 /* Try to join the last block in the freelist and the
    1107             :                  * newly allocated memory */
    1108         170 :                 if ((trail != 0) && (trail + trailp->size == block)) {
    1109         135 :                         trailp->size += blockp->size;
    1110         135 :                         trailp->next = blockp->next;
    1111             : 
    1112         135 :                         block = trail;
    1113         135 :                         trail = ttrail;
    1114             :                 }
    1115             :         }
    1116             : 
    1117             :         /* Now we have found a block which is big enough in block.
    1118             :          * The predecessor of this block is in trail. */
    1119     7387679 :         blockp = HEAP_index(heap, block, CHUNK);
    1120             : 
    1121             :         /* If selected block is bigger than block needed split block
    1122             :          * in two.
    1123             :          * TUNE: use different amount than 2*sizeof(CHUNK) */
    1124     7387679 :         if (blockp->size >= nbytes + 2 * sizeof(CHUNK)) {
    1125     7387844 :                 size_t newblock = block + nbytes;
    1126     7387844 :                 CHUNK *newblockp = HEAP_index(heap, newblock, CHUNK);
    1127             : 
    1128     7387844 :                 newblockp->size = blockp->size - nbytes;
    1129     7387844 :                 newblockp->next = blockp->next;
    1130             : 
    1131     7387844 :                 blockp->next = newblock;
    1132     7387844 :                 blockp->size = nbytes;
    1133             :         }
    1134             : 
    1135             :         /* Delete block from freelist */
    1136     7387679 :         if (trail == 0) {
    1137     7387679 :                 hheader->head = blockp->next;
    1138             :         } else {
    1139           0 :                 trailp = HEAP_index(heap, trail, CHUNK);
    1140             : 
    1141           0 :                 trailp->next = blockp->next;
    1142             :         }
    1143             : 
    1144     7387679 :         block += hheader->alignment;
    1145     7387679 :         return (var_t) block;
    1146             : }
    1147             : 
    1148             : void
    1149          35 : HEAP_free(Heap *heap, var_t mem)
    1150             : {
    1151             : /* we cannot free pieces of the heap because we may have used
    1152             :  * append_varsized_bat to create the heap; if we did, there may be
    1153             :  * multiple locations in the offset heap that refer to the same entry in
    1154             :  * the vheap, so we cannot free any until we free all */
    1155          35 :         (void) heap;
    1156          35 :         (void) mem;
    1157             : #if 0
    1158             :         HEADER *hheader = HEAP_index(heap, 0, HEADER);
    1159             :         CHUNK *beforep;
    1160             :         CHUNK *blockp;
    1161             :         CHUNK *afterp;
    1162             :         size_t after, before, block = mem;
    1163             : 
    1164             :         assert(hheader->alignment == 8 || hheader->alignment == 4);
    1165             :         if (hheader->alignment != 8 && hheader->alignment != 4) {
    1166             :                 GDKerror("Heap structure corrupt\n");
    1167             :                 return;
    1168             :         }
    1169             : 
    1170             :         block -= hheader->alignment;
    1171             :         blockp = HEAP_index(heap, block, CHUNK);
    1172             : 
    1173             :         /* block   -- block which we want to free
    1174             :          * before  -- first free block before block
    1175             :          * after   -- first free block after block
    1176             :          */
    1177             : 
    1178             :         before = 0;
    1179             :         for (after = hheader->head; after != 0; after = HEAP_index(heap, after, CHUNK)->next) {
    1180             :                 if (after > block)
    1181             :                         break;
    1182             :                 before = after;
    1183             :         }
    1184             : 
    1185             :         beforep = HEAP_index(heap, before, CHUNK);
    1186             :         afterp = HEAP_index(heap, after, CHUNK);
    1187             : 
    1188             :         /* If it is not the last free block. */
    1189             :         if (after != 0) {
    1190             :                 /*
    1191             :                  * If this block and the block after are consecutive.
    1192             :                  */
    1193             :                 if (block + blockp->size == after) {
    1194             :                         /*
    1195             :                          * We unite them.
    1196             :                          */
    1197             :                         blockp->size += afterp->size;
    1198             :                         blockp->next = afterp->next;
    1199             :                 } else
    1200             :                         blockp->next = after;
    1201             :         } else {
    1202             :                 /*
    1203             :                  * It is the last block in the freelist.
    1204             :                  */
    1205             :                 blockp->next = 0;
    1206             :         }
    1207             : 
    1208             :         /*
    1209             :          * If it is not the first block in the list.
    1210             :          */
    1211             :         if (before != 0) {
    1212             :                 /*
    1213             :                  * If the before block and this block are consecutive.
    1214             :                  */
    1215             :                 if (before + beforep->size == block) {
    1216             :                         /*
    1217             :                          * We unite them.
    1218             :                          */
    1219             :                         beforep->size += blockp->size;
    1220             :                         beforep->next = blockp->next;
    1221             :                 } else
    1222             :                         beforep->next = block;
    1223             :         } else {
    1224             :                 /*
    1225             :                  * Add block at head of free list.
    1226             :                  */
    1227             :                 hheader->head = block;
    1228             :         }
    1229             : #endif
    1230          35 : }
    1231             : 
    1232             : void
    1233         135 : HEAP_recover(Heap *h, const var_t *offsets, BUN noffsets)
    1234             : {
    1235         135 :         HEADER *hheader;
    1236         135 :         CHUNK *blockp;
    1237         135 :         size_t dirty = 0;
    1238         135 :         var_t maxoff = 0;
    1239         135 :         BUN i;
    1240             : 
    1241         135 :         if (!h->cleanhash)
    1242             :                 return;
    1243         135 :         hheader = HEAP_index(h, 0, HEADER);
    1244         135 :         assert(h->free >= sizeof(HEADER));
    1245         135 :         assert(hheader->version == HEAPVERSION);
    1246         135 :         assert(h->size >= hheader->firstblock);
    1247         414 :         for (i = 0; i < noffsets; i++)
    1248         279 :                 if (offsets[i] > maxoff)
    1249             :                         maxoff = offsets[i];
    1250         135 :         assert(maxoff < h->free);
    1251         135 :         if (maxoff == 0) {
    1252           0 :                 if (hheader->head != hheader->firstblock) {
    1253           0 :                         hheader->head = hheader->firstblock;
    1254           0 :                         dirty = sizeof(HEADER);
    1255             :                 }
    1256           0 :                 blockp = HEAP_index(h, hheader->firstblock, CHUNK);
    1257           0 :                 if (blockp->next != 0 ||
    1258           0 :                     blockp->size != h->size - hheader->head) {
    1259           0 :                         blockp->size = (size_t) (h->size - hheader->head);
    1260           0 :                         blockp->next = 0;
    1261           0 :                         dirty = hheader->firstblock + sizeof(CHUNK);
    1262             :                 }
    1263             :         } else {
    1264         135 :                 size_t block = maxoff - hheader->alignment;
    1265         135 :                 size_t end = block + *HEAP_index(h, block, size_t);
    1266         135 :                 size_t trail;
    1267             : 
    1268         135 :                 assert(end <= h->free);
    1269         135 :                 if (end + sizeof(CHUNK) <= h->free) {
    1270         135 :                         blockp = HEAP_index(h, end, CHUNK);
    1271         135 :                         if (hheader->head <= end &&
    1272         135 :                             blockp->next == 0 &&
    1273         135 :                             blockp->size == h->free - end)
    1274             :                                 return;
    1275           0 :                 } else if (hheader->head == 0) {
    1276             :                         /* no free space after last allocated block
    1277             :                          * and no free list */
    1278             :                         return;
    1279             :                 }
    1280           0 :                 block = hheader->head;
    1281           0 :                 trail = 0;
    1282           0 :                 while (block < maxoff && block != 0) {
    1283           0 :                         blockp = HEAP_index(h, block, CHUNK);
    1284           0 :                         trail = block;
    1285           0 :                         block = blockp->next;
    1286             :                 }
    1287           0 :                 if (trail == 0) {
    1288             :                         /* no free list */
    1289           0 :                         if (end + sizeof(CHUNK) > h->free) {
    1290             :                                 /* no free space after last allocated
    1291             :                                  * block */
    1292           0 :                                 if (hheader->head != 0) {
    1293           0 :                                         hheader->head = 0;
    1294           0 :                                         dirty = sizeof(HEADER);
    1295             :                                 }
    1296             :                         } else {
    1297             :                                 /* there is free space after last
    1298             :                                  * allocated block */
    1299           0 :                                 if (hheader->head != end) {
    1300           0 :                                         hheader->head = end;
    1301           0 :                                         dirty = sizeof(HEADER);
    1302             :                                 }
    1303           0 :                                 blockp = HEAP_index(h, end, CHUNK);
    1304           0 :                                 if (blockp->next != 0 ||
    1305           0 :                                     blockp->size != h->free - end) {
    1306           0 :                                         blockp->next = 0;
    1307           0 :                                         blockp->size = h->free - end;
    1308           0 :                                         dirty = end + sizeof(CHUNK);
    1309             :                                 }
    1310             :                         }
    1311             :                 } else {
    1312             :                         /* there is a free list */
    1313           0 :                         blockp = HEAP_index(h, trail, CHUNK);
    1314           0 :                         if (end + sizeof(CHUNK) > h->free) {
    1315             :                                 /* no free space after last allocated
    1316             :                                  * block */
    1317           0 :                                 if (blockp->next != 0) {
    1318           0 :                                         blockp->next = 0;
    1319           0 :                                         dirty = trail + sizeof(CHUNK);
    1320             :                                 }
    1321             :                         } else {
    1322             :                                 /* there is free space after last
    1323             :                                  * allocated block */
    1324           0 :                                 if (blockp->next != end) {
    1325           0 :                                         blockp->next = end;
    1326           0 :                                         dirty = trail + sizeof(CHUNK);
    1327             :                                 }
    1328           0 :                                 blockp = HEAP_index(h, end, CHUNK);
    1329           0 :                                 if (blockp->next != 0 ||
    1330           0 :                                     blockp->size != h->free - end) {
    1331           0 :                                         blockp->next = 0;
    1332           0 :                                         blockp->size = h->free - end;
    1333           0 :                                         dirty = end + sizeof(CHUNK);
    1334             :                                 }
    1335             :                         }
    1336             :                 }
    1337             :         }
    1338           0 :         h->cleanhash = false;
    1339           0 :         if (dirty) {
    1340           0 :                 if (h->storage == STORE_MMAP) {
    1341           0 :                         if (!(ATOMIC_GET(&GDKdebug) & NOSYNCMASK))
    1342           0 :                                 (void) MT_msync(h->base, dirty);
    1343             :                         else
    1344           0 :                                 h->dirty = true;
    1345             :                 } else
    1346           0 :                         h->dirty = true;
    1347             :         }
    1348             : }

Generated by: LCOV version 1.14