Writing plugins in C?
/* The size of disk in bytes (initialized by
size=<SIZE> parameter). */
static int64_t size = 0;
/* Debug directory operations
(-D memory.dir=1). */
int memory_debug_dir;
static struct sparse_array *sa;
static void
memory_load (void)
{
sa = alloc_sparse_array (memory_debug_dir);
if (sa == NULL) {
perror ("malloc");
exit (EXIT_FAILURE);
}
}
static void
memory_unload (void)
{
free_sparse_array (sa);
}
static int
memory_config (const char *key,
const char *value)
{
if (strcmp (key, "size") == 0) {
size = nbdkit_parse_size (value);
if (size == -1)
return -1;
}
else {
nbdkit_error
("unknown parameter '%s'", key);
return -1;
}
return 0;
}
static int
memory_config_complete (void)
{
if (size == 0) {
nbdkit_error ("you must specify "
"size=<SIZE> on the "
"command line");
return -1;
}
return 0;
}
#define memory_config_help \
"size=<SIZE> (required)"
" Size of the backing disk"
/* Create the per-connection handle. */
static void *
memory_open (int readonly)
{
/* Used only as a handle pointer. */
static int mh;
return &mh;
}
#define THREAD_MODEL \
NBDKIT_THREAD_MODEL_SERIALIZE_ALL_REQUESTS
/* Get the disk size. */
static int64_t
memory_get_size (void *handle)
{
return (int64_t) size;
}
/* Read data. */
static int
memory_pread (void *handle, void *buf,
uint32_t count, uint64_t offset)
{
sparse_array_read (sa, buf, count, offset);
return 0;
}
/* Write data. */
static int
memory_pwrite (void *handle,
const void *buf,
uint32_t count, uint64_t offset)
{
return sparse_array_write (sa,
buf, count, offset);
}
/* Zero. */
static int
memory_zero (void *handle,
uint32_t count,
uint64_t offset, int may_trim)
{
sparse_array_zero (sa, count, offset);
return 0;
}
/* Trim (same as zero). */
static int
memory_trim (void *handle,
uint32_t count, uint64_t offset)
{
sparse_array_zero (sa, count, offset);
return 0;
}
static struct nbdkit_plugin plugin = {
.name = "memory",
.version = PACKAGE_VERSION,
.load = memory_load,
.unload = memory_unload,
.config = memory_config,
.config_complete = memory_config_complete,
.config_help = memory_config_help,
.open = memory_open,
.get_size = memory_get_size,
.pread = memory_pread,
.pwrite = memory_pwrite,
.zero = memory_zero,
.trim = memory_trim,
/* In this plugin, errno is preserved
* properly along error return
* paths from failed system calls.
*/
.errno_is_preserved = 1,
};
NBDKIT_REGISTER_PLUGIN(plugin)