Debian Codegraph @

Xpjproject/pjlib/src/pj/ioqueue_epoll.c

raw symbols SCIP
1 /*
2 * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
3 * Copyright (C) 2003-2008 Benny Prijono <[email protected]>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19 /*
20 * ioqueue_epoll.c
21 *
22 * This is the implementation of IOQueue framework using /dev/epoll
23 * API in _both_ Linux user-mode and kernel-mode.
24 */
25
26 #include <pj/ioqueue.h>
27 #include <pj/os.h>
28 #include <pj/lock.h>
29 #include <pj/log.h>
30 #include <pj/list.h>
31 #include <pj/pool.h>
32 #include <pj/string.h>
33 #include <pj/assert.h>
34 #include <pj/errno.h>
35 #include <pj/sock.h>
36 #include <pj/compat/socket.h>
37 #include <pj/rand.h>
38
39
40 /* Only build when the backend is using epoll. */
41 #if PJ_IOQUEUE_IMP == PJ_IOQUEUE_IMP_EPOLL
42
43
44 #include <sys/epoll.h>
45 #include <sys/eventfd.h>
46 #include <errno.h>
47 #include <unistd.h>
48
49 #define epoll_data data.ptr
50 #define epoll_data_type void*
51 #define ioctl_val_type unsigned long
52 #define getsockopt_val_ptr int*
53 #define os_getsockopt getsockopt
54 #define os_ioctl ioctl
55 #define os_read read
56 #define os_close close
57 #define os_epoll_create epoll_create1
58 #define os_epoll_ctl epoll_ctl
59 #define os_epoll_wait epoll_wait
60
61
62 #define THIS_FILE "ioq_epoll"
63
64 //#define TRACE_(expr) PJ_LOG(3,expr)
65 #define TRACE_(expr)
66
67 /* Enable this during development to warn against stray events.
68 * But don't enable this during production, for performance reason.
69 */
70 //#define TRACE_WARN(expr) PJ_LOG(2,expr)
71 #define TRACE_WARN(expr)
72
73
74 #ifndef EPOLLEXCLUSIVE
75 # define EPOLLEXCLUSIVE (1U << 28)
76 #endif
77
78 enum { IO_MASK = EPOLLIN | EPOLLOUT | EPOLLERR };
79
80 static char ioq_name[32];
81
82 /*
83 * Include common ioqueue abstraction.
84 */
85 #include "ioqueue_common_abs.h"
86
87 /*
88 * This describes each key.
89 */
90 struct pj_ioqueue_key_t
91 {
92 DECLARE_COMMON_KEY
93 struct epoll_event ev;
94 };
95
96 struct queue
97 {
98 pj_ioqueue_key_t *key;
99 enum ioqueue_event_type event_type;
100 };
101
102 /*
103 * This describes the I/O queue.
104 */
105 struct pj_ioqueue_t
106 {
107 DECLARE_COMMON_IOQUEUE
108
109 unsigned max, count;
110 //pj_ioqueue_key_t hlist;
111 pj_ioqueue_key_t active_list;
112 int epfd;
113 //struct epoll_event *events;
114 //struct queue *queue;
115
116 #if PJ_IOQUEUE_HAS_SAFE_UNREG
117 pj_mutex_t *ref_cnt_mutex;
118 pj_ioqueue_key_t closing_list;
119 pj_ioqueue_key_t free_list;
120 #endif
121 };
122
123 /* Include implementation for common abstraction after we declare
124 * pj_ioqueue_key_t and pj_ioqueue_t.
125 */
126 #include "ioqueue_common_abs.c"
127
128 #if PJ_IOQUEUE_HAS_SAFE_UNREG
129 /* Scan closing keys to be put to free list again */
130 static void scan_closing_keys(pj_ioqueue_t *ioqueue);
131 #endif
132
133
134 /* EPOLLEXCLUSIVE or EPOLLONESHOT is reported to cause perm handshake error
135 * on OpenSSL 1.0.2, so let's disable this when using OpenSSL older than
136 * version 1.1.0.
137 */
138 #if defined(PJ_HAS_SSL_SOCK) && PJ_HAS_SSL_SOCK != 0 && \
139 (PJ_SSL_SOCK_IMP == PJ_SSL_SOCK_IMP_OPENSSL)
140
141 # include <openssl/opensslv.h>
142 # if OPENSSL_VERSION_NUMBER < 0x10100000L
143 # define DISABLE_EXCLUSIVE_ONESHOT "problem with OpenSSL ver <= 1.0.2"
144 # endif
145
146 #endif
147
148
149 /*
150 * Run-time detection of epoll exclusive/oneshot on the machine.
151 */
152 static unsigned detect_epoll_support()
153 {
154 static int epoll_support = -1;
155 struct epoll_event ev;
156 int rc;
157 int epfd = -1, evfd = -1, disable_exclusive = 0;
158 int tmp_epoll_support = 0, support_exclusive = 0, support_oneshot = 0;
159
160 /* Note: this function should be thread-safe */
161 if (epoll_support != -1)
162 return epoll_support;
163
164 #ifdef DISABLE_EXCLUSIVE_ONESHOT
165 PJ_LOG(3,(THIS_FILE, "epoll EXCLUSIVE/ONESHOT support disabled, reason: %s",
166 DISABLE_EXCLUSIVE_ONESHOT));
167 epoll_support = 0;
168 return epoll_support;
169 #endif
170
171 epfd = os_epoll_create(EPOLL_CLOEXEC);
172 if (epfd < 0)
173 goto on_error;
174
175 evfd = eventfd(0, EFD_CLOEXEC);
176 if (evfd < 0)
177 goto on_error;
178
179 /*
180 * Choose events that should cause an error on EPOLLEXCLUSIVE enabled
181 * kernels - specifically the combination of EPOLLONESHOT and
182 * EPOLLEXCLUSIVE
183 */
184 pj_bzero(&ev, sizeof(ev));
185 ev.events = EPOLLIN | EPOLLEXCLUSIVE | EPOLLONESHOT;
186 rc = epoll_ctl(epfd, EPOLL_CTL_ADD, evfd, &ev);
187 if (rc == 0) {
188 /* The kernel has accepted our invalid request. Assume it probably
189 * doesn't know about/support EPOLLEXCLUSIVE. But we assume that
190 * it may still be able to support EPOLLONESHOT, since this was
191 * added very long time ago.
192 */
193 disable_exclusive = 1;
194 rc = epoll_ctl(epfd, EPOLL_CTL_DEL, evfd, &ev);
195 if (rc != 0)
196 goto on_error;
197
198 } else if (errno != EINVAL) {
199 /* Unexpected error */
200 goto on_error;
201 }
202
203 /* Check EPOLLEXCLUSIVE support */
204 if (!disable_exclusive) {
205 ev.events = EPOLLIN | EPOLLEXCLUSIVE;
206 rc = epoll_ctl(epfd, EPOLL_CTL_ADD, evfd, &ev);
207 if (rc == 0) {
208 support_exclusive = 1;
209 rc = epoll_ctl(epfd, EPOLL_CTL_DEL, evfd, &ev);
210 if (rc != 0)
211 goto on_error;
212 }
213 }
214
215 /* Check EPOLLONESHOT support */
216 ev.events = EPOLLIN | EPOLLONESHOT;
217 rc = epoll_ctl(epfd, EPOLL_CTL_ADD, evfd, &ev);
218 if (rc == 0) {
219 support_oneshot = 1;
220 rc = epoll_ctl(epfd, EPOLL_CTL_DEL, evfd, &ev);
221 if (rc != 0)
222 goto on_error;
223 }
224
225 tmp_epoll_support = 0;
226 if (support_exclusive && !disable_exclusive)
227 tmp_epoll_support |= PJ_IOQUEUE_EPOLL_EXCLUSIVE;
228 if (support_oneshot)
229 tmp_epoll_support |= PJ_IOQUEUE_EPOLL_ONESHOT;
230
231 pj_ansi_snprintf(ioq_name, sizeof(ioq_name), "epoll[0x%x]",
232 tmp_epoll_support);
233 epoll_support = tmp_epoll_support;
234
235 if (epfd > 0)
236 os_close(epfd);
237 if (evfd > 0)
238 os_close(evfd);
239
240 return epoll_support;
241
242 on_error:
243 rc = PJ_RETURN_OS_ERROR(pj_get_native_netos_error());
244 PJ_PERROR(2,(THIS_FILE, rc, "detect_epoll_support() error"));
245 if (epfd >= 0)
246 os_close(epfd);
247 if (evfd >= 0)
248 os_close(evfd);
249 return 0;
250 }
251
252 /*
253 * pj_ioqueue_name()
254 */
255 PJ_DEF(const char*) pj_ioqueue_name(void)
256 {
257 detect_epoll_support();
258 return ioq_name;
259 }
260
261
262 /*
263 * pj_ioqueue_create()
264 *
265 * Create epoll ioqueue.
266 */
267 PJ_DEF(pj_status_t) pj_ioqueue_create( pj_pool_t *pool,
268 pj_size_t max_fd,
269 pj_ioqueue_t **p_ioqueue)
270 {
271 return pj_ioqueue_create2(pool, max_fd, NULL, p_ioqueue);
272 }
273
274 /*
275 * pj_ioqueue_create2()
276 *
277 * Create epoll ioqueue.
278 */
279 PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool,
280 pj_size_t max_fd,
281 const pj_ioqueue_cfg *cfg,
282 pj_ioqueue_t **p_ioqueue)
283 {
284 pj_ioqueue_t *ioqueue;
285 pj_status_t rc;
286 pj_lock_t *lock;
287 const unsigned type_mask = PJ_IOQUEUE_EPOLL_EXCLUSIVE |
288 PJ_IOQUEUE_EPOLL_ONESHOT;
289 unsigned epoll_support, valid_types;
290 pj_size_t i;
291
292 /* Check that arguments are valid. */
293 PJ_ASSERT_RETURN(pool != NULL && p_ioqueue != NULL &&
294 max_fd > 0, PJ_EINVAL);
295
296 /* Check that size of pj_ioqueue_op_key_t is sufficient */
297 PJ_ASSERT_RETURN(sizeof(pj_ioqueue_op_key_t)-sizeof(void*) >=
298 sizeof(union operation_key), PJ_EBUG);
299
300 ioqueue = pj_pool_alloc(pool, sizeof(pj_ioqueue_t));
301
302 ioqueue_init(ioqueue);
303
304 if (cfg)
305 pj_memcpy(&ioqueue->cfg, cfg, sizeof(*cfg));
306 else {
307 pj_ioqueue_cfg_default(&ioqueue->cfg);
308 cfg = &ioqueue->cfg;
309 }
310 ioqueue->max = max_fd;
311 ioqueue->count = 0;
312 pj_list_init(&ioqueue->active_list);
313
314 /* Adjust/validate epoll type according to supported epoll types.
315 */
316 epoll_support = detect_epoll_support();
317 valid_types = epoll_support & cfg->epoll_flags;
318 /* Note that epoll_flags may be used to specify options other than
319 * epoll types in the future, hence be careful when clearing the
320 * bits (only bits related to epoll types should be cleared)
321 */
322 ioqueue->cfg.epoll_flags &= ~type_mask;
323 if (valid_types & PJ_IOQUEUE_EPOLL_EXCLUSIVE) {
324 ioqueue->cfg.epoll_flags |= PJ_IOQUEUE_EPOLL_EXCLUSIVE;
325 } else if (valid_types & PJ_IOQUEUE_EPOLL_ONESHOT) {
326 ioqueue->cfg.epoll_flags |= PJ_IOQUEUE_EPOLL_ONESHOT;
327 } else if ((cfg->epoll_flags & type_mask) == 0) {
328 /* user has disabled both EXCLUSIVE and ONESHOT */
329 } else {
330 /* the requested epoll type is not available */
331 return PJ_EINVAL;
332 }
333
334 #if PJ_IOQUEUE_HAS_SAFE_UNREG
335 /* When safe unregistration is used (the default), we pre-create
336 * all keys and put them in the free list.
337 */
338
339 /* Mutex to protect key's reference counter
340 * We don't want to use key's mutex or ioqueue's mutex because
341 * that would create deadlock situation in some cases.
342 */
343 rc = pj_mutex_create_simple(pool, NULL, &ioqueue->ref_cnt_mutex);
344 if (rc != PJ_SUCCESS)
345 return rc;
346
347
348 /* Init key list */
349 pj_list_init(&ioqueue->free_list);
350 pj_list_init(&ioqueue->closing_list);
351
352
353 /* Pre-create all keys according to max_fd */
354 for ( i=0; i<max_fd; ++i) {
355 pj_ioqueue_key_t *key;
356
357 key = PJ_POOL_ALLOC_T(pool, pj_ioqueue_key_t);
358 key->ref_count = 0;
359 rc = pj_lock_create_recursive_mutex(pool, NULL, &key->lock);
360 if (rc != PJ_SUCCESS) {
361 key = ioqueue->free_list.next;
362 while (key != &ioqueue->free_list) {
363 pj_lock_destroy(key->lock);
364 key = key->next;
365 }
366 pj_mutex_destroy(ioqueue->ref_cnt_mutex);
367 return rc;
368 }
369
370 pj_list_push_back(&ioqueue->free_list, key);
371 }
372 #endif
373
374 rc = pj_lock_create_simple_mutex(pool, "ioq%p", &lock);
375 if (rc != PJ_SUCCESS)
376 return rc;
377
378 rc = pj_ioqueue_set_lock(ioqueue, lock, PJ_TRUE);
379 if (rc != PJ_SUCCESS)
380 return rc;
381
382 ioqueue->epfd = os_epoll_create(EPOLL_CLOEXEC);
383 if (ioqueue->epfd < 0) {
384 pj_lock_acquire(ioqueue->lock);
385 ioqueue_destroy(ioqueue);
386 return PJ_RETURN_OS_ERROR(pj_get_native_os_error());
387 }
388
389 /*ioqueue->events = pj_pool_calloc(pool, max_fd, sizeof(struct epoll_event));
390 PJ_ASSERT_RETURN(ioqueue->events != NULL, PJ_ENOMEM);
391
392 ioqueue->queue = pj_pool_calloc(pool, max_fd, sizeof(struct queue));
393 PJ_ASSERT_RETURN(ioqueue->queue != NULL, PJ_ENOMEM);
394 */
395
396 PJ_LOG(4, ("pjlib", "epoll I/O Queue created (flags:0x%x, ptr=%p)",
397 ioqueue->cfg.epoll_flags, ioqueue));
398
399 *p_ioqueue = ioqueue;
400 return PJ_SUCCESS;
401 }
402
403 /*
404 * pj_ioqueue_destroy()
405 *
406 * Destroy ioqueue.
407 */
408 PJ_DEF(pj_status_t) pj_ioqueue_destroy(pj_ioqueue_t *ioqueue)
409 {
410 pj_ioqueue_key_t *key;
411
412 PJ_ASSERT_RETURN(ioqueue, PJ_EINVAL);
413 PJ_ASSERT_RETURN(ioqueue->epfd > 0, PJ_EINVALIDOP);
414
415 pj_lock_acquire(ioqueue->lock);
416 os_close(ioqueue->epfd);
417 ioqueue->epfd = 0;
418
419 #if PJ_IOQUEUE_HAS_SAFE_UNREG
420 /* Destroy reference counters */
421 key = ioqueue->active_list.next;
422 while (key != &ioqueue->active_list) {
423 pj_lock_destroy(key->lock);
424 key = key->next;
425 }
426
427 key = ioqueue->closing_list.next;
428 while (key != &ioqueue->closing_list) {
429 pj_lock_destroy(key->lock);
430 key = key->next;
431 }
432
433 key = ioqueue->free_list.next;
434 while (key != &ioqueue->free_list) {
435 pj_lock_destroy(key->lock);
436 key = key->next;
437 }
438
439 pj_mutex_destroy(ioqueue->ref_cnt_mutex);
440 #endif
441 return ioqueue_destroy(ioqueue);
442 }
443
444 /*
445 * pj_ioqueue_register_sock()
446 *
447 * Register a socket to ioqueue.
448 */
449 PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool,
450 pj_ioqueue_t *ioqueue,
451 pj_sock_t sock,
452 pj_grp_lock_t *grp_lock,
453 void *user_data,
454 const pj_ioqueue_callback *cb,
455 pj_ioqueue_key_t **p_key)
456 {
457 pj_ioqueue_key_t *key = NULL;
458 pj_uint32_t value;
459 int rc;
460 pj_status_t status = PJ_SUCCESS;
461
462 PJ_ASSERT_RETURN(pool && ioqueue && sock != PJ_INVALID_SOCKET &&
463 cb && p_key, PJ_EINVAL);
464
465 pj_lock_acquire(ioqueue->lock);
466
467 if (ioqueue->count >= ioqueue->max) {
468 status = PJ_ETOOMANY;
469 TRACE_((THIS_FILE, "pj_ioqueue_register_sock error: too many files"));
470 goto on_return;
471 }
472
473 /* Set socket to nonblocking. */
474 value = 1;
475 if ((rc=os_ioctl(sock, FIONBIO, (ioctl_val_type)&value))) {
476 TRACE_((THIS_FILE, "pj_ioqueue_register_sock error: ioctl rc=%d",
477 rc));
478 status = pj_get_netos_error();
479 goto on_return;
480 }
481
482 /* If safe unregistration (PJ_IOQUEUE_HAS_SAFE_UNREG) is used, get
483 * the key from the free list. Otherwise allocate a new one.
484 */
485 #if PJ_IOQUEUE_HAS_SAFE_UNREG
486
487 /* Scan closing_keys first to let them come back to free_list */
488 scan_closing_keys(ioqueue);
489
490 pj_assert(!pj_list_empty(&ioqueue->free_list));
491 if (pj_list_empty(&ioqueue->free_list)) {
492 status = PJ_ETOOMANY;
493 goto on_return;
494 }
495
496 key = ioqueue->free_list.next;
497 pj_list_erase(key);
498 #else
499 /* Create key. */
500 key = (pj_ioqueue_key_t*)pj_pool_zalloc(pool, sizeof(pj_ioqueue_key_t));
501 #endif
502
503 status = ioqueue_init_key(pool, ioqueue, key, sock, grp_lock, user_data, cb);
504 if (status != PJ_SUCCESS) {
505 key = NULL;
506 goto on_return;
507 }
508 pj_bzero(&key->ev, sizeof(key->ev));
509 key->ev.epoll_data = (epoll_data_type)key;
510 key->ev.events = 0;
511 if (ioqueue->cfg.epoll_flags & PJ_IOQUEUE_EPOLL_EXCLUSIVE)
512 key->ev.events |= EPOLLEXCLUSIVE;
513 else if (ioqueue->cfg.epoll_flags & PJ_IOQUEUE_EPOLL_ONESHOT)
514 key->ev.events |= EPOLLONESHOT;
515
516 /* Create key's mutex */
517 /* rc = pj_mutex_create_recursive(pool, NULL, &key->mutex);
518 if (rc != PJ_SUCCESS) {
519 key = NULL;
520 goto on_return;
521 }
522 */
523 /* os_epoll_ctl. */
524 rc = os_epoll_ctl(ioqueue->epfd, EPOLL_CTL_ADD, sock, &key->ev);
525 if (rc < 0) {
526 status = pj_get_os_error();
527 pj_lock_destroy(key->lock);
528 key = NULL;
529 PJ_PERROR(1,(THIS_FILE, status, "epol_ctl(ADD) error"));
530 goto on_return;
531 }
532
533 /* Register */
534 pj_list_insert_before(&ioqueue->active_list, key);
535 ++ioqueue->count;
536
537 //TRACE_((THIS_FILE, "socket registered, count=%d", ioqueue->count));
538
539 on_return:
540 if (status != PJ_SUCCESS) {
541 if (key && key->grp_lock)
542 pj_grp_lock_dec_ref_dbg(key->grp_lock, "ioqueue", 0);
543 }
544 *p_key = key;
545 pj_lock_release(ioqueue->lock);
546
547 return status;
548 }
549
550 PJ_DEF(pj_status_t) pj_ioqueue_register_sock( pj_pool_t *pool,
551 pj_ioqueue_t *ioqueue,
552 pj_sock_t sock,
553 void *user_data,
554 const pj_ioqueue_callback *cb,
555 pj_ioqueue_key_t **p_key)
556 {
557 return pj_ioqueue_register_sock2(pool, ioqueue, sock, NULL, user_data,
558 cb, p_key);
559 }
560
561 #if PJ_IOQUEUE_HAS_SAFE_UNREG
562 /* Increment key's reference counter */
563 static void increment_counter(pj_ioqueue_key_t *key)
564 {
565 pj_mutex_lock(key->ioqueue->ref_cnt_mutex);
566 ++key->ref_count;
567 pj_mutex_unlock(key->ioqueue->ref_cnt_mutex);
568 }
569
570 /* Decrement the key's reference counter, and when the counter reach zero,
571 * destroy the key.
572 *
573 * Note: MUST NOT CALL THIS FUNCTION WHILE HOLDING ioqueue's LOCK.
574 */
575 static void decrement_counter(pj_ioqueue_key_t *key)
576 {
577 pj_lock_acquire(key->ioqueue->lock);
578 pj_mutex_lock(key->ioqueue->ref_cnt_mutex);
579 --key->ref_count;
580 if (key->ref_count == 0) {
581
582 pj_assert(key->closing == 1);
583 pj_gettickcount(&key->free_time);
584 key->free_time.msec += PJ_IOQUEUE_KEY_FREE_DELAY;
585 pj_time_val_normalize(&key->free_time);
586
587 pj_list_erase(key);
588 pj_list_push_back(&key->ioqueue->closing_list, key);
589
590 }
591 pj_mutex_unlock(key->ioqueue->ref_cnt_mutex);
592 pj_lock_release(key->ioqueue->lock);
593 }
594 #endif
595
596 /*
597 * pj_ioqueue_unregister()
598 *
599 * Unregister handle from ioqueue.
600 */
601 PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key)
602 {
603 pj_ioqueue_t *ioqueue;
604 int status;
605
606 PJ_ASSERT_RETURN(key != NULL, PJ_EINVAL);
607
608 ioqueue = key->ioqueue;
609
610 /* Lock the key to make sure no callback is simultaneously modifying
611 * the key. We need to lock the key before ioqueue here to prevent
612 * deadlock.
613 */
614 pj_ioqueue_lock_key(key);
615
616 /* Best effort to avoid double key-unregistration */
617 if (IS_CLOSING(key)) {
618 pj_ioqueue_unlock_key(key);
619 return PJ_SUCCESS;
620 }
621
622 /* Also lock ioqueue */
623 pj_lock_acquire(ioqueue->lock);
624
625 /* Avoid "negative" ioqueue count */
626 if (ioqueue->count > 0) {
627 --ioqueue->count;
628 } else {
629 /* If this happens, very likely there is double unregistration
630 * of a key.
631 */
632 pj_assert(!"Bad ioqueue count in key unregistration!");
633 PJ_LOG(1,(THIS_FILE, "Bad ioqueue count in key unregistration!"));
634 }
635
636 #if !PJ_IOQUEUE_HAS_SAFE_UNREG
637 pj_list_erase(key);
638 #endif
639
640 /* Note: although event argument is ignored on EPOLL_CTL_DEL, we still
641 * need to clear the IO flags to be safe (in case another thread is run
642 * after we exit this function).
643 */
644 key->ev.events &= ~IO_MASK;
645 status = os_epoll_ctl( ioqueue->epfd, EPOLL_CTL_DEL, key->fd, &key->ev);
646 if (status != 0) {
647 status = pj_get_os_error();
648 PJ_PERROR(2, (THIS_FILE, status,
649 "Ignoring pj_ioqueue_unregister error: os_epoll_ctl"));
650 /* From epoll doc: "Closing a file descriptor cause it to be
651 * removed from all epoll interest lists". So we should just
652 * proceed instead of returning failure here.
653 */
654 // pj_lock_release(ioqueue->lock);
655 // pj_ioqueue_unlock_key(key);
656 // return rc;
657 }
658
659 /* Destroy the key. */
660 pj_sock_close(key->fd);
661
662 pj_lock_release(ioqueue->lock);
663
664 /* Mark key is closing. */
665 key->closing = 1;
666
667 pj_ioqueue_unlock_key(key);
668
669 #if PJ_IOQUEUE_HAS_SAFE_UNREG
670 /* Drain pending write callbacks. See #4864, #4878. */
671 ioqueue_drain_pending_writes(key);
672
673 /* Decrement counter. */
674 decrement_counter(key);
675 #else
676 /* Destroy the key lock */
677 pj_lock_destroy(key->lock);
678 #endif
679
680 /* Done. */
681 if (key->grp_lock) {
682 pj_grp_lock_dec_ref_dbg(key->grp_lock, "ioqueue", 0);
683 }
684
685 return PJ_SUCCESS;
686 }
687
688
689 static void update_epoll_event_set(pj_ioqueue_t *ioqueue,
690 pj_ioqueue_key_t *key,
691 pj_uint32_t events)
692 {
693 int rc;
694 /* From epoll_ctl(2):
695 * EPOLLEXCLUSIVE may be used only in an EPOLL_CTL_ADD operation;
696 * attempts to employ it with EPOLL_CTL_MOD yield an error.
697 */
698 if (key->ev.events & EPOLLEXCLUSIVE) {
699 rc = os_epoll_ctl(ioqueue->epfd, EPOLL_CTL_DEL, key->fd, &key->ev);
700 key->ev.events = events;
701 rc = os_epoll_ctl(ioqueue->epfd, EPOLL_CTL_ADD, key->fd, &key->ev);
702 } else {
703 key->ev.events = events;
704 rc = os_epoll_ctl(ioqueue->epfd, EPOLL_CTL_MOD, key->fd, &key->ev);
705 }
706
707 if (rc != 0) {
708 pj_status_t status = pj_get_os_error();
709 PJ_PERROR(1,(THIS_FILE, status,
710 "epol_ctl(MOD) error (events=0x%x)", events));
711 }
712 }
713
714
715 /* ioqueue_remove_from_set()
716 * This function is called from ioqueue_dispatch_event() to instruct
717 * the ioqueue to remove the specified descriptor from ioqueue's descriptor
718 * set for the specified event.
719 */
720 static void ioqueue_remove_from_set( pj_ioqueue_t *ioqueue,
721 pj_ioqueue_key_t *key,
722 enum ioqueue_event_type event_type )
723 {
724 ioqueue_remove_from_set2(ioqueue, key, event_type);
725 }
726
727 static void ioqueue_remove_from_set2(pj_ioqueue_t *ioqueue,
728 pj_ioqueue_key_t *key,
729 unsigned event_types)
730 {
731 pj_uint32_t events = key->ev.events;
732
733 if (event_types & READABLE_EVENT)
734 events &= ~EPOLLIN;
735 if (event_types & WRITEABLE_EVENT)
736 events &= ~EPOLLOUT;
737
738 /* Note that although EPOLLERR is removed, epoll will still report
739 * EPOLLERR events to us and there is no way to disable it. But we
740 * still remove it from "events" anyway to make our interest correct
741 * in our own record.
742 */
743 if (event_types & EXCEPTION_EVENT)
744 events &= ~EPOLLERR;
745
746 if (events != key->ev.events)
747 update_epoll_event_set(ioqueue, key, events);
748 }
749
750 /*
751 * ioqueue_add_to_set()
752 * This function is called from pj_ioqueue_recv(), pj_ioqueue_send() etc
753 * to instruct the ioqueue to add the specified handle to ioqueue's descriptor
754 * set for the specified event.
755 */
756 static void ioqueue_add_to_set( pj_ioqueue_t *ioqueue,
757 pj_ioqueue_key_t *key,
758 enum ioqueue_event_type event_type )
759 {
760 ioqueue_add_to_set2(ioqueue, key, event_type);
761 }
762
763 static void ioqueue_add_to_set2(pj_ioqueue_t *ioqueue,
764 pj_ioqueue_key_t *key,
765 unsigned event_types )
766 {
767 pj_uint32_t events = key->ev.events;
768
769 if (event_types & READABLE_EVENT)
770 events |= EPOLLIN;
771 if (event_types & WRITEABLE_EVENT)
772 events |= EPOLLOUT;
773 if (event_types & EXCEPTION_EVENT)
774 events |= EPOLLERR;
775
776 if (events != key->ev.events)
777 update_epoll_event_set(ioqueue, key, events);
778 }
779
780
781 #if PJ_IOQUEUE_HAS_SAFE_UNREG
782 /* Scan closing keys to be put to free list again */
783 static void scan_closing_keys(pj_ioqueue_t *ioqueue)
784 {
785 pj_time_val now;
786 pj_ioqueue_key_t *h;
787
788 pj_gettickcount(&now);
789 h = ioqueue->closing_list.next;
790 while (h != &ioqueue->closing_list) {
791 pj_ioqueue_key_t *next = h->next;
792
793 pj_assert(h->closing != 0);
794
795 if (PJ_TIME_VAL_GTE(now, h->free_time)) {
796 pj_list_erase(h);
797 // Don't set grp_lock to NULL otherwise the other thread
798 // will crash. Just leave it as dangling pointer, but this
799 // should be safe
800 //h->grp_lock = NULL;
801 pj_list_push_back(&ioqueue->free_list, h);
802 }
803 h = next;
804 }
805 }
806 #endif
807
808 /*
809 * pj_ioqueue_poll()
810 *
811 */
812 PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioqueue, const pj_time_val *timeout)
813 {
814 int i, count, event_cnt, processed_cnt;
815 int msec;
816 //struct epoll_event *events = ioqueue->events;
817 //struct queue *queue = ioqueue->queue;
818 enum { MAX_EVENTS = PJ_IOQUEUE_MAX_CAND_EVENTS };
819 struct epoll_event events[MAX_EVENTS];
820 struct queue queue[MAX_EVENTS];
821 pj_timestamp t1, t2;
822
823 PJ_CHECK_STACK();
824
825 msec = timeout ? PJ_TIME_VAL_MSEC(*timeout) : 9000;
826
827 TRACE_((THIS_FILE, "start os_epoll_wait, msec=%d", msec));
828 pj_get_timestamp(&t1);
829
830 //count = os_epoll_wait( ioqueue->epfd, events, ioqueue->max, msec);
831 count = os_epoll_wait( ioqueue->epfd, events, MAX_EVENTS, msec);
832 if (count == 0) {
833 #if PJ_IOQUEUE_HAS_SAFE_UNREG
834 /* Check the closing keys only when there's no activity and when there are
835 * pending closing keys.
836 */
837 if (count == 0 && !pj_list_empty(&ioqueue->closing_list)) {
838 pj_lock_acquire(ioqueue->lock);
839 scan_closing_keys(ioqueue);
840 pj_lock_release(ioqueue->lock);
841 }
842 #endif
843 TRACE_((THIS_FILE, " os_epoll_wait timed out"));
844 return count;
845 }
846 else if (count < 0) {
847 TRACE_((THIS_FILE, " os_epoll_wait error"));
848 return -pj_get_netos_error();
849 }
850
851 pj_get_timestamp(&t2);
852 TRACE_((THIS_FILE, " os_epoll_wait returns %d, time=%d usec",
853 count, pj_elapsed_usec(&t1, &t2)));
854
855 /* Lock ioqueue. */
856 pj_lock_acquire(ioqueue->lock);
857
858 for (event_cnt=0, i=0; i<count; ++i) {
859 pj_ioqueue_key_t *h = (pj_ioqueue_key_t*)(epoll_data_type)
860 events[i].epoll_data;
861
862 TRACE_((THIS_FILE, " event %d: events=%x", i, events[i].events));
863
864 /*
865 * Check readability.
866 */
867 if ((events[i].events & EPOLLIN) &&
868 (key_has_pending_read(h) || key_has_pending_accept(h)) && !IS_CLOSING(h) ) {
869
870 #if PJ_IOQUEUE_HAS_SAFE_UNREG
871 increment_counter(h);
872 #endif
873 queue[event_cnt].key = h;
874 queue[event_cnt].event_type = READABLE_EVENT;
875 ++event_cnt;
876 continue;
877 }
878
879 /*
880 * Check for writeability.
881 */
882 if ((events[i].events & EPOLLOUT) && key_has_pending_write(h) && !IS_CLOSING(h)) {
883
884 #if PJ_IOQUEUE_HAS_SAFE_UNREG
885 increment_counter(h);
886 #endif
887 queue[event_cnt].key = h;
888 queue[event_cnt].event_type = WRITEABLE_EVENT;
889 ++event_cnt;
890 continue;
891 }
892
893 #if PJ_HAS_TCP
894 /*
895 * Check for completion of connect() operation.
896 */
897 if ((events[i].events & EPOLLOUT) && (h->connecting) && !IS_CLOSING(h)) {
898
899 #if PJ_IOQUEUE_HAS_SAFE_UNREG
900 increment_counter(h);
901 #endif
902 queue[event_cnt].key = h;
903 queue[event_cnt].event_type = WRITEABLE_EVENT;
904 ++event_cnt;
905 continue;
906 }
907 #endif /* PJ_HAS_TCP */
908
909 /*
910 * Check for error condition.
911 */
912 if ((events[i].events & EPOLLERR) && !IS_CLOSING(h)) {
913 /*
914 * We need to handle this exception event. If it's related to us
915 * connecting, report it as such. If not, just report it as a
916 * read event and the higher layers will handle it.
917 */
918 if (h->connecting) {
919 #if PJ_IOQUEUE_HAS_SAFE_UNREG
920 increment_counter(h);
921 #endif
922 queue[event_cnt].key = h;
923 queue[event_cnt].event_type = EXCEPTION_EVENT;
924 ++event_cnt;
925 } else if (key_has_pending_read(h) || key_has_pending_accept(h)) {
926 #if PJ_IOQUEUE_HAS_SAFE_UNREG
927 increment_counter(h);
928 #endif
929 queue[event_cnt].key = h;
930 queue[event_cnt].event_type = READABLE_EVENT;
931 ++event_cnt;
932 }
933 continue;
934 }
935
936 if (ioqueue->cfg.epoll_flags & PJ_IOQUEUE_EPOLL_ONESHOT) {
937 /* We are not processing this event, but we still need to rearm
938 * to receive future events.
939 */
940 if (!IS_CLOSING(h))
941 update_epoll_event_set(ioqueue, h, h->ev.events);
942 }
943
944 /* There are some innocent cases where this might happen:
945 * 1. TCP outgoing connection failure. Although app has handled the
946 * failure event, epoll will keep reporting EPOLLHUP until the
947 * socket is unregistered.
948 * 2. Thread A and B are woken up for a single EPOLLIN, (or when
949 * EPOLLEXCLUSIVE is used, two packets arrives almost simultaneously,
950 * only single pending recv() was submitted. This also causes both
951 * threads to be woken up. This scenario can be observed in ioq_reg.c
952 * test)
953 * - Thread A is processing the event
954 * - Thread B waits for ioqueue lock
955 * - Thread A releases the ioqueue lock, acquires key lock, remove
956 * pending recv() from list, release key lock (because concurrency
957 * is enabled).
958 * - Thread B resumes, it finds no pending recv() op.
959 * 3. Other scenarios involving TCP in normal operation using plain or
960 * EPOLLEXCLUSIVE (didn't happen with ONESHOT), for both EPOLLIN
961 * and EPOLLOUT events. Not sure what, but it happens only
962 * sporadically, so probably it's fine. This is reproducible with
963 * "tcp (multithreads)" test in ioq_stress_test.c.
964 */
965 TRACE_WARN((THIS_FILE, " UNHANDLED event %d: events=0x%x, h=%p",
966 i, events[i].events, h));
967 }
968 for (i=0; i<event_cnt; ++i) {
969 if (queue[i].key->grp_lock)
970 pj_grp_lock_add_ref_dbg(queue[i].key->grp_lock, "ioqueue", 0);
971 }
972
973 PJ_RACE_ME(5);
974
975 pj_lock_release(ioqueue->lock);
976
977 PJ_RACE_ME(5);
978
979 processed_cnt = 0;
980
981 /* Now process the events. */
982 for (i=0; i<event_cnt; ++i) {
983 /* Just do not exceed PJ_IOQUEUE_MAX_EVENTS_IN_SINGLE_POLL */
984 if (processed_cnt < PJ_IOQUEUE_MAX_EVENTS_IN_SINGLE_POLL) {
985 pj_bool_t event_done = PJ_FALSE;
986 switch (queue[i].event_type) {
987 case READABLE_EVENT:
988 event_done = ioqueue_dispatch_read_event(ioqueue,queue[i].key);
989
990 break;
991 case WRITEABLE_EVENT:
992 event_done = ioqueue_dispatch_write_event(ioqueue,
993 queue[i].key);
994
995 break;
996 case EXCEPTION_EVENT:
997 event_done = ioqueue_dispatch_exception_event(ioqueue,
998 queue[i].key);
999 break;
1000 case NO_EVENT:
1001 pj_assert(!"Invalid event!");
1002 break;
1003 }
1004 if (event_done) {
1005 ++processed_cnt;
1006 }
1007 }
1008
1009 /* Re-arm ONESHOT as long as there are pending requests. This is
1010 * necessary to deal with this case:
1011 * - thread A and B are calling ioqueue_recv()
1012 * - packet arrives, thread A is processing
1013 * - but thread A doesn't call ioqueue_recv() again
1014 * - if we don't rearm here, thread B will never get the event.
1015 *
1016 * On the other hand, if thread A calls ioqueue_recv() again above,
1017 * this will result in double epoll_ctl() calls. This should be okay,
1018 * albeit inefficient. We err on the safe side.
1019 */
1020 if ((ioqueue->cfg.epoll_flags & PJ_IOQUEUE_EPOLL_ONESHOT) &&
1021 (queue[i].key->ev.events & IO_MASK))
1022 {
1023 pj_ioqueue_lock_key(queue[i].key);
1024 update_epoll_event_set(ioqueue, queue[i].key,
1025 queue[i].key->ev.events);
1026 pj_ioqueue_unlock_key(queue[i].key);
1027 }
1028
1029 #if PJ_IOQUEUE_HAS_SAFE_UNREG
1030 decrement_counter(queue[i].key);
1031 #endif
1032
1033 if (queue[i].key->grp_lock)
1034 pj_grp_lock_dec_ref_dbg(queue[i].key->grp_lock,
1035 "ioqueue", 0);
1036 }
1037
1038 /* Special case:
1039 * When epoll returns > 0 but event_cnt, the number of events
1040 * we want to process, is zero.
1041 * There are several possibilities this can happen, see "UNHANDLED event"
1042 * log message above.
1043 */
1044 if (count > 0 && !event_cnt && msec > 0) {
1045 /* We need to sleep in order to avoid busy polling, such
1046 * as in the case of the thread that doesn't process
1047 * the event as explained above.
1048 * Limit the duration of the sleep, as doing pj_thread_sleep() for
1049 * a long time is very inefficient. The main objective here is just
1050 * to avoid busy loop.
1051 */
1052 int delay = msec - pj_elapsed_usec(&t1, &t2)/1000;
1053 if (delay > 10) delay = 10;
1054 if (delay > 0)
1055 pj_thread_sleep(delay);
1056 }
1057
1058 TRACE_((THIS_FILE, " poll: count=%d events=%d processed=%d",
1059 count, event_cnt, processed_cnt));
1060
1061 pj_get_timestamp(&t1);
1062 TRACE_((THIS_FILE, "ioqueue_poll() returns %d, time=%d usec",
1063 processed_cnt, pj_elapsed_usec(&t2, &t1)));
1064
1065 return processed_cnt;
1066 }
1067
1068 PJ_DEF(pj_oshandle_t) pj_ioqueue_get_os_handle( pj_ioqueue_t *ioqueue )
1069 {
1070 return ioqueue ? (pj_oshandle_t)&ioqueue->epfd : NULL;
1071 }
1072
1073 #endif /* PJ_IOQUEUE_IMP == PJ_IOQUEUE_IMP_EPOLL */