source: libcfa/src/concurrency/io.cfa@ 1d5e4711

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast new-ast-unique-expr pthread-emulation qualifiedEnum stuck-waitfor-destruct
Last change on this file since 1d5e4711 was 1d5e4711, checked in by Thierry Delisle <tdelisle@…>, 6 years ago

Optim: No longer call io_uring_enter to poll for events if

  • We don't want to block
  • There is nothing to submit

This is only valid for "interrupt driven I/O", polling driven I/O not yet supported.

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