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

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

Added the option to dynamically (at cluster creation time) enable/disable the user thread polling of I/O

  • 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                // Then loop until we need to start
525                while(!__atomic_load_n(&this.ring->done, __ATOMIC_SEQ_CST)) {
526                        // Drain the io
527                        this.waiting = false;
528                        int count = __drain_io( *this.ring, 0p, 0, false );
529
530                        // Update statistics
531                        #if !defined(__CFA_NO_STATISTICS__)
532                                this.ring->completion_q.stats.completed_avg.val += count;
533                                this.ring->completion_q.stats.completed_avg.fast_cnt += 1;
534                        #endif
535
536                        this.waiting = true;
537                        if(0 > count) {
538                                // If we got something, just yield and check again
539                                yield();
540                        }
541                        else {
542                                // We didn't get anything baton pass to the slow poller
543                                __cfadbg_print_safe(io_core, "Kernel I/O : Moving to ring %p to slow poller\n", &this.ring);
544                                post( this.ring->poller.sem );
545                                park( __cfaabi_dbg_ctx );
546                        }
547                }
548
549                __cfadbg_print_safe(io_core, "Kernel I/O : Fast poller for ring %p stopping\n", &this.ring);
550        }
551
552//=============================================================================================
553// I/O Submissions
554//=============================================================================================
555
556// Submition steps :
557// 1 - We need to make sure we don't overflow any of the buffer, P(ring.submit) to make sure
558//     entries are available. The semaphore make sure that there is no more operations in
559//     progress then the number of entries in the buffer. This probably limits concurrency
560//     more than necessary since submitted but not completed operations don't need any
561//     entries in user space. However, I don't know what happens if we overflow the buffers
562//     because too many requests completed at once. This is a safe approach in all cases.
563//     Furthermore, with hundreds of entries, this may be okay.
564//
565// 2 - Allocate a queue entry. The ring already has memory for all entries but only the ones
566//     listed in sq.array are visible by the kernel. For those not listed, the kernel does not
567//     offer any assurance that an entry is not being filled by multiple flags. Therefore, we
568//     need to write an allocator that allows allocating concurrently.
569//
570// 3 - Actually fill the submit entry, this is the only simple and straightforward step.
571//
572// 4 - Append the entry index to the array and adjust the tail accordingly. This operation
573//     needs to arrive to two concensus at the same time:
574//     A - The order in which entries are listed in the array: no two threads must pick the
575//         same index for their entries
576//     B - When can the tail be update for the kernel. EVERY entries in the array between
577//         head and tail must be fully filled and shouldn't ever be touched again.
578//
579
580        static inline [* struct io_uring_sqe, uint32_t] __submit_alloc( struct __io_data & ring ) {
581                // Wait for a spot to be available
582                P(ring.submit);
583
584                // Allocate the sqe
585                uint32_t idx = __atomic_fetch_add(&ring.submit_q.alloc, 1ul32, __ATOMIC_SEQ_CST);
586
587                // Validate that we didn't overflow anything
588                // Check that nothing overflowed
589                /* paranoid */ verify( true );
590
591                // Check that it goes head -> tail -> alloc and never head -> alloc -> tail
592                /* paranoid */ verify( true );
593
594                // Return the sqe
595                return [&ring.submit_q.sqes[ idx & (*ring.submit_q.mask)], idx];
596        }
597
598        static inline void __submit( struct __io_data & ring, uint32_t idx ) {
599                // get mutual exclusion
600                lock(ring.submit_q.lock __cfaabi_dbg_ctx2);
601
602                // Append to the list of ready entries
603                uint32_t * tail = ring.submit_q.tail;
604                const uint32_t mask = *ring.submit_q.mask;
605
606                ring.submit_q.array[ (*tail) & mask ] = idx & mask;
607                __atomic_fetch_add(tail, 1ul32, __ATOMIC_SEQ_CST);
608
609                // Submit however, many entries need to be submitted
610                int ret = syscall( __NR_io_uring_enter, ring.fd, 1, 0, 0, 0p, 0);
611                if( ret < 0 ) {
612                        switch((int)errno) {
613                        default:
614                                abort( "KERNEL ERROR: IO_URING SUBMIT - %s\n", strerror(errno) );
615                        }
616                }
617
618                // update statistics
619                #if !defined(__CFA_NO_STATISTICS__)
620                        ring.submit_q.stats.submit_avg.val += 1;
621                        ring.submit_q.stats.submit_avg.cnt += 1;
622                #endif
623
624                unlock(ring.submit_q.lock);
625                // Make sure that idx was submitted
626                // Be careful to not get false positive if we cycled the entire list or that someone else submitted for us
627                __cfadbg_print_safe( io, "Kernel I/O : Performed io_submit for %p, returned %d\n", active_thread(), ret );
628        }
629
630        static inline void ?{}(struct io_uring_sqe & this, uint8_t opcode, int fd) {
631                this.opcode = opcode;
632                #if !defined(IOSQE_ASYNC)
633                        this.flags = 0;
634                #else
635                        this.flags = IOSQE_ASYNC;
636                #endif
637                this.ioprio = 0;
638                this.fd = fd;
639                this.off = 0;
640                this.addr = 0;
641                this.len = 0;
642                this.rw_flags = 0;
643                this.__pad2[0] = this.__pad2[1] = this.__pad2[2] = 0;
644        }
645
646        static inline void ?{}(struct io_uring_sqe & this, uint8_t opcode, int fd, void * addr, uint32_t len, uint64_t off ) {
647                (this){ opcode, fd };
648                this.off = off;
649                this.addr = (uint64_t)addr;
650                this.len = len;
651        }
652
653
654//=============================================================================================
655// I/O Interface
656//=============================================================================================
657
658        #define __submit_prelude \
659                struct __io_data & ring = *active_cluster()->io; \
660                struct io_uring_sqe * sqe; \
661                uint32_t idx; \
662                [sqe, idx] = __submit_alloc( ring );
663
664        #define __submit_wait \
665                io_user_data data = { 0, active_thread() }; \
666                /*__cfaabi_bits_print_safe( STDERR_FILENO, "Preparing user data %p for %p\n", &data, data.thrd );*/ \
667                sqe->user_data = (uint64_t)&data; \
668                __submit( ring, idx ); \
669                park( __cfaabi_dbg_ctx ); \
670                return data.result;
671#endif
672
673// Some forward declarations
674extern "C" {
675        #include <unistd.h>
676        #include <sys/types.h>
677        #include <sys/socket.h>
678        #include <sys/syscall.h>
679        struct iovec;
680        extern ssize_t preadv2 (int fd, const struct iovec *iov, int iovcnt, off_t offset, int flags);
681        extern ssize_t pwritev2(int fd, const struct iovec *iov, int iovcnt, off_t offset, int flags);
682
683        extern int fsync(int fd);
684        extern int sync_file_range(int fd, int64_t offset, int64_t nbytes, unsigned int flags);
685
686        struct msghdr;
687        struct sockaddr;
688        extern ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags);
689        extern ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);
690        extern ssize_t send(int sockfd, const void *buf, size_t len, int flags);
691        extern ssize_t recv(int sockfd, void *buf, size_t len, int flags);
692        extern int accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags);
693        extern int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
694
695        extern int fallocate(int fd, int mode, uint64_t offset, uint64_t len);
696        extern int posix_fadvise(int fd, uint64_t offset, uint64_t len, int advice);
697        extern int madvise(void *addr, size_t length, int advice);
698
699        extern int openat(int dirfd, const char *pathname, int flags, mode_t mode);
700        extern int close(int fd);
701
702        extern ssize_t read (int fd, void *buf, size_t count);
703}
704
705//-----------------------------------------------------------------------------
706// Asynchronous operations
707ssize_t cfa_preadv2(int fd, const struct iovec *iov, int iovcnt, off_t offset, int flags) {
708        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_READV)
709                return preadv2(fd, iov, iovcnt, offset, flags);
710        #else
711                __submit_prelude
712
713                (*sqe){ IORING_OP_READV, fd, iov, iovcnt, offset };
714
715                __submit_wait
716        #endif
717}
718
719ssize_t cfa_pwritev2(int fd, const struct iovec *iov, int iovcnt, off_t offset, int flags) {
720        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_WRITEV)
721                return pwritev2(fd, iov, iovcnt, offset, flags);
722        #else
723                __submit_prelude
724
725                (*sqe){ IORING_OP_WRITEV, fd, iov, iovcnt, offset };
726
727                __submit_wait
728        #endif
729}
730
731int cfa_fsync(int fd) {
732        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_FSYNC)
733                return fsync(fd);
734        #else
735                __submit_prelude
736
737                (*sqe){ IORING_OP_FSYNC, fd };
738
739                __submit_wait
740        #endif
741}
742
743int cfa_sync_file_range(int fd, int64_t offset, int64_t nbytes, unsigned int flags) {
744        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_SYNC_FILE_RANGE)
745                return sync_file_range(fd, offset, nbytes, flags);
746        #else
747                __submit_prelude
748
749                (*sqe){ IORING_OP_SYNC_FILE_RANGE, fd };
750                sqe->off = offset;
751                sqe->len = nbytes;
752                sqe->sync_range_flags = flags;
753
754                __submit_wait
755        #endif
756}
757
758
759ssize_t cfa_sendmsg(int sockfd, const struct msghdr *msg, int flags) {
760        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_SENDMSG)
761                return sendmsg(sockfd, msg, flags);
762        #else
763                __submit_prelude
764
765                (*sqe){ IORING_OP_SENDMSG, sockfd, msg, 1, 0 };
766                sqe->msg_flags = flags;
767
768                __submit_wait
769        #endif
770}
771
772ssize_t cfa_recvmsg(int sockfd, struct msghdr *msg, int flags) {
773        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_RECVMSG)
774                return recvmsg(sockfd, msg, flags);
775        #else
776                __submit_prelude
777
778                (*sqe){ IORING_OP_RECVMSG, sockfd, msg, 1, 0 };
779                sqe->msg_flags = flags;
780
781                __submit_wait
782        #endif
783}
784
785ssize_t cfa_send(int sockfd, const void *buf, size_t len, int flags) {
786        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_SEND)
787                return send( sockfd, buf, len, flags );
788        #else
789                __submit_prelude
790
791                (*sqe){ IORING_OP_SEND, sockfd };
792                sqe->addr = (uint64_t)buf;
793                sqe->len = len;
794                sqe->msg_flags = flags;
795
796                __submit_wait
797        #endif
798}
799
800ssize_t cfa_recv(int sockfd, void *buf, size_t len, int flags) {
801        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_RECV)
802                return recv( sockfd, buf, len, flags );
803        #else
804                __submit_prelude
805
806                (*sqe){ IORING_OP_RECV, sockfd };
807                sqe->addr = (uint64_t)buf;
808                sqe->len = len;
809                sqe->msg_flags = flags;
810
811                __submit_wait
812        #endif
813}
814
815int cfa_accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags) {
816        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_ACCEPT)
817                return accept4( sockfd, addr, addrlen, flags );
818        #else
819                __submit_prelude
820
821                (*sqe){ IORING_OP_ACCEPT, sockfd };
822                sqe->addr = addr;
823                sqe->addr2 = addrlen;
824                sqe->accept_flags = flags;
825
826                __submit_wait
827        #endif
828}
829
830int cfa_connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
831        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_CONNECT)
832                return connect( sockfd, addr, addrlen );
833        #else
834                __submit_prelude
835
836                (*sqe){ IORING_OP_CONNECT, sockfd };
837                sqe->addr = (uint64_t)addr;
838                sqe->off = addrlen;
839
840                __submit_wait
841        #endif
842}
843
844int cfa_fallocate(int fd, int mode, uint64_t offset, uint64_t len) {
845        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_FALLOCATE)
846                return fallocate( fd, mode, offset, len );
847        #else
848                __submit_prelude
849
850                (*sqe){ IORING_OP_FALLOCATE, fd };
851                sqe->off = offset;
852                sqe->len = length;
853                sqe->mode = mode;
854
855                __submit_wait
856        #endif
857}
858
859int cfa_fadvise(int fd, uint64_t offset, uint64_t len, int advice) {
860        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_FADVISE)
861                return posix_fadvise( fd, offset, len, advice );
862        #else
863                __submit_prelude
864
865                (*sqe){ IORING_OP_FADVISE, fd };
866                sqe->off = (uint64_t)offset;
867                sqe->len = length;
868                sqe->fadvise_advice = advice;
869
870                __submit_wait
871        #endif
872}
873
874int cfa_madvise(void *addr, size_t length, int advice) {
875        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_MADVISE)
876                return madvise( addr, length, advice );
877        #else
878                __submit_prelude
879
880                (*sqe){ IORING_OP_MADVISE, 0 };
881                sqe->addr = (uint64_t)addr;
882                sqe->len = length;
883                sqe->fadvise_advice = advice;
884
885                __submit_wait
886        #endif
887}
888
889int cfa_openat(int dirfd, const char *pathname, int flags, mode_t mode) {
890        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_OPENAT)
891                return openat( dirfd, pathname, flags, mode );
892        #else
893                __submit_prelude
894
895                (*sqe){ IORING_OP_OPENAT, dirfd };
896                sqe->addr = (uint64_t)pathname;
897                sqe->open_flags = flags;
898                sqe->mode = mode;
899
900                __submit_wait
901        #endif
902}
903
904int cfa_close(int fd) {
905        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_CLOSE)
906                return close( fd );
907        #else
908                __submit_prelude
909
910                (*sqe){ IORING_OP_CLOSE, fd };
911
912                __submit_wait
913        #endif
914}
915
916
917ssize_t cfa_read(int fd, void *buf, size_t count) {
918        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_READ)
919                return read( fd, buf, count );
920        #else
921                __submit_prelude
922
923                (*sqe){ IORING_OP_READ, fd, buf, count, 0 };
924
925                __submit_wait
926        #endif
927}
928
929ssize_t cfa_write(int fd, void *buf, size_t count) {
930        #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_WRITE)
931                return read( fd, buf, count );
932        #else
933                __submit_prelude
934
935                (*sqe){ IORING_OP_WRITE, fd, buf, count, 0 };
936
937                __submit_wait
938        #endif
939}
940
941//-----------------------------------------------------------------------------
942// Check if a function is asynchronous
943
944// Macro magic to reduce the size of the following switch case
945#define IS_DEFINED_APPLY(f, ...) f(__VA_ARGS__)
946#define IS_DEFINED_SECOND(first, second, ...) second
947#define IS_DEFINED_TEST(expansion) _CFA_IO_FEATURE_##expansion
948#define IS_DEFINED(macro) IS_DEFINED_APPLY( IS_DEFINED_SECOND,IS_DEFINED_TEST(macro) false, true)
949
950bool has_user_level_blocking( fptr_t func ) {
951        #if defined(HAVE_LINUX_IO_URING_H)
952                if( /*func == (fptr_t)preadv2 || */
953                        func == (fptr_t)cfa_preadv2 )
954                        #define _CFA_IO_FEATURE_IORING_OP_READV ,
955                        return IS_DEFINED(IORING_OP_READV);
956
957                if( /*func == (fptr_t)pwritev2 || */
958                        func == (fptr_t)cfa_pwritev2 )
959                        #define _CFA_IO_FEATURE_IORING_OP_WRITEV ,
960                        return IS_DEFINED(IORING_OP_WRITEV);
961
962                if( /*func == (fptr_t)fsync || */
963                        func == (fptr_t)cfa_fsync )
964                        #define _CFA_IO_FEATURE_IORING_OP_FSYNC ,
965                        return IS_DEFINED(IORING_OP_FSYNC);
966
967                if( /*func == (fptr_t)ync_file_range || */
968                        func == (fptr_t)cfa_sync_file_range )
969                        #define _CFA_IO_FEATURE_IORING_OP_SYNC_FILE_RANGE ,
970                        return IS_DEFINED(IORING_OP_SYNC_FILE_RANGE);
971
972                if( /*func == (fptr_t)sendmsg || */
973                        func == (fptr_t)cfa_sendmsg )
974                        #define _CFA_IO_FEATURE_IORING_OP_SENDMSG ,
975                        return IS_DEFINED(IORING_OP_SENDMSG);
976
977                if( /*func == (fptr_t)recvmsg || */
978                        func == (fptr_t)cfa_recvmsg )
979                        #define _CFA_IO_FEATURE_IORING_OP_RECVMSG ,
980                        return IS_DEFINED(IORING_OP_RECVMSG);
981
982                if( /*func == (fptr_t)send || */
983                        func == (fptr_t)cfa_send )
984                        #define _CFA_IO_FEATURE_IORING_OP_SEND ,
985                        return IS_DEFINED(IORING_OP_SEND);
986
987                if( /*func == (fptr_t)recv || */
988                        func == (fptr_t)cfa_recv )
989                        #define _CFA_IO_FEATURE_IORING_OP_RECV ,
990                        return IS_DEFINED(IORING_OP_RECV);
991
992                if( /*func == (fptr_t)accept4 || */
993                        func == (fptr_t)cfa_accept4 )
994                        #define _CFA_IO_FEATURE_IORING_OP_ACCEPT ,
995                        return IS_DEFINED(IORING_OP_ACCEPT);
996
997                if( /*func == (fptr_t)connect || */
998                        func == (fptr_t)cfa_connect )
999                        #define _CFA_IO_FEATURE_IORING_OP_CONNECT ,
1000                        return IS_DEFINED(IORING_OP_CONNECT);
1001
1002                if( /*func == (fptr_t)fallocate || */
1003                        func == (fptr_t)cfa_fallocate )
1004                        #define _CFA_IO_FEATURE_IORING_OP_FALLOCATE ,
1005                        return IS_DEFINED(IORING_OP_FALLOCATE);
1006
1007                if( /*func == (fptr_t)posix_fadvise || */
1008                        func == (fptr_t)cfa_fadvise )
1009                        #define _CFA_IO_FEATURE_IORING_OP_FADVISE ,
1010                        return IS_DEFINED(IORING_OP_FADVISE);
1011
1012                if( /*func == (fptr_t)madvise || */
1013                        func == (fptr_t)cfa_madvise )
1014                        #define _CFA_IO_FEATURE_IORING_OP_MADVISE ,
1015                        return IS_DEFINED(IORING_OP_MADVISE);
1016
1017                if( /*func == (fptr_t)openat || */
1018                        func == (fptr_t)cfa_openat )
1019                        #define _CFA_IO_FEATURE_IORING_OP_OPENAT ,
1020                        return IS_DEFINED(IORING_OP_OPENAT);
1021
1022                if( /*func == (fptr_t)close || */
1023                        func == (fptr_t)cfa_close )
1024                        #define _CFA_IO_FEATURE_IORING_OP_CLOSE ,
1025                        return IS_DEFINED(IORING_OP_CLOSE);
1026
1027                if( /*func == (fptr_t)read || */
1028                        func == (fptr_t)cfa_read )
1029                        #define _CFA_IO_FEATURE_IORING_OP_READ ,
1030                        return IS_DEFINED(IORING_OP_READ);
1031
1032                if( /*func == (fptr_t)write || */
1033                        func == (fptr_t)cfa_write )
1034                        #define _CFA_IO_FEATURE_IORING_OP_WRITE ,
1035                        return IS_DEFINED(IORING_OP_WRITE);
1036        #endif
1037
1038        return false;
1039}
Note: See TracBrowser for help on using the repository browser.