What it is
libstorelib is the client library of the
ADP software stack. A program links it and uses the ADP card
directly as a key-value store through C functions, for example the storage manager of a database. The program writes
a value under a key, reads the value back by the key, and deletes the key.
The library has two sets of calls. This page describes both.
| Calls | What they do | Where on this page |
|---|---|---|
The synchronous calls: ADP_OpenDB, ADP_Put, ADP_Get and others | Open and close card databases. Read, write and delete one key with one call. | From card databases to the rules and limits |
adp_aio: the functions adp_aio_* | One process, with no extra threads, keeps tens of requests in flight at the card. | Many requests in flight |
Start with the synchronous calls, also when you plan to use adp_aio: an adp_aio request goes to a card database
that the program opens with ADP_OpenDB.
Requirements
For every program on this page:
- The host of the card. The program runs on the server that has the ADP card and the ADP software stack. The
library talks to the card device
/dev/adp<N>and to the storage service of the card,adpstore@<N>, on the same host.Nis the number of the card:0for/dev/adp0andadpstore@0. - The storage service active, in key-value mode:
product_type = 0(configure the storage service). To check the service, runsystemctl status adpstore@0, thenadpcli system is_ready -x 0. - The header and the library. The installer of the stack puts them in
/etc/adp: the headerstore_lib_expo.h, the shared librarylibstorelib.so, and the logging librarylibzlog.sothatlibstorelibneeds. The installer also registers/etc/adpwith the dynamic loader, so a program finds the library at run time. Link with-lstorelib. - Access. Run the program as root, or give its user write access to
/etc/adp/storelib_log.confand to the log directory/var/log/adp. The process also needs access to the card device/dev/adp0.
The library logs every open, every close and every error to /var/log/adp/storelib.log. Two environment variables
change the place: STORELIB_ADP_LOG_CONF is the path of another log configuration file, and STORELIB_LOG_FILE_PATH
is another log directory.
For adp_aio only:
- A kernel with io_uring that does not lose wake-ups
(kernel for
adp_aio). - The card driver of the ADP software stack with the asynchronous path: then
/sys/module/adp/parameters/adp_uring_statsexists.
Card databases
A card database is a separate key-value namespace on the card. Its name is a number that your application chooses,
the identify parameter of type ADP_IDENTIFY_t (an unsigned long).
- Two programs that open the same number on the same card work with the same database.
- Keys of different databases do not collide: two databases can hold the same key with different values.
- A card holds up to 4096 databases.
- A database and its keys stay on the card when the program closes it.
- There is no call that lists the keys of a database.
Choose a number that nothing else uses. The storage gateway of the KV cache keeps its own databases on the same
card. To check a number, call ADP_GetDBInfo: it returns ADP_STATUS_NON_EXIST for a number that is free. The usage
report of the card, adpcli system get_disk_usage -x 0, shows how many databases the card holds, for example
Number of databases : 176 / 4096 (0 deleting).
IMPORTANT
Decide whether the card is a cache or the main storage of your data. With key eviction on, the card frees space by
itself: it can drop any old key of any database, also the keys of your application. Key eviction is on by default
in key-value mode, and the KV cache requires it. A card that must keep every key runs with key_eviction = false
(configure the storage service). Then a full card refuses writes
with ADP_STATUS_OUT_OF_SPACE until you delete keys or databases.
Your first program
The example kv_demo.c opens a database on card 0 and writes one key with ADP_Put. Then it reads the key back
with ADP_Get, asks for it with ADP_Exist, deletes it with ADP_Delete and closes the database. With the argument
--delete-db it also removes the database from the card (deleting a database).
/*
* kv_demo.c - a first program for the ADP card.
*
* It opens a card database, writes a key, reads it back, deletes it and closes the database.
* With the argument --delete-db it also removes the database from the card.
*/
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include "store_lib_expo.h"
#define CARD_ID 0 /* the card: /dev/adp0, storage service adpstore@0 */
#define DB_IDENTIFY 0x6b7664656d6fUL /* the number of this database on the card */
/* Report a call that failed. Returns true when it failed. */
static bool failed(const char *call, ADP_STATUS_et status)
{
if (status == ADP_STATUS_OK)
return false;
fprintf(stderr, "%s: status %d\n", call, (int)status);
return true;
}
int main(int argc, char **argv)
{
bool delete_db = argc > 1 && strcmp(argv[1], "--delete-db") == 0;
ADP_DB_OPEN_OPTIONS_t open_options = { .createIfMissing = true };
ADP_DB_t db;
ADP_STATUS_et status;
char key[] = "user:1001";
char value[] = "Ada Lovelace";
char buffer[64];
unsigned int size = 0;
int result = 1;
/* 1. Open the database. The card creates it at the first open. */
status = ADP_OpenDB(DB_IDENTIFY, &open_options, CARD_ID, &db);
if (failed("ADP_OpenDB", status))
return 1;
/* 2. Write a key. With SYNC the call returns when the card has the value. */
status = ADP_Put(db, key, strlen(key), value, sizeof value, ADP_OPTION_MASK_SYNC);
if (failed("ADP_Put", status))
goto out;
printf("put %s = %s\n", key, value);
/* 3. Read it back. size is the size of the stored value. */
status = ADP_Get(db, key, strlen(key), buffer, sizeof buffer, &size);
if (failed("ADP_Get", status))
goto out;
printf("get %s = %s (%u bytes)\n", key, buffer, size);
/* 4. Ask whether a key exists, without reading the value. */
status = ADP_Exist(db, key, strlen(key));
printf("exist %s: %s\n", key, status == ADP_STATUS_OK ? "yes" : "no");
/* 5. Delete the key. A read of it now returns ADP_STATUS_NON_EXIST. */
status = ADP_Delete(db, key, strlen(key), ADP_OPTION_MASK_SYNC);
if (failed("ADP_Delete", status))
goto out;
status = ADP_Get(db, key, strlen(key), buffer, sizeof buffer, &size);
printf("delete %s: %s\n", key, status == ADP_STATUS_NON_EXIST ? "gone" : "still there");
result = 0;
out:
/* 6. Close the database. The database and its keys stay on the card. */
if (failed("ADP_CloseDB", ADP_CloseDB(db)))
return 1;
/* 7. On request, remove the database and all its keys from the card. */
if (result == 0 && delete_db) {
ADP_DB_DELETE_OPTIONS_t delete_options = { .errorIfMissing = true };
if (failed("ADP_DeleteDB", ADP_DeleteDB(DB_IDENTIFY, &delete_options, CARD_ID)))
return 1;
printf("database 0x%lx removed\n", DB_IDENTIFY);
}
return result;
}
Build the example
Build on the host of the card:
gcc -O2 -Wall -Wextra -I/etc/adp -o kv_demo kv_demo.c -L/etc/adp -Wl,-rpath,/etc/adp -lstorelib
| Option | Why |
|---|---|
-I/etc/adp | The directory of the header store_lib_expo.h. |
-L/etc/adp -lstorelib | The shared library libstorelib.so. |
-Wl,-rpath,/etc/adp | Writes the directory of the library into the program. The program also finds the library without this option, because the installer registers /etc/adp with the dynamic loader. |
- C dialect. Use the default dialect of gcc, or
-std=gnu11or-std=gnu17. The header uses the typeuint, which glibc declares only in the GNU dialects. With-std=c11or-std=c99the build stops withstore_lib_expo.h: error: unknown type name 'uint'. - C++. The header has
extern "C", so a C++ program can include it. - Threads. Add
-lpthreadonly when your program itself uses threads. - Static linking. Link the shared library. The static archive
/etc/adp/libstorelib.adoes not link alone: it needs more system libraries.
Run the example
Run the program as root (requirements):
./kv_demo
put user:1001 = Ada Lovelace
get user:1001 = Ada Lovelace (13 bytes)
exist user:1001: yes
delete user:1001: gone
The output is the same on the first run, when the card creates the database, and on every later run. The value has
13 bytes because the example writes the string together with its end byte (sizeof value).
When a call fails, the example prints the name of the call and the status as a number, for example
ADP_OpenDB: status 15. The table in what a call returns explains the numbers.
After the run, the database 0x6b7664656d6f stays on the card.
The synchronous calls
The header store_lib_expo.h declares the calls. Each call except ADP_GetSystemVersion returns a status of type
ADP_STATUS_et. ADP_STATUS_OK (0) is success.
ADP_STATUS_et ADP_OpenDB(ADP_IDENTIFY_t identify, ADP_DB_OPEN_OPTIONS_t* dbOpenOptions, int card, ADP_DB_t* db);
ADP_STATUS_et ADP_CloseDB(ADP_DB_t db);
ADP_STATUS_et ADP_Put(ADP_DB_t db, void* key, unsigned int keySize, void* val, unsigned int valSize, unsigned int options);
ADP_STATUS_et ADP_Get(ADP_DB_t db, void* key, unsigned int keySize, void* buff, unsigned int buffSize, uint* objectSize);
ADP_STATUS_et ADP_Delete(ADP_DB_t db, void* key, unsigned int keySize, unsigned int options);
ADP_STATUS_et ADP_Exist(ADP_DB_t db, void* key, unsigned int keySize);
ADP_STATUS_et ADP_Flush(ADP_DB_t db);
ADP_STATUS_et ADP_FlushAsync(ADP_DB_t db);
ADP_STATUS_et ADP_DeleteDB(ADP_IDENTIFY_t identify, ADP_DB_DELETE_OPTIONS_t *userOptions, int card);
ADP_STATUS_et ADP_GetDBInfo(ADP_IDENTIFY_t identify, int card, ADP_DB_INFO_t *dbInfo);
ADP_STATUS_et ADP_GetCapacityUsage(int card, ADP_CAPACITY_USAGE_INFO_t *usageInfo);
ADP_VERSION_t ADP_GetSystemVersion(void);
identify is the number of the database. card is the number of the card: 0 for /dev/adp0. db is the handle
that ADP_OpenDB returns.
| Function | What it does |
|---|---|
ADP_OpenDB | Opens the database identify on the card and puts the handle into *db. The open options say whether the card creates a database that does not exist. |
ADP_CloseDB | Sends the writes that are still in the write buffer to the card and closes the handle. The database and its keys stay on the card. |
ADP_Put | Writes a value under a key. When the key exists, the new value replaces the old one. options is 0 or ADP_OPTION_MASK_SYNC (writes). |
ADP_Get | Reads the value of a key into the buffer buff of buffSize bytes. *objectSize receives the size of the stored value. |
ADP_Exist | Asks whether a key exists, without reading the value: ADP_STATUS_OK when it exists, ADP_STATUS_NON_EXIST when not. |
ADP_Delete | Deletes a key. options is 0 or ADP_OPTION_MASK_SYNC, as for ADP_Put. |
ADP_Flush | Sends the write buffer of the database to the card and waits until it is sent. |
ADP_FlushAsync | Starts to send the write buffer and returns. |
ADP_DeleteDB | Removes a database and all its keys from the card (deleting a database). |
ADP_GetDBInfo | Tells whether a database exists and whether the card is removing it (bIsDeleting). The fields dbNumOfKeys and dbDataInBytes are not live counters: do not count keys with them. |
ADP_GetCapacityUsage | Fills the usage of the whole card: physicalDiskSpaceUsedInBytes, physicalDiskSpaceInBytes, validObjectCount, maxValidObjectCount and utilization (from 0 to 1). |
ADP_GetSystemVersion | Returns the system version as four uint8_t fields: systemVersion, majorVersion, minorVersion and patchVersion. |
The header also declares the functions ADP_ExportDB_*, which copy databases between cards as a stream. This page
does not describe them.
Open options
ADP_OpenDB takes a pointer to ADP_DB_OPEN_OPTIONS_t. The example sets createIfMissing and leaves the other
fields at zero.
| Field | Meaning |
|---|---|
createIfMissing | true: the card creates the database when it does not exist. |
errorIfExists | true: the open returns ADP_STATUS_EXIST when the database exists. |
tailSizeInBytes | The size of the write buffers. 0 is the default size. |
streamId | Use 0. |
exportDbIngestOnlyMode | Use false. |
A NULL pointer in place of the options means createIfMissing = true and errorIfExists = false.
What a call returns
| Situation | Status |
|---|---|
| Success. | ADP_STATUS_OK (0) |
ADP_OpenDB without createIfMissing, and the database does not exist. | ADP_STATUS_NON_EXIST (5). The handle is ADP_DB_INVALID (65535). |
ADP_OpenDB with errorIfExists = true, and the database exists. | ADP_STATUS_EXIST (4). The handle is ADP_DB_INVALID. |
ADP_OpenDB a second time for the same database in one process. | ADP_STATUS_OK and the same handle. The library counts the opens. The database closes at the last matching ADP_CloseDB. |
ADP_Get or ADP_Exist of a key that does not exist. | ADP_STATUS_NON_EXIST (5). The reported size is 0. |
ADP_Get with a buffer that is smaller than the value. | ADP_STATUS_INCOMPLETE (12). *objectSize is the full size of the value. Ignore the content of the buffer. |
ADP_Delete of a key that does not exist. | ADP_STATUS_OK (0) |
ADP_Put on a key that exists. | ADP_STATUS_OK (0). The value is replaced, and the same process reads the new value at once. |
| A key of 0 bytes or of more than 4096 bytes. | ADP_STATUS_INVALID_PARAM (6) |
| A value of more than 262144 bytes. | ADP_STATUS_INVALID_VAL (7) |
Any call on a handle that is closed. One ADP_CloseDB too many. | ADP_STATUS_INVALID_PARAM (6) |
| The card is full and refuses writes. | ADP_STATUS_OUT_OF_SPACE (8) |
| The storage service does not answer at open. | ADP_STATUS_SYSTEM_NOT_READY (15) |
| A write buffer could not be sent to the card. Also every later call on this database. | ADP_STATUS_ERROR (1). Close the database and open it again. |
ADP_DeleteDB of a database that is open in the calling process. | ADP_STATUS_FAIL (3). Close the database first. |
ADP_DeleteDB or ADP_GetDBInfo of a database that does not exist. | ADP_STATUS_NON_EXIST (5). ADP_DeleteDB with errorIfMissing = false returns ADP_STATUS_OK. |
All values of ADP_STATUS_et, in order:
| Value | Status | Value | Status |
|---|---|---|---|
0 | ADP_STATUS_OK | 11 | ADP_STATUS_NOT_ENOUGH_RESOURCES |
1 | ADP_STATUS_ERROR | 12 | ADP_STATUS_INCOMPLETE |
2 | ADP_STATUS_MEDIA_ERR | 13 | ADP_STATUS_CHECKSUM_FAILED |
3 | ADP_STATUS_FAIL | 14 | ADP_STATUS_NOT_SUPPORTED |
4 | ADP_STATUS_EXIST | 15 | ADP_STATUS_SYSTEM_NOT_READY |
5 | ADP_STATUS_NON_EXIST | 16 | ADP_STATUS_DB_RECOVERY_NEEDED |
6 | ADP_STATUS_INVALID_PARAM | 17 | ADP_STATUS_VERSION_MISMATCH |
7 | ADP_STATUS_INVALID_VAL | 18 | ADP_STATUS_END_OF_FILE |
8 | ADP_STATUS_OUT_OF_SPACE | 19 | ADP_STATUS_BUSY |
9 | ADP_STATUS_INVALID_CPL | 20 | ADP_STATUS_TIMEOUT |
10 | ADP_STATUS_MAX_DBS_REACHED | 21 | ADP_STATUS_NO_LONGER_VALID |
Writes: when they are visible and durable
The options parameter of ADP_Put and ADP_Delete decides when a write reaches the card.
options = 0 | options = ADP_OPTION_MASK_SYNC | |
|---|---|---|
| The call returns | at once | when the card has accepted the write |
| The process that wrote reads the new value | at once | at once |
| Another process reads the new value | after the write buffer goes to the card | after the call returns |
The process ends without ADP_CloseDB | writes that are still in the write buffer are lost | the write is on the card |
| The cost | no wait for the card | one round trip to the card for each call |
Without the flag, the library keeps the change in a write buffer in the memory of the process, about 500 KB for
each open database. The library sends the write buffer to the card in three cases: when the buffer is full, at
ADP_Flush, and at ADP_CloseDB. It does not send the buffer by time, so a write can stay in the write buffer as
long as the database is open. Until the buffer goes to the card, another process gets ADP_STATUS_NON_EXIST for a
key that is new.
ADP_Flush sends the write buffer and waits. After it returns, other processes read the writes that were in the
buffer. ADP_FlushAsync starts to send the write buffer and returns.
With ADP_OPTION_MASK_SYNC, the call returns when the card has accepted the write. Use the flag when another
process must read the write, or when the write must not be lost with the process. Each such call costs one round trip
to the card. The section on adp_aio writes gives the speed of a synchronous ADP_Put that waits for the card
(writes and when other processes see them).
A process that dies. A process that ends without ADP_CloseDB loses the writes that are still in the write
buffer: kill, _exit and any other end that skips ADP_CloseDB. The library installs no signal handlers. A
program that must not lose buffered writes at SIGTERM or SIGINT handles the signal itself and calls
ADP_CloseDB.
A write that the card has accepted does not depend on the process any more. For what the card keeps when the storage service or the server stops abruptly, see durability.
NOTE
The header has two more flags for options: ADP_OPTION_MASK_OVERWRITE_KEY and ADP_OPTION_MASK_ADD_CRC. Do not
set them.
Deleting a database
ADP_CloseDB deletes nothing. ADP_DeleteDB(identify, &options, card) removes a database and all its keys from the
card, also the keys that other programs wrote under the same number. It takes the number of the database, not a
handle.
IMPORTANT
Call ADP_DeleteDB only on a card whose storage service runs with key_eviction = false. With key eviction on,
the storage service does not support the deletion of a database. On such a card, do not call ADP_DeleteDB.
Delete the keys with ADP_Delete, or leave the keys to eviction.
Key eviction is the key key_eviction in section [db_settings] of /etc/adp/<N>/adpstore.ini. It is on by default
in key-value mode. With key eviction on, the storage service logs Key eviction is ENABLED, delete DB not supported
when it starts. Read its log with journalctl -u adpstore@0. Wiping the card
describes how to switch key eviction off and on again on a card of the KV cache.
A database may be deleted when both conditions are true:
- The storage service of the card runs with
key_eviction = false. - The calling process has closed the database. While the database is open in the calling process,
ADP_DeleteDBreturnsADP_STATUS_FAIL(3).
The example closes the database and then deletes it, when you give it --delete-db:
./kv_demo --delete-db
put user:1001 = Ada Lovelace
get user:1001 = Ada Lovelace (13 bytes)
exist user:1001: yes
delete user:1001: gone
database 0x6b7664656d6f removed
ADP_DeleteDB returns at once with ADP_STATUS_OK, and the card removes the database in the background. For a small
database this takes a few seconds.
| While the card removes the database | After that | |
|---|---|---|
ADP_GetDBInfo returns | ADP_STATUS_OK, with bIsDeleting = true | ADP_STATUS_NON_EXIST |
adpcli system get_disk_usage -x 0 shows | Number of databases : 176 / 4096 (1 deleting) | Number of databases : 175 / 4096 (0 deleting) |
- A database that does not exist.
ADP_DeleteDBreturnsADP_STATUS_NON_EXIST(5) witherrorIfMissing = trueand withNULLin place of the options, becauseerrorIfMissing = trueis the default. WitherrorIfMissing = falseit returnsADP_STATUS_OK. - A second delete. A second
ADP_DeleteDBwhile the card still removes the database returnsADP_STATUS_NON_EXIST. - The number is free at once. After
ADP_DeleteDB, anADP_OpenDBwithcreateIfMissingcreates an empty database under the same number. A key of the old database returnsADP_STATUS_NON_EXISTthere.
Rules and limits of the synchronous calls
Limits:
- A key is 1 to 4096 bytes, and the bytes can have any value. The
adp_aiofunctions take shorter keys (limits). - A value is up to 262144 bytes (256 KiB) with the default open options.
- A card holds up to 4096 databases.
- No call lists the keys of a database.
Rules:
- Always close the database. Call
ADP_CloseDBon every way out of the program, once for eachADP_OpenDB. The close sends the buffered writes to the card. - Each process opens the database itself.
- Threads. Several threads of one process can use one handle. The library starts one background thread for each open database, at the first write.
- Flags. Set only
0orADP_OPTION_MASK_SYNCinoptions. Do not setADP_OPTION_MASK_OVERWRITE_KEY. Do not setADP_OPTION_MASK_ADD_CRC. - Read buffer. Give
ADP_Geta buffer of at least 1 byte. - Deleting a database. Call
ADP_DeleteDBonly when key eviction is off (deleting a database). - A full card. With key eviction off, a full card refuses writes with
ADP_STATUS_OUT_OF_SPACEuntil you delete keys or databases. Send the lastADP_DeletewithADP_OPTION_MASK_SYNC. - After
ADP_STATUS_ERROR. Close the database and open it again. - Access. Run as root, or give the user write access to
/etc/adp/storelib_log.confand to the log directory/var/log/adp.
Many requests in flight: adp_aio
adp_aio is the asynchronous part of libstorelib. One process, with no extra threads, puts tens of requests at the
card at the same time and collects the answers as they complete.
The process queues many requests, hands them to the kernel with one system call, and collects the results in any
order as the card completes them. The library works through io_uring, with the support built into the card driver; it
needs no other library. Like the synchronous calls, adp_aio works on the host of the card
(requirements).
Why it exists
The synchronous call of storelib, ADP_Get, sends one read to the card and waits about 110 µs for the answer. The
card needs 32 to 64 reads in flight to run at full speed, so a sequential scan that fetches one page at a time runs at
tens of MB/s. On a card with 12 SSDs, one process reads 8 KB pages at 46 MB/s with ADP_Get and at about 2000 MB/s
with adp_aio (the measurement). Threads give the same depth, but a database backend is
often a single-threaded process.
How it works
A process works in this order:
- Open a card database:
ADP_OpenDBfromstore_lib_expo.h(card databases). The returnedADP_DB_tis thedbparameter of alladp_aiofunctions. - Open a context:
adp_aio_open. One process needs one context. - Queue requests:
adp_aio_get,adp_aio_exists,adp_aio_put,adp_aio_delete. The kernel and the card do not know about them yet. - Submit them with one system call:
adp_aio_submit. It does not wait for results. - Collect results:
adp_aio_reap. Each result carries theuser_datanumber you gave the request. - Repeat steps 3 to 5 while there is work, then collect the results of all requests in flight.
- Close the context (
adp_aio_close), then the card database (ADP_CloseDB).adp_aio_closesends the writes that are still in the write buffer, so it goes first.
Functions
| Function | What it does |
|---|---|
adp_aio_open | Opens the context. depth (1 to 4096) is the most requests in flight; for sequential reads take 32 to 128. flags is 0 or ADP_AIO_WRITE_VISIBLE (writes). |
adp_aio_get | Queues a read of one key into your buffer. The buffer address and length are multiples of 4, because the card writes into the buffer directly. The buffer must live until you collect the result. |
adp_aio_exists | Queues a check whether a key exists, without reading the value. |
adp_aio_put | Queues a write. The library copies the key and the value at once. A value is up to 256 KB. |
adp_aio_delete | Queues a delete. A delete of a key that does not exist is not an error. |
adp_aio_submit | Hands all queued requests to the kernel with one system call. More requests per call cost less CPU per request. |
adp_aio_reap | Collects results. It can return at once, sleep until the first result, or sleep with a time limit. |
adp_aio_fd | A descriptor that becomes readable when results are ready, for poll, epoll or the event loop of your program. |
adp_aio_get_many | Reads n keys and waits for all of them. One call replaces a loop of ADP_Get. n can be larger than the depth. |
adp_aio_iter_open, adp_aio_iter_next, adp_aio_iter_seek, adp_aio_iter_close | Walk pages in block-number order, with read-ahead (walking pages). |
adp_aio_count_blocks | Finds the number of blocks: the first block number that does not exist. |
adp_aio_sqe_get, adp_aio_cqe_get | Put a read into an io_uring ring of your own program, and decode its result in any process (shared rings). |
adp_aio_close | Sends the buffered writes to the card and closes the context. |
adp_aio_strerror | A short English text for a result code, for logs. |
The functions return 0 or a positive number on success and a negative errno code on error, for example
-EINVAL. -EAGAIN from a queue call means the context is full: collect results and repeat the call.
Results
Each result is an adp_aio_done: your user_data, a status and the size of the value.
status | Meaning |
|---|---|
ADP_AIO_OK (0) | Done. For a read or a write, size is the size of the value. |
ADP_AIO_NOT_FOUND (1) | The key does not exist. This is not a device error. |
ADP_AIO_SMALL_BUF (2) | The buffer is smaller than the value. size is the size needed. |
| negative | An error: -EIO, -ENOSPC (the card is full), -EBADMSG (data checksum), -EBUSY or -ENODEV (the card driver is not in a working state, for example while the storage service restarts), and others. |
Results come back in any order. Use user_data to match a result with its request, for example the number of its
buffer.
Example: a sequential read
This is the main loop of the read example that comes with the library. It keeps depth reads at the card from one process. Each read
has its own buffer, and user_data is the number of that buffer.
#include "store_lib_expo.h" /* ADP_OpenDB, ADP_CloseDB, ADP_DB_t */
#include "adp_aio.h" /* adp_aio_* */
ADP_DB_t db = open_db(identify); /* ADP_OpenDB with createIfMissing */
adp_aio_ctx *ctx;
int rc = adp_aio_open(&ctx, depth, 0); /* reads need no flags */
/* One 8 KB buffer for each request in flight, aligned like pages in shared buffers. */
unsigned char *buffers;
posix_memalign((void **)&buffers, 4096, (size_t)depth * PAGE_BYTES);
while (next < npages || in_work > 0) {
/* Queue reads while there are free buffers. */
while (nfree > 0 && next < npages) {
unsigned slot = free_slots[--nfree];
PageKey key = page_key(next);
/* user_data = buffer number. It is returned in the result. */
rc = adp_aio_get(ctx, db, &key, sizeof key, buffers + (size_t)slot * PAGE_BYTES, PAGE_BYTES, slot);
if (rc != 0)
die_aio("adp_aio_get", rc);
slot_block[slot] = next++;
in_work++;
}
/* Submit what was queued. */
rc = adp_aio_submit(ctx);
if (rc < 0 && rc != -EAGAIN)
die_aio("adp_aio_submit", rc);
/* Collect what is ready. Sleep until at least one result is ready. */
int n = adp_aio_reap(ctx, results, 64, 1, -1);
if (n < 0)
die_aio("adp_aio_reap", n);
for (int i = 0; i < n; i++) {
unsigned slot = (unsigned)results[i].user_data;
/* ... check results[i].status, use the page of block slot_block[slot] ... */
free_slots[nfree++] = slot; /* the buffer is free again */
in_work--;
}
}
adp_aio_close(ctx); /* first the context */
ADP_CloseDB(db); /* then the card database */
The other examples show writes, waiting on the descriptor with poll, a batch read with adp_aio_get_many, and
deletes.
Writes and when other processes see them
Like the synchronous ADP_Put, adp_aio collects writes in a write buffer of about 500 KB in the memory of the
process and sends the whole buffer to the card with one command, with no thread. The flag of the context decides
when.
With ADP_AIO_WRITE_VISIBLE | Without the flag | |
|---|---|---|
| The write buffer goes to the card | at every adp_aio_submit | when it is full, and at adp_aio_close |
| The result of a write comes | when the card has accepted the write buffer | at once, at adp_aio_submit |
| Other processes see the write | from the moment you collect its result | after the write buffer is sent; the moment is not known in advance |
| The process dies | writes with a collected result are on the card | writes in the write buffer are lost |
| Use it for | normal work of a database | a bulk load that nobody reads before it ends |
With the flag the guarantee is the one of pwrite and pread: when process A has collected ADP_AIO_OK for a write
and tells process B, B reads the new value. Two writes of one key never change places. ADP_AIO_OK means that the
card has accepted the data: a guarantee of visibility, not of fsync (durability).
A process sees its own writes at once through adp_aio_get, in both modes, but a synchronous ADP_Get does not see
the writes still in the write buffer of adp_aio. Do not write one key through both ADP_Put and adp_aio_put in
one process: their order is not defined.
On a card with one SSD, one process wrote 8 KB pages at about 1100 MB/s with ADP_AIO_WRITE_VISIBLE and 32 writes in
flight, against 185 MB/s with a synchronous ADP_Put that waits for the card on every page.
Walking pages by block number
The card stores keys by hash. It keeps no key order and has no prefix search. So adp_aio walks pages by block
number: 0, 1, 2 and so on. You give a key template and the offset of a 4-byte block number in it, and the
library builds the key of each block.
adp_aio_iter_opts o = {
.key = &key, /* key template, copied at open */
.key_len = 24,
.block_off = 20, /* where the block number is in the key */
.end_block = UINT32_MAX, /* up to the first block that does not exist */
.value_size = 8192,
.window = 64, /* reads kept in flight */
};
adp_aio_iter *it;
adp_aio_iter_open(ctx, db, &o, &it);
uint32_t block, size;
const void *page;
while (adp_aio_iter_next(it, &block, &page, &size) == 1) {
/* blocks come strictly in block-number order */
}
adp_aio_iter_close(it);
The walk reads ahead with up to window reads in flight, keeps its own buffers and returns blocks strictly in
order, each as it was at the moment of the read-ahead. So it suits a pass over a whole table (a copy, a check, a
count), not pages for the buffer cache of a database.
adp_aio_count_blocks finds the number of blocks without reading every key: for a million blocks it needs 5 round
trips to the card, about 150 key checks. It assumes there are no gaps.
Limits
- A context is not thread-safe: call all its functions from one thread. Use one context per process.
- A submitted request cannot be cancelled. It completes by itself, usually in a fraction of a millisecond.
- There is no iterator over keys, because the card keeps keys by hash. The page walk goes by block numbers.
- A key is 1 to 255 bytes (at most 48 bytes through
adp_aio_sqe_get). A value is up to 256 KB. - A read buffer has an address and a length that are multiples of 4, and a length above 0.
Example: PostgreSQL reads a table
Take a PostgreSQL storage manager that keeps each 8 KB page of a table as one key on the card. This section shows how
such a storage manager uses adp_aio, and what it gains on a sequential scan.
The page key
The value is the page, 8192 bytes. The key is 24 bytes: tablespace, database, relation, backend, fork and block
number, 4 bytes each. The block number is last, at offset 20: the block_off of the
page walk. For adp_aio a key is any 1 to 255 bytes.
The number of blocks of a relation can be one more value under its own key, written with adp_aio_put together with
the new blocks. Or the storage manager finds it with adp_aio_count_blocks.
Storage manager calls
| Storage manager operation | adp_aio calls |
|---|---|
| A backend opens the card database | ADP_OpenDB, then once adp_aio_open(&ctx, 64, ADP_AIO_WRITE_VISIBLE) |
| Start an asynchronous read of blocks | adp_aio_get for each block, then adp_aio_submit |
| Complete the asynchronous read | adp_aio_reap(ctx, out, max, 0, 0) after adp_aio_fd becomes readable |
| A synchronous read of several blocks | adp_aio_get_many |
| Write or extend | adp_aio_put for each block, adp_aio_submit, then adp_aio_reap until all writes have results |
| Drop blocks (unlink, truncate) | adp_aio_delete for each block, adp_aio_submit, adp_aio_reap |
| The backend exits | collect all results, adp_aio_close, then ADP_CloseDB |
A sequential scan asks for blocks ahead of the one it processes. The storage manager queues them all, submits them in one call and keeps 64 reads at the card. A backend waits on the descriptor of the context together with its latch, in the same wait set:
AddWaitEventToSet(set, WL_SOCKET_READABLE, adp_aio_fd(ctx), NULL, NULL);
Collect results with adp_aio_reap(ctx, done, 32, 0, 0), which does not sleep. When it returns 0, wait on the set.
ADP_AIO_OK is a page that has been read. ADP_AIO_NOT_FOUND is a block that is not on the card.
Reads that another backend completes
PostgreSQL allows one backend to start a read and another backend to complete it. A context belongs to one process, so it must not keep reads in flight that another backend waits for.
- With
io_method = io_uring, reads go into the io_uring ring of PostgreSQL itself:adp_aio_sqe_getfills one entry per block, and a usualio_uring_submitsends them. The backend that waits takes the results and decodes them withadp_aio_cqe_get, which needs no context. The rings must be created withIORING_SETUP_SQE128andIORING_SETUP_CQE32, the page buffers must be in shared memory, and the key is at most 48 bytes. This path needs a kernel that does not lose wake-ups (requirements). - With any other
io_method, a backend sends the blocks of one read call through its own context and collects all results before it returns.
Rules for a backend
- fork. Each backend opens its own context after
fork. The context of the parent returns-EPERMin the child. - No threads.
ADP_OpenDB,ADP_Get,ADP_ExistandADP_CloseDBstart no threads. The firstADP_Put,ADP_DeleteorADP_Flushstarts the write thread of storelib, so a backend writes only throughadp_aio. - Pinned buffers. A page in shared buffers stays pinned until the result of its read is collected. A request cannot be cancelled.
- Signals. The kernel wakes the process with the notification signal of io_uring, so
pollandepoll_waitcan returnEINTR. Repeat the wait.WaitEventSetWaitalready does. - Key eviction off. Here the card is the main storage, not a cache: set
key_eviction = false(key eviction).
Measured: sequential read
One ADP card with 12 SAS SSDs in RAID 5, a server with 112 CPUs, Linux 6.1. The data: 9.7 GB of 8 KB PostgreSQL pages, one page per key, on the SSDs of the card. One or more processes read all pages in block order. Median of three runs. The checksum of all pages is the same in every mode. The CPU time is for the whole server, kernel and driver included.
| How the pages are read | MB/s | CPU, µs per page |
|---|---|---|
ADP_Get, one page at a time, 1 process | 46 | 13 |
adp_aio, 1 process, depth 1 | 46 | 14 |
adp_aio, 1 process, depth 8 | 309 | 25 |
adp_aio, 1 process, depth 16 | 628 | 22 |
adp_aio, 1 process, depth 32 | 1277 | 13 |
adp_aio, 1 process, depth 64 | 1999 | 10 |
adp_aio, 1 process, depth 128 | 1983 | 14 |
ADP_Get, 8 processes | 371 | 11 |
adp_aio, 8 processes, depth 32 each | 7125 | 17 |
adp_aio, 16 processes, depth 64 each | 9571 | 26 |
One process with adp_aio at depth 64 reads about 43 times faster than one process with ADP_Get, and 8 processes
with adp_aio about 19 times faster than 8 processes with ADP_Get. At depth 1 the two are the same: the gain comes
only from the reads in flight.
Keep the queue full. A loop of adp_aio_get, adp_aio_submit and adp_aio_reap keeps the card busy. A batch
that waits for all its reads leaves the queue empty between batches: on the same server, one process at depth 64 read
2540–2859 MB/s with the loop and 1143–1252 MB/s with adp_aio_get_many in calls of 64 pages. For a scan, use the loop
or the page walk.
Server settings
Two settings of the server change the speed more than the code, also on the synchronous path:
- IOMMU translation off for the card (kernel parameter
iommu.passthrough=1). - The I/O scheduler
noneon the SAS and SATA SSDs of the card. NVMe SSDs have it already.
On the server of the measurement above, 64 processes with 2 reads in flight each read 2.3 GB/s at 125 µs of CPU per
page with IOMMU translation and mq-deadline, and 5.3 GB/s at 17 µs per page with neither. The driver also keeps
the PCIe link of the card awake (PCIe power saving).
If something does not work
The library logs every open, every close and every error to /var/log/adp/storelib.log. Read this log first.
| What you see | Cause | What to do |
|---|---|---|
The build stops with store_lib_expo.h: error: unknown type name 'uint'. | A strict ISO C dialect: -std=c11 or -std=c99. | Use the default dialect of gcc, or -std=gnu11 or -std=gnu17. |
The process prints Log init failed and Failed to initialize logger and exits. | The process user cannot write /etc/adp/storelib_log.conf. | Run the program as root. Or give the user write access to the file, for example chmod 666 /etc/adp/storelib_log.conf, and to the log directory /var/log/adp. |
ADP_OpenDB returns ADP_STATUS_SYSTEM_NOT_READY (15). | The storage service of the card does not answer. | systemctl status adpstore@0, then adpcli system is_ready -x 0. |
ADP_OpenDB returns ADP_STATUS_NON_EXIST (5). | The database does not exist, and createIfMissing is not set. | Set createIfMissing = true. |
ADP_Get returns ADP_STATUS_INCOMPLETE (12). | The buffer is smaller than the value. | Ignore the content of the buffer. Read again with a buffer of at least *objectSize bytes. |
A call returns ADP_STATUS_INVALID_PARAM (6). | A key of 0 bytes or of more than 4096 bytes, or a handle that is closed. | Check the size of the key. Call ADP_CloseDB once for each ADP_OpenDB, and make no call on the handle after the last one. |
ADP_Put returns ADP_STATUS_INVALID_VAL (7). | A value of more than 262144 bytes. | Keep each value at 262144 bytes or less. |
ADP_Put returns ADP_STATUS_OUT_OF_SPACE (8). | The card is full and refuses writes (capacity). | On a card with key eviction off, delete keys or databases. Send the last ADP_Delete with ADP_OPTION_MASK_SYNC. |
Every call on a database returns ADP_STATUS_ERROR (1). | A write buffer could not be sent to the card. | Close the database and open it again. |
| Another process does not see a write. | The write is still in the write buffer of the process that wrote it. | Write with ADP_OPTION_MASK_SYNC, or call ADP_Flush (writes). |
| Writes are missing after the program ended. | The process ended without ADP_CloseDB, with writes in the write buffer. | Call ADP_CloseDB on every way out, also in your handlers of SIGTERM and SIGINT. |
Keys return ADP_STATUS_NON_EXIST, and no program deleted them. | Key eviction is on, and the card dropped old keys to free space. | A card that must keep every key runs with key_eviction = false (configure the storage service). |
ADP_DeleteDB returns ADP_STATUS_FAIL (3). | The database is open in the calling process. | Call ADP_CloseDB first. |
ADP_DeleteDB returns ADP_STATUS_NON_EXIST (5). | The database does not exist, or the card is already removing it. | Nothing. With errorIfMissing = false, the call returns ADP_STATUS_OK for a database that does not exist. |
adp_aio_open returns -EOPNOTSUPP. | A driver without the asynchronous path, a kernel older than 6.1, or io_uring off. | Check that /sys/module/adp/parameters/adp_uring_stats exists. |
adp_aio_open returns -ENODEV. | No /dev/adp0, or the storage service of the card does not run. | systemctl status adpstore@0, then adpcli system is_ready -x 0. |
adp_aio_get returns -EINVAL. | The buffer address or length is not a multiple of 4, or a length is 0. | Align the buffer, for example posix_memalign(&p, 4096, size). |
A call returns -EAGAIN. | No room in the context. | adp_aio_submit, then adp_aio_reap, then repeat the call. |
A call returns -EPERM. | The context was opened before fork. | Open a new context in the child. |
A process sleeps in io_uring_enter while its result is already in the ring. | A kernel that loses io_uring wake-ups. | Update the kernel (kernel for adp_aio). |
Planning a deployment?
Talk to our engineers about your models, context lengths, concurrency and where the ADP card should sit.