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

Generated by: LCOV version 1.14