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-04 20:04:04 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 Strimps Strimps;
     569             : 
     570             : #ifdef HAVE_RTREE
     571             : typedef struct RTree RTree;
     572             : #endif
     573             : 
     574             : /*
     575             :  * @+ Binary Association Tables
     576             :  * Having gone to the previous preliminary definitions, we will now
     577             :  * introduce the structure of Binary Association Tables (BATs) in
     578             :  * detail. They are the basic storage unit on which GDK is modeled.
     579             :  *
     580             :  * The BAT holds an unlimited number of binary associations, called
     581             :  * BUNs (@strong{Binary UNits}).  The two attributes of a BUN are
     582             :  * called @strong{head} (left) and @strong{tail} (right) in the
     583             :  * remainder of this document.
     584             :  *
     585             :  *  @c image{http://monetdb.cwi.nl/projects/monetdb-mk/imgs/bat1,,,,feps}
     586             :  *
     587             :  * The above figure shows what a BAT looks like. It consists of two
     588             :  * columns, called head and tail, such that we have always binary
     589             :  * tuples (BUNs). The overlooking structure is the @strong{BAT
     590             :  * record}.  It points to a heap structure called the @strong{BUN
     591             :  * heap}.  This heap contains the atomic values inside the two
     592             :  * columns. If they are fixed-sized atoms, these atoms reside directly
     593             :  * in the BUN heap. If they are variable-sized atoms (such as string
     594             :  * or polygon), however, the columns has an extra heap for storing
     595             :  * those (such @strong{variable-sized atom heaps} are then referred to
     596             :  * as @strong{Head Heap}s and @strong{Tail Heap}s). The BUN heap then
     597             :  * contains integer byte-offsets (fixed-sized, of course) into a head-
     598             :  * or tail-heap.
     599             :  *
     600             :  * The BUN heap contains a contiguous range of BUNs. It starts after
     601             :  * the @strong{first} pointer, and finishes at the end in the
     602             :  * @strong{free} area of the BUN. All BUNs after the @strong{inserted}
     603             :  * pointer have been added in the last transaction (and will be
     604             :  * deleted on a transaction abort). All BUNs between the
     605             :  * @strong{deleted} pointer and the @strong{first} have been deleted
     606             :  * in this transaction (and will be reinserted at a transaction
     607             :  * abort).
     608             :  *
     609             :  * The location of a certain BUN in a BAT may change between
     610             :  * successive library routine invocations.  Therefore, one should
     611             :  * avoid keeping references into the BAT storage area for long
     612             :  * periods.
     613             :  *
     614             :  * Passing values between the library routines and the enclosing C
     615             :  * program is primarily through value pointers of type ptr. Pointers
     616             :  * into the BAT storage area should only be used for retrieval. Direct
     617             :  * updates of data stored in a BAT is forbidden. The user should
     618             :  * adhere to the interface conventions to guarantee the integrity
     619             :  * rules and to maintain the (hidden) auxiliary search structures.
     620             :  *
     621             :  * @- GDK variant record type
     622             :  * When manipulating values, MonetDB puts them into value records.
     623             :  * The built-in types have a direct entry in the union. Others should
     624             :  * be represented as a pointer of memory in pval or as a string, which
     625             :  * is basically the same. In such cases the len field indicates the
     626             :  * size of this piece of memory.
     627             :  */
     628             : typedef struct {
     629             :         union {                 /* storage is first in the record */
     630             :                 int ival;
     631             :                 oid oval;
     632             :                 sht shval;
     633             :                 bte btval;
     634             :                 msk mval;
     635             :                 flt fval;
     636             :                 ptr pval;
     637             :                 bat bval;
     638             :                 str sval;
     639             :                 dbl dval;
     640             :                 lng lval;
     641             : #ifdef HAVE_HGE
     642             :                 hge hval;
     643             : #endif
     644             :                 uuid uval;
     645             :         } val;
     646             :         size_t len;
     647             :         short vtype;
     648             :         bool bat;
     649             : } *ValPtr, ValRecord;
     650             : 
     651             : /* interface definitions */
     652             : gdk_export void *VALconvert(int typ, ValPtr t);
     653             : gdk_export char *VALformat(const ValRecord *res)
     654             :         __attribute__((__warn_unused_result__));
     655             : gdk_export ValPtr VALcopy(ValPtr dst, const ValRecord *src);
     656             : gdk_export ValPtr VALinit(ValPtr d, int tpe, const void *s);
     657             : gdk_export void VALempty(ValPtr v);
     658             : gdk_export void VALclear(ValPtr v);
     659             : gdk_export ValPtr VALset(ValPtr v, int t, void *p);
     660             : gdk_export void *VALget(ValPtr v);
     661             : gdk_export int VALcmp(const ValRecord *p, const ValRecord *q);
     662             : gdk_export bool VALisnil(const ValRecord *v);
     663             : 
     664             : /*
     665             :  * @- The BAT record
     666             :  * The elements of the BAT structure are introduced in the remainder.
     667             :  * Instead of using the underlying types hidden beneath it, one should
     668             :  * use a @emph{BAT} type that is supposed to look like this:
     669             :  * @verbatim
     670             :  * typedef struct {
     671             :  *           // static BAT properties
     672             :  *           bat    batCacheid;       // bat id: index in BBPcache
     673             :  *           bool   batTransient;     // persistence mode
     674             :  *           bool   batCopiedtodisk;  // BAT is saved on disk?
     675             :  *           // dynamic BAT properties
     676             :  *           int    batHeat;          // heat of BAT in the BBP
     677             :  *           Heap*  batBuns;          // Heap where the buns are stored
     678             :  *           // DELTA status
     679             :  *           BUN    batInserted;      // first inserted BUN
     680             :  *           BUN    batCount;         // Tuple count
     681             :  *           // Tail properties
     682             :  *           int    ttype;            // Tail type number
     683             :  *           bool   tkey;             // tail values are unique
     684             :  *           bool   tnonil;           // tail has no nils
     685             :  *           bool   tsorted;          // are tail values currently ordered?
     686             :  *           // Tail storage
     687             :  *           int    tloc;             // byte-offset in BUN for tail elements
     688             :  *           Heap   *theap;           // heap for varsized tail values
     689             :  *           Hash   *thash;           // linear chained hash table on tail
     690             :  *           orderidx torderidx;      // order oid index on tail
     691             :  *  } BAT;
     692             :  * @end verbatim
     693             :  *
     694             :  * The internal structure of the @strong{BAT} record is in fact much
     695             :  * more complex, but GDK programmers should refrain of making use of
     696             :  * that.
     697             :  *
     698             :  * Since we don't want to pay cost to keep both views in line with
     699             :  * each other under BAT updates, we work with shared pieces of memory
     700             :  * between the two views. An update to one will thus automatically
     701             :  * update the other.  In the same line, we allow @strong{synchronized
     702             :  * BATs} (BATs with identical head columns, and marked as such in the
     703             :  * @strong{BAT Alignment} interface) now to be clustered horizontally.
     704             :  *
     705             :  *  @c image{http://monetdb.cwi.nl/projects/monetdb-mk/imgs/bat2,,,,feps}
     706             :  */
     707             : 
     708             : typedef struct PROPrec PROPrec;
     709             : 
     710             : /* see also comment near BATassertProps() for more information about
     711             :  * the properties */
     712             : typedef struct {
     713             :         uint16_t width;         /* byte-width of the atom array */
     714             :         int8_t type;            /* type id. */
     715             :         uint8_t shift;          /* log2 of bun width */
     716             :         bool key:1,             /* no duplicate values present */
     717             :                 nonil:1,        /* there are no nils in the column */
     718             :                 nil:1,          /* there is a nil in the column */
     719             :                 sorted:1,       /* column is sorted in ascending order */
     720             :                 revsorted:1,    /* column is sorted in descending order */
     721             :                 ascii:1;        /* string column is fully ASCII (7 bit) */
     722             :         BUN nokey[2];           /* positions that prove key==FALSE */
     723             :         BUN nosorted;           /* position that proves sorted==FALSE */
     724             :         BUN norevsorted;        /* position that proves revsorted==FALSE */
     725             :         BUN minpos, maxpos;     /* location of min/max value */
     726             :         double unique_est;      /* estimated number of unique values */
     727             :         oid seq;                /* start of dense sequence */
     728             : 
     729             :         Heap *heap;             /* space for the column. */
     730             :         BUN baseoff;            /* offset in heap->base (in whole items) */
     731             :         Heap *vheap;            /* space for the varsized data. */
     732             :         Hash *hash;             /* hash table */
     733             : #ifdef HAVE_RTREE
     734             :         RTree *rtree;           /* rtree geometric index */
     735             : #endif
     736             :         Heap *orderidx;         /* order oid index */
     737             :         Strimps *strimps;       /* string imprint index  */
     738             : 
     739             :         PROPrec *props;         /* list of dynamic properties stored in the bat descriptor */
     740             : } COLrec;
     741             : 
     742             : #define ORDERIDXOFF             3
     743             : 
     744             : /* assert that atom width is power of 2, i.e., width == 1<<shift */
     745             : #define assert_shift_width(shift,width) assert(((shift) == 0 && (width) == 0) || ((unsigned)1<<(shift)) == (unsigned)(width))
     746             : 
     747             : #define GDKLIBRARY_HASHASH      061044U /* first in Jul2021: hashash bit in string heaps */
     748             : #define GDKLIBRARY_HSIZE        061045U /* first in Jan2022: heap "size" values */
     749             : #define GDKLIBRARY_JSON         061046U /* first in Sep2022: json storage changes*/
     750             : #define GDKLIBRARY_STATUS       061047U /* first in Dec2023: no status/filename columns */
     751             : #define GDKLIBRARY              061050U /* first in Aug2024 */
     752             : 
     753             : /* The batRestricted field indicates whether a BAT is readonly.
     754             :  * we have modes: BAT_WRITE  = all permitted
     755             :  *                BAT_APPEND = append-only
     756             :  *                BAT_READ   = read-only
     757             :  * VIEW bats are always mapped read-only.
     758             :  */
     759             : typedef enum {
     760             :         BAT_WRITE,                /* all kinds of access allowed */
     761             :         BAT_READ,                 /* only read-access allowed */
     762             :         BAT_APPEND,               /* only reads and appends allowed */
     763             : } restrict_t;
     764             : 
     765             : /* theaplock: this lock should be held when reading or writing any of
     766             :  * the fields that are saved in the BBP.dir file (plus any, if any, that
     767             :  * share bitfields with any of the fields), i.e. hseqbase,
     768             :  * batRestricted, batTransient, batCount, and the theap properties tkey,
     769             :  * tseqbase, tsorted, trevsorted, twidth, tshift, tnonil, tnil, tnokey,
     770             :  * tnosorted, tnorevsorted, tminpos, tmaxpos, and tunique_est, also when
     771             :  * BBP_logical(bid) is changed, and also when reading or writing any of
     772             :  * the following fields: theap, tvheap, batInserted, batCapacity.  There
     773             :  * is no need for the lock if the bat cannot possibly be modified
     774             :  * concurrently, e.g. when it is new and not yet returned to the
     775             :  * interpreter or during system initialization.
     776             :  * If multiple bats need to be locked at the same time by the same
     777             :  * thread, first lock the view, then the view's parent(s). */
     778             : typedef struct BAT {
     779             :         /* static bat properties */
     780             :         oid hseqbase;           /* head seq base */
     781             :         MT_Id creator_tid;      /* which thread created it */
     782             :         bat batCacheid;         /* index into BBP */
     783             :         role_t batRole;         /* role of the bat */
     784             : 
     785             :         /* dynamic bat properties */
     786             :         restrict_t batRestricted:2; /* access privileges */
     787             :         bool
     788             :          batTransient:1,        /* should the BAT persist on disk? */
     789             :          batCopiedtodisk:1;     /* once written */
     790             :         uint16_t selcnt;        /* how often used in equi select without hash */
     791             :         uint16_t unused;        /* value=0 for now (sneakily used by mat.c) */
     792             : 
     793             :         /* delta status administration */
     794             :         BUN batInserted;        /* start of inserted elements */
     795             :         BUN batCount;           /* tuple count */
     796             :         BUN batCapacity;        /* tuple capacity */
     797             : 
     798             :         /* dynamic column properties */
     799             :         COLrec T;               /* column info */
     800             :         MT_Lock theaplock;      /* lock protecting heap reference changes */
     801             :         MT_RWLock thashlock;    /* lock specifically for hash management */
     802             :         MT_Lock batIdxLock;     /* lock to manipulate other indexes/properties */
     803             :         Heap *oldtail;          /* old tail heap, to be destroyed after commit */
     804             : } BAT;
     805             : 
     806             : /* macros to hide complexity of the BAT structure */
     807             : #define ttype           T.type
     808             : #define tkey            T.key
     809             : #define tseqbase        T.seq
     810             : #define tsorted         T.sorted
     811             : #define trevsorted      T.revsorted
     812             : #define tascii          T.ascii
     813             : #define torderidx       T.orderidx
     814             : #define twidth          T.width
     815             : #define tshift          T.shift
     816             : #define tnonil          T.nonil
     817             : #define tnil            T.nil
     818             : #define tnokey          T.nokey
     819             : #define tnosorted       T.nosorted
     820             : #define tnorevsorted    T.norevsorted
     821             : #define tminpos         T.minpos
     822             : #define tmaxpos         T.maxpos
     823             : #define tunique_est     T.unique_est
     824             : #define theap           T.heap
     825             : #define tbaseoff        T.baseoff
     826             : #define tvheap          T.vheap
     827             : #define thash           T.hash
     828             : #define tprops          T.props
     829             : #define tstrimps        T.strimps
     830             : #ifdef HAVE_RTREE
     831             : #define trtree          T.rtree
     832             : #endif
     833             : 
     834             : /* some access functions for the bitmask type */
     835             : static inline void
     836         134 : mskSet(BAT *b, BUN p)
     837             : {
     838         134 :         ((uint32_t *) b->theap->base)[p / 32] |= 1U << (p % 32);
     839         134 : }
     840             : 
     841             : static inline void
     842        7857 : mskClr(BAT *b, BUN p)
     843             : {
     844        7857 :         ((uint32_t *) b->theap->base)[p / 32] &= ~(1U << (p % 32));
     845        7857 : }
     846             : 
     847             : static inline void
     848        7991 : mskSetVal(BAT *b, BUN p, msk v)
     849             : {
     850        7991 :         if (v)
     851         134 :                 mskSet(b, p);
     852             :         else
     853        7857 :                 mskClr(b, p);
     854        7991 : }
     855             : 
     856             : static inline msk
     857           0 : mskGetVal(BAT *b, BUN p)
     858             : {
     859           0 :         return ((uint32_t *) b->theap->base)[p / 32] & (1U << (p % 32));
     860             : }
     861             : 
     862             : /*
     863             :  * @- Heap Management
     864             :  * Heaps are the low-level entities of mass storage in
     865             :  * BATs. Currently, they can either be stored on disk, loaded into
     866             :  * memory, or memory mapped.
     867             :  * @multitable @columnfractions 0.08 0.7
     868             :  * @item int
     869             :  * @tab
     870             :  *  HEAPalloc (Heap *h, size_t nitems, size_t itemsize);
     871             :  * @item int
     872             :  * @tab
     873             :  *  HEAPfree (Heap *h, bool remove);
     874             :  * @item int
     875             :  * @tab
     876             :  *  HEAPextend (Heap *h, size_t size, bool mayshare);
     877             :  * @item int
     878             :  * @tab
     879             :  *  HEAPload (Heap *h, str nme,ext, bool trunc);
     880             :  * @item int
     881             :  * @tab
     882             :  *  HEAPsave (Heap *h, str nme,ext, bool dosync);
     883             :  * @item int
     884             :  * @tab
     885             :  *  HEAPcopy (Heap *dst,*src);
     886             :  * @end multitable
     887             :  *
     888             :  *
     889             :  * These routines should be used to alloc free or extend heaps; they
     890             :  * isolate you from the different ways heaps can be accessed.
     891             :  */
     892             : gdk_export gdk_return HEAPextend(Heap *h, size_t size, bool mayshare)
     893             :         __attribute__((__warn_unused_result__));
     894             : gdk_export size_t HEAPvmsize(Heap *h);
     895             : gdk_export size_t HEAPmemsize(Heap *h);
     896             : gdk_export void HEAPdecref(Heap *h, bool remove);
     897             : gdk_export void HEAPincref(Heap *h);
     898             : 
     899             : #define VIEWtparent(x)  ((x)->theap == NULL || (x)->theap->parentid == (x)->batCacheid ? 0 : (x)->theap->parentid)
     900             : #define VIEWvtparent(x) ((x)->tvheap == NULL || (x)->tvheap->parentid == (x)->batCacheid ? 0 : (x)->tvheap->parentid)
     901             : 
     902             : #define isVIEW(x)       (VIEWtparent(x) != 0 || VIEWvtparent(x) != 0)
     903             : 
     904             : /*
     905             :  * @+ BAT Buffer Pool
     906             :  * @multitable @columnfractions 0.08 0.7
     907             :  * @item int
     908             :  * @tab BBPfix (bat bi)
     909             :  * @item int
     910             :  * @tab BBPunfix (bat bi)
     911             :  * @item int
     912             :  * @tab BBPretain (bat bi)
     913             :  * @item int
     914             :  * @tab BBPrelease (bat bi)
     915             :  * @item bat
     916             :  * @tab BBPindex  (str nme)
     917             :  * @item BAT*
     918             :  * @tab BATdescriptor (bat bi)
     919             :  * @end multitable
     920             :  *
     921             :  * The BAT Buffer Pool module contains the code to manage the storage
     922             :  * location of BATs.
     923             :  *
     924             :  * The remaining BBP tables contain status information to load, swap
     925             :  * and migrate the BATs. The core table is BBPcache which contains a
     926             :  * pointer to the BAT descriptor with its heaps.  A zero entry means
     927             :  * that the file resides on disk. Otherwise it has been read or mapped
     928             :  * into memory.
     929             :  *
     930             :  * BATs loaded into memory are retained in a BAT buffer pool.  They
     931             :  * retain their position within the cache during their life cycle,
     932             :  * which make indexing BATs a stable operation.
     933             :  *
     934             :  * The BBPindex routine checks if a BAT with a certain name is
     935             :  * registered in the buffer pools. If so, it returns its BAT id.  The
     936             :  * BATdescriptor routine has a BAT id parameter, and returns a pointer
     937             :  * to the corresponding BAT record (after incrementing the reference
     938             :  * count). The BAT will be loaded into memory, if necessary.
     939             :  *
     940             :  * The structure of the BBP file obeys the tuple format for GDK.
     941             :  *
     942             :  * The status and BAT persistency information is encoded in the status
     943             :  * field.
     944             :  */
     945             : typedef struct {
     946             :         char *logical;          /* logical name (may point at bak) */
     947             :         char bak[16];           /* logical name backup (tmp_%o) */
     948             :         BAT descr;              /* the BAT descriptor */
     949             :         char *options;          /* A string list of options */
     950             : #if SIZEOF_VOID_P == 4
     951             :         char physical[20];      /* dir + basename for storage */
     952             : #else
     953             :         char physical[24];      /* dir + basename for storage */
     954             : #endif
     955             :         bat next;               /* next BBP slot in linked list */
     956             :         int refs;               /* in-memory references on which the loaded status of a BAT relies */
     957             :         int lrefs;              /* logical references on which the existence of a BAT relies */
     958             :         ATOMIC_TYPE status;     /* status mask used for spin locking */
     959             :         MT_Id pid;              /* creator of this bat while "private" */
     960             : } BBPrec;
     961             : 
     962             : gdk_export bat BBPlimit;
     963             : #if SIZEOF_VOID_P == 4
     964             : #define N_BBPINIT       1000
     965             : #define BBPINITLOG      11
     966             : #else
     967             : #define N_BBPINIT       10000
     968             : #define BBPINITLOG      14
     969             : #endif
     970             : #define BBPINIT         (1 << BBPINITLOG)
     971             : /* absolute maximum number of BATs is N_BBPINIT * BBPINIT
     972             :  * this also gives the longest possible "physical" name and "bak" name
     973             :  * of a BAT: the "bak" name is "tmp_%o", so at most 14 + \0 bytes on 64
     974             :  * bit architecture and 11 + \0 on 32 bit architecture; the physical
     975             :  * name is a bit more complicated, but the longest possible name is 22 +
     976             :  * \0 bytes (16 + \0 on 32 bits), the longest possible extension adds
     977             :  * another 17 bytes (.thsh(grp|uni)(l|b)%08x) */
     978             : gdk_export BBPrec *BBP[N_BBPINIT];
     979             : 
     980             : /* fast defines without checks; internal use only  */
     981             : #define BBP_record(i)   BBP[(i)>>BBPINITLOG][(i)&(BBPINIT-1)]
     982             : #define BBP_logical(i)  BBP_record(i).logical
     983             : #define BBP_bak(i)      BBP_record(i).bak
     984             : #define BBP_next(i)     BBP_record(i).next
     985             : #define BBP_physical(i) BBP_record(i).physical
     986             : #define BBP_options(i)  BBP_record(i).options
     987             : #define BBP_desc(i)     (&BBP_record(i).descr)
     988             : #define BBP_refs(i)     BBP_record(i).refs
     989             : #define BBP_lrefs(i)    BBP_record(i).lrefs
     990             : #define BBP_status(i)   ((unsigned) ATOMIC_GET(&BBP_record(i).status))
     991             : #define BBP_pid(i)      BBP_record(i).pid
     992             : #define BATgetId(b)     BBP_logical((b)->batCacheid)
     993             : #define BBPvalid(i)     (BBP_logical(i) != NULL)
     994             : 
     995             : #define BBPRENAME_ALREADY       (-1)
     996             : #define BBPRENAME_ILLEGAL       (-2)
     997             : #define BBPRENAME_LONG          (-3)
     998             : #define BBPRENAME_MEMORY        (-4)
     999             : 
    1000             : gdk_export void BBPlock(void);
    1001             : gdk_export void BBPunlock(void);
    1002             : gdk_export void BBPtmlock(void);
    1003             : gdk_export void BBPtmunlock(void);
    1004             : 
    1005             : gdk_export BAT *BBPquickdesc(bat b);
    1006             : 
    1007             : /* BAT iterator, also protects use of BAT heaps with reference counts.
    1008             :  *
    1009             :  * A BAT iterator has to be used with caution, but it does have to be
    1010             :  * used in many place.
    1011             :  *
    1012             :  * An iterator is initialized by assigning it the result of a call to
    1013             :  * either bat_iterator or bat_iterator_nolock.  The former must be
    1014             :  * accompanied by a call to bat_iterator_end to release resources.
    1015             :  *
    1016             :  * bat_iterator should be used for BATs that could possibly be modified
    1017             :  * in another thread while we're reading the contents of the BAT.
    1018             :  * Alternatively, but only for very quick access, the theaplock can be
    1019             :  * taken, the data read, and the lock released.  For longer duration
    1020             :  * accesses, it is better to use the iterator, even without the BUNt*
    1021             :  * macros, since the theaplock is only held very briefly.
    1022             :  *
    1023             :  * Note, bat_iterator must only be used for read-only access.
    1024             :  *
    1025             :  * If BATs are to be modified, higher level code must assure that no
    1026             :  * other thread is going to modify the same BAT at the same time.  A
    1027             :  * to-be-modified BAT should not use bat_iterator.  It can use
    1028             :  * bat_iterator_nolock, but be aware that this creates a copy of the
    1029             :  * heap pointer(s) (i.e. theap and tvheap) and if the heaps get
    1030             :  * extended, the pointers in the BAT structure may be modified, but that
    1031             :  * does not modify the pointers in the iterator.  This means that after
    1032             :  * operations that may grow a heap, the iterator should be
    1033             :  * reinitialized.
    1034             :  *
    1035             :  * The BAT iterator provides a number of fields that can (and often
    1036             :  * should) be used to access information about the BAT.  For string
    1037             :  * BATs, if a parallel threads adds values, the offset heap (theap) may
    1038             :  * get replaced by one that is wider.  This involves changing the twidth
    1039             :  * and tshift values in the BAT structure.  These changed values should
    1040             :  * not be used to access the data in the iterator.  Instead, use the
    1041             :  * width and shift values in the iterator itself.
    1042             :  */
    1043             : typedef struct BATiter {
    1044             :         BAT *b;
    1045             :         Heap *h;
    1046             :         void *base;
    1047             :         Heap *vh;
    1048             :         BUN count;
    1049             :         BUN baseoff;
    1050             :         oid tseq;
    1051             :         BUN hfree, vhfree;
    1052             :         BUN nokey[2];
    1053             :         BUN nosorted, norevsorted;
    1054             :         BUN minpos, maxpos;
    1055             :         double unique_est;
    1056             :         uint16_t width;
    1057             :         uint8_t shift;
    1058             :         int8_t type;
    1059             :         bool key:1,
    1060             :                 nonil:1,
    1061             :                 nil:1,
    1062             :                 sorted:1,
    1063             :                 revsorted:1,
    1064             :                 hdirty:1,
    1065             :                 vhdirty:1,
    1066             :                 copiedtodisk:1,
    1067             :                 transient:1,
    1068             :                 ascii:1;
    1069             :         restrict_t restricted:2;
    1070             : #ifndef NDEBUG
    1071             :         bool locked:1;
    1072             : #endif
    1073             :         union {
    1074             :                 oid tvid;
    1075             :                 bool tmsk;
    1076             :         };
    1077             : } BATiter;
    1078             : 
    1079             : static inline BATiter
    1080   117522194 : bat_iterator_nolock(BAT *b)
    1081             : {
    1082             :         /* does not get matched by bat_iterator_end */
    1083   117522194 :         if (b) {
    1084   117522194 :                 const bool isview = VIEWtparent(b) != 0;
    1085   235044388 :                 return (BATiter) {
    1086             :                         .b = b,
    1087             :                         .h = b->theap,
    1088   117522194 :                         .base = b->theap->base ? b->theap->base + (b->tbaseoff << b->tshift) : NULL,
    1089   117522194 :                         .baseoff = b->tbaseoff,
    1090   117522194 :                         .vh = b->tvheap,
    1091   117522194 :                         .count = b->batCount,
    1092   117522194 :                         .width = b->twidth,
    1093   117522194 :                         .shift = b->tshift,
    1094             :                         .type = b->ttype,
    1095   117522194 :                         .tseq = b->tseqbase,
    1096             :                         /* don't use b->theap->free in case b is a slice */
    1097   117522194 :                         .hfree = b->ttype ?
    1098             :                                   b->ttype == TYPE_msk ?
    1099   115989360 :                                    (((size_t) b->batCount + 31) / 32) * 4 :
    1100   232882156 :                                   (size_t) b->batCount << b->tshift :
    1101             :                                  0,
    1102   117522194 :                         .vhfree = b->tvheap ? b->tvheap->free : 0,
    1103   117522194 :                         .nokey[0] = b->tnokey[0],
    1104   117522194 :                         .nokey[1] = b->tnokey[1],
    1105   117522194 :                         .nosorted = b->tnosorted,
    1106   117522194 :                         .norevsorted = b->tnorevsorted,
    1107   117522194 :                         .minpos = isview ? BUN_NONE : b->tminpos,
    1108   103812374 :                         .maxpos = isview ? BUN_NONE : b->tmaxpos,
    1109   117522194 :                         .unique_est = b->tunique_est,
    1110   117522194 :                         .key = b->tkey,
    1111   117522194 :                         .nonil = b->tnonil,
    1112   117522194 :                         .nil = b->tnil,
    1113   117522194 :                         .sorted = b->tsorted,
    1114   117522194 :                         .revsorted = b->trevsorted,
    1115   117522194 :                         .ascii = b->tascii,
    1116             :                         /* only look at heap dirty flag if we own it */
    1117   117522194 :                         .hdirty = b->theap->parentid == b->batCacheid && b->theap->dirty,
    1118             :                         /* also, if there is no vheap, it's not dirty */
    1119   117522194 :                         .vhdirty = b->tvheap && b->tvheap->parentid == b->batCacheid && b->tvheap->dirty,
    1120   117522194 :                         .copiedtodisk = b->batCopiedtodisk,
    1121   117522194 :                         .transient = b->batTransient,
    1122   117522194 :                         .restricted = b->batRestricted,
    1123             : #ifndef NDEBUG
    1124             :                         .locked = false,
    1125             : #endif
    1126             :                 };
    1127             :         }
    1128           0 :         return (BATiter) {0};
    1129             : }
    1130             : 
    1131             : static inline void
    1132    35175185 : bat_iterator_incref(BATiter *bi)
    1133             : {
    1134             : #ifndef NDEBUG
    1135    35175185 :         bi->locked = true;
    1136             : #endif
    1137    35175185 :         HEAPincref(bi->h);
    1138    35183416 :         if (bi->vh)
    1139     7868059 :                 HEAPincref(bi->vh);
    1140    35183439 : }
    1141             : 
    1142             : static inline BATiter
    1143    34002321 : bat_iterator(BAT *b)
    1144             : {
    1145             :         /* needs matching bat_iterator_end */
    1146    34002321 :         BATiter bi;
    1147    34002321 :         if (b) {
    1148    32345095 :                 BAT *pb = NULL, *pvb = NULL;
    1149             :                 /* for a view, always first lock the view and then the
    1150             :                  * parent(s)
    1151             :                  * note that a varsized bat can have two different
    1152             :                  * parents and that the parent for the tail can itself
    1153             :                  * have a parent for its vheap (which would have to be
    1154             :                  * our own vheap parent), so lock the vheap after the
    1155             :                  * tail */
    1156    32345095 :                 MT_lock_set(&b->theaplock);
    1157    32341863 :                 if (b->theap->parentid != b->batCacheid) {
    1158     9260850 :                         pb = BBP_desc(b->theap->parentid);
    1159     9260850 :                         MT_lock_set(&pb->theaplock);
    1160             :                 }
    1161    32342006 :                 if (b->tvheap &&
    1162     7172312 :                     b->tvheap->parentid != b->batCacheid &&
    1163     2297042 :                     b->tvheap->parentid != b->theap->parentid) {
    1164      192751 :                         pvb = BBP_desc(b->tvheap->parentid);
    1165      192751 :                         MT_lock_set(&pvb->theaplock);
    1166             :                 }
    1167    32342003 :                 bi = bat_iterator_nolock(b);
    1168    32342003 :                 bat_iterator_incref(&bi);
    1169    32345966 :                 if (pvb)
    1170      192753 :                         MT_lock_unset(&pvb->theaplock);
    1171    32347733 :                 if (pb)
    1172     9262429 :                         MT_lock_unset(&pb->theaplock);
    1173    32346928 :                 MT_lock_unset(&b->theaplock);
    1174             :         } else {
    1175     1657226 :                 bi = (BATiter) {
    1176             :                         .b = NULL,
    1177             : #ifndef NDEBUG
    1178             :                         .locked = true,
    1179             : #endif
    1180             :                 };
    1181             :         }
    1182    34001300 :         return bi;
    1183             : }
    1184             : 
    1185             : /* return a copy of a BATiter instance; needs to be released with
    1186             :  * bat_iterator_end */
    1187             : static inline BATiter
    1188       48482 : bat_iterator_copy(BATiter *bip)
    1189             : {
    1190       48482 :         assert(bip);
    1191       48482 :         assert(bip->locked);
    1192       48482 :         if (bip->h)
    1193       48482 :                 HEAPincref(bip->h);
    1194       48482 :         if (bip->vh)
    1195       17263 :                 HEAPincref(bip->vh);
    1196       48482 :         return *bip;
    1197             : }
    1198             : 
    1199             : static inline void
    1200    36887847 : bat_iterator_end(BATiter *bip)
    1201             : {
    1202             :         /* matches bat_iterator */
    1203    36887847 :         assert(bip);
    1204    36887847 :         assert(bip->locked);
    1205    36887847 :         if (bip->h)
    1206    35230500 :                 HEAPdecref(bip->h, false);
    1207    36886781 :         if (bip->vh)
    1208     7885348 :                 HEAPdecref(bip->vh, false);
    1209    36886760 :         *bip = (BATiter) {0};
    1210    36886760 : }
    1211             : 
    1212             : /*
    1213             :  * @- Internal HEAP Chunk Management
    1214             :  * Heaps are used in BATs to store data for variable-size atoms.  The
    1215             :  * implementer must manage malloc()/free() functionality for atoms in
    1216             :  * this heap. A standard implementation is provided here.
    1217             :  *
    1218             :  * @table @code
    1219             :  * @item void
    1220             :  * HEAP_initialize  (Heap* h, size_t nbytes, size_t nprivate, int align )
    1221             :  * @item void
    1222             :  * HEAP_destroy     (Heap* h)
    1223             :  * @item var_t
    1224             :  * HEAP_malloc      (Heap* heap, size_t nbytes)
    1225             :  * @item void
    1226             :  * HEAP_free        (Heap *heap, var_t block)
    1227             :  * @item int
    1228             :  * HEAP_private     (Heap* h)
    1229             :  * @item void
    1230             :  * HEAP_printstatus (Heap* h)
    1231             :  * @end table
    1232             :  *
    1233             :  * The heap space starts with a private space that is left untouched
    1234             :  * by the normal chunk allocation.  You can use this private space
    1235             :  * e.g. to store the root of an rtree HEAP_malloc allocates a chunk of
    1236             :  * memory on the heap, and returns an index to it.  HEAP_free frees a
    1237             :  * previously allocated chunk HEAP_private returns an integer index to
    1238             :  * private space.
    1239             :  */
    1240             : 
    1241             : gdk_export gdk_return HEAP_initialize(
    1242             :         Heap *heap,             /* nbytes -- Initial size of the heap. */
    1243             :         size_t nbytes,          /* alignment -- for objects on the heap. */
    1244             :         size_t nprivate,        /* nprivate -- Size of private space */
    1245             :         int alignment           /* alignment restriction for allocated chunks */
    1246             :         );
    1247             : 
    1248             : gdk_export var_t HEAP_malloc(BAT *b, size_t nbytes);
    1249             : gdk_export void HEAP_free(Heap *heap, var_t block);
    1250             : 
    1251             : /*
    1252             :  * @- BAT construction
    1253             :  * @multitable @columnfractions 0.08 0.7
    1254             :  * @item @code{BAT* }
    1255             :  * @tab COLnew (oid headseq, int tailtype, BUN cap, role_t role)
    1256             :  * @item @code{BAT* }
    1257             :  * @tab BATextend (BAT *b, BUN newcap)
    1258             :  * @end multitable
    1259             :  *
    1260             :  * A temporary BAT is instantiated using COLnew with the type aliases
    1261             :  * of the required binary association. The aliases include the
    1262             :  * built-in types, such as TYPE_int....TYPE_ptr, and the atomic types
    1263             :  * introduced by the user. The initial capacity to be accommodated
    1264             :  * within a BAT is indicated by cap.  Their extend is automatically
    1265             :  * incremented upon storage overflow.  Failure to create the BAT
    1266             :  * results in a NULL pointer.
    1267             :  *
    1268             :  * The routine BATclone creates an empty BAT storage area with the
    1269             :  * properties inherited from its argument.
    1270             :  */
    1271             : gdk_export BAT *COLnew(oid hseq, int tltype, BUN capacity, role_t role)
    1272             :         __attribute__((__warn_unused_result__));
    1273             : gdk_export BAT *COLnew2(oid hseq, int tt, BUN cap, role_t role, uint16_t width)
    1274             :         __attribute__((__warn_unused_result__));
    1275             : gdk_export BAT *BATdense(oid hseq, oid tseq, BUN cnt)
    1276             :         __attribute__((__warn_unused_result__));
    1277             : gdk_export gdk_return BATextend(BAT *b, BUN newcap)
    1278             :         __attribute__((__warn_unused_result__));
    1279             : 
    1280             : /* internal */
    1281             : gdk_export uint8_t ATOMelmshift(int sz)
    1282             :         __attribute__((__const__));
    1283             : gdk_export gdk_return ATOMheap(int id, Heap *hp, size_t cap)
    1284             :         __attribute__((__warn_unused_result__));
    1285             : gdk_export const char *BATtailname(const BAT *b);
    1286             : 
    1287             : gdk_export gdk_return GDKupgradevarheap(BAT *b, var_t v, BUN cap, BUN ncopy)
    1288             :         __attribute__((__warn_unused_result__));
    1289             : gdk_export gdk_return BUNappend(BAT *b, const void *right, bool force)
    1290             :         __attribute__((__warn_unused_result__));
    1291             : gdk_export gdk_return BUNappendmulti(BAT *b, const void *values, BUN count, bool force)
    1292             :         __attribute__((__warn_unused_result__));
    1293             : gdk_export gdk_return BATappend(BAT *b, BAT *n, BAT *s, bool force)
    1294             :         __attribute__((__warn_unused_result__));
    1295             : 
    1296             : gdk_export gdk_return BUNreplace(BAT *b, oid left, const void *right, bool force)
    1297             :         __attribute__((__warn_unused_result__));
    1298             : gdk_export gdk_return BUNreplacemulti(BAT *b, const oid *positions, const void *values, BUN count, bool force)
    1299             :         __attribute__((__warn_unused_result__));
    1300             : gdk_export gdk_return BUNreplacemultiincr(BAT *b, oid position, const void *values, BUN count, bool force)
    1301             :         __attribute__((__warn_unused_result__));
    1302             : 
    1303             : gdk_export gdk_return BUNdelete(BAT *b, oid o)
    1304             :         __attribute__((__warn_unused_result__));
    1305             : gdk_export gdk_return BATdel(BAT *b, BAT *d)
    1306             :         __attribute__((__warn_unused_result__));
    1307             : 
    1308             : gdk_export gdk_return BATreplace(BAT *b, BAT *p, BAT *n, bool force)
    1309             :         __attribute__((__warn_unused_result__));
    1310             : gdk_export gdk_return BATupdate(BAT *b, BAT *p, BAT *n, bool force)
    1311             :         __attribute__((__warn_unused_result__));
    1312             : gdk_export gdk_return BATupdatepos(BAT *b, const oid *positions, BAT *n, bool autoincr, bool force)
    1313             :         __attribute__((__warn_unused_result__));
    1314             : 
    1315             : /* Functions to perform a binary search on a sorted BAT.
    1316             :  * See gdk_search.c for details. */
    1317             : gdk_export BUN SORTfnd(BAT *b, const void *v);
    1318             : gdk_export BUN SORTfndfirst(BAT *b, const void *v);
    1319             : gdk_export BUN SORTfndlast(BAT *b, const void *v);
    1320             : 
    1321             : gdk_export BUN ORDERfnd(BAT *b, Heap *oidxh, const void *v);
    1322             : gdk_export BUN ORDERfndfirst(BAT *b, Heap *oidxh, const void *v);
    1323             : gdk_export BUN ORDERfndlast(BAT *b, Heap *oidxh, const void *v);
    1324             : 
    1325             : gdk_export BUN BUNfnd(BAT *b, const void *right);
    1326             : 
    1327             : #define BUNfndVOID(b, v)                                                \
    1328             :         (((is_oid_nil(*(const oid*)(v)) ^ is_oid_nil((b)->tseqbase)) |       \
    1329             :                 (*(const oid*)(v) < (b)->tseqbase) |                      \
    1330             :                 (*(const oid*)(v) >= (b)->tseqbase + (b)->batCount)) ? \
    1331             :          BUN_NONE :                                                     \
    1332             :          (BUN) (*(const oid*)(v) - (b)->tseqbase))
    1333             : 
    1334             : #define BATttype(b)     (BATtdense(b) ? TYPE_oid : (b)->ttype)
    1335             : 
    1336             : #define tailsize(b,p)   ((b)->ttype ?                                \
    1337             :                          (ATOMstorage((b)->ttype) == TYPE_msk ?      \
    1338             :                           (((size_t) (p) + 31) / 32) * 4 :      \
    1339             :                           ((size_t) (p)) << (b)->tshift) :     \
    1340             :                          0)
    1341             : 
    1342             : #define Tloc(b,p)       ((void *)((b)->theap->base+(((size_t)(p)+(b)->tbaseoff)<<(b)->tshift)))
    1343             : 
    1344             : typedef var_t stridx_t;
    1345             : #define SIZEOF_STRIDX_T SIZEOF_VAR_T
    1346             : #define GDK_VARALIGN SIZEOF_STRIDX_T
    1347             : 
    1348             : #define BUNtvaroff(bi,p) VarHeapVal((bi).base, (p), (bi).width)
    1349             : 
    1350             : #define BUNtmsk(bi,p)   Tmsk(&(bi), (p))
    1351             : #define BUNtloc(bi,p)   (assert((bi).type != TYPE_msk), ((void *) ((char *) (bi).base + ((p) << (bi).shift))))
    1352             : #define BUNtpos(bi,p)   Tpos(&(bi),p)
    1353             : #define BUNtvar(bi,p)   (assert((bi).type && (bi).vh), (void *) ((bi).vh->base+BUNtvaroff(bi,p)))
    1354             : #define BUNtail(bi,p)   ((bi).type?(bi).vh?BUNtvar(bi,p):(bi).type==TYPE_msk?BUNtmsk(bi,p):BUNtloc(bi,p):BUNtpos(bi,p))
    1355             : 
    1356             : #define BATcount(b)     ((b)->batCount)
    1357             : 
    1358             : #include "gdk_atoms.h"
    1359             : 
    1360             : #include "gdk_cand.h"
    1361             : 
    1362             : /*
    1363             :  * @- BAT properties
    1364             :  * @multitable @columnfractions 0.08 0.7
    1365             :  * @item BUN
    1366             :  * @tab BATcount (BAT *b)
    1367             :  * @item void
    1368             :  * @tab BATsetcapacity (BAT *b, BUN cnt)
    1369             :  * @item void
    1370             :  * @tab BATsetcount (BAT *b, BUN cnt)
    1371             :  * @item BAT *
    1372             :  * @tab BATkey (BAT *b, bool onoff)
    1373             :  * @item BAT *
    1374             :  * @tab BATmode (BAT *b, bool transient)
    1375             :  * @item BAT *
    1376             :  * @tab BATsetaccess (BAT *b, restrict_t mode)
    1377             :  * @item int
    1378             :  * @tab BATdirty (BAT *b)
    1379             :  * @item restrict_t
    1380             :  * @tab BATgetaccess (BAT *b)
    1381             :  * @end multitable
    1382             :  *
    1383             :  * The function BATcount returns the number of associations stored in
    1384             :  * the BAT.
    1385             :  *
    1386             :  * The BAT is given a new logical name using BBPrename.
    1387             :  *
    1388             :  * The integrity properties to be maintained for the BAT are
    1389             :  * controlled separately.  A key property indicates that duplicates in
    1390             :  * the association dimension are not permitted.
    1391             :  *
    1392             :  * The persistency indicator tells the retention period of BATs.  The
    1393             :  * system support two modes: PERSISTENT and TRANSIENT.
    1394             :  * The PERSISTENT BATs are automatically saved upon session boundary
    1395             :  * or transaction commit.  TRANSIENT BATs are removed upon transaction
    1396             :  * boundary.  All BATs are initially TRANSIENT unless their mode is
    1397             :  * changed using the routine BATmode.
    1398             :  *
    1399             :  * The BAT properties may be changed at any time using BATkey
    1400             :  * and BATmode.
    1401             :  *
    1402             :  * Valid BAT access properties can be set with BATsetaccess and
    1403             :  * BATgetaccess: BAT_READ, BAT_APPEND, and BAT_WRITE.  BATs can be
    1404             :  * designated to be read-only. In this case some memory optimizations
    1405             :  * may be made (slice and fragment bats can point to stable subsets of
    1406             :  * a parent bat).  A special mode is append-only. It is then allowed
    1407             :  * to insert BUNs at the end of the BAT, but not to modify anything
    1408             :  * that already was in there.
    1409             :  */
    1410             : gdk_export BUN BATcount_no_nil(BAT *b, BAT *s);
    1411             : gdk_export void BATsetcapacity(BAT *b, BUN cnt);
    1412             : gdk_export void BATsetcount(BAT *b, BUN cnt);
    1413             : gdk_export BUN BATgrows(BAT *b);
    1414             : gdk_export gdk_return BATkey(BAT *b, bool onoff);
    1415             : gdk_export gdk_return BATmode(BAT *b, bool transient);
    1416             : gdk_export void BAThseqbase(BAT *b, oid o);
    1417             : gdk_export void BATtseqbase(BAT *b, oid o);
    1418             : 
    1419             : gdk_export BAT *BATsetaccess(BAT *b, restrict_t mode)
    1420             :         __attribute__((__warn_unused_result__));
    1421             : gdk_export restrict_t BATgetaccess(BAT *b);
    1422             : 
    1423             : 
    1424             : #define BATdirty(b)     (!(b)->batCopiedtodisk ||                    \
    1425             :                          (b)->theap->dirty ||                             \
    1426             :                          ((b)->tvheap != NULL && (b)->tvheap->dirty))
    1427             : #define BATdirtybi(bi)  (!(bi).copiedtodisk || (bi).hdirty || (bi).vhdirty)
    1428             : 
    1429             : #define BATcapacity(b)  (b)->batCapacity
    1430             : /*
    1431             :  * @- BAT manipulation
    1432             :  * @multitable @columnfractions 0.08 0.7
    1433             :  * @item BAT *
    1434             :  * @tab BATclear (BAT *b, bool force)
    1435             :  * @item BAT *
    1436             :  * @tab COLcopy (BAT *b, int tt, bool writeable, role_t role)
    1437             :  * @end multitable
    1438             :  *
    1439             :  * The routine BATclear removes the binary associations, leading to an
    1440             :  * empty, but (re-)initialized BAT. Its properties are retained.  A
    1441             :  * temporary copy is obtained with Colcopy. The new BAT has an unique
    1442             :  * name.
    1443             :  */
    1444             : gdk_export gdk_return BATclear(BAT *b, bool force);
    1445             : gdk_export BAT *COLcopy(BAT *b, int tt, bool writable, role_t role);
    1446             : 
    1447             : gdk_export gdk_return BATgroup(BAT **groups, BAT **extents, BAT **histo, BAT *b, BAT *s, BAT *g, BAT *e, BAT *h)
    1448             :         __attribute__((__warn_unused_result__));
    1449             : /*
    1450             :  * @- BAT Input/Output
    1451             :  * @multitable @columnfractions 0.08 0.7
    1452             :  * @item BAT *
    1453             :  * @tab BATload (str name)
    1454             :  * @item BAT *
    1455             :  * @tab BATsave (BAT *b)
    1456             :  * @item int
    1457             :  * @tab BATdelete (BAT *b)
    1458             :  * @end multitable
    1459             :  *
    1460             :  * A BAT created by COLnew is considered temporary until one calls the
    1461             :  * routine BATsave or BATmode.  This routine reserves disk space and
    1462             :  * checks for name clashes in the BAT directory. It also makes the BAT
    1463             :  * persistent. The empty BAT is initially marked as ordered on both
    1464             :  * columns.
    1465             :  *
    1466             :  * Failure to read or write the BAT results in a NULL, otherwise it
    1467             :  * returns the BAT pointer.
    1468             :  *
    1469             :  * @- Heap Storage Modes
    1470             :  * The discriminative storage modes are memory-mapped, compressed, or
    1471             :  * loaded in memory.  As can be seen in the bat record, each BAT has
    1472             :  * one BUN-heap (@emph{bn}), and possibly two heaps (@emph{hh} and
    1473             :  * @emph{th}) for variable-sized atoms.
    1474             :  */
    1475             : 
    1476             : gdk_export gdk_return BATsave(BAT *b)
    1477             :         __attribute__((__warn_unused_result__));
    1478             : 
    1479             : #define NOFARM (-1) /* indicate to GDKfilepath to create relative path */
    1480             : 
    1481             : gdk_export char *GDKfilepath(int farmid, const char *dir, const char *nme, const char *ext);
    1482             : gdk_export bool GDKinmemory(int farmid);
    1483             : gdk_export bool GDKembedded(void);
    1484             : gdk_export gdk_return GDKcreatedir(const char *nme);
    1485             : 
    1486             : gdk_export void OIDXdestroy(BAT *b);
    1487             : 
    1488             : /*
    1489             :  * @- Printing
    1490             :  * @multitable @columnfractions 0.08 0.7
    1491             :  * @item int
    1492             :  * @tab BATprintcolumns (stream *f, int argc, BAT *b[]);
    1493             :  * @end multitable
    1494             :  *
    1495             :  * The functions to convert BATs into ASCII. They are primarily meant for ease of
    1496             :  * debugging and to a lesser extent for output processing.  Printing a
    1497             :  * BAT is done essentially by looping through its components, printing
    1498             :  * each association.
    1499             :  *
    1500             :  */
    1501             : gdk_export gdk_return BATprintcolumns(stream *s, int argc, BAT *argv[]);
    1502             : gdk_export gdk_return BATprint(stream *s, BAT *b);
    1503             : 
    1504             : /*
    1505             :  * @- BAT clustering
    1506             :  * @multitable @columnfractions 0.08 0.7
    1507             :  * @item bool
    1508             :  * @tab BATordered (BAT *b)
    1509             :  * @end multitable
    1510             :  *
    1511             :  * When working in a main-memory situation, clustering of data on
    1512             :  * disk-pages is not important. Whenever mmap()-ed data is used
    1513             :  * intensively, reducing the number of page faults is a hot issue.
    1514             :  *
    1515             :  * The above functions rearrange data in MonetDB heaps (used for
    1516             :  * storing BUNs var-sized atoms, or accelerators). Applying these
    1517             :  * clusterings will allow that MonetDB's main-memory oriented
    1518             :  * algorithms work efficiently also in a disk-oriented context.
    1519             :  *
    1520             :  * BATordered starts a check on the tail values to see if they are
    1521             :  * ordered. The result is returned and stored in the tsorted field of
    1522             :  * the BAT.
    1523             :  */
    1524             : gdk_export bool BATordered(BAT *b);
    1525             : gdk_export bool BATordered_rev(BAT *b);
    1526             : gdk_export gdk_return BATsort(BAT **sorted, BAT **order, BAT **groups, BAT *b, BAT *o, BAT *g, bool reverse, bool nilslast, bool stable)
    1527             :         __attribute__((__warn_unused_result__));
    1528             : 
    1529             : 
    1530             : 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);
    1531             : 
    1532             : /* BAT is dense (i.e., BATtvoid() is true and tseqbase is not NIL) */
    1533             : #define BATtdense(b)    (!is_oid_nil((b)->tseqbase) &&                       \
    1534             :                          ((b)->tvheap == NULL || (b)->tvheap->free == 0))
    1535             : #define BATtdensebi(bi) (!is_oid_nil((bi)->tseq) &&                  \
    1536             :                          ((bi)->vh == NULL || (bi)->vhfree == 0))
    1537             : /* BATtvoid: BAT can be (or actually is) represented by TYPE_void */
    1538             : #define BATtvoid(b)     (BATtdense(b) || (b)->ttype==TYPE_void)
    1539             : #define BATtkey(b)      ((b)->tkey || BATtdense(b))
    1540             : 
    1541             : /* set some properties that are trivial to deduce; called with theaplock
    1542             :  * held */
    1543             : static inline void
    1544     4903672 : BATsettrivprop(BAT *b)
    1545             : {
    1546     4903672 :         assert(!is_oid_nil(b->hseqbase));
    1547     4903672 :         assert(is_oid_nil(b->tseqbase) || ATOMtype(b->ttype) == TYPE_oid);
    1548     4903672 :         if (b->ttype == TYPE_void) {
    1549     1226160 :                 if (is_oid_nil(b->tseqbase)) {
    1550         131 :                         b->tnonil = b->batCount == 0;
    1551         131 :                         b->tnil = !b->tnonil;
    1552         131 :                         b->trevsorted = true;
    1553         131 :                         b->tkey = b->batCount <= 1;
    1554             :                 } else {
    1555     1226029 :                         b->tnonil = true;
    1556     1226029 :                         b->tnil = false;
    1557     1226029 :                         b->tkey = true;
    1558     1226029 :                         b->trevsorted = b->batCount <= 1;
    1559             :                 }
    1560     1226160 :                 b->tsorted = true;
    1561     3677512 :         } else if (b->batCount <= 1) {
    1562     1376652 :                 b->tnosorted = b->tnorevsorted = 0;
    1563     1376652 :                 b->tnokey[0] = b->tnokey[1] = 0;
    1564     1376652 :                 b->tunique_est = (double) b->batCount;
    1565     1376652 :                 b->tkey = true;
    1566     1376652 :                 if (ATOMlinear(b->ttype)) {
    1567     1376652 :                         b->tsorted = true;
    1568     1376652 :                         b->trevsorted = true;
    1569     1376652 :                         if (b->batCount == 0) {
    1570      855255 :                                 b->tminpos = BUN_NONE;
    1571      855255 :                                 b->tmaxpos = BUN_NONE;
    1572      855255 :                                 b->tnonil = true;
    1573      855255 :                                 b->tnil = false;
    1574      855255 :                                 if (b->ttype == TYPE_oid) {
    1575       11877 :                                         b->tseqbase = 0;
    1576             :                                 }
    1577      521397 :                         } else if (b->ttype == TYPE_oid) {
    1578       68055 :                                 oid sqbs = ((const oid *) b->theap->base)[b->tbaseoff];
    1579       68055 :                                 if (is_oid_nil(sqbs)) {
    1580         336 :                                         b->tnonil = false;
    1581         336 :                                         b->tnil = true;
    1582         336 :                                         b->tminpos = BUN_NONE;
    1583         336 :                                         b->tmaxpos = BUN_NONE;
    1584             :                                 } else {
    1585       67719 :                                         b->tnonil = true;
    1586       67719 :                                         b->tnil = false;
    1587       67719 :                                         b->tminpos = 0;
    1588       67719 :                                         b->tmaxpos = 0;
    1589             :                                 }
    1590       68055 :                                 b->tseqbase = sqbs;
    1591      453242 :                         } else if ((b->tvheap
    1592      131695 :                                     ? ATOMcmp(b->ttype,
    1593             :                                               b->tvheap->base + VarHeapVal(Tloc(b, 0), 0, b->twidth),
    1594             :                                               ATOMnilptr(b->ttype))
    1595      321647 :                                     : ATOMcmp(b->ttype, Tloc(b, 0),
    1596      906584 :                                               ATOMnilptr(b->ttype))) == 0) {
    1597             :                                 /* the only value is NIL */
    1598       17019 :                                 b->tminpos = BUN_NONE;
    1599       17019 :                                 b->tmaxpos = BUN_NONE;
    1600             :                         } else {
    1601             :                                 /* the only value is both min and max */
    1602      436223 :                                 b->tminpos = 0;
    1603      436223 :                                 b->tmaxpos = 0;
    1604             :                         }
    1605             :                 } else {
    1606           0 :                         b->tsorted = false;
    1607           0 :                         b->trevsorted = false;
    1608           0 :                         b->tminpos = BUN_NONE;
    1609           0 :                         b->tmaxpos = BUN_NONE;
    1610             :                 }
    1611     2300860 :         } else if (b->batCount == 2 && ATOMlinear(b->ttype)) {
    1612      174963 :                 int c;
    1613      174963 :                 if (b->tvheap)
    1614       41076 :                         c = ATOMcmp(b->ttype,
    1615             :                                     b->tvheap->base + VarHeapVal(Tloc(b, 0), 0, b->twidth),
    1616             :                                     b->tvheap->base + VarHeapVal(Tloc(b, 0), 1, b->twidth));
    1617             :                 else
    1618      133887 :                         c = ATOMcmp(b->ttype, Tloc(b, 0), Tloc(b, 1));
    1619      174954 :                 b->tsorted = c <= 0;
    1620      174954 :                 b->tnosorted = !b->tsorted;
    1621      174954 :                 b->trevsorted = c >= 0;
    1622      174954 :                 b->tnorevsorted = !b->trevsorted;
    1623      174954 :                 b->tkey = c != 0;
    1624      174954 :                 b->tnokey[0] = 0;
    1625      174954 :                 b->tnokey[1] = !b->tkey;
    1626      174954 :                 b->tunique_est = (double) (1 + b->tkey);
    1627     2125897 :         } else if (!ATOMlinear(b->ttype)) {
    1628           0 :                 b->tsorted = false;
    1629           0 :                 b->trevsorted = false;
    1630           0 :                 b->tminpos = BUN_NONE;
    1631           0 :                 b->tmaxpos = BUN_NONE;
    1632             :         }
    1633     4903563 : }
    1634             : 
    1635             : static inline void
    1636         310 : BATnegateprops(BAT *b)
    1637             : {
    1638             :         /* disable all properties here */
    1639         310 :         b->tnonil = false;
    1640         310 :         b->tnil = false;
    1641         310 :         if (b->ttype) {
    1642         310 :                 b->tsorted = false;
    1643         310 :                 b->trevsorted = false;
    1644         310 :                 b->tnosorted = 0;
    1645         310 :                 b->tnorevsorted = 0;
    1646             :         }
    1647         310 :         b->tseqbase = oid_nil;
    1648         310 :         b->tkey = false;
    1649         310 :         b->tnokey[0] = 0;
    1650         310 :         b->tnokey[1] = 0;
    1651         310 :         b->tmaxpos = b->tminpos = BUN_NONE;
    1652         310 : }
    1653             : 
    1654             : /*
    1655             :  * @- GDK error handling
    1656             :  *  @multitable @columnfractions 0.08 0.7
    1657             :  * @item str
    1658             :  * @tab
    1659             :  *  GDKmessage
    1660             :  * @item bit
    1661             :  * @tab
    1662             :  *  GDKfatal(str msg)
    1663             :  * @item int
    1664             :  * @tab
    1665             :  *  GDKwarning(str msg)
    1666             :  * @item int
    1667             :  * @tab
    1668             :  *  GDKerror (str msg)
    1669             :  * @item int
    1670             :  * @tab
    1671             :  *  GDKgoterrors ()
    1672             :  * @item int
    1673             :  * @tab
    1674             :  *  GDKsyserror (str msg)
    1675             :  * @item str
    1676             :  * @tab
    1677             :  *  GDKerrbuf
    1678             :  *  @item
    1679             :  * @tab GDKsetbuf (str buf)
    1680             :  * @end multitable
    1681             :  *
    1682             :  * The error handling mechanism is not sophisticated yet. Experience
    1683             :  * should show if this mechanism is sufficient.  Most routines return
    1684             :  * a pointer with zero to indicate an error.
    1685             :  *
    1686             :  * The error messages are also copied to standard output.  The last
    1687             :  * error message is kept around in a global variable.
    1688             :  *
    1689             :  * Error messages can also be collected in a user-provided buffer,
    1690             :  * instead of being echoed to a stream. This is a thread-specific
    1691             :  * issue; you want to decide on the error mechanism on a
    1692             :  * thread-specific basis.  This effect is established with
    1693             :  * GDKsetbuf. The memory (de)allocation of this buffer, that must at
    1694             :  * least be 1024 chars long, is entirely by the user. A pointer to
    1695             :  * this buffer is kept in the pseudo-variable GDKerrbuf. Normally,
    1696             :  * this is a NULL pointer.
    1697             :  */
    1698             : #define GDKMAXERRLEN    10240
    1699             : #define GDKWARNING      "!WARNING: "
    1700             : #define GDKERROR        "!ERROR: "
    1701             : #define GDKMESSAGE      "!OS: "
    1702             : #define GDKFATAL        "!FATAL: "
    1703             : 
    1704             : /* Data Distilleries uses ICU for internationalization of some MonetDB error messages */
    1705             : 
    1706             : #include "gdk_tracer.h"
    1707             : 
    1708             : gdk_export gdk_return GDKtracer_fill_comp_info(BAT *id, BAT *component, BAT *log_level);
    1709             : 
    1710             : #define GDKerror(...)                                           \
    1711             :         GDKtracer_log(__FILE__, __func__, __LINE__, M_ERROR,    \
    1712             :                       GDK, NULL, __VA_ARGS__)
    1713             : #define GDKsyserr(errno, ...)                                           \
    1714             :         GDKtracer_log(__FILE__, __func__, __LINE__, M_ERROR,            \
    1715             :                       GDK, GDKstrerror(errno, (char[64]){0}, 64),       \
    1716             :                       __VA_ARGS__)
    1717             : #define GDKsyserror(...)        GDKsyserr(errno, __VA_ARGS__)
    1718             : 
    1719             : gdk_export void GDKclrerr(void);
    1720             : 
    1721             : 
    1722             : /* tfastins* family: update a value at a particular location in the bat
    1723             :  * bunfastapp* family: append a value to the bat
    1724             :  * *_nocheck: do not check whether the capacity is large enough
    1725             :  * * (without _nocheck): check bat capacity and possibly extend
    1726             :  *
    1727             :  * This means, for tfastins* it is the caller's responsibility to set
    1728             :  * the batCount and theap->free values correctly (e.g. by calling
    1729             :  * BATsetcount(), and for *_nocheck to make sure there is enough space
    1730             :  * allocated in the theap (tvheap for variable-sized types is still
    1731             :  * extended if needed, making that these functions can fail).
    1732             :  */
    1733             : static inline gdk_return __attribute__((__warn_unused_result__))
    1734   103846324 : tfastins_nocheckVAR(BAT *b, BUN p, const void *v)
    1735             : {
    1736   103846324 :         var_t d;
    1737   103846324 :         gdk_return rc;
    1738   103846324 :         assert(b->tbaseoff == 0);
    1739   103846324 :         assert(b->theap->parentid == b->batCacheid);
    1740   103846324 :         MT_lock_set(&b->theaplock);
    1741   103627473 :         rc = ATOMputVAR(b, &d, v);
    1742   103862007 :         MT_lock_unset(&b->theaplock);
    1743   105007068 :         if (rc != GDK_SUCCEED)
    1744             :                 return rc;
    1745   105427668 :         if (b->twidth < SIZEOF_VAR_T &&
    1746    93493515 :             (b->twidth <= 2 ? d - GDK_VAROFFSET : d) >= ((size_t) 1 << (8 << b->tshift))) {
    1747             :                 /* doesn't fit in current heap, upgrade it */
    1748       14039 :                 rc = GDKupgradevarheap(b, d, 0, MAX(p, b->batCount));
    1749       14039 :                 if (rc != GDK_SUCCEED)
    1750             :                         return rc;
    1751             :         }
    1752   105427668 :         switch (b->twidth) {
    1753    30958422 :         case 1:
    1754    30958422 :                 ((uint8_t *) b->theap->base)[p] = (uint8_t) (d - GDK_VAROFFSET);
    1755    30958422 :                 break;
    1756    18093369 :         case 2:
    1757    18093369 :                 ((uint16_t *) b->theap->base)[p] = (uint16_t) (d - GDK_VAROFFSET);
    1758    18093369 :                 break;
    1759    44772630 :         case 4:
    1760    44772630 :                 ((uint32_t *) b->theap->base)[p] = (uint32_t) d;
    1761    44772630 :                 break;
    1762             : #if SIZEOF_VAR_T == 8
    1763    11603247 :         case 8:
    1764    11603247 :                 ((uint64_t *) b->theap->base)[p] = (uint64_t) d;
    1765    11603247 :                 break;
    1766             : #endif
    1767             :         default:
    1768           0 :                 MT_UNREACHABLE();
    1769             :         }
    1770             :         return GDK_SUCCEED;
    1771             : }
    1772             : 
    1773             : static inline gdk_return __attribute__((__warn_unused_result__))
    1774   357058847 : tfastins_nocheckFIX(BAT *b, BUN p, const void *v)
    1775             : {
    1776   357058847 :         return ATOMputFIX(b->ttype, Tloc(b, p), v);
    1777             : }
    1778             : 
    1779             : static inline gdk_return __attribute__((__warn_unused_result__))
    1780   363952003 : tfastins_nocheck(BAT *b, BUN p, const void *v)
    1781             : {
    1782   363952003 :         assert(b->theap->parentid == b->batCacheid);
    1783   363952003 :         assert(b->tbaseoff == 0);
    1784   363952003 :         if (b->ttype == TYPE_void) {
    1785             :                 ;
    1786   363952003 :         } else if (ATOMstorage(b->ttype) == TYPE_msk) {
    1787           0 :                 mskSetVal(b, p, * (msk *) v);
    1788   363952003 :         } else if (b->tvheap) {
    1789    40051941 :                 return tfastins_nocheckVAR(b, p, v);
    1790             :         } else {
    1791   323900062 :                 return tfastins_nocheckFIX(b, p, v);
    1792             :         }
    1793             :         return GDK_SUCCEED;
    1794             : }
    1795             : 
    1796             : static inline gdk_return __attribute__((__warn_unused_result__))
    1797   351089349 : tfastins(BAT *b, BUN p, const void *v)
    1798             : {
    1799   351089349 :         if (p >= BATcapacity(b)) {
    1800           0 :                 if (p >= BUN_MAX) {
    1801           0 :                         GDKerror("tfastins: too many elements to accommodate (" BUNFMT ")\n", BUN_MAX);
    1802           0 :                         return GDK_FAIL;
    1803             :                 }
    1804           0 :                 BUN sz = BATgrows(b);
    1805           0 :                 if (sz <= p)
    1806           0 :                         sz = p + BATTINY;
    1807           0 :                 gdk_return rc = BATextend(b, sz);
    1808           0 :                 if (rc != GDK_SUCCEED)
    1809             :                         return rc;
    1810             :         }
    1811   351089349 :         return tfastins_nocheck(b, p, v);
    1812             : }
    1813             : 
    1814             : static inline gdk_return __attribute__((__warn_unused_result__))
    1815     7957975 : bunfastapp_nocheck(BAT *b, const void *v)
    1816             : {
    1817     7957975 :         BUN p = b->batCount;
    1818     7957975 :         if (ATOMstorage(b->ttype) == TYPE_msk && p % 32 == 0)
    1819           0 :                 ((uint32_t *) b->theap->base)[p / 32] = 0;
    1820     7957975 :         gdk_return rc = tfastins_nocheck(b, p, v);
    1821     7957418 :         if (rc == GDK_SUCCEED) {
    1822     7957860 :                 b->batCount++;
    1823     7957860 :                 if (ATOMstorage(b->ttype) == TYPE_msk) {
    1824           0 :                         if (p % 32 == 0)
    1825           0 :                                 b->theap->free += 4;
    1826             :                 } else
    1827     7957860 :                         b->theap->free += b->twidth;
    1828             :         }
    1829     7957418 :         return rc;
    1830             : }
    1831             : 
    1832             : static inline gdk_return __attribute__((__warn_unused_result__))
    1833   351083021 : bunfastapp(BAT *b, const void *v)
    1834             : {
    1835   351083021 :         BUN p = b->batCount;
    1836   351083021 :         if (ATOMstorage(b->ttype) == TYPE_msk && p % 32 == 0)
    1837           0 :                 ((uint32_t *) b->theap->base)[p / 32] = 0;
    1838   351083021 :         gdk_return rc = tfastins(b, p, v);
    1839   345974022 :         if (rc == GDK_SUCCEED) {
    1840   337387815 :                 b->batCount++;
    1841   337387815 :                 if (ATOMstorage(b->ttype) == TYPE_msk) {
    1842           0 :                         if (p % 32 == 0)
    1843           0 :                                 b->theap->free += 4;
    1844             :                 } else
    1845   337387815 :                         b->theap->free += b->twidth;
    1846             :         }
    1847   345974022 :         return rc;
    1848             : }
    1849             : 
    1850             : #define bunfastappTYPE(TYPE, b, v)                                      \
    1851             :         (BATcount(b) >= BATcapacity(b) &&                            \
    1852             :          ((BATcount(b) == BUN_MAX &&                                    \
    1853             :            (GDKerror("bunfastapp: too many elements to accommodate (" BUNFMT ")\n", BUN_MAX), \
    1854             :             true)) ||                                                   \
    1855             :           BATextend((b), BATgrows(b)) != GDK_SUCCEED) ?                 \
    1856             :          GDK_FAIL :                                                     \
    1857             :          (assert((b)->theap->parentid == (b)->batCacheid),             \
    1858             :           (b)->theap->free += sizeof(TYPE),                               \
    1859             :           ((TYPE *) (b)->theap->base)[(b)->batCount++] = * (const TYPE *) (v), \
    1860             :           GDK_SUCCEED))
    1861             : 
    1862             : static inline gdk_return __attribute__((__warn_unused_result__))
    1863         344 : bunfastapp_nocheckVAR(BAT *b, const void *v)
    1864             : {
    1865         344 :         gdk_return rc;
    1866         344 :         rc = tfastins_nocheckVAR(b, b->batCount, v);
    1867         343 :         if (rc == GDK_SUCCEED) {
    1868         343 :                 b->batCount++;
    1869         343 :                 b->theap->free += b->twidth;
    1870             :         }
    1871         343 :         return rc;
    1872             : }
    1873             : 
    1874             : /* Strimps exported functions */
    1875             : gdk_export gdk_return STRMPcreate(BAT *b, BAT *s);
    1876             : gdk_export BAT *STRMPfilter(BAT *b, BAT *s, const char *q, const bool keep_nils);
    1877             : gdk_export void STRMPdestroy(BAT *b);
    1878             : gdk_export bool BAThasstrimps(BAT *b);
    1879             : gdk_export gdk_return BATsetstrimps(BAT *b);
    1880             : 
    1881             : /* Rtree structure functions */
    1882             : #ifdef HAVE_RTREE
    1883             : gdk_export bool RTREEexists(BAT *b);
    1884             : gdk_export bool RTREEexists_bid(bat bid);
    1885             : gdk_export gdk_return BATrtree(BAT *wkb, BAT* mbr);
    1886             : /* inMBR is really a struct mbr * from geom module, but that is not
    1887             :  * available here */
    1888             : gdk_export BUN* RTREEsearch(BAT *b, const void *inMBR, int result_limit);
    1889             : #endif
    1890             : 
    1891             : gdk_export void RTREEdestroy(BAT *b);
    1892             : gdk_export void RTREEfree(BAT *b);
    1893             : 
    1894             : /* The ordered index structure */
    1895             : 
    1896             : gdk_export gdk_return BATorderidx(BAT *b, bool stable);
    1897             : gdk_export gdk_return GDKmergeidx(BAT *b, BAT**a, int n_ar);
    1898             : gdk_export bool BATcheckorderidx(BAT *b);
    1899             : 
    1900             : #include "gdk_delta.h"
    1901             : #include "gdk_hash.h"
    1902             : #include "gdk_bbp.h"
    1903             : #include "gdk_utils.h"
    1904             : 
    1905             : /* functions defined in gdk_bat.c */
    1906             : gdk_export gdk_return void_inplace(BAT *b, oid id, const void *val, bool force)
    1907             :         __attribute__((__warn_unused_result__));
    1908             : gdk_export BAT *BATattach(int tt, const char *heapfile, role_t role);
    1909             : 
    1910             : #ifdef NATIVE_WIN32
    1911             : #ifdef _MSC_VER
    1912             : #define fileno _fileno
    1913             : #endif
    1914             : #define fdopen _fdopen
    1915             : #define putenv _putenv
    1916             : #endif
    1917             : 
    1918             : /* Return a pointer to the value contained in V.  Also see VALget
    1919             :  * which returns a void *. */
    1920             : static inline const void *
    1921   303814241 : VALptr(const ValRecord *v)
    1922             : {
    1923   303814241 :         switch (ATOMstorage(v->vtype)) {
    1924      626316 :         case TYPE_void: return (const void *) &v->val.oval;
    1925           0 :         case TYPE_msk: return (const void *) &v->val.mval;
    1926    13628343 :         case TYPE_bte: return (const void *) &v->val.btval;
    1927     1219012 :         case TYPE_sht: return (const void *) &v->val.shval;
    1928   122665679 :         case TYPE_int: return (const void *) &v->val.ival;
    1929       13093 :         case TYPE_flt: return (const void *) &v->val.fval;
    1930      566498 :         case TYPE_dbl: return (const void *) &v->val.dval;
    1931    71067309 :         case TYPE_lng: return (const void *) &v->val.lval;
    1932             : #ifdef HAVE_HGE
    1933       16682 :         case TYPE_hge: return (const void *) &v->val.hval;
    1934             : #endif
    1935         770 :         case TYPE_uuid: return (const void *) &v->val.uval;
    1936      270170 :         case TYPE_ptr: return (const void *) &v->val.pval;
    1937    93737689 :         case TYPE_str: return (const void *) v->val.sval;
    1938        2680 :         default:       return (const void *) v->val.pval;
    1939             :         }
    1940             : }
    1941             : 
    1942             : #define THREADS         1024    /* maximum value for gdk_nr_threads */
    1943             : 
    1944             : gdk_export stream *GDKstdout;
    1945             : gdk_export stream *GDKstdin;
    1946             : 
    1947             : #define GDKerrbuf       (GDKgetbuf())
    1948             : 
    1949             : static inline bat
    1950   376158790 : BBPcheck(bat x)
    1951             : {
    1952   376158790 :         if (!is_bat_nil(x)) {
    1953   375667515 :                 assert(x > 0);
    1954             : 
    1955   375667515 :                 if (x < 0 || x >= getBBPsize() || BBP_logical(x) == NULL) {
    1956           0 :                         TRC_DEBUG(CHECK_, "range error %d\n", (int) x);
    1957             :                 } else {
    1958   375214296 :                         assert(BBP_pid(x) == 0 || BBP_pid(x) == MT_getpid());
    1959   375205579 :                         return x;
    1960             :                 }
    1961             :         }
    1962             :         return 0;
    1963             : }
    1964             : 
    1965             : gdk_export BAT *BATdescriptor(bat i);
    1966             : 
    1967             : static inline void *
    1968     7787696 : Tpos(BATiter *bi, BUN p)
    1969             : {
    1970     7787696 :         assert(bi->base == NULL);
    1971     7787696 :         if (bi->vh) {
    1972     1465129 :                 oid o;
    1973     1465129 :                 assert(!is_oid_nil(bi->tseq));
    1974     1465129 :                 if (((ccand_t *) bi->vh)->type == CAND_NEGOID) {
    1975     1465129 :                         BUN nexc = (bi->vhfree - sizeof(ccand_t)) / SIZEOF_OID;
    1976     1465129 :                         o = bi->tseq + p;
    1977     1465129 :                         if (nexc > 0) {
    1978     1465129 :                                 const oid *exc = (const oid *) (bi->vh->base + sizeof(ccand_t));
    1979     1465129 :                                 if (o >= exc[0]) {
    1980       12624 :                                         if (o + nexc > exc[nexc - 1]) {
    1981             :                                                 o += nexc;
    1982             :                                         } else {
    1983        3160 :                                                 BUN lo = 0;
    1984        3160 :                                                 BUN hi = nexc - 1;
    1985       25277 :                                                 while (hi - lo > 1) {
    1986       18957 :                                                         BUN mid = (hi + lo) / 2;
    1987       18957 :                                                         if (exc[mid] - mid > o)
    1988             :                                                                 hi = mid;
    1989             :                                                         else
    1990       10100 :                                                                 lo = mid;
    1991             :                                                 }
    1992        3160 :                                                 o += hi;
    1993             :                                         }
    1994             :                                 }
    1995             :                         }
    1996             :                 } else {
    1997           0 :                         const uint32_t *msk = (const uint32_t *) (bi->vh->base + sizeof(ccand_t));
    1998           0 :                         BUN nmsk = (bi->vhfree - sizeof(ccand_t)) / sizeof(uint32_t);
    1999           0 :                         o = 0;
    2000           0 :                         for (BUN i = 0; i < nmsk; i++) {
    2001           0 :                                 uint32_t m = candmask_pop(msk[i]);
    2002           0 :                                 if (o + m > p) {
    2003           0 :                                         m = msk[i];
    2004           0 :                                         for (i = 0; i < 32; i++) {
    2005           0 :                                                 if (m & (1U << i) && ++o == p)
    2006             :                                                         break;
    2007             :                                         }
    2008             :                                         break;
    2009             :                                 }
    2010           0 :                                 o += m;
    2011             :                         }
    2012             :                 }
    2013     1465129 :                 bi->tvid = o;
    2014     6322567 :         } else if (is_oid_nil(bi->tseq)) {
    2015           0 :                 bi->tvid = oid_nil;
    2016             :         } else {
    2017     6322567 :                 bi->tvid = bi->tseq + p;
    2018             :         }
    2019     7787696 :         return (void *) &bi->tvid;
    2020             : }
    2021             : 
    2022             : static inline bool
    2023         381 : Tmskval(BATiter *bi, BUN p)
    2024             : {
    2025         381 :         assert(ATOMstorage(bi->type) == TYPE_msk);
    2026         381 :         return ((uint32_t *) bi->base)[p / 32] & (1U << (p % 32));
    2027             : }
    2028             : 
    2029             : static inline void *
    2030         381 : Tmsk(BATiter *bi, BUN p)
    2031             : {
    2032         381 :         bi->tmsk = Tmskval(bi, p);
    2033         381 :         return &bi->tmsk;
    2034             : }
    2035             : 
    2036             : /* return the oid value at BUN position p from the (v)oid bat b
    2037             :  * works with any TYPE_void or TYPE_oid bat */
    2038             : static inline oid
    2039    22590525 : BUNtoid(BAT *b, BUN p)
    2040             : {
    2041    22590525 :         assert(ATOMtype(b->ttype) == TYPE_oid);
    2042             :         /* BATcount is the number of valid entries, so with
    2043             :          * exceptions, the last value can well be larger than
    2044             :          * b->tseqbase + BATcount(b) */
    2045    22590525 :         assert(p < BATcount(b));
    2046    22590525 :         assert(b->ttype == TYPE_void || b->tvheap == NULL);
    2047    22590525 :         if (is_oid_nil(b->tseqbase)) {
    2048    22053580 :                 if (b->ttype == TYPE_void)
    2049           0 :                         return oid_nil;
    2050    22053580 :                 MT_lock_set(&b->theaplock);
    2051    21513012 :                 oid o = ((const oid *) b->theap->base)[p + b->tbaseoff];
    2052    21513012 :                 MT_lock_unset(&b->theaplock);
    2053    20997687 :                 return o;
    2054             :         }
    2055      536945 :         if (b->ttype == TYPE_oid || b->tvheap == NULL) {
    2056      523713 :                 return b->tseqbase + p;
    2057             :         }
    2058             :         /* b->tvheap != NULL, so we know there will be no parallel
    2059             :          * modifications (so no locking) */
    2060       13232 :         BATiter bi = bat_iterator_nolock(b);
    2061       13232 :         return * (oid *) Tpos(&bi, p);
    2062             : }
    2063             : 
    2064             : /*
    2065             :  * @+ Transaction Management
    2066             :  */
    2067             : gdk_export gdk_return TMsubcommit_list(bat *restrict subcommit, BUN *restrict sizes, int cnt, lng logno)
    2068             :         __attribute__((__warn_unused_result__));
    2069             : 
    2070             : /*
    2071             :  * @- Delta Management
    2072             :  *  @multitable @columnfractions 0.08 0.6
    2073             :  * @item BAT *
    2074             :  * @tab BATcommit (BAT *b)
    2075             :  * @end multitable
    2076             :  *
    2077             :  * The BAT keeps track of updates with respect to a 'previous state'.
    2078             :  * Do not confuse 'previous state' with 'stable' or 'commited-on-disk',
    2079             :  * because these concepts are not always the same. In particular, they
    2080             :  * diverge when BATcommit and BATfakecommit are called explicitly,
    2081             :  * bypassing the normal global TMcommit protocol (some applications need
    2082             :  * that flexibility).
    2083             :  *
    2084             :  * BATcommit make the current BAT state the new 'stable state'.  This
    2085             :  * happens inside the global TMcommit on all persistent BATs previous
    2086             :  * to writing all bats to persistent storage using a BBPsync.
    2087             :  */
    2088             : gdk_export void BATcommit(BAT *b, BUN size);
    2089             : 
    2090             : /*
    2091             :  * @+ BAT Alignment and BAT views
    2092             :  * @multitable @columnfractions 0.08 0.7
    2093             :  * @item int
    2094             :  * @tab ALIGNsynced (BAT* b1, BAT* b2)
    2095             :  * @item int
    2096             :  * @tab ALIGNsync   (BAT *b1, BAT *b2)
    2097             :  * @item int
    2098             :  * @tab ALIGNrelated (BAT *b1, BAT *b2)
    2099             :  *
    2100             :  * @item BAT*
    2101             :  * @tab VIEWcreate   (oid seq, BAT *b, BUN lo, BUN hi)
    2102             :  * @item int
    2103             :  * @tab isVIEW   (BAT *b)
    2104             :  * @item bat
    2105             :  * @tab VIEWhparent   (BAT *b)
    2106             :  * @item bat
    2107             :  * @tab VIEWtparent   (BAT *b)
    2108             :  * @end multitable
    2109             :  *
    2110             :  * Alignments of two columns of a BAT means that the system knows
    2111             :  * whether these two columns are exactly equal. Relatedness of two
    2112             :  * BATs means that one pair of columns (either head or tail) of both
    2113             :  * BATs is aligned. The first property is checked by ALIGNsynced, the
    2114             :  * latter by ALIGNrelated.
    2115             :  *
    2116             :  * All algebraic BAT commands propagate the properties - including
    2117             :  * alignment properly on their results.
    2118             :  *
    2119             :  * VIEW BATs are BATs that lend their storage from a parent BAT.  They
    2120             :  * are just a descriptor that points to the data in this parent BAT. A
    2121             :  * view is created with VIEWcreate. The cache id of the parent (if
    2122             :  * any) is returned by VIEWtparent (otherwise it returns 0).
    2123             :  *
    2124             :  * VIEW bats are read-only!!
    2125             :  */
    2126             : gdk_export int ALIGNsynced(BAT *b1, BAT *b2);
    2127             : 
    2128             : gdk_export void BATassertProps(BAT *b);
    2129             : 
    2130             : gdk_export BAT *VIEWcreate(oid seq, BAT *b, BUN l, BUN h);
    2131             : gdk_export void VIEWbounds(BAT *b, BAT *view, BUN l, BUN h);
    2132             : 
    2133             : #define ALIGNapp(x, f, e)                                               \
    2134             :         do {                                                            \
    2135             :                 if (!(f)) {                                             \
    2136             :                         MT_lock_set(&(x)->theaplock);                    \
    2137             :                         if ((x)->batRestricted == BAT_READ ||                \
    2138             :                            ((ATOMIC_GET(&(x)->theap->refs) & HEAPREFS) > 1)) { \
    2139             :                                 GDKerror("access denied to %s, aborting.\n", BATgetId(x)); \
    2140             :                                 MT_lock_unset(&(x)->theaplock);          \
    2141             :                                 return (e);                             \
    2142             :                         }                                               \
    2143             :                         MT_lock_unset(&(x)->theaplock);                  \
    2144             :                 }                                                       \
    2145             :         } while (false)
    2146             : 
    2147             : /*
    2148             :  * @+ BAT Iterators
    2149             :  *  @multitable @columnfractions 0.15 0.7
    2150             :  * @item BATloop
    2151             :  * @tab
    2152             :  *  (BAT *b; BUN p, BUN q)
    2153             :  * @item BATloopDEL
    2154             :  * @tab
    2155             :  *  (BAT *b; BUN p; BUN q; int dummy)
    2156             :  * @item HASHloop
    2157             :  * @tab
    2158             :  *  (BAT *b; Hash *h, size_t dummy; ptr value)
    2159             :  * @item HASHloop_bte
    2160             :  * @tab
    2161             :  *  (BAT *b; Hash *h, size_t idx; bte *value, BUN w)
    2162             :  * @item HASHloop_sht
    2163             :  * @tab
    2164             :  *  (BAT *b; Hash *h, size_t idx; sht *value, BUN w)
    2165             :  * @item HASHloop_int
    2166             :  * @tab
    2167             :  *  (BAT *b; Hash *h, size_t idx; int *value, BUN w)
    2168             :  * @item HASHloop_flt
    2169             :  * @tab
    2170             :  *  (BAT *b; Hash *h, size_t idx; flt *value, BUN w)
    2171             :  * @item HASHloop_lng
    2172             :  * @tab
    2173             :  *  (BAT *b; Hash *h, size_t idx; lng *value, BUN w)
    2174             :  * @item HASHloop_hge
    2175             :  * @tab
    2176             :  *  (BAT *b; Hash *h, size_t idx; hge *value, BUN w)
    2177             :  * @item HASHloop_dbl
    2178             :  * @tab
    2179             :  *  (BAT *b; Hash *h, size_t idx; dbl *value, BUN w)
    2180             :  * @item  HASHloop_str
    2181             :  * @tab
    2182             :  *  (BAT *b; Hash *h, size_t idx; str value, BUN w)
    2183             :  * @item HASHlooploc
    2184             :  * @tab
    2185             :  *  (BAT *b; Hash *h, size_t idx; ptr value, BUN w)
    2186             :  * @item HASHloopvar
    2187             :  * @tab
    2188             :  *  (BAT *b; Hash *h, size_t idx; ptr value, BUN w)
    2189             :  * @end multitable
    2190             :  *
    2191             :  * The @emph{BATloop()} looks like a function call, but is actually a
    2192             :  * macro.
    2193             :  *
    2194             :  * @- simple sequential scan
    2195             :  * The first parameter is a BAT, the p and q are BUN pointers, where p
    2196             :  * is the iteration variable.
    2197             :  */
    2198             : #define BATloop(r, p, q)                                \
    2199             :         for (q = BATcount(r), p = 0; p < q; p++)
    2200             : 
    2201             : /*
    2202             :  * @+ Common BAT Operations
    2203             :  * Much used, but not necessarily kernel-operations on BATs.
    2204             :  *
    2205             :  * For each BAT we maintain its dimensions as separately accessible
    2206             :  * properties. They can be used to improve query processing at higher
    2207             :  * levels.
    2208             :  */
    2209             : enum prop_t {
    2210             :         GDK_MIN_BOUND, /* MINimum allowed value for range partitions [min, max> */
    2211             :         GDK_MAX_BOUND, /* MAXimum of the range partitions [min, max>, ie. excluding this max value */
    2212             :         GDK_NOT_NULL,  /* bat bound to be not null */
    2213             :         /* CURRENTLY_NO_PROPERTIES_DEFINED, */
    2214             : };
    2215             : 
    2216             : gdk_export ValPtr BATgetprop(BAT *b, enum prop_t idx);
    2217             : gdk_export ValPtr BATgetprop_nolock(BAT *b, enum prop_t idx);
    2218             : gdk_export void BATrmprop(BAT *b, enum prop_t idx);
    2219             : gdk_export void BATrmprop_nolock(BAT *b, enum prop_t idx);
    2220             : gdk_export ValPtr BATsetprop(BAT *b, enum prop_t idx, int type, const void *v);
    2221             : gdk_export ValPtr BATsetprop_nolock(BAT *b, enum prop_t idx, int type, const void *v);
    2222             : 
    2223             : /*
    2224             :  * @- BAT relational operators
    2225             :  *
    2226             :  * The full-materialization policy intermediate results in MonetDB
    2227             :  * means that a join can produce an arbitrarily large result and choke
    2228             :  * the system. The Data Distilleries tool therefore first computes the
    2229             :  * join result size before the actual join (better waste time than
    2230             :  * crash the server). To exploit that perfect result size knowledge,
    2231             :  * an result-size estimate parameter was added to all equi-join
    2232             :  * implementations.  TODO: add this for
    2233             :  * semijoin/select/unique/diff/intersect
    2234             :  *
    2235             :  * @- modes for thethajoin
    2236             :  */
    2237             : #define JOIN_EQ         0
    2238             : #define JOIN_LT         (-1)
    2239             : #define JOIN_LE         (-2)
    2240             : #define JOIN_GT         1
    2241             : #define JOIN_GE         2
    2242             : #define JOIN_BAND       3
    2243             : #define JOIN_NE         (-3)
    2244             : 
    2245             : gdk_export BAT *BATselect(BAT *b, BAT *s, const void *tl, const void *th, bool li, bool hi, bool anti, bool nil_matches);
    2246             : gdk_export BAT *BATthetaselect(BAT *b, BAT *s, const void *val, const char *op);
    2247             : 
    2248             : gdk_export BAT *BATconstant(oid hseq, int tt, const void *val, BUN cnt, role_t role);
    2249             : gdk_export gdk_return BATsubcross(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, bool max_one)
    2250             :         __attribute__((__warn_unused_result__));
    2251             : gdk_export gdk_return BAToutercross(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, bool max_one)
    2252             :         __attribute__((__warn_unused_result__));
    2253             : 
    2254             : gdk_export gdk_return BATleftjoin(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, bool nil_matches, BUN estimate)
    2255             :         __attribute__((__warn_unused_result__));
    2256             : gdk_export gdk_return BATmarkjoin(BAT **r1p, BAT **r2p, BAT **r3p, BAT *l, BAT *r, BAT *sl, BAT *sr, BUN estimate)
    2257             :         __attribute__((__warn_unused_result__));
    2258             : 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)
    2259             :         __attribute__((__warn_unused_result__));
    2260             : gdk_export gdk_return BATthetajoin(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, int op, bool nil_matches, BUN estimate)
    2261             :         __attribute__((__warn_unused_result__));
    2262             : 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)
    2263             :         __attribute__((__warn_unused_result__));
    2264             : gdk_export BAT *BATintersect(BAT *l, BAT *r, BAT *sl, BAT *sr, bool nil_matches, bool max_one, BUN estimate);
    2265             : gdk_export BAT *BATdiff(BAT *l, BAT *r, BAT *sl, BAT *sr, bool nil_matches, bool not_in, BUN estimate);
    2266             : gdk_export gdk_return BATjoin(BAT **r1p, BAT **r2p, BAT *l, BAT *r, BAT *sl, BAT *sr, bool nil_matches, BUN estimate)
    2267             :         __attribute__((__warn_unused_result__));
    2268             : gdk_export BUN BATguess_uniques(BAT *b, struct canditer *ci);
    2269             : 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)
    2270             :         __attribute__((__warn_unused_result__));
    2271             : 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)
    2272             :         __attribute__((__warn_unused_result__));
    2273             : gdk_export BAT *BATproject(BAT *restrict l, BAT *restrict r);
    2274             : gdk_export BAT *BATproject2(BAT *restrict l, BAT *restrict r1, BAT *restrict r2);
    2275             : gdk_export BAT *BATprojectchain(BAT **bats);
    2276             : 
    2277             : gdk_export BAT *BATslice(BAT *b, BUN low, BUN high);
    2278             : 
    2279             : gdk_export BAT *BATunique(BAT *b, BAT *s);
    2280             : 
    2281             : gdk_export gdk_return BATfirstn(BAT **topn, BAT **gids, BAT *b, BAT *cands, BAT *grps, BUN n, bool asc, bool nilslast, bool distinct)
    2282             :         __attribute__((__warn_unused_result__));
    2283             : 
    2284             : #include "gdk_calc.h"
    2285             : 
    2286             : gdk_export gdk_return GDKtoupper(char **restrict buf, size_t *restrict buflen, const char *restrict s);
    2287             : gdk_export gdk_return GDKtolower(char **restrict buf, size_t *restrict buflen, const char *restrict s);
    2288             : gdk_export gdk_return GDKcasefold(char **restrict buf, size_t *restrict buflen, const char *restrict s);
    2289             : gdk_export int GDKstrncasecmp(const char *str1, const char *str2, size_t l1, size_t l2);
    2290             : gdk_export int GDKstrcasecmp(const char *s1, const char *s2);
    2291             : gdk_export char *GDKstrcasestr(const char *haystack, const char *needle);
    2292             : gdk_export BAT *BATtoupper(BAT *b, BAT *s);
    2293             : gdk_export BAT *BATtolower(BAT *b, BAT *s);
    2294             : gdk_export BAT *BATcasefold(BAT *b, BAT *s);
    2295             : gdk_export gdk_return GDKasciify(char **restrict buf, size_t *restrict buflen, const char *restrict s);
    2296             : gdk_export BAT *BATasciify(BAT *b, BAT *s);
    2297             : 
    2298             : /*
    2299             :  * @- BAT sample operators
    2300             :  *
    2301             :  * @multitable @columnfractions 0.08 0.7
    2302             :  * @item BAT *
    2303             :  * @tab BATsample (BAT *b, n)
    2304             :  * @end multitable
    2305             :  *
    2306             :  * The routine BATsample returns a random sample on n BUNs of a BAT.
    2307             :  *
    2308             :  */
    2309             : gdk_export BAT *BATsample(BAT *b, BUN n);
    2310             : gdk_export BAT *BATsample_with_seed(BAT *b, BUN n, uint64_t seed);
    2311             : 
    2312             : /*
    2313             :  *
    2314             :  */
    2315             : #define MAXPARAMS       32
    2316             : 
    2317             : #define CHECK_QRY_TIMEOUT_SHIFT 14
    2318             : #define CHECK_QRY_TIMEOUT_STEP  (1 << CHECK_QRY_TIMEOUT_SHIFT)
    2319             : #define CHECK_QRY_TIMEOUT_MASK  (CHECK_QRY_TIMEOUT_STEP - 1)
    2320             : 
    2321             : #define TIMEOUT_MSG "Timeout was reached!"
    2322             : #define INTERRUPT_MSG "Query interrupted!"
    2323             : #define DISCONNECT_MSG "Client is disconnected!"
    2324             : #define EXITING_MSG "Server is exiting!"
    2325             : 
    2326             : #define QRY_TIMEOUT (-1)        /* query timed out */
    2327             : #define QRY_INTERRUPT (-2)      /* client indicated interrupt */
    2328             : #define QRY_DISCONNECT (-3)     /* client disconnected */
    2329             : 
    2330             : static const char *
    2331           3 : TIMEOUT_MESSAGE(QryCtx *qc)
    2332             : {
    2333           3 :         if (GDKexiting())
    2334             :                 return EXITING_MSG;
    2335           3 :         if (qc) {
    2336           3 :                 switch (qc->endtime) {
    2337             :                 case QRY_TIMEOUT:
    2338             :                         return TIMEOUT_MSG;
    2339           0 :                 case QRY_INTERRUPT:
    2340           0 :                         return INTERRUPT_MSG;
    2341           0 :                 case QRY_DISCONNECT:
    2342           0 :                         return DISCONNECT_MSG;
    2343             :                 default:
    2344           0 :                         MT_UNREACHABLE();
    2345             :                 }
    2346             :         }
    2347             :         return NULL;
    2348             : }
    2349             : 
    2350             : static inline void
    2351           3 : TIMEOUT_ERROR(QryCtx *qc, const char *file, const char *func, int lineno)
    2352             : {
    2353           3 :         const char *e = TIMEOUT_MESSAGE(qc);
    2354           3 :         if (e) {
    2355           3 :                 GDKtracer_log(file, func, lineno, M_ERROR, GDK, NULL,
    2356             :                               "%s\n", e);
    2357             :         }
    2358           3 : }
    2359             : 
    2360             : #define TIMEOUT_HANDLER(rtpe, qc)                                       \
    2361             :         do {                                                            \
    2362             :                 TIMEOUT_ERROR(qc, __FILE__, __func__, __LINE__);        \
    2363             :                 return rtpe;                                            \
    2364             :         } while(0)
    2365             : 
    2366             : static inline bool
    2367     9862029 : TIMEOUT_TEST(QryCtx *qc)
    2368             : {
    2369     9862029 :         if (qc == NULL)
    2370             :                 return false;
    2371     9862202 :         if (qc->endtime < 0)
    2372             :                 return true;
    2373     9862200 :         if (qc->endtime && GDKusec() > qc->endtime) {
    2374           3 :                 qc->endtime = QRY_TIMEOUT;
    2375           3 :                 return true;
    2376             :         }
    2377     9862197 :         switch (bstream_getoob(qc->bs)) {
    2378           0 :         case -1:
    2379           0 :                 qc->endtime = QRY_DISCONNECT;
    2380           0 :                 return true;
    2381             :         case 0:
    2382             :                 return false;
    2383           0 :         default:
    2384           0 :                 qc->endtime = QRY_INTERRUPT;
    2385           0 :                 return true;
    2386             :         }
    2387             : }
    2388             : 
    2389             : #define GOTO_LABEL_TIMEOUT_HANDLER(label, qc)                           \
    2390             :         do {                                                            \
    2391             :                 TIMEOUT_ERROR(qc, __FILE__, __func__, __LINE__);        \
    2392             :                 goto label;                                             \
    2393             :         } while(0)
    2394             : 
    2395             : #define GDK_CHECK_TIMEOUT_BODY(qc, callback)            \
    2396             :         do {                                            \
    2397             :                 if (GDKexiting() || TIMEOUT_TEST(qc)) { \
    2398             :                         callback;                       \
    2399             :                 }                                       \
    2400             :         } while (0)
    2401             : 
    2402             : #define GDK_CHECK_TIMEOUT(qc, counter, callback)                \
    2403             :         do {                                                    \
    2404             :                 if (counter > CHECK_QRY_TIMEOUT_STEP) {              \
    2405             :                         GDK_CHECK_TIMEOUT_BODY(qc, callback);   \
    2406             :                         counter = 0;                            \
    2407             :                 } else {                                        \
    2408             :                         counter++;                              \
    2409             :                 }                                               \
    2410             :         } while (0)
    2411             : 
    2412             : /* here are some useful constructs to iterate a number of times (the
    2413             :  * REPEATS argument--only evaluated once) and checking for a timeout
    2414             :  * every once in a while; the QC->endtime value is a variable of type lng
    2415             :  * which is either 0 or the GDKusec() compatible time after which the
    2416             :  * loop should terminate; check for this condition after the loop using
    2417             :  * the TIMEOUT_CHECK macro; in order to break out of any of these loops,
    2418             :  * use TIMEOUT_LOOP_BREAK since plain break won't do it; it is perfectly
    2419             :  * ok to use continue inside the body */
    2420             : 
    2421             : /* use IDX as a loop variable (already declared), initializing it to 0
    2422             :  * and incrementing it on each iteration */
    2423             : #define TIMEOUT_LOOP_IDX(IDX, REPEATS, QC)                              \
    2424             :         for (BUN REPS = (IDX = 0, (REPEATS)); REPS > 0; REPS = 0) /* "loops" at most once */ \
    2425             :                 for (BUN CTR1 = 0, END1 = (REPS + CHECK_QRY_TIMEOUT_STEP) >> CHECK_QRY_TIMEOUT_SHIFT; CTR1 < END1 && !GDKexiting() && ((QC) == NULL || (QC)->endtime >= 0); CTR1++) \
    2426             :                         if (CTR1 > 0 && TIMEOUT_TEST(QC)) {          \
    2427             :                                 break;                                  \
    2428             :                         } else                                          \
    2429             :                                 for (BUN CTR2 = 0, END2 = CTR1 == END1 - 1 ? REPS & CHECK_QRY_TIMEOUT_MASK : CHECK_QRY_TIMEOUT_STEP; CTR2 < END2; CTR2++, IDX++)
    2430             : 
    2431             : /* declare and use IDX as a loop variable, initializing it to 0 and
    2432             :  * incrementing it on each iteration */
    2433             : #define TIMEOUT_LOOP_IDX_DECL(IDX, REPEATS, QC)                         \
    2434             :         for (BUN IDX = 0, REPS = (REPEATS); REPS > 0; REPS = 0) /* "loops" at most once */ \
    2435             :                 for (BUN CTR1 = 0, END1 = (REPS + CHECK_QRY_TIMEOUT_STEP) >> CHECK_QRY_TIMEOUT_SHIFT; CTR1 < END1 && !GDKexiting() && ((QC) == NULL || (QC)->endtime >= 0); CTR1++) \
    2436             :                         if (CTR1 > 0 && TIMEOUT_TEST(QC)) {          \
    2437             :                                 break;                                  \
    2438             :                         } else                                          \
    2439             :                                 for (BUN CTR2 = 0, END2 = CTR1 == END1 - 1 ? REPS & CHECK_QRY_TIMEOUT_MASK : CHECK_QRY_TIMEOUT_STEP; CTR2 < END2; CTR2++, IDX++)
    2440             : 
    2441             : /* there is no user-visible loop variable */
    2442             : #define TIMEOUT_LOOP(REPEATS, QC)                                       \
    2443             :         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++) \
    2444             :                 if (CTR1 > 0 && TIMEOUT_TEST(QC)) {                  \
    2445             :                         break;                                          \
    2446             :                 } else                                                  \
    2447             :                         for (BUN CTR2 = 0, END2 = CTR1 == END1 - 1 ? REPS & CHECK_QRY_TIMEOUT_MASK : CHECK_QRY_TIMEOUT_STEP; CTR2 < END2; CTR2++)
    2448             : 
    2449             : /* break out of the loop (cannot use do/while trick here) */
    2450             : #define TIMEOUT_LOOP_BREAK                      \
    2451             :         {                                       \
    2452             :                 END1 = END2 = 0;                \
    2453             :                 continue;                       \
    2454             :         }
    2455             : 
    2456             : /* check whether a timeout occurred, and execute the CALLBACK argument
    2457             :  * if it did */
    2458             : #define TIMEOUT_CHECK(QC, CALLBACK)                                     \
    2459             :         do {                                                            \
    2460             :                 if (GDKexiting() || ((QC) && (QC)->endtime < 0))  \
    2461             :                         CALLBACK;                                       \
    2462             :         } while (0)
    2463             : 
    2464             : typedef struct gdk_callback {
    2465             :         char *name;
    2466             :         int argc;
    2467             :         int interval;  // units sec
    2468             :         lng last_called; // timestamp GDKusec
    2469             :         gdk_return (*func)(int argc, void *argv[]);
    2470             :         struct gdk_callback *next;
    2471             :         void *argv[];
    2472             : } gdk_callback;
    2473             : 
    2474             : typedef gdk_return gdk_callback_func(int argc, void *argv[]);
    2475             : 
    2476             : gdk_export gdk_return gdk_add_callback(char *name, gdk_callback_func *f, int argc, void
    2477             :                 *argv[], int interval);
    2478             : gdk_export gdk_return gdk_remove_callback(char *, gdk_callback_func *f);
    2479             : 
    2480             : 
    2481             : #include <setjmp.h>
    2482             : 
    2483             : typedef struct exception_buffer {
    2484             : #ifdef HAVE_SIGLONGJMP
    2485             :         sigjmp_buf state;
    2486             : #else
    2487             :         jmp_buf state;
    2488             : #endif
    2489             :         int code;
    2490             :         char *msg;
    2491             :         int enabled;
    2492             : } exception_buffer;
    2493             : 
    2494             : gdk_export exception_buffer *eb_init(exception_buffer *eb);
    2495             : 
    2496             : /* != 0 on when we return to the savepoint */
    2497             : #ifdef HAVE_SIGLONGJMP
    2498             : #define eb_savepoint(eb) ((eb)->enabled = 1, sigsetjmp((eb)->state, 0))
    2499             : #else
    2500             : #define eb_savepoint(eb) ((eb)->enabled = 1, setjmp((eb)->state))
    2501             : #endif
    2502             : gdk_export _Noreturn void eb_error(exception_buffer *eb, char *msg, int val);
    2503             : 
    2504             : typedef struct allocator {
    2505             :         struct allocator *pa;
    2506             :         size_t size;
    2507             :         size_t nr;
    2508             :         char **blks;
    2509             :         size_t used;    /* memory used in last block */
    2510             :         size_t usedmem; /* used memory */
    2511             :         void *freelist; /* list of freed blocks */
    2512             :         exception_buffer eb;
    2513             : } allocator;
    2514             : 
    2515             : gdk_export allocator *sa_create( allocator *pa );
    2516             : gdk_export allocator *sa_reset( allocator *sa );
    2517             : gdk_export void *sa_alloc( allocator *sa,  size_t sz );
    2518             : gdk_export void *sa_zalloc( allocator *sa,  size_t sz );
    2519             : gdk_export void *sa_realloc( allocator *sa,  void *ptr, size_t sz, size_t osz );
    2520             : gdk_export void sa_destroy( allocator *sa );
    2521             : gdk_export char *sa_strndup( allocator *sa, const char *s, size_t l);
    2522             : gdk_export char *sa_strdup( allocator *sa, const char *s);
    2523             : gdk_export char *sa_strconcat( allocator *sa, const char *s1, const char *s2);
    2524             : gdk_export size_t sa_size( allocator *sa );
    2525             : 
    2526             : #if !defined(NDEBUG) && !defined(__COVERITY__) && defined(__GNUC__)
    2527             : #define sa_alloc(sa, sz)                                        \
    2528             :         ({                                                      \
    2529             :                 allocator *_sa = (sa);                          \
    2530             :                 size_t _sz = (sz);                              \
    2531             :                 void *_res = sa_alloc(_sa, _sz);                \
    2532             :                 TRC_DEBUG(ALLOC,                                \
    2533             :                                 "sa_alloc(%p,%zu) -> %p\n",        \
    2534             :                                 _sa, _sz, _res);                \
    2535             :                 _res;                                           \
    2536             :         })
    2537             : #define sa_zalloc(sa, sz)                                       \
    2538             :         ({                                                      \
    2539             :                 allocator *_sa = (sa);                          \
    2540             :                 size_t _sz = (sz);                              \
    2541             :                 void *_res = sa_zalloc(_sa, _sz);               \
    2542             :                 TRC_DEBUG(ALLOC,                                \
    2543             :                                 "sa_zalloc(%p,%zu) -> %p\n",       \
    2544             :                                 _sa, _sz, _res);                \
    2545             :                 _res;                                           \
    2546             :         })
    2547             : #define sa_realloc(sa, ptr, sz, osz)                                    \
    2548             :         ({                                                              \
    2549             :                 allocator *_sa = (sa);                                  \
    2550             :                 void *_ptr = (ptr);                                     \
    2551             :                 size_t _sz = (sz);                                      \
    2552             :                 size_t _osz = (osz);                                    \
    2553             :                 void *_res = sa_realloc(_sa, _ptr, _sz, _osz);          \
    2554             :                 TRC_DEBUG(ALLOC,                                        \
    2555             :                                 "sa_realloc(%p,%p,%zu,%zu) -> %p\n",       \
    2556             :                                 _sa, _ptr, _sz, _osz, _res);            \
    2557             :                 _res;                                                   \
    2558             :         })
    2559             : #define sa_strdup(sa, s)                                                \
    2560             :         ({                                                              \
    2561             :                 allocator *_sa = (sa);                                  \
    2562             :                 const char *_s = (s);                                   \
    2563             :                 char *_res = sa_strdup(_sa, _s);                        \
    2564             :                 TRC_DEBUG(ALLOC,                                        \
    2565             :                                 "sa_strdup(%p,len=%zu) -> %p\n",   \
    2566             :                                 _sa, strlen(_s), _res);                 \
    2567             :                 _res;                                                   \
    2568             :         })
    2569             : #define sa_strndup(sa, s, l)                                            \
    2570             :         ({                                                              \
    2571             :                 allocator *_sa = (sa);                                  \
    2572             :                 const char *_s = (s);                                   \
    2573             :                 size_t _l = (l);                                        \
    2574             :                 char *_res = sa_strndup(_sa, _s, _l);                   \
    2575             :                 TRC_DEBUG(ALLOC,                                        \
    2576             :                                 "sa_strndup(%p,len=%zu) -> %p\n",  \
    2577             :                                 _sa, _l, _res);                         \
    2578             :                 _res;                                                   \
    2579             :         })
    2580             : #endif
    2581             : 
    2582             : #endif /* _GDK_H_ */

Generated by: LCOV version 1.14