source: libcfa/src/concurrency/io/setup.cfa@ 108f98b2

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 108f98b2 was ece0e80, checked in by Thierry Delisle <tdelisle@…>, 5 years ago

Added prints.
Naive implementation of cancel.
Server now shutdown cleanly.

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