source: libcfa/src/concurrency/io.cfa @ 90a10e8

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 90a10e8 was e9c0b4c, checked in by Thierry Delisle <tdelisle@…>, 3 years ago

I/O drain now keeps the schedlock for the duration of the call.
(Rather than locking/unlocking for each thread).

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