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-20 21:24:02 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        1570 : HEAPcreatefile(int farmid, size_t *maxsz, const char *fn)
      56             : {
      57        1570 :         void *base = NULL;
      58        1570 :         char path[MAXPATH];
      59        1570 :         int fd;
      60             : 
      61        1570 :         if (farmid != NOFARM) {
      62             :                 /* call GDKfilepath once here instead of twice inside
      63             :                  * the calls to GDKfdlocate and GDKload */
      64        1034 :                 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        1596 :         fd = GDKfdlocate(NOFARM, fn, "wb", NULL);
      70        1608 :         if (fd >= 0) {
      71        1608 :                 close(fd);
      72        1614 :                 base = GDKload(NOFARM, fn, NULL, *maxsz, maxsz, STORE_MMAP);
      73             :         }
      74             :         return base;
      75             : }
      76             : 
      77             : static char *
      78       50559 : decompose_filename(str nme)
      79             : {
      80       50559 :         char *ext;
      81             : 
      82       50559 :         ext = strchr(nme, '.'); /* extract base and ext from heap file name */
      83       50559 :         if (ext) {
      84       50559 :                 *ext++ = 0;
      85             :         }
      86       50559 :         return ext;
      87             : }
      88             : 
      89             : /* this function is called with the theaplock held */
      90             : gdk_return
      91       49828 : HEAPgrow(Heap **hp, size_t size, bool mayshare)
      92             : {
      93       49828 :         Heap *new;
      94             : 
      95       49828 :         ATOMIC_BASE_TYPE refs = ATOMIC_GET(&(*hp)->refs);
      96       49828 :         if ((refs & HEAPREFS) == 1) {
      97       49761 :                 return HEAPextend(*hp, size, mayshare);
      98             :         }
      99          67 :         new = GDKmalloc(sizeof(Heap));
     100          67 :         if (new != NULL) {
     101          67 :                 Heap *old = *hp;
     102          67 :                 *new = (Heap) {
     103          67 :                         .farmid = old->farmid,
     104             :                         .dirty = true,
     105          67 :                         .parentid = old->parentid,
     106          67 :                         .wasempty = old->wasempty,
     107          67 :                         .hasfile = old->hasfile,
     108          67 :                         .refs = ATOMIC_VAR_INIT(1 | (refs & HEAPREMOVE)),
     109             :                 };
     110          67 :                 memcpy(new->filename, old->filename, sizeof(new->filename));
     111          67 :                 if (HEAPalloc(new, size, 1) == GDK_SUCCEED) {
     112          67 :                         new->free = old->free;
     113          67 :                         new->cleanhash = old->cleanhash;
     114          67 :                         if (old->free > 0 &&
     115          62 :                             (new->storage == STORE_MEM || old->storage == STORE_MEM))
     116          40 :                                 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          67 :                         HEAPdecref(*hp, false);
     122          67 :                         *hp = new;
     123             :                 } else {
     124           0 :                         GDKfree(new);
     125           0 :                         new = NULL;
     126             :                 }
     127             :         }
     128          67 :         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     9042230 : HEAPalloc(Heap *h, size_t nitems, size_t itemsize)
     141             : {
     142     9042230 :         size_t size = 0;
     143     9042230 :         QryCtx *qc = h->farmid == 1 ? MT_thread_get_qry_ctx() : NULL;
     144             : 
     145     9062950 :         h->base = NULL;
     146     9062950 :         h->size = 1;
     147     9062950 :         if (itemsize) {
     148             :                 /* check for overflow */
     149     9062950 :                 if (nitems > BUN_NONE / itemsize) {
     150           0 :                         GDKerror("allocating more than heap can accommodate\n");
     151           0 :                         return GDK_FAIL;
     152             :                 }
     153     9062950 :                 h->size = MAX(1, nitems) * itemsize;
     154             :         }
     155     9062950 :         h->free = 0;
     156     9062950 :         h->cleanhash = false;
     157             : 
     158             : #ifdef SIZE_CHECK_IN_HEAPS_ONLY
     159     9062950 :         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     9046532 :         size_t allocated;
     167     9046532 :         if (GDKinmemory(h->farmid) ||
     168    18111737 :             ((allocated = GDKmem_cursize()) + h->size < GDK_mem_maxsize &&
     169     9061045 :              h->size < (h->farmid == 0 ? GDK_mmap_minsize_persistent : GDK_mmap_minsize_transient) &&
     170     9080830 :              h->size < ((GDK_mem_maxsize - allocated) >> 6))) {
     171     9108079 :                 h->storage = STORE_MEM;
     172     9108079 :                 size = h->size;
     173     9108079 :                 if (qc != NULL) {
     174     5892796 :                         ATOMIC_BASE_TYPE sz = ATOMIC_ADD(&qc->datasize, size);
     175     5892796 :                         sz += size;
     176     5892796 :                         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     9108079 :                 h->base = GDKmalloc(size);
     183     9107771 :                 TRC_DEBUG(HEAP, "%s %zu %p\n", h->filename, size, h->base);
     184     9107771 :                 if (h->base == NULL && qc != NULL)
     185           0 :                         ATOMIC_SUB(&qc->datasize, size);
     186             :         }
     187             : 
     188     9064444 :         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     9064449 :         h->newstorage = h->storage;
     220     9064449 :         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       65983 : HEAPextend(Heap *h, size_t size, bool mayshare)
     243             : {
     244       65983 :         size_t osize = h->size;
     245       65983 :         size_t xsize;
     246       65983 :         QryCtx *qc = h->farmid == 1 ? MT_thread_get_qry_ctx() : NULL;
     247             : 
     248       66002 :         if (size <= h->size)
     249             :                 return GDK_SUCCEED;     /* nothing to do */
     250             : 
     251       50498 :         char nme[sizeof(h->filename)], *ext;
     252       50498 :         const char *failure = "None";
     253             : 
     254       50498 :         if (GDKinmemory(h->farmid)) {
     255          44 :                 strcpy_len(nme, ":memory:", sizeof(nme));
     256          44 :                 ext = "ext";
     257             :         } else {
     258       50386 :                 strcpy_len(nme, h->filename, sizeof(nme));
     259       50512 :                 ext = decompose_filename(nme);
     260             :         }
     261       50599 :         failure = "size > h->size";
     262             : 
     263             : #ifdef SIZE_CHECK_IN_HEAPS_ONLY
     264       50599 :         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       50500 :         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       50035 :                 Heap bak = *h;
     313       50035 :                 size_t allocated;
     314       50035 :                 bool must_mmap = (!GDKinmemory(h->farmid) &&
     315       49999 :                                    (h->newstorage != STORE_MEM ||
     316       99874 :                                     (allocated = GDKmem_cursize()) + size >= GDK_mem_maxsize ||
     317       49945 :                                     size >= (h->farmid == 0 ? GDK_mmap_minsize_persistent : GDK_mmap_minsize_transient) ||
     318       48916 :                                     size >= ((GDK_mem_maxsize - allocated) >> 6)));
     319             : 
     320       50033 :                 h->size = size;
     321       50033 :                 xsize = size - osize;
     322             : 
     323             :                 /* try GDKrealloc if the heap size stays within
     324             :                  * reasonable limits */
     325       50033 :                 if (!must_mmap) {
     326       48931 :                         if (qc != NULL) {
     327       24663 :                                 ATOMIC_BASE_TYPE sz = ATOMIC_ADD(&qc->datasize, xsize);
     328       24663 :                                 sz += xsize;
     329       24663 :                                 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       50213 :                                         return GDK_FAIL;
     334             :                                 }
     335             :                         }
     336       48931 :                         h->newstorage = h->storage = STORE_MEM;
     337       48931 :                         h->base = GDKrealloc(h->base, size);
     338       49103 :                         TRC_DEBUG(HEAP, "Extending malloced heap %s %zu->%zu %p->%p\n", h->filename, bak.size, size, bak.base, h->base);
     339       49103 :                         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        1102 :                 if (!GDKinmemory(h->farmid)) {
     349             :                         /* too big: convert it to a disk-based temporary heap */
     350             : 
     351        1072 :                         assert(h->storage == STORE_MEM);
     352        1072 :                         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        1072 :                         int fd = GDKfdlocate(h->farmid, nme, "rb", ext);
     358        1070 :                         if (fd >= 0) {
     359          35 :                                 assert(h->hasfile);
     360          35 :                                 close(fd);
     361          35 :                                 fd = GDKfdlocate(h->farmid, nme, "wb", ext);
     362          35 :                                 if (fd >= 0) {
     363          35 :                                         gdk_return rc = GDKextendf(fd, size, nme);
     364          35 :                                         close(fd);
     365          35 :                                         if (rc != GDK_SUCCEED) {
     366           0 :                                                 failure = "h->storage == STORE_MEM && can_map && fd >= 0 && GDKextendf() != GDK_SUCCEED";
     367           0 :                                                 goto failed;
     368             :                                         }
     369          35 :                                         h->storage = h->newstorage == STORE_MMAP && !mayshare ? STORE_PRIV : h->newstorage;
     370             :                                         /* make sure we really MMAP */
     371          35 :                                         if (must_mmap && h->newstorage == STORE_MEM)
     372          35 :                                                 h->storage = STORE_MMAP;
     373          35 :                                         h->newstorage = h->storage;
     374             : 
     375          35 :                                         h->base = NULL;
     376          35 :                                         TRC_DEBUG(HEAP, "Converting malloced to %s mmapped heap %s\n", h->newstorage == STORE_MMAP ? "shared" : "privately", h->filename);
     377             :                                         /* try to allocate a memory-mapped based
     378             :                                          * heap */
     379          35 :                                         if (HEAPload(h, nme, ext, false) == GDK_SUCCEED) {
     380             :                                                 /* copy data to heap and free old
     381             :                                                  * memory */
     382          35 :                                                 memcpy(h->base, bak.base, bak.free);
     383          35 :                                                 HEAPfree(&bak, false);
     384          35 :                                                 return GDK_SUCCEED;
     385             :                                         }
     386             :                                         failure = "h->storage == STORE_MEM && can_map && fd >= 0 && HEAPload() != GDK_SUCCEED";
     387             :                                         /* we failed */
     388             :                                 } else {
     389             :                                         failure = "h->storage == STORE_MEM && can_map && fd < 0";
     390             :                                 }
     391             :                         } else {
     392             :                                 /* no pre-existing heap file, so create a new
     393             :                                  * one */
     394        1035 :                                 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        1035 :                                 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       99908 : GDKupgradevarheap(BAT *b, var_t v, BUN cap, BUN ncopy)
     443             : {
     444       99908 :         uint8_t shift = b->tshift;
     445       99908 :         uint16_t width = b->twidth;
     446       99908 :         uint8_t *pc;
     447       99908 :         uint16_t *ps;
     448       99908 :         uint32_t *pi;
     449             : #if SIZEOF_VAR_T == 8
     450       99908 :         uint64_t *pl;
     451             : #endif
     452       99908 :         size_t i, n;
     453       99908 :         size_t newsize;
     454       99908 :         bat bid = b->batCacheid;
     455       99908 :         Heap *old, *new;
     456             : 
     457       99908 :         old = b->theap;
     458             : //      assert(old->storage == STORE_MEM);
     459       99908 :         assert(old->parentid == b->batCacheid);
     460       99908 :         assert(b->tbaseoff == 0);
     461       99908 :         assert(width != 0);
     462       99908 :         assert(v >= GDK_VAROFFSET);
     463             : 
     464      129780 :         while (width < SIZEOF_VAR_T && (width <= 2 ? v - GDK_VAROFFSET : v) >= ((var_t) 1 << (8 * width))) {
     465       29872 :                 width <<= 1;
     466       29872 :                 shift++;
     467             :         }
     468             :         /* if cap(acity) given (we check whether it is larger than the
     469             :          * old), then grow to cap */
     470       99908 :         if (cap > (old->size >> b->tshift))
     471        6416 :                 newsize = cap << shift;
     472             :         else
     473       93492 :                 newsize = (old->size >> b->tshift) << shift;
     474       99908 :         if (b->twidth == width) {
     475       71781 :                 if (newsize <= old->size) {
     476             :                         /* nothing to do */
     477       66767 :                         if (cap > b->batCapacity)
     478           0 :                                 BATsetcapacity(b, cap);
     479       66767 :                         return GDK_SUCCEED;
     480             :                 }
     481        5014 :                 return BATextend(b, newsize >> shift);
     482             :         }
     483             : 
     484       28127 :         n = MIN(ncopy, old->size >> b->tshift);
     485             : 
     486       42198 :         MT_thread_setalgorithm(n ? "widen offset heap" : "widen empty offset heap");
     487             : 
     488       28300 :         new = GDKmalloc(sizeof(Heap));
     489       28304 :         if (new == NULL)
     490             :                 return GDK_FAIL;
     491       28304 :         *new = (Heap) {
     492       28304 :                 .farmid = old->farmid,
     493             :                 .dirty = true,
     494       28304 :                 .parentid = old->parentid,
     495       28304 :                 .wasempty = old->wasempty,
     496       28304 :                 .refs = ATOMIC_VAR_INIT(1 | (ATOMIC_GET(&old->refs) & HEAPREMOVE)),
     497             :         };
     498       28304 :         settailname(new, BBP_physical(b->batCacheid), b->ttype, width);
     499       28271 :         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       28293 :         new->free = old->free << (shift - b->tshift);
     505             :         /* per the above, width > b->twidth, so certain combinations are
     506             :          * impossible */
     507       28293 :         switch (width) {
     508       25455 :         case 2:
     509       25455 :                 ps = (uint16_t *) new->base;
     510       25455 :                 switch (b->twidth) {
     511       25455 :                 case 1:
     512       25455 :                         pc = (uint8_t *) old->base;
     513     1248372 :                         for (i = 0; i < n; i++)
     514     1222917 :                                 ps[i] = pc[i];
     515       25455 :                         break;
     516             :                 default:
     517           0 :                         MT_UNREACHABLE();
     518             :                 }
     519             : #ifndef NDEBUG
     520             :                 /* valgrind */
     521       25455 :                 memset(ps + n, 0, new->size - n * 2);
     522             : #endif
     523       25455 :                 break;
     524        2838 :         case 4:
     525        2838 :                 pi = (uint32_t *) new->base;
     526        2838 :                 switch (b->twidth) {
     527        1660 :                 case 1:
     528        1660 :                         pc = (uint8_t *) old->base;
     529        1664 :                         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     1551785 :                         for (i = 0; i < n; i++)
     535     1550607 :                                 pi[i] = ps[i] + GDK_VAROFFSET;
     536             :                         break;
     537             :                 default:
     538           0 :                         MT_UNREACHABLE();
     539             :                 }
     540             : #ifndef NDEBUG
     541             :                 /* valgrind */
     542        2838 :                 memset(pi + n, 0, new->size - n * 4);
     543             : #endif
     544        2838 :                 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       28293 :         MT_lock_set(&b->theaplock);
     577       28251 :         b->tshift = shift;
     578       28251 :         b->twidth = width;
     579       28251 :         if (cap > BATcapacity(b))
     580        1395 :                 BATsetcapacity(b, cap);
     581       28250 :         b->theap = new;
     582       28250 :         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        2100 :                         HEAPfree(old, false);
     588             :                 }
     589             :         } else {
     590       26151 :                 ValPtr p = BATgetprop_nolock(b, (enum prop_t) 20);
     591       52274 :                 HEAPdecref(old, p == NULL || strcmp(((Heap*) p->val.pval)->filename, old->filename) != 0);
     592             :         }
     593       28282 :         MT_lock_unset(&b->theaplock);
     594       28229 :         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        4863 : HEAPcopy(Heap *dst, Heap *src, size_t offset)
     604             : {
     605        4863 :         if (offset > src->free)
     606             :                 offset = src->free;
     607        4863 :         if (HEAPalloc(dst, src->free - offset, 1) == GDK_SUCCEED) {
     608        4869 :                 dst->free = src->free - offset;
     609        4869 :                 memcpy(dst->base, src->base + offset, src->free - offset);
     610        4869 :                 dst->cleanhash = src->cleanhash;
     611        4869 :                 dst->dirty = true;
     612        4869 :                 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    16647625 : HEAPfree(Heap *h, bool rmheap)
     621             : {
     622    16647625 :         if (h->base) {
     623     9176265 :                 if (h->farmid == 1 && (h->storage == STORE_MEM || h->storage == STORE_MMAP || h->storage == STORE_PRIV)) {
     624     8584449 :                         QryCtx *qc = MT_thread_get_qry_ctx();
     625     8589575 :                         if (qc)
     626     5932440 :                                 ATOMIC_SUB(&qc->datasize, h->size);
     627             :                 }
     628     9181391 :                 if (h->storage == STORE_MEM) {       /* plain memory */
     629     9178716 :                         TRC_DEBUG(HEAP, "HEAPfree %s %zu %p\n", h->filename, h->size, h->base);
     630     9178716 :                         GDKfree(h->base);
     631        2675 :                 } 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        2628 :                 } else if (h->storage != STORE_NOWN) {       /* mapped file, or STORE_PRIV */
     635        5256 :                         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        2631 :                         if (ret != GDK_SUCCEED) {
     642           0 :                                 GDKsyserror("HEAPfree: %s was not mapped\n",
     643             :                                             h->filename);
     644           0 :                                 assert(0);
     645             :                         }
     646        2631 :                         TRC_DEBUG(HEAP, "munmap(base=%p, size=%zu) = %d\n",
     647             :                                   (void *)h->base, h->size, (int) ret);
     648             :                 }
     649             :         }
     650    16653850 :         h->base = NULL;
     651    16653850 :         if (rmheap && !GDKinmemory(h->farmid)) {
     652    15964805 :                 char path[MAXPATH];
     653             : 
     654    15964805 :                 if (h->hasfile) {
     655       40461 :                         if (GDKfilepath(path, sizeof(path), h->farmid, BATDIR, h->filename, NULL) == GDK_SUCCEED) {
     656       40461 :                                 int ret = MT_remove(path);
     657       40461 :                                 if (ret == -1) {
     658             :                                         /* unexpectedly not present */
     659           0 :                                         perror(path);
     660             :                                 }
     661       40461 :                                 assert(ret == 0);
     662       40461 :                                 h->hasfile = false;
     663             :                         }
     664       40461 :                         if (GDKfilepath(path, sizeof(path), h->farmid, BATDIR, h->filename, "new") == GDK_SUCCEED) {
     665             :                                 /* in practice, should never be present */
     666       40461 :                                 int ret = MT_remove(path);
     667       40461 :                                 if (ret == -1 && errno != ENOENT)
     668           0 :                                         perror(path);
     669       40461 :                                 assert(ret == -1 && errno == ENOENT);
     670             :                         }
     671             : #ifndef NDEBUG
     672    15924344 :                 } else if (GDKfilepath(path, sizeof(path), h->farmid, BATDIR, h->filename, NULL) == GDK_SUCCEED) {
     673             :                         /* should not be present */
     674    15906916 :                         struct stat st;
     675    15906916 :                         assert(stat(path, &st) == -1 && errno == ENOENT);
     676             : #endif
     677             :                 }
     678             :         }
     679    16522122 : }
     680             : 
     681             : void
     682    78663647 : HEAPdecref(Heap *h, bool remove)
     683             : {
     684    78663647 :         if (remove)
     685    13042219 :                 ATOMIC_OR(&h->refs, HEAPREMOVE);
     686    78663647 :         ATOMIC_BASE_TYPE refs = ATOMIC_DEC(&h->refs);
     687             :         //printf("dec ref(%d) %p %d\n", (int)h->refs, h, h->parentid);
     688    78663647 :         switch (refs & HEAPREFS) {
     689    13108308 :         case 0:
     690    13108308 :                 HEAPfree(h, (bool) (refs & HEAPREMOVE));
     691    12967069 :                 GDKfree(h);
     692    12967069 :                 break;
     693    29707581 :         case 1:
     694    29707581 :                 if (refs & DELAYEDREMOVE) {
     695             :                         /* only reference left is b->oldtail */
     696        1729 :                         HEAPfree(h, false);
     697             :                 }
     698             :                 break;
     699             :         default:
     700             :                 break;
     701             :         }
     702    78654402 : }
     703             : 
     704             : void
     705    65313561 : HEAPincref(Heap *h)
     706             : {
     707             :         //printf("inc ref(%d) %p %d\n", (int)h->refs, h, h->parentid);
     708    65313561 :         ATOMIC_INC(&h->refs);
     709    65313561 : }
     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       25292 : HEAPload(Heap *h, const char *nme, const char *ext, bool trunc)
     718             : {
     719       25292 :         size_t minsize;
     720       25292 :         int ret = 0;
     721       25292 :         char srcpath[MAXPATH], dstpath[MAXPATH];
     722       25292 :         lng t0;
     723       25292 :         const char suffix[] = ".new";
     724             : 
     725       25292 :         if (h->storage == STORE_INVALID || h->newstorage == STORE_INVALID) {
     726       25257 :                 size_t allocated;
     727       50513 :                 h->storage = h->newstorage = h->size < (h->farmid == 0 ? GDK_mmap_minsize_persistent : GDK_mmap_minsize_transient) &&
     728       24279 :                         (allocated = GDKmem_cursize()) < GDK_mem_maxsize &&
     729       49535 :                         h->size < ((GDK_mem_maxsize - allocated) >> 6) ? STORE_MEM : STORE_MMAP;
     730             :         }
     731             : 
     732       25291 :         minsize = (h->size + GDK_mmap_pagesize - 1) & ~(GDK_mmap_pagesize - 1);
     733       25291 :         if (h->storage != STORE_MEM && minsize != h->size)
     734         126 :                 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       25291 :         if (trunc) {
     739             :                 /* round up mmap heap sizes to GDK_mmap_pagesize
     740             :                  * segments, also add some slack */
     741       24131 :                 int fd;
     742             : 
     743       24131 :                 if (minsize == 0)
     744           0 :                         minsize = GDK_mmap_pagesize; /* minimum of one page */
     745       24131 :                 if ((fd = GDKfdlocate(h->farmid, nme, "rb+", ext)) >= 0) {
     746       24131 :                         struct stat stb;
     747       24131 :                         if (fstat(fd, &stb) == 0 &&
     748       24133 :                             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       24132 :                         close(fd);
     758             :                 }
     759             :         }
     760             : 
     761       25293 :         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       25293 :         if (GDKfilepath(dstpath, sizeof(dstpath), h->farmid, BATDIR, nme, ext) != GDK_SUCCEED)
     770             :                 return GDK_FAIL;
     771       25292 :         strconcat_len(srcpath, sizeof(srcpath), dstpath, suffix, NULL);
     772             : 
     773       25292 :         t0 = GDKusec();
     774       25292 :         ret = MT_rename(srcpath, dstpath);
     775       25293 :         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       25293 :         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       25293 :         size_t size = h->size;
     788       25293 :         QryCtx *qc = NULL;
     789       25293 :         if (h->storage != STORE_MEM)
     790        1014 :                 size = (size + GDK_mmap_pagesize - 1) & ~(GDK_mmap_pagesize - 1);
     791       25293 :         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       25293 :         if (h->storage == STORE_MEM && h->free == 0) {
     802           0 :                 h->base = GDKmalloc(h->size);
     803           0 :                 h->wasempty = true;
     804             :         } else {
     805       25293 :                 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       25293 :                 h->base = GDKload(h->farmid, nme, ext, h->free, &h->size, h->storage);
     812             :         }
     813       25293 :         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       25293 :         h->dirty = false;    /* we just read it, so it's clean */
     820       25293 :         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      342993 : HEAPsave(Heap *h, const char *nme, const char *ext, bool dosync, BUN free, MT_Lock *lock)
     840             : {
     841      342993 :         storage_t store = h->newstorage;
     842      342993 :         long_str extension;
     843      342993 :         gdk_return rc;
     844      342993 :         const char suffix[] = ".new";
     845             : 
     846      342993 :         if (h->base == NULL) {
     847           0 :                 GDKerror("no heap to save\n");
     848           0 :                 return GDK_FAIL;
     849             :         }
     850      342993 :         if (free == 0) {
     851             :                 /* nothing to see, please move on */
     852        7141 :                 if (lock)
     853        7141 :                         MT_lock_set(lock);
     854        7141 :                 h->wasempty = true;
     855           0 :                 if (lock)
     856        7141 :                         MT_lock_unset(lock);
     857        7141 :                 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        7141 :                 return GDK_SUCCEED;
     863             :         }
     864      335852 :         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      335852 :         } else if (store != STORE_MEM) {
     871        1076 :                 store = h->storage;
     872             :         }
     873      335852 :         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      335852 :         rc = GDKsave(h->farmid, nme, ext, h->base, free, store, dosync);
     878      335852 :         if (lock)
     879      308579 :                 MT_lock_set(lock);
     880      335852 :         if (rc == GDK_SUCCEED) {
     881      335852 :                 h->hasfile = true;
     882      335852 :                 h->dirty = free != h->free;
     883      335852 :                 h->wasempty = false;
     884             :         } else {
     885           0 :                 h->dirty = true;
     886           0 :                 if (store != STORE_MMAP)
     887           0 :                         h->hasfile = false;
     888             :         }
     889      335852 :         if (lock)
     890      308579 :                 MT_lock_unset(lock);
     891             :         return rc;
     892             : }
     893             : 
     894             : 
     895             : /* Return the (virtual) size of the heap. */
     896             : size_t
     897      344021 : HEAPvmsize(Heap *h)
     898             : {
     899      344021 :         if (h && h->base && h->free)
     900       45853 :                 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      344021 : HEAPmemsize(Heap *h)
     908             : {
     909      344021 :         if (h && h->base && h->free && h->storage != STORE_MMAP)
     910       45601 :                 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        2003 : roundup_num(size_t number, int alignment)
     974             : {
     975        2003 :         size_t rval;
     976             : 
     977        2003 :         rval = number + (size_t) alignment - 1;
     978        2003 :         rval -= (rval % (size_t) alignment);
     979        2003 :         return rval;
     980             : }
     981             : 
     982             : #define HEAP_index(HEAP,INDEX,TYPE)     ((TYPE *)((char *) (HEAP)->base + (INDEX)))
     983             : 
     984             : 
     985             : static void
     986        2003 : HEAP_empty(Heap *heap, size_t nprivate, int alignment)
     987             : {
     988             :         /* Find position of header block. */
     989        2003 :         HEADER *hheader = HEAP_index(heap, 0, HEADER);
     990             : 
     991             :         /* Calculate position of first and only free block. */
     992        2003 :         size_t head = roundup_num((size_t) (roundup_8(sizeof(HEADER)) + roundup_8(nprivate)), alignment);
     993        2003 :         CHUNK *headp = HEAP_index(heap, head, CHUNK);
     994             : 
     995        2003 :         assert(roundup_8(sizeof(HEADER)) + roundup_8(nprivate) <= VAR_MAX);
     996             : 
     997             :         /* Fill header block. */
     998        2003 :         hheader->head = head;
     999        2003 :         hheader->sizefcn = NULL;
    1000        2003 :         hheader->alignment = alignment;
    1001        2003 :         hheader->firstblock = head;
    1002        2003 :         hheader->version = HEAPVERSION;
    1003             : 
    1004             :         /* Fill first free block. */
    1005        2003 :         assert(heap->size - head <= VAR_MAX);
    1006        2003 :         headp->size = (size_t) (heap->size - head);
    1007        2003 :         headp->next = 0;
    1008             : 
    1009        2003 :         heap->dirty = true;
    1010        2003 : }
    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     7402098 : HEAP_malloc(BAT *b, size_t nbytes)
    1040             : {
    1041     7402098 :         Heap *heap = b->tvheap;
    1042     7402098 :         size_t block, trail, ttrail;
    1043     7402098 :         CHUNK *blockp;
    1044     7402098 :         CHUNK *trailp;
    1045     7402098 :         HEADER *hheader = HEAP_index(heap, 0, HEADER);
    1046             : 
    1047             :         /* add space for size field */
    1048     7402098 :         nbytes += hheader->alignment;
    1049     7402098 :         nbytes = roundup_8(nbytes);
    1050     7402098 :         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     7402098 :         ttrail = 0;
    1058     7402098 :         trail = 0;
    1059     7402233 :         for (block = hheader->head; block != 0; block = blockp->next) {
    1060     7402064 :                 blockp = HEAP_index(heap, block, CHUNK);
    1061             : 
    1062     7402064 :                 assert(trail == 0 || block > trail);
    1063     7402064 :                 if (trail != 0 && block <= trail) {
    1064           0 :                         GDKerror("Free list is not orderered\n");
    1065           0 :                         return (var_t) -1;
    1066             :                 }
    1067             : 
    1068     7402064 :                 if (blockp->size >= nbytes)
    1069             :                         break;
    1070         135 :                 ttrail = trail;
    1071         135 :                 trail = block;
    1072             :         }
    1073             : 
    1074             :         /* If no block of acceptable size is found we try to enlarge
    1075             :          * the heap. */
    1076     7402098 :         if (block == 0) {
    1077         170 :                 size_t newsize;
    1078             : 
    1079         170 :                 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         170 :                 newsize = MIN(heap->free, (size_t) 1 << 30);
    1084             : #endif
    1085         170 :                 newsize = (size_t) roundup_8(heap->free + MAX(newsize, nbytes));
    1086         170 :                 assert(heap->free <= VAR_MAX);
    1087         170 :                 block = (size_t) heap->free; /* current end-of-heap */
    1088             : 
    1089             :                 /* Increase the size of the heap. */
    1090         170 :                 TRC_DEBUG(HEAP, "HEAPextend in HEAP_malloc %s %zu %zu\n", heap->filename, heap->size, newsize);
    1091         170 :                 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         134 :                         trailp->size += blockp->size;
    1110         134 :                         trailp->next = blockp->next;
    1111             : 
    1112         134 :                         block = trail;
    1113         134 :                         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     7402098 :         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     7402098 :         if (blockp->size >= nbytes + 2 * sizeof(CHUNK)) {
    1125     7402062 :                 size_t newblock = block + nbytes;
    1126     7402062 :                 CHUNK *newblockp = HEAP_index(heap, newblock, CHUNK);
    1127             : 
    1128     7402062 :                 newblockp->size = blockp->size - nbytes;
    1129     7402062 :                 newblockp->next = blockp->next;
    1130             : 
    1131     7402062 :                 blockp->next = newblock;
    1132     7402062 :                 blockp->size = nbytes;
    1133             :         }
    1134             : 
    1135             :         /* Delete block from freelist */
    1136     7402098 :         if (trail == 0) {
    1137     7402098 :                 hheader->head = blockp->next;
    1138             :         } else {
    1139           0 :                 trailp = HEAP_index(heap, trail, CHUNK);
    1140             : 
    1141           0 :                 trailp->next = blockp->next;
    1142             :         }
    1143             : 
    1144     7402098 :         block += hheader->alignment;
    1145     7402098 :         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