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

ADTast-experimentalenumforall-pointer-decaypthread-emulationqualifiedEnum
Last change on this file since e8ac228 was e8ac228, checked in by Thierry Delisle <tdelisle@…>, 2 years ago

Fix major bug where to few items were submitted.

  • Property mode set to 100644
File size: 15.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
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, unpark_hint );
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 ), UNPARK_LOCAL );
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                __attribute__((unused)) cluster * cltr = proc->cltr;
141                $io_context & ctx = *proc->io.ctx;
142
143                // for(i; 2) {
144                //      unsigned idx = proc->rdq.id + i;
145                //      cltr->ready_queue.lanes.tscs[idx].tv = -1ull;
146                // }
147
148                __ioarbiter_flush( ctx );
149
150                __STATS__( true, io.calls.flush++; )
151                int ret = syscall( __NR_io_uring_enter, ctx.fd, ctx.sq.to_submit, 0, 0, (sigset_t *)0p, _NSIG / 8);
152                if( ret < 0 ) {
153                        switch((int)errno) {
154                        case EAGAIN:
155                        case EINTR:
156                        case EBUSY:
157                                // Update statistics
158                                __STATS__( false, io.calls.errors.busy ++; )
159                                // for(i; 2) {
160                                //      unsigned idx = proc->rdq.id + i;
161                                //      cltr->ready_queue.lanes.tscs[idx].tv = rdtscl();
162                                // }
163                                return;
164                        default:
165                                abort( "KERNEL ERROR: IO_URING SYSCALL - (%d) %s\n", (int)errno, strerror(errno) );
166                        }
167                }
168
169                __cfadbg_print_safe(io, "Kernel I/O : %u submitted to io_uring %d\n", ret, ctx.fd);
170                __STATS__( true, io.calls.submitted += ret; )
171                /* paranoid */ verify( ctx.sq.to_submit <= *ctx.sq.num );
172                /* paranoid */ verify( ctx.sq.to_submit >= ret );
173
174                ctx.sq.to_submit -= ret;
175
176                /* paranoid */ verify( ctx.sq.to_submit <= *ctx.sq.num );
177
178                // Release the consumed SQEs
179                __release_sqes( ctx );
180
181                /* paranoid */ verify( ! __preemption_enabled() );
182
183                ctx.proc->io.pending = false;
184
185                __cfa_io_drain( proc );
186                // for(i; 2) {
187                //      unsigned idx = proc->rdq.id + i;
188                //      cltr->ready_queue.lanes.tscs[idx].tv = rdtscl();
189                // }
190        }
191
192//=============================================================================================
193// I/O Submissions
194//=============================================================================================
195
196// Submition steps :
197// 1 - Allocate a queue entry. The ring already has memory for all entries but only the ones
198//     listed in sq.array are visible by the kernel. For those not listed, the kernel does not
199//     offer any assurance that an entry is not being filled by multiple flags. Therefore, we
200//     need to write an allocator that allows allocating concurrently.
201//
202// 2 - Actually fill the submit entry, this is the only simple and straightforward step.
203//
204// 3 - Append the entry index to the array and adjust the tail accordingly. This operation
205//     needs to arrive to two concensus at the same time:
206//     A - The order in which entries are listed in the array: no two threads must pick the
207//         same index for their entries
208//     B - When can the tail be update for the kernel. EVERY entries in the array between
209//         head and tail must be fully filled and shouldn't ever be touched again.
210//
211        //=============================================================================================
212        // Allocation
213        // for user's convenience fill the sqes from the indexes
214        static inline void __fill(struct io_uring_sqe * out_sqes[], __u32 want, __u32 idxs[], struct $io_context * ctx)  {
215                struct io_uring_sqe * sqes = ctx->sq.sqes;
216                for(i; want) {
217                        __cfadbg_print_safe(io, "Kernel I/O : filling loop\n");
218                        out_sqes[i] = &sqes[idxs[i]];
219                }
220        }
221
222        // Try to directly allocate from the a given context
223        // Not thread-safe
224        static inline bool __alloc(struct $io_context * ctx, __u32 idxs[], __u32 want) {
225                __sub_ring_t & sq = ctx->sq;
226                const __u32 mask  = *sq.mask;
227                __u32 fhead = sq.free_ring.head;    // get the current head of the queue
228                __u32 ftail = sq.free_ring.tail;    // get the current tail of the queue
229
230                // If we don't have enough sqes, fail
231                if((ftail - fhead) < want) { return false; }
232
233                // copy all the indexes we want from the available list
234                for(i; want) {
235                        __cfadbg_print_safe(io, "Kernel I/O : allocating loop\n");
236                        idxs[i] = sq.free_ring.array[(fhead + i) & mask];
237                }
238
239                // Advance the head to mark the indexes as consumed
240                __atomic_store_n(&sq.free_ring.head, fhead + want, __ATOMIC_RELEASE);
241
242                // return success
243                return true;
244        }
245
246        // Allocate an submit queue entry.
247        // The kernel cannot see these entries until they are submitted, but other threads must be
248        // able to see which entries can be used and which are already un used by an other thread
249        // for convenience, return both the index and the pointer to the sqe
250        // sqe == &sqes[idx]
251        struct $io_context * cfa_io_allocate(struct io_uring_sqe * sqes[], __u32 idxs[], __u32 want) {
252                __cfadbg_print_safe(io, "Kernel I/O : attempting to allocate %u\n", want);
253
254                disable_interrupts();
255                processor * proc = __cfaabi_tls.this_processor;
256                $io_context * ctx = proc->io.ctx;
257                /* paranoid */ verify( __cfaabi_tls.this_processor );
258                /* paranoid */ verify( ctx );
259
260                __cfadbg_print_safe(io, "Kernel I/O : attempting to fast allocation\n");
261
262                // We can proceed to the fast path
263                if( __alloc(ctx, idxs, want) ) {
264                        // Allocation was successful
265                        __STATS__( true, io.alloc.fast += 1; )
266                        enable_interrupts();
267
268                        __cfadbg_print_safe(io, "Kernel I/O : fast allocation successful from ring %d\n", ctx->fd);
269
270                        __fill( sqes, want, idxs, ctx );
271                        return ctx;
272                }
273                // The fast path failed, fallback
274                __STATS__( true, io.alloc.fail += 1; )
275
276                // Fast path failed, fallback on arbitration
277                __STATS__( true, io.alloc.slow += 1; )
278                enable_interrupts();
279
280                $io_arbiter * ioarb = proc->cltr->io.arbiter;
281                /* paranoid */ verify( ioarb );
282
283                __cfadbg_print_safe(io, "Kernel I/O : falling back on arbiter for allocation\n");
284
285                struct $io_context * ret = __ioarbiter_allocate(*ioarb, idxs, want);
286
287                __cfadbg_print_safe(io, "Kernel I/O : slow allocation completed from ring %d\n", ret->fd);
288
289                __fill( sqes, want, idxs,ret );
290                return ret;
291        }
292
293
294        //=============================================================================================
295        // submission
296        static inline void __submit( struct $io_context * ctx, __u32 idxs[], __u32 have, bool lazy) {
297                // We can proceed to the fast path
298                // Get the right objects
299                __sub_ring_t & sq = ctx->sq;
300                const __u32 mask  = *sq.mask;
301                __u32 tail = *sq.kring.tail;
302
303                // Add the sqes to the array
304                for( i; have ) {
305                        __cfadbg_print_safe(io, "Kernel I/O : __submit loop\n");
306                        sq.kring.array[ (tail + i) & mask ] = idxs[i];
307                }
308
309                // Make the sqes visible to the submitter
310                __atomic_store_n(sq.kring.tail, tail + have, __ATOMIC_RELEASE);
311                sq.to_submit += have;
312
313                ctx->proc->io.pending = true;
314                ctx->proc->io.dirty   = true;
315                if(sq.to_submit > 30 || !lazy) {
316                        ready_schedule_lock();
317                        __cfa_io_flush( ctx->proc );
318                        ready_schedule_unlock();
319                }
320        }
321
322        void cfa_io_submit( struct $io_context * inctx, __u32 idxs[], __u32 have, bool lazy ) __attribute__((nonnull (1))) {
323                __cfadbg_print_safe(io, "Kernel I/O : attempting to submit %u (%s)\n", have, lazy ? "lazy" : "eager");
324
325                disable_interrupts();
326                processor * proc = __cfaabi_tls.this_processor;
327                $io_context * ctx = proc->io.ctx;
328                /* paranoid */ verify( __cfaabi_tls.this_processor );
329                /* paranoid */ verify( ctx );
330
331                // Can we proceed to the fast path
332                if( ctx == inctx )              // We have the right instance?
333                {
334                        __submit(ctx, idxs, have, lazy);
335
336                        // Mark the instance as no longer in-use, re-enable interrupts and return
337                        __STATS__( true, io.submit.fast += 1; )
338                        enable_interrupts();
339
340                        __cfadbg_print_safe(io, "Kernel I/O : submitted on fast path\n");
341                        return;
342                }
343
344                // Fast path failed, fallback on arbitration
345                __STATS__( true, io.submit.slow += 1; )
346                enable_interrupts();
347
348                __cfadbg_print_safe(io, "Kernel I/O : falling back on arbiter for submission\n");
349
350                __ioarbiter_submit(inctx, idxs, have, lazy);
351        }
352
353        //=============================================================================================
354        // Flushing
355        // Go through the ring's submit queue and release everything that has already been consumed
356        // by io_uring
357        // This cannot be done by multiple threads
358        static __u32 __release_sqes( struct $io_context & ctx ) {
359                const __u32 mask = *ctx.sq.mask;
360
361                __attribute__((unused))
362                __u32 ctail = *ctx.sq.kring.tail;    // get the current tail of the queue
363                __u32 chead = *ctx.sq.kring.head;        // get the current head of the queue
364                __u32 phead = ctx.sq.kring.released; // get the head the last time we were here
365
366                __u32 ftail = ctx.sq.free_ring.tail;  // get the current tail of the queue
367
368                // the 3 fields are organized like this diagram
369                // except it's are ring
370                // ---+--------+--------+----
371                // ---+--------+--------+----
372                //    ^        ^        ^
373                // phead    chead    ctail
374
375                // make sure ctail doesn't wrap around and reach phead
376                /* paranoid */ verify(
377                           (ctail >= chead && chead >= phead)
378                        || (chead >= phead && phead >= ctail)
379                        || (phead >= ctail && ctail >= chead)
380                );
381
382                // find the range we need to clear
383                __u32 count = chead - phead;
384
385                if(count == 0) {
386                        return 0;
387                }
388
389                // We acquired an previous-head/current-head range
390                // go through the range and release the sqes
391                for( i; count ) {
392                        __cfadbg_print_safe(io, "Kernel I/O : release loop\n");
393                        __u32 idx = ctx.sq.kring.array[ (phead + i) & mask ];
394                        ctx.sq.free_ring.array[ (ftail + i) & mask ] = idx;
395                }
396
397                ctx.sq.kring.released = chead;          // note up to were we processed
398                __atomic_store_n(&ctx.sq.free_ring.tail, ftail + count, __ATOMIC_SEQ_CST);
399
400                __ioarbiter_notify(ctx);
401
402                return count;
403        }
404
405//=============================================================================================
406// I/O Arbiter
407//=============================================================================================
408        static inline void block(__outstanding_io_queue & queue, __outstanding_io & item) {
409                // Lock the list, it's not thread safe
410                lock( queue.lock __cfaabi_dbg_ctx2 );
411                {
412                        // Add our request to the list
413                        add( queue.queue, item );
414
415                        // Mark as pending
416                        __atomic_store_n( &queue.empty, false, __ATOMIC_SEQ_CST );
417                }
418                unlock( queue.lock );
419
420                wait( item.sem );
421        }
422
423        static inline bool empty(__outstanding_io_queue & queue ) {
424                return __atomic_load_n( &queue.empty, __ATOMIC_SEQ_CST);
425        }
426
427        static $io_context * __ioarbiter_allocate( $io_arbiter & this, __u32 idxs[], __u32 want ) {
428                __cfadbg_print_safe(io, "Kernel I/O : arbiter allocating\n");
429
430                __STATS__( false, io.alloc.block += 1; )
431
432                // No one has any resources left, wait for something to finish
433                // We need to add ourself to a list of pending allocs and wait for an answer
434                __pending_alloc pa;
435                pa.idxs = idxs;
436                pa.want = want;
437
438                block(this.pending, (__outstanding_io&)pa);
439
440                return pa.ctx;
441
442        }
443
444        static void __ioarbiter_notify( $io_arbiter & this, $io_context * ctx ) {
445                /* paranoid */ verify( !empty(this.pending.queue) );
446
447                lock( this.pending.lock __cfaabi_dbg_ctx2 );
448                {
449                        while( !empty(this.pending.queue) ) {
450                                __cfadbg_print_safe(io, "Kernel I/O : notifying\n");
451                                __u32 have = ctx->sq.free_ring.tail - ctx->sq.free_ring.head;
452                                __pending_alloc & pa = (__pending_alloc&)head( this.pending.queue );
453
454                                if( have > pa.want ) goto DONE;
455                                drop( this.pending.queue );
456
457                                /* paranoid */__attribute__((unused)) bool ret =
458
459                                __alloc(ctx, pa.idxs, pa.want);
460
461                                /* paranoid */ verify( ret );
462
463                                pa.ctx = ctx;
464
465                                post( pa.sem );
466                        }
467
468                        this.pending.empty = true;
469                        DONE:;
470                }
471                unlock( this.pending.lock );
472        }
473
474        static void __ioarbiter_notify( $io_context & ctx ) {
475                if(!empty( ctx.arbiter->pending )) {
476                        __ioarbiter_notify( *ctx.arbiter, &ctx );
477                }
478        }
479
480        // Simply append to the pending
481        static void __ioarbiter_submit( $io_context * ctx, __u32 idxs[], __u32 have, bool lazy ) {
482                __cfadbg_print_safe(io, "Kernel I/O : submitting %u from the arbiter to context %u\n", have, ctx->fd);
483
484                __cfadbg_print_safe(io, "Kernel I/O : waiting to submit %u\n", have);
485
486                __external_io ei;
487                ei.idxs = idxs;
488                ei.have = have;
489                ei.lazy = lazy;
490
491                block(ctx->ext_sq, (__outstanding_io&)ei);
492
493                __cfadbg_print_safe(io, "Kernel I/O : %u submitted from arbiter\n", have);
494        }
495
496        static void __ioarbiter_flush( $io_context & ctx ) {
497                if(!empty( ctx.ext_sq )) {
498                        __STATS__( false, io.flush.external += 1; )
499
500                        __cfadbg_print_safe(io, "Kernel I/O : arbiter flushing\n");
501
502                        lock( ctx.ext_sq.lock __cfaabi_dbg_ctx2 );
503                        {
504                                while( !empty(ctx.ext_sq.queue) ) {
505                                        __external_io & ei = (__external_io&)drop( ctx.ext_sq.queue );
506
507                                        __submit(&ctx, ei.idxs, ei.have, ei.lazy);
508
509                                        post( ei.sem );
510                                }
511
512                                ctx.ext_sq.empty = true;
513                        }
514                        unlock(ctx.ext_sq.lock );
515                }
516        }
517#endif
Note: See TracBrowser for help on using the repository browser.