LCOV - code coverage report
Current view: top level - gdk - gdk.h (source / functions) Hit Total Coverage
Test: coverage.info Lines: 310 362 85.6 %
Date: 2024-10-03 20:03:20 Functions: 25 25 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             :  * @t The Goblin Database Kernel
      15             :  * @v Version 3.05
      16             :  * @a Martin L. Kersten, Peter Boncz, Niels Nes, Sjoerd Mullender
      17             :  *
      18             :  * @+ The Inner Core
      19             :  * The innermost library of the MonetDB database system is formed by
      20             :  * the library called GDK, an abbreviation of Goblin Database Kernel.
      21             :  * Its development was originally rooted in the design of a pure
      22             :  * active-object-oriented programming language, before development
      23             :  * was shifted towards a reusable database kernel engine.
      24             :  *
      25             :  * GDK is a C library that provides ACID properties on a DSM model
      26             :  * @tex
      27             :  * [@cite{Copeland85}]
      28             :  * @end tex
      29             :  * , using main-memory
      30             :  * database algorithms
      31             :  * @tex
      32             :  * [@cite{Garcia-Molina92}]
      33             :  * @end tex
      34             :  *  built on virtual-memory
      35             :  * OS primitives and multi-threaded parallelism.
      36             :  * Its implementation has undergone various changes over its decade
      37             :  * of development, many of which were driven by external needs to
      38             :  * obtain a robust and fast database system.
      39             :  *
      40             :  * The coding scheme explored in GDK has also laid a foundation to
      41             :  * communicate over time experiences and to provide (hopefully)
      42             :  * helpful advice near to the place where the code-reader needs it.
      43             :  * Of course, over such a long time the documentation diverges from
      44             :  * reality. Especially in areas where the environment of this package
      45             :  * is being described.
      46             :  * Consider such deviations as historic landmarks, e.g. crystallization
      47             :  * of brave ideas and mistakes rectified at a later stage.
      48             :  *
      49             :  * @+ Short Outline
      50             :  * The facilities provided in this implementation are:
      51             :  * @itemize
      52             :  * @item
      53             :  * GDK or Goblin Database Kernel routines for session management
      54             :  * @item
      55             :  *  BAT routines that define the primitive operations on the
      56             :  * database tables (BATs).
      57             :  * @item
      58             :  *  BBP routines to manage the BAT Buffer Pool (BBP).
      59             :  * @item
      60             :  *  ATOM routines to manipulate primitive types, define new types
      61             :  * using an ADT interface.
      62             :  * @item
      63             :  *  HEAP routines for manipulating heaps: linear spaces of memory
      64             :  * that are GDK's vehicle of mass storage (on which BATs are built).
      65             :  * @item
      66             :  *  DELTA routines to access inserted/deleted elements within a
      67             :  * transaction.
      68             :  * @item
      69             :  *  HASH routines for manipulating GDK's built-in linear-chained
      70             :  * hash tables, for accelerating lookup searches on BATs.
      71             :  * @item
      72             :  *  TM routines that provide basic transaction management primitives.
      73             :  * @item
      74             :  *  TRG routines that provided active database support. [DEPRECATED]
      75             :  * @item
      76             :  *  ALIGN routines that implement BAT alignment management.
      77             :  * @end itemize
      78             :  *
      79             :  * The Binary Association Table (BAT) is the lowest level of storage
      80             :  * considered in the Goblin runtime system
      81             :  * @tex
      82             :  * [@cite{Goblin}]
      83             :  * @end tex
      84             :  * .  A BAT is a
      85             :  * self-descriptive main-memory structure that represents the
      86             :  * @strong{binary relationship} between two atomic types.  The
      87             :  * association can be defined over:
      88             :  * @table @code
      89             :  * @item void:
      90             :  *  virtual-OIDs: a densely ascending column of OIDs (takes zero-storage).
      91             :  * @item bit:
      92             :  *  Booleans, implemented as one byte values.
      93             :  * @item bte:
      94             :  *  Tiny (1-byte) integers (8-bit @strong{integer}s).
      95             :  * @item sht:
      96             :  *  Short integers (16-bit @strong{integer}s).
      97             :  * @item int:
      98             :  *  This is the C @strong{int} type (32-bit).
      99             :  * @item oid:
     100             :  *  Unique @strong{long int} values uses as object identifier. Highest
     101             :  *          bit cleared always.  Thus, oids-s are 31-bit numbers on
     102             :  *          32-bit systems, and 63-bit numbers on 64-bit systems.
     103             :  * @item ptr:
     104             :  * Memory pointer values. DEPRECATED.  Can only be stored in transient
     105             :  * BATs.
     106             :  * @item flt:
     107             :  *  The IEEE @strong{float} type.
     108             :  * @item dbl:
     109             :  *  The IEEE @strong{double} type.
     110             :  * @item lng:
     111             :  *  Longs: the C @strong{long long} type (64-bit integers).
     112             :  * @item hge:
     113             :  *  "huge" integers: the GCC @strong{__int128} type (128-bit integers).
     114             :  * @item str:
     115             :  *  UTF-8 strings (Unicode). A zero-terminated byte sequence.
     116             :  * @item bat:
     117             :  *  Bat descriptor. This allows for recursive administered tables, but
     118             :  *  severely complicates transaction management. Therefore, they CAN
     119             :  *  ONLY BE STORED IN TRANSIENT BATs.
     120             :  * @end table
     121             :  *
     122             :  * This model can be used as a back-end model underlying other -higher
     123             :  * level- models, in order to achieve @strong{better performance} and
     124             :  * @strong{data independence} in one go. The relational model and the
     125             :  * object-oriented model can be mapped on BATs by vertically splitting
     126             :  * every table (or class) for each attribute. Each such a column is
     127             :  * then stored in a BAT with type @strong{bat[oid,attribute]}, where
     128             :  * the unique object identifiers link tuples in the different BATs.
     129             :  * Relationship attributes in the object-oriented model hence are
     130             :  * mapped to @strong{bat[oid,oid]} tables, being equivalent to the
     131             :  * concept of @emph{join indexes} @tex [@cite{Valduriez87}] @end tex .
     132             :  *
     133             :  * The set of built-in types can be extended with user-defined types
     134             :  * through an ADT interface.  They are linked with the kernel to
     135             :  * obtain an enhanced library, or they are dynamically loaded upon
     136             :  * request.
     137             :  *
     138             :  * Types can be derived from other types. They represent something
     139             :  * different than that from which they are derived, but their internal
     140             :  * storage management is equal. This feature facilitates the work of
     141             :  * extension programmers, by enabling reuse of implementation code,
     142             :  * but is also used to keep the GDK code portable from 32-bits to
     143             :  * 64-bits machines: the @strong{oid} and @strong{ptr} types are
     144             :  * derived from @strong{int} on 32-bits machines, but is derived from
     145             :  * @strong{lng} on 64 bits machines. This requires changes in only two
     146             :  * lines of code each.
     147             :  *
     148             :  * To accelerate lookup and search in BATs, GDK supports one built-in
     149             :  * search accelerator: hash tables. We choose an implementation
     150             :  * efficient for main-memory: bucket chained hash
     151             :  * @tex
     152             :  * [@cite{LehCar86,Analyti92}]
     153             :  * @end tex
     154             :  * . Alternatively, when the table is sorted, it will resort to
     155             :  * merge-scan operations or binary lookups.
     156             :  *
     157             :  * BATs are built on the concept of heaps, which are large pieces of
     158             :  * main memory. They can also consist of virtual memory, in case the
     159             :  * working set exceeds main-memory. In this case, GDK supports
     160             :  * operations that cluster the heaps of a BAT, in order to improve
     161             :  * performance of its main-memory.
     162             :  *
     163             :  *
     164             :  * @- Rationale
     165             :  * The rationale for choosing a BAT as the building block for both
     166             :  * relational and object-oriented system is based on the following
     167             :  * observations:
     168             :  *
     169             :  * @itemize
     170             :  * @item -
     171             :  * Given the fact that CPU speed and main-memory increase in current
     172             :  * workstation hardware for the last years has been exceeding IO
     173             :  * access speed increase, traditional disk-page oriented algorithms do
     174             :  * no longer take best advantage of hardware, in most database
     175             :  * operations.
     176             :  *
     177             :  * Instead of having a disk-block oriented kernel with a large memory
     178             :  * cache, we choose to build a main-memory kernel, that only under
     179             :  * large data volumes slowly degrades to IO-bound performance,
     180             :  * comparable to traditional systems
     181             :  * @tex
     182             :  * [@cite{boncz95,boncz96}]
     183             :  * @end tex
     184             :  * .
     185             :  *
     186             :  * @item -
     187             :  * Traditional (disk-based) relational systems move too much data
     188             :  * around to save on (main-memory) join operations.
     189             :  *
     190             :  * The fully decomposed store (DSM
     191             :  * @tex
     192             :  * [@cite{Copeland85})]
     193             :  * @end tex
     194             :  * assures that only those attributes of a relation that are needed,
     195             :  * will have to be accessed.
     196             :  *
     197             :  * @item -
     198             :  * The data management issues for a binary association is much
     199             :  * easier to deal with than traditional @emph{struct}-based approaches
     200             :  * encountered in relational systems.
     201             :  *
     202             :  * @item -
     203             :  * Object-oriented systems often maintain a double cache, one with the
     204             :  * disk-based representation and a C pointer-based main-memory
     205             :  * structure.  This causes expensive conversions and replicated
     206             :  * storage management.  GDK does not do such `pointer swizzling'. It
     207             :  * used virtual-memory (@strong{mmap()}) and buffer management advice
     208             :  * (@strong{madvise()}) OS primitives to cache only once. Tables take
     209             :  * the same form in memory as on disk, making the use of this
     210             :  * technique transparent
     211             :  * @tex
     212             :  * [@cite{oo7}]
     213             :  * @end tex
     214             :  * .
     215             :  * @end itemize
     216             :  *
     217             :  * A RDBMS or OODBMS based on BATs strongly depends on our ability to
     218             :  * efficiently support tuples and to handle small joins, respectively.
     219             :  *
     220             :  * The remainder of this document describes the Goblin Database kernel
     221             :  * implementation at greater detail. It is organized as follows:
     222             :  * @table @code
     223             :  * @item @strong{GDK Interface}:
     224             :  *
     225             :  * It describes the global interface with which GDK sessions can be
     226             :  * started and ended, and environment variables used.
     227             :  *
     228             :  * @item @strong{Binary Association Tables}:
     229             :  *
     230             :  * As already mentioned, these are the primary data structure of GDK.
     231             :  * This chapter describes the kernel operations for creation,
     232             :  * destruction and basic manipulation of BATs and BUNs (i.e. tuples:
     233             :  * Binary UNits).
     234             :  *
     235             :  * @item @strong{BAT Buffer Pool:}
     236             :  *
     237             :  * All BATs are registered in the BAT Buffer Pool. This directory is
     238             :  * used to guide swapping in and out of BATs. Here we find routines
     239             :  * that guide this swapping process.
     240             :  *
     241             :  * @item @strong{GDK Extensibility:}
     242             :  *
     243             :  * Atoms can be defined using a unified ADT interface.  There is also
     244             :  * an interface to extend the GDK library with dynamically linked
     245             :  * object code.
     246             :  *
     247             :  * @item @strong{GDK Utilities:}
     248             :  *
     249             :  * Memory allocation and error handling primitives are
     250             :  * provided. Layers built on top of GDK should use them, for proper
     251             :  * system monitoring.  Thread management is also included here.
     252             :  *
     253             :  * @item @strong{Transaction Management:}
     254             :  *
     255             :  * For the time being, we just provide BAT-grained concurrency and
     256             :  * global transactions. Work is needed here.
     257             :  *
     258             :  * @item @strong{BAT Alignment:}
     259             :  * Due to the mapping of multi-ary datamodels onto the BAT model, we
     260             :  * expect many correspondences among BATs, e.g.
     261             :  * @emph{bat(oid,attr1),..  bat(oid,attrN)} vertical
     262             :  * decompositions. Frequent activities will be to jump from one
     263             :  * attribute to the other (`bunhopping'). If the head columns are
     264             :  * equal lists in two BATs, merge or even array lookups can be used
     265             :  * instead of hash lookups. The alignment interface makes these
     266             :  * relations explicitly manageable.
     267             :  *
     268             :  * In GDK, complex data models are mapped with DSM on binary tables.
     269             :  * Usually, one decomposes @emph{N}-ary relations into @emph{N} BATs
     270             :  * with an @strong{oid} in the head column, and the attribute in the
     271             :  * tail column.  There may well be groups of tables that have the same
     272             :  * sets of @strong{oid}s, equally ordered. The alignment interface is
     273             :  * intended to make this explicit.  Implementations can use this
     274             :  * interface to detect this situation, and use cheaper algorithms
     275             :  * (like merge-join, or even array lookup) instead.
     276             :  *
     277             :  * @item @strong{BAT Iterators:}
     278             :  *
     279             :  * Iterators are C macros that generally encapsulate a complex
     280             :  * for-loop.  They would be the equivalent of cursors in the SQL
     281             :  * model. The macro interface (instead of a function call interface)
     282             :  * is chosen to achieve speed when iterating main-memory tables.
     283             :  *
     284             :  * @item @strong{Common BAT Operations:}
     285             :  *
     286             :  * These are much used operations on BATs, such as aggregate functions
     287             :  * and relational operators. They are implemented in terms of BAT- and
     288             :  * BUN-manipulation GDK primitives.
     289             :  * @end table
     290             :  *
     291             :  * @+ Interface Files
     292             :  * In this section we summarize the user interface to the GDK library.
     293             :  * It consist of a header file (gdk.h) and an object library
     294             :  * (gdklib.a), which implements the required functionality. The header
     295             :  * file must be included in any program that uses the library. The
     296             :  * library must be linked with such a program.
     297             :  *
     298             :  * @- Database Context
     299             :  *
     300             :  * The MonetDB environment settings are collected in a configuration
     301             :  * file. Amongst others it contains the location of the database
     302             :  * directory.  First, the database directory is closed for other
     303             :  * servers running at the same time.  Second, performance enhancements
     304             :  * may take effect, such as locking the code into memory (if the OS
     305             :  * permits) and preloading the data dictionary.  An error at this
     306             :  * stage normally lead to an abort.
     307             :  */
     308             : 
     309             : #ifndef _GDK_H_
     310             : #define _GDK_H_
     311             : 
     312             : /* standard includes upon which all configure tests depend */
     313             : #ifdef HAVE_SYS_TYPES_H
     314             : # include <sys/types.h>
     315             : #endif
     316             : #ifdef HAVE_SYS_STAT_H
     317             : # include <sys/stat.h>
     318             : #endif
     319             : #include <stddef.h>
     320             : #include <string.h>
     321             : #ifdef HAVE_UNISTD_H
     322             : # include <unistd.h>
     323             : #endif
     324             : 
     325             : #include <ctype.h>                /* isspace etc. */
     326             : 
     327             : #ifdef HAVE_SYS_FILE_H
     328             : # include <sys/file.h>
     329             : #endif
     330             : 
     331             : #ifdef HAVE_DIRENT_H
     332             : # include <dirent.h>
     333             : #endif
     334             : 
     335             : #include <limits.h>               /* for *_MIN and *_MAX */
     336             : #include <float.h>                /* for FLT_MAX and DBL_MAX */
     337             : 
     338             : #ifdef WIN32
     339             : #ifndef LIBGDK
     340             : #define gdk_export extern __declspec(dllimport)
     341             : #else
     342             : #define gdk_export extern __declspec(dllexport)
     343             : #endif
     344             : #else
     345             : #define gdk_export extern
     346             : #endif
     347             : 
     348             : /* Only ever compare with GDK_SUCCEED, never with GDK_FAIL, and do not
     349             :  * use as a Boolean. */
     350             : typedef enum { GDK_FAIL, GDK_SUCCEED } gdk_return;
     351             : 
     352             : gdk_export _Noreturn void GDKfatal(_In_z_ _Printf_format_string_ const char *format, ...)
     353             :         __attribute__((__format__(__printf__, 1, 2)));
     354             : 
     355             : #include "gdk_system.h"
     356             : #include "gdk_posix.h"
     357             : #include "stream.h"
     358             : #include "mstring.h"
     359             : 
     360             : #undef MIN
     361             : #undef MAX
     362             : #define MAX(A,B)        ((A)<(B)?(B):(A))
     363             : #define MIN(A,B)        ((A)>(B)?(B):(A))
     364             : 
     365             : /* defines from ctype with casts that allow passing char values */
     366             : #define GDKisspace(c)   isspace((unsigned char) (c))
     367             : #define GDKisalnum(c)   isalnum((unsigned char) (c))
     368             : #define GDKisdigit(c)   isdigit((unsigned char) (c))
     369             : #define GDKisxdigit(c)  isxdigit((unsigned char) (c))
     370             : 
     371             : #define BATDIR          "bat"
     372             : #define TEMPDIR_NAME    "TEMP_DATA"
     373             : 
     374             : #define DELDIR          BATDIR DIR_SEP_STR "DELETE_ME"
     375             : #define BAKDIR          BATDIR DIR_SEP_STR "BACKUP"
     376             : #define SUBDIR          BAKDIR DIR_SEP_STR "SUBCOMMIT" /* note K, not T */
     377             : #define LEFTDIR         BATDIR DIR_SEP_STR "LEFTOVERS"
     378             : #define TEMPDIR         BATDIR DIR_SEP_STR TEMPDIR_NAME
     379             : 
     380             : /*
     381             :    See `man mserver5` or tools/mserver/mserver5.1
     382             :    for a documentation of the following debug options.
     383             : */
     384             : 
     385             : #define THRDMASK        (1U)
     386             : #define CHECKMASK       (1U<<1)
     387             : #define CHECKDEBUG      if (ATOMIC_GET(&GDKdebug) & CHECKMASK)
     388             : #define PROPMASK        (1U<<3)   /* unused */
     389             : #define PROPDEBUG       if (ATOMIC_GET(&GDKdebug) & PROPMASK) /* unused */
     390             : #define IOMASK          (1U<<4)
     391             : #define BATMASK         (1U<<5)
     392             : #define PARMASK         (1U<<7)
     393             : #define TMMASK          (1U<<9)
     394             : #define TEMMASK         (1U<<10)
     395             : #define PERFMASK        (1U<<12)
     396             : #define DELTAMASK       (1U<<13)
     397             : #define LOADMASK        (1U<<14)
     398             : #define PUSHCANDMASK    (1U<<15)  /* used in opt_pushselect.c */
     399             : #define TAILCHKMASK     (1U<<16)  /* check .tail file size during commit */
     400             : #define ACCELMASK       (1U<<20)
     401             : #define ALGOMASK        (1U<<21)
     402             : 
     403             : #define NOSYNCMASK      (1U<<24)
     404             : 
     405             : #define DEADBEEFMASK    (1U<<25)
     406             : #define DEADBEEFCHK     if (!(ATOMIC_GET(&GDKdebug) & DEADBEEFMASK))
     407             : 
     408             : #define ALLOCMASK       (1U<<26)
     409             : 
     410             : /* M5, only; cf.,
     411             :  * monetdb5/mal/mal.h
     412             :  */
     413             : #define OPTMASK         (1U<<27)
     414             : 
     415             : #define HEAPMASK        (1U<<28)
     416             : 
     417             : #define FORCEMITOMASK   (1U<<29)
     418             : #define FORCEMITODEBUG  if (ATOMIC_GET(&GDKdebug) & FORCEMITOMASK)
     419             : 
     420             : #ifndef TRUE
     421             : #define TRUE            true
     422             : #define FALSE           false
     423             : #endif
     424             : 
     425             : #define BATMARGIN       1.2     /* extra free margin for new heaps */
     426             : #define BATTINY_BITS    8
     427             : #define BATTINY         ((BUN)1<<BATTINY_BITS)    /* minimum allocation buncnt for a BAT */
     428             : 
     429             : enum {
     430             :         TYPE_void = 0,
     431             :         TYPE_msk,               /* bit mask */
     432             :         TYPE_bit,               /* TRUE, FALSE, or nil */
     433             :         TYPE_bte,
     434             :         TYPE_sht,
     435             :         TYPE_int,
     436             :         TYPE_oid,
     437             :         TYPE_ptr,               /* C pointer! */
     438             :         TYPE_flt,
     439             :         TYPE_dbl,
     440             :         TYPE_lng,
     441             : #ifdef HAVE_HGE
     442             :         TYPE_hge,
     443             : #endif
     444             :         TYPE_date,
     445             :         TYPE_daytime,
     446             :         TYPE_timestamp,
     447             :         TYPE_uuid,
     448             :         TYPE_str,
     449             :         TYPE_blob,
     450             :         TYPE_any = 255,         /* limit types to <255! */
     451             : };
     452             : 
     453             : typedef bool msk;
     454             : typedef int8_t bit;
     455             : typedef int8_t bte;
     456             : typedef int16_t sht;
     457             : /* typedef int64_t lng; -- defined in gdk_system.h */
     458             : typedef uint64_t ulng;
     459             : 
     460             : #define SIZEOF_OID      SIZEOF_SIZE_T
     461             : typedef size_t oid;
     462             : #define OIDFMT          "%zu"
     463             : 
     464             : typedef int bat;                /* Index into BBP */
     465             : typedef void *ptr;              /* Internal coding of types */
     466             : 
     467             : #define SIZEOF_PTR      SIZEOF_VOID_P
     468             : typedef float flt;
     469             : typedef double dbl;
     470             : typedef char *str;
     471             : 
     472             : #define UUID_SIZE       16      /* size of a UUID */
     473             : #define UUID_STRLEN     36      /* length of string representation */
     474             : 
     475             : typedef union {
     476             : #ifdef HAVE_HGE
     477             :         hge h;                  /* force alignment, not otherwise used */
     478             : #else
     479             :         lng l[2];               /* force alignment, not otherwise used */
     480             : #endif
     481             :         uint8_t u[UUID_SIZE];
     482             : } uuid;
     483             : 
     484             : typedef struct {
     485             :         size_t nitems;
     486             :         char data[] __attribute__((__nonstring__));
     487             : } blob;
     488             : gdk_export size_t blobsize(size_t nitems) __attribute__((__const__));
     489             : 
     490             : #define SIZEOF_LNG              8
     491             : #define LL_CONSTANT(val)        INT64_C(val)
     492             : #define LLFMT                   "%" PRId64
     493             : #define ULLFMT                  "%" PRIu64
     494             : #define LLSCN                   "%" SCNd64
     495             : #define ULLSCN                  "%" SCNu64
     496             : 
     497             : typedef oid var_t;              /* type used for heap index of var-sized BAT */
     498             : #define SIZEOF_VAR_T    SIZEOF_OID
     499             : #define VARFMT          OIDFMT
     500             : 
     501             : #if SIZEOF_VAR_T == SIZEOF_INT
     502             : #define VAR_MAX         ((var_t) INT_MAX)
     503             : #else
     504             : #define VAR_MAX         ((var_t) INT64_MAX)
     505             : #endif
     506             : 
     507             : typedef oid BUN;                /* BUN position */
     508             : #define SIZEOF_BUN      SIZEOF_OID
     509             : #define BUNFMT          OIDFMT
     510             : /* alternatively:
     511             : typedef size_t BUN;
     512             : #define SIZEOF_BUN      SIZEOF_SIZE_T
     513             : #define BUNFMT          "%zu"
     514             : */
     515             : #if SIZEOF_BUN == SIZEOF_INT
     516             : #define BUN_NONE ((BUN) INT_MAX)
     517             : #else
     518             : #define BUN_NONE ((BUN) INT64_MAX)
     519             : #endif
     520             : #define BUN_MAX (BUN_NONE - 1)  /* maximum allowed size of a BAT */
     521             : 
     522             : /*
     523             :  * @- Checking and Error definitions:
     524             :  */
     525             : #define ATOMextern(t)   (ATOMstorage(t) >= TYPE_str)
     526             : 
     527             : typedef enum {
     528             :         PERSISTENT = 0,
     529             :         TRANSIENT,
     530             :         SYSTRANS,
     531             : } role_t;
     532             : 
     533             : /* Heap storage modes */
     534             : typedef enum {
     535             :         STORE_INVALID = 0,      /* invalid value, used to indicate error */
     536             :         STORE_MEM,              /* load into GDKmalloced memory */
     537             :         STORE_MMAP,             /* mmap() into virtual memory */
     538             :         STORE_PRIV,             /* BAT copy of copy-on-write mmap */
     539             :         STORE_CMEM,             /* load into malloc (not GDKmalloc) memory*/
     540             :         STORE_NOWN,             /* memory not owned by the BAT */
     541             :         STORE_MMAPABS,          /* mmap() into virtual memory from an
     542             :                                  * absolute path (not part of dbfarm) */
     543             : } storage_t;
     544             : 
     545             : typedef struct {
     546             :         size_t free;            /* index where free area starts. */
     547             :         size_t size;            /* size of the heap (bytes) */
     548             :         char *base;             /* base pointer in memory. */
     549             : #if SIZEOF_VOID_P == 4
     550             :         char filename[32];      /* file containing image of the heap */
     551             : #else
     552             :         char filename[40];      /* file containing image of the heap */
     553             : #endif
     554             : 
     555             :         ATOMIC_TYPE refs;       /* reference count for this heap */
     556             :         bte farmid;             /* id of farm where heap is located */
     557             :         bool cleanhash;         /* string heaps must clean hash */
     558             :         bool dirty;             /* specific heap dirty marker */
     559             :         bool remove;            /* remove storage file when freeing */
     560             :         bool wasempty;          /* heap was empty when last saved/created */
     561             :         bool hasfile;           /* .filename exists on disk */
     562             :         storage_t storage;      /* storage mode (mmap/malloc). */
     563             :         storage_t newstorage;   /* new desired storage mode at re-allocation. */
     564             :         bat parentid;           /* cache id of VIEW parent bat */
     565             : } Heap;
     566             : 
     567             : typedef struct Hash Hash;
     568             : typedef struct Imprints Imprints;
     569             : typedef struct Strimps Strimps;
     570             : 
     571             : #ifdef HAVE_RTREE
     572             : typedef struct RTree RTree;
     573             : #endif
     574             : 
     575             : /*
     576             :  * @+ Binary Association Tables
     577             :  * Having gone to the previous preliminary definitions, we will now
     578             :  * introduce the structure of Binary Association Tables (BATs) in
     579             :  * detail. They are the basic storage unit on which GDK is modeled.
     580             :  *
     581             :  * The BAT holds an unlimited number of binary associations, called
     582             :  * BUNs (@strong{Binary UNits}).  The two attributes of a BUN are
     583             :  * called @strong{head} (left) and @strong{tail} (right) in the
     584             :  * remainder of this document.
     585             :  *
     586             :  *  @c image{http://monetdb.cwi.nl/projects/monetdb-mk/imgs/bat1,,,,feps}
     587             :  *
     588             :  * The above figure shows what a BAT looks like. It consists of two
     589             :  * columns, called head and tail, such that we have always binary
     590             :  * tuples (BUNs). The overlooking structure is the @strong{BAT
     591             :  * record}.  It points to a heap structure called the @strong{BUN
     592             :  * heap}.  This heap contains the atomic values inside the two
     593             :  * columns. If they are fixed-sized atoms, these atoms reside directly
     594             :  * in the BUN heap. If they are variable-sized atoms (such as string
     595             :  * or polygon), however, the columns has an extra heap for storing
     596             :  * those (such @strong{variable-sized atom heaps} are then referred to
     597             :  * as @strong{Head Heap}s and @strong{Tail Heap}s). The BUN heap then
     598             :  * contains integer byte-offsets (fixed-sized, of course) into a head-
     599             :  * or tail-heap.
     600             :  *
     601             :  * The BUN heap contains a contiguous range of BUNs. It starts after
     602             :  * the @strong{first} pointer, and finishes at the end in the
     603             :  * @strong{free} area of the BUN. All BUNs after the @strong{inserted}
     604             :  * pointer have been added in the last transaction (and will be
     605             :  * deleted on a transaction abort). All BUNs between the
     606             :  * @strong{deleted} pointer and the @strong{first} have been deleted
     607             :  * in this transaction (and will be reinserted at a transaction
     608             :  * abort).
     609             :  *
     610             :  * The location of a certain BUN in a BAT may change between
     611             :  * successive library routine invocations.  Therefore, one should
     612             :  * avoid keeping references into the BAT storage area for long
     613             :  * periods.
     614             :  *
     615             :  * Passing values between the library routines and the enclosing C
     616             :  * program is primarily through value pointers of type ptr. Pointers
     617             :  * into the BAT storage area should only be used for retrieval. Direct
     618             :  * updates of data stored in a BAT is forbidden. The user should
     619             :  * adhere to the interface conventions to guarantee the integrity
     620             :  * rules and to maintain the (hidden) auxiliary search structures.
     621             :  *
     622             :  * @- GDK variant record type
     623             :  * When manipulating values, MonetDB puts them into value records.
     624             :  * The built-in types have a direct entry in the union. Others should
     625             :  * be represented as a pointer of memory in pval or as a string, which
     626             :  * is basically the same. In such cases the len field indicates the
     627             :  * size of this piece of memory.
     628             :  */
     629             : typedef struct {
     630             :         union {                 /* storage is first in the record */
     631             :                 int ival;
     632             :                 oid oval;
     633             :                 sht shval;
     634             :                 bte btval;
     635             :                 msk mval;
     636             :                 flt fval;
     637             :                 ptr pval;
     638             :                 bat bval;
     639             :                 str sval;
     640             :                 dbl dval;
     641             :                 lng lval;
     642             : #ifdef HAVE_HGE
     643             :                 hge hval;
     644             : #endif
     645             :                 uuid uval;
     646             :         } val;
     647             :         size_t len;
     648             :         short vtype;
     649             :         bool bat;
     650             : } *ValPtr, ValRecord;
     651             : 
     652             : /* interface definitions */
     653             : gdk_export void *VALconvert(int typ, ValPtr t);
     654             : gdk_export char *VALformat(const ValRecord *res)
     655             :         __attribute__((__warn_unused_result__));
     656             : gdk_export ValPtr VALcopy(ValPtr dst, const ValRecord *src);
     657             : gdk_export ValPtr VALinit(ValPtr d, int tpe, const void *s);
     658             : gdk_export void VALempty(ValPtr v);
     659             : gdk_export void VALclear(ValPtr v);
     660             : gdk_export ValPtr VALset(ValPtr v, int t, void *p);
     661             : gdk_export void *VALget(ValPtr v);
     662             : gdk_export int VALcmp(const ValRecord *p, const ValRecord *q);
     663             : gdk_export bool VALisnil(const ValRecord *v);
     664             : 
     665             : /*
     666             :  * @- The BAT record
     667             :  * The elements of the BAT structure are introduced in the remainder.
     668             :  * Instead of using the underlying types hidden beneath it, one should
     669             :  * use a @emph{BAT} type that is supposed to look like this:
     670             :  * @verbatim
     671             :  * typedef struct {
     672             :  *           // static BAT properties
     673             :  *           bat    batCacheid;       // bat id: index in BBPcache
     674             :  *           bool   batTransient;     // persistence mode
     675             :  *           bool   batCopiedtodisk;  // BAT is saved on disk?
     676             :  *           // dynamic BAT properties
     677             :  *           int    batHeat;          // heat of BAT in the BBP
     678             :  *           Heap*  batBuns;          // Heap where the buns are stored
     679             :  *           // DELTA status
     680             :  *           BUN    batInserted;      // first inserted BUN
     681             :  *           BUN    batCount;         // Tuple count
     682             :  *           // Tail properties
     683             :  *           int    ttype;            // Tail type number
     684             :  *           bool   tkey;             // tail values are unique
     685             :  *           bool   tnonil;           // tail has no nils
     686             :  *           bool   tsorted;          // are tail values currently ordered?
     687             :  *           // Tail storage
     688             :  *           int    tloc;             // byte-offset in BUN for tail elements
     689             :  *           Heap   *theap;           // heap for varsized tail values
     690             :  *           Hash   *thash;           // linear chained hash table on tail
     691             :  *           Imprints *timprints;     // column imprints index on tail
     692             :  *           orderidx torderidx;      // order oid index on tail
     693             :  *  } BAT;
     694             :  * @end verbatim
     695             :  *
     696             :  * The internal structure of the @strong{BAT} record is in fact much
     697             :  * more complex, but GDK programmers should refrain of making use of
     698             :  * that.
     699             :  *
     700             :  * Since we don't want to pay cost to keep both views in line with
     701             :  * each other under BAT updates, we work with shared pieces of memory
     702             :  * between the two views. An update to one will thus automatically
     703             :  * update the other.  In the same line, we allow @strong{synchronized
     704             :  * BATs} (BATs with identical head columns, and marked as such in the
     705             :  * @strong{BAT Alignment} interface) now to be clustered horizontally.
     706             :  *
     707             :  *  @c image{http://monetdb.cwi.nl/projects/monetdb-mk/imgs/bat2,,,,feps}
     708             :  */
     709             : 
     710             : typedef struct PROPrec PROPrec;
     711             : 
     712             : /* see also comment near BATassertProps() for more information about
     713             :  * the properties */
     714             : typedef struct {
     715             :         uint16_t width;         /* byte-width of the atom array */
     716             :         int8_t type;            /* type id. */
     717             :         uint8_t shift;          /* log2 of bun width */
     718             :         bool key:1,             /* no duplicate values present */
     719             :                 nonil:1,        /* there are no nils in the column */
     720             :                 nil:1,          /* there is a nil in the column */
     721             :                 sorted:1,       /* column is sorted in ascending order */
     722             :                 revsorted:1,    /* column is sorted in descending order */
     723             :                 ascii:1;        /* string column is fully ASCII (7 bit) */
     724             :         BUN nokey[2];           /* positions that prove key==FALSE */
     725             :         BUN nosorted;           /* position that proves sorted==FALSE */
     726             :         BUN norevsorted;        /* position that proves revsorted==FALSE */
     727             :         BUN minpos, maxpos;     /* location of min/max value */
     728             :         double unique_est;      /* estimated number of unique values */
     729             :         oid seq;                /* start of dense sequence */
     730             : 
     731             :         Heap *heap;             /* space for the column. */
     732             :         BUN baseoff;            /* offset in heap->base (in whole items) */
     733             :         Heap *vheap;            /* space for the varsized data. */
     734             :         Hash *hash;             /* hash table */
     735             : #ifdef HAVE_RTREE
     736             :         RTree *rtree;           /* rtree geometric index */
     737             : #endif
     738             :         Imprints *imprints;     /* column imprints index */
     739             :         Heap *orderidx;         /* order oid index */
     740             :         Strimps *strimps;       /* string imprint index  */
     741             : 
     742             :         PROPrec *props;         /* list of dynamic properties stored in the bat descriptor */
     743             : } COLrec;
     744             : 
     745             : #define ORDERIDXOFF             3
     746             : 
     747             : /* assert that atom width is power of 2, i.e., width == 1<<shift */
     748             : #define assert_shift_width(shift,width) assert(((shift) == 0 && (width) == 0) || ((unsigned)1<<(shift)) == (unsigned)(width))
     749             : 
     750             : #define GDKLIBRARY_HASHASH      061044U /* first in Jul2021: hashash bit in string heaps */
     751             : #define GDKLIBRARY_HSIZE        061045U /* first in Jan2022: heap "size" values */
     752             : #define GDKLIBRARY_JSON         061046U /* first in Sep2022: json storage changes*/
     753             : #define GDKLIBRARY_STATUS       061047U /* first in Dec2023: no status/filename columns */
     754             : #define GDKLIBRARY              061050U /* first in Aug2024 */
     755             : 
     756             : /* The batRestricted field indicates whether a BAT is readonly.
     757             :  * we have modes: BAT_WRITE  = all permitted
     758             :  *                BAT_APPEND = append-only
     759             :  *                BAT_READ   = read-only
     760             :  * VIEW bats are always mapped read-only.
     761             :  */
     762             : typedef enum {
     763             :         BAT_WRITE,                /* all kinds of access allowed */
     764             :         BAT_READ,                 /* only read-access allowed */
     765             :         BAT_APPEND,               /* only reads and appends allowed */
     766             : } restrict_t;
     767             : 
     768             : /* theaplock: this lock should be held when reading or writing any of
     769             :  * the fields that are saved in the BBP.dir file (plus any, if any, that
     770             :  * share bitfields with any of the fields), i.e. hseqbase,
     771             :  * batRestricted, batTransient, batCount, and the theap properties tkey,
     772             :  * tseqbase, tsorted, trevsorted, twidth, tshift, tnonil, tnil, tnokey,
     773             :  * tnosorted, tnorevsorted, tminpos, tmaxpos, and tunique_est, also when
     774             :  * BBP_logical(bid) is changed, and also when reading or writing any of
     775             :  * the following fields: theap, tvheap, batInserted, batCapacity.  There
     776             :  * is no need for the lock if the bat cannot possibly be modified
     777             :  * concurrently, e.g. when it is new and not yet returned to the
     778             :  * interpreter or during system initialization.
     779             :  * If multiple bats need to be locked at the same time by the same
     780             :  * thread, first lock the view, then the view's parent(s). */
     781             : typedef struct BAT {
     782             :         /* static bat properties */
     783             :         oid hseqbase;           /* head seq base */
     784             :         MT_Id creator_tid;      /* which thread created it */
     785             :         bat batCacheid;         /* index into BBP */
     786             :         role_t batRole;         /* role of the bat */
     787             : 
     788             :         /* dynamic bat properties */
     789             :         restrict_t batRestricted:2; /* access privileges */
     790             :         bool
     791             :          batTransient:1,        /* should the BAT persist on disk? */
     792             :          batCopiedtodisk:1;     /* once written */
     793             :         uint16_t selcnt;        /* how often used in equi select without hash */
     794             :         uint16_t unused;        /* value=0 for now (sneakily used by mat.c) */
     795             : 
     796             :         /* delta status administration */
     797             :         BUN batInserted;        /* start of inserted elements */
     798             :         BUN batCount;           /* tuple count */
     799             :         BUN batCapacity;        /* tuple capacity */
     800             : 
     801             :         /* dynamic column properties */
     802             :         COLrec T;               /* column info */
     803             :         MT_Lock theaplock;      /* lock protecting heap reference changes */
     804             :         MT_RWLock thashlock;    /* lock specifically for hash management */
     805             :         MT_Lock batIdxLock;     /* lock to manipulate other indexes/properties */
     806             :         Heap *oldtail;          /* old tail heap, to be destroyed after commit */
     807             : } BAT;
     808             : 
     809             : /* macros to hide complexity of the BAT structure */
     810             : #define ttype           T.type
     811             : #define tkey            T.key
     812             : #define tseqbase        T.seq
     813             : #define tsorted         T.sorted
     814             : #define trevsorted      T.revsorted
     815             : #define tascii          T.ascii
     816             : #define torderidx       T.orderidx
     817             : #define twidth          T.width
     818             : #define tshift          T.shift
     819             : #define tnonil          T.nonil
     820             : #define tnil            T.nil
     821             : #define tnokey          T.nokey
     822             : #define tnosorted       T.nosorted
     823             : #define tnorevsorted    T.norevsorted
     824             : #define tminpos         T.minpos
     825             : #define tmaxpos         T.maxpos
     826             : #define tunique_est     T.unique_est
     827             : #define theap           T.heap
     828             : #define tbaseoff        T.baseoff
     829             : #define tvheap          T.vheap
     830             : #define thash           T.hash
     831             : #define timprints       T.imprints
     832             : #define tprops          T.props
     833             : #define tstrimps        T.strimps
     834             : #ifdef HAVE_RTREE
     835             : #define trtree          T.rtree
     836             : #endif
     837             : 
     838             : /* some access functions for the bitmask type */
     839             : static inline void
     840         134 : mskSet(BAT *b, BUN p)
     841             : {
     842         134 :         ((uint32_t *) b->theap->base)[p / 32] |= 1U << (p % 32);
     843         134 : }
     844             : 
     845             : static inline void
     846        7822 : mskClr(BAT *b, BUN p)
     847             : {
     848        7822 :         ((uint32_t *) b->theap->base)[p / 32] &= ~(1U << (p % 32));
     849        7822 : }
     850             : 
     851             : static inline void
     852        7956 : mskSetVal(BAT *b, BUN p, msk v)
     853             : {
     854        7956 :         if (v)
     855         134 :                 mskSet(b, p);
     856             :         else
     857        7822 :                 mskClr(b, p);
     858        7956 : }
     859             : 
     860             : static inline msk
     861           0 : mskGetVal(BAT *b, BUN p)
     862             : {
     863           0 :         return ((uint32_t *) b->theap->base)[p / 32] & (1U << (p % 32));
     864             : }
     865             : 
     866             : /*
     867             :  * @- Heap Management
     868             :  * Heaps are the low-level entities of mass storage in
     869             :  * BATs. Currently, they can either be stored on disk, loaded into
     870             :  * memory, or memory mapped.
     871             :  * @multitable @columnfractions 0.08 0.7
     872             :  * @item int
     873             :  * @tab
     874             :  *  HEAPalloc (Heap *h, size_t nitems, size_t itemsize);
     875             :  * @item int
     876             :  * @tab
     877             :  *  HEAPfree (Heap *h, bool remove);
     878             :  * @item int
     879             :  * @tab
     880             :  *  HEAPextend (Heap *h, size_t size, bool mayshare);
     881             :  * @item int
     882             :  * @tab
     883             :  *  HEAPload (Heap *h, str nme,ext, bool trunc);
     884             :  * @item int
     885             :  * @tab
     886             :  *  HEAPsave (Heap *h, str nme,ext, bool dosync);
     887             :  * @item int
     888             :  * @tab
     889             :  *  HEAPcopy (Heap *dst,*src);
     890             :  * @end multitable
     891             :  *
     892             :  *
     893             :  * These routines should be used to alloc free or extend heaps; they
     894             :  * isolate you from the different ways heaps can be accessed.
     895             :  */
     896             : gdk_export gdk_return HEAPextend(Heap *h, size_t size, bool mayshare)
     897             :         __attribute__((__warn_unused_result__));
     898             : gdk_export size_t HEAPvmsize(Heap *h);
     899             : gdk_export size_t HEAPmemsize(Heap *h);
     900             : gdk_export void HEAPdecref(Heap *h, bool remove);
     901             : gdk_export void HEAPincref(Heap *h);
     902             : 
     903             : #define VIEWtparent(x)  ((x)->theap == NULL || (x)->theap->parentid == (x)->batCacheid ? 0 : (x)->theap->parentid)
     904             : #define VIEWvtparent(x) ((x)->tvheap == NULL || (x)->tvheap->parentid == (x)->batCacheid ? 0 : (x)->tvheap->parentid)
     905             : 
     906             : #define isVIEW(x)       (VIEWtparent(x) != 0 || VIEWvtparent(x) != 0)
     907             : 
     908             : /*
     909             :  * @+ BAT Buffer Pool
     910             :  * @multitable @columnfractions 0.08 0.7
     911             :  * @item int
     912             :  * @tab BBPfix (bat bi)
     913             :  * @item int
     914             :  * @tab BBPunfix (bat bi)
     915             :  * @item int
     916             :  * @tab BBPretain (bat bi)
     917             :  * @item int
     918             :  * @tab BBPrelease (bat bi)
     919             :  * @item bat
     920             :  * @tab BBPindex  (str nme)
     921             :  * @item BAT*
     922             :  * @tab BATdescriptor (bat bi)
     923             :  * @end multitable
     924             :  *
     925             :  * The BAT Buffer Pool module contains the code to manage the storage
     926             :  * location of BATs.
     927             :  *
     928             :  * The remaining BBP tables contain status information to load, swap
     929             :  * and migrate the BATs. The core table is BBPcache which contains a
     930             :  * pointer to the BAT descriptor with its heaps.  A zero entry means
     931             :  * that the file resides on disk. Otherwise it has been read or mapped
     932             :  * into memory.
     933             :  *
     934             :  * BATs loaded into memory are retained in a BAT buffer pool.  They
     935             :  * retain their position within the cache during their life cycle,
     936             :  * which make indexing BATs a stable operation.
     937             :  *
     938             :  * The BBPindex routine checks if a BAT with a certain name is
     939             :  * registered in the buffer pools. If so, it returns its BAT id.  The
     940             :  * BATdescriptor routine has a BAT id parameter, and returns a pointer
     941             :  * to the corresponding BAT record (after incrementing the reference
     942             :  * count). The BAT will be loaded into memory, if necessary.
     943             :  *
     944             :  * The structure of the BBP file obeys the tuple format for GDK.
     945             :  *
     946             :  * The status and BAT persistency information is encoded in the status
     947             :  * field.
     948             :  */
     949             : typedef struct {
     950             :         char *logical;          /* logical name (may point at bak) */
     951             :         char bak[16];           /* logical name backup (tmp_%o) */
     952             :         BAT descr;              /* the BAT descriptor */
     953             :         char *options;          /* A string list of options */
     954             : #if SIZEOF_VOID_P == 4
     955             :         char physical[20];      /* dir + basename for storage */
     956             : #else
     957             :         char physical[24];      /* dir + basename for storage */
     958             : #endif
     959             :         bat next;               /* next BBP slot in linked list */
     960             :         int refs;               /* in-memory references on which the loaded status of a BAT relies */
     961             :         int lrefs;              /* logical references on which the existence of a BAT relies */
     962             :         ATOMIC_TYPE status;     /* status mask used for spin locking */
     963             :         MT_Id pid;              /* creator of this bat while "private" */
     964             : } BBPrec;
     965             : 
     966             : gdk_export bat BBPlimit;
     967             : #if SIZEOF_VOID_P == 4
     968             : #define N_BBPINIT       1000
     969             : #define BBPINITLOG      11
     970             : #else
     971             : #define N_BBPINIT       10000
     972             : #define BBPINITLOG      14
     973             : #endif
     974             : #define BBPINIT         (1 << BBPINITLOG)
     975             : /* absolute maximum number of BATs is N_BBPINIT * BBPINIT
     976             :  * this also gives the longest possible "physical" name and "bak" name
     977             :  * of a BAT: the "bak" name is "tmp_%o", so at most 14 + \0 bytes on 64
     978             :  * bit architecture and 11 + \0 on 32 bit architecture; the physical
     979             :  * name is a bit more complicated, but the longest possible name is 22 +
     980             :  * \0 bytes (16 + \0 on 32 bits), the longest possible extension adds
     981             :  * another 17 bytes (.thsh(grp|uni)(l|b)%08x) */
     982             : gdk_export BBPrec *BBP[N_BBPINIT];
     983             : 
     984             : /* fast defines without checks; internal use only  */
     985             : #define BBP_record(i)   BBP[(i)>>BBPINITLOG][(i)&(BBPINIT-1)]
     986             : #define BBP_logical(i)  BBP_record(i).logical
     987             : #define BBP_bak(i)      BBP_record(i).bak
     988             : #define BBP_next(i)     BBP_record(i).next
     989             : #define BBP_physical(i) BBP_record(i).physical
     990             : #define BBP_options(i)  BBP_record(i).options
     991             : #define BBP_desc(i)     (&BBP_record(i).descr)
     992             : #define BBP_refs(i)     BBP_record(i).refs
     993             : #define BBP_lrefs(i)    BBP_record(i).lrefs
     994             : #define BBP_status(i)   ((unsigned) ATOMIC_GET(&BBP_record(i).status))
     995             : #define BBP_pid(i)      BBP_record(i).pid
     996             : #define BATgetId(b)     BBP_logical((b)->batCacheid)
     997             : #define BBPvalid(i)     (BBP_logical(i) != NULL)
     998             : 
     999             : #define BBPRENAME_ALREADY       (-1)
    1000             : #define BBPRENAME_ILLEGAL       (-2)
    1001             : #define BBPRENAME_LONG          (-3)
    1002             : #define BBPRENAME_MEMORY        (-4)
    1003             : 
    1004             : gdk_export void BBPlock(void);
    1005             : gdk_export void BBPunlock(void);
    1006             : gdk_export void BBPtmlock(void);
    1007             : gdk_export void BBPtmunlock(void);
    1008             : 
    1009             : gdk_export BAT *BBPquickdesc(bat b);
    1010             : 
    1011             : /* BAT iterator, also protects use of BAT heaps with reference counts.
    1012             :  *
    1013             :  * A BAT iterator has to be used with caution, but it does have to be
    1014             :  * used in many place.
    1015             :  *
    1016             :  * An iterator is initialized by assigning it the result of a call to
    1017             :  * either bat_iterator or bat_iterator_nolock.  The former must be
    1018             :  * accompanied by a call to bat_iterator_end to release resources.
    1019             :  *
    1020             :  * bat_iterator should be used for BATs that could possibly be modified
    1021             :  * in another thread while we're reading the contents of the BAT.
    1022             :  * Alternatively, but only for very quick access, the theaplock can be
    1023             :  * taken, the data read, and the lock released.  For longer duration
    1024             :  * accesses, it is better to use the iterator, even without the BUNt*
    1025             :  * macros, since the theaplock is only held very briefly.
    1026             :  *
    1027             :  * Note, bat_iterator must only be used for read-only access.
    1028             :  *
    1029             :  * If BATs are to be modified, higher level code must assure that no
    1030             :  * other thread is going to modify the same BAT at the same time.  A
    1031             :  * to-be-modified BAT should not use bat_iterator.  It can use
    1032             :  * bat_iterator_nolock, but be aware that this creates a copy of the
    1033             :  * heap pointer(s) (i.e. theap and tvheap) and if the heaps get
    1034             :  * extended, the pointers in the BAT structure may be modified, but that
    1035             :  * does not modify the pointers in the iterator.  This means that after
    1036             :  * operations that may grow a heap, the iterator should be
    1037             :  * reinitialized.
    1038             :  *
    1039             :  * The BAT iterator provides a number of fields that can (and often
    1040             :  * should) be used to access information about the BAT.  For string
    1041             :  * BATs, if a parallel threads adds values, the offset heap (theap) may
    1042             :  * get replaced by one that is wider.  This involves changing the twidth
    1043             :  * and tshift values in the BAT structure.  These changed values should
    1044             :  * not be used to access the data in the iterator.  Instead, use the
    1045             :  * width and shift values in the iterator itself.
    1046             :  */
    1047             : typedef struct BATiter {
    1048             :         BAT *b;
    1049             :         Heap *h;
    1050             :         void *base;
    1051             :         Heap *vh;
    1052             :         BUN count;
    1053             :         BUN baseoff;
    1054             :         oid tseq;
    1055             :         BUN hfree, vhfree;
    1056             :         BUN nokey[2];
    1057             :         BUN nosorted, norevsorted;
    1058             :         BUN minpos, maxpos;
    1059             :         double unique_est;
    1060             :         uint16_t width;
    1061             :         uint8_t shift;
    1062             :         int8_t type;
    1063             :         bool key:1,
    1064             :                 nonil:1,
    1065             :                 nil:1,
    1066             :                 sorted:1,
    1067             :                 revsorted:1,
    1068             :                 hdirty:1,
    1069             :                 vhdirty:1,
    1070             :                 copiedtodisk:1,
    1071             :                 transient:1,
    1072             :                 ascii:1;
    1073             :         restrict_t restricted:2;
    1074             : #ifndef NDEBUG
    1075             :         bool locked:1;
    1076             : #endif
    1077             :         union {
    1078             :                 oid tvid;
    1079             :                 bool tmsk;
    1080             :         };
    1081             : } BATiter;
    1082             : 
    1083             : static inline BATiter
    1084   117717661 : bat_iterator_nolock(BAT *b)
    1085             : {
    1086             :         /* does not get matched by bat_iterator_end */
    1087   117717661 :         if (b) {
    1088   117717661 :                 const bool isview = VIEWtparent(b) != 0;
    1089   235435322 :                 return (BATiter) {
    1090             :                         .b = b,
    1091             :                         .h = b->theap,
    1092   117717661 :                         .base = b->theap->base ? b->theap->base + (b->tbaseoff << b->tshift) : NULL,
    1093   117717661 :                         .baseoff = b->tbaseoff,
    1094   117717661 :                         .vh = b->tvheap,
    1095   117717661 :                         .count = b->batCount,
    1096   117717661 :                         .width = b->twidth,
    1097   117717661 :                         .shift = b->tshift,
    1098             :                         .type = b->ttype,
    1099   117717661 :                         .tseq = b->tseqbase,
    1100             :                         /* don't use b->theap->free in case b is a slice */
    1101   117717661 :                         .hfree = b->ttype ?
    1102             :                                   b->ttype == TYPE_msk ?
    1103   116189890 :                                    (((size_t) b->batCount + 31) / 32) * 4 :
    1104   233285200 :                                   (size_t) b->batCount << b->tshift :
    1105             :                                  0,
    1106   117717661 :                         .vhfree = b->tvheap ? b->tvheap->free : 0,
    1107   117717661 :                         .nokey[0] = b->tnokey[0],
    1108   117717661 :                         .nokey[1] = b->tnokey[1],
    1109   117717661 :                         .nosorted = b->tnosorted,
    1110   117717661 :                         .norevsorted = b->tnorevsorted,
    1111   117717661 :                         .minpos = isview ? BUN_NONE : b->tminpos,
    1112   104082013 :                         .maxpos = isview ? BUN_NONE : b->tmaxpos,
    1113   117717661 :                         .unique_est = b->tunique_est,
    1114   117717661 :                         .key = b->tkey,
    1115   117717661 :                         .nonil = b->tnonil,
    1116   117717661 :                         .nil = b->tnil,
    1117   117717661 :                         .sorted = b->tsorted,
    1118   117717661 :                         .revsorted = b->trevsorted,
    1119   117717661 :                         .ascii = b->tascii,
    1120             :                         /* only look at heap dirty flag if we own it */
    1121   117717661 :                         .hdirty = b->theap->parentid == b->batCacheid && b->theap->dirty,
    1122             :                         /* also, if there is no vheap, it's not dirty */
    1123   117717661 :                         .vhdirty = b->tvheap && b->tvheap->parentid == b->batCacheid && b->tvheap->dirty,
    1124   117717661 :                         .copiedtodisk = b->batCopiedtodisk,
    1125   117717661 :                         .transient = b->batTransient,
    1126   117717661 :                         .restricted = b->batRestricted,
    1127             : #ifndef NDEBUG
    1128             :                         .locked = false,
    1129             : #endif
    1130             :                 };
    1131             :         }
    1132           0 :         return (BATiter) {0};
    1133             : }
    1134             : 
    1135             : static inline void
    1136    34811875 : bat_iterator_incref(BATiter *bi)
    1137             : {
    1138             : #ifndef NDEBUG
    1139    34811875 :         bi->locked = true;
    1140             : #endif
    1141    34811875 :         HEAPincref(bi->h);
    1142    34819826 :         if (bi->vh)
    1143     7770286 :                 HEAPincref(bi->vh);
    1144    34819840 : }
    1145             : 
    1146             : static inline BATiter
    1147    33669469 : bat_iterator(BAT *b)
    1148             : {
    1149             :         /* needs matching bat_iterator_end */
    1150    33669469 :         BATiter bi;
    1151    33669469 :         if (b) {
    1152    32015153 :                 BAT *pb = NULL, *pvb = NULL;
    1153             :                 /* for a view, always first lock the view and then the
    1154             :                  * parent(s)
    1155             :                  * note that a varsized bat can have two different
    1156             :                  * parents and that the parent for the tail can itself
    1157             :                  * have a parent for its vheap (which would have to be
    1158             :                  * our own vheap parent), so lock the vheap after the
    1159             :                  * tail */
    1160    32015153 :                 MT_lock_set(&b->theaplock);
    1161    32011694 :                 if (b->theap->parentid != b->batCacheid) {
    1162     9196762 :                         pb = BBP_desc(b->theap->parentid);
    1163     9196762 :                         MT_lock_set(&pb->theaplock);
    1164             :                 }
    1165    32012214 :                 if (b->tvheap &&
    1166     7082703 :                     b->tvheap->parentid != b->batCacheid &&
    1167     2277935 :                     b->tvheap->parentid != b->theap->parentid) {
    1168      193608 :                         pvb = BBP_desc(b->tvheap->parentid);
    1169      193608 :                         MT_lock_set(&pvb->theaplock);
    1170             :                 }
    1171    32012214 :                 bi = bat_iterator_nolock(b);
    1172    32012214 :                 bat_iterator_incref(&bi);
    1173    32015907 :                 if (pvb)
    1174      193613 :                         MT_lock_unset(&pvb->theaplock);
    1175    32017968 :                 if (pb)
    1176     9198380 :                         MT_lock_unset(&pb->theaplock);
    1177    32017033 :                 MT_lock_unset(&b->theaplock);
    1178             :         } else {
    1179     1654316 :                 bi = (BATiter) {
    1180             :                         .b = NULL,
    1181             : #ifndef NDEBUG
    1182             :                         .locked = true,
    1183             : #endif
    1184             :                 };
    1185             :         }
    1186    33668859 :         return bi;
    1187             : }
    1188             : 
    1189             : /* return a copy of a BATiter instance; needs to be released with
    1190             :  * bat_iterator_end */
    1191             : static inline BATiter
    1192       48482 : bat_iterator_copy(BATiter *bip)
    1193             : {
    1194       48482 :         assert(bip);
    1195       48482 :         assert(bip->locked);
    1196       48482 :         if (bip->h)
    1197       48482 :                 HEAPincref(bip->h);
    1198       48482 :         if (bip->vh)
    1199       17263 :                 HEAPincref(bip->vh);
    1200       48482 :         return *bip;
    1201             : }
    1202             : 
    1203             : static inline void
    1204    36521692 : bat_iterator_end(BATiter *bip)
    1205             : {
    1206             :         /* matches bat_iterator */
    1207    36521692 :         assert(bip);
    1208    36521692 :         assert(bip->locked);
    1209    36521692 :         if (bip->h)
    1210    34867263 :                 HEAPdecref(bip->h, false);
    1211    36519828 :         if (bip->vh)
    1212     7787560 :                 HEAPdecref(bip->vh, false);
    1213    36519863 :         *bip = (BATiter) {0};
    1214    36519863 : }
    1215             : 
    1216             : /*
    1217             :  * @- Internal HEAP Chunk Management
    1218             :  * Heaps are used in BATs to store data for variable-size atoms.  The
    1219             :  * implementer must manage malloc()/free() functionality for atoms in
    1220             :  * this heap. A standard implementation is provided here.
    1221             :  *
    1222             :  * @table @code
    1223             :  * @item void
    1224             :  * HEAP_initialize  (Heap* h, size_t nbytes, size_t nprivate, int align )
    1225             :  * @item void
    1226             :  * HEAP_destroy     (Heap* h)
    1227             :  * @item var_t
    1228             :  * HEAP_malloc      (Heap* heap, size_t nbytes)
    1229             :  * @item void
    1230             :  * HEAP_free        (Heap *heap, var_t block)
    1231             :  * @item int
    1232             :  * HEAP_private     (Heap* h)
    1233             :  * @item void
    1234             :  * HEAP_printstatus (Heap* h)
    1235             :  * @end table
    1236             :  *
    1237             :  * The heap space starts with a private space that is left untouched
    1238             :  * by the normal chunk allocation.  You can use this private space
    1239             :  * e.g. to store the root of an rtree HEAP_malloc allocates a chunk of
    1240             :  * memory on the heap, and returns an index to it.  HEAP_free frees a
    1241             :  * previously allocated chunk HEAP_private returns an integer index to
    1242             :  * private space.
    1243             :  */
    1244             : 
    1245             : gdk_export gdk_return HEAP_initialize(
    1246             :         Heap *heap,             /* nbytes -- Initial size of the heap. */
    1247             :         size_t nbytes,          /* alignment -- for objects on the heap. */
    1248             :         size_t nprivate,        /* nprivate -- Size of private space */
    1249             :         int alignment           /* alignment restriction for allocated chunks */
    1250             :         );
    1251             : 
    1252             : gdk_export var_t HEAP_malloc(BAT *b, size_t nbytes);
    1253             : gdk_export void HEAP_free(Heap *heap, var_t block);
    1254             : 
    1255             : /*
    1256             :  * @- BAT construction
    1257             :  * @multitable @columnfractions 0.08 0.7
    1258             :  * @item @code{BAT* }
    1259             :  * @tab COLnew (oid headseq, int tailtype, BUN cap, role_t role)
    1260             :  * @item @code{BAT* }
    1261             :  * @tab BATextend (BAT *b, BUN newcap)
    1262             :  * @end multitable
    1263             :  *
    1264             :  * A temporary BAT is instantiated using COLnew with the type aliases
    1265             :  * of the required binary association. The aliases include the
    1266             :  * built-in types, such as TYPE_int....TYPE_ptr, and the atomic types
    1267             :  * introduced by the user. The initial capacity to be accommodated
    1268             :  * within a BAT is indicated by cap.  Their extend is automatically
    1269             :  * incremented upon storage overflow.  Failure to create the BAT
    1270             :  * results in a NULL pointer.
    1271             :  *
    1272             :  * The routine BATclone creates an empty BAT storage area with the
    1273             :  * properties inherited from its argument.
    1274             :  */
    1275             : gdk_export BAT *COLnew(oid hseq, int tltype, BUN capacity, role_t role)
    1276             :         __attribute__((__warn_unused_result__));
    1277             : gdk_export BAT *COLnew2(oid hseq, int tt, BUN cap, role_t role, uint16_t width)
    1278             :         __attribute__((__warn_unused_result__));
    1279             : gdk_export BAT *BATdense(oid hseq, oid tseq, BUN cnt)
    1280             :         __attribute__((__warn_unused_result__));
    1281             : gdk_export gdk_return BATextend(BAT *b, BUN newcap)
    1282             :         __attribute__((__warn_unused_result__));
    1283             : 
    1284             : /* internal */
    1285             : gdk_export uint8_t ATOMelmshift(int sz)
    1286             :         __attribute__((__const__));
    1287             : gdk_export gdk_return ATOMheap(int id, Heap *hp, size_t cap)
    1288             :         __attribute__((__warn_unused_result__));
    1289             : gdk_export const char *BATtailname(const BAT *b);
    1290             : 
    1291             : gdk_export gdk_return GDKupgradevarheap(BAT *b, var_t v, BUN cap, BUN ncopy)
    1292             :         __attribute__((__warn_unused_result__));
    1293             : gdk_export gdk_return BUNappend(BAT *b, const void *right, bool force)
    1294             :         __attribute__((__warn_unused_result__));
    1295             : gdk_export gdk_return BUNappendmulti(BAT *b, const void *values, BUN count, bool force)
    1296             :         __attribute__((__warn_unused_result__));
    1297             : gdk_export gdk_return BATappend(BAT *b, BAT *n, BAT *s, bool force)
    1298             :         __attribute__((__warn_unused_result__));
    1299             : 
    1300             : gdk_export gdk_return BUNreplace(BAT *b, oid left, const void *right, bool force)
    1301             :         __attribute__((__warn_unused_result__));
    1302             : gdk_export gdk_return BUNreplacemulti(BAT *b, const oid *positions, const void *values, BUN count, bool force)
    1303             :         __attribute__((__warn_unused_result__));
    1304             : gdk_export gdk_return BUNreplacemultiincr(BAT *b, oid position, const void *values, BUN count, bool force)
    1305             :         __attribute__((__warn_unused_result__));
    1306             : 
    1307             : gdk_export gdk_return BUNdelete(BAT *b, oid o)
    1308             :         __attribute__((__warn_unused_result__));
    1309             : gdk_export gdk_return BATdel(BAT *b, BAT *d)
    1310             :         __attribute__((__warn_unused_result__));
    1311             : 
    1312             : gdk_export gdk_return BATreplace(BAT *b, BAT *p, BAT *n, bool force)
    1313             :         __attribute__((__warn_unused_result__));
    1314             : gdk_export gdk_return BATupdate(BAT *b, BAT *p, BAT *n, bool force)
    1315             :         __attribute__((__warn_unused_result__));
    1316             : gdk_export gdk_return BATupdatepos(BAT *b, const oid *positions, BAT *n, bool autoincr, bool force)
    1317             :         __attribute__((__warn_unused_result__));
    1318             : 
    1319             : /* Functions to perform a binary search on a sorted BAT.
    1320             :  * See gdk_search.c for details. */
    1321             : gdk_export BUN SORTfnd(BAT *b, const void *v);
    1322             : gdk_export BUN SORTfndfirst(BAT *b, const void *v);
    1323             : gdk_export BUN SORTfndlast(BAT *b, const void *v);
    1324             : 
    1325             : gdk_export BUN ORDERfnd(BAT *b, Heap *oidxh, const void *v);
    1326             : gdk_export BUN ORDERfndfirst(BAT *b, Heap *oidxh, const void *v);
    1327             : gdk_export BUN ORDERfndlast(BAT *b, Heap *oidxh, const void *v);
    1328             : 
    1329             : gdk_export BUN BUNfnd(BAT *b, const void *right);
    1330             : 
    1331             : #define BUNfndVOID(b, v)                                                \
    1332             :         (((is_oid_nil(*(const oid*)(v)) ^ is_oid_nil((b)->tseqbase)) |       \
    1333             :                 (*(const oid*)(v) < (b)->tseqbase) |                      \
    1334             :                 (*(const oid*)(v) >= (b)->tseqbase + (b)->batCount)) ? \
    1335             :          BUN_NONE :                                                     \
    1336             :          (BUN) (*(const oid*)(v) - (b)->tseqbase))
    1337             : 
    1338             : #define BATttype(b)     (BATtdense(b) ? TYPE_oid : (b)->ttype)
    1339             : 
    1340             : #define tailsize(b,p)   ((b)->ttype ?                                \
    1341             :                          (ATOMstorage((b)->ttype) == TYPE_msk ?      \
    1342             :                           (((size_t) (p) + 31) / 32) * 4 :      \
    1343             :                           ((size_t) (p)) << (b)->tshift) :     \
    1344             :                          0)
    1345             : 
    1346             : #define Tloc(b,p)       ((void *)((b)->theap->base+(((size_t)(p)+(b)->tbaseoff)<<(b)->tshift)))
    1347             : 
    1348             : typedef var_t stridx_t;
    1349             : #define SIZEOF_STRIDX_T SIZEOF_VAR_T
    1350             : #define GDK_VARALIGN SIZEOF_STRIDX_T
    1351             : 
    1352             : #define BUNtvaroff(bi,p) VarHeapVal((bi).base, (p), (bi).width)
    1353             : 
    1354             : #define BUNtmsk(bi,p)   Tmsk(&(bi), (p))
    1355             : #define BUNtloc(bi,p)   (assert((bi).type != TYPE_msk), ((void *) ((char *) (bi).base + ((p) << (bi).shift))))
    1356             : #define BUNtpos(bi,p)   Tpos(&(bi),p)
    1357             : #define BUNtvar(bi,p)   (assert((bi).type && (bi).vh), (void *) ((bi).vh->base+BUNtvaroff(bi,p)))
    1358             : #define BUNtail(bi,p)   ((bi).type?(bi).vh?BUNtvar(bi,p):(bi).type==TYPE_msk?BUNtmsk(bi,p):BUNtloc(bi,p):BUNtpos(bi,p))
    1359             : 
    1360             : #define BATcount(b)     ((b)->batCount)
    1361             : 
    1362             : #include "gdk_atoms.h"
    1363             : 
    1364             : #include "gdk_cand.h"
    1365             : 
    1366             : /*
    1367             :  * @- BAT properties
    1368             :  * @multitable @columnfractions 0.08 0.7
    1369             :  * @item BUN
    1370             :  * @tab BATcount (BAT *b)
    1371             :  * @item void
    1372             :  * @tab BATsetcapacity (BAT *b, BUN cnt)
    1373             :  * @item void
    1374             :  * @tab BATsetcount (BAT *b, BUN cnt)
    1375             :  * @item BAT *
    1376             :  * @tab BATkey (BAT *b, bool onoff)
    1377             :  * @item BAT *
    1378             :  * @tab BATmode (BAT *b, bool transient)
    1379             :  * @item BAT *
    1380             :  * @tab BATsetaccess (BAT *b, restrict_t mode)
    1381             :  * @item int
    1382             :  * @tab BATdirty (BAT *b)
    1383             :  * @item restrict_t
    1384             :  * @tab BATgetaccess (BAT *b)
    1385             :  * @end multitable
    1386             :  *
    1387             :  * The function BATcount returns the number of associations stored in
    1388             :  * the BAT.
    1389             :  *
    1390             :  * The BAT is given a new logical name using BBPrename.
    1391             :  *
    1392             :  * The integrity properties to be maintained for the BAT are
    1393             :  * controlled separately.  A key property indicates that duplicates in
    1394             :  * the association dimension are not permitted.
    1395             :  *
    1396             :  * The persistency indicator tells the retention period of BATs.  The
    1397             :  * system support two modes: PERSISTENT and TRANSIENT.
    1398             :  * The PERSISTENT BATs are automatically saved upon session boundary
    1399             :  * or transaction commit.  TRANSIENT BATs are removed upon transaction
    1400             :  * boundary.  All BATs are initially TRANSIENT unless their mode is
    1401             :  * changed using the routine BATmode.
    1402             :  *
    1403             :  * The BAT properties may be changed at any time using BATkey
    1404             :  * and BATmode.
    1405             :  *
    1406             :  * Valid BAT access properties can be set with BATsetaccess and
    1407             :  * BATgetaccess: BAT_READ, BAT_APPEND, and BAT_WRITE.  BATs can be
    1408             :  * designated to be read-only. In this case some memory optimizations
    1409             :  * may be made (slice and fragment bats can point to stable subsets of
    1410             :  * a parent bat).  A special mode is append-only. It is then allowed
    1411             :  * to insert BUNs at the end of the BAT, but not to modify anything
    1412             :  * that already was in there.
    1413             :  */
    1414             : gdk_export BUN BATcount_no_nil(BAT *b, BAT *s);
    1415             : gdk_export void BATsetcapacity(BAT *b, BUN cnt);
    1416             : gdk_export void BATsetcount(BAT *b, BUN cnt);
    1417             : gdk_export BUN BATgrows(BAT *b);
    1418             : gdk_export gdk_return BATkey(BAT *b, bool onoff);
    1419             : gdk_export gdk_return BATmode(BAT *b, bool transient);
    1420             : gdk_export void BAThseqbase(BAT *b, oid o);
    1421             : gdk_export void BATtseqbase(BAT *b, oid o);
    1422             : 
    1423             : gdk_export BAT *BATsetaccess(BAT *b, restrict_t mode)
    1424             :         __attribute__((__warn_unused_result__));
    1425             : gdk_export restrict_t BATgetaccess(BAT *b);
    1426             : 
    1427             : 
    1428             : #define BATdirty(b)     (!(b)->batCopiedtodisk ||                    \
    1429             :                          (b)->theap->dirty ||                             \
    1430             :                          ((b)->tvheap != NULL && (b)->tvheap->dirty))
    1431             : #define BATdirtybi(bi)  (!(bi).copiedtodisk || (bi).hdirty || (bi).vhdirty)
    1432             : 
    1433             : #define BATcapacity(b)  (b)->batCapacity
    1434             : /*
    1435             :  * @- BAT manipulation
    1436             :  * @multitable @columnfractions 0.08 0.7
    1437             :  * @item BAT *
    1438             :  * @tab BATclear (BAT *b, bool force)
    1439             :  * @item BAT *
    1440             :  * @tab COLcopy (BAT *b, int tt, bool writeable, role_t role)
    1441             :  * @end multitable
    1442             :  *
    1443             :  * The routine BATclear removes the binary associations, leading to an
    1444             :  * empty, but (re-)initialized BAT. Its properties are retained.  A
    1445             :  * temporary copy is obtained with Colcopy. The new BAT has an unique
    1446             :  * name.
    1447             :  */
    1448             : gdk_export gdk_return BATclear(BAT *b, bool force);
    1449             : gdk_export BAT *COLcopy(BAT *b, int tt, bool writable, role_t role);
    1450             : 
    1451             : gdk_export gdk_return BATgroup(BAT **groups, BAT **extents, BAT **histo, BAT *b, BAT *s, BAT *g, BAT *e, BAT *h)
    1452             :         __attribute__((__warn_unused_result__));
    1453             : /*
    1454             :  * @- BAT Input/Output
    1455             :  * @multitable @columnfractions 0.08 0.7
    1456             :  * @item BAT *
    1457             :  * @tab BATload (str name)
    1458             :  * @item BAT *
    1459             :  * @tab BATsave (BAT *b)
    1460             :  * @item int
    1461             :  * @tab BATdelete (BAT *b)
    1462             :  * @end multitable
    1463             :  *
    1464             :  * A BAT created by COLnew is considered temporary until one calls the
    1465             :  * routine BATsave or BATmode.  This routine reserves disk space and
    1466             :  * checks for name clashes in the BAT directory. It also makes the BAT
    1467             :  * persistent. The empty BAT is initially marked as ordered on both
    1468             :  * columns.
    1469             :  *
    1470             :  * Failure to read or write the BAT results in a NULL, otherwise it
    1471             :  * returns the BAT pointer.
    1472             :  *
    1473             :  * @- Heap Storage Modes
    1474             :  * The discriminative storage modes are memory-mapped, compressed, or
    1475             :  * loaded in memory.  As can be seen in the bat record, each BAT has
    1476             :  * one BUN-heap (@emph{bn}), and possibly two heaps (@emph{hh} and
    1477             :  * @emph{th}) for variable-sized atoms.
    1478             :  */
    1479             : 
    1480             : gdk_export gdk_return BATsave(BAT *b)
    1481             :         __attribute__((__warn_unused_result__));
    1482             : 
    1483             : #define NOFARM (-1) /* indicate to GDKfilepath to create relative path */
    1484             : 
    1485             : gdk_export char *GDKfilepath(int farmid, const char *dir, const char *nme, const char *ext);
    1486             : gdk_export bool GDKinmemory(int farmid);
    1487             : gdk_export bool GDKembedded(void);
    1488             : gdk_export gdk_return GDKcreatedir(const char *nme);
    1489             : 
    1490             : gdk_export void OIDXdestroy(BAT *b);
    1491             : 
    1492             : /*
    1493             :  * @- Printing
    1494             :  * @multitable @columnfractions 0.08 0.7
    1495             :  * @item int
    1496             :  * @tab BATprintcolumns (stream *f, int argc, BAT *b[]);
    1497             :  * @end multitable
    1498             :  *
    1499             :  * The functions to convert BATs into ASCII. They are primarily meant for ease of
    1500             :  * debugging and to a lesser extent for output processing.  Printing a
    1501             :  * BAT is done essentially by looping through its components, printing
    1502             :  * each association.
    1503             :  *
    1504             :  */
    1505             : gdk_export gdk_return BATprintcolumns(stream *s, int argc, BAT *argv[]);
    1506             : gdk_export gdk_return BATprint(stream *s, BAT *b);
    1507             : 
    1508             : /*
    1509             :  * @- BAT clustering
    1510             :  * @multitable @columnfractions 0.08 0.7
    1511             :  * @item bool
    1512             :  * @tab BATordered (BAT *b)
    1513             :  * @end multitable
    1514             :  *
    1515             :  * When working in a main-memory situation, clustering of data on
    1516             :  * disk-pages is not important. Whenever mmap()-ed data is used
    1517             :  * intensively, reducing the number of page faults is a hot issue.
    1518             :  *
    1519             :  * The above functions rearrange data in MonetDB heaps (used for
    1520             :  * storing BUNs var-sized atoms, or accelerators). Applying these
    1521             :  * clusterings will allow that MonetDB's main-memory oriented
    1522             :  * algorithms work efficiently also in a disk-oriented context.
    1523             :  *
    1524             :  * BATordered starts a check on the tail values to see if they are
    1525             :  * ordered. The result is returned and stored in the tsorted field of
    1526             :  * the BAT.
    1527             :  */
    1528             : gdk_export bool BATordered(BAT *b);
    1529             : gdk_export bool BATordered_rev(BAT *b);
    1530             : gdk_export gdk_return BATsort(BAT **sorted, BAT **order, BAT **groups, BAT *b, BAT *o, BAT *g, bool reverse, bool nilslast, bool stable)
    1531             :         __attribute__((__warn_unused_result__));
    1532             : 
    1533             : 
    1534             : gdk_export void GDKqsort(void *restrict h, void *restrict t, const void *restrict base, size_t n, int hs, int ts, int tpe, bool reverse, bool nilslast);
    1535             : 
    1536             : /* BAT is dense (i.e., BATtvoid() is true and tseqbase is not NIL) */
    1537             : #define BATtdense(b)    (!is_oid_nil((b)->tseqbase) &&                       \
    1538             :                          ((b)->tvheap == NULL || (b)->tvheap->free == 0))
    1539             : #define BATtdensebi(bi) (!is_oid_nil((bi)->tseq) &&                  \
    1540             :                          ((bi)->vh == NULL || (bi)->vhfree == 0))
    1541             : /* BATtvoid: BAT can be (or actually is) represented by TYPE_void */
    1542             : #define BATtvoid(b)     (BATtdense(b) || (b)->ttype==TYPE_void)
    1543             : #define BATtkey(b)      ((b)->tkey || BATtdense(b))
    1544             : 
    1545             : /* set some properties that are trivial to deduce; called with theaplock
    1546             :  * held */
    1547             : static inline void
    1548     4891091 : BATsettrivprop(BAT *b)
    1549             : {
    1550     4891091 :         assert(!is_oid_nil(b->hseqbase));
    1551     4891091 :         assert(is_oid_nil(b->tseqbase) || ATOMtype(b->ttype) == TYPE_oid);
    1552     4891091 :         if (b->ttype == TYPE_void) {
    1553     1225086 :                 if (is_oid_nil(b->tseqbase)) {
    1554         130 :                         b->tnonil = b->batCount == 0;
    1555         130 :                         b->tnil = !b->tnonil;
    1556         130 :                         b->trevsorted = true;
    1557         130 :                         b->tkey = b->batCount <= 1;
    1558             :                 } else {
    1559     1224956 :                         b->tnonil = true;
    1560     1224956 :                         b->tnil = false;
    1561     1224956 :                         b->tkey = true;
    1562     1224956 :                         b->trevsorted = b->batCount <= 1;
    1563             :                 }
    1564     1225086 :                 b->tsorted = true;
    1565     3666005 :         } else if (b->batCount <= 1) {
    1566     1375132 :                 b->tnosorted = b->tnorevsorted = 0;
    1567     1375132 :                 b->tnokey[0] = b->tnokey[1] = 0;
    1568     1375132 :                 b->tunique_est = (double) b->batCount;
    1569     1375132 :                 b->tkey = true;
    1570     1375132 :                 if (ATOMlinear(b->ttype)) {
    1571     1375132 :                         b->tsorted = true;
    1572     1375132 :                         b->trevsorted = true;
    1573     1375132 :                         if (b->batCount == 0) {
    1574      854623 :                                 b->tminpos = BUN_NONE;
    1575      854623 :                                 b->tmaxpos = BUN_NONE;
    1576      854623 :                                 b->tnonil = true;
    1577      854623 :                                 b->tnil = false;
    1578      854623 :                                 if (b->ttype == TYPE_oid) {
    1579       11876 :                                         b->tseqbase = 0;
    1580             :                                 }
    1581      520509 :                         } else if (b->ttype == TYPE_oid) {
    1582       68010 :                                 oid sqbs = ((const oid *) b->theap->base)[b->tbaseoff];
    1583       68010 :                                 if (is_oid_nil(sqbs)) {
    1584         334 :                                         b->tnonil = false;
    1585         334 :                                         b->tnil = true;
    1586         334 :                                         b->tminpos = BUN_NONE;
    1587         334 :                                         b->tmaxpos = BUN_NONE;
    1588             :                                 } else {
    1589       67676 :                                         b->tnonil = true;
    1590       67676 :                                         b->tnil = false;
    1591       67676 :                                         b->tminpos = 0;
    1592       67676 :                                         b->tmaxpos = 0;
    1593             :                                 }
    1594       68010 :                                 b->tseqbase = sqbs;
    1595      452516 :                         } else if ((b->tvheap
    1596      131530 :                                     ? ATOMcmp(b->ttype,
    1597             :                                               b->tvheap->base + VarHeapVal(Tloc(b, 0), 0, b->twidth),
    1598             :                                               ATOMnilptr(b->ttype))
    1599      320969 :                                     : ATOMcmp(b->ttype, Tloc(b, 0),
    1600      905015 :                                               ATOMnilptr(b->ttype))) == 0) {
    1601             :                                 /* the only value is NIL */
    1602       17048 :                                 b->tminpos = BUN_NONE;
    1603       17048 :                                 b->tmaxpos = BUN_NONE;
    1604             :                         } else {
    1605             :                                 /* the only value is both min and max */
    1606      435468 :                                 b->tminpos = 0;
    1607      435468 :                                 b->tmaxpos = 0;
    1608             :                         }
    1609             :                 } else {
    1610           0 :                         b->tsorted = false;
    1611           0 :                         b->trevsorted = false;
    1612           0 :                         b->tminpos = BUN_NONE;
    1613           0 :                         b->tmaxpos = BUN_NONE;
    1614             :                 }
    1615     2290873 :         } else if (b->batCount == 2 && ATOMlinear(b->ttype)) {
    1616      175202 :                 int c;
    1617      175202 :                 if (b->tvheap)
    1618       41070 :                         c = ATOMcmp(b->ttype,
    1619             :                                     b->tvheap->base + VarHeapVal(Tloc(b, 0), 0, b->twidth),
    1620             :                                     b->tvheap->base + VarHeapVal(Tloc(b, 0), 1, b->twidth));
    1621             :                 else
    1622      134132 :                         c = ATOMcmp(b->ttype, Tloc(b, 0), Tloc(b, 1));
    1623      175195 :                 b->tsorted = c <= 0;
    1624      175195 :                 b->tnosorted = !b->tsorted;
    1625      175195 :                 b->trevsorted = c >= 0;
    1626      175195 :                 b->tnorevsorted = !b->trevsorted;
    1627      175195 :                 b->tkey = c != 0;
    1628      175195 :                 b->tnokey[0] = 0;
    1629      175195 :                 b->tnokey[1] = !b->tkey;
    1630      175195 :                 b->tunique_est = (double) (1 + b->tkey);
    1631     2115671 :         } else if (!ATOMlinear(b->ttype)) {
    1632           0 :                 b->tsorted = false;
    1633           0 :                 b->trevsorted = false;
    1634           0 :                 b->tminpos = BUN_NONE;
    1635           0 :                 b->tmaxpos = BUN_NONE;
    1636             :         }
    1637     4891101 : }
    1638             : 
    1639             : static inline void
    1640         310 : BATnegateprops(BAT *b)
    1641             : {
    1642             :         /* disable all properties here */
    1643         310 :         b->tnonil = false;
    1644         310 :         b->tnil = false;
    1645         310 :         if (b->ttype) {
    1646         310 :                 b->tsorted = false;
    1647         310 :                 b->trevsorted = false;
    1648         310 :                 b->tnosorted = 0;
    1649         310 :                 b->tnorevsorted = 0;
    1650             :         }
    1651         310 :         b->tseqbase = oid_nil;
    1652         310 :         b->tkey = false;
    1653         310 :         b->tnokey[0] = 0;
    1654         310 :         b->tnokey[1] = 0;
    1655         310 :         b->tmaxpos = b->tminpos = BUN_NONE;
    1656         310 : }
    1657             : 
    1658             : /*
    1659             :  * @- GDK error handling
    1660             :  *  @multitable @columnfractions 0.08 0.7
    1661             :  * @item str
    1662             :  * @tab
    1663             :  *  GDKmessage
    1664             :  * @item bit
    1665             :  * @tab
    1666             :  *  GDKfatal(str msg)
    1667             :  * @item int
    1668             :  * @tab
    1669             :  *  GDKwarning(str msg)
    1670             :  * @item int
    1671             :  * @tab
    1672             :  *  GDKerror (str msg)
    1673             :  * @item int
    1674             :  * @tab
    1675             :  *  GDKgoterrors ()
    1676             :  * @item int
    1677             :  * @tab
    1678             :  *  GDKsyserror (str msg)
    1679             :  * @item str
    1680             :  * @tab
    1681             :  *  GDKerrbuf
    1682             :  *  @item
    1683             :  * @tab GDKsetbuf (str buf)
    1684             :  * @end multitable
    1685             :  *
    1686             :  * The error handling mechanism is not sophisticated yet. Experience
    1687             :  * should show if this mechanism is sufficient.  Most routines return
    1688             :  * a pointer with zero to indicate an error.
    1689             :  *
    1690             :  * The error messages are also copied to standard output.  The last
    1691             :  * error message is kept around in a global variable.
    1692             :  *
    1693             :  * Error messages can also be collected in a user-provided buffer,
    1694             :  * instead of being echoed to a stream. This is a thread-specific
    1695             :  * issue; you want to decide on the error mechanism on a
    1696             :  * thread-specific basis.  This effect is established with
    1697             :  * GDKsetbuf. The memory (de)allocation of this buffer, that must at
    1698             :  * least be 1024 chars long, is entirely by the user. A pointer to
    1699             :  * this buffer is kept in the pseudo-variable GDKerrbuf. Normally,
    1700             :  * this is a NULL pointer.
    1701             :  */
    1702             : #define GDKMAXERRLEN    10240
    1703             : #define GDKWARNING      "!WARNING: "
    1704             : #define GDKERROR        "!ERROR: "
    1705             : #define GDKMESSAGE      "!OS: "
    1706             : #define GDKFATAL        "!FATAL: "
    1707             : 
    1708             : /* Data Distilleries uses ICU for internationalization of some MonetDB error messages */
    1709             : 
    1710             : #include "gdk_tracer.h"
    1711             : 
    1712             : gdk_export gdk_return GDKtracer_fill_comp_info(BAT *id, BAT *component, BAT *log_level);
    1713             : 
    1714             : #define GDKerror(format, ...)                                   \
    1715             :         GDKtracer_log(__FILE__, __func__, __LINE__, M_ERROR,    \
    1716             :                       GDK, NULL, format, ##__VA_ARGS__)
    1717             : #define GDKsyserr(errno, format, ...)                                   \
    1718             :         GDKtracer_log(__FILE__, __func__, __LINE__, M_ERROR,            \
    1719             :                       GDK, GDKstrerror(errno, (char[64]){0}, 64),       \
    1720             :                       format, ##__VA_ARGS__)
    1721             : #define GDKsyserror(format, ...)        GDKsyserr(errno, format, ##__VA_ARGS__)
    1722             : 
    1723             : gdk_export void GDKclrerr(void);
    1724             : 
    1725             : 
    1726             : /* tfastins* family: update a value at a particular location in the bat
    1727             :  * bunfastapp* family: append a value to the bat
    1728             :  * *_nocheck: do not check whether the capacity is large enough
    1729             :  * * (without _nocheck): check bat capacity and possibly extend
    1730             :  *
    1731             :  * This means, for tfastins* it is the caller's responsibility to set
    1732             :  * the batCount and theap->free values correctly (e.g. by calling
    1733             :  * BATsetcount(), and for *_nocheck to make sure there is enough space
    1734             :  * allocated in the theap (tvheap for variable-sized types is still
    1735             :  * extended if needed, making that these functions can fail).
    1736             :  */
    1737             : static inline gdk_return __attribute__((__warn_unused_result__))
    1738   104411695 : tfastins_nocheckVAR(BAT *b, BUN p, const void *v)
    1739             : {
    1740   104411695 :         var_t d;
    1741   104411695 :         gdk_return rc;
    1742   104411695 :         assert(b->tbaseoff == 0);
    1743   104411695 :         assert(b->theap->parentid == b->batCacheid);
    1744   104411695 :         MT_lock_set(&b->theaplock);
    1745   104958276 :         rc = ATOMputVAR(b, &d, v);
    1746   104797307 :         MT_lock_unset(&b->theaplock);
    1747   105682825 :         if (rc != GDK_SUCCEED)
    1748             :                 return rc;
    1749   105659814 :         if (b->twidth < SIZEOF_VAR_T &&
    1750    93951329 :             (b->twidth <= 2 ? d - GDK_VAROFFSET : d) >= ((size_t) 1 << (8 << b->tshift))) {
    1751             :                 /* doesn't fit in current heap, upgrade it */
    1752       14045 :                 rc = GDKupgradevarheap(b, d, 0, MAX(p, b->batCount));
    1753       14046 :                 if (rc != GDK_SUCCEED)
    1754             :                         return rc;
    1755             :         }
    1756   105659815 :         switch (b->twidth) {
    1757    30464221 :         case 1:
    1758    30464221 :                 ((uint8_t *) b->theap->base)[p] = (uint8_t) (d - GDK_VAROFFSET);
    1759    30464221 :                 break;
    1760    18050223 :         case 2:
    1761    18050223 :                 ((uint16_t *) b->theap->base)[p] = (uint16_t) (d - GDK_VAROFFSET);
    1762    18050223 :                 break;
    1763    45542125 :         case 4:
    1764    45542125 :                 ((uint32_t *) b->theap->base)[p] = (uint32_t) d;
    1765    45542125 :                 break;
    1766             : #if SIZEOF_VAR_T == 8
    1767    11603246 :         case 8:
    1768    11603246 :                 ((uint64_t *) b->theap->base)[p] = (uint64_t) d;
    1769    11603246 :                 break;
    1770             : #endif
    1771             :         default:
    1772           0 :                 MT_UNREACHABLE();
    1773             :         }
    1774             :         return GDK_SUCCEED;
    1775             : }
    1776             : 
    1777             : static inline gdk_return __attribute__((__warn_unused_result__))
    1778   353584547 : tfastins_nocheckFIX(BAT *b, BUN p, const void *v)
    1779             : {
    1780   353584547 :         return ATOMputFIX(b->ttype, Tloc(b, p), v);
    1781             : }
    1782             : 
    1783             : static inline gdk_return __attribute__((__warn_unused_result__))
    1784   359288134 : tfastins_nocheck(BAT *b, BUN p, const void *v)
    1785             : {
    1786   359288134 :         assert(b->theap->parentid == b->batCacheid);
    1787   359288134 :         assert(b->tbaseoff == 0);
    1788   359288134 :         if (b->ttype == TYPE_void) {
    1789             :                 ;
    1790   359288134 :         } else if (ATOMstorage(b->ttype) == TYPE_msk) {
    1791           0 :                 mskSetVal(b, p, * (msk *) v);
    1792   359288134 :         } else if (b->tvheap) {
    1793    39945868 :                 return tfastins_nocheckVAR(b, p, v);
    1794             :         } else {
    1795   319342266 :                 return tfastins_nocheckFIX(b, p, v);
    1796             :         }
    1797             :         return GDK_SUCCEED;
    1798             : }
    1799             : 
    1800             : static inline gdk_return __attribute__((__warn_unused_result__))
    1801   346923215 : tfastins(BAT *b, BUN p, const void *v)
    1802             : {
    1803   346923215 :         if (p >= BATcapacity(b)) {
    1804           0 :                 if (p >= BUN_MAX) {
    1805           0 :                         GDKerror("tfastins: too many elements to accommodate (" BUNFMT ")\n", BUN_MAX);
    1806           0 :                         return GDK_FAIL;
    1807             :                 }
    1808           0 :                 BUN sz = BATgrows(b);
    1809           0 :                 if (sz <= p)
    1810           0 :                         sz = p + BATTINY;
    1811           0 :                 gdk_return rc = BATextend(b, sz);
    1812           0 :                 if (rc != GDK_SUCCEED)
    1813             :                         return rc;
    1814             :         }
    1815   346923215 :         return tfastins_nocheck(b, p, v);
    1816             : }
    1817             : 
    1818             : static inline gdk_return __attribute__((__warn_unused_result__))
    1819     8032565 : bunfastapp_nocheck(BAT *b, const void *v)
    1820             : {
    1821     8032565 :         BUN p = b->batCount;
    1822     8032565 :         if (ATOMstorage(b->ttype) == TYPE_msk && p % 32 == 0)
    1823           0 :                 ((uint32_t *) b->theap->base)[p / 32] = 0;
    1824     8032565 :         gdk_return rc = tfastins_nocheck(b, p, v);
    1825     8033215 :         if (rc == GDK_SUCCEED) {
    1826     8033401 :                 b->batCount++;
    1827     8033401 :                 if (ATOMstorage(b->ttype) == TYPE_msk) {
    1828           0 :                         if (p % 32 == 0)
    1829           0 :                                 b->theap->free += 4;
    1830             :                 } else
    1831     8033401 :                         b->theap->free += b->twidth;
    1832             :         }
    1833     8033215 :         return rc;
    1834             : }
    1835             : 
    1836             : static inline gdk_return __attribute__((__warn_unused_result__))
    1837   346942536 : bunfastapp(BAT *b, const void *v)
    1838             : {
    1839   346942536 :         BUN p = b->batCount;
    1840   346942536 :         if (ATOMstorage(b->ttype) == TYPE_msk && p % 32 == 0)
    1841           0 :                 ((uint32_t *) b->theap->base)[p / 32] = 0;
    1842   346942536 :         gdk_return rc = tfastins(b, p, v);
    1843   342128644 :         if (rc == GDK_SUCCEED) {
    1844   337520999 :                 b->batCount++;
    1845   337520999 :                 if (ATOMstorage(b->ttype) == TYPE_msk) {
    1846           0 :                         if (p % 32 == 0)
    1847           0 :                                 b->theap->free += 4;
    1848             :                 } else
    1849   337520999 :                         b->theap->free += b->twidth;
    1850             :         }
    1851   342128644 :         return rc;
    1852             : }
    1853             : 
    1854             : #define bunfastappTYPE(TYPE, b, v)                                      \
    1855             :         (BATcount(b) >= BATcapacity(b) &&                            \
    1856             :          ((BATcount(b) == BUN_MAX &&                                    \
    1857             :            (GDKerror("bunfastapp: too many elements to accommodate (" BUNFMT ")\n", BUN_MAX), \
    1858             :             true)) ||                                                   \
    1859             :           BATextend((b), BATgrows(b)) != GDK_SUCCEED) ?                 \
    1860             :          GDK_FAIL :                                                     \
    1861             :          (assert((b)->theap->parentid == (b)->batCacheid),             \
    1862             :           (b)->theap->free += sizeof(TYPE),                               \
    1863             :           ((TYPE *) (b)->theap->base)[(b)->batCount++] = * (const TYPE *) (v), \
    1864             :           GDK_SUCCEED))
    1865             : 
    1866             : static inline gdk_return __attribute__((__warn_unused_result__))
    1867         344 : bunfastapp_nocheckVAR(BAT *b, const void *v)
    1868             : {
    1869         344 :         gdk_return rc;
    1870         344 :         rc = tfastins_nocheckVAR(b, b->batCount, v);
    1871         344 :         if (rc == GDK_SUCCEED) {
    1872         344 :                 b->batCount++;
    1873         344 :                 b->theap->free += b->twidth;
    1874             :         }
    1875         344 :         return rc;
    1876             : }
    1877             : 
    1878             : /*
    1879             :  * @- Column Imprints Functions
    1880             :  *
    1881             :  * @multitable @columnfractions 0.08 0.7
    1882             :  * @item BAT*
    1883             :  * @tab
    1884             :  *  BATimprints (BAT *b)
    1885             :  * @end multitable
    1886             :  *
    1887             :  * The column imprints index structure.
    1888             :  *
    1889             :  */
    1890             : 
    1891             : gdk_export gdk_return BATimprints(BAT *b);
    1892             : gdk_export void IMPSdestroy(BAT *b);
    1893             : gdk_export lng IMPSimprintsize(BAT *b);
    1894             : 
    1895             : /* Strimps exported functions */
    1896             : gdk_export gdk_return STRMPcreate(BAT *b, BAT *s);
    1897             : gdk_export BAT *STRMPfilter(BAT *b, BAT *s, const char *q, const bool keep_nils);
    1898             : gdk_export void STRMPdestroy(BAT *b);
    1899             : gdk_export bool BAThasstrimps(BAT *b);
    1900             : gdk_export gdk_return BATsetstrimps(BAT *b);
    1901             : 
    1902             : /* Rtree structure functions */
    1903             : #ifdef HAVE_RTREE
    1904             : gdk_export bool RTREEexists(BAT *b);
    1905             : gdk_export bool RTREEexists_bid(bat bid);
    1906             : gdk_export gdk_return BATrtree(BAT *wkb, BAT* mbr);
    1907             : /* inMBR is really a struct mbr * from geom module, but that is not
    1908             :  * available here */
    1909             : gdk_export BUN* RTREEsearch(BAT *b, const void *inMBR, int result_limit);
    1910             : #endif
    1911             : 
    1912             : gdk_export void RTREEdestroy(BAT *b);
    1913             : gdk_export void RTREEfree(BAT *b);
    1914             : 
    1915             : /* The ordered index structure */
    1916             : 
    1917             : gdk_export gdk_return BATorderidx(BAT *b, bool stable);
    1918             : gdk_export gdk_return GDKmergeidx(BAT *b, BAT**a, int n_ar);
    1919             : gdk_export bool BATcheckorderidx(BAT *b);
    1920             : 
    1921             : #include "gdk_delta.h"
    1922             : #include "gdk_hash.h"
    1923             : #include "gdk_bbp.h"
    1924             : #include "gdk_utils.h"
    1925             : 
    1926             : /* functions defined in gdk_bat.c */
    1927             : gdk_export gdk_return void_inplace(BAT *b, oid id, const void *val, bool force)
    1928             :         __attribute__((__warn_unused_result__));
    1929             : gdk_export BAT *BATattach(int tt, const char *heapfile, role_t role);
    1930             : 
    1931             : #ifdef NATIVE_WIN32
    1932             : #ifdef _MSC_VER
    1933             : #define fileno _fileno
    1934             : #endif
    1935             : #define fdopen _fdopen
    1936             : #define putenv _putenv
    1937             : #endif
    1938             : 
    1939             : /* Return a pointer to the value contained in V.  Also see VALget
    1940             :  * which returns a void *. */
    1941             : static inline const void *
    1942   299501398 : VALptr(const ValRecord *v)
    1943             : {
    1944   299501398 :         switch (ATOMstorage(v->vtype)) {
    1945      607815 :         case TYPE_void: return (const void *) &v->val.oval;
    1946           0 :         case TYPE_msk: return (const void *) &v->val.mval;
    1947    13715542 :         case TYPE_bte: return (const void *) &v->val.btval;
    1948     1203202 :         case TYPE_sht: return (const void *) &v->val.shval;
    1949   122437645 :         case TYPE_int: return (const void *) &v->val.ival;
    1950       13125 :         case TYPE_flt: return (const void *) &v->val.fval;
    1951      566279 :         case TYPE_dbl: return (const void *) &v->val.dval;
    1952    68312192 :         case TYPE_lng: return (const void *) &v->val.lval;
    1953             : #ifdef HAVE_HGE
    1954       16731 :         case TYPE_hge: return (const void *) &v->val.hval;
    1955             : #endif
    1956         770 :         case TYPE_uuid: return (const void *) &v->val.uval;
    1957      268238 :         case TYPE_ptr: return (const void *) &v->val.pval;
    1958    92357182 :         case TYPE_str: return (const void *) v->val.sval;
    1959        2677 :         default:       return (const void *) v->val.pval;
    1960             :         }
    1961             : }
    1962             : 
    1963             : #define THREADS         1024    /* maximum value for gdk_nr_threads */
    1964             : 
    1965             : gdk_export stream *GDKstdout;
    1966             : gdk_export stream *GDKstdin;
    1967             : 
    1968             : #define GDKerrbuf       (GDKgetbuf())
    1969             : 
    1970             : static inline bat
    1971   378405863 : BBPcheck(bat x)
    1972             : {
    1973   378405863 :         if (!is_bat_nil(x)) {
    1974   378003846 :                 assert(x > 0);
    1975             : 
    1976   378003846 :                 if (x < 0 || x >= getBBPsize() || BBP_logical(x) == NULL) {
    1977           0 :                         TRC_DEBUG(CHECK_, "range error %d\n", (int) x);
    1978             :                 } else {
    1979   377413954 :                         assert(BBP_pid(x) == 0 || BBP_pid(x) == MT_getpid());
    1980   377406000 :                         return x;
    1981             :                 }
    1982             :         }
    1983             :         return 0;
    1984             : }
    1985             : 
    1986             : gdk_export BAT *BATdescriptor(bat i);
    1987             : 
    1988             : static inline void *
    1989     7668158 : Tpos(BATiter *bi, BUN p)
    1990             : {
    1991     7668158 :         assert(bi->base == NULL);
    1992     7668158 :         if (bi->vh) {
    1993     1361456 :                 oid o;
    1994     1361456 :                 assert(!is_oid_nil(bi->tseq));
    1995     1361456 :                 if (((ccand_t *) bi->vh)->type == CAND_NEGOID) {
    1996     1361456 :                         BUN nexc = (bi->vhfree - sizeof(ccand_t)) / SIZEOF_OID;
    1997     1361456 :                         o = bi->tseq + p;
    1998     1361456 :                         if (nexc > 0) {
    1999     1361455 :                                 const oid *exc = (const oid *) (bi->vh->base + sizeof(ccand_t));
    2000     1361455 :                                 if (o >= exc[0]) {
    2001       12664 :                                         if (o + nexc > exc[nexc - 1]) {
    2002             :                                                 o += nexc;
    2003             :                                         } else {
    2004        3194 :                                                 BUN lo = 0;
    2005        3194 :                                                 BUN hi = nexc - 1;
    2006       25454 :                                                 while (hi - lo > 1) {
    2007       19066 :                                                         BUN mid = (hi + lo) / 2;
    2008       19066 :                                                         if (exc[mid] - mid > o)
    2009             :                                                                 hi = mid;
    2010             :                                                         else
    2011       10308 :                                                                 lo = mid;
    2012             :                                                 }
    2013        3194 :                                                 o += hi;
    2014             :                                         }
    2015             :                                 }
    2016             :                         }
    2017             :                 } else {
    2018           0 :                         const uint32_t *msk = (const uint32_t *) (bi->vh->base + sizeof(ccand_t));
    2019           0 :                         BUN nmsk = (bi->vhfree - sizeof(ccand_t)) / sizeof(uint32_t);
    2020           0 :                         o = 0;
    2021           0 :                         for (BUN i = 0; i < nmsk; i++) {
    2022           0 :                                 uint32_t m = candmask_pop(msk[i]);
    2023           0 :                                 if (o + m > p) {
    2024           0 :                                         m = msk[i];
    2025           0 :                                         for (i = 0; i < 32; i++) {
    2026           0 :                                                 if (m & (1U << i) && ++o == p)
    2027             :                                                         break;
    2028             :                                         }
    2029             :                                         break;
    2030             :                                 }
    2031           0 :                                 o += m;
    2032             :                         }
    2033             :                 }
    2034     1361456 :                 bi->tvid = o;
    2035     6306702 :         } else if (is_oid_nil(bi->tseq)) {
    2036           0 :                 bi->tvid = oid_nil;
    2037             :         } else {
    2038     6306702 :                 bi->tvid = bi->tseq + p;
    2039             :         }
    2040     7668158 :         return (void *) &bi->tvid;
    2041             : }
    2042             : 
    2043             : static inline bool
    2044         361 : Tmskval(BATiter *bi, BUN p)
    2045             : {
    2046         361 :         assert(ATOMstorage(bi->type) == TYPE_msk);
    2047         361 :         return ((uint32_t *) bi->base)[p / 32] & (1U << (p % 32));
    2048             : }
    2049             : 
    2050             : static inline void *
    2051         361 : Tmsk(BATiter *bi, BUN p)
    2052             : {
    2053         361 :         bi->tmsk = Tmskval(bi, p);
    2054         361 :         return &bi->tmsk;
    2055             : }
    2056             : 
    2057             : /* return the oid value at BUN position p from the (v)oid bat b
    2058             :  * works with any TYPE_void or TYPE_oid bat */
    2059             : static inline oid
    2060    22545519 : BUNtoid(BAT *b, BUN p)
    2061             : {
    2062    22545519 :         assert(ATOMtype(b->ttype) == TYPE_oid);
    2063             :         /* BATcount is the number of valid entries, so with
    2064             :          * exceptions, the last value can well be larger than
    2065             :          * b->tseqbase + BATcount(b) */
    2066    22545519 :         assert(p < BATcount(b));
    2067    22545519 :         assert(b->ttype == TYPE_void || b->tvheap == NULL);
    2068    22545519 :         if (is_oid_nil(b->tseqbase)) {
    2069    22011048 :                 if (b->ttype == TYPE_void)
    2070           0 :                         return oid_nil;
    2071    22011048 :                 MT_lock_set(&b->theaplock);
    2072    21704759 :                 oid o = ((const oid *) b->theap->base)[p + b->tbaseoff];
    2073    21704759 :                 MT_lock_unset(&b->theaplock);
    2074    21109265 :                 return o;
    2075             :         }
    2076      534471 :         if (b->ttype == TYPE_oid || b->tvheap == NULL) {
    2077      521239 :                 return b->tseqbase + p;
    2078             :         }
    2079             :         /* b->tvheap != NULL, so we know there will be no parallel
    2080             :          * modifications (so no locking) */
    2081       13232 :         BATiter bi = bat_iterator_nolock(b);
    2082       13232 :         return * (oid *) Tpos(&bi, p);
    2083             : }
    2084             : 
    2085             : /*
    2086             :  * @+ Transaction Management
    2087             :  */
    2088             : gdk_export gdk_return TMsubcommit_list(bat *restrict subcommit, BUN *restrict sizes, int cnt, lng logno)
    2089             :         __attribute__((__warn_unused_result__));
    2090             : 
    2091             : /*
    2092             :  * @- Delta Management
    2093             :  *  @multitable @columnfractions 0.08 0.6
    2094             :  * @item BAT *
    2095             :  * @tab BATcommit (BAT *b)
    2096             :  * @end multitable
    2097             :  *
    2098             :  * The BAT keeps track of updates with respect to a 'previous state'.
    2099             :  * Do not confuse 'previous state' with 'stable' or 'commited-on-disk',
    2100             :  * because these concepts are not always the same. In particular, they
    2101             :  * diverge when BATcommit and BATfakecommit are called explicitly,
    2102             :  * bypassing the normal global TMcommit protocol (some applications need
    2103             :  * that flexibility).
    2104             :  *
    2105             :  * BATcommit make the current BAT state the new 'stable state'.  This
    2106             :  * happens inside the global TMcommit on all persistent BATs previous
    2107             :  * to writing all bats to persistent storage using a BBPsync.
    2108             :  */
    2109             : gdk_export void BATcommit(BAT *b, BUN size);
    2110             : 
    2111             : /*
    2112             :  * @+ BAT Alignment and BAT views
    2113             :  * @multitable @columnfractions 0.08 0.7
    2114             :  * @item int
    2115             :  * @tab ALIGNsynced (BAT* b1, BAT* b2)
    2116             :  * @item int
    2117             :  * @tab ALIGNsync   (BAT *b1, BAT *b2)
    2118             :  * @item int
    2119             :  * @tab ALIGNrelated (BAT *b1, BAT *b2)
    2120             :  *
    2121             :  * @item BAT*
    2122             :  * @tab VIEWcreate   (oid seq, BAT *b, BUN lo, BUN hi)
    2123             :  * @item int
    2124             :  * @tab isVIEW   (BAT *b)
    2125             :  * @item bat
    2126             :  * @tab VIEWhparent   (BAT *b)
    2127             :  * @item bat
    2128             :  * @tab VIEWtparent   (BAT *b)
    2129             :  * @end multitable
    2130             :  *
    2131             :  * Alignments of two columns of a BAT means that the system knows
    2132             :  * whether these two columns are exactly equal. Relatedness of two
    2133             :  * BATs means that one pair of columns (either head or tail) of both
    2134             :  * BATs is aligned. The first property is checked by ALIGNsynced, the
    2135             :  * latter by ALIGNrelated.
    2136             :  *
    2137             :  * All algebraic BAT commands propagate the properties - including
    2138             :  * alignment properly on their results.
    2139             :  *
    2140             :  * VIEW BATs are BATs that lend their storage from a parent BAT.  They
    2141             :  * are just a descriptor that points to the data in this parent BAT. A
    2142             :  * view is created with VIEWcreate. The cache id of the parent (if
    2143             :  * any) is returned by VIEWtparent (otherwise it returns 0).
    2144             :  *
    2145             :  * VIEW bats are read-only!!
    2146             :  */
    2147             : gdk_export int ALIGNsynced(BAT *b1, BAT *b2);
    2148             : 
    2149             : gdk_export void BATassertProps(BAT *b);
    2150             : 
    2151             : gdk_export BAT *VIEWcreate(oid seq, BAT *b, BUN l, BUN h);
    2152             : gdk_export void VIEWbounds(BAT *b, BAT *view, BUN l, BUN h);
    2153             : 
    2154             : #define ALIGNapp(x, f, e)                                               \
    2155             :         do {                                                            \
    2156             :                 if (!(f)) {                                             \
    2157             :                         MT_lock_set(&(x)->theaplock);                    \
    2158             :                         if ((x)->batRestricted == BAT_READ ||                \
    2159             :                            ((ATOMIC_GET(&(x)->theap->refs) & HEAPREFS) > 1)) { \
    2160             :                                 GDKerror("access denied to %s, aborting.\n", BATgetId(x)); \
    2161             :                                 MT_lock_unset(&(x)->theaplock);          \
    2162             :                                 return (e);                             \
    2163             :                         }                                               \
    2164             :                         MT_lock_unset(&(x)->theaplock);                  \
    2165             :                 }                                                       \
    2166             :         } while (false)
    2167             : 
    2168             : /*
    2169             :  * @+ BAT Iterators
    2170             :  *  @multitable @columnfractions 0.15 0.7
    2171             :  * @item BATloop
    2172             :  * @tab
    2173             :  *  (BAT *b; BUN p, BUN q)
    2174             :  * @item BATloopDEL
    2175             :  * @tab
    2176             :  *  (BAT *b; BUN p; BUN q; int dummy)
    2177             :  * @item HASHloop
    2178             :  * @tab
    2179             :  *  (BAT *b; Hash *h, size_t dummy; ptr value)
    2180             :  * @item HASHloop_bte
    2181             :  * @tab
    2182             :  *  (BAT *b; Hash *h, size_t idx; bte *value, BUN w)
    2183             :  * @item HASHloop_sht
    2184             :  * @tab
    2185             :  *  (BAT *b; Hash *h, size_t idx; sht *value, BUN w)
    2186             :  * @item HASHloop_int
    2187             :  * @tab
    2188             :  *  (BAT *b; Hash *h, size_t idx; int *value, BUN w)
    2189             :  * @item HASHloop_flt
    2190             :  * @tab
    2191             :  *  (BAT *b; Hash *h, size_t idx; flt *value, BUN w)
    2192             :  * @item HASHloop_lng
    2193             :  * @tab
    2194             :  *  (BAT *b; Hash *h, size_t idx; lng *value, BUN w)
    2195             :  * @item HASHloop_hge
    2196             :  * @tab
    2197             :  *  (BAT *b; Hash *h, size_t idx; hge *value, BUN w)
    2198             :  * @item HASHloop_dbl
    2199             :  * @tab
    2200             :  *  (BAT *b; Hash *h, size_t idx; dbl *value, BUN w)
    2201             :  * @item  HASHloop_str
    2202             :  * @tab
    2203             :  *  (BAT *b; Hash *h, size_t idx; str value, BUN w)
    2204             :  * @item HASHlooploc
    2205             :  * @tab
    2206             :  *  (BAT *b; Hash *h, size_t idx; ptr value, BUN w)
    2207             :  * @item HASHloopvar
    2208             :  * @tab
    2209             :  *  (BAT *b; Hash *h, size_t idx; ptr value, BUN w)
    2210             :  * @end multitable
    2211             :  *
    2212             :  * The @emph{BATloop()} looks like a function call, but is actually a
    2213             :  * macro.
    2214             :  *
    2215             :  * @- simple sequential scan
    2216             :  * The first parameter is a BAT, the p and q are BUN pointers, where p
    2217             :  * is the iteration variable.
    2218             :  */
    2219             : #define BATloop(r, p, q)                                \
    2220             :         for (q = BATcount(r), p = 0; p < q; p++)
    2221             : 
    2222             : /*
    2223             :  * @+ Common BAT Operations
    2224             :  * Much used, but not necessarily kernel-operations on BATs.
    2225             :  *
    2226             :  * For each BAT we maintain its dimensions as separately accessible
    2227             :  * properties. They can be used to improve query processing at higher
    2228             :  * levels.
    2229             :  */
    2230             : enum prop_t {
    2231             :         GDK_MIN_BOUND, /* MINimum allowed value for range partitions [min, max> */
    2232             :         GDK_MAX_BOUND, /* MAXimum of the range partitions [min, max>, ie. excluding this max value */
    2233             :         GDK_NOT_NULL,  /* bat bound to be not null */
    2234             :         /* CURRENTLY_NO_PROPERTIES_DEFINED, */
    2235             : };
    2236             : 
    2237             : gdk_export ValPtr BATgetprop(BAT *b, enum prop_t idx);
    2238             : gdk_export ValPtr BATgetprop_nolock(BAT *b, enum prop_t idx);
    2239             : gdk_export void BATrmprop(BAT *b, enum prop_t idx);
    2240             : gdk_export void BATrmprop_nolock(BAT *b, enum prop_t idx);
    2241             : gdk_export ValPtr BATsetprop(BAT *b, enum prop_t idx, int type, const void *v);
    2242             : gdk_export ValPtr BATsetprop_nolock(BAT *b, enum prop_t idx, int type, const void *v);
    2243             : 
    2244             : /*
    2245             :  * @- BAT relational operators
    2246             :  *
    2247             :  * The full-materialization policy intermediate results in MonetDB
    2248             :  * means that a join can produce an arbitrarily large result and choke
    2249             :  * the system. The Data Distilleries tool therefore first computes the
    2250             :  * join result size before the actual join (better waste time than
    2251             :  * crash the server). To exploit that perfect result size knowledge,
    2252             :  * an result-size estimate parameter was added to all equi-join
    2253             :  * implementations.  TODO: add this for
    2254             :  * semijoin/select/unique/diff/intersect
    2255             :  *
    2256             :  * @- modes for thethajoin
    2257             :  */
    2258             : #define JOIN_EQ         0
    2259             : #define JOIN_LT         (-1)
    2260             : #define JOIN_LE         (-2)
    2261             : #define JOIN_GT         1
    2262             : #define JOIN_GE         2
    2263             : #define JOIN_BAND       3
    2264             : #define JOIN_NE         (-3)
    2265             : 
    2266             : gdk_export BAT *BATselect(BAT *b, BAT *s, const void *tl, const void *th, bool li, bool hi, bool anti);
    2267             : gdk_export BAT *BATthetaselect(BAT *b, BAT *s, const void *val, const char *op);
    2268             : 
    2269             : gdk_export BAT *BATconstant(oid hseq, int tt, const void *val, BUN cnt, role_t role);
    2270             : gdk_export gdk_return BATsubcross(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, bool max_one)
    2271             :         __attribute__((__warn_unused_result__));
    2272             : gdk_export gdk_return BAToutercross(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, bool max_one)
    2273             :         __attribute__((__warn_unused_result__));
    2274             : 
    2275             : gdk_export gdk_return BATleftjoin(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, bool nil_matches, BUN estimate)
    2276             :         __attribute__((__warn_unused_result__));
    2277             : gdk_export gdk_return BATmarkjoin(BAT **r1p, BAT **r2p, BAT **r3p, BAT *l, BAT *r, BAT *sl, BAT *sr, BUN estimate)
    2278             :         __attribute__((__warn_unused_result__));
    2279             : gdk_export gdk_return BATouterjoin(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, bool nil_matches, bool match_one, BUN estimate)
    2280             :         __attribute__((__warn_unused_result__));
    2281             : gdk_export gdk_return BATthetajoin(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, int op, bool nil_matches, BUN estimate)
    2282             :         __attribute__((__warn_unused_result__));
    2283             : gdk_export gdk_return BATsemijoin(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, bool nil_matches, bool max_one, BUN estimate)
    2284             :         __attribute__((__warn_unused_result__));
    2285             : gdk_export BAT *BATintersect(BAT *l, BAT *r, BAT *sl, BAT *sr, bool nil_matches, bool max_one, BUN estimate);
    2286             : gdk_export BAT *BATdiff(BAT *l, BAT *r, BAT *sl, BAT *sr, bool nil_matches, bool not_in, BUN estimate);
    2287             : gdk_export gdk_return BATjoin(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, bool nil_matches, BUN estimate)
    2288             :         __attribute__((__warn_unused_result__));
    2289             : gdk_export BUN BATguess_uniques(BAT *b, struct canditer *ci);
    2290             : gdk_export gdk_return BATbandjoin(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, const void *c1, const void *c2, bool li, bool hi, BUN estimate)
    2291             :         __attribute__((__warn_unused_result__));
    2292             : gdk_export gdk_return BATrangejoin(BAT **r1p, BAT **r2p, BAT *l, BAT *rl, BAT *rh, BAT *sl, BAT *sr, bool li, bool hi, bool anti, bool symmetric, BUN estimate)
    2293             :         __attribute__((__warn_unused_result__));
    2294             : gdk_export BAT *BATproject(BAT *restrict l, BAT *restrict r);
    2295             : gdk_export BAT *BATproject2(BAT *restrict l, BAT *restrict r1, BAT *restrict r2);
    2296             : gdk_export BAT *BATprojectchain(BAT **bats);
    2297             : 
    2298             : gdk_export BAT *BATslice(BAT *b, BUN low, BUN high);
    2299             : 
    2300             : gdk_export BAT *BATunique(BAT *b, BAT *s);
    2301             : 
    2302             : gdk_export gdk_return BATfirstn(BAT **topn, BAT **gids, BAT *b, BAT *cands, BAT *grps, BUN n, bool asc, bool nilslast, bool distinct)
    2303             :         __attribute__((__warn_unused_result__));
    2304             : 
    2305             : #include "gdk_calc.h"
    2306             : 
    2307             : gdk_export gdk_return GDKtoupper(char **restrict buf, size_t *restrict buflen, const char *restrict s);
    2308             : gdk_export gdk_return GDKtolower(char **restrict buf, size_t *restrict buflen, const char *restrict s);
    2309             : gdk_export gdk_return GDKcasefold(char **restrict buf, size_t *restrict buflen, const char *restrict s);
    2310             : gdk_export int GDKstrncasecmp(const char *str1, const char *str2, size_t l1, size_t l2);
    2311             : gdk_export int GDKstrcasecmp(const char *s1, const char *s2);
    2312             : gdk_export char *GDKstrcasestr(const char *haystack, const char *needle);
    2313             : gdk_export BAT *BATtoupper(BAT *b, BAT *s);
    2314             : gdk_export BAT *BATtolower(BAT *b, BAT *s);
    2315             : gdk_export BAT *BATcasefold(BAT *b, BAT *s);
    2316             : gdk_export gdk_return GDKasciify(char **restrict buf, size_t *restrict buflen, const char *restrict s);
    2317             : gdk_export BAT *BATasciify(BAT *b, BAT *s);
    2318             : 
    2319             : /*
    2320             :  * @- BAT sample operators
    2321             :  *
    2322             :  * @multitable @columnfractions 0.08 0.7
    2323             :  * @item BAT *
    2324             :  * @tab BATsample (BAT *b, n)
    2325             :  * @end multitable
    2326             :  *
    2327             :  * The routine BATsample returns a random sample on n BUNs of a BAT.
    2328             :  *
    2329             :  */
    2330             : gdk_export BAT *BATsample(BAT *b, BUN n);
    2331             : gdk_export BAT *BATsample_with_seed(BAT *b, BUN n, uint64_t seed);
    2332             : 
    2333             : /*
    2334             :  *
    2335             :  */
    2336             : #define MAXPARAMS       32
    2337             : 
    2338             : #define CHECK_QRY_TIMEOUT_SHIFT 14
    2339             : #define CHECK_QRY_TIMEOUT_STEP  (1 << CHECK_QRY_TIMEOUT_SHIFT)
    2340             : #define CHECK_QRY_TIMEOUT_MASK  (CHECK_QRY_TIMEOUT_STEP - 1)
    2341             : 
    2342             : #define TIMEOUT_MSG "Timeout was reached!"
    2343             : #define INTERRUPT_MSG "Query interrupted!"
    2344             : #define DISCONNECT_MSG "Client is disconnected!"
    2345             : #define EXITING_MSG "Server is exiting!"
    2346             : 
    2347             : #define QRY_TIMEOUT (-1)        /* query timed out */
    2348             : #define QRY_INTERRUPT (-2)      /* client indicated interrupt */
    2349             : #define QRY_DISCONNECT (-3)     /* client disconnected */
    2350             : 
    2351             : static const char *
    2352           3 : TIMEOUT_MESSAGE(QryCtx *qc)
    2353             : {
    2354           3 :         if (GDKexiting())
    2355             :                 return EXITING_MSG;
    2356           3 :         if (qc) {
    2357           3 :                 switch (qc->endtime) {
    2358             :                 case QRY_TIMEOUT:
    2359             :                         return TIMEOUT_MSG;
    2360           0 :                 case QRY_INTERRUPT:
    2361           0 :                         return INTERRUPT_MSG;
    2362           0 :                 case QRY_DISCONNECT:
    2363           0 :                         return DISCONNECT_MSG;
    2364             :                 default:
    2365           0 :                         MT_UNREACHABLE();
    2366             :                 }
    2367             :         }
    2368             :         return NULL;
    2369             : }
    2370             : 
    2371             : static inline void
    2372           3 : TIMEOUT_ERROR(QryCtx *qc, const char *file, const char *func, int lineno)
    2373             : {
    2374           3 :         const char *e = TIMEOUT_MESSAGE(qc);
    2375           3 :         if (e) {
    2376           3 :                 GDKtracer_log(file, func, lineno, M_ERROR, GDK, NULL,
    2377             :                               "%s\n", e);
    2378             :         }
    2379           3 : }
    2380             : 
    2381             : #define TIMEOUT_HANDLER(rtpe, qc)                                       \
    2382             :         do {                                                            \
    2383             :                 TIMEOUT_ERROR(qc, __FILE__, __func__, __LINE__);        \
    2384             :                 return rtpe;                                            \
    2385             :         } while(0)
    2386             : 
    2387             : static inline bool
    2388     9738215 : TIMEOUT_TEST(QryCtx *qc)
    2389             : {
    2390     9738215 :         if (qc == NULL)
    2391             :                 return false;
    2392     9738713 :         if (qc->endtime < 0)
    2393             :                 return true;
    2394     9738710 :         if (qc->endtime && GDKusec() > qc->endtime) {
    2395           3 :                 qc->endtime = QRY_TIMEOUT;
    2396           3 :                 return true;
    2397             :         }
    2398     9738707 :         switch (bstream_getoob(qc->bs)) {
    2399           0 :         case -1:
    2400           0 :                 qc->endtime = QRY_DISCONNECT;
    2401           0 :                 return true;
    2402             :         case 0:
    2403             :                 return false;
    2404           0 :         default:
    2405           0 :                 qc->endtime = QRY_INTERRUPT;
    2406           0 :                 return true;
    2407             :         }
    2408             : }
    2409             : 
    2410             : #define GOTO_LABEL_TIMEOUT_HANDLER(label, qc)                           \
    2411             :         do {                                                            \
    2412             :                 TIMEOUT_ERROR(qc, __FILE__, __func__, __LINE__);        \
    2413             :                 goto label;                                             \
    2414             :         } while(0)
    2415             : 
    2416             : #define GDK_CHECK_TIMEOUT_BODY(qc, callback)            \
    2417             :         do {                                            \
    2418             :                 if (GDKexiting() || TIMEOUT_TEST(qc)) { \
    2419             :                         callback;                       \
    2420             :                 }                                       \
    2421             :         } while (0)
    2422             : 
    2423             : #define GDK_CHECK_TIMEOUT(qc, counter, callback)                \
    2424             :         do {                                                    \
    2425             :                 if (counter > CHECK_QRY_TIMEOUT_STEP) {              \
    2426             :                         GDK_CHECK_TIMEOUT_BODY(qc, callback);   \
    2427             :                         counter = 0;                            \
    2428             :                 } else {                                        \
    2429             :                         counter++;                              \
    2430             :                 }                                               \
    2431             :         } while (0)
    2432             : 
    2433             : /* here are some useful constructs to iterate a number of times (the
    2434             :  * REPEATS argument--only evaluated once) and checking for a timeout
    2435             :  * every once in a while; the QC->endtime value is a variable of type lng
    2436             :  * which is either 0 or the GDKusec() compatible time after which the
    2437             :  * loop should terminate; check for this condition after the loop using
    2438             :  * the TIMEOUT_CHECK macro; in order to break out of any of these loops,
    2439             :  * use TIMEOUT_LOOP_BREAK since plain break won't do it; it is perfectly
    2440             :  * ok to use continue inside the body */
    2441             : 
    2442             : /* use IDX as a loop variable (already declared), initializing it to 0
    2443             :  * and incrementing it on each iteration */
    2444             : #define TIMEOUT_LOOP_IDX(IDX, REPEATS, QC)                              \
    2445             :         for (BUN REPS = (IDX = 0, (REPEATS)); REPS > 0; REPS = 0) /* "loops" at most once */ \
    2446             :                 for (BUN CTR1 = 0, END1 = (REPS + CHECK_QRY_TIMEOUT_STEP) >> CHECK_QRY_TIMEOUT_SHIFT; CTR1 < END1 && !GDKexiting() && ((QC) == NULL || (QC)->endtime >= 0); CTR1++) \
    2447             :                         if (CTR1 > 0 && TIMEOUT_TEST(QC)) {          \
    2448             :                                 break;                                  \
    2449             :                         } else                                          \
    2450             :                                 for (BUN CTR2 = 0, END2 = CTR1 == END1 - 1 ? REPS & CHECK_QRY_TIMEOUT_MASK : CHECK_QRY_TIMEOUT_STEP; CTR2 < END2; CTR2++, IDX++)
    2451             : 
    2452             : /* declare and use IDX as a loop variable, initializing it to 0 and
    2453             :  * incrementing it on each iteration */
    2454             : #define TIMEOUT_LOOP_IDX_DECL(IDX, REPEATS, QC)                         \
    2455             :         for (BUN IDX = 0, REPS = (REPEATS); REPS > 0; REPS = 0) /* "loops" at most once */ \
    2456             :                 for (BUN CTR1 = 0, END1 = (REPS + CHECK_QRY_TIMEOUT_STEP) >> CHECK_QRY_TIMEOUT_SHIFT; CTR1 < END1 && !GDKexiting() && ((QC) == NULL || (QC)->endtime >= 0); CTR1++) \
    2457             :                         if (CTR1 > 0 && TIMEOUT_TEST(QC)) {          \
    2458             :                                 break;                                  \
    2459             :                         } else                                          \
    2460             :                                 for (BUN CTR2 = 0, END2 = CTR1 == END1 - 1 ? REPS & CHECK_QRY_TIMEOUT_MASK : CHECK_QRY_TIMEOUT_STEP; CTR2 < END2; CTR2++, IDX++)
    2461             : 
    2462             : /* there is no user-visible loop variable */
    2463             : #define TIMEOUT_LOOP(REPEATS, QC)                                       \
    2464             :         for (BUN CTR1 = 0, REPS = (REPEATS), END1 = (REPS + CHECK_QRY_TIMEOUT_STEP) >> CHECK_QRY_TIMEOUT_SHIFT; CTR1 < END1 && !GDKexiting() && ((QC) == NULL || (QC)->endtime >= 0); CTR1++) \
    2465             :                 if (CTR1 > 0 && TIMEOUT_TEST(QC)) {                  \
    2466             :                         break;                                          \
    2467             :                 } else                                                  \
    2468             :                         for (BUN CTR2 = 0, END2 = CTR1 == END1 - 1 ? REPS & CHECK_QRY_TIMEOUT_MASK : CHECK_QRY_TIMEOUT_STEP; CTR2 < END2; CTR2++)
    2469             : 
    2470             : /* break out of the loop (cannot use do/while trick here) */
    2471             : #define TIMEOUT_LOOP_BREAK                      \
    2472             :         {                                       \
    2473             :                 END1 = END2 = 0;                \
    2474             :                 continue;                       \
    2475             :         }
    2476             : 
    2477             : /* check whether a timeout occurred, and execute the CALLBACK argument
    2478             :  * if it did */
    2479             : #define TIMEOUT_CHECK(QC, CALLBACK)                                     \
    2480             :         do {                                                            \
    2481             :                 if (GDKexiting() || ((QC) && (QC)->endtime < 0))  \
    2482             :                         CALLBACK;                                       \
    2483             :         } while (0)
    2484             : 
    2485             : typedef struct gdk_callback {
    2486             :         char *name;
    2487             :         int argc;
    2488             :         int interval;  // units sec
    2489             :         lng last_called; // timestamp GDKusec
    2490             :         gdk_return (*func)(int argc, void *argv[]);
    2491             :         struct gdk_callback *next;
    2492             :         void *argv[];
    2493             : } gdk_callback;
    2494             : 
    2495             : typedef gdk_return gdk_callback_func(int argc, void *argv[]);
    2496             : 
    2497             : gdk_export gdk_return gdk_add_callback(char *name, gdk_callback_func *f, int argc, void
    2498             :                 *argv[], int interval);
    2499             : gdk_export gdk_return gdk_remove_callback(char *, gdk_callback_func *f);
    2500             : 
    2501             : 
    2502             : #include <setjmp.h>
    2503             : 
    2504             : typedef struct exception_buffer {
    2505             : #ifdef HAVE_SIGLONGJMP
    2506             :         sigjmp_buf state;
    2507             : #else
    2508             :         jmp_buf state;
    2509             : #endif
    2510             :         int code;
    2511             :         char *msg;
    2512             :         int enabled;
    2513             : } exception_buffer;
    2514             : 
    2515             : gdk_export exception_buffer *eb_init(exception_buffer *eb);
    2516             : 
    2517             : /* != 0 on when we return to the savepoint */
    2518             : #ifdef HAVE_SIGLONGJMP
    2519             : #define eb_savepoint(eb) ((eb)->enabled = 1, sigsetjmp((eb)->state, 0))
    2520             : #else
    2521             : #define eb_savepoint(eb) ((eb)->enabled = 1, setjmp((eb)->state))
    2522             : #endif
    2523             : gdk_export _Noreturn void eb_error(exception_buffer *eb, char *msg, int val);
    2524             : 
    2525             : typedef struct allocator {
    2526             :         struct allocator *pa;
    2527             :         size_t size;
    2528             :         size_t nr;
    2529             :         char **blks;
    2530             :         size_t used;    /* memory used in last block */
    2531             :         size_t usedmem; /* used memory */
    2532             :         void *freelist; /* list of freed blocks */
    2533             :         exception_buffer eb;
    2534             : } allocator;
    2535             : 
    2536             : gdk_export allocator *sa_create( allocator *pa );
    2537             : gdk_export allocator *sa_reset( allocator *sa );
    2538             : gdk_export void *sa_alloc( allocator *sa,  size_t sz );
    2539             : gdk_export void *sa_zalloc( allocator *sa,  size_t sz );
    2540             : gdk_export void *sa_realloc( allocator *sa,  void *ptr, size_t sz, size_t osz );
    2541             : gdk_export void sa_destroy( allocator *sa );
    2542             : gdk_export char *sa_strndup( allocator *sa, const char *s, size_t l);
    2543             : gdk_export char *sa_strdup( allocator *sa, const char *s);
    2544             : gdk_export char *sa_strconcat( allocator *sa, const char *s1, const char *s2);
    2545             : gdk_export size_t sa_size( allocator *sa );
    2546             : 
    2547             : #if !defined(NDEBUG) && !defined(__COVERITY__) && defined(__GNUC__)
    2548             : #define sa_alloc(sa, sz)                                        \
    2549             :         ({                                                      \
    2550             :                 allocator *_sa = (sa);                          \
    2551             :                 size_t _sz = (sz);                              \
    2552             :                 void *_res = sa_alloc(_sa, _sz);                \
    2553             :                 TRC_DEBUG(ALLOC,                                \
    2554             :                                 "sa_alloc(%p,%zu) -> %p\n",        \
    2555             :                                 _sa, _sz, _res);                \
    2556             :                 _res;                                           \
    2557             :         })
    2558             : #define sa_zalloc(sa, sz)                                       \
    2559             :         ({                                                      \
    2560             :                 allocator *_sa = (sa);                          \
    2561             :                 size_t _sz = (sz);                              \
    2562             :                 void *_res = sa_zalloc(_sa, _sz);               \
    2563             :                 TRC_DEBUG(ALLOC,                                \
    2564             :                                 "sa_zalloc(%p,%zu) -> %p\n",       \
    2565             :                                 _sa, _sz, _res);                \
    2566             :                 _res;                                           \
    2567             :         })
    2568             : #define sa_realloc(sa, ptr, sz, osz)                                    \
    2569             :         ({                                                              \
    2570             :                 allocator *_sa = (sa);                                  \
    2571             :                 void *_ptr = (ptr);                                     \
    2572             :                 size_t _sz = (sz);                                      \
    2573             :                 size_t _osz = (osz);                                    \
    2574             :                 void *_res = sa_realloc(_sa, _ptr, _sz, _osz);          \
    2575             :                 TRC_DEBUG(ALLOC,                                        \
    2576             :                                 "sa_realloc(%p,%p,%zu,%zu) -> %p\n",       \
    2577             :                                 _sa, _ptr, _sz, _osz, _res);            \
    2578             :                 _res;                                                   \
    2579             :         })
    2580             : #define sa_strdup(sa, s)                                                \
    2581             :         ({                                                              \
    2582             :                 allocator *_sa = (sa);                                  \
    2583             :                 const char *_s = (s);                                   \
    2584             :                 char *_res = sa_strdup(_sa, _s);                        \
    2585             :                 TRC_DEBUG(ALLOC,                                        \
    2586             :                                 "sa_strdup(%p,len=%zu) -> %p\n",   \
    2587             :                                 _sa, strlen(_s), _res);                 \
    2588             :                 _res;                                                   \
    2589             :         })
    2590             : #define sa_strndup(sa, s, l)                                            \
    2591             :         ({                                                              \
    2592             :                 allocator *_sa = (sa);                                  \
    2593             :                 const char *_s = (s);                                   \
    2594             :                 size_t _l = (l);                                        \
    2595             :                 char *_res = sa_strndup(_sa, _s, _l);                   \
    2596             :                 TRC_DEBUG(ALLOC,                                        \
    2597             :                                 "sa_strndup(%p,len=%zu) -> %p\n",  \
    2598             :                                 _sa, _l, _res);                         \
    2599             :                 _res;                                                   \
    2600             :         })
    2601             : #endif
    2602             : 
    2603             : #endif /* _GDK_H_ */

Generated by: LCOV version 1.14