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

Generated by: LCOV version 1.14