source: libcfa/src/concurrency/io.cfa @ 4e74466

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

Fast poller thread now polls a few times before baton-passing to the slow thread.
Currently doing 5 tries, the number is arbitrary and requires more work.

  • Property mode set to 100644
File size: 31.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 __CFA_DEBUG_PRINT_IO__
17// #define __CFA_DEBUG_PRINT_IO_CORE__
18
19#include "kernel.hfa"
20
21#if !defined(HAVE_LINUX_IO_URING_H)
22        void __kernel_io_startup( cluster &, int, bool ) {
23                // Nothing to do without io_uring
24        }
25
26        void __kernel_io_finish_start( cluster & ) {
27                // Nothing to do without io_uring
28        }
29
30        void __kernel_io_prepare_stop( cluster & ) {
31                // Nothing to do without io_uring
32        }
33
34        void __kernel_io_shutdown( cluster &, bool ) {
35                // Nothing to do without io_uring
36        }
37
38#else
39        extern "C" {
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                #include <sys/syscall.h>
47
48                #include <linux/io_uring.h>
49        }
50
51        #include "bits/signal.hfa"
52        #include "kernel_private.hfa"
53        #include "thread.hfa"
54
55        uint32_t entries_per_cluster() {
56                return 256;
57        }
58
59        static void * __io_poller_slow( void * arg );
60
61        // Weirdly, some systems that do support io_uring don't actually define these
62        #ifdef __alpha__
63                /*
64                * alpha is the only exception, all other architectures
65                * have common numbers for new system calls.
66                */
67                #ifndef __NR_io_uring_setup
68                        #define __NR_io_uring_setup           535
69                #endif
70                #ifndef __NR_io_uring_enter
71                        #define __NR_io_uring_enter           536
72                #endif
73                #ifndef __NR_io_uring_register
74                        #define __NR_io_uring_register        537
75                #endif
76        #else /* !__alpha__ */
77                #ifndef __NR_io_uring_setup
78                        #define __NR_io_uring_setup           425
79                #endif
80                #ifndef __NR_io_uring_enter
81                        #define __NR_io_uring_enter           426
82                #endif
83                #ifndef __NR_io_uring_register
84                        #define __NR_io_uring_register        427
85                #endif
86        #endif
87
88        // Fast poller user-thread
89        // Not using the "thread" keyword because we want to control
90        // more carefully when to start/stop it
91        struct __io_poller_fast {
92                struct __io_data * ring;
93                bool waiting;
94                $thread thrd;
95        };
96
97        void ?{}( __io_poller_fast & this, struct cluster & cltr ) {
98                this.ring = cltr.io;
99                this.waiting = true;
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
112                // The actual kernel ring which uses head/tail
113                // indexes into the sqes arrays
114                uint32_t * array;
115
116                // number of entries and mask to go with it
117                const uint32_t * num;
118                const uint32_t * mask;
119
120                // Submission flags (Not sure what for)
121                uint32_t * flags;
122
123                // number of sqes not submitted (whatever that means)
124                uint32_t * dropped;
125
126                // Like head/tail but not seen by the kernel
127                volatile uint32_t alloc;
128                volatile uint32_t ready;
129
130                __spinlock_t lock;
131
132                // A buffer of sqes (not the actual ring)
133                struct io_uring_sqe * sqes;
134
135                // The location and size of the mmaped area
136                void * ring_ptr;
137                size_t ring_sz;
138
139                // Statistics
140                #if !defined(__CFA_NO_STATISTICS__)
141                        struct {
142                                struct {
143                                        unsigned long long int val;
144                                        unsigned long long int cnt;
145                                } submit_avg;
146                        } stats;
147                #endif
148        };
149
150        struct __completion_data {
151                // Head and tail of the ring
152                volatile uint32_t * head;
153                volatile uint32_t * tail;
154
155                // number of entries and mask to go with it
156                const uint32_t * mask;
157                const uint32_t * num;
158
159                // number of cqes not submitted (whatever that means)
160                uint32_t * overflow;
161
162                // the kernel ring
163                struct io_uring_cqe * cqes;
164
165                // The location and size of the mmaped area
166                void * ring_ptr;
167                size_t ring_sz;
168
169                // Statistics
170                #if !defined(__CFA_NO_STATISTICS__)
171                        struct {
172                                struct {
173                                        unsigned long long int val;
174                                        unsigned long long int slow_cnt;
175                                        unsigned long long int fast_cnt;
176                                } completed_avg;
177                        } stats;
178                #endif
179        };
180
181        struct __io_data {
182                struct __submition_data submit_q;
183                struct __completion_data completion_q;
184                uint32_t ring_flags;
185                int cltr_flags;
186                int fd;
187                semaphore submit;
188                volatile bool done;
189                struct {
190                        struct {
191                                void * stack;
192                                pthread_t kthrd;
193                        } slow;
194                        __io_poller_fast fast;
195                        __bin_sem_t sem;
196                } poller;
197        };
198
199//=============================================================================================
200// I/O Startup / Shutdown logic
201//=============================================================================================
202        void __kernel_io_startup( cluster & this, int io_flags, bool main_cluster ) {
203                this.io = malloc();
204
205                // Step 1 : call to setup
206                struct io_uring_params params;
207                memset(&params, 0, sizeof(params));
208
209                uint32_t nentries = entries_per_cluster();
210
211                int fd = syscall(__NR_io_uring_setup, nentries, &params );
212                if(fd < 0) {
213                        abort("KERNEL ERROR: IO_URING SETUP - %s\n", strerror(errno));
214                }
215
216                // Step 2 : mmap result
217                memset( this.io, 0, sizeof(struct __io_data) );
218                struct __submition_data  & sq = this.io->submit_q;
219                struct __completion_data & cq = this.io->completion_q;
220
221                // calculate the right ring size
222                sq.ring_sz = params.sq_off.array + (params.sq_entries * sizeof(unsigned)           );
223                cq.ring_sz = params.cq_off.cqes  + (params.cq_entries * sizeof(struct io_uring_cqe));
224
225                // Requires features
226                #if defined(IORING_FEAT_SINGLE_MMAP)
227                        // adjust the size according to the parameters
228                        if ((params.features & IORING_FEAT_SINGLE_MMAP) != 0) {
229                                cq->ring_sz = sq->ring_sz = max(cq->ring_sz, sq->ring_sz);
230                        }
231                #endif
232
233                // mmap the Submit Queue into existence
234                sq.ring_ptr = mmap(0, sq.ring_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_SQ_RING);
235                if (sq.ring_ptr == (void*)MAP_FAILED) {
236                        abort("KERNEL ERROR: IO_URING MMAP1 - %s\n", strerror(errno));
237                }
238
239                // Requires features
240                #if defined(IORING_FEAT_SINGLE_MMAP)
241                        // mmap the Completion Queue into existence (may or may not be needed)
242                        if ((params.features & IORING_FEAT_SINGLE_MMAP) != 0) {
243                                cq->ring_ptr = sq->ring_ptr;
244                        }
245                        else
246                #endif
247                {
248                        // We need multiple call to MMAP
249                        cq.ring_ptr = mmap(0, cq.ring_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_CQ_RING);
250                        if (cq.ring_ptr == (void*)MAP_FAILED) {
251                                munmap(sq.ring_ptr, sq.ring_sz);
252                                abort("KERNEL ERROR: IO_URING MMAP2 - %s\n", strerror(errno));
253                        }
254                }
255
256                // mmap the submit queue entries
257                size_t size = params.sq_entries * sizeof(struct io_uring_sqe);
258                sq.sqes = (struct io_uring_sqe *)mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_SQES);
259                if (sq.sqes == (struct io_uring_sqe *)MAP_FAILED) {
260                        munmap(sq.ring_ptr, sq.ring_sz);
261                        if (cq.ring_ptr != sq.ring_ptr) munmap(cq.ring_ptr, cq.ring_sz);
262                        abort("KERNEL ERROR: IO_URING MMAP3 - %s\n", strerror(errno));
263                }
264
265                // Get the pointers from the kernel to fill the structure
266                // submit queue
267                sq.head    = (volatile uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.head);
268                sq.tail    = (volatile uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.tail);
269                sq.mask    = (   const uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.ring_mask);
270                sq.num     = (   const uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.ring_entries);
271                sq.flags   = (         uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.flags);
272                sq.dropped = (         uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.dropped);
273                sq.array   = (         uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.array);
274                sq.alloc = *sq.tail;
275                sq.ready = *sq.tail;
276
277                // completion queue
278                cq.head     = (volatile uint32_t *)(((intptr_t)cq.ring_ptr) + params.cq_off.head);
279                cq.tail     = (volatile uint32_t *)(((intptr_t)cq.ring_ptr) + params.cq_off.tail);
280                cq.mask     = (   const uint32_t *)(((intptr_t)cq.ring_ptr) + params.cq_off.ring_mask);
281                cq.num      = (   const uint32_t *)(((intptr_t)cq.ring_ptr) + params.cq_off.ring_entries);
282                cq.overflow = (         uint32_t *)(((intptr_t)cq.ring_ptr) + params.cq_off.overflow);
283                cq.cqes   = (struct io_uring_cqe *)(((intptr_t)cq.ring_ptr) + params.cq_off.cqes);
284
285                // some paranoid checks
286                /* 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  );
287                /* paranoid */ verifyf( (*cq.num)  >= nentries, "IO_URING Expected %u entries, got %u", nentries, *cq.num );
288                /* paranoid */ verifyf( (*cq.head) == 0, "IO_URING Expected head to be 0, got %u", *cq.head );
289                /* paranoid */ verifyf( (*cq.tail) == 0, "IO_URING Expected tail to be 0, got %u", *cq.tail );
290
291                /* 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 );
292                /* paranoid */ verifyf( (*sq.num) >= nentries, "IO_URING Expected %u entries, got %u", nentries, *sq.num );
293                /* paranoid */ verifyf( (*sq.head) == 0, "IO_URING Expected head to be 0, got %u", *sq.head );
294                /* paranoid */ verifyf( (*sq.tail) == 0, "IO_URING Expected tail to be 0, got %u", *sq.tail );
295
296                // Update the global ring info
297                this.io->ring_flags = params.flags;
298                this.io->cltr_flags = io_flags;
299                this.io->fd         = fd;
300                this.io->done       = false;
301                (this.io->submit){ min(*sq.num, *cq.num) };
302
303                // Initialize statistics
304                #if !defined(__CFA_NO_STATISTICS__)
305                        this.io->submit_q.stats.submit_avg.val = 0;
306                        this.io->submit_q.stats.submit_avg.cnt = 0;
307                        this.io->completion_q.stats.completed_avg.val = 0;
308                        this.io->completion_q.stats.completed_avg.slow_cnt = 0;
309                        this.io->completion_q.stats.completed_avg.fast_cnt = 0;
310                #endif
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.stack = __create_pthread( &this.io->poller.slow.kthrd, __io_poller_slow, &this );
327        }
328
329        void __kernel_io_prepare_stop( cluster & this ) {
330                __cfadbg_print_safe(io_core, "Kernel I/O : Stopping pollers for cluster\n", &this);
331                // Notify the poller thread of the shutdown
332                __atomic_store_n(&this.io->done, true, __ATOMIC_SEQ_CST);
333
334                // Stop the IO Poller
335                sigval val = { 1 };
336                pthread_sigqueue( this.io->poller.slow.kthrd, SIGUSR1, val );
337                post( this.io->poller.sem );
338
339                // Wait for the poller thread to finish
340                pthread_join( this.io->poller.slow.kthrd, 0p );
341                free( this.io->poller.slow.stack );
342
343                __cfadbg_print_safe(io_core, "Kernel I/O : Slow poller stopped for cluster\n", &this);
344
345                if( this.io->cltr_flags & CFA_CLUSTER_IO_POLLER_USER_THREAD ) {
346                        verify( this.io->poller.fast.waiting );
347                        verify( this.io->poller.fast.thrd.state == Blocked );
348
349                        this.io->poller.fast.thrd.curr_cluster = mainCluster;
350
351                        // unpark the fast io_poller
352                        unpark( &this.io->poller.fast.thrd __cfaabi_dbg_ctx2 );
353
354                        ^(this.io->poller.fast){};
355
356                        __cfadbg_print_safe(io_core, "Kernel I/O : Fast poller stopped for cluster\n", &this);
357                }
358        }
359
360        void __kernel_io_shutdown( cluster & this, bool main_cluster ) {
361                if(!main_cluster) {
362                        __kernel_io_prepare_stop( this );
363                }
364
365                // print statistics
366                #if !defined(__CFA_NO_STATISTICS__)
367                        if(this.print_stats) {
368                                with(this.io->submit_q.stats, this.io->completion_q.stats) {
369                                        __cfaabi_bits_print_safe( STDERR_FILENO,
370                                                "----- I/O uRing Stats -----\n"
371                                                "- total submit calls  : %llu\n"
372                                                "- avg submit          : %lf\n"
373                                                "- total wait calls    : %llu (%llu slow, %llu fast)\n"
374                                                "- avg completion/wait : %lf\n",
375                                                submit_avg.cnt,
376                                                ((double)submit_avg.val) / submit_avg.cnt,
377                                                completed_avg.slow_cnt + completed_avg.fast_cnt,
378                                                completed_avg.slow_cnt,  completed_avg.fast_cnt,
379                                                ((double)completed_avg.val) / (completed_avg.slow_cnt + completed_avg.fast_cnt)
380                                        );
381                                }
382                        }
383                #endif
384
385                // Shutdown the io rings
386                struct __submition_data  & sq = this.io->submit_q;
387                struct __completion_data & cq = this.io->completion_q;
388
389                // unmap the submit queue entries
390                munmap(sq.sqes, (*sq.num) * sizeof(struct io_uring_sqe));
391
392                // unmap the Submit Queue ring
393                munmap(sq.ring_ptr, sq.ring_sz);
394
395                // unmap the Completion Queue ring, if it is different
396                if (cq.ring_ptr != sq.ring_ptr) {
397                        munmap(cq.ring_ptr, cq.ring_sz);
398                }
399
400                // close the file descriptor
401                close(this.io->fd);
402
403                free( this.io );
404        }
405
406//=============================================================================================
407// I/O Polling
408//=============================================================================================
409        struct io_user_data {
410                int32_t result;
411                $thread * thrd;
412        };
413
414        // Process a single completion message from the io_uring
415        // This is NOT thread-safe
416        static int __drain_io( struct __io_data & ring, sigset_t * mask, int waitcnt, bool in_kernel ) {
417                int ret = syscall( __NR_io_uring_enter, ring.fd, 0, waitcnt, IORING_ENTER_GETEVENTS, mask, _NSIG / 8);
418                if( ret < 0 ) {
419                        switch((int)errno) {
420                        case EAGAIN:
421                        case EINTR:
422                                return -EAGAIN;
423                        default:
424                                abort( "KERNEL ERROR: IO_URING WAIT - %s\n", strerror(errno) );
425                        }
426                }
427
428                // Drain the queue
429                unsigned head = *ring.completion_q.head;
430                unsigned tail = __atomic_load_n(ring.completion_q.tail, __ATOMIC_ACQUIRE);
431
432                // Nothing was new return 0
433                if (head == tail) {
434                        return 0;
435                }
436
437                uint32_t count = tail - head;
438                for(i; count) {
439                        unsigned idx = (head + i) & (*ring.completion_q.mask);
440                        struct io_uring_cqe & cqe = ring.completion_q.cqes[idx];
441
442                        /* paranoid */ verify(&cqe);
443
444                        struct io_user_data * data = (struct io_user_data *)cqe.user_data;
445                        __cfadbg_print_safe( io, "Kernel I/O : Performed reading io cqe %p, result %d for %p\n", data, cqe.res, data->thrd );
446
447                        data->result = cqe.res;
448                        if(!in_kernel) { unpark( data->thrd __cfaabi_dbg_ctx2 ); }
449                        else         { __unpark( data->thrd __cfaabi_dbg_ctx2 ); }
450                }
451
452                // Allow new submissions to happen
453                V(ring.submit, count);
454
455                // Mark to the kernel that the cqe has been seen
456                // Ensure that the kernel only sees the new value of the head index after the CQEs have been read.
457                __atomic_fetch_add( ring.completion_q.head, count, __ATOMIC_RELAXED );
458
459                return count;
460        }
461
462        static void * __io_poller_slow( void * arg ) {
463                cluster * cltr = (cluster *)arg;
464                struct __io_data & ring = *cltr->io;
465
466                sigset_t mask;
467                sigfillset(&mask);
468                if ( pthread_sigmask( SIG_BLOCK, &mask, 0p ) == -1 ) {
469                        abort( "KERNEL ERROR: IO_URING - pthread_sigmask" );
470                }
471
472                sigdelset( &mask, SIGUSR1 );
473
474                verify( (*ring.submit_q.head) == (*ring.submit_q.tail) );
475                verify( (*ring.completion_q.head) == (*ring.completion_q.tail) );
476
477                __cfadbg_print_safe(io_core, "Kernel I/O : Slow poller for ring %p ready\n", &ring);
478
479                if( ring.cltr_flags & CFA_CLUSTER_IO_POLLER_USER_THREAD ) {
480                        while(!__atomic_load_n(&ring.done, __ATOMIC_SEQ_CST)) {
481                                // In the user-thread approach drain and if anything was drained,
482                                // batton pass to the user-thread
483                                int count = __drain_io( ring, &mask, 1, true );
484
485                                // Update statistics
486                                #if !defined(__CFA_NO_STATISTICS__)
487                                        ring.completion_q.stats.completed_avg.val += count;
488                                        ring.completion_q.stats.completed_avg.slow_cnt += 1;
489                                #endif
490
491                                if(count > 0) {
492                                        __cfadbg_print_safe(io_core, "Kernel I/O : Moving to ring %p to fast poller\n", &ring);
493                                        __unpark( &ring.poller.fast.thrd __cfaabi_dbg_ctx2 );
494                                        wait( ring.poller.sem );
495                                }
496                        }
497                }
498                else {
499                        while(!__atomic_load_n(&ring.done, __ATOMIC_SEQ_CST)) {
500                                //In the naive approach, just poll the io completion queue directly
501                                int count = __drain_io( ring, &mask, 1, true );
502
503                                // Update statistics
504                                #if !defined(__CFA_NO_STATISTICS__)
505                                        ring.completion_q.stats.completed_avg.val += count;
506                                        ring.completion_q.stats.completed_avg.slow_cnt += 1;
507                                #endif
508                        }
509                }
510
511                __cfadbg_print_safe(io_core, "Kernel I/O : Slow poller for ring %p stopping\n", &ring);
512
513                return 0p;
514        }
515
516        void main( __io_poller_fast & this ) {
517                verify( this.ring->cltr_flags & CFA_CLUSTER_IO_POLLER_USER_THREAD );
518
519                // Start parked
520                park( __cfaabi_dbg_ctx );
521
522                __cfadbg_print_safe(io_core, "Kernel I/O : Fast poller for ring %p ready\n", &this.ring);
523
524                int reset = 0;
525
526                // Then loop until we need to start
527                while(!__atomic_load_n(&this.ring->done, __ATOMIC_SEQ_CST)) {
528                        // Drain the io
529                        this.waiting = false;
530                        int count = __drain_io( *this.ring, 0p, 0, false );
531                        reset += count > 0 ? 1 : 0;
532
533                        // Update statistics
534                        #if !defined(__CFA_NO_STATISTICS__)
535                                this.ring->completion_q.stats.completed_avg.val += count;
536                                this.ring->completion_q.stats.completed_avg.fast_cnt += 1;
537                        #endif
538
539                        this.waiting = true;
540                        if(reset < 5) {
541                                // If we got something, just yield and check again
542                                yield();
543                        }
544                        else {
545                                // We didn't get anything baton pass to the slow poller
546                                __cfadbg_print_safe(io_core, "Kernel I/O : Moving to ring %p to slow poller\n", &this.ring);
547                                post( this.ring->poller.sem );
548                                park( __cfaabi_dbg_ctx );
549                                reset = 0;
550                        }
551                }
552
553                __cfadbg_print_safe(io_core, "Kernel I/O : Fast poller for ring %p stopping\n", &this.ring);
554        }
555
556//=============================================================================================
557// I/O Submissions
558//=============================================================================================
559
560// Submition steps :
561// 1 - We need to make sure we don't overflow any of the buffer, P(ring.submit) to make sure
562//     entries are available. The semaphore make sure that there is no more operations in
563//     progress then the number of entries in the buffer. This probably limits concurrency
564//     more than necessary since submitted but not completed operations don't need any
565//     entries in user space. However, I don't know what happens if we overflow the buffers
566//     because too many requests completed at once. This is a safe approach in all cases.
567//     Furthermore, with hundreds of entries, this may be okay.
568//
569// 2 - Allocate a queue entry. The ring already has memory for all entries but only the ones
570//     listed in sq.array are visible by the kernel. For those not listed, the kernel does not
571//     offer any assurance that an entry is not being filled by multiple flags. Therefore, we
572//     need to write an allocator that allows allocating concurrently.
573//
574// 3 - Actually fill the submit entry, this is the only simple and straightforward step.
575//
576// 4 - Append the entry index to the array and adjust the tail accordingly. This operation
577//     needs to arrive to two concensus at the same time:
578//     A - The order in which entries are listed in the array: no two threads must pick the
579//         same index for their entries
580//     B - When can the tail be update for the kernel. EVERY entries in the array between
581//         head and tail must be fully filled and shouldn't ever be touched again.
582//
583
584        static inline [* struct io_uring_sqe, uint32_t] __submit_alloc( struct __io_data & ring ) {
585                // Wait for a spot to be available
586                P(ring.submit);
587
588                // Allocate the sqe
589                uint32_t idx = __atomic_fetch_add(&ring.submit_q.alloc, 1ul32, __ATOMIC_SEQ_CST);
590
591                // Validate that we didn't overflow anything
592                // Check that nothing overflowed
593                /* paranoid */ verify( true );
594
595                // Check that it goes head -> tail -> alloc and never head -> alloc -> tail
596                /* paranoid */ verify( true );
597
598                // Return the sqe
599                return [&ring.submit_q.sqes[ idx & (*ring.submit_q.mask)], idx];
600        }
601
602        static inline void __submit( struct __io_data & ring, uint32_t idx ) {
603                // get mutual exclusion
604                lock(ring.submit_q.lock __cfaabi_dbg_ctx2);
605
606                // Append to the list of ready entries
607                uint32_t * tail = ring.submit_q.tail;
608                const uint32_t mask = *ring.submit_q.mask;
609
610                ring.submit_q.array[ (*tail) & mask ] = idx & mask;
611                __atomic_fetch_add(tail, 1ul32, __ATOMIC_SEQ_CST);
612
613                // Submit however, many entries need to be submitted
614                int ret = syscall( __NR_io_uring_enter, ring.fd, 1, 0, 0, 0p, 0);
615                if( ret < 0 ) {
616                        switch((int)errno) {
617                        default:
618                                abort( "KERNEL ERROR: IO_URING SUBMIT - %s\n", strerror(errno) );
619                        }
620                }
621
622                // update statistics
623                #if !defined(__CFA_NO_STATISTICS__)
624                        ring.submit_q.stats.submit_avg.val += 1;
625                        ring.submit_q.stats.submit_avg.cnt += 1;
626                #endif
627
628                unlock(ring.submit_q.lock);
629                // Make sure that idx was submitted
630                // Be careful to not get false positive if we cycled the entire list or that someone else submitted for us
631                __cfadbg_print_safe( io, "Kernel I/O : Performed io_submit for %p, returned %d\n", active_thread(), ret );
632        }
633
634        static inline void ?{}(struct io_uring_sqe & this, uint8_t opcode, int fd) {
635                this.opcode = opcode;
636                #if !defined(IOSQE_ASYNC)
637                        this.flags = 0;
638                #else
639                        this.flags = IOSQE_ASYNC;
640                #endif
641                this.ioprio = 0;
642                this.fd = fd;
643                this.off = 0;
644                this.addr = 0;
645                this.len = 0;
646                this.rw_flags = 0;
647                this.__pad2[0] = this.__pad2[1] = this.__pad2[2] = 0;
648        }
649
650        static inline void ?{}(struct io_uring_sqe & this, uint8_t opcode, int fd, void * addr, uint32_t len, uint64_t off ) {
651                (this){ opcode, fd };
652                this.off = off;
653                this.addr = (uint64_t)addr;
654                this.len = len;
655        }
656
657
658//=============================================================================================
659// I/O Interface
660//=============================================================================================
661
662        #define __submit_prelude \
663                struct __io_data & ring = *active_cluster()->io; \
664                struct io_uring_sqe * sqe; \
665                uint32_t idx; \
666                [sqe, idx] = __submit_alloc( ring );
667
668        #define __submit_wait \
669                io_user_data data = { 0, active_thread() }; \
670                /*__cfaabi_bits_print_safe( STDERR_FILENO, "Preparing user data %p for %p\n", &data, data.thrd );*/ \
671                sqe->user_data = (uint64_t)&data; \
672                __submit( ring, idx ); \
673                park( __cfaabi_dbg_ctx ); \
674                return data.result;
675#endif
676
677// Some forward declarations
678extern "C" {
679        #include <unistd.h>
680        #include <sys/types.h>
681        #include <sys/socket.h>
682        #include <sys/syscall.h>
683        struct iovec;
684        extern ssize_t preadv2 (int fd, const struct iovec *iov, int iovcnt, off_t offset, int flags);
685        extern ssize_t pwritev2(int fd, const struct iovec *iov, int iovcnt, off_t offset, int flags);
686
687        extern int fsync(int fd);
688        extern int sync_file_range(int fd, int64_t offset, int64_t nbytes, unsigned int flags);
689
690        struct msghdr;
691        struct sockaddr;
692        extern ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags);
693        extern ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);
694        extern ssize_t send(int sockfd, const void *buf, size_t len, int flags);
695        extern ssize_t recv(int sockfd, void *buf, size_t len, int flags);
696        extern int accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags);
697        extern int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
698
699        extern int fallocate(int fd, int mode, uint64_t offset, uint64_t len);
700        extern int posix_fadvise(int fd, uint64_t offset, uint64_t len, int advice);
701        extern int madvise(void *addr, size_t length, int advice);
702
703        extern int openat(int dirfd, const char *pathname, int flags, mode_t mode);
704        extern int close(int fd);
705
706        extern ssize_t read (int fd, void *buf, size_t count);
707}
708
709//-----------------------------------------------------------------------------
710// Asynchronous operations
711ssize_t cfa_preadv2(int fd, const struct iovec *iov, int iovcnt, off_t offset, int flags) {
712        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_READV)
713                return preadv2(fd, iov, iovcnt, offset, flags);
714        #else
715                __submit_prelude
716
717                (*sqe){ IORING_OP_READV, fd, iov, iovcnt, offset };
718
719                __submit_wait
720        #endif
721}
722
723ssize_t cfa_pwritev2(int fd, const struct iovec *iov, int iovcnt, off_t offset, int flags) {
724        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_WRITEV)
725                return pwritev2(fd, iov, iovcnt, offset, flags);
726        #else
727                __submit_prelude
728
729                (*sqe){ IORING_OP_WRITEV, fd, iov, iovcnt, offset };
730
731                __submit_wait
732        #endif
733}
734
735int cfa_fsync(int fd) {
736        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_FSYNC)
737                return fsync(fd);
738        #else
739                __submit_prelude
740
741                (*sqe){ IORING_OP_FSYNC, fd };
742
743                __submit_wait
744        #endif
745}
746
747int cfa_sync_file_range(int fd, int64_t offset, int64_t nbytes, unsigned int flags) {
748        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_SYNC_FILE_RANGE)
749                return sync_file_range(fd, offset, nbytes, flags);
750        #else
751                __submit_prelude
752
753                (*sqe){ IORING_OP_SYNC_FILE_RANGE, fd };
754                sqe->off = offset;
755                sqe->len = nbytes;
756                sqe->sync_range_flags = flags;
757
758                __submit_wait
759        #endif
760}
761
762
763ssize_t cfa_sendmsg(int sockfd, const struct msghdr *msg, int flags) {
764        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_SENDMSG)
765                return sendmsg(sockfd, msg, flags);
766        #else
767                __submit_prelude
768
769                (*sqe){ IORING_OP_SENDMSG, sockfd, msg, 1, 0 };
770                sqe->msg_flags = flags;
771
772                __submit_wait
773        #endif
774}
775
776ssize_t cfa_recvmsg(int sockfd, struct msghdr *msg, int flags) {
777        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_RECVMSG)
778                return recvmsg(sockfd, msg, flags);
779        #else
780                __submit_prelude
781
782                (*sqe){ IORING_OP_RECVMSG, sockfd, msg, 1, 0 };
783                sqe->msg_flags = flags;
784
785                __submit_wait
786        #endif
787}
788
789ssize_t cfa_send(int sockfd, const void *buf, size_t len, int flags) {
790        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_SEND)
791                return send( sockfd, buf, len, flags );
792        #else
793                __submit_prelude
794
795                (*sqe){ IORING_OP_SEND, sockfd };
796                sqe->addr = (uint64_t)buf;
797                sqe->len = len;
798                sqe->msg_flags = flags;
799
800                __submit_wait
801        #endif
802}
803
804ssize_t cfa_recv(int sockfd, void *buf, size_t len, int flags) {
805        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_RECV)
806                return recv( sockfd, buf, len, flags );
807        #else
808                __submit_prelude
809
810                (*sqe){ IORING_OP_RECV, sockfd };
811                sqe->addr = (uint64_t)buf;
812                sqe->len = len;
813                sqe->msg_flags = flags;
814
815                __submit_wait
816        #endif
817}
818
819int cfa_accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags) {
820        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_ACCEPT)
821                return accept4( sockfd, addr, addrlen, flags );
822        #else
823                __submit_prelude
824
825                (*sqe){ IORING_OP_ACCEPT, sockfd };
826                sqe->addr = addr;
827                sqe->addr2 = addrlen;
828                sqe->accept_flags = flags;
829
830                __submit_wait
831        #endif
832}
833
834int cfa_connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
835        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_CONNECT)
836                return connect( sockfd, addr, addrlen );
837        #else
838                __submit_prelude
839
840                (*sqe){ IORING_OP_CONNECT, sockfd };
841                sqe->addr = (uint64_t)addr;
842                sqe->off = addrlen;
843
844                __submit_wait
845        #endif
846}
847
848int cfa_fallocate(int fd, int mode, uint64_t offset, uint64_t len) {
849        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_FALLOCATE)
850                return fallocate( fd, mode, offset, len );
851        #else
852                __submit_prelude
853
854                (*sqe){ IORING_OP_FALLOCATE, fd };
855                sqe->off = offset;
856                sqe->len = length;
857                sqe->mode = mode;
858
859                __submit_wait
860        #endif
861}
862
863int cfa_fadvise(int fd, uint64_t offset, uint64_t len, int advice) {
864        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_FADVISE)
865                return posix_fadvise( fd, offset, len, advice );
866        #else
867                __submit_prelude
868
869                (*sqe){ IORING_OP_FADVISE, fd };
870                sqe->off = (uint64_t)offset;
871                sqe->len = length;
872                sqe->fadvise_advice = advice;
873
874                __submit_wait
875        #endif
876}
877
878int cfa_madvise(void *addr, size_t length, int advice) {
879        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_MADVISE)
880                return madvise( addr, length, advice );
881        #else
882                __submit_prelude
883
884                (*sqe){ IORING_OP_MADVISE, 0 };
885                sqe->addr = (uint64_t)addr;
886                sqe->len = length;
887                sqe->fadvise_advice = advice;
888
889                __submit_wait
890        #endif
891}
892
893int cfa_openat(int dirfd, const char *pathname, int flags, mode_t mode) {
894        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_OPENAT)
895                return openat( dirfd, pathname, flags, mode );
896        #else
897                __submit_prelude
898
899                (*sqe){ IORING_OP_OPENAT, dirfd };
900                sqe->addr = (uint64_t)pathname;
901                sqe->open_flags = flags;
902                sqe->mode = mode;
903
904                __submit_wait
905        #endif
906}
907
908int cfa_close(int fd) {
909        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_CLOSE)
910                return close( fd );
911        #else
912                __submit_prelude
913
914                (*sqe){ IORING_OP_CLOSE, fd };
915
916                __submit_wait
917        #endif
918}
919
920
921ssize_t cfa_read(int fd, void *buf, size_t count) {
922        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_READ)
923                return read( fd, buf, count );
924        #else
925                __submit_prelude
926
927                (*sqe){ IORING_OP_READ, fd, buf, count, 0 };
928
929                __submit_wait
930        #endif
931}
932
933ssize_t cfa_write(int fd, void *buf, size_t count) {
934        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_WRITE)
935                return read( fd, buf, count );
936        #else
937                __submit_prelude
938
939                (*sqe){ IORING_OP_WRITE, fd, buf, count, 0 };
940
941                __submit_wait
942        #endif
943}
944
945//-----------------------------------------------------------------------------
946// Check if a function is asynchronous
947
948// Macro magic to reduce the size of the following switch case
949#define IS_DEFINED_APPLY(f, ...) f(__VA_ARGS__)
950#define IS_DEFINED_SECOND(first, second, ...) second
951#define IS_DEFINED_TEST(expansion) _CFA_IO_FEATURE_##expansion
952#define IS_DEFINED(macro) IS_DEFINED_APPLY( IS_DEFINED_SECOND,IS_DEFINED_TEST(macro) false, true)
953
954bool has_user_level_blocking( fptr_t func ) {
955        #if defined(HAVE_LINUX_IO_URING_H)
956                if( /*func == (fptr_t)preadv2 || */
957                        func == (fptr_t)cfa_preadv2 )
958                        #define _CFA_IO_FEATURE_IORING_OP_READV ,
959                        return IS_DEFINED(IORING_OP_READV);
960
961                if( /*func == (fptr_t)pwritev2 || */
962                        func == (fptr_t)cfa_pwritev2 )
963                        #define _CFA_IO_FEATURE_IORING_OP_WRITEV ,
964                        return IS_DEFINED(IORING_OP_WRITEV);
965
966                if( /*func == (fptr_t)fsync || */
967                        func == (fptr_t)cfa_fsync )
968                        #define _CFA_IO_FEATURE_IORING_OP_FSYNC ,
969                        return IS_DEFINED(IORING_OP_FSYNC);
970
971                if( /*func == (fptr_t)ync_file_range || */
972                        func == (fptr_t)cfa_sync_file_range )
973                        #define _CFA_IO_FEATURE_IORING_OP_SYNC_FILE_RANGE ,
974                        return IS_DEFINED(IORING_OP_SYNC_FILE_RANGE);
975
976                if( /*func == (fptr_t)sendmsg || */
977                        func == (fptr_t)cfa_sendmsg )
978                        #define _CFA_IO_FEATURE_IORING_OP_SENDMSG ,
979                        return IS_DEFINED(IORING_OP_SENDMSG);
980
981                if( /*func == (fptr_t)recvmsg || */
982                        func == (fptr_t)cfa_recvmsg )
983                        #define _CFA_IO_FEATURE_IORING_OP_RECVMSG ,
984                        return IS_DEFINED(IORING_OP_RECVMSG);
985
986                if( /*func == (fptr_t)send || */
987                        func == (fptr_t)cfa_send )
988                        #define _CFA_IO_FEATURE_IORING_OP_SEND ,
989                        return IS_DEFINED(IORING_OP_SEND);
990
991                if( /*func == (fptr_t)recv || */
992                        func == (fptr_t)cfa_recv )
993                        #define _CFA_IO_FEATURE_IORING_OP_RECV ,
994                        return IS_DEFINED(IORING_OP_RECV);
995
996                if( /*func == (fptr_t)accept4 || */
997                        func == (fptr_t)cfa_accept4 )
998                        #define _CFA_IO_FEATURE_IORING_OP_ACCEPT ,
999                        return IS_DEFINED(IORING_OP_ACCEPT);
1000
1001                if( /*func == (fptr_t)connect || */
1002                        func == (fptr_t)cfa_connect )
1003                        #define _CFA_IO_FEATURE_IORING_OP_CONNECT ,
1004                        return IS_DEFINED(IORING_OP_CONNECT);
1005
1006                if( /*func == (fptr_t)fallocate || */
1007                        func == (fptr_t)cfa_fallocate )
1008                        #define _CFA_IO_FEATURE_IORING_OP_FALLOCATE ,
1009                        return IS_DEFINED(IORING_OP_FALLOCATE);
1010
1011                if( /*func == (fptr_t)posix_fadvise || */
1012                        func == (fptr_t)cfa_fadvise )
1013                        #define _CFA_IO_FEATURE_IORING_OP_FADVISE ,
1014                        return IS_DEFINED(IORING_OP_FADVISE);
1015
1016                if( /*func == (fptr_t)madvise || */
1017                        func == (fptr_t)cfa_madvise )
1018                        #define _CFA_IO_FEATURE_IORING_OP_MADVISE ,
1019                        return IS_DEFINED(IORING_OP_MADVISE);
1020
1021                if( /*func == (fptr_t)openat || */
1022                        func == (fptr_t)cfa_openat )
1023                        #define _CFA_IO_FEATURE_IORING_OP_OPENAT ,
1024                        return IS_DEFINED(IORING_OP_OPENAT);
1025
1026                if( /*func == (fptr_t)close || */
1027                        func == (fptr_t)cfa_close )
1028                        #define _CFA_IO_FEATURE_IORING_OP_CLOSE ,
1029                        return IS_DEFINED(IORING_OP_CLOSE);
1030
1031                if( /*func == (fptr_t)read || */
1032                        func == (fptr_t)cfa_read )
1033                        #define _CFA_IO_FEATURE_IORING_OP_READ ,
1034                        return IS_DEFINED(IORING_OP_READ);
1035
1036                if( /*func == (fptr_t)write || */
1037                        func == (fptr_t)cfa_write )
1038                        #define _CFA_IO_FEATURE_IORING_OP_WRITE ,
1039                        return IS_DEFINED(IORING_OP_WRITE);
1040        #endif
1041
1042        return false;
1043}
Note: See TracBrowser for help on using the repository browser.