// // Cforall Version 1.0.0 Copyright (C) 2020 University of Waterloo // // The contents of this file are covered under the licence agreement in the // file "LICENCE" distributed with Cforall. // // io.cfa -- // // Author : Thierry Delisle // Created On : Thu Apr 23 17:31:00 2020 // Last Modified By : // Last Modified On : // Update Count : // // #define __CFA_DEBUG_PRINT_IO__ // #define __CFA_DEBUG_PRINT_IO_CORE__ #include "kernel.hfa" #include "bitmanip.hfa" #if !defined(HAVE_LINUX_IO_URING_H) void __kernel_io_startup( cluster &, unsigned, bool ) { // Nothing to do without io_uring } void __kernel_io_finish_start( cluster & ) { // Nothing to do without io_uring } void __kernel_io_prepare_stop( cluster & ) { // Nothing to do without io_uring } void __kernel_io_shutdown( cluster &, bool ) { // Nothing to do without io_uring } #else extern "C" { #define _GNU_SOURCE /* See feature_test_macros(7) */ #include #include #include #include #include #include #include } #include "bits/signal.hfa" #include "kernel_private.hfa" #include "thread.hfa" uint32_t entries_per_cluster() { return 256; } static void * __io_poller_slow( void * arg ); // Weirdly, some systems that do support io_uring don't actually define these #ifdef __alpha__ /* * alpha is the only exception, all other architectures * have common numbers for new system calls. */ #ifndef __NR_io_uring_setup #define __NR_io_uring_setup 535 #endif #ifndef __NR_io_uring_enter #define __NR_io_uring_enter 536 #endif #ifndef __NR_io_uring_register #define __NR_io_uring_register 537 #endif #else /* !__alpha__ */ #ifndef __NR_io_uring_setup #define __NR_io_uring_setup 425 #endif #ifndef __NR_io_uring_enter #define __NR_io_uring_enter 426 #endif #ifndef __NR_io_uring_register #define __NR_io_uring_register 427 #endif #endif // Fast poller user-thread // Not using the "thread" keyword because we want to control // more carefully when to start/stop it struct __io_poller_fast { struct __io_data * ring; $thread thrd; }; void ?{}( __io_poller_fast & this, struct cluster & cltr ) { this.ring = cltr.io; (this.thrd){ "Fast I/O Poller", cltr }; } void ^?{}( __io_poller_fast & mutex this ); void main( __io_poller_fast & this ); static inline $thread * get_thread( __io_poller_fast & this ) { return &this.thrd; } void ^?{}( __io_poller_fast & mutex this ) {} struct __submition_data { // Head and tail of the ring (associated with array) volatile uint32_t * head; volatile uint32_t * tail; // The actual kernel ring which uses head/tail // indexes into the sqes arrays uint32_t * array; // number of entries and mask to go with it const uint32_t * num; const uint32_t * mask; // Submission flags (Not sure what for) uint32_t * flags; // number of sqes not submitted (whatever that means) uint32_t * dropped; // Like head/tail but not seen by the kernel volatile uint32_t * ready; uint32_t ready_cnt; __spinlock_t lock; // A buffer of sqes (not the actual ring) struct io_uring_sqe * sqes; // The location and size of the mmaped area void * ring_ptr; size_t ring_sz; }; struct __completion_data { // Head and tail of the ring volatile uint32_t * head; volatile uint32_t * tail; // number of entries and mask to go with it const uint32_t * mask; const uint32_t * num; // number of cqes not submitted (whatever that means) uint32_t * overflow; // the kernel ring struct io_uring_cqe * cqes; // The location and size of the mmaped area void * ring_ptr; size_t ring_sz; }; struct __io_data { struct __submition_data submit_q; struct __completion_data completion_q; uint32_t ring_flags; int cltr_flags; int fd; semaphore submit; volatile bool done; struct { struct { void * stack; pthread_t kthrd; volatile bool blocked; } slow; __io_poller_fast fast; __bin_sem_t sem; } poller; }; //============================================================================================= // I/O Startup / Shutdown logic //============================================================================================= void __kernel_io_startup( cluster & this, unsigned io_flags, bool main_cluster ) { this.io = malloc(); // Step 1 : call to setup struct io_uring_params params; memset(¶ms, 0, sizeof(params)); uint32_t nentries = entries_per_cluster(); int fd = syscall(__NR_io_uring_setup, nentries, ¶ms ); if(fd < 0) { abort("KERNEL ERROR: IO_URING SETUP - %s\n", strerror(errno)); } // Step 2 : mmap result memset( this.io, 0, sizeof(struct __io_data) ); struct __submition_data & sq = this.io->submit_q; struct __completion_data & cq = this.io->completion_q; // calculate the right ring size sq.ring_sz = params.sq_off.array + (params.sq_entries * sizeof(unsigned) ); cq.ring_sz = params.cq_off.cqes + (params.cq_entries * sizeof(struct io_uring_cqe)); // Requires features #if defined(IORING_FEAT_SINGLE_MMAP) // adjust the size according to the parameters if ((params.features & IORING_FEAT_SINGLE_MMAP) != 0) { cq->ring_sz = sq->ring_sz = max(cq->ring_sz, sq->ring_sz); } #endif // mmap the Submit Queue into existence sq.ring_ptr = mmap(0, sq.ring_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_SQ_RING); if (sq.ring_ptr == (void*)MAP_FAILED) { abort("KERNEL ERROR: IO_URING MMAP1 - %s\n", strerror(errno)); } // Requires features #if defined(IORING_FEAT_SINGLE_MMAP) // mmap the Completion Queue into existence (may or may not be needed) if ((params.features & IORING_FEAT_SINGLE_MMAP) != 0) { cq->ring_ptr = sq->ring_ptr; } else #endif { // We need multiple call to MMAP cq.ring_ptr = mmap(0, cq.ring_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_CQ_RING); if (cq.ring_ptr == (void*)MAP_FAILED) { munmap(sq.ring_ptr, sq.ring_sz); abort("KERNEL ERROR: IO_URING MMAP2 - %s\n", strerror(errno)); } } // mmap the submit queue entries size_t size = params.sq_entries * sizeof(struct io_uring_sqe); sq.sqes = (struct io_uring_sqe *)mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_SQES); if (sq.sqes == (struct io_uring_sqe *)MAP_FAILED) { munmap(sq.ring_ptr, sq.ring_sz); if (cq.ring_ptr != sq.ring_ptr) munmap(cq.ring_ptr, cq.ring_sz); abort("KERNEL ERROR: IO_URING MMAP3 - %s\n", strerror(errno)); } // Get the pointers from the kernel to fill the structure // submit queue sq.head = (volatile uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.head); sq.tail = (volatile uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.tail); sq.mask = ( const uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.ring_mask); sq.num = ( const uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.ring_entries); sq.flags = ( uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.flags); sq.dropped = ( uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.dropped); sq.array = ( uint32_t *)(((intptr_t)sq.ring_ptr) + params.sq_off.array); { const uint32_t num = *sq.num; for( i; num ) { sq.sqes[i].user_data = 0ul64; } } if( io_flags & CFA_CLUSTER_IO_POLLER_THREAD_SUBMITS ) { /* paranoid */ verify( is_pow2( io_flags >> CFA_CLUSTER_IO_BUFFLEN_OFFSET ) || ((io_flags >> CFA_CLUSTER_IO_BUFFLEN_OFFSET) < 8) ); sq.ready_cnt = max(io_flags >> CFA_CLUSTER_IO_BUFFLEN_OFFSET, 8); sq.ready = alloc_align( 64, sq.ready_cnt ); for(i; sq.ready_cnt) { sq.ready[i] = -1ul32; } } else { sq.ready_cnt = 0; sq.ready = 0p; } // completion queue cq.head = (volatile uint32_t *)(((intptr_t)cq.ring_ptr) + params.cq_off.head); cq.tail = (volatile uint32_t *)(((intptr_t)cq.ring_ptr) + params.cq_off.tail); cq.mask = ( const uint32_t *)(((intptr_t)cq.ring_ptr) + params.cq_off.ring_mask); cq.num = ( const uint32_t *)(((intptr_t)cq.ring_ptr) + params.cq_off.ring_entries); cq.overflow = ( uint32_t *)(((intptr_t)cq.ring_ptr) + params.cq_off.overflow); cq.cqes = (struct io_uring_cqe *)(((intptr_t)cq.ring_ptr) + params.cq_off.cqes); // some paranoid checks /* 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 ); /* paranoid */ verifyf( (*cq.num) >= nentries, "IO_URING Expected %u entries, got %u", nentries, *cq.num ); /* paranoid */ verifyf( (*cq.head) == 0, "IO_URING Expected head to be 0, got %u", *cq.head ); /* paranoid */ verifyf( (*cq.tail) == 0, "IO_URING Expected tail to be 0, got %u", *cq.tail ); /* 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 ); /* paranoid */ verifyf( (*sq.num) >= nentries, "IO_URING Expected %u entries, got %u", nentries, *sq.num ); /* paranoid */ verifyf( (*sq.head) == 0, "IO_URING Expected head to be 0, got %u", *sq.head ); /* paranoid */ verifyf( (*sq.tail) == 0, "IO_URING Expected tail to be 0, got %u", *sq.tail ); // Update the global ring info this.io->ring_flags = params.flags; this.io->cltr_flags = io_flags; this.io->fd = fd; this.io->done = false; (this.io->submit){ min(*sq.num, *cq.num) }; if(!main_cluster) { __kernel_io_finish_start( this ); } } void __kernel_io_finish_start( cluster & this ) { if( this.io->cltr_flags & CFA_CLUSTER_IO_POLLER_USER_THREAD ) { __cfadbg_print_safe(io_core, "Kernel I/O : Creating fast poller for cluter %p\n", &this); (this.io->poller.fast){ this }; __thrd_start( this.io->poller.fast, main ); } // Create the poller thread __cfadbg_print_safe(io_core, "Kernel I/O : Creating slow poller for cluter %p\n", &this); this.io->poller.slow.blocked = false; this.io->poller.slow.stack = __create_pthread( &this.io->poller.slow.kthrd, __io_poller_slow, &this ); } void __kernel_io_prepare_stop( cluster & this ) { __cfadbg_print_safe(io_core, "Kernel I/O : Stopping pollers for cluster\n", &this); // Notify the poller thread of the shutdown __atomic_store_n(&this.io->done, true, __ATOMIC_SEQ_CST); // Stop the IO Poller sigval val = { 1 }; pthread_sigqueue( this.io->poller.slow.kthrd, SIGUSR1, val ); post( this.io->poller.sem ); // Wait for the poller thread to finish pthread_join( this.io->poller.slow.kthrd, 0p ); free( this.io->poller.slow.stack ); __cfadbg_print_safe(io_core, "Kernel I/O : Slow poller stopped for cluster\n", &this); if( this.io->cltr_flags & CFA_CLUSTER_IO_POLLER_USER_THREAD ) { with( this.io->poller.fast ) { /* paranoid */ verify( this.procs.head == 0p || &this == mainCluster ); /* paranoid */ verify( this.idles.head == 0p || &this == mainCluster ); // We need to adjust the clean-up based on where the thread is if( thrd.state == Ready || thrd.preempted != __NO_PREEMPTION ) { // This is the tricky case // The thread was preempted and now it is on the ready queue /* paranoid */ verify( thrd.next != 0p ); // The thread should be the last on the list /* paranoid */ verify( this.ready_queue.head == &thrd ); // The thread should be the only thing on the list // Remove the thread from the ready queue of this cluster this.ready_queue.head = 1p; thrd.next = 0p; __cfaabi_dbg_debug_do( thrd.unpark_stale = true ); // Fixup the thread state thrd.state = Blocked; thrd.preempted = __NO_PREEMPTION; // Pretend like the thread was blocked all along } // !!! This is not an else if !!! if( thrd.state == Blocked ) { // This is the "easy case" // The thread is parked and can easily be moved to active cluster verify( thrd.curr_cluster != active_cluster() || thrd.curr_cluster == mainCluster ); thrd.curr_cluster = active_cluster(); // unpark the fast io_poller unpark( &thrd __cfaabi_dbg_ctx2 ); } else { // The thread is in a weird state // I don't know what to do here abort("Fast poller thread is in unexpected state, cannot clean-up correctly\n"); } } ^(this.io->poller.fast){}; __cfadbg_print_safe(io_core, "Kernel I/O : Fast poller stopped for cluster\n", &this); } } void __kernel_io_shutdown( cluster & this, bool main_cluster ) { if(!main_cluster) { __kernel_io_prepare_stop( this ); } // Shutdown the io rings struct __submition_data & sq = this.io->submit_q; struct __completion_data & cq = this.io->completion_q; // unmap the submit queue entries munmap(sq.sqes, (*sq.num) * sizeof(struct io_uring_sqe)); // unmap the Submit Queue ring munmap(sq.ring_ptr, sq.ring_sz); // unmap the Completion Queue ring, if it is different if (cq.ring_ptr != sq.ring_ptr) { munmap(cq.ring_ptr, cq.ring_sz); } // close the file descriptor close(this.io->fd); free( this.io->submit_q.ready ); // Maybe null, doesn't matter free( this.io ); } //============================================================================================= // I/O Polling //============================================================================================= struct io_user_data { int32_t result; $thread * thrd; }; // Process a single completion message from the io_uring // This is NOT thread-safe static [int, bool] __drain_io( & struct __io_data ring, * sigset_t mask, int waitcnt, bool in_kernel ) { unsigned to_submit = 0; if( ring.cltr_flags & CFA_CLUSTER_IO_POLLER_THREAD_SUBMITS ) { // If the poller thread also submits, then we need to aggregate the submissions which are ready uint32_t tail = *ring.submit_q.tail; const uint32_t mask = *ring.submit_q.mask; // Go through the list of ready submissions for( i; ring.submit_q.ready_cnt ) { // replace any submission with the sentinel, to consume it. uint32_t idx = __atomic_exchange_n( &ring.submit_q.ready[i], -1ul32, __ATOMIC_RELAXED); // If it was already the sentinel, then we are done if( idx == -1ul32 ) continue; // If we got a real submission, append it to the list ring.submit_q.array[ (tail + to_submit) & mask ] = idx & mask; to_submit++; } // Increment the tail based on how many we are ready to submit __atomic_fetch_add(ring.submit_q.tail, to_submit, __ATOMIC_SEQ_CST); } const uint32_t smask = *ring.submit_q.mask; uint32_t shead = *ring.submit_q.head; int ret = syscall( __NR_io_uring_enter, ring.fd, to_submit, waitcnt, IORING_ENTER_GETEVENTS, mask, _NSIG / 8); if( ret < 0 ) { switch((int)errno) { case EAGAIN: case EINTR: return -EAGAIN; default: abort( "KERNEL ERROR: IO_URING WAIT - %s\n", strerror(errno) ); } } verify( (shead + ret) == *ring.submit_q.head ); // Release the consumed SQEs for( i; ret ) { uint32_t idx = ring.submit_q.array[ (i + shead) & smask ]; ring.submit_q.sqes[ idx ].user_data = 0; } uint32_t avail = 0; uint32_t sqe_num = *ring.submit_q.num; for(i; sqe_num) { if( ring.submit_q.sqes[ i ].user_data == 0 ) avail++; } // update statistics #if !defined(__CFA_NO_STATISTICS__) __tls_stats()->io.submit_q.stats.submit_avg.rdy += to_submit; __tls_stats()->io.submit_q.stats.submit_avg.csm += ret; __tls_stats()->io.submit_q.stats.submit_avg.avl += avail; __tls_stats()->io.submit_q.stats.submit_avg.cnt += 1; #endif // Drain the queue unsigned head = *ring.completion_q.head; unsigned tail = *ring.completion_q.tail; const uint32_t mask = *ring.completion_q.mask; // Memory barrier __atomic_thread_fence( __ATOMIC_SEQ_CST ); // Nothing was new return 0 if (head == tail) { return 0; } uint32_t count = tail - head; for(i; count) { unsigned idx = (head + i) & mask; struct io_uring_cqe & cqe = ring.completion_q.cqes[idx]; /* paranoid */ verify(&cqe); struct io_user_data * data = (struct io_user_data *)cqe.user_data; __cfadbg_print_safe( io, "Kernel I/O : Performed reading io cqe %p, result %d for %p\n", data, cqe.res, data->thrd ); data->result = cqe.res; if(!in_kernel) { unpark( data->thrd __cfaabi_dbg_ctx2 ); } else { __unpark( data->thrd __cfaabi_dbg_ctx2 ); } } // Allow new submissions to happen // V(ring.submit, count); // Mark to the kernel that the cqe has been seen // Ensure that the kernel only sees the new value of the head index after the CQEs have been read. __atomic_thread_fence( __ATOMIC_SEQ_CST ); __atomic_fetch_add( ring.completion_q.head, count, __ATOMIC_RELAXED ); return [count, count > 0 || to_submit > 0]; } static void * __io_poller_slow( void * arg ) { cluster * cltr = (cluster *)arg; struct __io_data & ring = *cltr->io; sigset_t mask; sigfillset(&mask); if ( pthread_sigmask( SIG_BLOCK, &mask, 0p ) == -1 ) { abort( "KERNEL ERROR: IO_URING - pthread_sigmask" ); } sigdelset( &mask, SIGUSR1 ); verify( (*ring.submit_q.head) == (*ring.submit_q.tail) ); verify( (*ring.completion_q.head) == (*ring.completion_q.tail) ); __cfadbg_print_safe(io_core, "Kernel I/O : Slow poller for ring %p ready\n", &ring); if( ring.cltr_flags & CFA_CLUSTER_IO_POLLER_USER_THREAD ) { while(!__atomic_load_n(&ring.done, __ATOMIC_SEQ_CST)) { __atomic_store_n( &ring.poller.slow.blocked, true, __ATOMIC_SEQ_CST ); // In the user-thread approach drain and if anything was drained, // batton pass to the user-thread int count; bool again; [count, again] = __drain_io( ring, &mask, 1, true ); __atomic_store_n( &ring.poller.slow.blocked, false, __ATOMIC_SEQ_CST ); // Update statistics #if !defined(__CFA_NO_STATISTICS__) __tls_stats()->io.complete_q.stats.completed_avg.val += count; __tls_stats()->io.complete_q.stats.completed_avg.slow_cnt += 1; #endif if(again) { __cfadbg_print_safe(io_core, "Kernel I/O : Moving to ring %p to fast poller\n", &ring); __unpark( &ring.poller.fast.thrd __cfaabi_dbg_ctx2 ); wait( ring.poller.sem ); } } } else { while(!__atomic_load_n(&ring.done, __ATOMIC_SEQ_CST)) { //In the naive approach, just poll the io completion queue directly int count; bool again; [count, again] = __drain_io( ring, &mask, 1, true ); // Update statistics #if !defined(__CFA_NO_STATISTICS__) __tls_stats()->io.complete_q.stats.completed_avg.val += count; __tls_stats()->io.complete_q.stats.completed_avg.slow_cnt += 1; #endif } } __cfadbg_print_safe(io_core, "Kernel I/O : Slow poller for ring %p stopping\n", &ring); return 0p; } void main( __io_poller_fast & this ) { verify( this.ring->cltr_flags & CFA_CLUSTER_IO_POLLER_USER_THREAD ); // Start parked park( __cfaabi_dbg_ctx ); __cfadbg_print_safe(io_core, "Kernel I/O : Fast poller for ring %p ready\n", &this.ring); int reset = 0; // Then loop until we need to start while(!__atomic_load_n(&this.ring->done, __ATOMIC_SEQ_CST)) { // Drain the io int count; bool again; [count, again] = __drain_io( *this.ring, 0p, 0, false ); if(!again) reset++; // Update statistics #if !defined(__CFA_NO_STATISTICS__) __tls_stats()->io.complete_q.stats.completed_avg.val += count; __tls_stats()->io.complete_q.stats.completed_avg.fast_cnt += 1; #endif // If we got something, just yield and check again if(reset < 5) { yield(); } // We didn't get anything baton pass to the slow poller else { __cfadbg_print_safe(io_core, "Kernel I/O : Moving to ring %p to slow poller\n", &this.ring); reset = 0; // wake up the slow poller post( this.ring->poller.sem ); // park this thread park( __cfaabi_dbg_ctx ); } } __cfadbg_print_safe(io_core, "Kernel I/O : Fast poller for ring %p stopping\n", &this.ring); } static inline void __wake_poller( struct __io_data & ring ) __attribute__((artificial)); static inline void __wake_poller( struct __io_data & ring ) { if(!__atomic_load_n( &ring.poller.slow.blocked, __ATOMIC_SEQ_CST)) return; sigval val = { 1 }; pthread_sigqueue( ring.poller.slow.kthrd, SIGUSR1, val ); } //============================================================================================= // I/O Submissions //============================================================================================= // Submition steps : // 1 - We need to make sure we don't overflow any of the buffer, P(ring.submit) to make sure // entries are available. The semaphore make sure that there is no more operations in // progress then the number of entries in the buffer. This probably limits concurrency // more than necessary since submitted but not completed operations don't need any // entries in user space. However, I don't know what happens if we overflow the buffers // because too many requests completed at once. This is a safe approach in all cases. // Furthermore, with hundreds of entries, this may be okay. // // 2 - Allocate a queue entry. The ring already has memory for all entries but only the ones // listed in sq.array are visible by the kernel. For those not listed, the kernel does not // offer any assurance that an entry is not being filled by multiple flags. Therefore, we // need to write an allocator that allows allocating concurrently. // // 3 - Actually fill the submit entry, this is the only simple and straightforward step. // // 4 - Append the entry index to the array and adjust the tail accordingly. This operation // needs to arrive to two concensus at the same time: // A - The order in which entries are listed in the array: no two threads must pick the // same index for their entries // B - When can the tail be update for the kernel. EVERY entries in the array between // head and tail must be fully filled and shouldn't ever be touched again. // static inline [* struct io_uring_sqe, uint32_t] __submit_alloc( struct __io_data & ring, uint64_t data ) { verify( data != 0 ); // Prepare the data we need __attribute((unused)) int len = 0; __attribute((unused)) int block = 0; uint32_t cnt = *ring.submit_q.num; uint32_t mask = *ring.submit_q.mask; uint32_t off = __tls_rand(); // Loop around looking for an available spot LOOKING: for() { // Look through the list starting at some offset for(i; cnt) { uint64_t expected = 0; uint32_t idx = (i + off) & mask; struct io_uring_sqe * sqe = &ring.submit_q.sqes[idx]; volatile uint64_t * udata = &sqe->user_data; if( *udata == expected && __atomic_compare_exchange_n( udata, &expected, data, true, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED ) ) { // update statistics #if !defined(__CFA_NO_STATISTICS__) __tls_stats()->io.submit_q.stats.alloc_avg.val += len; __tls_stats()->io.submit_q.stats.alloc_avg.block += block; __tls_stats()->io.submit_q.stats.alloc_avg.cnt += 1; #endif // Success return the data return [sqe, idx]; } verify(expected != data); len ++; } block++; yield(); } } static inline void __submit( struct __io_data & ring, uint32_t idx ) { // Get now the data we definetely need uint32_t * const tail = ring.submit_q.tail; const uint32_t mask = *ring.submit_q.mask; // There are 2 submission schemes, check which one we are using if( ring.cltr_flags & CFA_CLUSTER_IO_POLLER_THREAD_SUBMITS ) { // If the poller thread submits, then we just need to add this to the ready array /* paranoid */ verify( idx <= mask ); /* paranoid */ verify( idx != -1ul32 ); // We need to find a spot in the ready array __attribute((unused)) int len = 0; __attribute((unused)) int block = 0; uint32_t ready_mask = ring.submit_q.ready_cnt - 1; uint32_t off = __tls_rand(); LOOKING: for() { for(i; ring.submit_q.ready_cnt) { uint32_t ii = (i + off) & ready_mask; uint32_t expected = -1ul32; if( __atomic_compare_exchange_n( &ring.submit_q.ready[ii], &expected, idx, true, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED ) ) { break LOOKING; } verify(expected != idx); len ++; } block++; yield(); } __wake_poller( ring ); // update statistics #if !defined(__CFA_NO_STATISTICS__) __tls_stats()->io.submit_q.stats.look_avg.val += len; __tls_stats()->io.submit_q.stats.look_avg.block += block; __tls_stats()->io.submit_q.stats.look_avg.cnt += 1; #endif __cfadbg_print_safe( io, "Kernel I/O : Added %u to ready for %p\n", idx, active_thread() ); } else { // get mutual exclusion lock(ring.submit_q.lock __cfaabi_dbg_ctx2); // Append to the list of ready entries /* paranoid */ verify( idx <= mask ); ring.submit_q.array[ (*tail) & mask ] = idx & mask; __atomic_fetch_add(tail, 1ul32, __ATOMIC_SEQ_CST); // Submit however, many entries need to be submitted int ret = syscall( __NR_io_uring_enter, ring.fd, 1, 0, 0, 0p, 0); if( ret < 0 ) { switch((int)errno) { default: abort( "KERNEL ERROR: IO_URING SUBMIT - %s\n", strerror(errno) ); } } // update statistics #if !defined(__CFA_NO_STATISTICS__) __tls_stats()->io.submit_q.stats.submit_avg.csm += 1; __tls_stats()->io.submit_q.stats.submit_avg.cnt += 1; #endif unlock(ring.submit_q.lock); __cfadbg_print_safe( io, "Kernel I/O : Performed io_submit for %p, returned %d\n", active_thread(), ret ); } } static inline void ?{}(struct io_uring_sqe & this, uint8_t opcode, int fd) { this.opcode = opcode; #if !defined(IOSQE_ASYNC) this.flags = 0; #else this.flags = IOSQE_ASYNC; #endif this.ioprio = 0; this.fd = fd; this.off = 0; this.addr = 0; this.len = 0; this.rw_flags = 0; this.__pad2[0] = this.__pad2[1] = this.__pad2[2] = 0; } static inline void ?{}(struct io_uring_sqe & this, uint8_t opcode, int fd, void * addr, uint32_t len, uint64_t off ) { (this){ opcode, fd }; this.off = off; this.addr = (uint64_t)addr; this.len = len; } //============================================================================================= // I/O Interface //============================================================================================= #define __submit_prelude \ io_user_data data = { 0, active_thread() }; \ struct __io_data & ring = *data.thrd->curr_cluster->io; \ struct io_uring_sqe * sqe; \ uint32_t idx; \ [sqe, idx] = __submit_alloc( ring, (uint64_t)&data ); #define __submit_wait \ /*__cfaabi_bits_print_safe( STDERR_FILENO, "Preparing user data %p for %p\n", &data, data.thrd );*/ \ verify( sqe->user_data == (uint64_t)&data ); \ __submit( ring, idx ); \ park( __cfaabi_dbg_ctx ); \ return data.result; #endif // Some forward declarations extern "C" { #include #include #include #include #if defined(HAVE_PREADV2) struct iovec; extern ssize_t preadv2 (int fd, const struct iovec *iov, int iovcnt, off_t offset, int flags); #endif #if defined(HAVE_PWRITEV2) struct iovec; extern ssize_t pwritev2(int fd, const struct iovec *iov, int iovcnt, off_t offset, int flags); #endif extern int fsync(int fd); extern int sync_file_range(int fd, int64_t offset, int64_t nbytes, unsigned int flags); struct msghdr; struct sockaddr; extern ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags); extern ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags); extern ssize_t send(int sockfd, const void *buf, size_t len, int flags); extern ssize_t recv(int sockfd, void *buf, size_t len, int flags); extern int accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags); extern int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen); extern int fallocate(int fd, int mode, uint64_t offset, uint64_t len); extern int posix_fadvise(int fd, uint64_t offset, uint64_t len, int advice); extern int madvise(void *addr, size_t length, int advice); extern int openat(int dirfd, const char *pathname, int flags, mode_t mode); extern int close(int fd); extern ssize_t read (int fd, void *buf, size_t count); } //----------------------------------------------------------------------------- // Asynchronous operations #if defined(HAVE_PREADV2) ssize_t cfa_preadv2(int fd, const struct iovec *iov, int iovcnt, off_t offset, int flags) { #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_READV) return preadv2(fd, iov, iovcnt, offset, flags); #else __submit_prelude (*sqe){ IORING_OP_READV, fd, iov, iovcnt, offset }; __submit_wait #endif } #endif #if defined(HAVE_PWRITEV2) ssize_t cfa_pwritev2(int fd, const struct iovec *iov, int iovcnt, off_t offset, int flags) { #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_WRITEV) return pwritev2(fd, iov, iovcnt, offset, flags); #else __submit_prelude (*sqe){ IORING_OP_WRITEV, fd, iov, iovcnt, offset }; __submit_wait #endif } #endif int cfa_fsync(int fd) { #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_FSYNC) return fsync(fd); #else __submit_prelude (*sqe){ IORING_OP_FSYNC, fd }; __submit_wait #endif } int cfa_sync_file_range(int fd, int64_t offset, int64_t nbytes, unsigned int flags) { #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_SYNC_FILE_RANGE) return sync_file_range(fd, offset, nbytes, flags); #else __submit_prelude (*sqe){ IORING_OP_SYNC_FILE_RANGE, fd }; sqe->off = offset; sqe->len = nbytes; sqe->sync_range_flags = flags; __submit_wait #endif } ssize_t cfa_sendmsg(int sockfd, const struct msghdr *msg, int flags) { #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_SENDMSG) return sendmsg(sockfd, msg, flags); #else __submit_prelude (*sqe){ IORING_OP_SENDMSG, sockfd, msg, 1, 0 }; sqe->msg_flags = flags; __submit_wait #endif } ssize_t cfa_recvmsg(int sockfd, struct msghdr *msg, int flags) { #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_RECVMSG) return recvmsg(sockfd, msg, flags); #else __submit_prelude (*sqe){ IORING_OP_RECVMSG, sockfd, msg, 1, 0 }; sqe->msg_flags = flags; __submit_wait #endif } ssize_t cfa_send(int sockfd, const void *buf, size_t len, int flags) { #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_SEND) return send( sockfd, buf, len, flags ); #else __submit_prelude (*sqe){ IORING_OP_SEND, sockfd }; sqe->addr = (uint64_t)buf; sqe->len = len; sqe->msg_flags = flags; __submit_wait #endif } ssize_t cfa_recv(int sockfd, void *buf, size_t len, int flags) { #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_RECV) return recv( sockfd, buf, len, flags ); #else __submit_prelude (*sqe){ IORING_OP_RECV, sockfd }; sqe->addr = (uint64_t)buf; sqe->len = len; sqe->msg_flags = flags; __submit_wait #endif } int cfa_accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags) { #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_ACCEPT) return accept4( sockfd, addr, addrlen, flags ); #else __submit_prelude (*sqe){ IORING_OP_ACCEPT, sockfd }; sqe->addr = addr; sqe->addr2 = addrlen; sqe->accept_flags = flags; __submit_wait #endif } int cfa_connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) { #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_CONNECT) return connect( sockfd, addr, addrlen ); #else __submit_prelude (*sqe){ IORING_OP_CONNECT, sockfd }; sqe->addr = (uint64_t)addr; sqe->off = addrlen; __submit_wait #endif } int cfa_fallocate(int fd, int mode, uint64_t offset, uint64_t len) { #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_FALLOCATE) return fallocate( fd, mode, offset, len ); #else __submit_prelude (*sqe){ IORING_OP_FALLOCATE, fd }; sqe->off = offset; sqe->len = length; sqe->mode = mode; __submit_wait #endif } int cfa_fadvise(int fd, uint64_t offset, uint64_t len, int advice) { #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_FADVISE) return posix_fadvise( fd, offset, len, advice ); #else __submit_prelude (*sqe){ IORING_OP_FADVISE, fd }; sqe->off = (uint64_t)offset; sqe->len = length; sqe->fadvise_advice = advice; __submit_wait #endif } int cfa_madvise(void *addr, size_t length, int advice) { #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_MADVISE) return madvise( addr, length, advice ); #else __submit_prelude (*sqe){ IORING_OP_MADVISE, 0 }; sqe->addr = (uint64_t)addr; sqe->len = length; sqe->fadvise_advice = advice; __submit_wait #endif } int cfa_openat(int dirfd, const char *pathname, int flags, mode_t mode) { #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_OPENAT) return openat( dirfd, pathname, flags, mode ); #else __submit_prelude (*sqe){ IORING_OP_OPENAT, dirfd }; sqe->addr = (uint64_t)pathname; sqe->open_flags = flags; sqe->mode = mode; __submit_wait #endif } int cfa_close(int fd) { #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_CLOSE) return close( fd ); #else __submit_prelude (*sqe){ IORING_OP_CLOSE, fd }; __submit_wait #endif } ssize_t cfa_read(int fd, void *buf, size_t count) { #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_READ) return read( fd, buf, count ); #else __submit_prelude (*sqe){ IORING_OP_READ, fd, buf, count, 0 }; __submit_wait #endif } ssize_t cfa_write(int fd, void *buf, size_t count) { #if !defined(HAVE_LINUX_IO_URING_H) || !defined(IORING_OP_WRITE) return read( fd, buf, count ); #else __submit_prelude (*sqe){ IORING_OP_WRITE, fd, buf, count, 0 }; __submit_wait #endif } //----------------------------------------------------------------------------- // Check if a function is asynchronous // Macro magic to reduce the size of the following switch case #define IS_DEFINED_APPLY(f, ...) f(__VA_ARGS__) #define IS_DEFINED_SECOND(first, second, ...) second #define IS_DEFINED_TEST(expansion) _CFA_IO_FEATURE_##expansion #define IS_DEFINED(macro) IS_DEFINED_APPLY( IS_DEFINED_SECOND,IS_DEFINED_TEST(macro) false, true) bool has_user_level_blocking( fptr_t func ) { #if defined(HAVE_LINUX_IO_URING_H) #if defined(HAVE_PREADV2) if( /*func == (fptr_t)preadv2 || */ func == (fptr_t)cfa_preadv2 ) #define _CFA_IO_FEATURE_IORING_OP_READV , return IS_DEFINED(IORING_OP_READV); #endif #if defined(HAVE_PWRITEV2) if( /*func == (fptr_t)pwritev2 || */ func == (fptr_t)cfa_pwritev2 ) #define _CFA_IO_FEATURE_IORING_OP_WRITEV , return IS_DEFINED(IORING_OP_WRITEV); #endif if( /*func == (fptr_t)fsync || */ func == (fptr_t)cfa_fsync ) #define _CFA_IO_FEATURE_IORING_OP_FSYNC , return IS_DEFINED(IORING_OP_FSYNC); if( /*func == (fptr_t)ync_file_range || */ func == (fptr_t)cfa_sync_file_range ) #define _CFA_IO_FEATURE_IORING_OP_SYNC_FILE_RANGE , return IS_DEFINED(IORING_OP_SYNC_FILE_RANGE); if( /*func == (fptr_t)sendmsg || */ func == (fptr_t)cfa_sendmsg ) #define _CFA_IO_FEATURE_IORING_OP_SENDMSG , return IS_DEFINED(IORING_OP_SENDMSG); if( /*func == (fptr_t)recvmsg || */ func == (fptr_t)cfa_recvmsg ) #define _CFA_IO_FEATURE_IORING_OP_RECVMSG , return IS_DEFINED(IORING_OP_RECVMSG); if( /*func == (fptr_t)send || */ func == (fptr_t)cfa_send ) #define _CFA_IO_FEATURE_IORING_OP_SEND , return IS_DEFINED(IORING_OP_SEND); if( /*func == (fptr_t)recv || */ func == (fptr_t)cfa_recv ) #define _CFA_IO_FEATURE_IORING_OP_RECV , return IS_DEFINED(IORING_OP_RECV); if( /*func == (fptr_t)accept4 || */ func == (fptr_t)cfa_accept4 ) #define _CFA_IO_FEATURE_IORING_OP_ACCEPT , return IS_DEFINED(IORING_OP_ACCEPT); if( /*func == (fptr_t)connect || */ func == (fptr_t)cfa_connect ) #define _CFA_IO_FEATURE_IORING_OP_CONNECT , return IS_DEFINED(IORING_OP_CONNECT); if( /*func == (fptr_t)fallocate || */ func == (fptr_t)cfa_fallocate ) #define _CFA_IO_FEATURE_IORING_OP_FALLOCATE , return IS_DEFINED(IORING_OP_FALLOCATE); if( /*func == (fptr_t)posix_fadvise || */ func == (fptr_t)cfa_fadvise ) #define _CFA_IO_FEATURE_IORING_OP_FADVISE , return IS_DEFINED(IORING_OP_FADVISE); if( /*func == (fptr_t)madvise || */ func == (fptr_t)cfa_madvise ) #define _CFA_IO_FEATURE_IORING_OP_MADVISE , return IS_DEFINED(IORING_OP_MADVISE); if( /*func == (fptr_t)openat || */ func == (fptr_t)cfa_openat ) #define _CFA_IO_FEATURE_IORING_OP_OPENAT , return IS_DEFINED(IORING_OP_OPENAT); if( /*func == (fptr_t)close || */ func == (fptr_t)cfa_close ) #define _CFA_IO_FEATURE_IORING_OP_CLOSE , return IS_DEFINED(IORING_OP_CLOSE); if( /*func == (fptr_t)read || */ func == (fptr_t)cfa_read ) #define _CFA_IO_FEATURE_IORING_OP_READ , return IS_DEFINED(IORING_OP_READ); if( /*func == (fptr_t)write || */ func == (fptr_t)cfa_write ) #define _CFA_IO_FEATURE_IORING_OP_WRITE , return IS_DEFINED(IORING_OP_WRITE); #endif return false; }