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

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

Fix io to no longer use monitors since some usages aren't in threads

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