source: libcfa/src/concurrency/io/setup.cfa@ b57db73

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

Removed some warnings and allowed io calls to compile without io_uring.

  • Property mode set to 100644
File size: 18.0 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/setup.cfa --
8//
9// Author : Thierry Delisle
10// Created On : Fri Jul 31 16:25:51 2020
11// Last Modified By :
12// Last Modified On :
13// Update Count :
14//
15
16#define __cforall_thread__
17#define _GNU_SOURCE /* See feature_test_macros(7) */
18
19#if defined(__CFA_DEBUG__)
20 // #define __CFA_DEBUG_PRINT_IO__
21 // #define __CFA_DEBUG_PRINT_IO_CORE__
22#endif
23
24#include "io/types.hfa"
25#include "kernel.hfa"
26
27#if !defined(CFA_HAVE_LINUX_IO_URING_H)
28 void __kernel_io_startup() {
29 // Nothing to do without io_uring
30 }
31
32 void __kernel_io_shutdown() {
33 // Nothing to do without io_uring
34 }
35
36 void ?{}(io_context_params & this) {}
37
38 void ?{}(io_context & this, struct cluster & cl) {}
39 void ?{}(io_context & this, struct cluster & cl, const io_context_params & params) {}
40
41 void ^?{}(io_context & this) {}
42 void ^?{}(io_context & this, bool cluster_context) {}
43
44 void register_fixed_files( io_context &, int *, unsigned ) {}
45 void register_fixed_files( cluster &, int *, unsigned ) {}
46
47#else
48 #include <errno.h>
49 #include <stdint.h>
50 #include <string.h>
51 #include <signal.h>
52 #include <unistd.h>
53
54 extern "C" {
55 #include <pthread.h>
56 #include <sys/epoll.h>
57 #include <sys/eventfd.h>
58 #include <sys/mman.h>
59 #include <sys/syscall.h>
60
61 #include <linux/io_uring.h>
62 }
63
64 #include "bitmanip.hfa"
65 #include "kernel_private.hfa"
66 #include "thread.hfa"
67
68 void ?{}(io_context_params & this) {
69 this.num_entries = 256;
70 this.num_ready = 256;
71 this.submit_aff = -1;
72 this.eager_submits = false;
73 this.poller_submits = false;
74 this.poll_submit = false;
75 this.poll_complete = false;
76 }
77
78 static void * __io_poller_slow( void * arg );
79
80 // Weirdly, some systems that do support io_uring don't actually define these
81 #ifdef __alpha__
82 /*
83 * alpha is the only exception, all other architectures
84 * have common numbers for new system calls.
85 */
86 #ifndef __NR_io_uring_setup
87 #define __NR_io_uring_setup 535
88 #endif
89 #ifndef __NR_io_uring_enter
90 #define __NR_io_uring_enter 536
91 #endif
92 #ifndef __NR_io_uring_register
93 #define __NR_io_uring_register 537
94 #endif
95 #else /* !__alpha__ */
96 #ifndef __NR_io_uring_setup
97 #define __NR_io_uring_setup 425
98 #endif
99 #ifndef __NR_io_uring_enter
100 #define __NR_io_uring_enter 426
101 #endif
102 #ifndef __NR_io_uring_register
103 #define __NR_io_uring_register 427
104 #endif
105 #endif
106
107//=============================================================================================
108// I/O Startup / Shutdown logic + Master Poller
109//=============================================================================================
110
111 // IO Master poller loop forward
112 static void * iopoll_loop( __attribute__((unused)) void * args );
113
114 static struct {
115 pthread_t thrd; // pthread handle to io poller thread
116 void * stack; // pthread stack for io poller thread
117 int epollfd; // file descriptor to the epoll instance
118 volatile bool run; // Whether or not to continue
119 } iopoll;
120
121 void __kernel_io_startup(void) {
122 __cfadbg_print_safe(io_core, "Kernel : Creating EPOLL instance\n" );
123
124 iopoll.epollfd = epoll_create1(0);
125 if (iopoll.epollfd == -1) {
126 abort( "internal error, epoll_create1\n");
127 }
128
129 __cfadbg_print_safe(io_core, "Kernel : Starting io poller thread\n" );
130
131 iopoll.run = true;
132 iopoll.stack = __create_pthread( &iopoll.thrd, iopoll_loop, 0p );
133 }
134
135 void __kernel_io_shutdown(void) {
136 // Notify the io poller thread of the shutdown
137 iopoll.run = false;
138 sigval val = { 1 };
139 pthread_sigqueue( iopoll.thrd, SIGUSR1, val );
140
141 // Wait for the io poller thread to finish
142
143 __destroy_pthread( iopoll.thrd, iopoll.stack, 0p );
144
145 int ret = close(iopoll.epollfd);
146 if (ret == -1) {
147 abort( "internal error, close epoll\n");
148 }
149
150 // Io polling is now fully stopped
151
152 __cfadbg_print_safe(io_core, "Kernel : IO poller stopped\n" );
153 }
154
155 static void * iopoll_loop( __attribute__((unused)) void * args ) {
156 __processor_id_t id;
157 id.full_proc = false;
158 id.id = doregister(&id);
159 __cfaabi_tls.this_proc_id = &id;
160 __cfadbg_print_safe(io_core, "Kernel : IO poller thread starting\n" );
161
162 // Block signals to control when they arrive
163 sigset_t mask;
164 sigfillset(&mask);
165 if ( pthread_sigmask( SIG_BLOCK, &mask, 0p ) == -1 ) {
166 abort( "internal error, pthread_sigmask" );
167 }
168
169 sigdelset( &mask, SIGUSR1 );
170
171 // Create sufficient events
172 struct epoll_event events[10];
173 // Main loop
174 while( iopoll.run ) {
175 __cfadbg_print_safe(io_core, "Kernel I/O - epoll : waiting on io_uring contexts\n");
176
177 // Wait for events
178 int nfds = epoll_pwait( iopoll.epollfd, events, 10, -1, &mask );
179
180 __cfadbg_print_safe(io_core, "Kernel I/O - epoll : %d io contexts events, waking up\n", nfds);
181
182 // Check if an error occured
183 if (nfds == -1) {
184 if( errno == EINTR ) continue;
185 abort( "internal error, pthread_sigmask" );
186 }
187
188 for(i; nfds) {
189 $io_ctx_thread * io_ctx = ($io_ctx_thread *)(uintptr_t)events[i].data.u64;
190 /* paranoid */ verify( io_ctx );
191 __cfadbg_print_safe(io_core, "Kernel I/O - epoll : Unparking io poller %d (%p)\n", io_ctx->ring->fd, io_ctx);
192 #if !defined( __CFA_NO_STATISTICS__ )
193 __cfaabi_tls.this_stats = io_ctx->self.curr_cluster->stats;
194 #endif
195
196 eventfd_t v;
197 eventfd_read(io_ctx->ring->efd, &v);
198
199 post( io_ctx->sem );
200 }
201 }
202
203 __cfadbg_print_safe(io_core, "Kernel : IO poller thread stopping\n" );
204 unregister(&id);
205 return 0p;
206 }
207
208//=============================================================================================
209// I/O Context Constrution/Destruction
210//=============================================================================================
211
212 void ?{}($io_ctx_thread & this, struct cluster & cl) { (this.self){ "IO Poller", cl }; }
213 void main( $io_ctx_thread & this );
214 static inline $thread * get_thread( $io_ctx_thread & this ) { return &this.self; }
215 void ^?{}( $io_ctx_thread & mutex this ) {}
216
217 static void __io_create ( __io_data & this, const io_context_params & params_in );
218 static void __io_destroy( __io_data & this );
219
220 void ?{}(io_context & this, struct cluster & cl, const io_context_params & params) {
221 (this.thrd){ cl };
222 this.thrd.ring = malloc();
223 __cfadbg_print_safe(io_core, "Kernel I/O : Creating ring for io_context %p\n", &this);
224 __io_create( *this.thrd.ring, params );
225
226 __cfadbg_print_safe(io_core, "Kernel I/O : Starting poller thread for io_context %p\n", &this);
227 this.thrd.done = false;
228 __thrd_start( this.thrd, main );
229
230 __cfadbg_print_safe(io_core, "Kernel I/O : io_context %p ready\n", &this);
231 }
232
233 void ?{}(io_context & this, struct cluster & cl) {
234 io_context_params params;
235 (this){ cl, params };
236 }
237
238 void ^?{}(io_context & this, bool cluster_context) {
239 __cfadbg_print_safe(io_core, "Kernel I/O : tearing down io_context %p\n", &this);
240
241 // Notify the thread of the shutdown
242 __atomic_store_n(&this.thrd.done, true, __ATOMIC_SEQ_CST);
243
244 // If this is an io_context within a cluster, things get trickier
245 $thread & thrd = this.thrd.self;
246 if( cluster_context ) {
247 // We are about to do weird things with the threads
248 // we don't need interrupts to complicate everything
249 disable_interrupts();
250
251 // Get cluster info
252 cluster & cltr = *thrd.curr_cluster;
253 /* paranoid */ verify( cltr.idles.total == 0 || &cltr == mainCluster );
254 /* paranoid */ verify( !ready_mutate_islocked() );
255
256 // We need to adjust the clean-up based on where the thread is
257 if( thrd.state == Ready || thrd.preempted != __NO_PREEMPTION ) {
258 // This is the tricky case
259 // The thread was preempted or ready to run and now it is on the ready queue
260 // but the cluster is shutting down, so there aren't any processors to run the ready queue
261 // the solution is to steal the thread from the ready-queue and pretend it was blocked all along
262
263 ready_schedule_lock();
264 // The thread should on the list
265 /* paranoid */ verify( thrd.link.next != 0p );
266
267 // Remove the thread from the ready queue of this cluster
268 // The thread should be the last on the list
269 __attribute__((unused)) bool removed = remove_head( &cltr, &thrd );
270 /* paranoid */ verify( removed );
271 thrd.link.next = 0p;
272 thrd.link.prev = 0p;
273
274 // Fixup the thread state
275 thrd.state = Blocked;
276 thrd.ticket = TICKET_BLOCKED;
277 thrd.preempted = __NO_PREEMPTION;
278
279 ready_schedule_unlock();
280
281 // Pretend like the thread was blocked all along
282 }
283 // !!! This is not an else if !!!
284 // Ok, now the thread is blocked (whether we cheated to get here or not)
285 if( thrd.state == Blocked ) {
286 // This is the "easy case"
287 // The thread is parked and can easily be moved to active cluster
288 verify( thrd.curr_cluster != active_cluster() || thrd.curr_cluster == mainCluster );
289 thrd.curr_cluster = active_cluster();
290
291 // unpark the fast io_poller
292 unpark( &thrd );
293 }
294 else {
295 // The thread is in a weird state
296 // I don't know what to do here
297 abort("io_context poller thread is in unexpected state, cannot clean-up correctly\n");
298 }
299
300 // The weird thread kidnapping stuff is over, restore interrupts.
301 enable_interrupts( __cfaabi_dbg_ctx );
302 } else {
303 post( this.thrd.sem );
304 }
305
306 ^(this.thrd){};
307 __cfadbg_print_safe(io_core, "Kernel I/O : Stopped poller thread for io_context %p\n", &this);
308
309 __io_destroy( *this.thrd.ring );
310 __cfadbg_print_safe(io_core, "Kernel I/O : Destroyed ring for io_context %p\n", &this);
311
312 free(this.thrd.ring);
313 }
314
315 void ^?{}(io_context & this) {
316 ^(this){ false };
317 }
318
319 extern void __disable_interrupts_hard();
320 extern void __enable_interrupts_hard();
321
322 static void __io_create( __io_data & this, const io_context_params & params_in ) {
323 // Step 1 : call to setup
324 struct io_uring_params params;
325 memset(&params, 0, sizeof(params));
326 if( params_in.poll_submit ) params.flags |= IORING_SETUP_SQPOLL;
327 if( params_in.poll_complete ) params.flags |= IORING_SETUP_IOPOLL;
328
329 __u32 nentries = params_in.num_entries != 0 ? params_in.num_entries : 256;
330 if( !is_pow2(nentries) ) {
331 abort("ERROR: I/O setup 'num_entries' must be a power of 2\n");
332 }
333 if( params_in.poller_submits && params_in.eager_submits ) {
334 abort("ERROR: I/O setup 'poller_submits' and 'eager_submits' cannot be used together\n");
335 }
336
337 int fd = syscall(__NR_io_uring_setup, nentries, &params );
338 if(fd < 0) {
339 abort("KERNEL ERROR: IO_URING SETUP - %s\n", strerror(errno));
340 }
341
342 // Step 2 : mmap result
343 memset( &this, 0, sizeof(struct __io_data) );
344 struct __submition_data & sq = this.submit_q;
345 struct __completion_data & cq = this.completion_q;
346
347 // calculate the right ring size
348 sq.ring_sz = params.sq_off.array + (params.sq_entries * sizeof(unsigned) );
349 cq.ring_sz = params.cq_off.cqes + (params.cq_entries * sizeof(struct io_uring_cqe));
350
351 // Requires features
352 #if defined(IORING_FEAT_SINGLE_MMAP)
353 // adjust the size according to the parameters
354 if ((params.features & IORING_FEAT_SINGLE_MMAP) != 0) {
355 cq.ring_sz = sq.ring_sz = max(cq.ring_sz, sq.ring_sz);
356 }
357 #endif
358
359 // mmap the Submit Queue into existence
360 sq.ring_ptr = mmap(0, sq.ring_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_SQ_RING);
361 if (sq.ring_ptr == (void*)MAP_FAILED) {
362 abort("KERNEL ERROR: IO_URING MMAP1 - %s\n", strerror(errno));
363 }
364
365 // Requires features
366 #if defined(IORING_FEAT_SINGLE_MMAP)
367 // mmap the Completion Queue into existence (may or may not be needed)
368 if ((params.features & IORING_FEAT_SINGLE_MMAP) != 0) {
369 cq.ring_ptr = sq.ring_ptr;
370 }
371 else
372 #endif
373 {
374 // We need multiple call to MMAP
375 cq.ring_ptr = mmap(0, cq.ring_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_CQ_RING);
376 if (cq.ring_ptr == (void*)MAP_FAILED) {
377 munmap(sq.ring_ptr, sq.ring_sz);
378 abort("KERNEL ERROR: IO_URING MMAP2 - %s\n", strerror(errno));
379 }
380 }
381
382 // mmap the submit queue entries
383 size_t size = params.sq_entries * sizeof(struct io_uring_sqe);
384 sq.sqes = (struct io_uring_sqe *)mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_SQES);
385 if (sq.sqes == (struct io_uring_sqe *)MAP_FAILED) {
386 munmap(sq.ring_ptr, sq.ring_sz);
387 if (cq.ring_ptr != sq.ring_ptr) munmap(cq.ring_ptr, cq.ring_sz);
388 abort("KERNEL ERROR: IO_URING MMAP3 - %s\n", strerror(errno));
389 }
390
391 // Step 3 : Initialize the data structure
392 // Get the pointers from the kernel to fill the structure
393 // submit queue
394 sq.head = (volatile __u32 *)(((intptr_t)sq.ring_ptr) + params.sq_off.head);
395 sq.tail = (volatile __u32 *)(((intptr_t)sq.ring_ptr) + params.sq_off.tail);
396 sq.mask = ( const __u32 *)(((intptr_t)sq.ring_ptr) + params.sq_off.ring_mask);
397 sq.num = ( const __u32 *)(((intptr_t)sq.ring_ptr) + params.sq_off.ring_entries);
398 sq.flags = ( __u32 *)(((intptr_t)sq.ring_ptr) + params.sq_off.flags);
399 sq.dropped = ( __u32 *)(((intptr_t)sq.ring_ptr) + params.sq_off.dropped);
400 sq.array = ( __u32 *)(((intptr_t)sq.ring_ptr) + params.sq_off.array);
401 sq.prev_head = *sq.head;
402
403 {
404 const __u32 num = *sq.num;
405 for( i; num ) {
406 __sqe_clean( &sq.sqes[i] );
407 }
408 }
409
410 (sq.submit_lock){};
411 (sq.release_lock){};
412
413 if( params_in.poller_submits || params_in.eager_submits ) {
414 /* paranoid */ verify( is_pow2( params_in.num_ready ) || (params_in.num_ready < 8) );
415 sq.ready_cnt = max( params_in.num_ready, 8 );
416 sq.ready = alloc( sq.ready_cnt, 64`align );
417 for(i; sq.ready_cnt) {
418 sq.ready[i] = -1ul32;
419 }
420 sq.prev_ready = 0;
421 }
422 else {
423 sq.ready_cnt = 0;
424 sq.ready = 0p;
425 sq.prev_ready = 0;
426 }
427
428 // completion queue
429 cq.head = (volatile __u32 *)(((intptr_t)cq.ring_ptr) + params.cq_off.head);
430 cq.tail = (volatile __u32 *)(((intptr_t)cq.ring_ptr) + params.cq_off.tail);
431 cq.mask = ( const __u32 *)(((intptr_t)cq.ring_ptr) + params.cq_off.ring_mask);
432 cq.num = ( const __u32 *)(((intptr_t)cq.ring_ptr) + params.cq_off.ring_entries);
433 cq.overflow = ( __u32 *)(((intptr_t)cq.ring_ptr) + params.cq_off.overflow);
434 cq.cqes = (struct io_uring_cqe *)(((intptr_t)cq.ring_ptr) + params.cq_off.cqes);
435
436 // Step 4 : eventfd
437 // io_uring_register is so f*cking slow on some machine that it
438 // will never succeed if preemption isn't hard blocked
439 __disable_interrupts_hard();
440
441 int efd = eventfd(0, 0);
442 if (efd < 0) {
443 abort("KERNEL ERROR: IO_URING EVENTFD - %s\n", strerror(errno));
444 }
445
446 int ret = syscall( __NR_io_uring_register, fd, IORING_REGISTER_EVENTFD, &efd, 1);
447 if (ret < 0) {
448 abort("KERNEL ERROR: IO_URING EVENTFD REGISTER - %s\n", strerror(errno));
449 }
450
451 __enable_interrupts_hard();
452
453 // some paranoid checks
454 /* 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 );
455 /* paranoid */ verifyf( (*cq.num) >= nentries, "IO_URING Expected %u entries, got %u", nentries, *cq.num );
456 /* paranoid */ verifyf( (*cq.head) == 0, "IO_URING Expected head to be 0, got %u", *cq.head );
457 /* paranoid */ verifyf( (*cq.tail) == 0, "IO_URING Expected tail to be 0, got %u", *cq.tail );
458
459 /* 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 );
460 /* paranoid */ verifyf( (*sq.num) >= nentries, "IO_URING Expected %u entries, got %u", nentries, *sq.num );
461 /* paranoid */ verifyf( (*sq.head) == 0, "IO_URING Expected head to be 0, got %u", *sq.head );
462 /* paranoid */ verifyf( (*sq.tail) == 0, "IO_URING Expected tail to be 0, got %u", *sq.tail );
463
464 // Update the global ring info
465 this.ring_flags = params.flags;
466 this.fd = fd;
467 this.efd = efd;
468 this.eager_submits = params_in.eager_submits;
469 this.poller_submits = params_in.poller_submits;
470 }
471
472 static void __io_destroy( __io_data & this ) {
473 // Shutdown the io rings
474 struct __submition_data & sq = this.submit_q;
475 struct __completion_data & cq = this.completion_q;
476
477 // unmap the submit queue entries
478 munmap(sq.sqes, (*sq.num) * sizeof(struct io_uring_sqe));
479
480 // unmap the Submit Queue ring
481 munmap(sq.ring_ptr, sq.ring_sz);
482
483 // unmap the Completion Queue ring, if it is different
484 if (cq.ring_ptr != sq.ring_ptr) {
485 munmap(cq.ring_ptr, cq.ring_sz);
486 }
487
488 // close the file descriptor
489 close(this.fd);
490 close(this.efd);
491
492 free( this.submit_q.ready ); // Maybe null, doesn't matter
493 }
494
495//=============================================================================================
496// I/O Context Sleep
497//=============================================================================================
498 #define IOEVENTS EPOLLIN | EPOLLONESHOT
499
500 static inline void __ioctx_epoll_ctl($io_ctx_thread & ctx, int op, const char * error) {
501 struct epoll_event ev;
502 ev.events = IOEVENTS;
503 ev.data.u64 = (__u64)&ctx;
504 int ret = epoll_ctl(iopoll.epollfd, op, ctx.ring->efd, &ev);
505 if (ret < 0) {
506 abort( "KERNEL ERROR: EPOLL %s - (%d) %s\n", error, (int)errno, strerror(errno) );
507 }
508 }
509
510 void __ioctx_register($io_ctx_thread & ctx) {
511 __ioctx_epoll_ctl(ctx, EPOLL_CTL_ADD, "ADD");
512 }
513
514 void __ioctx_prepare_block($io_ctx_thread & ctx) {
515 __cfadbg_print_safe(io_core, "Kernel I/O - epoll : Re-arming io poller %d (%p)\n", ctx.ring->fd, &ctx);
516 __ioctx_epoll_ctl(ctx, EPOLL_CTL_MOD, "REARM");
517 }
518
519//=============================================================================================
520// I/O Context Misc Setup
521//=============================================================================================
522 void register_fixed_files( io_context & ctx, int * files, unsigned count ) {
523 int ret = syscall( __NR_io_uring_register, ctx.thrd.ring->fd, IORING_REGISTER_FILES, files, count );
524 if( ret < 0 ) {
525 abort( "KERNEL ERROR: IO_URING SYSCALL - (%d) %s\n", (int)errno, strerror(errno) );
526 }
527
528 __cfadbg_print_safe( io_core, "Kernel I/O : Performed io_register for %p, returned %d\n", active_thread(), ret );
529 }
530
531 void register_fixed_files( cluster & cltr, int * files, unsigned count ) {
532 for(i; cltr.io.cnt) {
533 register_fixed_files( cltr.io.ctxs[i], files, count );
534 }
535 }
536#endif
Note: See TracBrowser for help on using the repository browser.