source: libcfa/src/concurrency/io.cfa @ 34b61882

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

Submission release is now based on previous seen head rather than the return value of io_uring_enter
This will make it easier to support SQ POLLING
It is not currently thread safe.
It is unclear if it can be made thread safe

  • Property mode set to 100644
File size: 27.6 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 __CFA_DEBUG_PRINT_IO__
17// #define __CFA_DEBUG_PRINT_IO_CORE__
18
19#include "kernel.hfa"
20#include "bitmanip.hfa"
21
22#if !defined(HAVE_LINUX_IO_URING_H)
23        void __kernel_io_startup( cluster &, unsigned, bool ) {
24                // Nothing to do without io_uring
25        }
26
27        void __kernel_io_finish_start( cluster & ) {
28                // Nothing to do without io_uring
29        }
30
31        void __kernel_io_prepare_stop( cluster & ) {
32                // Nothing to do without io_uring
33        }
34
35        void __kernel_io_shutdown( cluster &, bool ) {
36                // Nothing to do without io_uring
37        }
38
39#else
40        #define _GNU_SOURCE         /* See feature_test_macros(7) */
41        #include <errno.h>
42        #include <stdint.h>
43        #include <string.h>
44        #include <unistd.h>
45        #include <sys/mman.h>
46
47        extern "C" {
48                #include <sys/syscall.h>
49
50                #include <linux/io_uring.h>
51        }
52
53        #include "bits/signal.hfa"
54        #include "kernel_private.hfa"
55        #include "thread.hfa"
56
57        uint32_t entries_per_cluster() {
58                return 256;
59        }
60
61        static void * __io_poller_slow( void * arg );
62
63        // Weirdly, some systems that do support io_uring don't actually define these
64        #ifdef __alpha__
65                /*
66                * alpha is the only exception, all other architectures
67                * have common numbers for new system calls.
68                */
69                #ifndef __NR_io_uring_setup
70                        #define __NR_io_uring_setup           535
71                #endif
72                #ifndef __NR_io_uring_enter
73                        #define __NR_io_uring_enter           536
74                #endif
75                #ifndef __NR_io_uring_register
76                        #define __NR_io_uring_register        537
77                #endif
78        #else /* !__alpha__ */
79                #ifndef __NR_io_uring_setup
80                        #define __NR_io_uring_setup           425
81                #endif
82                #ifndef __NR_io_uring_enter
83                        #define __NR_io_uring_enter           426
84                #endif
85                #ifndef __NR_io_uring_register
86                        #define __NR_io_uring_register        427
87                #endif
88        #endif
89
90        // Fast poller user-thread
91        // Not using the "thread" keyword because we want to control
92        // more carefully when to start/stop it
93        struct __io_poller_fast {
94                struct __io_data * ring;
95                $thread thrd;
96        };
97
98        void ?{}( __io_poller_fast & this, struct cluster & cltr ) {
99                this.ring = cltr.io;
100                (this.thrd){ "Fast I/O Poller", cltr };
101        }
102        void ^?{}( __io_poller_fast & mutex this );
103        void main( __io_poller_fast & this );
104        static inline $thread * get_thread( __io_poller_fast & this ) { return &this.thrd; }
105        void ^?{}( __io_poller_fast & mutex this ) {}
106
107        struct __submition_data {
108                // Head and tail of the ring (associated with array)
109                volatile uint32_t * head;
110                volatile uint32_t * tail;
111                volatile uint32_t prev_head;
112
113                // The actual kernel ring which uses head/tail
114                // indexes into the sqes arrays
115                uint32_t * array;
116
117                // number of entries and mask to go with it
118                const uint32_t * num;
119                const uint32_t * mask;
120
121                // Submission flags (Not sure what for)
122                uint32_t * flags;
123
124                // number of sqes not submitted (whatever that means)
125                uint32_t * dropped;
126
127                // Like head/tail but not seen by the kernel
128                volatile uint32_t * ready;
129                uint32_t ready_cnt;
130
131                __spinlock_t lock;
132
133                // A buffer of sqes (not the actual ring)
134                struct io_uring_sqe * sqes;
135
136                // The location and size of the mmaped area
137                void * ring_ptr;
138                size_t ring_sz;
139        };
140
141        struct __completion_data {
142                // Head and tail of the ring
143                volatile uint32_t * head;
144                volatile uint32_t * tail;
145
146                // number of entries and mask to go with it
147                const uint32_t * mask;
148                const uint32_t * num;
149
150                // number of cqes not submitted (whatever that means)
151                uint32_t * overflow;
152
153                // the kernel ring
154                struct io_uring_cqe * cqes;
155
156                // The location and size of the mmaped area
157                void * ring_ptr;
158                size_t ring_sz;
159        };
160
161        struct __io_data {
162                struct __submition_data submit_q;
163                struct __completion_data completion_q;
164                uint32_t ring_flags;
165                int cltr_flags;
166                int fd;
167                semaphore submit;
168                volatile bool done;
169                struct {
170                        struct {
171                                __processor_id_t id;
172                                void * stack;
173                                pthread_t kthrd;
174                                volatile bool blocked;
175                        } slow;
176                        __io_poller_fast fast;
177                        __bin_sem_t sem;
178                } poller;
179        };
180
181//=============================================================================================
182// I/O Startup / Shutdown logic
183//=============================================================================================
184        void __kernel_io_startup( cluster & this, unsigned io_flags, bool main_cluster ) {
185                if( (io_flags & CFA_CLUSTER_IO_POLLER_THREAD_SUBMITS) && (io_flags & CFA_CLUSTER_IO_EAGER_SUBMITS) ) {
186                        abort("CFA_CLUSTER_IO_POLLER_THREAD_SUBMITS and CFA_CLUSTER_IO_EAGER_SUBMITS cannot be mixed\n");
187                }
188
189                this.io = malloc();
190
191                // Step 1 : call to setup
192                struct io_uring_params params;
193                memset(&params, 0, sizeof(params));
194                if( io_flags & CFA_CLUSTER_IO_KERNEL_POLL_SUBMITS   ) params.flags |= IORING_SETUP_SQPOLL;
195                if( io_flags & CFA_CLUSTER_IO_KERNEL_POLL_COMPLETES ) params.flags |= IORING_SETUP_IOPOLL;
196
197                uint32_t nentries = entries_per_cluster();
198
199                int fd = syscall(__NR_io_uring_setup, nentries, &params );
200                if(fd < 0) {
201                        abort("KERNEL ERROR: IO_URING SETUP - %s\n", strerror(errno));
202                }
203
204                // Step 2 : mmap result
205                memset( this.io, 0, sizeof(struct __io_data) );
206                struct __submition_data  & sq = this.io->submit_q;
207                struct __completion_data & cq = this.io->completion_q;
208
209                // calculate the right ring size
210                sq.ring_sz = params.sq_off.array + (params.sq_entries * sizeof(unsigned)           );
211                cq.ring_sz = params.cq_off.cqes  + (params.cq_entries * sizeof(struct io_uring_cqe));
212
213                // Requires features
214                #if defined(IORING_FEAT_SINGLE_MMAP)
215                        // adjust the size according to the parameters
216                        if ((params.features & IORING_FEAT_SINGLE_MMAP) != 0) {
217                                cq->ring_sz = sq->ring_sz = max(cq->ring_sz, sq->ring_sz);
218                        }
219                #endif
220
221                // mmap the Submit Queue into existence
222                sq.ring_ptr = mmap(0, sq.ring_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_SQ_RING);
223                if (sq.ring_ptr == (void*)MAP_FAILED) {
224                        abort("KERNEL ERROR: IO_URING MMAP1 - %s\n", strerror(errno));
225                }
226
227                // Requires features
228                #if defined(IORING_FEAT_SINGLE_MMAP)
229                        // mmap the Completion Queue into existence (may or may not be needed)
230                        if ((params.features & IORING_FEAT_SINGLE_MMAP) != 0) {
231                                cq->ring_ptr = sq->ring_ptr;
232                        }
233                        else
234                #endif
235                {
236                        // We need multiple call to MMAP
237                        cq.ring_ptr = mmap(0, cq.ring_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_CQ_RING);
238                        if (cq.ring_ptr == (void*)MAP_FAILED) {
239                                munmap(sq.ring_ptr, sq.ring_sz);
240                                abort("KERNEL ERROR: IO_URING MMAP2 - %s\n", strerror(errno));
241                        }
242                }
243
244                // mmap the submit queue entries
245                size_t size = params.sq_entries * sizeof(struct io_uring_sqe);
246                sq.sqes = (struct io_uring_sqe *)mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_SQES);
247                if (sq.sqes == (struct io_uring_sqe *)MAP_FAILED) {
248                        munmap(sq.ring_ptr, sq.ring_sz);
249                        if (cq.ring_ptr != sq.ring_ptr) munmap(cq.ring_ptr, cq.ring_sz);
250                        abort("KERNEL ERROR: IO_URING MMAP3 - %s\n", strerror(errno));
251                }
252
253                // Get the pointers from the kernel to fill the structure
254                // submit queue
255                sq.head    = (volatile uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.head);
256                sq.tail    = (volatile uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.tail);
257                sq.mask    = (   const uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.ring_mask);
258                sq.num     = (   const uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.ring_entries);
259                sq.flags   = (         uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.flags);
260                sq.dropped = (         uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.dropped);
261                sq.array   = (         uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.array);
262                sq.prev_head = *sq.head;
263
264                {
265                        const uint32_t num = *sq.num;
266                        for( i; num ) {
267                                sq.sqes[i].user_data = 0ul64;
268                        }
269                }
270
271                (sq.lock){};
272
273                if( io_flags & ( CFA_CLUSTER_IO_POLLER_THREAD_SUBMITS | CFA_CLUSTER_IO_EAGER_SUBMITS ) ) {
274                        /* paranoid */ verify( is_pow2( io_flags >> CFA_CLUSTER_IO_BUFFLEN_OFFSET ) || ((io_flags >> CFA_CLUSTER_IO_BUFFLEN_OFFSET) < 8)  );
275                        sq.ready_cnt = max(io_flags >> CFA_CLUSTER_IO_BUFFLEN_OFFSET, 8);
276                        sq.ready = alloc_align( 64, sq.ready_cnt );
277                        for(i; sq.ready_cnt) {
278                                sq.ready[i] = -1ul32;
279                        }
280                }
281                else {
282                        sq.ready_cnt = 0;
283                        sq.ready = 0p;
284                }
285
286                // completion queue
287                cq.head     = (volatile uint32_t *)(((intptr_t)cq.ring_ptr) + params.cq_off.head);
288                cq.tail     = (volatile uint32_t *)(((intptr_t)cq.ring_ptr) + params.cq_off.tail);
289                cq.mask     = (   const uint32_t *)(((intptr_t)cq.ring_ptr) + params.cq_off.ring_mask);
290                cq.num      = (   const uint32_t *)(((intptr_t)cq.ring_ptr) + params.cq_off.ring_entries);
291                cq.overflow = (         uint32_t *)(((intptr_t)cq.ring_ptr) + params.cq_off.overflow);
292                cq.cqes   = (struct io_uring_cqe *)(((intptr_t)cq.ring_ptr) + params.cq_off.cqes);
293
294                // some paranoid checks
295                /* paranoid */ verifyf( (*cq.mask) == ((*cq.num) - 1ul32), "IO_URING Expected mask to be %u (%u entries), was %u", (*cq.num) - 1ul32, *cq.num, *cq.mask  );
296                /* paranoid */ verifyf( (*cq.num)  >= nentries, "IO_URING Expected %u entries, got %u", nentries, *cq.num );
297                /* paranoid */ verifyf( (*cq.head) == 0, "IO_URING Expected head to be 0, got %u", *cq.head );
298                /* paranoid */ verifyf( (*cq.tail) == 0, "IO_URING Expected tail to be 0, got %u", *cq.tail );
299
300                /* paranoid */ verifyf( (*sq.mask) == ((*sq.num) - 1ul32), "IO_URING Expected mask to be %u (%u entries), was %u", (*sq.num) - 1ul32, *sq.num, *sq.mask );
301                /* paranoid */ verifyf( (*sq.num) >= nentries, "IO_URING Expected %u entries, got %u", nentries, *sq.num );
302                /* paranoid */ verifyf( (*sq.head) == 0, "IO_URING Expected head to be 0, got %u", *sq.head );
303                /* paranoid */ verifyf( (*sq.tail) == 0, "IO_URING Expected tail to be 0, got %u", *sq.tail );
304
305                // Update the global ring info
306                this.io->ring_flags = params.flags;
307                this.io->cltr_flags = io_flags;
308                this.io->fd         = fd;
309                this.io->done       = false;
310                (this.io->submit){ min(*sq.num, *cq.num) };
311
312                if(!main_cluster) {
313                        __kernel_io_finish_start( this );
314                }
315        }
316
317        void __kernel_io_finish_start( cluster & this ) {
318                if( this.io->cltr_flags & CFA_CLUSTER_IO_POLLER_USER_THREAD ) {
319                        __cfadbg_print_safe(io_core, "Kernel I/O : Creating fast poller for cluter %p\n", &this);
320                        (this.io->poller.fast){ this };
321                        __thrd_start( this.io->poller.fast, main );
322                }
323
324                // Create the poller thread
325                __cfadbg_print_safe(io_core, "Kernel I/O : Creating slow poller for cluter %p\n", &this);
326                this.io->poller.slow.blocked = false;
327                this.io->poller.slow.stack = __create_pthread( &this.io->poller.slow.kthrd, __io_poller_slow, &this );
328        }
329
330        void __kernel_io_prepare_stop( cluster & this ) {
331                __cfadbg_print_safe(io_core, "Kernel I/O : Stopping pollers for cluster\n", &this);
332                // Notify the poller thread of the shutdown
333                __atomic_store_n(&this.io->done, true, __ATOMIC_SEQ_CST);
334
335                // Stop the IO Poller
336                sigval val = { 1 };
337                pthread_sigqueue( this.io->poller.slow.kthrd, SIGUSR1, val );
338                post( this.io->poller.sem );
339
340                // Wait for the poller thread to finish
341                pthread_join( this.io->poller.slow.kthrd, 0p );
342                free( this.io->poller.slow.stack );
343
344                __cfadbg_print_safe(io_core, "Kernel I/O : Slow poller stopped for cluster\n", &this);
345
346                if( this.io->cltr_flags & CFA_CLUSTER_IO_POLLER_USER_THREAD ) {
347                        with( this.io->poller.fast ) {
348                                /* paranoid */ verify( this.nprocessors == 0 || &this == mainCluster );
349                                /* paranoid */ verify( !ready_mutate_islocked() );
350
351                                // We need to adjust the clean-up based on where the thread is
352                                if( thrd.state == Ready || thrd.preempted != __NO_PREEMPTION ) {
353
354                                        ready_schedule_lock( (struct __processor_id_t *)active_processor() );
355
356                                                // This is the tricky case
357                                                // The thread was preempted and now it is on the ready queue
358                                                // The thread should be the last on the list
359                                                /* paranoid */ verify( thrd.link.next != 0p );
360
361                                                // Remove the thread from the ready queue of this cluster
362                                                __attribute__((unused)) bool removed = remove_head( &this, &thrd );
363                                                /* paranoid */ verify( removed );
364                                                thrd.link.next = 0p;
365                                                thrd.link.prev = 0p;
366                                                __cfaabi_dbg_debug_do( thrd.unpark_stale = true );
367
368                                                // Fixup the thread state
369                                                thrd.state = Blocked;
370                                                thrd.ticket = 0;
371                                                thrd.preempted = __NO_PREEMPTION;
372
373                                        ready_schedule_unlock( (struct __processor_id_t *)active_processor() );
374
375                                        // Pretend like the thread was blocked all along
376                                }
377                                // !!! This is not an else if !!!
378                                if( thrd.state == Blocked ) {
379
380                                        // This is the "easy case"
381                                        // The thread is parked and can easily be moved to active cluster
382                                        verify( thrd.curr_cluster != active_cluster() || thrd.curr_cluster == mainCluster );
383                                        thrd.curr_cluster = active_cluster();
384
385                                        // unpark the fast io_poller
386                                        unpark( &thrd __cfaabi_dbg_ctx2 );
387                                }
388                                else {
389
390                                        // The thread is in a weird state
391                                        // I don't know what to do here
392                                        abort("Fast poller thread is in unexpected state, cannot clean-up correctly\n");
393                                }
394
395                        }
396
397                        ^(this.io->poller.fast){};
398
399                        __cfadbg_print_safe(io_core, "Kernel I/O : Fast poller stopped for cluster\n", &this);
400                }
401        }
402
403        void __kernel_io_shutdown( cluster & this, bool main_cluster ) {
404                if(!main_cluster) {
405                        __kernel_io_prepare_stop( this );
406                }
407
408                // Shutdown the io rings
409                struct __submition_data  & sq = this.io->submit_q;
410                struct __completion_data & cq = this.io->completion_q;
411
412                // unmap the submit queue entries
413                munmap(sq.sqes, (*sq.num) * sizeof(struct io_uring_sqe));
414
415                // unmap the Submit Queue ring
416                munmap(sq.ring_ptr, sq.ring_sz);
417
418                // unmap the Completion Queue ring, if it is different
419                if (cq.ring_ptr != sq.ring_ptr) {
420                        munmap(cq.ring_ptr, cq.ring_sz);
421                }
422
423                // close the file descriptor
424                close(this.io->fd);
425
426                free( this.io->submit_q.ready ); // Maybe null, doesn't matter
427                free( this.io );
428        }
429
430//=============================================================================================
431// I/O Polling
432//=============================================================================================
433        static unsigned __collect_submitions( struct __io_data & ring );
434        static uint32_t __release_consumed_submission( struct __io_data & ring );
435
436        // Process a single completion message from the io_uring
437        // This is NOT thread-safe
438        static [int, bool] __drain_io( & struct __io_data ring, * sigset_t mask, int waitcnt, bool in_kernel ) {
439                /* paranoid */ verify( !kernelTLS.preemption_state.enabled );
440                const uint32_t smask = *ring.submit_q.mask;
441
442                unsigned to_submit = 0;
443                if( ring.cltr_flags & CFA_CLUSTER_IO_POLLER_THREAD_SUBMITS ) {
444                        // If the poller thread also submits, then we need to aggregate the submissions which are ready
445                        to_submit = __collect_submitions( ring );
446                }
447
448                if (to_submit > 0 || waitcnt > 0) {
449                        int ret = syscall( __NR_io_uring_enter, ring.fd, to_submit, waitcnt, IORING_ENTER_GETEVENTS, mask, _NSIG / 8);
450                        if( ret < 0 ) {
451                                switch((int)errno) {
452                                case EAGAIN:
453                                case EINTR:
454                                        return [0, true];
455                                default:
456                                        abort( "KERNEL ERROR: IO_URING WAIT - %s\n", strerror(errno) );
457                                }
458                        }
459
460                        // Release the consumed SQEs
461                        __release_consumed_submission( ring );
462
463                        // update statistics
464                        __STATS__( true,
465                                if( to_submit > 0 ) {
466                                        io.submit_q.submit_avg.rdy += to_submit;
467                                        io.submit_q.submit_avg.csm += ret;
468                                        io.submit_q.submit_avg.cnt += 1;
469                                }
470                        )
471                }
472
473                // Memory barrier
474                __atomic_thread_fence( __ATOMIC_SEQ_CST );
475
476                // Drain the queue
477                unsigned head = *ring.completion_q.head;
478                unsigned tail = *ring.completion_q.tail;
479                const uint32_t mask = *ring.completion_q.mask;
480
481                // Nothing was new return 0
482                if (head == tail) {
483                        return [0, to_submit > 0];
484                }
485
486                uint32_t count = tail - head;
487                /* paranoid */ verify( count != 0 );
488                for(i; count) {
489                        unsigned idx = (head + i) & mask;
490                        struct io_uring_cqe & cqe = ring.completion_q.cqes[idx];
491
492                        /* paranoid */ verify(&cqe);
493
494                        struct __io_user_data_t * data = (struct __io_user_data_t *)(uintptr_t)cqe.user_data;
495                        __cfadbg_print_safe( io, "Kernel I/O : Performed reading io cqe %p, result %d for %p\n", data, cqe.res, data->thrd );
496
497                        data->result = cqe.res;
498                        if(!in_kernel) { unpark( data->thrd __cfaabi_dbg_ctx2 ); }
499                        else         { __unpark( &ring.poller.slow.id, data->thrd __cfaabi_dbg_ctx2 ); }
500                }
501
502                // Allow new submissions to happen
503                // V(ring.submit, count);
504
505                // Mark to the kernel that the cqe has been seen
506                // Ensure that the kernel only sees the new value of the head index after the CQEs have been read.
507                __atomic_thread_fence( __ATOMIC_SEQ_CST );
508                __atomic_fetch_add( ring.completion_q.head, count, __ATOMIC_RELAXED );
509
510                return [count, count > 0 || to_submit > 0];
511        }
512
513        static void * __io_poller_slow( void * arg ) {
514                #if !defined( __CFA_NO_STATISTICS__ )
515                        __stats_t local_stats;
516                        __init_stats( &local_stats );
517                        kernelTLS.this_stats = &local_stats;
518                #endif
519
520                cluster * cltr = (cluster *)arg;
521                struct __io_data & ring = *cltr->io;
522
523                ring.poller.slow.id.id = doregister( &ring.poller.slow.id );
524
525                sigset_t mask;
526                sigfillset(&mask);
527                if ( pthread_sigmask( SIG_BLOCK, &mask, 0p ) == -1 ) {
528                        abort( "KERNEL ERROR: IO_URING - pthread_sigmask" );
529                }
530
531                sigdelset( &mask, SIGUSR1 );
532
533                verify( (*ring.submit_q.head) == (*ring.submit_q.tail) );
534                verify( (*ring.completion_q.head) == (*ring.completion_q.tail) );
535
536                __cfadbg_print_safe(io_core, "Kernel I/O : Slow poller for ring %p ready\n", &ring);
537
538                if( ring.cltr_flags & CFA_CLUSTER_IO_POLLER_USER_THREAD ) {
539                        while(!__atomic_load_n(&ring.done, __ATOMIC_SEQ_CST)) {
540
541                                __atomic_store_n( &ring.poller.slow.blocked, true, __ATOMIC_SEQ_CST );
542
543                                // In the user-thread approach drain and if anything was drained,
544                                // batton pass to the user-thread
545                                int count;
546                                bool again;
547                                [count, again] = __drain_io( ring, &mask, 1, true );
548
549                                __atomic_store_n( &ring.poller.slow.blocked, false, __ATOMIC_SEQ_CST );
550
551                                // Update statistics
552                                __STATS__( true,
553                                        io.complete_q.completed_avg.val += count;
554                                        io.complete_q.completed_avg.slow_cnt += 1;
555                                )
556
557                                if(again) {
558                                        __cfadbg_print_safe(io_core, "Kernel I/O : Moving to ring %p to fast poller\n", &ring);
559                                        __unpark( &ring.poller.slow.id, &ring.poller.fast.thrd __cfaabi_dbg_ctx2 );
560                                        wait( ring.poller.sem );
561                                }
562                        }
563                }
564                else {
565                        while(!__atomic_load_n(&ring.done, __ATOMIC_SEQ_CST)) {
566                                //In the naive approach, just poll the io completion queue directly
567                                int count;
568                                bool again;
569                                [count, again] = __drain_io( ring, &mask, 1, true );
570
571                                // Update statistics
572                                __STATS__( true,
573                                        io.complete_q.completed_avg.val += count;
574                                        io.complete_q.completed_avg.slow_cnt += 1;
575                                )
576                        }
577                }
578
579                __cfadbg_print_safe(io_core, "Kernel I/O : Slow poller for ring %p stopping\n", &ring);
580
581                unregister( &ring.poller.slow.id );
582
583                #if !defined(__CFA_NO_STATISTICS__)
584                        __tally_stats(cltr->stats, &local_stats);
585                #endif
586
587                return 0p;
588        }
589
590        void main( __io_poller_fast & this ) {
591                verify( this.ring->cltr_flags & CFA_CLUSTER_IO_POLLER_USER_THREAD );
592
593                // Start parked
594                park( __cfaabi_dbg_ctx );
595
596                __cfadbg_print_safe(io_core, "Kernel I/O : Fast poller for ring %p ready\n", &this.ring);
597
598                int reset = 0;
599
600                // Then loop until we need to start
601                while(!__atomic_load_n(&this.ring->done, __ATOMIC_SEQ_CST)) {
602
603                        // Drain the io
604                        int count;
605                        bool again;
606                        disable_interrupts();
607                                [count, again] = __drain_io( *this.ring, 0p, 0, false );
608
609                                if(!again) reset++;
610
611                                // Update statistics
612                                __STATS__( true,
613                                        io.complete_q.completed_avg.val += count;
614                                        io.complete_q.completed_avg.fast_cnt += 1;
615                                )
616                        enable_interrupts( __cfaabi_dbg_ctx );
617
618                        // If we got something, just yield and check again
619                        if(reset < 5) {
620                                yield();
621                        }
622                        // We didn't get anything baton pass to the slow poller
623                        else {
624                                __cfadbg_print_safe(io_core, "Kernel I/O : Moving to ring %p to slow poller\n", &this.ring);
625                                reset = 0;
626
627                                // wake up the slow poller
628                                post( this.ring->poller.sem );
629
630                                // park this thread
631                                park( __cfaabi_dbg_ctx );
632                        }
633                }
634
635                __cfadbg_print_safe(io_core, "Kernel I/O : Fast poller for ring %p stopping\n", &this.ring);
636        }
637
638        static inline void __wake_poller( struct __io_data & ring ) __attribute__((artificial));
639        static inline void __wake_poller( struct __io_data & ring ) {
640                if(!__atomic_load_n( &ring.poller.slow.blocked, __ATOMIC_SEQ_CST)) return;
641
642                sigval val = { 1 };
643                pthread_sigqueue( ring.poller.slow.kthrd, SIGUSR1, val );
644        }
645
646//=============================================================================================
647// I/O Submissions
648//=============================================================================================
649
650// Submition steps :
651// 1 - Allocate a queue entry. The ring already has memory for all entries but only the ones
652//     listed in sq.array are visible by the kernel. For those not listed, the kernel does not
653//     offer any assurance that an entry is not being filled by multiple flags. Therefore, we
654//     need to write an allocator that allows allocating concurrently.
655//
656// 2 - Actually fill the submit entry, this is the only simple and straightforward step.
657//
658// 3 - Append the entry index to the array and adjust the tail accordingly. This operation
659//     needs to arrive to two concensus at the same time:
660//     A - The order in which entries are listed in the array: no two threads must pick the
661//         same index for their entries
662//     B - When can the tail be update for the kernel. EVERY entries in the array between
663//         head and tail must be fully filled and shouldn't ever be touched again.
664//
665
666        [* struct io_uring_sqe, uint32_t] __submit_alloc( struct __io_data & ring, uint64_t data ) {
667                /* paranoid */ verify( data != 0 );
668
669                // Prepare the data we need
670                __attribute((unused)) int len   = 0;
671                __attribute((unused)) int block = 0;
672                uint32_t cnt = *ring.submit_q.num;
673                uint32_t mask = *ring.submit_q.mask;
674
675                disable_interrupts();
676                        uint32_t off = __tls_rand();
677                enable_interrupts( __cfaabi_dbg_ctx );
678
679                // Loop around looking for an available spot
680                for() {
681                        // Look through the list starting at some offset
682                        for(i; cnt) {
683                                uint64_t expected = 0;
684                                uint32_t idx = (i + off) & mask;
685                                struct io_uring_sqe * sqe = &ring.submit_q.sqes[idx];
686                                volatile uint64_t * udata = &sqe->user_data;
687
688                                if( *udata == expected &&
689                                        __atomic_compare_exchange_n( udata, &expected, data, true, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED ) )
690                                {
691                                        // update statistics
692                                        __STATS__( false,
693                                                io.submit_q.alloc_avg.val   += len;
694                                                io.submit_q.alloc_avg.block += block;
695                                                io.submit_q.alloc_avg.cnt   += 1;
696                                        )
697
698
699                                        // Success return the data
700                                        return [sqe, idx];
701                                }
702                                verify(expected != data);
703
704                                len ++;
705                        }
706
707                        block++;
708                        yield();
709                }
710        }
711
712        static inline uint32_t __submit_to_ready_array( struct __io_data & ring, uint32_t idx, const uint32_t mask ) {
713                /* paranoid */ verify( idx <= mask   );
714                /* paranoid */ verify( idx != -1ul32 );
715
716                // We need to find a spot in the ready array
717                __attribute((unused)) int len   = 0;
718                __attribute((unused)) int block = 0;
719                uint32_t ready_mask = ring.submit_q.ready_cnt - 1;
720
721                disable_interrupts();
722                        uint32_t off = __tls_rand();
723                enable_interrupts( __cfaabi_dbg_ctx );
724
725                uint32_t picked;
726                LOOKING: for() {
727                        for(i; ring.submit_q.ready_cnt) {
728                                picked = (i + off) & ready_mask;
729                                uint32_t expected = -1ul32;
730                                if( __atomic_compare_exchange_n( &ring.submit_q.ready[picked], &expected, idx, true, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED ) ) {
731                                        break LOOKING;
732                                }
733                                verify(expected != idx);
734
735                                len ++;
736                        }
737
738                        block++;
739                        if( try_lock(ring.submit_q.lock __cfaabi_dbg_ctx2) ) {
740                                __release_consumed_submission( ring );
741                                unlock( ring.submit_q.lock );
742                        }
743                        else {
744                                yield();
745                        }
746                }
747
748                // update statistics
749                __STATS__( false,
750                        io.submit_q.look_avg.val   += len;
751                        io.submit_q.look_avg.block += block;
752                        io.submit_q.look_avg.cnt   += 1;
753                )
754
755                return picked;
756        }
757
758        void __submit( struct __io_data & ring, uint32_t idx ) {
759                // Get now the data we definetely need
760                uint32_t * const tail = ring.submit_q.tail;
761                const uint32_t mask = *ring.submit_q.mask;
762
763                // There are 2 submission schemes, check which one we are using
764                if( ring.cltr_flags & CFA_CLUSTER_IO_POLLER_THREAD_SUBMITS ) {
765                        // If the poller thread submits, then we just need to add this to the ready array
766                        __submit_to_ready_array( ring, idx, mask );
767
768                        __wake_poller( ring );
769
770                        __cfadbg_print_safe( io, "Kernel I/O : Added %u to ready for %p\n", idx, active_thread() );
771                }
772                else if( ring.cltr_flags & CFA_CLUSTER_IO_EAGER_SUBMITS ) {
773                        uint32_t picked = __submit_to_ready_array( ring, idx, mask );
774
775                        for() {
776                                yield();
777
778                                // If some one else collected our index, we are done
779                                #warning ABA problem
780                                if( ring.submit_q.ready[picked] != idx ) {
781                                        __STATS__( false,
782                                                io.submit_q.helped += 1;
783                                        )
784                                        return;
785                                }
786
787                                if( try_lock(ring.submit_q.lock __cfaabi_dbg_ctx2) ) {
788                                        __STATS__( false,
789                                                io.submit_q.leader += 1;
790                                        )
791                                        break;
792                                }
793
794                                __STATS__( false,
795                                        io.submit_q.busy += 1;
796                                )
797                        }
798
799                        // We got the lock
800                        unsigned to_submit = __collect_submitions( ring );
801                        int ret = syscall( __NR_io_uring_enter, ring.fd, to_submit, 0, 0, 0p, _NSIG / 8);
802                        if( ret < 0 ) {
803                                switch((int)errno) {
804                                case EAGAIN:
805                                case EINTR:
806                                        unlock(ring.submit_q.lock);
807                                        return;
808                                default:
809                                        abort( "KERNEL ERROR: IO_URING WAIT - %s\n", strerror(errno) );
810                                }
811                        }
812
813                        /* paranoid */ verify( ret > 0 );
814
815                        // Release the consumed SQEs
816                        __release_consumed_submission( ring );
817
818                        // update statistics
819                        __STATS__( true,
820                                io.submit_q.submit_avg.rdy += to_submit;
821                                io.submit_q.submit_avg.csm += ret;
822                                io.submit_q.submit_avg.cnt += 1;
823                        )
824
825                        unlock(ring.submit_q.lock);
826                }
827                else {
828                        // get mutual exclusion
829                        lock(ring.submit_q.lock __cfaabi_dbg_ctx2);
830
831                        // Append to the list of ready entries
832
833                        /* paranoid */ verify( idx <= mask );
834
835                        ring.submit_q.array[ (*tail) & mask ] = idx & mask;
836                        __atomic_fetch_add(tail, 1ul32, __ATOMIC_SEQ_CST);
837
838                        // Submit however, many entries need to be submitted
839                        int ret = syscall( __NR_io_uring_enter, ring.fd, 1, 0, 0, 0p, 0);
840                        if( ret < 0 ) {
841                                switch((int)errno) {
842                                default:
843                                        abort( "KERNEL ERROR: IO_URING SUBMIT - %s\n", strerror(errno) );
844                                }
845                        }
846
847                        // update statistics
848                        __STATS__( false,
849                                io.submit_q.submit_avg.csm += 1;
850                                io.submit_q.submit_avg.cnt += 1;
851                        )
852
853                        // Release the consumed SQEs
854                        __release_consumed_submission( ring );
855
856                        unlock(ring.submit_q.lock);
857
858                        __cfadbg_print_safe( io, "Kernel I/O : Performed io_submit for %p, returned %d\n", active_thread(), ret );
859                }
860        }
861
862        static unsigned __collect_submitions( struct __io_data & ring ) {
863                /* paranoid */ verify( ring.submit_q.ready != 0p );
864                /* paranoid */ verify( ring.submit_q.ready_cnt > 0 );
865
866                unsigned to_submit = 0;
867                uint32_t tail = *ring.submit_q.tail;
868                const uint32_t mask = *ring.submit_q.mask;
869
870                // Go through the list of ready submissions
871                for( i; ring.submit_q.ready_cnt ) {
872                        // replace any submission with the sentinel, to consume it.
873                        uint32_t idx = __atomic_exchange_n( &ring.submit_q.ready[i], -1ul32, __ATOMIC_RELAXED);
874
875                        // If it was already the sentinel, then we are done
876                        if( idx == -1ul32 ) continue;
877
878                        // If we got a real submission, append it to the list
879                        ring.submit_q.array[ (tail + to_submit) & mask ] = idx & mask;
880                        to_submit++;
881                }
882
883                // Increment the tail based on how many we are ready to submit
884                __atomic_fetch_add(ring.submit_q.tail, to_submit, __ATOMIC_SEQ_CST);
885
886                return to_submit;
887        }
888
889        static uint32_t __release_consumed_submission( struct __io_data & ring ) {
890                const uint32_t smask = *ring.submit_q.mask;
891                uint32_t chead = *ring.submit_q.head;
892                uint32_t phead = ring.submit_q.prev_head;
893                ring.submit_q.prev_head = chead;
894                uint32_t count = chead - phead;
895                for( i; count ) {
896                        uint32_t idx = ring.submit_q.array[ (phead + i) & smask ];
897                        ring.submit_q.sqes[ idx ].user_data = 0;
898                }
899                return count;
900        }
901#endif
Note: See TracBrowser for help on using the repository browser.