Debian Codegraph @

c/src/proactor/epoll.c

raw
1 /*
2 *
3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
18 * under the License.
19 *
20 */
21
22 /*
23 The epoll proactor works with multiple concurrent threads. If there is no work to do,
24 one thread temporarily becomes the poller thread, while other inbound threads suspend
25 waiting for work. The poller calls epoll_wait(), generates work lists, resumes suspended
26 threads, and grabs work for itself or polls again.
27
28 A serialized grouping of Proton events is a task (connection, listener, proactor).
29 Each has multiple pollable fds that make it schedulable. E.g. a connection could have a
30 socket fd, (indirect) timerfd, and (indirect) eventfd all signaled in a single epoll_wait().
31
32 At the conclusion of each
33 N = epoll_wait(..., N_MAX, timeout)
34
35 there will be N epoll events and M tasks on a ready list. M can be very large in a
36 server with many active connections. The poller makes the tasks "runnable" if they are
37 not already running. A running task cannot be made runnable again until it completes
38 a chunk of work and calls unassign_thread(). (N + M - duplicates) tasks will be
39 scheduled. A new poller will occur when next_runnable() returns NULL.
40
41 A task may have its own dedicated kernel file descriptor (socket, timerfd) which can be seen
42 by the poller to make the task runnable. A task may aslso be scheduled to run by placing it
43 on a ready queue which is monitored by the poller via two eventfds.
44
45 Lock ordering - never add locks right to left:
46 task -> sched -> ready
47 non-proactor-task -> proactor-task
48 tslot -> sched
49
50 TODO: doc new work: warm (assigned), earmarked (assigned), runnables (unordered), sched_ready
51 list (ordered), resched list (ordered).
52 TODO: document role of sched_pending and how sched_XXX (i.e. sched_interrupt)
53 transitions from "private to the scheduler" to "visible to the task".
54 TODO: document task.working duration can be long: from xxx_process() to xxx_done() or null batch.
55 */
56
57
58 /* Enable POSIX features beyond c99 for modern pthread and standard strerror_r() */
59 #ifndef _POSIX_C_SOURCE
60 #define _POSIX_C_SOURCE 200809L
61 #endif
62 /* Avoid GNU extensions, in particular the incompatible alternative strerror_r() */
63 #undef _GNU_SOURCE
64
65 #include "epoll-internal.h"
66 #include "proactor-internal.h"
67 #include "core/engine-internal.h"
68 #include "core/logger_private.h"
69 #include "core/util.h"
70
71 #include <proton/condition.h>
72 #include <proton/connection_driver.h>
73 #include <proton/engine.h>
74 #include <proton/proactor.h>
75 #include <proton/transport.h>
76 #include <proton/listener.h>
77 #include <proton/netaddr.h>
78 #include <proton/raw_connection.h>
79
80 #include <assert.h>
81 #include <stddef.h>
82 #include <stdio.h>
83 #include <stdlib.h>
84 #include <string.h>
85
86 #include <errno.h>
87 #include <pthread.h>
88 #include <sys/epoll.h>
89 #include <unistd.h>
90 #include <sys/socket.h>
91 #include <netdb.h>
92 #include <fcntl.h>
93 #include <netinet/tcp.h>
94 #include <sys/eventfd.h>
95 #include <limits.h>
96 #include <time.h>
97 #include <alloca.h>
98
99 #include "./netaddr-internal.h" /* Include after socket/inet headers */
100
101 // TODO: logging in general
102 // SIGPIPE?
103 // Can some of the mutexes be spinlocks (any benefit over adaptive pthread mutex)?
104 // Maybe futex is even better?
105 // See other "TODO" in code.
106 //
107 // Consider case of large number of ready tasks: next_event_batch() could start by
108 // looking for ready tasks before a kernel call to epoll_wait(), or there
109 // could be several eventfds with random assignment of wakeables.
110
111
112 /* Like strerror_r but provide a default message if strerror_r fails */
113 void pstrerror(int err, strerrorbuf msg) {
114 int e = strerror_r(err, msg, sizeof(strerrorbuf));
115 if (e) snprintf(msg, sizeof(strerrorbuf), "unknown error %d", err);
116 }
117
118 /* epoll_ctl()/epoll_wait() do not form a memory barrier, so cached memory
119 writes to struct epoll_extended_t in the EPOLL_ADD thread might not be
120 visible to epoll_wait() thread. This function creates a memory barrier,
121 called before epoll_ctl() and after epoll_wait()
122 */
123 static void memory_barrier(epoll_extended_t *ee) {
124 // Mutex lock/unlock has the side-effect of being a memory barrier.
125 lock(&ee->barrier_mutex);
126 unlock(&ee->barrier_mutex);
127 }
128
129 /* Read from an event FD */
130 static uint64_t read_uint64(int fd) {
131 uint64_t result = 0;
132 ssize_t n = read(fd, &result, sizeof(result));
133 if (n != sizeof(result) && !(n < 0 && errno == EAGAIN)) {
134 EPOLL_FATAL("eventfd read error", errno);
135 }
136 return result;
137 }
138
139 // ========================================================================
140 // Proactor common code
141 // ========================================================================
142
143 const char *AMQP_PORT = "5672";
144 const char *AMQP_PORT_NAME = "amqp";
145
146 // The number of times a connection event batch may be replenished for
147 // a thread between calls to wait(). Some testing shows that
148 // increasing this value above 1 actually slows performance slightly
149 // and increases latency.
150 #define HOG_MAX 1
151
152 /* pn_proactor_t and pn_listener_t are plain C structs with normal memory management.
153 Class definitions are for identification as pn_event_t context only.
154 */
155 PN_STRUCT_CLASSDEF(pn_proactor)
156 PN_STRUCT_CLASSDEF(pn_listener)
157
158 bool start_polling(epoll_extended_t *ee, int epollfd) {
159 if (ee->polling)
160 return false;
161 ee->polling = true;
162 struct epoll_event ev = {0};
163 ev.data.ptr = ee;
164 ev.events = ee->wanted | EPOLLONESHOT;
165 memory_barrier(ee);
166 return (epoll_ctl(epollfd, EPOLL_CTL_ADD, ee->fd, &ev) == 0);
167 }
168
169 void stop_polling(epoll_extended_t *ee, int epollfd) {
170 // TODO: check for error, return bool or just log?
171 // TODO: is EPOLL_CTL_DEL ever needed beyond auto de-register when ee->fd is closed?
172 if (ee->fd == -1 || !ee->polling || epollfd == -1)
173 return;
174 struct epoll_event ev = {0};
175 ev.data.ptr = ee;
176 ev.events = 0;
177 memory_barrier(ee);
178 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, ee->fd, &ev) == -1)
179 EPOLL_FATAL("EPOLL_CTL_DEL", errno);
180 ee->fd = -1;
181 ee->polling = false;
182 }
183
184 void rearm_polling(epoll_extended_t *ee, int epollfd) {
185 struct epoll_event ev = {0};
186 ev.data.ptr = ee;
187 ev.events = ee->wanted | EPOLLONESHOT;
188 memory_barrier(ee);
189 if (epoll_ctl(epollfd, EPOLL_CTL_MOD, ee->fd, &ev) == -1)
190 EPOLL_FATAL("arming polled file descriptor", errno);
191 }
192
193 static void rearm(pn_proactor_t *p, epoll_extended_t *ee) {
194 rearm_polling(ee, p->epollfd);
195 }
196
197 /*
198 * The proactor maintains a number of serialization tasks: each
199 * connection, each listener, the proactor itself. The serialization
200 * is presented to the application via each associated event batch.
201 *
202 * A task will only ever run in a single thread at a time.
203 *
204 * Other threads of excution (including user threads) can interact with a
205 * particular task (i.e. connection wake or proactor interrupt). Mutexes are
206 * needed here for shared access to task data. schedule()/notify_poller() are
207 * used to ensure a task will run to act on the changed data.
208 *
209 * To minimize trips through the kernel, schedule() is a no-op if the task is
210 * already running or about to run. Conversely, a task must never stop working
211 * without checking state that may have been recently changed by another thread.
212 *
213 * External wake operations, like pn_connection_wake() or expired timers are
214 * built on top of this schedule() mechanism.
215 *
216 * pn_proactor_interrupt() must be async-signal-safe so it has a dedicated
217 * eventfd to allow a lock-free pn_proactor_interrupt() implementation.
218 */
219
220
221 // Fake thread for temporarily disabling the scheduling of a task.
222 static struct tslot_t *RESCHEDULE_PLACEHOLDER = (struct tslot_t*) -1;
223
224 void task_init(task_t *tsk, task_type_t t, pn_proactor_t *p) {
225 memset(tsk, 0, sizeof(*tsk));
226 pmutex_init(&tsk->mutex);
227 tsk->proactor = p;
228 tsk->type = t;
229 }
230
231 /*
232 * schedule() strategy with eventfd:
233 * - tasks can be in the ready list only once
234 * - a scheduling thread will only activate the eventfd if ready_list_active is false
235 * There is a single rearm between ready list empty and non-empty
236 *
237 * There can potentially be many tasks with work pending.
238 *
239 * The ready list is in two parts. The front is the chunk the
240 * poller will process until the next epoll_wait(). sched_ready
241 * indicates which chunk it is on. The task may already be running or
242 * scheduled to run.
243 *
244 * The task must be actually running to absorb task_t->ready.
245 *
246 * The ready list can keep growing while popping ready tasks. The list between
247 * sched_ready_first and sched_ready_last are protected by the sched
248 * lock (for pop operations), sched_ready_last to ready_list_last are
249 * protected by the eventfd mutex (for add operations). Both locks
250 * are needed to cross or reconcile the two portions of the list.
251 */
252
253 // Call with sched lock held and sched_ready_count > 0.
254 static task_t *sched_ready_pop_front(pn_proactor_t *p) {
255 // every task on the sched_ready_list is either currently running,
256 // or to be scheduled. schedule() will not "see" any of the ready_next
257 // pointers until ready and working have transitioned to 0
258 // and false, when a task stops working.
259 //
260 // every task must transition as:
261 //
262 // !ready .. schedule() .. on ready_list .. on sched_ready_list .. working task .. !sched_ready && !ready
263 //
264 // Intervening locks at each transition ensures ready_next has memory coherence throughout the ready task scheduling cycle.
265 assert (p->sched_ready_count);
266 task_t *tsk = p->sched_ready_first;
267 p->sched_ready_count--;
268 if (tsk == p->sched_ready_last) {
269 p->sched_ready_first = p->sched_ready_last = NULL;
270 } else {
271 p->sched_ready_first = tsk->ready_next;
272 }
273 if (p->sched_ready_count == 0) {
274 assert(!p->sched_ready_first);
275 p->sched_ready_pending = false;
276 }
277 return tsk;
278 }
279
280 // Call only as the poller task that has already called schedule_ready_list() and already
281 // incremented p->ready_list_generation. All list elements before sched_ready_last have
282 // correct generation from mutex barrier and cannot have tsk->ready_generation set to a
283 // new generation until after the poller task releases the sched lock and allows tsk to
284 // run again.
285 inline static bool on_sched_ready_list(task_t *tsk, pn_proactor_t *p) {
286 return tsk->ready_generation && (tsk->ready_generation != p->ready_list_generation);
287 }
288
289 // part1: call with tsk->owner lock held, return true if notify_poller required by caller.
290 // Nothing to do if the task is currently at work or work is already pending.
291 bool schedule(task_t *tsk) {
292 bool notify = false;
293
294 if (!tsk->ready) {
295 if (!tsk->working) {
296 tsk->ready = true;
297 pn_proactor_t *p = tsk->proactor;
298 lock(&p->eventfd_mutex);
299 assert(tsk->ready_generation == 0); // Can't be on list twice
300 tsk->ready_next = NULL;
301 tsk->ready_generation = p->ready_list_generation;
302 p->ready_list_count++;
303 if (!p->ready_list_first) {
304 p->ready_list_first = p->ready_list_last = tsk;
305 } else {
306 p->ready_list_last->ready_next = tsk;
307 p->ready_list_last = tsk;
308 }
309 if (!p->ready_list_active) {
310 // unblock poller via the eventfd
311 p->ready_list_active = true;
312 notify = true;
313 }
314 unlock(&p->eventfd_mutex);
315 }
316 }
317
318 return notify;
319 }
320
321 // part2: unblock epoll_wait(). Make OS call without lock held.
322 void notify_poller(pn_proactor_t *p) {
323 if (p->eventfd == -1)
324 return;
325 rearm(p, &p->epoll_schedule);
326 }
327
328 // call with task lock held from xxx_process().
329 void schedule_done(task_t *tsk) {
330 assert(tsk->ready);
331 lock(&tsk->proactor->eventfd_mutex);
332 assert(tsk->ready_generation != 0);
333 tsk->ready_generation = 0;
334 unlock(&tsk->proactor->eventfd_mutex);
335 tsk->ready = false;
336 }
337
338
339 /*
340 * Scheduler/poller
341 */
342
343 // Internal use only
344 /* How long to defer suspending */
345 static int pni_spins = 0;
346 /* Prefer immediate running by poller over warm running by suspended thread */
347 static bool pni_immediate = false;
348 /* Toggle use of warm scheduling */
349 static int pni_warm_sched = true;
350
351
352 // Call with sched lock
353 static void suspend_list_add_tail(pn_proactor_t *p, tslot_t *ts) {
354 LL_ADD(p, suspend_list, ts);
355 }
356
357 // Call with sched lock
358 static void suspend_list_insert_head(pn_proactor_t *p, tslot_t *ts) {
359 ts->suspend_list_next = p->suspend_list_head;
360 ts->suspend_list_prev = NULL;
361 if (p->suspend_list_head)
362 p->suspend_list_head->suspend_list_prev = ts;
363 else
364 p->suspend_list_tail = ts;
365 p->suspend_list_head = ts;
366 }
367
368 // Call with sched lock
369 static void suspend(pn_proactor_t *p, tslot_t *ts) {
370 if (ts->state == NEW)
371 suspend_list_add_tail(p, ts);
372 else
373 suspend_list_insert_head(p, ts);
374 p->suspend_list_count++;
375 ts->state = SUSPENDED;
376 ts->scheduled = false;
377 unlock(&p->sched_mutex);
378
379 lock(&ts->mutex);
380 if (pni_spins && !ts->scheduled) {
381 // Medium length spinning tried here. Raises cpu dramatically,
382 // unclear throughput or latency benefit (not seen where most
383 // expected, modest at other times).
384 bool locked = true;
385 for (volatile int i = 0; i < pni_spins; i++) {
386 if (locked) {
387 unlock(&ts->mutex);
388 locked = false;
389 }
390 if ((i % 1000) == 0) {
391 locked = (pthread_mutex_trylock(&ts->mutex) == 0);
392 }
393 if (ts->scheduled) break;
394 }
395 if (!locked)
396 lock(&ts->mutex);
397 }
398
399 ts->suspended = true;
400 while (!ts->scheduled) {
401 pthread_cond_wait(&ts->cond, &ts->mutex);
402 }
403 ts->suspended = false;
404 unlock(&ts->mutex);
405 lock(&p->sched_mutex);
406 assert(ts->state == PROCESSING);
407 }
408
409 // Call with no lock
410 static void resume(pn_proactor_t *p, tslot_t *ts) {
411 lock(&ts->mutex);
412 ts->scheduled = true;
413 if (ts->suspended) {
414 pthread_cond_signal(&ts->cond);
415 }
416 unlock(&ts->mutex);
417 }
418
419 // Call with no lock
420 void pni_resume(pn_proactor_t *p, tslot_t *ts) {
421 resume(p, ts);
422 }
423
424 // Call with shed_lock held
425 // Caller must resume() return value if not null
426 static tslot_t *resume_one_thread(pn_proactor_t *p) {
427 // If pn_proactor_get has an early return, we need to resume one suspended thread (if any)
428 // to be the new poller.
429
430 tslot_t *ts = p->suspend_list_head;
431 if (ts) {
432 LL_REMOVE(p, suspend_list, ts);
433 p->suspend_list_count--;
434 ts->state = PROCESSING;
435 }
436 return ts;
437 }
438
439 // Call with sched lock
440 static void assign_thread(tslot_t *ts, task_t *tsk) {
441 assert(!tsk->runner);
442 tsk->runner = ts;
443 tsk->prev_runner = NULL;
444 tsk->runnables_idx = 0;
445 ts->task = tsk;
446 ts->prev_task = NULL;
447 }
448
449 // call with sched lock
450 static inline task_t *resched_pop_front(pn_proactor_t *p) {
451 assert(p->resched_cutoff);
452 task_t *tsk = p->resched_first;
453 p->resched_first = tsk->resched_next;
454 p->polled_resched_count--;
455 if (!p->resched_first)
456 p->resched_last = NULL;
457 if (tsk == p->resched_cutoff) {
458 assert(p->polled_resched_count == 0);
459 p->resched_cutoff = NULL;
460 }
461 tsk->resched_next = NULL;
462 return tsk;
463 }
464
465 // Call with sched lock.
466 // If true returned, caller must call notify_poller() after releasing the lock.
467 // If resume_thread is set, the caller must call resume() after releasing the lock.
468 bool unassign_thread(pn_proactor_t *p, tslot_t *ts, tslot_state new_state, tslot_t **resume_thread) {
469 task_t *tsk = ts->task;
470 bool notify = false;
471 bool deleting = (ts->state == DELETING);
472 *resume_thread = NULL;
473 ts->task = NULL;
474 ts->state = new_state;
475 if (tsk) {
476 tsk->runner = NULL;
477 tsk->prev_runner = ts;
478 }
479
480 // Check if unseen events or schedule() calls occurred while task was working.
481
482 if (tsk && !deleting) {
483 ts->prev_task = tsk;
484 if (tsk->sched_pending) {
485 // New work arrived, reschedule it:
486 tsk->runner = RESCHEDULE_PLACEHOLDER; // Block tsk from being scheduled untl resched list is processed.
487 assert(!tsk->resched_next);
488 if (p->resched_last) {
489 p->resched_last->resched_next = tsk;
490 p->resched_last = tsk;
491 } else {
492 p->resched_first = p->resched_last = tsk;
493 }
494 p->resched_count++;
495 if (p->poller_suspended) {
496 lock(&p->eventfd_mutex);
497 if (!p->ready_list_active) {
498 p->ready_list_active = true;
499 notify = true;
500 }
501 unlock(&p->eventfd_mutex);
502 }
503 }
504 }
505
506 // Earmark drain accounting.
507 if (ts->earmark_override) {
508 // This thread "stole" the task previously assigned to thread ts->earmark_override.
509 if (ts->earmark_override->generation == ts->earmark_override_gen) {
510 // Other (overridden) thread not seen since this thread completed the pending work on the task.
511 // Thread is perhaps gone forever, which may leave us short of a poller thread and hanging.
512 // Find a thread to resume if available. Worst case is a spurious resume/suspend by an idle thread.
513 *resume_thread = resume_one_thread(p);
514 }
515 ts->earmark_override = NULL;
516 }
517
518 return notify;
519 }
520
521 // Call with sched lock
522 static void earmark_thread(tslot_t *ts, task_t *tsk) {
523 assign_thread(ts, tsk);
524 ts->earmarked = true;
525 tsk->proactor->earmark_count++;
526 }
527
528 // Call with sched lock
529 static void remove_earmark(tslot_t *ts) {
530 task_t *tsk = ts->task;
531 ts->task = NULL;
532 tsk->runner = NULL;
533 ts->earmarked = false;
534 tsk->proactor->earmark_count--;
535 }
536
537 // Call with sched lock
538 static void make_runnable(task_t *tsk) {
539 pn_proactor_t *p = tsk->proactor;
540 assert(p->n_runnables <= p->runnables_capacity);
541 assert(!tsk->runnables_idx);
542 if (tsk->runner) return;
543
544 // Track it as normal or warm or earmarked
545 if (pni_warm_sched) {
546 tslot_t *ts = tsk->prev_runner;
547 if (ts && ts->prev_task == tsk) {
548 if (ts->state == SUSPENDED || ts->state == PROCESSING) {
549 if (p->n_warm_runnables < p->thread_capacity) {
550 p->warm_runnables[p->n_warm_runnables++] = tsk;
551 assign_thread(ts, tsk);
552 }
553 else {
554 p->runnables[p->n_runnables] = tsk;
555 tsk->runnables_idx = p->n_runnables + 1; // off by one accounting
556 p->n_runnables++;
557 }
558 return;
559 }
560 if (ts->state == UNUSED && !p->earmark_drain) {
561 earmark_thread(ts, tsk);
562 p->last_earmark = ts;
563 return;
564 }
565 }
566 }
567 p->runnables[p->n_runnables] = tsk;
568 tsk->runnables_idx = p->n_runnables + 1; // off by one accounting
569 p->n_runnables++;
570 }
571
572
573
574 void psocket_init(psocket_t* ps, epoll_type_t type)
575 {
576 ps->epoll_io.fd = -1;
577 ps->epoll_io.type = type;
578 ps->epoll_io.wanted = 0;
579 ps->epoll_io.polling = false;
580 }
581
582
583 /* Protects read/update of pn_connection_t pointer to it's pconnection_t
584 *
585 * Global because pn_connection_wake()/pn_connection_proactor() navigate from
586 * the pn_connection_t before we know the proactor or driver. Critical sections
587 * are small: only get/set of the pn_connection_t driver pointer.
588 *
589 * TODO: replace mutex with atomic load/store
590 */
591 static pthread_mutex_t driver_ptr_mutex = PTHREAD_MUTEX_INITIALIZER;
592
593 static pconnection_t *get_pconnection(pn_connection_t* c) {
594 if (!c) return NULL;
595 lock(&driver_ptr_mutex);
596 pn_connection_driver_t *d = *pn_connection_driver_ptr(c);
597 unlock(&driver_ptr_mutex);
598 if (!d) return NULL;
599 return containerof(d, pconnection_t, driver);
600 }
601
602 static void set_pconnection(pn_connection_t* c, pconnection_t *pc) {
603 lock(&driver_ptr_mutex);
604 *pn_connection_driver_ptr(c) = pc ? &pc->driver : NULL;
605 unlock(&driver_ptr_mutex);
606 }
607
608 static pn_event_batch_t *pconnection_process(pconnection_t *pc, uint32_t events, bool sched_ready, bool topup);
609 static void write_flush(pconnection_t *pc);
610 static void listener_begin_close(pn_listener_t* l);
611 static bool poller_do_epoll(struct pn_proactor_t* p, tslot_t *ts, bool can_block);
612 static void poller_done(struct pn_proactor_t* p, tslot_t *ts);
613
614 static inline pconnection_t *psocket_pconnection(psocket_t* ps) {
615 return ps->epoll_io.type == PCONNECTION_IO ? containerof(ps, pconnection_t, psocket) : NULL;
616 }
617
618 static inline pn_listener_t *psocket_listener(psocket_t* ps) {
619 return ps->epoll_io.type == LISTENER_IO ? containerof(ps, acceptor_t, psocket)->listener : NULL;
620 }
621
622 static inline acceptor_t *psocket_acceptor(psocket_t* ps) {
623 return ps->epoll_io.type == LISTENER_IO ? containerof(ps, acceptor_t, psocket) : NULL;
624 }
625
626 static inline pconnection_t *task_pconnection(task_t *t) {
627 return t->type == PCONNECTION ? containerof(t, pconnection_t, task) : NULL;
628 }
629
630 static inline pn_listener_t *task_listener(task_t *t) {
631 return t->type == LISTENER ? containerof(t, pn_listener_t, task) : NULL;
632 }
633
634 static pn_event_t *listener_batch_next(pn_event_batch_t *batch);
635 static pn_event_t *proactor_batch_next(pn_event_batch_t *batch);
636 static pn_event_t *pconnection_batch_next(pn_event_batch_t *batch);
637
638 static inline pn_proactor_t *batch_proactor(pn_event_batch_t *batch) {
639 return (batch->next_event == proactor_batch_next) ?
640 containerof(batch, pn_proactor_t, batch) : NULL;
641 }
642
643 static inline pn_listener_t *batch_listener(pn_event_batch_t *batch) {
644 return (batch->next_event == listener_batch_next) ?
645 containerof(batch, pn_listener_t, batch) : NULL;
646 }
647
648 static inline pconnection_t *batch_pconnection(pn_event_batch_t *batch) {
649 return (batch->next_event == pconnection_batch_next) ?
650 containerof(batch, pconnection_t, batch) : NULL;
651 }
652
653 static void psocket_error_str(psocket_t *ps, const char *msg, const char* what) {
654 pconnection_t *pc = psocket_pconnection(ps);
655 if (pc) {
656 pn_connection_driver_t *driver = &pc->driver;
657 pn_connection_driver_bind(driver); /* Bind so errors will be reported */
658 pni_proactor_set_cond(pn_transport_condition(driver->transport), what, pc->host, pc->port, msg);
659 pn_connection_driver_close(driver);
660 return;
661 }
662 pn_listener_t *l = psocket_listener(ps);
663 if (l) {
664 pni_proactor_set_cond(l->condition, what, l->host, l->port, msg);
665 listener_begin_close(l);
666 return;
667 }
668 }
669
670 static void psocket_error(psocket_t *ps, int err, const char* what) {
671 strerrorbuf msg;
672 pstrerror(err, msg);
673 psocket_error_str(ps, msg, what);
674 }
675
676 static void psocket_gai_error(psocket_t *ps, int gai_err, const char* what) {
677 psocket_error_str(ps, gai_strerror(gai_err), what);
678 }
679
680 static void listener_accepted_append(pn_listener_t *listener, accepted_t item) {
681 if (listener->pending_first+listener->pending_count >= listener->backlog) return;
682
683 listener->pending_accepteds[listener->pending_first+listener->pending_count] = item;
684 listener->pending_count++;
685 }
686
687 accepted_t *listener_accepted_next(pn_listener_t *listener) {
688 if (!listener->pending_count) return NULL;
689
690 listener->pending_count--;
691 return &listener->pending_accepteds[listener->pending_first++];
692 }
693
694 static void acceptor_list_append(acceptor_t **start, acceptor_t *item) {
695 assert(item->next == NULL);
696 if (*start) {
697 acceptor_t *end = *start;
698 while (end->next)
699 end = end->next;
700 end->next = item;
701 }
702 else *start = item;
703 }
704
705 static acceptor_t *acceptor_list_next(acceptor_t **start) {
706 acceptor_t *item = *start;
707 if (*start) *start = (*start)->next;
708 if (item) item->next = NULL;
709 return item;
710 }
711
712 // Add an overflowing acceptor to the overflow list. Called with listener task lock held.
713 static void acceptor_set_overflow(acceptor_t *a) {
714 a->overflowed = true;
715 a->listener->overflow_count++;
716 pn_proactor_t *p = a->listener->task.proactor;
717 lock(&p->overflow_mutex);
718 acceptor_list_append(&p->overflow, a);
719 unlock(&p->overflow_mutex);
720 }
721
722 /* TODO aconway 2017-06-08: we should also call proactor_rearm_overflow after a fixed delay,
723 even if the proactor has not freed any file descriptors, since other parts of the process
724 might have*/
725
726 // Activate overflowing listeners, called when there may be available file descriptors.
727 static void proactor_rearm_overflow(pn_proactor_t *p) {
728 lock(&p->overflow_mutex);
729 acceptor_t* ovflw = p->overflow;
730 p->overflow = NULL;
731 unlock(&p->overflow_mutex);
732 acceptor_t *a = acceptor_list_next(&ovflw);
733 while (a) {
734 pn_listener_t *l = a->listener;
735 lock(&l->task.mutex);
736 bool rearming = !l->task.closing;
737 bool notify = false;
738 assert(!a->armed);
739 assert(a->overflowed);
740 a->overflowed = false;
741 l->overflow_count++;
742 if (rearming) {
743 rearm(p, &a->psocket.epoll_io);
744 a->armed = true;
745 }
746 else notify = schedule(&l->task);
747 unlock(&l->task.mutex);
748 if (notify) notify_poller(p);
749 a = acceptor_list_next(&ovflw);
750 }
751 }
752
753 // Close an FD and rearm overflow listeners. Call with no listener locks held.
754 int pclosefd(pn_proactor_t *p, int fd) {
755 int err = close(fd);
756 if (!err && !p->shutting_down) proactor_rearm_overflow(p);
757 return err;
758 }
759
760
761 // ========================================================================
762 // pconnection
763 // ========================================================================
764
765 static void pconnection_tick(pconnection_t *pc);
766
767 static const char *pconnection_setup(pconnection_t *pc, pn_proactor_t *p, pn_connection_t *c, pn_transport_t *t, bool server, const char *addr, size_t addrlen)
768 {
769 memset(pc, 0, sizeof(*pc));
770
771 if (pn_connection_driver_init(&pc->driver, c, t) != 0) {
772 free(pc);
773 return "pn_connection_driver_init failure";
774 }
775 if (!(pc->timer = pni_timer(&p->timer_manager, pc))) {
776 free(pc);
777 return "connection timer creation failure";
778 }
779
780
781 task_init(&pc->task, PCONNECTION, p);
782 psocket_init(&pc->psocket, PCONNECTION_IO);
783 pni_parse_addr(addr, pc->addr_buf, addrlen+1, &pc->host, &pc->port);
784 pc->new_events = 0;
785 pc->tick_pending = false;
786 pc->queued_disconnect = false;
787 pc->disconnect_condition = NULL;
788
789 pc->current_arm = 0;
790 pc->connected = false;
791 pc->read_blocked = true;
792 pc->write_blocked = true;
793 pc->disconnected = false;
794 pc->output_drained = false;
795 pc->wbuf_completed = 0;
796 pc->wbuf_remaining = 0;
797 pc->wbuf_current = NULL;
798 pc->hog_count = 0;
799 pc->batch.next_event = pconnection_batch_next;
800
801 if (server) {
802 pn_transport_set_server(pc->driver.transport);
803 }
804
805 pmutex_init(&pc->rearm_mutex);
806
807 /* Set the pconnection_t backpointer last.
808 Connections that were released by pn_proactor_release_connection() must not reveal themselves
809 to be re-associated with a proactor till setup is complete.
810 */
811 set_pconnection(pc->driver.connection, pc);
812
813 return NULL;
814 }
815
816 // Call with lock held and closing == true (i.e. pn_connection_driver_finished() == true), no pending timer.
817 // Return true when all possible outstanding epoll events associated with this pconnection have been processed.
818 static inline bool pconnection_is_final(pconnection_t *pc) {
819 return !pc->current_arm && !pc->task.ready && !pc->tick_pending;
820 }
821
822 static void pconnection_final_free(pconnection_t *pc) {
823 // Ensure any lingering pconnection_rearm is all done.
824 lock(&pc->rearm_mutex); unlock(&pc->rearm_mutex);
825
826 if (pc->driver.connection) {
827 set_pconnection(pc->driver.connection, NULL);
828 }
829 if (pc->addrinfo) {
830 freeaddrinfo(pc->addrinfo);
831 }
832 pmutex_finalize(&pc->rearm_mutex);
833 pn_condition_free(pc->disconnect_condition);
834 pn_connection_driver_destroy(&pc->driver);
835 pni_timer_free(pc->timer);
836 task_finalize(&pc->task);
837 free(pc);
838 }
839
840
841 // call without lock
842 static void pconnection_cleanup(pconnection_t *pc) {
843 assert(pconnection_is_final(pc));
844 int fd = pc->psocket.epoll_io.fd;
845 stop_polling(&pc->psocket.epoll_io, pc->task.proactor->epollfd);
846 if (fd != -1)
847 pclosefd(pc->task.proactor, fd);
848
849 lock(&pc->task.mutex);
850 bool can_free = proactor_remove(&pc->task);
851 unlock(&pc->task.mutex);
852 if (can_free)
853 pconnection_final_free(pc);
854 // else proactor_disconnect logic owns psocket and its final free
855 }
856
857 static void set_wbuf(pconnection_t *pc, const char *start, size_t sz) {
858 pc->wbuf_completed = 0;
859 pc->wbuf_current = start;
860 pc->wbuf_remaining = sz;
861 }
862
863 // Never call with any locks held.
864 static void ensure_wbuf(pconnection_t *pc) {
865 // next connection_driver call is the expensive output generator
866 pn_bytes_t bytes = pn_connection_driver_write_buffer(&pc->driver);
867 set_wbuf(pc, bytes.start, bytes.size);
868 if (bytes.size == 0)
869 pc->output_drained = true;
870 }
871
872 // Call with lock held or from forced_shutdown
873 static void pconnection_begin_close(pconnection_t *pc) {
874 if (!pc->task.closing) {
875 pc->task.closing = true;
876 pc->tick_pending = false;
877 if (pc->current_arm) {
878 // Force EPOLLHUP callback(s)
879 shutdown(pc->psocket.epoll_io.fd, SHUT_RDWR);
880 }
881 pn_connection_driver_close(&pc->driver);
882 }
883 }
884
885 static void pconnection_forced_shutdown(pconnection_t *pc) {
886 // Called by proactor_free, no competing threads, no epoll activity.
887 pc->current_arm = 0;
888 pc->new_events = 0;
889 pconnection_begin_close(pc);
890 // pconnection_process will never be called again. Zero everything.
891 pc->task.ready = 0;
892 pn_collector_release(pc->driver.collector);
893 assert(pconnection_is_final(pc));
894 pconnection_cleanup(pc);
895 }
896
897 // Called from timer_manager with no locks.
898 void pni_pconnection_timeout(pconnection_t *pc) {
899 bool notify = false;
900 pn_proactor_t *p = pc->task.proactor;
901 uint64_t now = pn_proactor_now_64();
902 lock(&pc->task.mutex);
903 if (!pc->task.closing) {
904 // confirm no simultaneous timeout change from another thread.
905 if (pc->expected_timeout && now >= pc->expected_timeout) {
906 pc->tick_pending = true;
907 pc->expected_timeout = 0;
908 notify = schedule(&pc->task);
909 }
910 }
911 unlock(&pc->task.mutex);
912 if (notify)
913 notify_poller(p);
914 }
915
916 static pn_event_t *pconnection_batch_next(pn_event_batch_t *batch) {
917 pconnection_t *pc = batch_pconnection(batch);
918 if (!pc->driver.connection) return NULL;
919 pn_event_t *e = pn_connection_driver_next_event(&pc->driver);
920 if (!e) {
921 pn_proactor_t *p = pc->task.proactor;
922 bool idle_threads;
923 lock(&p->sched_mutex);
924 idle_threads = (p->suspend_list_head != NULL);
925 unlock(&p->sched_mutex);
926 if (idle_threads && !pc->write_blocked && !pc->read_blocked) {
927 write_flush(pc); // May generate transport event
928 pconnection_process(pc, 0, false, true);
929 e = pn_connection_driver_next_event(&pc->driver);
930 }
931 else {
932 write_flush(pc); // May generate transport event
933 e = pn_connection_driver_next_event(&pc->driver);
934 if (!e && pc->hog_count < HOG_MAX) {
935 pconnection_process(pc, 0, false, true);
936 e = pn_connection_driver_next_event(&pc->driver);
937 }
938 }
939 }
940 if (e) {
941 pc->output_drained = false;
942 pc->current_event_type = pn_event_type(e);
943 }
944 return e;
945 }
946
947 /* Shortcuts */
948 static inline bool pconnection_rclosed(pconnection_t *pc) {
949 return pn_connection_driver_read_closed(&pc->driver);
950 }
951
952 static inline bool pconnection_wclosed(pconnection_t *pc) {
953 return pn_connection_driver_write_closed(&pc->driver);
954 }
955
956 /* Call only from working task (no competitor for pc->current_arm or
957 connection driver). If true returned, caller must do
958 pconnection_rearm().
959
960 Never rearm(0 | EPOLLONESHOT), since this really means
961 rearm(EPOLLHUP | EPOLLERR | EPOLLONESHOT) and leaves doubt that the
962 EPOLL_CTL_DEL can prevent a parallel HUP/ERR error notification during
963 close/shutdown. Let read()/write() return 0 or -1 to trigger cleanup logic.
964 */
965 static int pconnection_rearm_check(pconnection_t *pc) {
966 if ((pconnection_rclosed(pc) && pconnection_wclosed(pc)) || pc->psocket.epoll_io.fd == -1) {
967 return 0;
968 }
969 uint32_t wanted_now = (pc->read_blocked && !pconnection_rclosed(pc)) ? EPOLLIN : 0;
970 if (!pconnection_wclosed(pc)) {
971 if (pc->write_blocked)
972 wanted_now |= EPOLLOUT;
973 else {
974 if (pc->wbuf_remaining > 0)
975 wanted_now |= EPOLLOUT;
976 }
977 }
978 if (!wanted_now) return 0;
979 if (wanted_now == pc->current_arm) return 0;
980
981 return wanted_now;
982 }
983
984 static inline void pconnection_rearm(pconnection_t *pc, int wanted_now) {
985 lock(&pc->rearm_mutex);
986 pc->current_arm = pc->psocket.epoll_io.wanted = wanted_now;
987 rearm(pc->task.proactor, &pc->psocket.epoll_io);
988 unlock(&pc->rearm_mutex);
989 // Return immediately. pc may have just been freed by another thread.
990 }
991
992 /* Call with task lock and having done a write_flush() to "know" the value of wbuf_remaining */
993 static inline bool pconnection_work_pending(pconnection_t *pc) {
994 if (pc->new_events || pni_task_wake_pending(&pc->task) || pc->tick_pending || pc->queued_disconnect)
995 return true;
996 if (!pc->read_blocked && !pconnection_rclosed(pc))
997 return true;
998 return (pc->wbuf_remaining > 0 && !pc->write_blocked);
999 }
1000
1001 /* Call with no locks. */
1002 static void pconnection_done(pconnection_t *pc) {
1003 pn_proactor_t *p = pc->task.proactor;
1004 tslot_t *ts = pc->task.runner;
1005 write_flush(pc);
1006 bool notify = false;
1007 bool self_sched = false;
1008 lock(&pc->task.mutex);
1009 pc->task.working = false; // So we can schedule() ourself if necessary. We remain the de facto
1010 // working task instance while the lock is held.
1011 pc->hog_count = 0;
1012 bool has_event = pconnection_has_event(pc);
1013
1014 if (has_event || pconnection_work_pending(pc)) {
1015 self_sched = true;
1016 } else if (pn_connection_driver_finished(&pc->driver)) {
1017 pconnection_begin_close(pc);
1018 if (pconnection_is_final(pc)) {
1019 unlock(&pc->task.mutex);
1020 pconnection_cleanup(pc);
1021 // pc may be undefined now
1022 lock(&p->sched_mutex);
1023 tslot_t *resume_thread;
1024 notify = unassign_thread(p, ts, UNUSED, &resume_thread);
1025 unlock(&p->sched_mutex);
1026 if (notify) notify_poller(p);
1027 if (resume_thread) resume(p, resume_thread);
1028 return;
1029 }
1030 }
1031 if (self_sched)
1032 notify = schedule(&pc->task);
1033
1034 int wanted = pconnection_rearm_check(pc);
1035 unlock(&pc->task.mutex);
1036
1037 if (wanted) pconnection_rearm(pc, wanted); // May free pc on another thread. Return without touching pc again.
1038 lock(&p->sched_mutex);
1039 tslot_t *resume_thread;
1040 if (unassign_thread(p, ts, UNUSED, &resume_thread))
1041 notify = true;
1042 unlock(&p->sched_mutex);
1043 if (notify) notify_poller(p);
1044 if (resume_thread) resume(p, resume_thread);
1045 return;
1046 }
1047
1048 // Return true unless error
1049 static bool pconnection_write(pconnection_t *pc) {
1050 size_t wbuf_size = pc->wbuf_remaining;
1051 ssize_t n = send(pc->psocket.epoll_io.fd, pc->wbuf_current, wbuf_size, MSG_NOSIGNAL);
1052 if (n > 0) {
1053 pc->wbuf_completed += n;
1054 pc->wbuf_remaining -= n;
1055 pc->io_doublecheck = false;
1056 if (pc->wbuf_remaining) {
1057 pc->write_blocked = true;
1058 pc->wbuf_current += n;
1059 }
1060 else {
1061 // write_done also calls pn_transport_pending(), so the transport knows all current output
1062 pn_bytes_t bytes = pn_connection_driver_write_done(&pc->driver, pc->wbuf_completed);
1063 set_wbuf(pc, bytes.start, bytes.size);
1064 if (bytes.size == 0)
1065 pc->output_drained = true;
1066 // TODO: revise transport API to allow similar efficient access to transport output
1067 }
1068 } else if (errno == EWOULDBLOCK) {
1069 pc->write_blocked = true;
1070 } else if (!(errno == EAGAIN || errno == EINTR)) {
1071 pc->wbuf_remaining = 0;
1072 return false;
1073 }
1074 return true;
1075 }
1076
1077 // Never call with any locks held.
1078 static void write_flush(pconnection_t *pc) {
1079 size_t prev_wbuf_remaining = 0;
1080
1081 while(!pc->write_blocked && !pc->output_drained && !pconnection_wclosed(pc)) {
1082 if (pc->wbuf_remaining == 0) {
1083 ensure_wbuf(pc);
1084 } else {
1085 // Check if we are doing multiple small writes in a row, possibly worth growing the transport output buffer.
1086 if (prev_wbuf_remaining
1087 && prev_wbuf_remaining == pc->wbuf_remaining // two max outputs in a row
1088 && pc->wbuf_remaining < 131072) {
1089 ensure_wbuf(pc); // second call -> unchanged wbuf or transport buffer size doubles and more bytes added
1090 prev_wbuf_remaining = 0;
1091 } else {
1092 prev_wbuf_remaining = pc->wbuf_remaining;
1093 }
1094 }
1095 if (pc->wbuf_remaining > 0) {
1096 if (!pconnection_write(pc)) {
1097 psocket_error(&pc->psocket, errno, pc->disconnected ? "disconnected" : "on write to");
1098 }
1099 // pconnection_write side effect: wbuf may be replenished, and if not, output_drained may be set.
1100 }
1101 else {
1102 if (pn_connection_driver_write_closed(&pc->driver)) {
1103 shutdown(pc->psocket.epoll_io.fd, SHUT_WR);
1104 pc->write_blocked = true;
1105 }
1106 }
1107 }
1108 }
1109
1110 static void pconnection_connected_lh(pconnection_t *pc);
1111 static void pconnection_maybe_connect_lh(pconnection_t *pc);
1112
1113 static pn_event_batch_t *pconnection_process(pconnection_t *pc, uint32_t events, bool sched_ready, bool topup) {
1114 bool waking = false;
1115 bool tick_required = false;
1116 bool immediate_write = false;
1117 lock(&pc->task.mutex);
1118 if (!topup) { // Save some state in case of crash investigation.
1119 pc->process_events = events;
1120 pc->process_args = (pc->tick_pending << 1) | sched_ready;
1121 }
1122 if (events) {
1123 pc->new_events = events;
1124 pc->current_arm = 0;
1125 events = 0;
1126 }
1127 if (sched_ready) schedule_done(&pc->task);
1128
1129 if (topup) {
1130 // Only called by the batch owner. Does not loop, just "tops up"
1131 // once. May be back depending on hog_count.
1132 assert(pc->task.working);
1133 }
1134 else {
1135 if (pc->task.working) {
1136 // Another thread is the working task. Should be impossible with new scheduler.
1137 EPOLL_FATAL("internal epoll proactor error: two worker threads", 0);
1138 }
1139 pc->task.working = true;
1140 }
1141
1142 // Confirmed as working thread. Review state and unlock ASAP.
1143
1144 retry:
1145
1146 if (pc->queued_disconnect) { // From pn_proactor_disconnect()
1147 pc->queued_disconnect = false;
1148 if (!pc->task.closing) {
1149 if (pc->disconnect_condition) {
1150 pn_condition_copy(pn_transport_condition(pc->driver.transport), pc->disconnect_condition);
1151 }
1152 pn_connection_driver_close(&pc->driver);
1153 }
1154 }
1155
1156 if (pconnection_has_event(pc)) {
1157 unlock(&pc->task.mutex);
1158 return &pc->batch;
1159 }
1160 bool closed = pconnection_rclosed(pc) && pconnection_wclosed(pc);
1161 if (pni_task_wake_pending(&pc->task)) {
1162 waking = !closed;
1163 pni_task_wake_done(&pc->task);
1164 }
1165 if (pc->tick_pending) {
1166 pc->tick_pending = false;
1167 tick_required = !closed;
1168 }
1169
1170 if (pc->new_events) {
1171 uint32_t update_events = pc->new_events;
1172 pc->current_arm = 0;
1173 pc->new_events = 0;
1174 if (!pc->task.closing) {
1175 if ((update_events & (EPOLLHUP | EPOLLERR)) && !pconnection_rclosed(pc) && !pconnection_wclosed(pc))
1176 pconnection_maybe_connect_lh(pc);
1177 else
1178 pconnection_connected_lh(pc); /* Non error event means we are connected */
1179 if (update_events & EPOLLOUT) {
1180 pc->write_blocked = false;
1181 if (pc->wbuf_remaining > 0)
1182 immediate_write = true;
1183 }
1184 if (update_events & EPOLLIN)
1185 pc->read_blocked = false;
1186 }
1187 }
1188
1189 if (pc->task.closing && pconnection_is_final(pc)) {
1190 unlock(&pc->task.mutex);
1191 pconnection_cleanup(pc);
1192 return NULL;
1193 }
1194
1195 unlock(&pc->task.mutex);
1196 pc->hog_count++; // working task doing work
1197
1198 if (waking) {
1199 pn_connection_t *c = pc->driver.connection;
1200 pn_collector_put(pn_connection_collector(c), PN_OBJECT, c, PN_CONNECTION_WAKE);
1201 waking = false;
1202 }
1203
1204 if (immediate_write) {
1205 immediate_write = false;
1206 write_flush(pc);
1207 }
1208
1209 if (!pconnection_rclosed(pc)) {
1210 pn_rwbytes_t rbuf = pn_connection_driver_read_buffer(&pc->driver);
1211 if (rbuf.size > 0 && !pc->read_blocked) {
1212 ssize_t n = read(pc->psocket.epoll_io.fd, rbuf.start, rbuf.size);
1213 if (n > 0) {
1214 pn_connection_driver_read_done(&pc->driver, n);
1215 // If n == rbuf.size then we should enlarge the buffer and see if there is more to read
1216 if ((size_t)n==rbuf.size) {
1217 rbuf = pn_connection_driver_read_buffer_sized(&pc->driver, n*2);
1218 if (rbuf.size > 0) {
1219 n = read(pc->psocket.epoll_io.fd, rbuf.start, rbuf.size);
1220 if (n > 0) {
1221 pn_connection_driver_read_done(&pc->driver, n);
1222 }
1223 }
1224 }
1225 // If we didn't read a full buffer (either in the first or second read) then we are blocked
1226 if ((size_t)n < rbuf.size && !pn_connection_driver_read_closed(&pc->driver)) {
1227 pc->read_blocked = true;
1228 }
1229 pc->output_drained = false;
1230 pconnection_tick(pc); /* check for tick changes. */
1231 tick_required = false;
1232 pc->io_doublecheck = false;
1233 }
1234 // Need to check for EOF and errors for either read
1235 if (n == 0) {
1236 pc->read_blocked = true;
1237 pn_connection_driver_read_close(&pc->driver);
1238 } else if (n < 0) {
1239 if (errno == EWOULDBLOCK) {
1240 pc->read_blocked = true;
1241 } else if (!(errno == EAGAIN || errno == EINTR)) {
1242 psocket_error(&pc->psocket, errno, pc->disconnected ? "disconnected" : "on read from");
1243 }
1244 }
1245 }
1246 } else {
1247 pc->read_blocked = true;
1248 }
1249
1250 if (tick_required) {
1251 pconnection_tick(pc); /* check for tick changes. */
1252 tick_required = false;
1253 pc->output_drained = false;
1254 }
1255
1256 if (topup) {
1257 // If there was anything new to topup, we have it by now.
1258 return NULL; // caller already owns the batch
1259 }
1260
1261 if (pconnection_has_event(pc)) {
1262 pc->output_drained = false;
1263 return &pc->batch;
1264 }
1265
1266 write_flush(pc);
1267
1268 lock(&pc->task.mutex);
1269 if (pc->task.closing && pconnection_is_final(pc)) {
1270 unlock(&pc->task.mutex);
1271 pconnection_cleanup(pc);
1272 return NULL;
1273 }
1274
1275 // Never stop working while work remains. hog_count exception to this rule is elsewhere.
1276
1277 if (pconnection_work_pending(pc)) {
1278 goto retry; // TODO: get rid of goto without adding more locking
1279 }
1280
1281 pc->task.working = false;
1282 pc->hog_count = 0;
1283 if (pn_connection_driver_finished(&pc->driver)) {
1284 pconnection_begin_close(pc);
1285 if (pconnection_is_final(pc)) {
1286 unlock(&pc->task.mutex);
1287 pconnection_cleanup(pc);
1288 return NULL;
1289 }
1290 }
1291
1292 // check one last time for new io before context switch
1293 bool workers_free;
1294 pn_proactor_t *p = pc->task.proactor;
1295 lock(&p->sched_mutex);
1296 workers_free = (p->suspend_list_head != NULL);
1297 unlock(&p->sched_mutex);
1298 if (workers_free && !pc->task.closing && !pc->io_doublecheck) {
1299 pc->io_doublecheck = true;
1300 pc->read_blocked = false;
1301 pc->write_blocked = false;
1302 pc->task.working = true;
1303 goto retry;
1304 }
1305
1306 int wanted = pconnection_rearm_check(pc); // holds rearm_mutex until pconnection_rearm() below
1307
1308 unlock(&pc->task.mutex);
1309 if (wanted) pconnection_rearm(pc, wanted); // May free pc on another thread. Return right away.
1310 return NULL;
1311 }
1312
1313 void configure_socket(int sock) {
1314 int flags = fcntl(sock, F_GETFL);
1315 flags |= O_NONBLOCK;
1316 (void)fcntl(sock, F_SETFL, flags); // TODO: check for error
1317
1318 int tcp_nodelay = 1;
1319 (void)setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (void*) &tcp_nodelay, sizeof(tcp_nodelay));
1320 }
1321
1322 /* Called with task.lock held */
1323 void pconnection_connected_lh(pconnection_t *pc) {
1324 if (!pc->connected) {
1325 pc->connected = true;
1326 if (pc->addrinfo) {
1327 freeaddrinfo(pc->addrinfo);
1328 pc->addrinfo = NULL;
1329 }
1330 pc->ai = NULL;
1331 socklen_t len = sizeof(pc->remote.ss);
1332 (void)getpeername(pc->psocket.epoll_io.fd, (struct sockaddr*)&pc->remote.ss, &len);
1333 }
1334 }
1335
1336 /* multi-address connections may call pconnection_start multiple times with diffferent FDs */
1337 static void pconnection_start(pconnection_t *pc, int fd) {
1338 int efd = pc->task.proactor->epollfd;
1339 /* Get the local socket name now, get the peer name in pconnection_connected */
1340 socklen_t len = sizeof(pc->local.ss);
1341 (void)getsockname(fd, (struct sockaddr*)&pc->local.ss, &len);
1342
1343 epoll_extended_t *ee = &pc->psocket.epoll_io;
1344 if (ee->polling) { /* This is not the first attempt, stop polling and close the old FD */
1345 int fd = ee->fd; /* Save fd, it will be set to -1 by stop_polling */
1346 stop_polling(ee, efd);
1347 pclosefd(pc->task.proactor, fd);
1348 }
1349 ee->fd = fd;
1350 pc->current_arm = ee->wanted = EPOLLIN | EPOLLOUT;
1351 start_polling(ee, efd); // TODO: check for error
1352 }
1353
1354 /* Called on initial connect, and if connection fails to try another address */
1355 static void pconnection_maybe_connect_lh(pconnection_t *pc) {
1356 errno = 0;
1357 if (!pc->connected) { /* Not yet connected */
1358 while (pc->ai) { /* Have an address */
1359 struct addrinfo *ai = pc->ai;
1360 pc->ai = pc->ai->ai_next; /* Move to next address in case this fails */
1361 int fd = socket(ai->ai_family, SOCK_STREAM, 0);
1362 if (fd >= 0) {
1363 configure_socket(fd);
1364 if (!connect(fd, ai->ai_addr, ai->ai_addrlen) || errno == EINPROGRESS) {
1365 pconnection_start(pc, fd);
1366 return; /* Async connection started */
1367 } else {
1368 close(fd);
1369 }
1370 }
1371 /* connect failed immediately, go round the loop to try the next addr */
1372 }
1373 freeaddrinfo(pc->addrinfo);
1374 pc->addrinfo = NULL;
1375 /* If there was a previous attempted connection, let the poller discover the
1376 errno from its socket, otherwise set the current error. */
1377 if (pc->psocket.epoll_io.fd < 0) {
1378 psocket_error(&pc->psocket, errno ? errno : ENOTCONN, "on connect");
1379 }
1380 }
1381 pc->disconnected = true;
1382 }
1383
1384 int pgetaddrinfo(const char *host, const char *port, int flags, struct addrinfo **res)
1385 {
1386 struct addrinfo hints = { 0 };
1387 hints.ai_family = AF_UNSPEC;
1388 hints.ai_socktype = SOCK_STREAM;
1389 hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG | flags;
1390 return getaddrinfo(host, port, &hints, res);
1391 }
1392
1393 static inline bool is_inactive(pn_proactor_t *p) {
1394 return (!p->tasks && !p->disconnects_pending && !p->timeout_set && !p->shutting_down);
1395 }
1396
1397 /* If inactive set need_inactive and return true if poller needs to be unblocked */
1398 bool schedule_if_inactive(pn_proactor_t *p) {
1399 if (is_inactive(p)) {
1400 p->need_inactive = true;
1401 return schedule(&p->task);
1402 }
1403 return false;
1404 }
1405
1406 void pn_proactor_connect2(pn_proactor_t *p, pn_connection_t *c, pn_transport_t *t, const char *addr) {
1407 size_t addrlen = strlen(addr);
1408 pconnection_t *pc = (pconnection_t*) malloc(sizeof(pconnection_t)+addrlen);
1409 assert(pc); // TODO: memory safety
1410 const char *err = pconnection_setup(pc, p, c, t, false, addr, addrlen);
1411 if (err) { /* TODO aconway 2017-09-13: errors must be reported as events */
1412 PN_LOG_DEFAULT(PN_SUBSYSTEM_EVENT, PN_LEVEL_ERROR, "pn_proactor_connect failure: %s", err);
1413 return;
1414 }
1415 // TODO: check case of proactor shutting down
1416
1417 lock(&pc->task.mutex);
1418 proactor_add(&pc->task);
1419 pn_connection_open(pc->driver.connection); /* Auto-open */
1420
1421 bool notify = false;
1422
1423 if (pc->disconnected) {
1424 notify = schedule(&pc->task); /* Error during initialization */
1425 } else {
1426 int gai_error = pgetaddrinfo(pc->host, pc->port, 0, &pc->addrinfo);
1427 if (!gai_error) {
1428 pn_connection_open(pc->driver.connection); /* Auto-open */
1429 pc->ai = pc->addrinfo;
1430 pconnection_maybe_connect_lh(pc); /* Start connection attempts */
1431 if (pc->disconnected) notify = schedule(&pc->task);
1432 } else {
1433 psocket_gai_error(&pc->psocket, gai_error, "connect to ");
1434 notify = schedule(&pc->task);
1435 lock(&p->task.mutex);
1436 notify |= schedule_if_inactive(p);
1437 unlock(&p->task.mutex);
1438 }
1439 }
1440 /* We need to issue INACTIVE on immediate failure */
1441 unlock(&pc->task.mutex);
1442 if (notify) notify_poller(p);
1443 }
1444
1445 static void pconnection_tick(pconnection_t *pc) {
1446 pn_transport_t *t = pc->driver.transport;
1447 if (pn_transport_get_idle_timeout(t) || pn_transport_get_remote_idle_timeout(t)) {
1448 uint64_t now = pn_proactor_now_64();
1449 uint64_t next = pn_transport_tick(t, now);
1450 if (next) {
1451 lock(&pc->task.mutex);
1452 pc->expected_timeout = next;
1453 unlock(&pc->task.mutex);
1454 if (pni_timer_set(pc->timer, next))
1455 notify_poller(pc->task.proactor);
1456 }
1457 }
1458 }
1459
1460 void pn_connection_wake(pn_connection_t* c) {
1461 pconnection_t *pc = get_pconnection(c);
1462 if (pc) {
1463 pn_proactor_t *p = pc->task.proactor;
1464 bool notify = false;
1465
1466 lock(&pc->task.mutex);
1467 if (!pc->task.closing) {
1468 notify = pni_task_wake(&pc->task);
1469 }
1470 unlock(&pc->task.mutex);
1471 if (notify) notify_poller(p);
1472 }
1473 }
1474
1475 void pn_proactor_release_connection(pn_connection_t *c) {
1476 pconnection_t *pc = get_pconnection(c);
1477 if (pc) {
1478 bool notify = false;
1479 pn_proactor_t *p = pc->task.proactor;
1480 set_pconnection(c, NULL);
1481 lock(&pc->task.mutex);
1482 pn_connection_driver_release_connection(&pc->driver);
1483 pconnection_begin_close(pc);
1484 notify = schedule(&pc->task);
1485 unlock(&pc->task.mutex);
1486 if (notify) notify_poller(p);
1487 }
1488 }
1489
1490 // ========================================================================
1491 // listener
1492 // ========================================================================
1493
1494 pn_listener_t *pn_event_listener(pn_event_t *e) {
1495 return (pn_event_class(e) == PN_CLASSCLASS(pn_listener)) ? (pn_listener_t*)pn_event_context(e) : NULL;
1496 }
1497
1498 pn_listener_t *pn_listener() {
1499 pn_listener_t *l = (pn_listener_t*)calloc(1, sizeof(pn_listener_t));
1500 if (l) {
1501 l->batch.next_event = listener_batch_next;
1502 l->collector = pn_collector();
1503 l->condition = pn_condition();
1504 l->attachments = pn_record();
1505 if (!l->condition || !l->collector || !l->attachments) {
1506 pn_listener_free(l);
1507 return NULL;
1508 }
1509 pn_proactor_t *unknown = NULL; // won't know until pn_proactor_listen
1510 task_init(&l->task, LISTENER, unknown);
1511 }
1512 return l;
1513 }
1514
1515 void pn_proactor_listen(pn_proactor_t *p, pn_listener_t *l, const char *addr, int backlog)
1516 {
1517 // TODO: check listener not already listening for this or another proactor
1518 lock(&l->task.mutex);
1519 l->task.proactor = p;
1520
1521 l->pending_accepteds = (accepted_t*)calloc(backlog, sizeof(accepted_t));
1522 assert(l->pending_accepteds);
1523 l->backlog = backlog;
1524
1525 pni_parse_addr(addr, l->addr_buf, sizeof(l->addr_buf), &l->host, &l->port);
1526
1527 struct addrinfo *addrinfo = NULL;
1528 int gai_err = pgetaddrinfo(l->host, l->port, AI_PASSIVE | AI_ALL, &addrinfo);
1529 if (!gai_err) {
1530 /* Count addresses, allocate enough space for sockets */
1531 size_t len = 0;
1532 for (struct addrinfo *ai = addrinfo; ai; ai = ai->ai_next) {
1533 ++len;
1534 }
1535 assert(len > 0); /* guaranteed by getaddrinfo */
1536 l->acceptors = (acceptor_t*)calloc(len, sizeof(acceptor_t));
1537 assert(l->acceptors); /* TODO aconway 2017-05-05: memory safety */
1538 l->acceptors_size = 0;
1539 uint16_t dynamic_port = 0; /* Record dynamic port from first bind(0) */
1540 /* Find working listen addresses */
1541 for (struct addrinfo *ai = addrinfo; ai; ai = ai->ai_next) {
1542 if (dynamic_port) set_port(ai->ai_addr, dynamic_port);
1543 int fd = socket(ai->ai_family, SOCK_STREAM, ai->ai_protocol);
1544 static int on = 1;
1545 if (fd >= 0) {
1546 configure_socket(fd);
1547 if (!setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) &&
1548 /* We listen to v4/v6 on separate sockets, don't let v6 listen for v4 */
1549 (ai->ai_family != AF_INET6 ||
1550 !setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on))) &&
1551 !bind(fd, ai->ai_addr, ai->ai_addrlen) &&
1552 !listen(fd, backlog))
1553 {
1554 acceptor_t *acceptor = &l->acceptors[l->acceptors_size++];
1555 /* Get actual address */
1556 socklen_t len = pn_netaddr_socklen(&acceptor->addr);
1557 (void)getsockname(fd, (struct sockaddr*)(&acceptor->addr.ss), &len);
1558 if (acceptor == l->acceptors) { /* First acceptor, check for dynamic port */
1559 dynamic_port = check_dynamic_port(ai->ai_addr, pn_netaddr_sockaddr(&acceptor->addr));
1560 } else { /* Link addr to previous addr */
1561 (acceptor-1)->addr.next = &acceptor->addr;
1562 }
1563
1564 acceptor->listener = l;
1565 psocket_t *ps = &acceptor->psocket;
1566 psocket_init(ps, LISTENER_IO);
1567 ps->epoll_io.fd = fd;
1568 ps->epoll_io.wanted = EPOLLIN;
1569 ps->epoll_io.polling = false;
1570 start_polling(&ps->epoll_io, l->task.proactor->epollfd); // TODO: check for error
1571 l->active_count++;
1572 acceptor->armed = true;
1573 } else {
1574 close(fd);
1575 }
1576 }
1577 }
1578 }
1579 if (addrinfo) {
1580 freeaddrinfo(addrinfo);
1581 }
1582 bool notify = schedule(&l->task);
1583
1584 if (l->acceptors_size == 0) { /* All failed, create dummy socket with an error */
1585 l->acceptors = (acceptor_t*)realloc(l->acceptors, sizeof(acceptor_t));
1586 l->acceptors_size = 1;
1587 memset(l->acceptors, 0, sizeof(acceptor_t));
1588 psocket_init(&l->acceptors[0].psocket, LISTENER_IO);
1589 l->acceptors[0].listener = l;
1590 if (gai_err) {
1591 psocket_gai_error(&l->acceptors[0].psocket, gai_err, "listen on");
1592 } else {
1593 psocket_error(&l->acceptors[0].psocket, errno, "listen on");
1594 }
1595 } else {
1596 pn_collector_put(l->collector, PN_CLASSCLASS(pn_listener), l, PN_LISTENER_OPEN);
1597 }
1598 proactor_add(&l->task);
1599 unlock(&l->task.mutex);
1600 if (notify) notify_poller(p);
1601 return;
1602 }
1603
1604 // call with lock held and task.working false
1605 static inline bool listener_can_free(pn_listener_t *l) {
1606 return l->task.closing && l->close_dispatched && !l->task.ready && !l->active_count && !l->overflow_count;
1607 }
1608
1609 static inline void listener_final_free(pn_listener_t *l) {
1610 task_finalize(&l->task);
1611 free(l->acceptors);
1612 free(l->pending_accepteds);
1613 free(l);
1614 }
1615
1616 void pn_listener_free(pn_listener_t *l) {
1617 /* Note at this point either the listener has never been used (freed by user)
1618 or it has been closed, so all its sockets are closed.
1619 */
1620 if (l) {
1621 bool can_free = true;
1622 if (l->collector) pn_collector_free(l->collector);
1623 if (l->condition) pn_condition_free(l->condition);
1624 if (l->attachments) pn_free(l->attachments);
1625 lock(&l->task.mutex);
1626 if (l->task.proactor) {
1627 can_free = proactor_remove(&l->task);
1628 }
1629 unlock(&l->task.mutex);
1630 if (can_free)
1631 listener_final_free(l);
1632 }
1633 }
1634
1635 /* Always call with lock held so it can be unlocked around overflow processing. */
1636 static void listener_begin_close(pn_listener_t* l) {
1637 if (!l->task.closing) {
1638 l->task.closing = true;
1639 bool polling = !l->task.proactor->shutting_down; // Is poller still running?
1640
1641 /* Close all listening sockets */
1642 for (size_t i = 0; i < l->acceptors_size; ++i) {
1643 acceptor_t *a = &l->acceptors[i];
1644 psocket_t *ps = &a->psocket;
1645 if (ps->epoll_io.fd >= 0) {
1646 if (a->armed && polling) {
1647 shutdown(ps->epoll_io.fd, SHUT_RD); // Force epoll event and callback
1648 } else {
1649 int fd = ps->epoll_io.fd;
1650 stop_polling(&ps->epoll_io, l->task.proactor->epollfd);
1651 close(fd);
1652 l->active_count--;
1653 }
1654 }
1655 }
1656 /* Close all sockets waiting for a pn_listener_accept2() */
1657 accepted_t *a = listener_accepted_next(l);
1658 while (a) {
1659 close(a->accepted_fd);
1660 a->accepted_fd = -1;
1661 a = listener_accepted_next(l);
1662 }
1663 assert(!l->pending_count);
1664
1665 pn_collector_put(l->collector, PN_CLASSCLASS(pn_listener), l, PN_LISTENER_CLOSE);
1666 }
1667 }
1668
1669 void pn_listener_close(pn_listener_t* l) {
1670 bool notify = false;
1671 lock(&l->task.mutex);
1672 pn_proactor_t *p = l->task.proactor;
1673 if (p && !l->task.closing) {
1674 listener_begin_close(l);
1675 notify = schedule(&l->task);
1676 }
1677 unlock(&l->task.mutex);
1678 if (notify) notify_poller(p);
1679 }
1680
1681 static void listener_forced_shutdown(pn_listener_t *l) {
1682 // Called by proactor_free, no competing threads, no epoll activity.
1683 lock(&l->task.mutex); // needed because of interaction with proactor_rearm_overflow
1684 listener_begin_close(l);
1685 unlock(&l->task.mutex);
1686 // pconnection_process will never be called again. Zero everything.
1687 l->task.ready = 0;
1688 l->close_dispatched = true;
1689 l->active_count = 0;
1690 assert(listener_can_free(l));
1691 pn_listener_free(l);
1692 }
1693
1694 /* Accept a connection as part of listener_process(). Called with listener task lock held. */
1695 /* Keep on accepting until we fill the backlog, would block or get an error */
1696 static void listener_accept_lh(psocket_t *ps) {
1697 pn_listener_t *l = psocket_listener(ps);
1698 while (l->pending_first+l->pending_count < l->backlog) {
1699 int fd = accept(ps->epoll_io.fd, NULL, 0);
1700 if (fd >= 0) {
1701 accepted_t accepted = {.accepted_fd = fd} ;
1702 listener_accepted_append(l, accepted);
1703 } else {
1704 int err = errno;
1705 if (err == ENFILE || err == EMFILE) {
1706 acceptor_t *acceptor = psocket_acceptor(ps);
1707 acceptor_set_overflow(acceptor);
1708 } else if (err != EWOULDBLOCK) {
1709 psocket_error(ps, err, "accept");
1710 }
1711 return;
1712 }
1713 }
1714 }
1715
1716 /* Process a listening socket */
1717 static pn_event_batch_t *listener_process(pn_listener_t *l, int n_events, bool tsk_ready) {
1718 // TODO: some parallelization of the accept mechanism.
1719 // pn_listener_t *l = psocket_listener(ps);
1720 // acceptor_t *a = psocket_acceptor(ps);
1721
1722 lock(&l->task.mutex);
1723 if (n_events) {
1724 for (size_t i = 0; i < l->acceptors_size; i++) {
1725 psocket_t *ps = &l->acceptors[i].psocket;
1726 if (ps->working_io_events) {
1727 uint32_t events = ps->working_io_events;
1728 ps->working_io_events = 0;
1729 if (l->task.closing) {
1730 l->acceptors[i].armed = false;
1731 int fd = ps->epoll_io.fd;
1732 stop_polling(&ps->epoll_io, l->task.proactor->epollfd);
1733 close(fd);
1734 l->active_count--;
1735 } else {
1736 l->acceptors[i].armed = false;
1737 if (events & EPOLLRDHUP) {
1738 /* Calls listener_begin_close which closes all the listener's sockets */
1739 psocket_error(ps, errno, "listener epoll");
1740 } else if (!l->task.closing && events & EPOLLIN) {
1741 listener_accept_lh(ps);
1742 }
1743 }
1744 }
1745 }
1746 }
1747 if (tsk_ready) {
1748 schedule_done(&l->task); // callback accounting
1749 }
1750 pn_event_batch_t *lb = NULL;
1751 if (!l->task.working) {
1752 l->task.working = true;
1753 if (listener_has_event(l))
1754 lb = &l->batch;
1755 else {
1756 l->task.working = false;
1757 if (listener_can_free(l)) {
1758 unlock(&l->task.mutex);
1759 pn_listener_free(l);
1760 return NULL;
1761 }
1762 }
1763 }
1764 unlock(&l->task.mutex);
1765 return lb;
1766 }
1767
1768 static pn_event_t *listener_batch_next(pn_event_batch_t *batch) {
1769 pn_listener_t *l = batch_listener(batch);
1770 lock(&l->task.mutex);
1771 pn_event_t *e = pn_collector_next(l->collector);
1772 if (!e && l->pending_count) {
1773 // empty collector means pn_collector_put() will not coalesce
1774 pn_collector_put(l->collector, PN_CLASSCLASS(pn_listener), l, PN_LISTENER_ACCEPT);
1775 e = pn_collector_next(l->collector);
1776 }
1777 if (e && pn_event_type(e) == PN_LISTENER_CLOSE)
1778 l->close_dispatched = true;
1779 unlock(&l->task.mutex);
1780 return pni_log_event(l, e);
1781 }
1782
1783 static void listener_done(pn_listener_t *l) {
1784 pn_proactor_t *p = l->task.proactor;
1785 tslot_t *ts = l->task.runner;
1786
1787 lock(&l->task.mutex);
1788
1789 if (l->close_dispatched && l->overflow_count) {
1790 unlock(&l->task.mutex);
1791 /* Remove all acceptors from the overflow list. closing flag prevents re-insertion.*/
1792 proactor_rearm_overflow(pn_listener_proactor(l));
1793 lock(&l->task.mutex);
1794 assert(l->overflow_count == 0);
1795 }
1796
1797 // Just in case the app didn't accept all the pending accepts
1798 // Shuffle the list back to start at 0
1799 memmove(&l->pending_accepteds[0], &l->pending_accepteds[l->pending_first], l->pending_count * sizeof(accepted_t));
1800 l->pending_first = 0;
1801
1802 if (!l->task.closing) {
1803 for (size_t i = 0; i < l->acceptors_size; i++) {
1804 acceptor_t *a = &l->acceptors[i];
1805 psocket_t *ps = &a->psocket;
1806
1807 // Rearm acceptor when appropriate
1808 if (ps->epoll_io.polling && l->pending_count==0 && !a->overflowed) {
1809 if (!a->armed) {
1810 rearm(l->task.proactor, &ps->epoll_io);
1811 a->armed = true;
1812 }
1813 }
1814 }
1815 }
1816
1817 bool notify = false;
1818 l->task.working = false;
1819
1820 if (listener_can_free(l)) {
1821 unlock(&l->task.mutex);
1822 pn_listener_free(l);
1823 lock(&p->sched_mutex);
1824 tslot_t *resume_thread;
1825 notify = unassign_thread(p, ts, UNUSED, &resume_thread);
1826 unlock(&p->sched_mutex);
1827 if (notify) notify_poller(p);
1828 if (resume_thread) resume(p, resume_thread);
1829 return;
1830 } else if (listener_has_event(l))
1831 notify = schedule(&l->task);
1832 unlock(&l->task.mutex);
1833
1834 lock(&p->sched_mutex);
1835 tslot_t *resume_thread;
1836 if (unassign_thread(p, ts, UNUSED, &resume_thread))
1837 notify = true;
1838 unlock(&p->sched_mutex);
1839 if (notify) notify_poller(p);
1840 if (resume_thread) resume(p, resume_thread);
1841 }
1842
1843 pn_proactor_t *pn_listener_proactor(pn_listener_t* l) {
1844 return l ? l->task.proactor : NULL;
1845 }
1846
1847 pn_condition_t* pn_listener_condition(pn_listener_t* l) {
1848 return l->condition;
1849 }
1850
1851 void *pn_listener_get_context(pn_listener_t *l) {
1852 return l->listener_context;
1853 }
1854
1855 void pn_listener_set_context(pn_listener_t *l, void *context) {
1856 l->listener_context = context;
1857 }
1858
1859 pn_record_t *pn_listener_attachments(pn_listener_t *l) {
1860 return l->attachments;
1861 }
1862
1863 void pn_listener_accept2(pn_listener_t *l, pn_connection_t *c, pn_transport_t *t) {
1864 pconnection_t *pc = (pconnection_t*) malloc(sizeof(pconnection_t));
1865 pn_proactor_t *p = pn_listener_proactor(l);
1866 assert(pc && p); // TODO: memory safety
1867 const char *err = pconnection_setup(pc, p, c, t, true, "", 0);
1868 if (err) {
1869 PN_LOG_DEFAULT(PN_SUBSYSTEM_EVENT, PN_LEVEL_ERROR, "pn_listener_accept failure: %s", err);
1870 return;
1871 }
1872 // TODO: fuller sanity check on input args
1873
1874 int err2 = 0;
1875 int fd = -1;
1876 bool notify = false;
1877 lock(&l->task.mutex);
1878 if (l->task.closing)
1879 err2 = EBADF;
1880 else {
1881 accepted_t *a = listener_accepted_next(l);
1882 if (a) {
1883 fd = a->accepted_fd;
1884 a->accepted_fd = -1;
1885 }
1886 else err2 = EWOULDBLOCK;
1887 }
1888
1889 proactor_add(&pc->task);
1890 lock(&pc->task.mutex);
1891 if (fd >= 0) {
1892 configure_socket(fd);
1893 pconnection_start(pc, fd);
1894 pconnection_connected_lh(pc);
1895 }
1896 else
1897 psocket_error(&pc->psocket, err2, "pn_listener_accept");
1898 if (!l->task.working && listener_has_event(l))
1899 notify = schedule(&l->task);
1900 unlock(&pc->task.mutex);
1901 unlock(&l->task.mutex);
1902 if (notify) notify_poller(p);
1903 }
1904
1905
1906 // ========================================================================
1907 // proactor
1908 // ========================================================================
1909
1910 // Call with sched_mutex. Alloc calls are expensive but only used when thread_count changes.
1911 static void grow_poller_bufs(pn_proactor_t* p) {
1912 // call if p->thread_count > p->thread_capacity
1913 assert(p->thread_count == 0 || p->thread_count > p->thread_capacity);
1914 do {
1915 p->thread_capacity += 8;
1916 } while (p->thread_count > p->thread_capacity);
1917
1918 p->warm_runnables = (task_t **) realloc(p->warm_runnables, p->thread_capacity * sizeof(task_t *));
1919 p->resume_list = (tslot_t **) realloc(p->resume_list, p->thread_capacity * sizeof(tslot_t *));
1920
1921 int old_cap = p->runnables_capacity;
1922 if (p->runnables_capacity == 0)
1923 p->runnables_capacity = 16;
1924 else if (p->runnables_capacity < p->thread_capacity)
1925 p->runnables_capacity = p->thread_capacity;
1926 if (p->runnables_capacity != old_cap) {
1927 p->runnables = (task_t **) realloc(p->runnables, p->runnables_capacity * sizeof(task_t *));
1928 p->kevents_capacity = p->runnables_capacity;
1929 size_t sz = p->kevents_capacity * sizeof(struct epoll_event);
1930 p->kevents = (struct epoll_event *) realloc(p->kevents, sz);
1931 memset(p->kevents, 0, sz);
1932 }
1933 }
1934
1935 /* Set up an epoll_extended_t to be used for ready list schedule() or interrupts */
1936 static void epoll_eventfd_init(epoll_extended_t *ee, int eventfd, int epollfd, bool always_set) {
1937 ee->fd = eventfd;
1938 ee->type = EVENT_FD;
1939 if (always_set) {
1940 uint64_t increment = 1;
1941 if (write(eventfd, &increment, sizeof(uint64_t)) != sizeof(uint64_t))
1942 EPOLL_FATAL("setting eventfd", errno);
1943 // eventfd is set forever. No reads, just rearms as needed.
1944 ee->wanted = 0;
1945 } else {
1946 ee->wanted = EPOLLIN;
1947 }
1948 ee->polling = false;
1949 start_polling(ee, epollfd); // TODO: check for error
1950 if (always_set)
1951 ee->wanted = EPOLLIN; // for all subsequent rearms
1952 }
1953
1954 pn_proactor_t *pn_proactor() {
1955 if (getenv("PNI_EPOLL_NOWARM")) pni_warm_sched = false;
1956 if (getenv("PNI_EPOLL_IMMEDIATE")) pni_immediate = true;
1957 if (getenv("PNI_EPOLL_SPINS")) pni_spins = atoi(getenv("PNI_EPOLL_SPINS"));
1958 pn_proactor_t *p = (pn_proactor_t*)calloc(1, sizeof(*p));
1959 if (!p) return NULL;
1960 p->epollfd = p->eventfd = -1;
1961 task_init(&p->task, PROACTOR, p);
1962 pmutex_init(&p->eventfd_mutex);
1963 pmutex_init(&p->sched_mutex);
1964 pmutex_init(&p->tslot_mutex);
1965 pmutex_init(&p->timeout_mutex);
1966
1967 if ((p->epollfd = epoll_create(1)) >= 0) {
1968 if ((p->eventfd = eventfd(0, EFD_NONBLOCK)) >= 0) {
1969 if ((p->interruptfd = eventfd(0, EFD_NONBLOCK)) >= 0) {
1970 if (pni_timer_manager_init(&p->timer_manager))
1971 if ((p->collector = pn_collector()) != NULL) {
1972 p->batch.next_event = &proactor_batch_next;
1973 start_polling(&p->timer_manager.epoll_timer, p->epollfd); // TODO: check for error
1974 epoll_eventfd_init(&p->epoll_schedule, p->eventfd, p->epollfd, true);
1975 epoll_eventfd_init(&p->epoll_interrupt, p->interruptfd, p->epollfd, false);
1976 p->tslot_map = pn_hash(PN_VOID, 0, 0.75);
1977 grow_poller_bufs(p);
1978 p->ready_list_generation = 1;
1979 return p;
1980 }
1981 }
1982 }
1983 }
1984 if (p->epollfd >= 0) close(p->epollfd);
1985 if (p->eventfd >= 0) close(p->eventfd);
1986 if (p->interruptfd >= 0) close(p->interruptfd);
1987 pni_timer_manager_finalize(&p->timer_manager);
1988 pmutex_finalize(&p->timeout_mutex);
1989 pmutex_finalize(&p->tslot_mutex);
1990 pmutex_finalize(&p->sched_mutex);
1991 pmutex_finalize(&p->eventfd_mutex);
1992 if (p->collector) pn_free(p->collector);
1993 assert(p->thread_count == 0);
1994 free (p);
1995 return NULL;
1996 }
1997
1998 void pn_proactor_free(pn_proactor_t *p) {
1999 // No competing threads, not even a pending timer
2000 p->shutting_down = true;
2001 close(p->epollfd);
2002 p->epollfd = -1;
2003 close(p->eventfd);
2004 p->eventfd = -1;
2005 close(p->interruptfd);
2006 p->interruptfd = -1;
2007 while (p->tasks) {
2008 task_t *tsk = p->tasks;
2009 p->tasks = tsk->next;
2010 switch (tsk->type) {
2011 case PCONNECTION:
2012 pconnection_forced_shutdown(task_pconnection(tsk));
2013 break;
2014 case LISTENER:
2015 listener_forced_shutdown(task_listener(tsk));
2016 break;
2017 default:
2018 break;
2019 }
2020 }
2021
2022 pni_timer_manager_finalize(&p->timer_manager);
2023 pn_collector_free(p->collector);
2024 pmutex_finalize(&p->timeout_mutex);
2025 pmutex_finalize(&p->tslot_mutex);
2026 pmutex_finalize(&p->sched_mutex);
2027 pmutex_finalize(&p->eventfd_mutex);
2028 task_finalize(&p->task);
2029 for (pn_handle_t entry = pn_hash_head(p->tslot_map); entry; entry = pn_hash_next(p->tslot_map, entry)) {
2030 tslot_t *ts = (tslot_t *) pn_hash_value(p->tslot_map, entry);
2031 pmutex_finalize(&ts->mutex);
2032 free(ts);
2033 }
2034 pn_free(p->tslot_map);
2035 free(p->kevents);
2036 free(p->runnables);
2037 free(p->warm_runnables);
2038 free(p->resume_list);
2039 free(p);
2040 }
2041
2042 pn_proactor_t *pn_event_proactor(pn_event_t *e) {
2043 if (pn_event_class(e) == PN_CLASSCLASS(pn_proactor)) return (pn_proactor_t*)pn_event_context(e);
2044 pn_listener_t *l = pn_event_listener(e);
2045 if (l) return l->task.proactor;
2046 pn_connection_t *c = pn_event_connection(e);
2047 if (c) return pn_connection_proactor(c);
2048 return NULL;
2049 }
2050
2051 static void proactor_add_event(pn_proactor_t *p, pn_event_type_t t) {
2052 pn_collector_put(p->collector, PN_CLASSCLASS(pn_proactor), p, t);
2053 }
2054
2055 // Call with lock held. Leave unchanged if events pending.
2056 // There can be multiple interrupts but only one inside the collector to avoid coalescing.
2057 // Return true if there is an event in the collector.
2058 static bool proactor_update_batch(pn_proactor_t *p) {
2059 if (proactor_has_event(p))
2060 return true;
2061
2062 if (p->need_timeout) {
2063 p->need_timeout = false;
2064 p->timeout_set = false;
2065 proactor_add_event(p, PN_PROACTOR_TIMEOUT);
2066 return true;
2067 }
2068 if (p->need_interrupt) {
2069 p->need_interrupt = false;
2070 proactor_add_event(p, PN_PROACTOR_INTERRUPT);
2071 return true;
2072 }
2073 if (p->need_inactive) {
2074 p->need_inactive = false;
2075 proactor_add_event(p, PN_PROACTOR_INACTIVE);
2076 return true;
2077 }
2078 return false;
2079 }
2080
2081 static pn_event_t *proactor_batch_next(pn_event_batch_t *batch) {
2082 pn_proactor_t *p = batch_proactor(batch);
2083 lock(&p->task.mutex);
2084 proactor_update_batch(p);
2085 pn_event_t *e = pn_collector_next(p->collector);
2086 if (e) {
2087 p->current_event_type = pn_event_type(e);
2088 if (p->current_event_type == PN_PROACTOR_TIMEOUT)
2089 p->timeout_processed = true;
2090 }
2091 unlock(&p->task.mutex);
2092 return pni_log_event(p, e);
2093 }
2094
2095 static pn_event_batch_t *proactor_process(pn_proactor_t *p, bool interrupt, bool tsk_ready) {
2096 if (interrupt) {
2097 (void)read_uint64(p->interruptfd);
2098 rearm(p, &p->epoll_interrupt);
2099 }
2100 lock(&p->task.mutex);
2101 if (interrupt) {
2102 p->need_interrupt = true;
2103 }
2104 if (tsk_ready) {
2105 schedule_done(&p->task);
2106 }
2107 if (!p->task.working) { /* Can generate proactor events */
2108 if (proactor_update_batch(p)) {
2109 p->task.working = true;
2110 unlock(&p->task.mutex);
2111 return &p->batch;
2112 }
2113 }
2114 unlock(&p->task.mutex);
2115 return NULL;
2116 }
2117
2118 void proactor_add(task_t *tsk) {
2119 pn_proactor_t *p = tsk->proactor;
2120 lock(&p->task.mutex);
2121 if (p->tasks) {
2122 p->tasks->prev = tsk;
2123 tsk->next = p->tasks;
2124 }
2125 p->tasks = tsk;
2126 p->task_count++;
2127 unlock(&p->task.mutex);
2128 }
2129
2130 // call with psocket's mutex held
2131 // return true if safe for caller to free psocket
2132 bool proactor_remove(task_t *tsk) {
2133 pn_proactor_t *p = tsk->proactor;
2134 // Disassociate this task from scheduler
2135 if (!p->shutting_down) {
2136 lock(&p->sched_mutex);
2137 tsk->runner->state = DELETING;
2138 for (pn_handle_t entry = pn_hash_head(p->tslot_map); entry; entry = pn_hash_next(p->tslot_map, entry)) {
2139 tslot_t *ts = (tslot_t *) pn_hash_value(p->tslot_map, entry);
2140 if (ts->task == tsk)
2141 ts->task = NULL;
2142 if (ts->prev_task == tsk)
2143 ts->prev_task = NULL;
2144 }
2145 unlock(&p->sched_mutex);
2146 }
2147
2148 lock(&p->task.mutex);
2149 bool can_free = true;
2150 if (tsk->disconnecting) {
2151 // No longer on tasks list
2152 --p->disconnects_pending;
2153 if (--tsk->disconnect_ops != 0) {
2154 // procator_disconnect() does the free
2155 can_free = false;
2156 }
2157 }
2158 else {
2159 // normal case
2160 if (tsk->prev)
2161 tsk->prev->next = tsk->next;
2162 else {
2163 p->tasks = tsk->next;
2164 tsk->next = NULL;
2165 if (p->tasks)
2166 p->tasks->prev = NULL;
2167 }
2168 if (tsk->next) {
2169 tsk->next->prev = tsk->prev;
2170 }
2171 p->task_count--;
2172 }
2173 bool notify = schedule_if_inactive(p);
2174 unlock(&p->task.mutex);
2175 if (notify) notify_poller(p);
2176 return can_free;
2177 }
2178
2179 static tslot_t *find_tslot(pn_proactor_t *p) {
2180 pthread_t tid = pthread_self();
2181 void *v = pn_hash_get(p->tslot_map, (uintptr_t) tid);
2182 if (v)
2183 return (tslot_t *) v;
2184 tslot_t *ts = (tslot_t *) calloc(1, sizeof(tslot_t));
2185 ts->state = NEW;
2186 pmutex_init(&ts->mutex);
2187
2188 lock(&p->sched_mutex);
2189 // keep important tslot related info thread-safe when holding either the sched or tslot mutex
2190 p->thread_count++;
2191 pn_hash_put(p->tslot_map, (uintptr_t) tid, ts);
2192 unlock(&p->sched_mutex);
2193 return ts;
2194 }
2195
2196 // Called with sched lock, returns with sched lock still held.
2197 static pn_event_batch_t *process(task_t *tsk) {
2198 bool tsk_ready = false;
2199 tsk->sched_pending = false;
2200 if (tsk->sched_ready) {
2201 // update the ready status before releasing the sched_mutex
2202 tsk->sched_ready = false;
2203 tsk_ready = true;
2204 }
2205 pn_proactor_t *p = tsk->proactor;
2206 pn_event_batch_t* batch = NULL;
2207 switch (tsk->type) {
2208 case PROACTOR: {
2209 bool intr = p->sched_interrupt;
2210 if (intr) p->sched_interrupt = false;
2211 unlock(&p->sched_mutex);
2212 batch = proactor_process(p, intr, tsk_ready);
2213 break;
2214 }
2215 case PCONNECTION: {
2216 pconnection_t *pc = task_pconnection(tsk);
2217 uint32_t events = pc->psocket.sched_io_events;
2218 if (events) pc->psocket.sched_io_events = 0;
2219 unlock(&p->sched_mutex);
2220 batch = pconnection_process(pc, events, tsk_ready, false);
2221 break;
2222 }
2223 case LISTENER: {
2224 pn_listener_t *l = task_listener(tsk);
2225 int n_events = 0;
2226 for (size_t i = 0; i < l->acceptors_size; i++) {
2227 psocket_t *ps = &l->acceptors[i].psocket;
2228 if (ps->sched_io_events) {
2229 ps->working_io_events = ps->sched_io_events;
2230 ps->sched_io_events = 0;
2231 }
2232 if (ps->working_io_events)
2233 n_events++;
2234 }
2235 unlock(&p->sched_mutex);
2236 batch = listener_process(l, n_events, tsk_ready);
2237 break;
2238 }
2239 case RAW_CONNECTION: {
2240 psocket_t *ps = pni_task_raw_psocket(tsk);
2241 uint32_t events = ps->sched_io_events;
2242 if (events) ps->sched_io_events = 0;
2243 unlock(&p->sched_mutex);
2244 batch = pni_raw_connection_process(tsk, events, tsk_ready);
2245 break;
2246 }
2247 case TIMER_MANAGER: {
2248 pni_timer_manager_t *tm = &p->timer_manager;
2249 bool timeout = tm->sched_timeout;
2250 if (timeout) tm->sched_timeout = false;
2251 unlock(&p->sched_mutex);
2252 batch = pni_timer_manager_process(tm, timeout, tsk_ready);
2253 break;
2254 }
2255 default:
2256 assert(NULL);
2257 }
2258 lock(&p->sched_mutex);
2259 return batch;
2260 }
2261
2262
2263 // Call with both sched_mutex and eventfd_mutex held
2264 static void schedule_ready_list(pn_proactor_t *p) {
2265 // Append ready_list_first..ready_list_last to end of sched_ready_last
2266 // May see several in single do_epoll() if EINTR.
2267 if (p->ready_list_first) {
2268 if (p->sched_ready_last)
2269 p->sched_ready_last->ready_next = p->ready_list_first; // join them
2270 if (!p->sched_ready_first)
2271 p->sched_ready_first = p->ready_list_first;
2272 p->sched_ready_last = p->ready_list_last;
2273 p->ready_list_first = p->ready_list_last = NULL;
2274
2275 // Track sched_ready_count to know how many threads may be needed.
2276 p->sched_ready_count += p->ready_list_count;
2277 p->ready_list_count = 0;
2278 }
2279 }
2280
2281 // Call with schedule lock and eventfd lock held. Called only by poller thread.
2282 // Needs to be quick.
2283 static task_t *post_event(pn_proactor_t *p, struct epoll_event *evp) {
2284 epoll_extended_t *ee = (epoll_extended_t *) evp->data.ptr;
2285 task_t *tsk = NULL;
2286
2287 switch (ee->type) {
2288 case EVENT_FD:
2289 if (ee->fd == p->interruptfd) { /* Interrupts have their own dedicated eventfd */
2290 p->sched_interrupt = true;
2291 tsk = &p->task;
2292 tsk->sched_pending = true;
2293 }
2294 // else if (ee->fd == p->eventfd)... schedule_ready_list already performed by poller task.
2295 break;
2296 case PCONNECTION_IO: {
2297 psocket_t *ps = containerof(ee, psocket_t, epoll_io);
2298 pconnection_t *pc = psocket_pconnection(ps);
2299 assert(pc);
2300 tsk = &pc->task;
2301 ps->sched_io_events = evp->events;
2302 tsk->sched_pending = true;
2303 break;
2304 }
2305 case LISTENER_IO: {
2306 psocket_t *ps = containerof(ee, psocket_t, epoll_io);
2307 pn_listener_t *l = psocket_listener(ps);
2308 assert(l);
2309 tsk = &l->task;
2310 ps->sched_io_events = evp->events;
2311 tsk->sched_pending = true;
2312 break;
2313 }
2314 case RAW_CONNECTION_IO: {
2315 psocket_t *ps = containerof(ee, psocket_t, epoll_io);
2316 tsk = pni_psocket_raw_task(ps);
2317 ps->sched_io_events = evp->events;
2318 tsk->sched_pending = true;
2319 break;
2320 }
2321 case TIMER: {
2322 pni_timer_manager_t *tm = &p->timer_manager;
2323 tsk = &tm->task;
2324 tm->sched_timeout = true;
2325 tsk->sched_pending = true;
2326 break;
2327 }
2328 }
2329 if (tsk && !tsk->runnables_idx && !tsk->runner && !on_sched_ready_list(tsk, p))
2330 return tsk;
2331 return NULL;
2332 }
2333
2334
2335 static inline task_t *post_ready(pn_proactor_t *p, task_t *tsk) {
2336 tsk->sched_ready = true;
2337 tsk->sched_pending = true;
2338 if (!tsk->runnables_idx && !tsk->runner)
2339 return tsk;
2340 return NULL;
2341 }
2342
2343 // call with sched_lock held
2344 static task_t *next_drain(pn_proactor_t *p, tslot_t *ts) {
2345 // This should be called seldomly, best case once per thread removal on shutdown.
2346 // TODO: how to reduce? Instrumented near 5 percent of earmarks, 1 in 2000 calls to do_epoll().
2347
2348 for (pn_handle_t entry = pn_hash_head(p->tslot_map); entry; entry = pn_hash_next(p->tslot_map, entry)) {
2349 tslot_t *ts2 = (tslot_t *) pn_hash_value(p->tslot_map, entry);
2350 if (ts2->earmarked) {
2351 // undo the old assign thread and earmark. ts2 may never come back
2352 task_t *switch_tsk = ts2->task;
2353 remove_earmark(ts2);
2354 assign_thread(ts, switch_tsk);
2355 ts->earmark_override = ts2;
2356 ts->earmark_override_gen = ts2->generation;
2357 return switch_tsk;
2358 }
2359 }
2360 assert(false);
2361 return NULL;
2362 }
2363
2364 // call with sched_lock held
2365 static task_t *next_runnable(pn_proactor_t *p, tslot_t *ts) {
2366 if (ts->task) {
2367 // Already assigned
2368 if (ts->earmarked) {
2369 ts->earmarked = false;
2370 if (--p->earmark_count == 0)
2371 p->earmark_drain = false;
2372 }
2373 return ts->task;
2374 }
2375
2376 // Take any runnables task if it results in a warm pairing.
2377 task_t *tsk = ts->prev_task;
2378 if (tsk && (tsk->runnables_idx)) {
2379 // A task can self delete, so don't allow it to run twice.
2380 task_t **runnables_slot = &p->runnables[tsk->runnables_idx -1];
2381 assert(*runnables_slot == tsk);
2382 *runnables_slot = NULL;
2383 assign_thread(ts, tsk);
2384 return tsk;
2385 }
2386
2387 // check for remaining runnable tasks
2388 if (p->n_runnables) {
2389 // Any unclaimed runnable?
2390 while (p->n_runnables) {
2391 tsk = p->runnables[p->next_runnable++];
2392 if (p->n_runnables == p->next_runnable)
2393 p->n_runnables = 0;
2394 if (tsk) {
2395 assign_thread(ts, tsk);
2396 return tsk;
2397 }
2398 }
2399 }
2400
2401 // sched_ready list tasks deferred in poller_do_epoll()
2402 while (p->sched_ready_pending) {
2403 tsk = sched_ready_pop_front(p);
2404 assert(tsk->ready); // eventfd_mutex required post ready set and pre move to sched_ready_list
2405 if (post_ready(p, tsk)) {
2406 assert(!tsk->runnables_idx && !tsk->runner);
2407 assign_thread(ts, tsk);
2408 return tsk;
2409 }
2410 }
2411
2412 // the resched list
2413 if (p->polled_resched_count) {
2414 // Unprocessed resched tasks remain.
2415 tsk = resched_pop_front(p);
2416 assert(tsk->sched_pending && !tsk->runnables_idx && tsk->runner == RESCHEDULE_PLACEHOLDER);
2417 tsk->runner = NULL;
2418 assign_thread(ts, tsk);
2419 return tsk;
2420 }
2421
2422 if (p->earmark_drain) {
2423 tsk = next_drain(p, ts);
2424 if (p->earmark_count == 0)
2425 p->earmark_drain = false;
2426 return tsk;
2427 }
2428
2429 return NULL;
2430 }
2431
2432 static pn_event_batch_t *next_event_batch(pn_proactor_t* p, bool can_block) {
2433 lock(&p->tslot_mutex);
2434 tslot_t * ts = find_tslot(p);
2435 unlock(&p->tslot_mutex);
2436
2437 lock(&p->sched_mutex);
2438 assert(ts->task == NULL || ts->earmarked);
2439 assert(ts->state == UNUSED || ts->state == NEW);
2440 ts->state = PROCESSING;
2441 ts->generation++; // wrapping OK. Just looking for any change
2442
2443 // Process outstanding epoll events until we get a batch or need to block.
2444 while (true) {
2445 // First see if there are any tasks waiting to run and perhaps generate new Proton events,
2446 task_t *tsk = next_runnable(p, ts);
2447 if (tsk) {
2448 ts->state = BATCHING;
2449 pn_event_batch_t *batch = process(tsk);
2450 if (batch) {
2451 unlock(&p->sched_mutex);
2452 return batch;
2453 }
2454 tslot_t *resume_thread;
2455 bool notify = unassign_thread(p, ts, PROCESSING, &resume_thread);
2456 if (notify || resume_thread) {
2457 unlock(&p->sched_mutex);
2458 if (notify) notify_poller(p);
2459 if (resume_thread) resume(p, resume_thread);
2460 lock(&p->sched_mutex);
2461 }
2462 continue; // Long time may have passed. Back to beginning.
2463 }
2464
2465 // Poll or wait for a runnable task
2466 if (p->poller == NULL) {
2467 bool return_immediately;
2468 p->poller = ts;
2469 // Get new epoll events (if any) and mark the relevant tasks as runnable
2470 return_immediately = poller_do_epoll(p, ts, can_block);
2471 p->poller = NULL;
2472 if (return_immediately) {
2473 // Check if another thread is available to continue epoll-ing.
2474 tslot_t *res_ts = resume_one_thread(p);
2475 ts->state = UNUSED;
2476 unlock(&p->sched_mutex);
2477 if (res_ts) resume(p, res_ts);
2478 return NULL;
2479 }
2480 poller_done(p, ts); // put suspended threads to work.
2481 } else if (!can_block) {
2482 ts->state = UNUSED;
2483 unlock(&p->sched_mutex);
2484 return NULL;
2485 } else {
2486 // TODO: loop while !poller_suspended, since new work coming
2487 suspend(p, ts);
2488 }
2489 } // while
2490 }
2491
2492 // Call with sched lock. Return true if !can_block and no new events to process.
2493 static bool poller_do_epoll(struct pn_proactor_t* p, tslot_t *ts, bool can_block) {
2494 // As poller with lots to do, be mindful of hogging the sched lock. Release when making kernel calls.
2495 assert(!p->resched_cutoff);
2496 assert(!p->sched_ready_first && !p->sched_ready_pending);
2497 int n_events;
2498 task_t *tsk;
2499 bool unpolled_work = false;
2500
2501 while (true) {
2502 assert(p->n_runnables == 0);
2503 if (p->thread_count > p->thread_capacity)
2504 grow_poller_bufs(p);
2505 p->next_runnable = 0;
2506 p->n_warm_runnables = 0;
2507 p->last_earmark = NULL;
2508
2509 bool unfinished_earmarks = p->earmark_count > 0;
2510 if (unfinished_earmarks || p->resched_first)
2511 unpolled_work = true;
2512 bool epoll_immediate = unpolled_work || !can_block;
2513
2514 // Determine if notify_poller() can be avoided.
2515 if (!epoll_immediate) {
2516 lock(&p->eventfd_mutex);
2517 if (p->ready_list_first) {
2518 unpolled_work = true;
2519 epoll_immediate = true;
2520 } else {
2521 // Poller may sleep. Enable eventfd wakeup.
2522 p->ready_list_active = false;
2523 }
2524 unlock(&p->eventfd_mutex);
2525 }
2526
2527 int timeout = (epoll_immediate) ? 0 : -1;
2528 p->poller_suspended = (timeout == -1);
2529 unlock(&p->sched_mutex);
2530
2531 n_events = epoll_wait(p->epollfd, p->kevents, p->kevents_capacity, timeout);
2532
2533 lock(&p->sched_mutex);
2534 p->poller_suspended = false;
2535
2536 if (p->resched_first) {
2537 // Defer future resched tasks until next do_epoll()
2538 p->resched_cutoff = p->resched_last;
2539 assert(p->polled_resched_count == 0);
2540 p->polled_resched_count = p->resched_count;
2541 p->resched_count = 0;
2542 unpolled_work = true;
2543 }
2544 if (p->earmark_count > 0) {
2545 p->earmark_drain = true;
2546 unpolled_work = true;
2547 }
2548 // Take stock of ready list before any post_event()
2549 lock(&p->eventfd_mutex);
2550 schedule_ready_list(p);
2551 if (p->sched_ready_first)
2552 unpolled_work = true;
2553 if (++p->ready_list_generation == 0) // wrapping OK, but 0 means unset
2554 p->ready_list_generation = 1;
2555 unlock(&p->eventfd_mutex);
2556
2557 if (n_events < 0) {
2558 if (errno != EINTR)
2559 perror("epoll_wait"); // TODO: proper log
2560 if (!can_block && !unpolled_work)
2561 return true;
2562 else
2563 continue;
2564 } else if (n_events == 0) {
2565 if (!can_block && !unpolled_work)
2566 return true;
2567 else {
2568 if (!epoll_immediate)
2569 perror("epoll_wait unexpected timeout"); // TODO: proper log
2570 if (!unpolled_work)
2571 continue;
2572 }
2573 }
2574
2575 break;
2576 }
2577
2578 // We have unpolled work or at least one new epoll event.
2579 // Remember tasks that together constitute new work. See note at beginning about duplicates.
2580
2581 lock(&p->eventfd_mutex);
2582
2583 // Longest hold of eventfd_mutex. The following must be quick with no external calls:
2584 // post_event(), make_runnable(), assign_thread(), earmark_thread().
2585 for (int i = 0; i < n_events; i++) {
2586 tsk = post_event(p, &p->kevents[i]);
2587 if (tsk)
2588 make_runnable(tsk);
2589 }
2590 unlock(&p->eventfd_mutex);
2591
2592 if (n_events > 0)
2593 memset(p->kevents, 0, sizeof(struct epoll_event) * n_events);
2594
2595 // The list of ready tasks can be very long. Tradeoff between slow walk through linked
2596 // list looking for more warm pairings (while holding the sched lock), or letting
2597 // threads looking for work grab from the front. Search less when busy. TODO:
2598 // instrument an optimal value or heuristic.
2599 int warm_tries = p->suspend_list_count - p->n_warm_runnables;
2600 if (warm_tries < 0)
2601 warm_tries = 0;
2602
2603 int max_runnables = p->runnables_capacity;
2604 while (p->sched_ready_count && p->n_runnables < max_runnables && warm_tries) {
2605 task_t *ctsk = sched_ready_pop_front(p);
2606 tsk = post_ready(p, ctsk);
2607 warm_tries--;
2608 if (tsk)
2609 make_runnable(tsk);
2610 }
2611 // sched_ready list is now either consumed or partially deferred.
2612 // Allow next_runnable() to see any remaining sched_ready tasks.
2613 p->sched_ready_pending = p->sched_ready_count > 0;
2614
2615 while (p->resched_cutoff && p->n_runnables < max_runnables && warm_tries) {
2616 task_t *ctsk = resched_pop_front(p);
2617 assert(ctsk->runner == RESCHEDULE_PLACEHOLDER && !ctsk->runnables_idx);
2618 ctsk->runner = NULL; // Allow task to run again.
2619 warm_tries--;
2620 make_runnable(ctsk);
2621 }
2622
2623 if (pni_immediate && !ts->task) {
2624 // Poller gets to run if possible
2625 task_t *ptsk;
2626 if (p->n_runnables) {
2627 assert(p->next_runnable == 0);
2628 ptsk = p->runnables[0];
2629 if (++p->next_runnable == p->n_runnables)
2630 p->n_runnables = 0;
2631 } else if (p->n_warm_runnables) {
2632 // Immediate doesn't contemplate some other (warm) thread running instead
2633 ptsk = p->warm_runnables[--p->n_warm_runnables];
2634 tslot_t *ts2 = ptsk->runner;
2635 ts2->prev_task = ts2->task = NULL;
2636 ptsk->runner = NULL;
2637 } else if (p->last_earmark) {
2638 ptsk = p->last_earmark->task;
2639 remove_earmark(p->last_earmark);
2640 if (p->earmark_count == 0)
2641 p->earmark_drain = false;
2642 } else {
2643 ptsk = NULL;
2644 }
2645 if (ptsk) {
2646 assign_thread(ts, ptsk);
2647 }
2648 }
2649 return false;
2650 }
2651
2652 // Call with sched lock, but only as poller.
2653 static void poller_done(struct pn_proactor_t* p, tslot_t *ts) {
2654 // Create a list of available threads to put to work.
2655 // ts is the poller thread
2656 int resume_list_count = 0;
2657 tslot_t **resume_list2 = NULL;
2658
2659 if (p->suspend_list_count) {
2660 int max_resumes = p->n_warm_runnables + p->n_runnables + p->sched_ready_count + p->polled_resched_count;
2661 max_resumes = pn_min(max_resumes, p->suspend_list_count);
2662 if (max_resumes) {
2663 resume_list2 = (tslot_t **) alloca(max_resumes * sizeof(tslot_t *));
2664 for (int i = 0; i < p->n_warm_runnables ; i++) {
2665 task_t *tsk = p->warm_runnables[i];
2666 tslot_t *tsp = tsk->runner;
2667 if (tsp->state == SUSPENDED) {
2668 resume_list2[resume_list_count++] = tsp;
2669 LL_REMOVE(p, suspend_list, tsp);
2670 p->suspend_list_count--;
2671 tsp->state = PROCESSING;
2672 }
2673 }
2674
2675 int can_use = p->suspend_list_count;
2676 if (!ts->task)
2677 can_use++;
2678 // Run as many unpaired runnable tasks as possible and allow for a new poller.
2679 int new_runners = pn_min(p->n_runnables + 1, can_use);
2680 if (!ts->task)
2681 new_runners--; // poller available and does not need resume
2682
2683 // Rare corner case on startup. New inbound threads can make the suspend_list too big for resume list.
2684 new_runners = pn_min(new_runners, p->thread_capacity - resume_list_count);
2685
2686 for (int i = 0; i < new_runners; i++) {
2687 tslot_t *tsp = p->suspend_list_head;
2688 assert(tsp);
2689 resume_list2[resume_list_count++] = tsp;
2690 LL_REMOVE(p, suspend_list, tsp);
2691 p->suspend_list_count--;
2692 tsp->state = PROCESSING;
2693 }
2694 }
2695 }
2696 p->poller = NULL;
2697
2698 if (resume_list_count) {
2699 // Allows a new poller to run concurrently. Touch only stack vars.
2700 unlock(&p->sched_mutex);
2701 for (int i = 0; i < resume_list_count; i++) {
2702 resume(p, resume_list2[i]);
2703 }
2704 lock(&p->sched_mutex);
2705 }
2706 }
2707
2708 pn_event_batch_t *pn_proactor_wait(struct pn_proactor_t* p) {
2709 return next_event_batch(p, true);
2710 }
2711
2712 pn_event_batch_t *pn_proactor_get(struct pn_proactor_t* p) {
2713 return next_event_batch(p, false);
2714 }
2715
2716 void pn_proactor_done(pn_proactor_t *p, pn_event_batch_t *batch) {
2717 pconnection_t *pc = batch_pconnection(batch);
2718 if (pc) {
2719 pconnection_done(pc);
2720 // pc possibly freed/invalid
2721 return;
2722 }
2723 pn_listener_t *l = batch_listener(batch);
2724 if (l) {
2725 listener_done(l);
2726 // l possibly freed/invalid
2727 return;
2728 }
2729 praw_connection_t *rc = pni_batch_raw_connection(batch);
2730 if (rc) {
2731 pni_raw_connection_done(rc);
2732 // rc possibly freed/invalid
2733 return;
2734 }
2735 pn_proactor_t *bp = batch_proactor(batch);
2736 if (bp == p) {
2737 bool notify = false;
2738 lock(&p->task.mutex);
2739 p->task.working = false;
2740 if (p->timeout_processed) {
2741 p->timeout_processed = false;
2742 if (schedule_if_inactive(p))
2743 notify = true;
2744 }
2745 proactor_update_batch(p);
2746 if (proactor_has_event(p))
2747 if (schedule(&p->task))
2748 notify = true;
2749
2750 unlock(&p->task.mutex);
2751 lock(&p->sched_mutex);
2752 tslot_t *ts = p->task.runner;
2753 tslot_t *resume_thread;
2754 if (unassign_thread(p, ts, UNUSED, &resume_thread))
2755 notify = true;
2756 unlock(&p->sched_mutex);
2757
2758 if (notify) notify_poller(p);
2759 if (resume_thread) resume(p, resume_thread);
2760 return;
2761 }
2762 }
2763
2764 void pn_proactor_interrupt(pn_proactor_t *p) {
2765 if (p->interruptfd == -1)
2766 return;
2767 uint64_t increment = 1;
2768 if (write(p->interruptfd, &increment, sizeof(uint64_t)) != sizeof(uint64_t))
2769 EPOLL_FATAL("setting eventfd", errno);
2770 }
2771
2772 void pn_proactor_set_timeout(pn_proactor_t *p, pn_millis_t t) {
2773 bool notify = false;
2774 lock(&p->timeout_mutex);
2775
2776 lock(&p->task.mutex);
2777 p->timeout_set = true;
2778 if (t == 0) {
2779 p->need_timeout = true;
2780 if (schedule(&p->task))
2781 notify = true;
2782 }
2783 unlock(&p->task.mutex);
2784
2785 if (t == 0) {
2786 if (pni_timer_set(p->timer, 0))
2787 notify = true;
2788 } else {
2789 if (pni_timer_set(p->timer, t + pn_proactor_now_64()))
2790 notify = true;
2791 }
2792 unlock(&p->timeout_mutex);
2793 if (notify) notify_poller(p);
2794 }
2795
2796 void pn_proactor_cancel_timeout(pn_proactor_t *p) {
2797 bool notify = false;
2798 lock(&p->timeout_mutex);
2799
2800 lock(&p->task.mutex);
2801 p->timeout_set = false;
2802 p->need_timeout = false;
2803 if (schedule_if_inactive(p))
2804 notify = true;
2805 unlock(&p->task.mutex);
2806
2807 if (pni_timer_set(p->timer, 0))
2808 notify = true;
2809 unlock(&p->timeout_mutex);
2810 if (notify) notify_poller(p);
2811 }
2812
2813 void pni_proactor_timeout(pn_proactor_t *p) {
2814 bool notify = false;
2815 lock(&p->task.mutex);
2816 if (!p->task.closing) {
2817 p->need_timeout = true;
2818 notify = schedule(&p->task);
2819 }
2820 unlock(&p->task.mutex);
2821 if (notify) notify_poller(p);
2822 }
2823
2824 pn_proactor_t *pn_connection_proactor(pn_connection_t* c) {
2825 pconnection_t *pc = get_pconnection(c);
2826 return pc ? pc->task.proactor : NULL;
2827 }
2828
2829 void pn_proactor_disconnect(pn_proactor_t *p, pn_condition_t *cond) {
2830 bool notify = false;
2831
2832 lock(&p->task.mutex);
2833 // Move the whole tasks list into a disconnecting state
2834 task_t *disconnecting_tasks = p->tasks;
2835 p->tasks = NULL;
2836 // First pass: mark each task as disconnecting and update global pending count.
2837 task_t *tsk = disconnecting_tasks;
2838 while (tsk) {
2839 tsk->disconnecting = true;
2840 tsk->disconnect_ops = 2; // Second pass below and proactor_remove(), in any order.
2841 p->disconnects_pending++;
2842 tsk = tsk->next;
2843 p->task_count--;
2844 }
2845 notify = schedule_if_inactive(p);
2846 unlock(&p->task.mutex);
2847 if (!disconnecting_tasks) {
2848 if (notify) notify_poller(p);
2849 return;
2850 }
2851
2852 // Second pass: different locking, close the tasks, free them if !disconnect_ops
2853 task_t *next = disconnecting_tasks;
2854 while (next) {
2855 tsk = next;
2856 next = tsk->next; /* Save next pointer in case we free tsk */
2857 bool do_free = false;
2858 bool tsk_notify = false;
2859 pmutex *tsk_mutex = NULL;
2860 // TODO: Need to extend this for raw connections too
2861 pconnection_t *pc = task_pconnection(tsk);
2862 if (pc) {
2863 tsk_mutex = &pc->task.mutex;
2864 lock(tsk_mutex);
2865 if (!tsk->closing) {
2866 tsk_notify = true;
2867 if (tsk->working) {
2868 // Must defer
2869 pc->queued_disconnect = true;
2870 if (cond) {
2871 if (!pc->disconnect_condition)
2872 pc->disconnect_condition = pn_condition();
2873 pn_condition_copy(pc->disconnect_condition, cond);
2874 }
2875 }
2876 else {
2877 // No conflicting working task.
2878 if (cond) {
2879 pn_condition_copy(pn_transport_condition(pc->driver.transport), cond);
2880 }
2881 pn_connection_driver_close(&pc->driver);
2882 }
2883 }
2884 } else {
2885 pn_listener_t *l = task_listener(tsk);
2886 assert(l);
2887 tsk_mutex = &l->task.mutex;
2888 lock(tsk_mutex);
2889 if (!tsk->closing) {
2890 tsk_notify = true;
2891 if (cond) {
2892 pn_condition_copy(pn_listener_condition(l), cond);
2893 }
2894 listener_begin_close(l);
2895 }
2896 }
2897
2898 lock(&p->task.mutex);
2899 if (--tsk->disconnect_ops == 0) {
2900 do_free = true;
2901 tsk_notify = false;
2902 notify = schedule_if_inactive(p);
2903 } else {
2904 // If initiating the close, schedule the task to do the free.
2905 if (tsk_notify)
2906 tsk_notify = schedule(tsk);
2907 if (tsk_notify)
2908 notify_poller(p);
2909 }
2910 unlock(&p->task.mutex);
2911 unlock(tsk_mutex);
2912
2913 // Unsafe to touch tsk after lock release, except if we are the designated final_free
2914 if (do_free) {
2915 if (pc) pconnection_final_free(pc);
2916 else listener_final_free(task_listener(tsk));
2917 }
2918 }
2919 if (notify)
2920 notify_poller(p);
2921 }
2922
2923 const pn_netaddr_t *pn_transport_local_addr(pn_transport_t *t) {
2924 pconnection_t *pc = get_pconnection(pn_transport_connection(t));
2925 return pc? &pc->local : NULL;
2926 }
2927
2928 const pn_netaddr_t *pn_transport_remote_addr(pn_transport_t *t) {
2929 pconnection_t *pc = get_pconnection(pn_transport_connection(t));
2930 return pc ? &pc->remote : NULL;
2931 }
2932
2933 const pn_netaddr_t *pn_listener_addr(pn_listener_t *l) {
2934 return l->acceptors_size > 0 ? &l->acceptors[0].addr : NULL;
2935 }
2936
2937 pn_millis_t pn_proactor_now(void) {
2938 return (pn_millis_t) pn_proactor_now_64();
2939 }
2940
2941 int64_t pn_proactor_now_64(void) {
2942 struct timespec t;
2943 clock_gettime(CLOCK_MONOTONIC, &t);
2944 return ((int64_t)t.tv_sec) * 1000 + t.tv_nsec / 1000000;
2945 }