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
[@@@alert "-unstable"]
open Eio.Std
module Fiber_context = Eio.Private.Fiber_context
module Trace = Eio.Private.Trace
module Suspended = Eio_utils.Suspended
module Zzz = Eio_utils.Zzz
module Lf_queue = Eio_utils.Lf_queue
let statx_works = ref false
type exit = [`Exit_scheduler]
type file_offset = [
| `Pos of Optint.Int63.t
| `Seekable_current
| `Nonseekable_current
]
type amount = Exactly of int | Upto of int
type rw_req = {
op : [`R|`W];
file_offset : file_offset;
fd : Unix.file_descr;
len : amount;
buf : Uring.Region.chunk;
mutable cur_off : int;
action : int Suspended.t;
}
type io_job =
| Read : rw_req -> io_job
| Job_no_cancel : int Suspended.t -> io_job
| Cancel_job : io_job
| Job : int Suspended.t -> io_job
| Write : rw_req -> io_job
| Job_fn : 'a Suspended.t * (int -> [`Exit_scheduler]) -> io_job
type runnable =
| IO : runnable
| Thread : 'a Suspended.t * 'a -> runnable
| Failed_thread : 'a Suspended.t * exn -> runnable
type t = {
uring: io_job Uring.t;
mem: Uring.Region.t option;
io_q: (t -> unit) Queue.t;
mem_q : Uring.Region.chunk Suspended.t Queue.t;
run_q : runnable Lf_queue.t;
eventfd : Eio_unix.Private.Rcfd.t;
need_wakeup : bool Atomic.t;
sleep_q: Zzz.t;
thread_pool : Eio_unix.Private.Thread_pool.t;
}
type _ Effect.t +=
| Enter : (t -> 'a Suspended.t -> unit) -> 'a Effect.t
| Cancel : io_job Uring.job -> unit Effect.t
| Alloc : Uring.Region.chunk option Effect.t
| Alloc_or_wait : Uring.Region.chunk Effect.t
| Free : Uring.Region.chunk -> unit Effect.t
let wake_buffer =
let b = Bytes.create 8 in
Bytes.set_int64_ne b 0 1L;
b
let wakeup t =
Atomic.set t.need_wakeup false;
Eio_unix.Private.Rcfd.use t.eventfd
(fun fd ->
let sent = Unix.single_write fd wake_buffer 0 8 in
assert (sent = 8)
)
~if_closed:ignore
let enqueue_thread st k x =
Lf_queue.push st.run_q (Thread (k, x));
if Atomic.get st.need_wakeup then wakeup st
let enqueue_failed_thread st k ex =
Lf_queue.push st.run_q (Failed_thread (k, ex));
if Atomic.get st.need_wakeup then wakeup st
let enqueue_at_head st k x =
Lf_queue.push_head st.run_q (Thread (k, x))
let enter op fn =
Trace.suspend_fiber op;
Effect.perform (Enter fn)
let submit uring =
if Uring.sqe_ready uring > 0 then
Trace.with_span "submit" (fun () -> Uring.submit uring)
else
0
let rec enqueue_job t fn =
match fn () with
| Some _ as r -> r
| None ->
if submit t.uring > 0 then enqueue_job t fn
else None
let rec enqueue_cancel job t =
Trace.log "cancel";
match enqueue_job t (fun () -> Uring.cancel t.uring job Cancel_job) with
| None -> Queue.push (fun t -> enqueue_cancel job t) t.io_q
| Some _ -> ()
let cancel job = Effect.perform (Cancel job)
let with_cancel_hook ~action t fn =
match Fiber_context.get_error action.Suspended.fiber with
| Some ex -> enqueue_failed_thread t action ex; false
| None ->
match enqueue_job t fn with
| None -> true
| Some job ->
Fiber_context.set_cancel_fn action.fiber (fun _ -> cancel job);
false
let submit_pending_io st =
match Queue.take_opt st.io_q with
| None -> ()
| Some fn ->
Trace.log "submit_pending_io";
fn st
let rec submit_rw_req st ({op; file_offset; fd; buf; len; cur_off; action} as req) =
let {uring;io_q;_} = st in
let off = Uring.Region.to_offset buf + cur_off in
let len = match len with Exactly l | Upto l -> l in
let len = len - cur_off in
let retry = with_cancel_hook ~action st (fun () ->
let file_offset =
match file_offset with
| `Pos x -> Optint.Int63.add x (Optint.Int63.of_int cur_off)
| `Seekable_current -> Optint.Int63.minus_one
| `Nonseekable_current -> Optint.Int63.zero
in
match op with
|`R -> Uring.read_fixed uring ~file_offset fd ~off ~len (Read req)
|`W -> Uring.write_fixed uring ~file_offset fd ~off ~len (Write req)
)
in
if retry then (
Trace.log "await-sqe";
Queue.push (fun st -> submit_rw_req st req) io_q
)
let errno_is_retry = function -62 | -11 | -4 -> true |_ -> false
let rec schedule ({run_q; sleep_q; mem_q; uring; _} as st) : [`Exit_scheduler] =
match Lf_queue.pop run_q with
| None -> assert false
| Some Thread (k, v) ->
Fiber_context.clear_cancel_fn k.fiber;
Suspended.continue k v
| Some Failed_thread (k, ex) ->
Fiber_context.clear_cancel_fn k.fiber;
Suspended.discontinue k ex
| Some IO ->
let now = Mtime_clock.now () in
match Zzz.pop ~now sleep_q with
| `Due k ->
Lf_queue.push run_q IO;
begin match k with
| Fiber k -> Suspended.continue k ()
| Fn fn -> fn (); schedule st
end
| `Wait_until _ | `Nothing as next_due ->
match Uring.get_cqe_nonblocking uring with
| Some { data = runnable; result } ->
Lf_queue.push run_q IO;
handle_complete st ~runnable result
| None ->
let timeout =
match next_due with
| `Wait_until time ->
let time = Mtime.to_uint64_ns time in
let now = Mtime.to_uint64_ns now in
let diff_ns = Int64.sub time now |> Int64.to_float in
Some (diff_ns /. 1e9)
| `Nothing -> None
in
if not (Lf_queue.is_empty st.run_q) then (
ignore (submit uring : int);
Lf_queue.push run_q IO;
schedule st
) else if timeout = None && Uring.active_ops uring = 0 then (
assert (Queue.length mem_q = 0);
Lf_queue.close st.run_q;
`Exit_scheduler
) else (
Atomic.set st.need_wakeup true;
if Lf_queue.is_empty st.run_q then (
Trace.suspend_domain Begin;
let result =
let timeout = Option.value timeout ~default:1e9 in
Uring.wait ~timeout uring
in
Trace.suspend_domain End;
Atomic.set st.need_wakeup false;
Lf_queue.push run_q IO;
match result with
| None ->
schedule st
| Some { data = runnable; result } ->
handle_complete st ~runnable result
) else (
ignore (submit uring : int);
Atomic.set st.need_wakeup false;
Lf_queue.push run_q IO;
schedule st
)
)
and handle_complete st ~runnable result =
submit_pending_io st;
match runnable with
| Read req ->
complete_rw_req st req result
| Write req ->
complete_rw_req st req result
| Job k ->
Fiber_context.clear_cancel_fn k.fiber;
if result >= 0 then Suspended.continue k result
else (
match Fiber_context.get_error k.fiber with
| None -> Suspended.continue k result
| Some e ->
Suspended.discontinue k e
)
| Job_no_cancel k ->
Suspended.continue k result
| Cancel_job ->
schedule st
| Job_fn (k, f) ->
Fiber_context.clear_cancel_fn k.fiber;
begin match Fiber_context.get_error k.fiber with
| None -> f result
| Some e -> Suspended.discontinue k e
end
and complete_rw_req st ({len; cur_off; action; _} as req) res =
Fiber_context.clear_cancel_fn action.fiber;
match res, len with
| 0, _ -> Suspended.discontinue action End_of_file
| e, _ when e < 0 ->
begin match Fiber_context.get_error action.fiber with
| Some e -> Suspended.discontinue action e
| None ->
if errno_is_retry e then (
submit_rw_req st req;
schedule st
) else (
Suspended.continue action e
)
end
| n, Exactly len when n < len - cur_off ->
req.cur_off <- req.cur_off + n;
submit_rw_req st req;
schedule st
| _, Exactly len -> Suspended.continue action len
| n, Upto _ -> Suspended.continue action n
let alloc_buf_or_wait st k =
match st.mem with
| None -> Suspended.discontinue k (Failure "No fixed buffer available")
| Some mem ->
match Uring.Region.alloc mem with
| buf -> Suspended.continue k buf
| exception Uring.Region.No_space ->
Queue.push k st.mem_q;
schedule st
let free_buf st buf =
match Queue.take_opt st.mem_q with
| None -> Uring.Region.free buf
| Some k -> enqueue_thread st k buf
let rec enqueue_poll_add fd poll_mask st action =
Trace.log "poll_add";
let retry = with_cancel_hook ~action st (fun () ->
Uring.poll_add st.uring fd poll_mask (Job action)
)
in
if retry then
Queue.push (fun st -> enqueue_poll_add fd poll_mask st action) st.io_q
let rec enqueue_poll_add_unix fd poll_mask st action cb =
Trace.log "poll_add";
let retry = with_cancel_hook ~action st (fun () ->
Uring.poll_add st.uring fd poll_mask (Job_fn (action, cb))
)
in
if retry then
Queue.push (fun st -> enqueue_poll_add_unix fd poll_mask st action cb) st.io_q
let rec enqueue_readv args st action =
let (file_offset,fd,bufs) = args in
let retry = with_cancel_hook ~action st (fun () ->
Uring.readv st.uring ~file_offset fd bufs (Job action))
in
if retry then
Queue.push (fun st -> enqueue_readv args st action) st.io_q
let read_eventfd fd buf =
let res = enter "read_eventfd" (enqueue_readv (Optint.Int63.zero, fd, [buf])) in
if res < 0 then (
raise @@ Unix.Unix_error (Uring.error_of_errno res, "readv", "")
) else if res = 0 then (
raise End_of_file
) else (
res
)
let monitor_event_fd t =
let buf = Cstruct.create 8 in
Eio_unix.Private.Rcfd.use ~if_closed:(fun () -> failwith "event_fd closed!") t.eventfd @@ fun fd ->
while true do
let got = read_eventfd fd buf in
assert (got = 8);
done;
assert false
let run ~ st main arg =
let rec fork ~new_fiber:fiber fn =
let open Effect.Deep in
Trace.fiber (Fiber_context.tid fiber);
match_with fn ()
{ retc = (fun () -> Fiber_context.destroy fiber; schedule st);
exnc = (fun ex ->
Fiber_context.destroy fiber;
Printexc.raise_with_backtrace ex (Printexc.get_raw_backtrace ())
);
effc = fun (type a) (e : a Effect.t) ->
match e with
| Enter fn -> Some (fun k ->
match Fiber_context.get_error fiber with
| Some e -> discontinue k e
| None ->
let k = { Suspended.k; fiber } in
fn st k;
schedule st
)
| Cancel job -> Some (fun k ->
enqueue_cancel job st;
continue k ()
)
| Eio.Private.Effects.Get_context -> Some (fun k -> continue k fiber)
| Eio.Private.Effects.Suspend f -> Some (fun k ->
let k = { Suspended.k; fiber } in
f fiber (function
| Ok v -> enqueue_thread st k v
| Error ex -> enqueue_failed_thread st k ex
);
schedule st
)
| Eio.Private.Effects.Fork (new_fiber, f) -> Some (fun k ->
let k = { Suspended.k; fiber } in
enqueue_at_head st k ();
fork ~new_fiber f
)
| Eio_unix.Private.Await_readable fd -> Some (fun k ->
match Fiber_context.get_error fiber with
| Some e -> discontinue k e
| None ->
let k = { Suspended.k; fiber } in
enqueue_poll_add_unix fd Uring.Poll_mask.(pollin + pollerr) st k (fun res ->
if res >= 0 then Suspended.continue k ()
else Suspended.discontinue k (Unix.Unix_error (Uring.error_of_errno res, "await_readable", ""))
);
schedule st
)
| Eio_unix.Private.Await_writable fd -> Some (fun k ->
match Fiber_context.get_error fiber with
| Some e -> discontinue k e
| None ->
let k = { Suspended.k; fiber } in
enqueue_poll_add_unix fd Uring.Poll_mask.(pollout + pollerr) st k (fun res ->
if res >= 0 then Suspended.continue k ()
else Suspended.discontinue k (Unix.Unix_error (Uring.error_of_errno res, "await_writable", ""))
);
schedule st
)
| Eio_unix.Private.Thread_pool.Run_in_systhread fn -> Some (fun k ->
let k = { Suspended.k; fiber } in
let enqueue x = enqueue_thread st k (x, st.thread_pool) in
Eio_unix.Private.Thread_pool.submit st.thread_pool ~ctx:fiber ~enqueue fn;
schedule st
)
| Alloc -> Some (fun k ->
match st.mem with
| None -> continue k None
| Some mem ->
match Uring.Region.alloc mem with
| buf -> continue k (Some buf)
| exception Uring.Region.No_space -> continue k None
)
| Alloc_or_wait -> Some (fun k ->
let k = { Suspended.k; fiber } in
alloc_buf_or_wait st k
)
| Free buf -> Some (fun k ->
free_buf st buf;
continue k ()
)
| e -> extra_effects.effc e
}
in
let result = ref None in
let `Exit_scheduler =
let new_fiber = Fiber_context.make_root () in
Domain_local_await.using
~prepare_for_await:Eio.Private.Dla.prepare_for_await
~while_running:(fun () ->
fork ~new_fiber (fun () ->
Switch.run_protected ~name:"eio_linux" (fun sw ->
Fiber.fork_daemon ~sw (fun () -> monitor_event_fd st);
match Eio_unix.Private.Thread_pool.run st.thread_pool (fun () -> main arg) with
| x -> result := Some (Ok x)
| exception ex ->
let bt = Printexc.get_raw_backtrace () in
result := Some (Error (ex, bt))
)
)
)
in
match Option.get !result with
| Ok x -> x
| Error (ex, bt) -> Printexc.raise_with_backtrace ex bt
type config = {
queue_depth : int;
n_blocks : int;
block_size : int;
polling_timeout : int option;
}
let config ?(queue_depth=64) ?n_blocks ?(block_size=4096) ?polling_timeout () =
let n_blocks = Option.value n_blocks ~default:queue_depth in
{
queue_depth;
n_blocks;
block_size;
polling_timeout;
}
external eio_eventfd : int -> Unix.file_descr = "caml_eio_eventfd"
let no_fallback (`Msg msg) = failwith msg
let with_eventfd fn =
let eventfd = Eio_unix.Private.Rcfd.make (eio_eventfd 0) in
let close () =
if not (Eio_unix.Private.Rcfd.close eventfd) then failwith "eventfd already closed!"
in
match fn eventfd with
| x -> close (); x
| exception ex ->
let bt = Printexc.get_raw_backtrace () in
close ();
Printexc.raise_with_backtrace ex bt
let with_sched ?(fallback=no_fallback) config fn =
let { queue_depth; n_blocks; block_size; polling_timeout } = config in
match Uring.create ~queue_depth ?polling_timeout () with
| exception Unix.Unix_error(ENOSYS, _, _) -> fallback (`Msg "io_uring is not available on this system")
| exception Unix.Unix_error(EPERM, _, _) -> fallback (`Msg "io_uring is not available (permission denied)")
| uring ->
let probe = Uring.get_probe uring in
if not (Uring.op_supported probe Uring.Op.mkdirat) then (
Uring.exit uring;
fallback (`Msg "Linux >= 5.15 is required for io_uring support")
) else (
statx_works := Uring.op_supported probe Uring.Op.msg_ring;
match
let mem =
let fixed_buf_len = block_size * n_blocks in
let buf = Bigarray.(Array1.create char c_layout fixed_buf_len) in
match Uring.set_fixed_buffer uring buf with
| Ok () ->
Some (Uring.Region.init ~block_size buf n_blocks)
| Error `ENOMEM ->
None
in
let run_q = Lf_queue.create () in
Lf_queue.push run_q IO;
let sleep_q = Zzz.create () in
let io_q = Queue.create () in
let mem_q = Queue.create () in
with_eventfd @@ fun eventfd ->
let thread_pool = Eio_unix.Private.Thread_pool.create ~sleep_q in
fn { mem; uring; run_q; io_q; mem_q; eventfd; need_wakeup = Atomic.make false; sleep_q; thread_pool }
with
| x -> Uring.exit uring; x
| exception ex ->
let bt = Printexc.get_raw_backtrace () in
begin
try Uring.exit uring
with ex2 ->
let bt2 = Printexc.get_raw_backtrace () in
raise (Eio.Exn.Multiple [(ex2, bt2); (ex, bt)])
end;
Printexc.raise_with_backtrace ex bt
)