File: plugin.c

package info (click to toggle)
nbdkit 1.42.9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 14,696 kB
  • sloc: ansic: 59,224; sh: 16,793; makefile: 6,463; python: 1,837; cpp: 1,116; ml: 504; perl: 502; tcl: 62
file content (991 lines) | stat: -rw-r--r-- 26,093 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
/* nbdkit
 * Copyright Red Hat
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of Red Hat nor the names of its contributors may be
 * used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY RED HAT AND CONTRIBUTORS ''AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RED HAT OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <config.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>

#include <caml/alloc.h>
#include <caml/bigarray.h>
#include <caml/callback.h>
#include <caml/fail.h>
#include <caml/memory.h>
#include <caml/mlvalues.h>
#include <caml/printexc.h>
#include <caml/threads.h>
#include <caml/version.h>

#define NBDKIT_API_VERSION 2
#include <nbdkit-plugin.h>

#include "array-size.h"

#include "plugin.h"

/* OCaml >= 5 requires that each thread except the main thread is
 * registered with the OCaml runtime, and unregistered before the
 * thread exits.  nbdkit doesn't provide APIs to notify us when a new
 * thread is created or destroyed, instead it just calls random entry
 * points on new threads.  So we have to register threads with the
 * OCaml runtime ourselves.
 *
 * We maintain a thread-local flag which tracks if we have registered
 * the thread.
 *
 * It also tracks if this thread is the main thread (ie. the thread
 * which called caml_startup) because that thread must not be
 * registered.  This scheme was suggested by Guillaume Munch-
 * Maccagnoni:
 * https://github.com/ocaml/ocaml/issues/13400#issuecomment-2309956292.
 *
 * For OCaml < 5 only, you shouldn't link the plugin with threads.cmxa
 * since that breaks nbdkit forking.  Symbols caml_c_thread_register
 * and caml_c_thread_unregister are pulled in only when you link with
 * threads.cmxa (which pulls in ocamllib/libthreads.a as a
 * side-effect), so when _not_ using threads.cmxa these symbols are
 * not present.
 */
#if OCAML_VERSION_MAJOR < 5

#define init_threads() /* nothing */
#define register_thread() /* nothing */
#define unregister_thread() /* nothing */

#else /* OCAML_VERSION_MAJOR >= 5 */

/* The key can have the following values:
 * NULL = new thread, not registered
 * &thread_key_main = this is the main thread, do not register
 * &thread_key_non_main = this is a non-main thread that has been registered
 */
static pthread_key_t thread_key;
/* These globals are just used as addresses: */
static char thread_key_main;
static char thread_key_non_main;

static void destroy_thread (void *val);

static void
init_threads (void)
{
  pthread_key_create (&thread_key, destroy_thread);

  /* Mark this as the main thread. */
  pthread_setspecific (thread_key, &thread_key_main);
}

static void
register_thread (void)
{
  void *val = pthread_getspecific (thread_key);
  if (val == NULL) {
    /* Register this non-main thread, and remember that we did it. */
    if (caml_c_thread_register () == 0) abort ();
    pthread_setspecific (thread_key, &thread_key_non_main);
  }
}

static void
destroy_thread (void *val)
{
  if (val == &thread_key_non_main) {
    /* Unregister this non-main thread.
     *
     * Originally we called abort() on failure here, but that causes
     * problems under valgrind (only).  Since unregistering the thread
     * is essentially optional, and the failure isn't actionable,
     * don't worry about it.
     */
    /*if (caml_c_thread_unregister () == 0) abort ();*/
    caml_c_thread_unregister ();
    pthread_setspecific (thread_key, NULL);
  }
}

#endif /* OCAML_VERSION_MAJOR >= 5 */

/* Instead of using the NBDKIT_REGISTER_PLUGIN macro, we construct the
 * nbdkit_plugin struct and return it from our own plugin_init
 * function.
 */
static int after_fork_wrapper (void);
static void close_wrapper (void *h);
static void unload_wrapper (void);
static void free_strings (void);
static void remove_roots (void);

static pid_t original_pid;

static struct nbdkit_plugin plugin = {
  ._struct_size = sizeof (plugin),
  ._api_version = NBDKIT_API_VERSION,
  ._thread_model = NBDKIT_THREAD_MODEL_PARALLEL,

  /* The following field is used as a canary to detect whether the
   * OCaml code started up and called us back successfully.  If it's
   * still set to NULL (see plugin_init below), then we can print a
   * suitable error message.
   */
  .name = NULL,

  /* We always call these, even if the OCaml code does not provide a
   * callback.
   */
  .after_fork = after_fork_wrapper,
  .close = close_wrapper,
  .unload = unload_wrapper,
};

NBDKIT_DLL_PUBLIC struct nbdkit_plugin *
plugin_init (void)
{
  char *argv[2] = { "nbdkit", NULL };

  /* Initialize OCaml runtime. */
  caml_startup (argv);

  /* We need to release the runtime system here so other threads may
   * use it.  Before we call any OCaml callbacks we must acquire the
   * runtime system again.
   */
  do_caml_release_runtime_system ();

  /* Initialize thread-specific key. */
  init_threads ();

  /* Save the PID so we know in after_fork if we forked. */
  original_pid = getpid ();

  /* It is expected that top level statements in the OCaml code have
   * by this point called NBDKit.register_plugin.  We know if this was
   * called because plugin.name will have been set (by
   * set_string_field "name").  If that didn't happen, something went
   * wrong so exit here.
   */
  if (plugin.name == NULL) {
    fprintf (stderr, "error: OCaml code did not call NBDKit.register_plugin\n");
    exit (EXIT_FAILURE);
  }
  return &plugin;
}

/* There is one global per callback called <callback>_fn.  These
 * globals store the OCaml functions that we actually call.  Also the
 * assigned ones are roots to ensure the GC doesn't free them.
 */
#define CB(name) static value name##_fn;
#include "callbacks.h"
#undef CB

/*----------------------------------------------------------------------*/
/* Wrapper functions that translate calls from C (ie. nbdkit) to OCaml. */

/* This macro calls nbdkit_error when we get an exception thrown in
 * OCaml callback code.  The 'return_stmt' parameter is usually a call
 * to CAMLreturnT, but may be empty in order to fall through.
 */
#define EXCEPTION_TO_ERROR(rv, return_stmt)                             \
  do {                                                                  \
    if (Is_exception_result (rv)) {                                     \
      nbdkit_error ("%s: %s", __func__,                                 \
                    caml_format_exception (Extract_exception (rv)));    \
      return_stmt;                                                      \
    }                                                                   \
  } while (0)

static void
load_wrapper (void)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  caml_callback (load_fn, Val_unit);
}

/* We always have an unload function, since it also has to free the
 * globals we allocated.
 */
static void
unload_wrapper (void)
{
  register_thread ();
  /* NB: Don't call ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE here since it
   * will release the lock after caml_shutdown (which is a bug), and
   * the runtime system must be locked when calling caml_shutdown.
   */
  do_caml_acquire_runtime_system ();

  if (unload_fn) {
    caml_callback (unload_fn, Val_unit);
  }

  free_strings ();
  remove_roots ();

#ifdef HAVE_CAML_SHUTDOWN
  caml_shutdown ();
#endif
}

static void
dump_plugin_wrapper (void)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);

  printf ("ocaml_version_major=%d\n", OCAML_VERSION_MAJOR);
  printf ("ocaml_version_minor=%d\n", OCAML_VERSION_MINOR);
  printf ("ocaml_version=%s\n", OCAML_VERSION_STRING);

  rv = caml_callback_exn (dump_plugin_fn, Val_unit);
  EXCEPTION_TO_ERROR (rv, /* fallthrough */);
  CAMLreturn0;
}

static int
config_wrapper (const char *key, const char *val)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal3 (keyv, valv, rv);

  keyv = caml_copy_string (key);
  valv = caml_copy_string (val);

  rv = caml_callback2_exn (config_fn, keyv, valv);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, 0);
}

static int
config_complete_wrapper (void)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);

  rv = caml_callback_exn (config_complete_fn, Val_unit);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, 0);
}

static int
thread_model_wrapper (void)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);

  rv = caml_callback_exn (thread_model_fn, Val_unit);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, Int_val (rv));
}

static int
get_ready_wrapper (void)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);

  rv = caml_callback_exn (get_ready_fn, Val_unit);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, 0);
}

/* We always have an after_fork wrapper, since if we really forked
 * then we must reinitialize the OCaml runtime.
 */
static int
after_fork_wrapper (void)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);

#if OCAML_VERSION_MAJOR >= 5
  /* If we forked, OCaml 5 requires that we reinitialize the runtime. */
  if (getpid () != original_pid) {
    extern void (*caml_atfork_hook)(void);
    caml_atfork_hook ();
  }
#endif

  if (after_fork_fn) {
    rv = caml_callback_exn (after_fork_fn, Val_unit);
    EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));
  }

  CAMLreturnT (int, 0);
}

static void
cleanup_wrapper (void)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);

  rv = caml_callback_exn (cleanup_fn, Val_unit);
  EXCEPTION_TO_ERROR (rv, CAMLreturn0);

  CAMLreturn0;
}

static int
preconnect_wrapper (int readonly)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);

  rv = caml_callback_exn (preconnect_fn, Val_bool (readonly));
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, 0);
}

static int
list_exports_wrapper (int readonly, int is_tls, struct nbdkit_exports *exports)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal2 (rv, v);

  rv = caml_callback2_exn (list_exports_fn, Val_bool (readonly),
                           Val_bool (is_tls));
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  /* Convert exports list into calls to nbdkit_add_export. */
  while (rv != Val_emptylist) {
    const char *name, *desc = NULL;

    v = Field (rv, 0);          /* export struct */
    name = String_val (Field (v, 0));
    if (Is_block (Field (v, 1)))
      desc = String_val (Field (Field (v, 1), 0));
    if (nbdkit_add_export (exports, name, desc) == -1) {
      CAMLreturnT (int, -1);
    }

    rv = Field (rv, 1);
  }

  CAMLreturnT (int, 0);
}

static const char *
default_export_wrapper (int readonly, int is_tls)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);
  const char *name;

  rv = caml_callback2_exn (default_export_fn, Val_bool (readonly),
                           Val_bool (is_tls));
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (const char *, NULL));

  name = nbdkit_strdup_intern (String_val (rv));
  CAMLreturnT (const char *, name);
}

/* The C handle. */
struct handle {
  value v;       /* The OCaml handle, also registered as a GC root. */
};

static void *
open_wrapper (int readonly)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);
  struct handle *h;

  rv = caml_callback_exn (open_fn, Val_bool (readonly));
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (void *, NULL));

  /* Allocate a root on the C heap that points to the OCaml handle. */
  h = malloc (sizeof *h);
  if (h == NULL) {
    nbdkit_error ("malloc: %m");
    CAMLreturnT (void *, NULL);
  }
  h->v = rv;
  caml_register_generational_global_root (&h->v);

  CAMLreturnT (void *, h);
}

/* We always have a close wrapper, since we need to unregister the
 * global root and free the handle.
 */
static void
close_wrapper (void *hv)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);
  struct handle *h = hv;

  if (close_fn) {
    rv = caml_callback_exn (close_fn, h->v);
    EXCEPTION_TO_ERROR (rv, /* fallthrough */);
  }

  caml_remove_generational_global_root (&h->v);
  free (h);

  CAMLreturn0;
}

static const char *
export_description_wrapper (void *hv)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);
  struct handle *h = hv;
  const char *desc;

  rv = caml_callback_exn (export_description_fn, h->v);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (const char *, NULL));

  desc = nbdkit_strdup_intern (String_val (rv));
  CAMLreturnT (const char *, desc);
}

static int64_t
get_size_wrapper (void *hv)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);
  struct handle *h = hv;
  int64_t r;

  rv = caml_callback_exn (get_size_fn, h->v);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int64_t, -1));

  r = Int64_val (rv);
  CAMLreturnT (int64_t, r);
}

static int
block_size_wrapper (void *hv,
                    uint32_t *minimum, uint32_t *preferred, uint32_t *maximum)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);
  struct handle *h = hv;
  int i;
  int64_t i64;

  rv = caml_callback_exn (block_size_fn, h->v);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  i = Int_val (Field  (rv, 0));
  if (i < 0 || i > 65536) {
    nbdkit_error ("minimum block size must be in range 1..65536");
    CAMLreturnT (int, -1);
  }
  *minimum = i;

  i = Int_val (Field  (rv, 1));
  if (i < 512 || i > 32 * 1024 * 1024) {
    nbdkit_error ("preferred block size must be in range 512..32M");
    CAMLreturnT (int, -1);
  }
  *preferred = i;

  i64 = Int64_val (Field  (rv, 2));
  if (i64 < -1 || i64 > UINT32_MAX) {
    nbdkit_error ("maximum block size out of range");
    CAMLreturnT (int, -1);
  }
  if (i64 == -1) /* Allow -1L to mean greatest block size. */
    *maximum = (uint32_t)-1;
  else
    *maximum = i;

  CAMLreturnT (int, 0);
}

static int
can_write_wrapper (void *hv)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);
  struct handle *h = hv;

  rv = caml_callback_exn (can_write_fn, h->v);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, Bool_val (rv));
}

static int
can_flush_wrapper (void *hv)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);
  struct handle *h = hv;

  rv = caml_callback_exn (can_flush_fn, h->v);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, Bool_val (rv));
}

static int
is_rotational_wrapper (void *hv)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);
  struct handle *h = hv;

  rv = caml_callback_exn (is_rotational_fn, h->v);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, Bool_val (rv));
}

static int
can_trim_wrapper (void *hv)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);
  struct handle *h = hv;

  rv = caml_callback_exn (can_trim_fn, h->v);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, Bool_val (rv));
}

static int
can_zero_wrapper (void *hv)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);
  struct handle *h = hv;

  rv = caml_callback_exn (can_zero_fn, h->v);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, Bool_val (rv));
}

static int
can_fua_wrapper (void *hv)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);
  struct handle *h = hv;

  rv = caml_callback_exn (can_fua_fn, h->v);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, Int_val (rv));
}

static int
can_fast_zero_wrapper (void *hv)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);
  struct handle *h = hv;

  rv = caml_callback_exn (can_fast_zero_fn, h->v);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, Bool_val (rv));
}

static int
can_cache_wrapper (void *hv)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);
  struct handle *h = hv;

  rv = caml_callback_exn (can_cache_fn, h->v);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, Int_val (rv));
}

static int
can_extents_wrapper (void *hv)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);
  struct handle *h = hv;

  rv = caml_callback_exn (can_extents_fn, h->v);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, Bool_val (rv));
}

static int
can_multi_conn_wrapper (void *hv)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal1 (rv);
  struct handle *h = hv;

  rv = caml_callback_exn (can_multi_conn_fn, h->v);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, Bool_val (rv));
}

static value
Val_flags (uint32_t flags)
{
  CAMLparam0 ();
  CAMLlocal2 (consv, rv);

  rv = Val_unit;
  if (flags & NBDKIT_FLAG_MAY_TRIM) {
    consv = caml_alloc (2, 0);
    Store_field (consv, 0, 0); /* 0 = May_trim */
    Store_field (consv, 1, rv);
    rv = consv;
  }
  if (flags & NBDKIT_FLAG_FUA) {
    consv = caml_alloc (2, 0);
    Store_field (consv, 0, 1); /* 1 = FUA */
    Store_field (consv, 1, rv);
    rv = consv;
  }
  if (flags & NBDKIT_FLAG_REQ_ONE) {
    consv = caml_alloc (2, 0);
    Store_field (consv, 0, 2); /* 2 = Req_one */
    Store_field (consv, 1, rv);
    rv = consv;
  }

  CAMLreturn (rv);
}

/* Wrap the buf in an OCaml bigarray so that callers can read and
 * write directly to it without copying.
 * https://discuss.ocaml.org/t/is-there-a-simple-library-that-wraps-a-c-mallocd-char-buffer/14323
 * https://v2.ocaml.org/manual/intfc.html#ss:C-Bigarrays-wrap
 */
static int
pread_wrapper (void *hv, void *buf, uint32_t count, uint64_t offset,
               uint32_t flags)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal4 (rv, ba, offsetv, flagsv);
  struct handle *h = hv;
  long dims[1] = { count };

  ba = caml_ba_alloc (CAML_BA_CHAR|CAML_BA_C_LAYOUT, 1, buf, dims);
  offsetv = caml_copy_int64 (offset);
  flagsv = Val_flags (flags);

  value args[] = { h->v, ba, offsetv, flagsv };
  rv = caml_callbackN_exn (pread_fn, ARRAY_SIZE (args), args);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, 0);
}

static int
pwrite_wrapper (void *hv, const void *buf, uint32_t count, uint64_t offset,
                uint32_t flags)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal4 (rv, ba, offsetv, flagsv);
  struct handle *h = hv;
  long dims[1] = { count };

  /* We discard the const of the incoming buffer, and in theory OCaml
   * plugins could try writing to it. XXX
   */
  ba = caml_ba_alloc (CAML_BA_CHAR|CAML_BA_C_LAYOUT, 1, (void *) buf, dims);
  offsetv = caml_copy_int64 (offset);
  flagsv = Val_flags (flags);

  value args[] = { h->v, ba, offsetv, flagsv };
  rv = caml_callbackN_exn (pwrite_fn, ARRAY_SIZE (args), args);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, 0);
}

static int
flush_wrapper (void *hv, uint32_t flags)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal2 (rv, flagsv);
  struct handle *h = hv;

  flagsv = Val_flags (flags);

  rv = caml_callback2_exn (flush_fn, h->v, flagsv);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, 0);
}

static int
trim_wrapper (void *hv, uint32_t count, uint64_t offset, uint32_t flags)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal4 (rv, countv, offsetv, flagsv);
  struct handle *h = hv;

  countv = caml_copy_int64 (count);
  offsetv = caml_copy_int64 (offset);
  flagsv = Val_flags (flags);

  value args[] = { h->v, countv, offsetv, flagsv };
  rv = caml_callbackN_exn (trim_fn, ARRAY_SIZE (args), args);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, 0);
}

static int
zero_wrapper (void *hv, uint32_t count, uint64_t offset, uint32_t flags)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal4 (rv, countv, offsetv, flagsv);
  struct handle *h = hv;

  countv = caml_copy_int64 (count);
  offsetv = caml_copy_int64 (offset);
  flagsv = Val_flags (flags);

  value args[] = { h->v, countv, offsetv, flagsv };
  rv = caml_callbackN_exn (zero_fn, ARRAY_SIZE (args), args);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, 0);
}

static int
extents_wrapper (void *hv, uint32_t count, uint64_t offset, uint32_t flags,
                 struct nbdkit_extents *extents)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal5 (rv, countv, offsetv, flagsv, v);
  struct handle *h = hv;

  countv = caml_copy_int64 (count);
  offsetv = caml_copy_int64 (offset);
  flagsv = Val_flags (flags);

  value args[] = { h->v, countv, offsetv, flagsv };
  rv = caml_callbackN_exn (extents_fn, ARRAY_SIZE (args), args);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  /* Convert extents list into calls to nbdkit_add_extent. */
  while (rv != Val_emptylist) {
    uint64_t length;
    uint32_t type = 0;

    v = Field (rv, 0);          /* extent struct */
    offset = Int64_val (Field (v, 0));
    length = Int64_val (Field (v, 1));
    if (Bool_val (Field (v, 2)))
      type |= NBDKIT_EXTENT_HOLE;
    if (Bool_val (Field (v, 3)))
      type |= NBDKIT_EXTENT_ZERO;
    if (nbdkit_add_extent (extents, offset, length, type) == -1) {
      CAMLreturnT (int, -1);
    }

    rv = Field (rv, 1);
  }

  CAMLreturnT (int, 0);
}

static int
cache_wrapper (void *hv, uint32_t count, uint64_t offset, uint32_t flags)
{
  register_thread ();
  ACQUIRE_RUNTIME_FOR_CURRENT_SCOPE ();
  CAMLparam0 ();
  CAMLlocal4 (rv, countv, offsetv, flagsv);
  struct handle *h = hv;

  countv = caml_copy_int64 (count);
  offsetv = caml_copy_int64 (offset);
  flagsv = Val_flags (flags);

  value args[] = { h->v, countv, offsetv, flagsv };
  rv = caml_callbackN_exn (cache_fn, ARRAY_SIZE (args), args);
  EXCEPTION_TO_ERROR (rv, CAMLreturnT (int, -1));

  CAMLreturnT (int, 0);
}

/*----------------------------------------------------------------------*/
/* set_* functions called from OCaml code at load time to initialize
 * fields in the plugin struct.
 */

/* NB: noalloc function */
NBDKIT_DLL_PUBLIC value
ocaml_nbdkit_set_string_field (value fieldv, value strv)
{
  const char *field = String_val (fieldv);
  char *str = strdup (String_val (strv));

  if (strcmp (field, "name") == 0)
    plugin.name = str;
  else if (strcmp (field, "longname") == 0)
    plugin.longname = str;
  else if (strcmp (field, "version") == 0)
    plugin.version = str;
  else if (strcmp (field, "description") == 0)
    plugin.description = str;
  else if (strcmp (field, "config_help") == 0)
    plugin.config_help = str;
  else if (strcmp (field, "magic_config_key") == 0)
    plugin.magic_config_key = str;
  else
    abort ();                   /* unknown field name */

  return Val_unit;
}

/* Free string fields, called from unload(). */
static void
free_strings (void)
{
  free ((char *) plugin.name);
  free ((char *) plugin.longname);
  free ((char *) plugin.version);
  free ((char *) plugin.description);
  free ((char *) plugin.config_help);
  free ((char *) plugin.magic_config_key);
}

NBDKIT_DLL_PUBLIC value
ocaml_nbdkit_set_field (value fieldv, value fv)
{
  CAMLparam2 (fieldv, fv);

  /* This isn't very efficient because we string-compare the field
   * names.  However it is only called when the plugin is being loaded
   * for a handful of fields so it's not performance critical.
   */
#define CB(name)                                         \
  if (strcmp (String_val (fieldv), #name) == 0) {        \
    plugin.name = name##_wrapper;                        \
    assert (!name##_fn);                                 \
    name##_fn = fv;                                      \
    caml_register_generational_global_root (&name##_fn); \
  } else
#include "callbacks.h"
#undef CB
  /* else if the field is not known */ abort ();

  CAMLreturn (Val_unit);
}

/* Called from unload() to remove the GC roots registered by set* functions. */
static void
remove_roots (void)
{
#define CB(name) \
  if (name##_fn) caml_remove_generational_global_root (&name##_fn);
#include "callbacks.h"
#undef CB
}