source: libcfa/src/concurrency/io.cfa @ 2b5be17

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 2b5be17 was be36ec3, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

No longer hold the submit lock when doing the io_uring_enter system call

  • Property mode set to 100644
File size: 13.6 KB
RevLine 
[ecf6b46]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
[3e2b9c9]16#define __cforall_thread__
17
[20ab637]18#if defined(__CFA_DEBUG__)
19        // #define __CFA_DEBUG_PRINT_IO__
[e660761]20        // #define __CFA_DEBUG_PRINT_IO_CORE__
[20ab637]21#endif
[4069faad]22
[f6660520]23
[3e2b9c9]24#if defined(CFA_HAVE_LINUX_IO_URING_H)
[31bb2e1]25        #define _GNU_SOURCE         /* See feature_test_macros(7) */
26        #include <errno.h>
[3e2b9c9]27        #include <signal.h>
[31bb2e1]28        #include <stdint.h>
29        #include <string.h>
30        #include <unistd.h>
31
[92976d9]32        extern "C" {
[f00b26d4]33                #include <sys/epoll.h>
[92976d9]34                #include <sys/syscall.h>
35
36                #include <linux/io_uring.h>
37        }
38
[3e2b9c9]39        #include "stats.hfa"
40        #include "kernel.hfa"
41        #include "kernel/fwd.hfa"
42        #include "io/types.hfa"
[185efe6]43
[92976d9]44//=============================================================================================
[3e2b9c9]45// I/O Syscall
[92976d9]46//=============================================================================================
[3e2b9c9]47        static int __io_uring_enter( struct __io_data & ring, unsigned to_submit, bool get ) {
[20ab637]48                bool need_sys_to_submit = false;
49                bool need_sys_to_complete = false;
50                unsigned flags = 0;
51
52                TO_SUBMIT:
53                if( to_submit > 0 ) {
54                        if( !(ring.ring_flags & IORING_SETUP_SQPOLL) ) {
55                                need_sys_to_submit = true;
56                                break TO_SUBMIT;
57                        }
58                        if( (*ring.submit_q.flags) & IORING_SQ_NEED_WAKEUP ) {
59                                need_sys_to_submit = true;
60                                flags |= IORING_ENTER_SQ_WAKEUP;
61                        }
62                }
63
64                if( get && !(ring.ring_flags & IORING_SETUP_SQPOLL) ) {
65                        flags |= IORING_ENTER_GETEVENTS;
66                        if( (ring.ring_flags & IORING_SETUP_IOPOLL) ) {
67                                need_sys_to_complete = true;
68                        }
69                }
70
71                int ret = 0;
72                if( need_sys_to_submit || need_sys_to_complete ) {
[f00b26d4]73                        ret = syscall( __NR_io_uring_enter, ring.fd, to_submit, 0, flags, 0p, _NSIG / 8);
[20ab637]74                        if( ret < 0 ) {
75                                switch((int)errno) {
76                                case EAGAIN:
77                                case EINTR:
78                                        ret = -1;
79                                        break;
80                                default:
81                                        abort( "KERNEL ERROR: IO_URING SYSCALL - (%d) %s\n", (int)errno, strerror(errno) );
82                                }
83                        }
84                }
85
86                // Memory barrier
87                __atomic_thread_fence( __ATOMIC_SEQ_CST );
88                return ret;
89        }
90
[92976d9]91//=============================================================================================
92// I/O Polling
93//=============================================================================================
[1d5e4711]94        static unsigned __collect_submitions( struct __io_data & ring );
[34b61882]95        static uint32_t __release_consumed_submission( struct __io_data & ring );
[1d5e4711]96
[f00b26d4]97        static inline void process(struct io_uring_cqe & cqe ) {
[5751a56]98                struct __io_user_data_t * data = (struct __io_user_data_t *)(uintptr_t)cqe.user_data;
99                __cfadbg_print_safe( io, "Kernel I/O : Syscall completed : cqe %p, result %d for %p\n", data, cqe.res, data->thrd );
100
101                data->result = cqe.res;
[f00b26d4]102                unpark( data->thrd __cfaabi_dbg_ctx2 );
[5751a56]103        }
104
[92976d9]105        // Process a single completion message from the io_uring
106        // This is NOT thread-safe
[f00b26d4]107        static [int, bool] __drain_io( & struct __io_data ring ) {
[e46c753]108                /* paranoid */ verify( !kernelTLS.preemption_state.enabled );
109
[5dadc9b]110                unsigned to_submit = 0;
[f00b26d4]111                if( ring.poller_submits ) {
[5dadc9b]112                        // If the poller thread also submits, then we need to aggregate the submissions which are ready
[e46c753]113                        to_submit = __collect_submitions( ring );
[5dadc9b]114                }
115
[f00b26d4]116                int ret = __io_uring_enter(ring, to_submit, true);
[20ab637]117                if( ret < 0 ) {
118                        return [0, true];
119                }
[1d5e4711]120
[20ab637]121                // update statistics
122                if (to_submit > 0) {
[1d5e4711]123                        __STATS__( true,
124                                if( to_submit > 0 ) {
125                                        io.submit_q.submit_avg.rdy += to_submit;
126                                        io.submit_q.submit_avg.csm += ret;
127                                        io.submit_q.submit_avg.cnt += 1;
128                                }
129                        )
[6f121b8]130                }
131
[20ab637]132                // Release the consumed SQEs
133                __release_consumed_submission( ring );
[6f121b8]134
[d384787]135                // Drain the queue
[92976d9]136                unsigned head = *ring.completion_q.head;
[6f121b8]137                unsigned tail = *ring.completion_q.tail;
138                const uint32_t mask = *ring.completion_q.mask;
139
[d384787]140                // Nothing was new return 0
141                if (head == tail) {
[e46c753]142                        return [0, to_submit > 0];
[d384787]143                }
[92976d9]144
[d384787]145                uint32_t count = tail - head;
[1d5e4711]146                /* paranoid */ verify( count != 0 );
[d384787]147                for(i; count) {
[6f121b8]148                        unsigned idx = (head + i) & mask;
[d384787]149                        struct io_uring_cqe & cqe = ring.completion_q.cqes[idx];
[92976d9]150
[d384787]151                        /* paranoid */ verify(&cqe);
[92976d9]152
[f00b26d4]153                        process( cqe );
[d384787]154                }
[2d8f7b0]155
[92976d9]156                // Mark to the kernel that the cqe has been seen
157                // Ensure that the kernel only sees the new value of the head index after the CQEs have been read.
[6f121b8]158                __atomic_thread_fence( __ATOMIC_SEQ_CST );
[d384787]159                __atomic_fetch_add( ring.completion_q.head, count, __ATOMIC_RELAXED );
[92976d9]160
[5dadc9b]161                return [count, count > 0 || to_submit > 0];
[92976d9]162        }
163
[f00b26d4]164        void main( $io_ctx_thread & this ) {
165                epoll_event ev;
[3e2b9c9]166                __ioctx_register( this, ev );
[1539bbd]167
[f00b26d4]168                __cfadbg_print_safe(io_core, "Kernel I/O : IO poller %p for ring %p ready\n", &this, &this.ring);
[1539bbd]169
[4e74466]170                int reset = 0;
[61dd73d]171                // Then loop until we need to start
[f00b26d4]172                while(!__atomic_load_n(&this.done, __ATOMIC_SEQ_CST)) {
[61dd73d]173                        // Drain the io
[5dadc9b]174                        int count;
175                        bool again;
[13c5e19]176                        disable_interrupts();
[f00b26d4]177                                [count, again] = __drain_io( *this.ring );
[5dadc9b]178
[13c5e19]179                                if(!again) reset++;
[3c039b0]180
[13c5e19]181                                // Update statistics
[47746a2]182                                __STATS__( true,
183                                        io.complete_q.completed_avg.val += count;
184                                        io.complete_q.completed_avg.fast_cnt += 1;
185                                )
[13c5e19]186                        enable_interrupts( __cfaabi_dbg_ctx );
[3c039b0]187
[5dadc9b]188                        // If we got something, just yield and check again
[4e74466]189                        if(reset < 5) {
[61dd73d]190                                yield();
191                        }
[5dadc9b]192                        // We didn't get anything baton pass to the slow poller
[61dd73d]193                        else {
[f00b26d4]194                                __cfadbg_print_safe(io_core, "Kernel I/O : Parking io poller %p\n", &this.self);
[5dadc9b]195                                reset = 0;
196
[3e2b9c9]197                                // block this thread
198                                __ioctx_prepare_block( this, ev );
[f00b26d4]199                                wait( this.sem );
[f6660520]200                        }
201                }
[61dd73d]202
203                __cfadbg_print_safe(io_core, "Kernel I/O : Fast poller for ring %p stopping\n", &this.ring);
204        }
[f6660520]205
[92976d9]206//=============================================================================================
207// I/O Submissions
208//=============================================================================================
209
[2d8f7b0]210// Submition steps :
[e46c753]211// 1 - Allocate a queue entry. The ring already has memory for all entries but only the ones
[2d8f7b0]212//     listed in sq.array are visible by the kernel. For those not listed, the kernel does not
213//     offer any assurance that an entry is not being filled by multiple flags. Therefore, we
214//     need to write an allocator that allows allocating concurrently.
215//
[e46c753]216// 2 - Actually fill the submit entry, this is the only simple and straightforward step.
[2d8f7b0]217//
[e46c753]218// 3 - Append the entry index to the array and adjust the tail accordingly. This operation
[2d8f7b0]219//     needs to arrive to two concensus at the same time:
220//     A - The order in which entries are listed in the array: no two threads must pick the
221//         same index for their entries
222//     B - When can the tail be update for the kernel. EVERY entries in the array between
223//         head and tail must be fully filled and shouldn't ever be touched again.
224//
225
[31bb2e1]226        [* struct io_uring_sqe, uint32_t] __submit_alloc( struct __io_data & ring, uint64_t data ) {
[e46c753]227                /* paranoid */ verify( data != 0 );
[13c5e19]228
[6f121b8]229                // Prepare the data we need
230                __attribute((unused)) int len   = 0;
231                __attribute((unused)) int block = 0;
232                uint32_t cnt = *ring.submit_q.num;
233                uint32_t mask = *ring.submit_q.mask;
[8ae4165]234
235                disable_interrupts();
236                        uint32_t off = __tls_rand();
237                enable_interrupts( __cfaabi_dbg_ctx );
[6f121b8]238
239                // Loop around looking for an available spot
[13c5e19]240                for() {
[6f121b8]241                        // Look through the list starting at some offset
242                        for(i; cnt) {
243                                uint64_t expected = 0;
244                                uint32_t idx = (i + off) & mask;
245                                struct io_uring_sqe * sqe = &ring.submit_q.sqes[idx];
[eafec07]246                                volatile uint64_t * udata = (volatile uint64_t *)&sqe->user_data;
[6f121b8]247
248                                if( *udata == expected &&
249                                        __atomic_compare_exchange_n( udata, &expected, data, true, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED ) )
250                                {
251                                        // update statistics
[47746a2]252                                        __STATS__( false,
253                                                io.submit_q.alloc_avg.val   += len;
254                                                io.submit_q.alloc_avg.block += block;
255                                                io.submit_q.alloc_avg.cnt   += 1;
256                                        )
[6f121b8]257
[13c5e19]258
[6f121b8]259                                        // Success return the data
260                                        return [sqe, idx];
261                                }
262                                verify(expected != data);
[2489d31]263
[6f121b8]264                                len ++;
265                        }
[2489d31]266
[6f121b8]267                        block++;
268                        yield();
269                }
[2489d31]270        }
271
[df40a56]272        static inline uint32_t __submit_to_ready_array( struct __io_data & ring, uint32_t idx, const uint32_t mask ) {
273                /* paranoid */ verify( idx <= mask   );
274                /* paranoid */ verify( idx != -1ul32 );
275
276                // We need to find a spot in the ready array
277                __attribute((unused)) int len   = 0;
278                __attribute((unused)) int block = 0;
279                uint32_t ready_mask = ring.submit_q.ready_cnt - 1;
280
281                disable_interrupts();
282                        uint32_t off = __tls_rand();
283                enable_interrupts( __cfaabi_dbg_ctx );
284
285                uint32_t picked;
286                LOOKING: for() {
287                        for(i; ring.submit_q.ready_cnt) {
288                                picked = (i + off) & ready_mask;
289                                uint32_t expected = -1ul32;
290                                if( __atomic_compare_exchange_n( &ring.submit_q.ready[picked], &expected, idx, true, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED ) ) {
291                                        break LOOKING;
292                                }
293                                verify(expected != idx);
294
295                                len ++;
296                        }
297
298                        block++;
[34b61882]299                        if( try_lock(ring.submit_q.lock __cfaabi_dbg_ctx2) ) {
300                                __release_consumed_submission( ring );
301                                unlock( ring.submit_q.lock );
302                        }
303                        else {
304                                yield();
305                        }
[df40a56]306                }
307
308                // update statistics
[47746a2]309                __STATS__( false,
310                        io.submit_q.look_avg.val   += len;
311                        io.submit_q.look_avg.block += block;
312                        io.submit_q.look_avg.cnt   += 1;
313                )
[df40a56]314
315                return picked;
316        }
317
[f00b26d4]318        void __submit( struct io_context * ctx, uint32_t idx ) __attribute__((nonnull (1))) {
319                __io_data & ring = *ctx->thrd.ring;
[5dadc9b]320                // Get now the data we definetely need
[eafec07]321                volatile uint32_t * const tail = ring.submit_q.tail;
[f00b26d4]322                const uint32_t mask  = *ring.submit_q.mask;
[2489d31]323
[5dadc9b]324                // There are 2 submission schemes, check which one we are using
[f00b26d4]325                if( ring.poller_submits ) {
[5dadc9b]326                        // If the poller thread submits, then we just need to add this to the ready array
[df40a56]327                        __submit_to_ready_array( ring, idx, mask );
[5dadc9b]328
[f00b26d4]329                        post( ctx->thrd.sem );
[5dadc9b]330
[dd4e2d7]331                        __cfadbg_print_safe( io, "Kernel I/O : Added %u to ready for %p\n", idx, active_thread() );
[2d8f7b0]332                }
[f00b26d4]333                else if( ring.eager_submits ) {
[e46c753]334                        uint32_t picked = __submit_to_ready_array( ring, idx, mask );
335
336                        for() {
337                                yield();
338
339                                // If some one else collected our index, we are done
[8bb239d]340                                #warning ABA problem
[e46c753]341                                if( ring.submit_q.ready[picked] != idx ) {
[47746a2]342                                        __STATS__( false,
343                                                io.submit_q.helped += 1;
344                                        )
[e46c753]345                                        return;
346                                }
347
348                                if( try_lock(ring.submit_q.lock __cfaabi_dbg_ctx2) ) {
[47746a2]349                                        __STATS__( false,
350                                                io.submit_q.leader += 1;
351                                        )
[e46c753]352                                        break;
353                                }
[8bb239d]354
[47746a2]355                                __STATS__( false,
356                                        io.submit_q.busy += 1;
357                                )
[e46c753]358                        }
359
360                        // We got the lock
[be36ec3]361                        // Collect the submissions
[e46c753]362                        unsigned to_submit = __collect_submitions( ring );
363
[be36ec3]364                        // Release the lock now so syscalls can overlap
365                        unlock(ring.submit_q.lock);
366
367                        // Actually submit
368                        int ret = __io_uring_enter( ring, to_submit, false );
369                        if( ret < 0 ) return;
[e46c753]370
371                        // Release the consumed SQEs
[34b61882]372                        __release_consumed_submission( ring );
[e46c753]373
374                        // update statistics
[be36ec3]375                        __STATS__( false,
[47746a2]376                                io.submit_q.submit_avg.rdy += to_submit;
377                                io.submit_q.submit_avg.csm += ret;
378                                io.submit_q.submit_avg.cnt += 1;
379                        )
[e46c753]380                }
[5dadc9b]381                else {
382                        // get mutual exclusion
383                        lock(ring.submit_q.lock __cfaabi_dbg_ctx2);
[2489d31]384
[20ab637]385                        /* paranoid */ verifyf( ring.submit_q.sqes[ idx ].user_data != 0,
386                        /* paranoid */  "index %u already reclaimed\n"
387                        /* paranoid */  "head %u, prev %u, tail %u\n"
388                        /* paranoid */  "[-0: %u,-1: %u,-2: %u,-3: %u]\n",
389                        /* paranoid */  idx,
390                        /* paranoid */  *ring.submit_q.head, ring.submit_q.prev_head, *tail
391                        /* paranoid */  ,ring.submit_q.array[ ((*ring.submit_q.head) - 0) & (*ring.submit_q.mask) ]
392                        /* paranoid */  ,ring.submit_q.array[ ((*ring.submit_q.head) - 1) & (*ring.submit_q.mask) ]
393                        /* paranoid */  ,ring.submit_q.array[ ((*ring.submit_q.head) - 2) & (*ring.submit_q.mask) ]
394                        /* paranoid */  ,ring.submit_q.array[ ((*ring.submit_q.head) - 3) & (*ring.submit_q.mask) ]
395                        /* paranoid */ );
396
[5dadc9b]397                        // Append to the list of ready entries
398
399                        /* paranoid */ verify( idx <= mask );
[20ab637]400                        ring.submit_q.array[ (*tail) & mask ] = idx;
[5dadc9b]401                        __atomic_fetch_add(tail, 1ul32, __ATOMIC_SEQ_CST);
[d384787]402
[5dadc9b]403                        // Submit however, many entries need to be submitted
[f00b26d4]404                        int ret = __io_uring_enter( ring, 1, false );
[5dadc9b]405                        if( ret < 0 ) {
406                                switch((int)errno) {
407                                default:
408                                        abort( "KERNEL ERROR: IO_URING SUBMIT - %s\n", strerror(errno) );
409                                }
410                        }
[d384787]411
[5dadc9b]412                        // update statistics
[47746a2]413                        __STATS__( false,
414                                io.submit_q.submit_avg.csm += 1;
415                                io.submit_q.submit_avg.cnt += 1;
416                        )
[5dadc9b]417
[34b61882]418                        // Release the consumed SQEs
419                        __release_consumed_submission( ring );
[7bfc849]420
[5dadc9b]421                        unlock(ring.submit_q.lock);
[dd4e2d7]422
423                        __cfadbg_print_safe( io, "Kernel I/O : Performed io_submit for %p, returned %d\n", active_thread(), ret );
[5dadc9b]424                }
[2489d31]425        }
[e46c753]426
427        static unsigned __collect_submitions( struct __io_data & ring ) {
428                /* paranoid */ verify( ring.submit_q.ready != 0p );
429                /* paranoid */ verify( ring.submit_q.ready_cnt > 0 );
430
431                unsigned to_submit = 0;
432                uint32_t tail = *ring.submit_q.tail;
433                const uint32_t mask = *ring.submit_q.mask;
434
435                // Go through the list of ready submissions
436                for( i; ring.submit_q.ready_cnt ) {
437                        // replace any submission with the sentinel, to consume it.
438                        uint32_t idx = __atomic_exchange_n( &ring.submit_q.ready[i], -1ul32, __ATOMIC_RELAXED);
439
440                        // If it was already the sentinel, then we are done
441                        if( idx == -1ul32 ) continue;
442
443                        // If we got a real submission, append it to the list
444                        ring.submit_q.array[ (tail + to_submit) & mask ] = idx & mask;
445                        to_submit++;
446                }
447
448                // Increment the tail based on how many we are ready to submit
449                __atomic_fetch_add(ring.submit_q.tail, to_submit, __ATOMIC_SEQ_CST);
450
451                return to_submit;
452        }
[34b61882]453
454        static uint32_t __release_consumed_submission( struct __io_data & ring ) {
455                const uint32_t smask = *ring.submit_q.mask;
[732b406]456
457                if( !try_lock(ring.submit_q.release_lock __cfaabi_dbg_ctx2) ) return 0;
[34b61882]458                uint32_t chead = *ring.submit_q.head;
459                uint32_t phead = ring.submit_q.prev_head;
460                ring.submit_q.prev_head = chead;
[732b406]461                unlock(ring.submit_q.release_lock);
462
[34b61882]463                uint32_t count = chead - phead;
464                for( i; count ) {
465                        uint32_t idx = ring.submit_q.array[ (phead + i) & smask ];
466                        ring.submit_q.sqes[ idx ].user_data = 0;
467                }
468                return count;
469        }
[47746a2]470#endif
Note: See TracBrowser for help on using the repository browser.