source: libcfa/src/concurrency/io.cfa@ a76202d

ADT ast-experimental enum pthread-emulation qualifiedEnum
Last change on this file since a76202d was 4ecc35a, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Added spin lock to io drain.
last step before completion fairness

  • Property mode set to 100644
File size: 17.5 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2020 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// io.cfa --
8//
9// Author : Thierry Delisle
10// Created On : Thu Apr 23 17:31:00 2020
11// Last Modified By :
12// Last Modified On :
13// Update Count :
14//
15
16#define __cforall_thread__
17#define _GNU_SOURCE
18
19#if defined(__CFA_DEBUG__)
20 // #define __CFA_DEBUG_PRINT_IO__
21 // #define __CFA_DEBUG_PRINT_IO_CORE__
22#endif
23
24
25#if defined(CFA_HAVE_LINUX_IO_URING_H)
26 #include <errno.h>
27 #include <signal.h>
28 #include <stdint.h>
29 #include <string.h>
30 #include <unistd.h>
31
32 extern "C" {
33 #include <sys/syscall.h>
34 #include <sys/eventfd.h>
35 #include <sys/uio.h>
36
37 #include <linux/io_uring.h>
38 }
39
40 #include "stats.hfa"
41 #include "kernel.hfa"
42 #include "kernel/fwd.hfa"
43 #include "kernel/private.hfa"
44 #include "io/types.hfa"
45
46 __attribute__((unused)) static const char * opcodes[] = {
47 "OP_NOP",
48 "OP_READV",
49 "OP_WRITEV",
50 "OP_FSYNC",
51 "OP_READ_FIXED",
52 "OP_WRITE_FIXED",
53 "OP_POLL_ADD",
54 "OP_POLL_REMOVE",
55 "OP_SYNC_FILE_RANGE",
56 "OP_SENDMSG",
57 "OP_RECVMSG",
58 "OP_TIMEOUT",
59 "OP_TIMEOUT_REMOVE",
60 "OP_ACCEPT",
61 "OP_ASYNC_CANCEL",
62 "OP_LINK_TIMEOUT",
63 "OP_CONNECT",
64 "OP_FALLOCATE",
65 "OP_OPENAT",
66 "OP_CLOSE",
67 "OP_FILES_UPDATE",
68 "OP_STATX",
69 "OP_READ",
70 "OP_WRITE",
71 "OP_FADVISE",
72 "OP_MADVISE",
73 "OP_SEND",
74 "OP_RECV",
75 "OP_OPENAT2",
76 "OP_EPOLL_CTL",
77 "OP_SPLICE",
78 "OP_PROVIDE_BUFFERS",
79 "OP_REMOVE_BUFFERS",
80 "OP_TEE",
81 "INVALID_OP"
82 };
83
84 static $io_context * __ioarbiter_allocate( $io_arbiter & this, __u32 idxs[], __u32 want );
85 static void __ioarbiter_submit( $io_context * , __u32 idxs[], __u32 have, bool lazy );
86 static void __ioarbiter_flush ( $io_context & );
87 static inline void __ioarbiter_notify( $io_context & ctx );
88//=============================================================================================
89// I/O Polling
90//=============================================================================================
91 static inline unsigned __flush( struct $io_context & );
92 static inline __u32 __release_sqes( struct $io_context & );
93 extern void __kernel_unpark( thread$ * thrd, unpark_hint );
94
95 bool __cfa_io_drain( $io_context * ctx ) {
96 /* paranoid */ verify( ! __preemption_enabled() );
97 /* paranoid */ verify( ready_schedule_islocked() );
98 /* paranoid */ verify( ctx );
99
100 // Drain the queue
101 unsigned head = *ctx->cq.head;
102 unsigned tail = *ctx->cq.tail;
103 const __u32 mask = *ctx->cq.mask;
104
105 __u32 count = tail - head;
106 __STATS__( false, io.calls.drain++; io.calls.completed += count; )
107
108 if(count == 0) return false;
109
110 if(!__atomic_try_acquire(&ctx->cq.lock)) {
111 return false;
112 }
113
114 for(i; count) {
115 unsigned idx = (head + i) & mask;
116 volatile struct io_uring_cqe & cqe = ctx->cq.cqes[idx];
117
118 /* paranoid */ verify(&cqe);
119
120 struct io_future_t * future = (struct io_future_t *)(uintptr_t)cqe.user_data;
121 __cfadbg_print_safe( io, "Kernel I/O : Syscall completed : cqe %p, result %d for %p\n", &cqe, cqe.res, future );
122
123 __kernel_unpark( fulfil( *future, cqe.res, false ), UNPARK_LOCAL );
124 }
125
126 __cfadbg_print_safe(io, "Kernel I/O : %u completed\n", count);
127
128 // Mark to the kernel that the cqe has been seen
129 // Ensure that the kernel only sees the new value of the head index after the CQEs have been read.
130 __atomic_store_n( ctx->cq.head, head + count, __ATOMIC_SEQ_CST );
131
132 /* paranoid */ verify( ready_schedule_islocked() );
133 /* paranoid */ verify( ! __preemption_enabled() );
134
135 __atomic_unlock(&ctx->cq.lock);
136
137 return true;
138 }
139
140 bool __cfa_io_flush( processor * proc, int min_comp ) {
141 /* paranoid */ verify( ! __preemption_enabled() );
142 /* paranoid */ verify( proc );
143 /* paranoid */ verify( proc->io.ctx );
144
145 __attribute__((unused)) cluster * cltr = proc->cltr;
146 $io_context & ctx = *proc->io.ctx;
147
148 __ioarbiter_flush( ctx );
149
150 if(ctx.sq.to_submit != 0 || min_comp > 0) {
151
152 __STATS__( true, io.calls.flush++; )
153 int ret = syscall( __NR_io_uring_enter, ctx.fd, ctx.sq.to_submit, min_comp, min_comp > 0 ? IORING_ENTER_GETEVENTS : 0, (sigset_t *)0p, _NSIG / 8);
154 if( ret < 0 ) {
155 switch((int)errno) {
156 case EAGAIN:
157 case EINTR:
158 case EBUSY:
159 // Update statistics
160 __STATS__( false, io.calls.errors.busy ++; )
161 return false;
162 default:
163 abort( "KERNEL ERROR: IO_URING SYSCALL - (%d) %s\n", (int)errno, strerror(errno) );
164 }
165 }
166
167 __cfadbg_print_safe(io, "Kernel I/O : %u submitted to io_uring %d\n", ret, ctx.fd);
168 __STATS__( true, io.calls.submitted += ret; )
169 /* paranoid */ verify( ctx.sq.to_submit <= *ctx.sq.num );
170 /* paranoid */ verify( ctx.sq.to_submit >= ret );
171
172 ctx.sq.to_submit -= ret;
173
174 /* paranoid */ verify( ctx.sq.to_submit <= *ctx.sq.num );
175
176 // Release the consumed SQEs
177 __release_sqes( ctx );
178
179 /* paranoid */ verify( ! __preemption_enabled() );
180
181 __atomic_store_n(&ctx.proc->io.pending, false, __ATOMIC_RELAXED);
182 }
183
184 ready_schedule_lock();
185 bool ret = __cfa_io_drain( &ctx );
186 ready_schedule_unlock();
187 return ret;
188 }
189
190//=============================================================================================
191// I/O Submissions
192//=============================================================================================
193
194// Submition steps :
195// 1 - Allocate a queue entry. The ring already has memory for all entries but only the ones
196// listed in sq.array are visible by the kernel. For those not listed, the kernel does not
197// offer any assurance that an entry is not being filled by multiple flags. Therefore, we
198// need to write an allocator that allows allocating concurrently.
199//
200// 2 - Actually fill the submit entry, this is the only simple and straightforward step.
201//
202// 3 - Append the entry index to the array and adjust the tail accordingly. This operation
203// needs to arrive to two concensus at the same time:
204// A - The order in which entries are listed in the array: no two threads must pick the
205// same index for their entries
206// B - When can the tail be update for the kernel. EVERY entries in the array between
207// head and tail must be fully filled and shouldn't ever be touched again.
208//
209 //=============================================================================================
210 // Allocation
211 // for user's convenience fill the sqes from the indexes
212 static inline void __fill(struct io_uring_sqe * out_sqes[], __u32 want, __u32 idxs[], struct $io_context * ctx) {
213 struct io_uring_sqe * sqes = ctx->sq.sqes;
214 for(i; want) {
215 __cfadbg_print_safe(io, "Kernel I/O : filling loop\n");
216 out_sqes[i] = &sqes[idxs[i]];
217 }
218 }
219
220 // Try to directly allocate from the a given context
221 // Not thread-safe
222 static inline bool __alloc(struct $io_context * ctx, __u32 idxs[], __u32 want) {
223 __sub_ring_t & sq = ctx->sq;
224 const __u32 mask = *sq.mask;
225 __u32 fhead = sq.free_ring.head; // get the current head of the queue
226 __u32 ftail = sq.free_ring.tail; // get the current tail of the queue
227
228 // If we don't have enough sqes, fail
229 if((ftail - fhead) < want) { return false; }
230
231 // copy all the indexes we want from the available list
232 for(i; want) {
233 __cfadbg_print_safe(io, "Kernel I/O : allocating loop\n");
234 idxs[i] = sq.free_ring.array[(fhead + i) & mask];
235 }
236
237 // Advance the head to mark the indexes as consumed
238 __atomic_store_n(&sq.free_ring.head, fhead + want, __ATOMIC_RELEASE);
239
240 // return success
241 return true;
242 }
243
244 // Allocate an submit queue entry.
245 // The kernel cannot see these entries until they are submitted, but other threads must be
246 // able to see which entries can be used and which are already un used by an other thread
247 // for convenience, return both the index and the pointer to the sqe
248 // sqe == &sqes[idx]
249 struct $io_context * cfa_io_allocate(struct io_uring_sqe * sqes[], __u32 idxs[], __u32 want) {
250 __cfadbg_print_safe(io, "Kernel I/O : attempting to allocate %u\n", want);
251
252 disable_interrupts();
253 processor * proc = __cfaabi_tls.this_processor;
254 $io_context * ctx = proc->io.ctx;
255 /* paranoid */ verify( __cfaabi_tls.this_processor );
256 /* paranoid */ verify( ctx );
257
258 __cfadbg_print_safe(io, "Kernel I/O : attempting to fast allocation\n");
259
260 // We can proceed to the fast path
261 if( __alloc(ctx, idxs, want) ) {
262 // Allocation was successful
263 __STATS__( true, io.alloc.fast += 1; )
264 enable_interrupts();
265
266 __cfadbg_print_safe(io, "Kernel I/O : fast allocation successful from ring %d\n", ctx->fd);
267
268 __fill( sqes, want, idxs, ctx );
269 return ctx;
270 }
271 // The fast path failed, fallback
272 __STATS__( true, io.alloc.fail += 1; )
273
274 // Fast path failed, fallback on arbitration
275 __STATS__( true, io.alloc.slow += 1; )
276 enable_interrupts();
277
278 $io_arbiter * ioarb = proc->cltr->io.arbiter;
279 /* paranoid */ verify( ioarb );
280
281 __cfadbg_print_safe(io, "Kernel I/O : falling back on arbiter for allocation\n");
282
283 struct $io_context * ret = __ioarbiter_allocate(*ioarb, idxs, want);
284
285 __cfadbg_print_safe(io, "Kernel I/O : slow allocation completed from ring %d\n", ret->fd);
286
287 __fill( sqes, want, idxs,ret );
288 return ret;
289 }
290
291 //=============================================================================================
292 // submission
293 static inline void __submit_only( struct $io_context * ctx, __u32 idxs[], __u32 have) {
294 // We can proceed to the fast path
295 // Get the right objects
296 __sub_ring_t & sq = ctx->sq;
297 const __u32 mask = *sq.mask;
298 __u32 tail = *sq.kring.tail;
299
300 // Add the sqes to the array
301 for( i; have ) {
302 __cfadbg_print_safe(io, "Kernel I/O : __submit loop\n");
303 sq.kring.array[ (tail + i) & mask ] = idxs[i];
304 }
305
306 // Make the sqes visible to the submitter
307 __atomic_store_n(sq.kring.tail, tail + have, __ATOMIC_RELEASE);
308 sq.to_submit += have;
309
310 __atomic_store_n(&ctx->proc->io.pending, true, __ATOMIC_RELAXED);
311 __atomic_store_n(&ctx->proc->io.dirty , true, __ATOMIC_RELAXED);
312 }
313
314 static inline void __submit( struct $io_context * ctx, __u32 idxs[], __u32 have, bool lazy) {
315 __sub_ring_t & sq = ctx->sq;
316 __submit_only(ctx, idxs, have);
317
318 if(sq.to_submit > 30) {
319 __tls_stats()->io.flush.full++;
320 __cfa_io_flush( ctx->proc, 0 );
321 }
322 if(!lazy) {
323 __tls_stats()->io.flush.eager++;
324 __cfa_io_flush( ctx->proc, 0 );
325 }
326 }
327
328 void cfa_io_submit( struct $io_context * inctx, __u32 idxs[], __u32 have, bool lazy ) __attribute__((nonnull (1))) {
329 __cfadbg_print_safe(io, "Kernel I/O : attempting to submit %u (%s)\n", have, lazy ? "lazy" : "eager");
330
331 disable_interrupts();
332 processor * proc = __cfaabi_tls.this_processor;
333 $io_context * ctx = proc->io.ctx;
334 /* paranoid */ verify( __cfaabi_tls.this_processor );
335 /* paranoid */ verify( ctx );
336
337 // Can we proceed to the fast path
338 if( ctx == inctx ) // We have the right instance?
339 {
340 __submit(ctx, idxs, have, lazy);
341
342 // Mark the instance as no longer in-use, re-enable interrupts and return
343 __STATS__( true, io.submit.fast += 1; )
344 enable_interrupts();
345
346 __cfadbg_print_safe(io, "Kernel I/O : submitted on fast path\n");
347 return;
348 }
349
350 // Fast path failed, fallback on arbitration
351 __STATS__( true, io.submit.slow += 1; )
352 enable_interrupts();
353
354 __cfadbg_print_safe(io, "Kernel I/O : falling back on arbiter for submission\n");
355
356 __ioarbiter_submit(inctx, idxs, have, lazy);
357 }
358
359 //=============================================================================================
360 // Flushing
361 // Go through the ring's submit queue and release everything that has already been consumed
362 // by io_uring
363 // This cannot be done by multiple threads
364 static __u32 __release_sqes( struct $io_context & ctx ) {
365 const __u32 mask = *ctx.sq.mask;
366
367 __attribute__((unused))
368 __u32 ctail = *ctx.sq.kring.tail; // get the current tail of the queue
369 __u32 chead = *ctx.sq.kring.head; // get the current head of the queue
370 __u32 phead = ctx.sq.kring.released; // get the head the last time we were here
371
372 __u32 ftail = ctx.sq.free_ring.tail; // get the current tail of the queue
373
374 // the 3 fields are organized like this diagram
375 // except it's are ring
376 // ---+--------+--------+----
377 // ---+--------+--------+----
378 // ^ ^ ^
379 // phead chead ctail
380
381 // make sure ctail doesn't wrap around and reach phead
382 /* paranoid */ verify(
383 (ctail >= chead && chead >= phead)
384 || (chead >= phead && phead >= ctail)
385 || (phead >= ctail && ctail >= chead)
386 );
387
388 // find the range we need to clear
389 __u32 count = chead - phead;
390
391 if(count == 0) {
392 return 0;
393 }
394
395 // We acquired an previous-head/current-head range
396 // go through the range and release the sqes
397 for( i; count ) {
398 __cfadbg_print_safe(io, "Kernel I/O : release loop\n");
399 __u32 idx = ctx.sq.kring.array[ (phead + i) & mask ];
400 ctx.sq.free_ring.array[ (ftail + i) & mask ] = idx;
401 }
402
403 ctx.sq.kring.released = chead; // note up to were we processed
404 __atomic_store_n(&ctx.sq.free_ring.tail, ftail + count, __ATOMIC_SEQ_CST);
405
406 __ioarbiter_notify(ctx);
407
408 return count;
409 }
410
411//=============================================================================================
412// I/O Arbiter
413//=============================================================================================
414 static inline bool enqueue(__outstanding_io_queue & queue, __outstanding_io & item) {
415 bool was_empty;
416
417 // Lock the list, it's not thread safe
418 lock( queue.lock __cfaabi_dbg_ctx2 );
419 {
420 was_empty = empty(queue.queue);
421
422 // Add our request to the list
423 add( queue.queue, item );
424
425 // Mark as pending
426 __atomic_store_n( &queue.empty, false, __ATOMIC_SEQ_CST );
427 }
428 unlock( queue.lock );
429
430 return was_empty;
431 }
432
433 static inline bool empty(__outstanding_io_queue & queue ) {
434 return __atomic_load_n( &queue.empty, __ATOMIC_SEQ_CST);
435 }
436
437 static $io_context * __ioarbiter_allocate( $io_arbiter & this, __u32 idxs[], __u32 want ) {
438 __cfadbg_print_safe(io, "Kernel I/O : arbiter allocating\n");
439
440 __STATS__( false, io.alloc.block += 1; )
441
442 // No one has any resources left, wait for something to finish
443 // We need to add ourself to a list of pending allocs and wait for an answer
444 __pending_alloc pa;
445 pa.idxs = idxs;
446 pa.want = want;
447
448 enqueue(this.pending, (__outstanding_io&)pa);
449
450 wait( pa.sem );
451
452 return pa.ctx;
453
454 }
455
456 static void __ioarbiter_notify( $io_arbiter & this, $io_context * ctx ) {
457 /* paranoid */ verify( !empty(this.pending.queue) );
458
459 lock( this.pending.lock __cfaabi_dbg_ctx2 );
460 {
461 while( !empty(this.pending.queue) ) {
462 __cfadbg_print_safe(io, "Kernel I/O : notifying\n");
463 __u32 have = ctx->sq.free_ring.tail - ctx->sq.free_ring.head;
464 __pending_alloc & pa = (__pending_alloc&)head( this.pending.queue );
465
466 if( have > pa.want ) goto DONE;
467 drop( this.pending.queue );
468
469 /* paranoid */__attribute__((unused)) bool ret =
470
471 __alloc(ctx, pa.idxs, pa.want);
472
473 /* paranoid */ verify( ret );
474
475 pa.ctx = ctx;
476
477 post( pa.sem );
478 }
479
480 this.pending.empty = true;
481 DONE:;
482 }
483 unlock( this.pending.lock );
484 }
485
486 static void __ioarbiter_notify( $io_context & ctx ) {
487 if(!empty( ctx.arbiter->pending )) {
488 __ioarbiter_notify( *ctx.arbiter, &ctx );
489 }
490 }
491
492 // Simply append to the pending
493 static void __ioarbiter_submit( $io_context * ctx, __u32 idxs[], __u32 have, bool lazy ) {
494 __cfadbg_print_safe(io, "Kernel I/O : submitting %u from the arbiter to context %u\n", have, ctx->fd);
495
496 __cfadbg_print_safe(io, "Kernel I/O : waiting to submit %u\n", have);
497
498 __external_io ei;
499 ei.idxs = idxs;
500 ei.have = have;
501 ei.lazy = lazy;
502
503 bool we = enqueue(ctx->ext_sq, (__outstanding_io&)ei);
504
505 __atomic_store_n(&ctx->proc->io.pending, true, __ATOMIC_SEQ_CST);
506
507 if( we ) {
508 sigval_t value = { PREEMPT_IO };
509 pthread_sigqueue(ctx->proc->kernel_thread, SIGUSR1, value);
510 }
511
512 wait( ei.sem );
513
514 __cfadbg_print_safe(io, "Kernel I/O : %u submitted from arbiter\n", have);
515 }
516
517 static void __ioarbiter_flush( $io_context & ctx ) {
518 if(!empty( ctx.ext_sq )) {
519 __STATS__( false, io.flush.external += 1; )
520
521 __cfadbg_print_safe(io, "Kernel I/O : arbiter flushing\n");
522
523 lock( ctx.ext_sq.lock __cfaabi_dbg_ctx2 );
524 {
525 while( !empty(ctx.ext_sq.queue) ) {
526 __external_io & ei = (__external_io&)drop( ctx.ext_sq.queue );
527
528 __submit_only(&ctx, ei.idxs, ei.have);
529
530 post( ei.sem );
531 }
532
533 ctx.ext_sq.empty = true;
534 }
535 unlock(ctx.ext_sq.lock );
536 }
537 }
538
539 #if defined(CFA_WITH_IO_URING_IDLE)
540 bool __kernel_read(processor * proc, io_future_t & future, iovec & iov, int fd) {
541 $io_context * ctx = proc->io.ctx;
542 /* paranoid */ verify( ! __preemption_enabled() );
543 /* paranoid */ verify( proc == __cfaabi_tls.this_processor );
544 /* paranoid */ verify( ctx );
545
546 __u32 idx;
547 struct io_uring_sqe * sqe;
548
549 // We can proceed to the fast path
550 if( !__alloc(ctx, &idx, 1) ) return false;
551
552 // Allocation was successful
553 __fill( &sqe, 1, &idx, ctx );
554
555 sqe->user_data = (uintptr_t)&future;
556 sqe->flags = 0;
557 sqe->fd = fd;
558 sqe->off = 0;
559 sqe->ioprio = 0;
560 sqe->fsync_flags = 0;
561 sqe->__pad2[0] = 0;
562 sqe->__pad2[1] = 0;
563 sqe->__pad2[2] = 0;
564
565 #if defined(CFA_HAVE_IORING_OP_READ)
566 sqe->opcode = IORING_OP_READ;
567 sqe->addr = (uint64_t)iov.iov_base;
568 sqe->len = iov.iov_len;
569 #elif defined(CFA_HAVE_READV) && defined(CFA_HAVE_IORING_OP_READV)
570 sqe->opcode = IORING_OP_READV;
571 sqe->addr = (uintptr_t)&iov;
572 sqe->len = 1;
573 #else
574 #error CFA_WITH_IO_URING_IDLE but none of CFA_HAVE_READV, CFA_HAVE_IORING_OP_READV or CFA_HAVE_IORING_OP_READ defined
575 #endif
576
577 asm volatile("": : :"memory");
578
579 /* paranoid */ verify( sqe->user_data == (uintptr_t)&future );
580 __submit( ctx, &idx, 1, true );
581
582 /* paranoid */ verify( proc == __cfaabi_tls.this_processor );
583 /* paranoid */ verify( ! __preemption_enabled() );
584
585 return true;
586 }
587 #endif
588#endif
Note: See TracBrowser for help on using the repository browser.