Debian Codegraph @

Xpjproject/pjlib/src/pj/ioqueue_common_abs.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 /*
21 * ioqueue_common_abs.c
22 *
23 * This contains common functionalities to emulate proactor pattern with
24 * various event dispatching mechanisms (e.g. select, epoll).
25 *
26 * This file will be included by the appropriate ioqueue implementation.
27 * This file is NOT supposed to be compiled as stand-alone source.
28 */
29
30 #define PENDING_RETRY 2
31
32 #if PJ_IOQUEUE_CALLBACK_NO_LOCK
33 static unsigned ioqueue_dispatch_read_event_no_lock(pj_ioqueue_key_t* h,
34 unsigned max_event);
35 static unsigned ioqueue_dispatch_write_event_no_lock(pj_ioqueue_key_t* h,
36 unsigned max_event);
37 #endif
38
39 PJ_DEF(void) pj_ioqueue_cfg_default(pj_ioqueue_cfg *cfg)
40 {
41 pj_bzero(cfg, sizeof(*cfg));
42 cfg->epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS;
43 cfg->default_concurrency = PJ_IOQUEUE_DEFAULT_ALLOW_CONCURRENCY;
44 }
45
46 static void ioqueue_init( pj_ioqueue_t *ioqueue )
47 {
48 ioqueue->lock = NULL;
49 ioqueue->auto_delete_lock = 0;
50 }
51
52 static pj_status_t ioqueue_destroy(pj_ioqueue_t *ioqueue)
53 {
54 if (ioqueue->auto_delete_lock && ioqueue->lock ) {
55 pj_lock_release(ioqueue->lock);
56 return pj_lock_destroy(ioqueue->lock);
57 }
58
59 return PJ_SUCCESS;
60 }
61
62 /*
63 * pj_ioqueue_set_lock()
64 */
65 PJ_DEF(pj_status_t) pj_ioqueue_set_lock( pj_ioqueue_t *ioqueue,
66 pj_lock_t *lock,
67 pj_bool_t auto_delete )
68 {
69 PJ_ASSERT_RETURN(ioqueue && lock, PJ_EINVAL);
70
71 if (ioqueue->auto_delete_lock && ioqueue->lock) {
72 pj_lock_destroy(ioqueue->lock);
73 }
74
75 ioqueue->lock = lock;
76 ioqueue->auto_delete_lock = auto_delete;
77
78 return PJ_SUCCESS;
79 }
80
81 static pj_status_t ioqueue_init_key( pj_pool_t *pool,
82 pj_ioqueue_t *ioqueue,
83 pj_ioqueue_key_t *key,
84 pj_sock_t sock,
85 pj_grp_lock_t *grp_lock,
86 void *user_data,
87 const pj_ioqueue_callback *cb)
88 {
89 pj_status_t rc;
90 int optlen;
91
92 PJ_UNUSED_ARG(pool);
93
94 key->ioqueue = ioqueue;
95 key->fd = sock;
96 key->user_data = user_data;
97 pj_list_init(&key->read_list);
98 pj_list_init(&key->write_list);
99 #if PJ_HAS_TCP
100 pj_list_init(&key->accept_list);
101 key->connecting = 0;
102 #endif
103 pj_list_init(&key->read_cb_list);
104 key->read_callback_thread = NULL;
105 pj_list_init(&key->write_cb_list);
106 key->write_callback_thread = NULL;
107 key->closing = 0;
108
109 /* Save callback. */
110 pj_memcpy(&key->cb, cb, sizeof(pj_ioqueue_callback));
111
112 #if PJ_IOQUEUE_HAS_SAFE_UNREG
113 /* Set initial reference count to 1 */
114 pj_assert(key->ref_count == 0);
115 ++key->ref_count;
116 #endif
117
118 rc = pj_ioqueue_set_concurrency(key, ioqueue->cfg.default_concurrency);
119 if (rc != PJ_SUCCESS)
120 return rc;
121
122 /* Get socket type. When socket type is datagram, some optimization
123 * will be performed during send to allow parallel send operations.
124 */
125 optlen = sizeof(key->fd_type);
126 rc = pj_sock_getsockopt(sock, pj_SOL_SOCKET(), pj_SO_TYPE(),
127 &key->fd_type, &optlen);
128 if (rc != PJ_SUCCESS)
129 key->fd_type = pj_SOCK_STREAM();
130
131 /* Create mutex for the key. */
132 #if !PJ_IOQUEUE_HAS_SAFE_UNREG
133 rc = pj_lock_create_simple_mutex(pool, NULL, &key->lock);
134 if (rc != PJ_SUCCESS)
135 return rc;
136 #endif
137
138 /* Group lock */
139 key->grp_lock = grp_lock;
140 if (key->grp_lock) {
141 pj_grp_lock_add_ref_dbg(key->grp_lock, "ioqueue", 0);
142 }
143
144 return PJ_SUCCESS;
145 }
146
147 /*
148 * pj_ioqueue_get_user_data()
149 *
150 * Obtain value associated with a key.
151 */
152 PJ_DEF(void*) pj_ioqueue_get_user_data( pj_ioqueue_key_t *key )
153 {
154 PJ_ASSERT_RETURN(key != NULL, NULL);
155 return key->user_data;
156 }
157
158 /*
159 * pj_ioqueue_set_user_data()
160 */
161 PJ_DEF(pj_status_t) pj_ioqueue_set_user_data( pj_ioqueue_key_t *key,
162 void *user_data,
163 void **old_data)
164 {
165 PJ_ASSERT_RETURN(key, PJ_EINVAL);
166
167 if (old_data)
168 *old_data = key->user_data;
169 key->user_data = user_data;
170
171 return PJ_SUCCESS;
172 }
173
174 PJ_INLINE(int) key_has_pending_write(pj_ioqueue_key_t *key)
175 {
176 return !pj_list_empty(&key->write_list);
177 }
178
179 PJ_INLINE(int) key_has_pending_read(pj_ioqueue_key_t *key)
180 {
181 return !pj_list_empty(&key->read_list);
182 }
183
184 PJ_INLINE(int) key_has_pending_accept(pj_ioqueue_key_t *key)
185 {
186 #if PJ_HAS_TCP
187 return !pj_list_empty(&key->accept_list);
188 #else
189 PJ_UNUSED_ARG(key);
190 return 0;
191 #endif
192 }
193
194 PJ_INLINE(int) key_has_pending_connect(pj_ioqueue_key_t *key)
195 {
196 return key->connecting;
197 }
198
199
200 #define IS_CLOSING(key) (key->closing)
201
202
203 /*
204 * ioqueue_dispatch_event()
205 *
206 * Report occurence of an event in the key to be processed by the
207 * framework.
208 */
209 static pj_bool_t ioqueue_dispatch_write_event( pj_ioqueue_t *ioqueue,
210 pj_ioqueue_key_t *h)
211 {
212 pj_status_t rc;
213
214 /* Try lock the key. */
215 rc = pj_ioqueue_trylock_key(h);
216 if (rc != PJ_SUCCESS) {
217 return PJ_FALSE;
218 }
219
220 if (IS_CLOSING(h)) {
221 pj_ioqueue_unlock_key(h);
222 return PJ_TRUE;
223 }
224
225 #if defined(PJ_HAS_TCP) && PJ_HAS_TCP!=0
226 if (h->connecting) {
227 /* Completion of connect() operation */
228 pj_status_t status;
229 pj_bool_t has_lock;
230
231 /* Clear operation. */
232 h->connecting = 0;
233
234 ioqueue_remove_from_set2(ioqueue, h, WRITEABLE_EVENT|EXCEPTION_EVENT);
235
236
237 #if (defined(PJ_HAS_SO_ERROR) && PJ_HAS_SO_ERROR!=0)
238 /* from connect(2):
239 * On Linux, use getsockopt to read the SO_ERROR option at
240 * level SOL_SOCKET to determine whether connect() completed
241 * successfully (if SO_ERROR is zero).
242 */
243 {
244 int value;
245 int vallen = sizeof(value);
246 int gs_rc = pj_sock_getsockopt(h->fd, SOL_SOCKET, SO_ERROR,
247 &value, &vallen);
248 if (gs_rc != 0) {
249 /* Argh!! What to do now???
250 * Just indicate that the socket is connected. The
251 * application will get error as soon as it tries to use
252 * the socket to send/receive.
253 */
254 status = PJ_SUCCESS;
255 } else {
256 status = PJ_STATUS_FROM_OS(value);
257 }
258 }
259 #elif (defined(PJ_WIN32) && PJ_WIN32!=0) || (defined(PJ_WIN64) && PJ_WIN64!=0)
260 status = PJ_SUCCESS; /* success */
261 #else
262 /* Excellent information in D.J. Bernstein page:
263 * http://cr.yp.to/docs/connect.html
264 *
265 * Seems like the most portable way of detecting connect()
266 * failure is to call getpeername(). If socket is connected,
267 * getpeername() will return 0. If the socket is not connected,
268 * it will return ENOTCONN, and read(fd, &ch, 1) will produce
269 * the right errno through error slippage. This is a combination
270 * of suggestions from Douglas C. Schmidt and Ken Keys.
271 */
272 {
273 struct sockaddr_in addr;
274 int addrlen = sizeof(addr);
275
276 status = pj_sock_getpeername(h->fd, (struct sockaddr*)&addr,
277 &addrlen);
278 }
279 #endif
280
281 /* Unlock; from this point we don't need to hold key's mutex
282 * (unless concurrency is disabled, which in this case we should
283 * hold the mutex while calling the callback) */
284 if (h->allow_concurrent) {
285 /* concurrency may be changed while we're in the callback, so
286 * save it to a flag.
287 */
288 has_lock = PJ_FALSE;
289 pj_ioqueue_unlock_key(h);
290 } else {
291 #if PJ_IOQUEUE_CALLBACK_NO_LOCK
292 /* Do not hold mutex while invoking callback */
293 has_lock = PJ_FALSE;
294 pj_ioqueue_unlock_key(h);
295 PJ_RACE_ME(5);
296 #else
297 has_lock = PJ_TRUE;
298 #endif
299 }
300
301 /* Call callback. */
302 if (h->cb.on_connect_complete && !IS_CLOSING(h))
303 (*h->cb.on_connect_complete)(h, status);
304
305 /* Unlock if we still hold the lock */
306 if (has_lock) {
307 pj_ioqueue_unlock_key(h);
308 }
309
310 /* Done. */
311
312 } else
313 #endif /* PJ_HAS_TCP */
314 if (key_has_pending_write(h)) {
315 /* Socket is writable. */
316 struct write_operation *write_op;
317 pj_ssize_t sent;
318 pj_status_t send_rc = PJ_SUCCESS;
319
320 /* Get the first in the queue. */
321 write_op = h->write_list.next;
322
323 /* For datagrams, we can remove the write_op from the list
324 * so that send() can work in parallel.
325 */
326 if (h->fd_type == pj_SOCK_DGRAM()) {
327 pj_list_erase(write_op);
328
329 if (pj_list_empty(&h->write_list))
330 ioqueue_remove_from_set(ioqueue, h, WRITEABLE_EVENT);
331
332 }
333
334 /* Send the data.
335 * Unfortunately we must do this while holding key's mutex, thus
336 * preventing parallel write on a single key.. :-((
337 */
338 sent = write_op->size - write_op->written;
339 if (write_op->op == PJ_IOQUEUE_OP_SEND) {
340 send_rc = pj_sock_send(h->fd, write_op->buf+write_op->written,
341 &sent, write_op->flags);
342 /* Can't do this. We only clear "op" after we're finished sending
343 * the whole buffer.
344 */
345 //write_op->op = 0;
346 } else if (write_op->op == PJ_IOQUEUE_OP_SEND_TO) {
347 int retry = 2;
348 while (--retry >= 0) {
349 send_rc = pj_sock_sendto(h->fd,
350 write_op->buf+write_op->written,
351 &sent, write_op->flags,
352 &write_op->rmt_addr,
353 write_op->rmt_addrlen);
354 #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \
355 PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0
356 /* Special treatment for dead UDP sockets here, see ticket #1107 */
357 if (send_rc==PJ_STATUS_FROM_OS(EPIPE) && !IS_CLOSING(h) &&
358 h->fd_type==pj_SOCK_DGRAM())
359 {
360 PJ_PERROR(4,(THIS_FILE, send_rc,
361 "Send error for socket %ld, retrying",
362 h->fd));
363 send_rc = replace_udp_sock(h);
364 continue;
365 }
366 #endif
367 break;
368 }
369
370 /* Can't do this. We only clear "op" after we're finished sending
371 * the whole buffer.
372 */
373 //write_op->op = 0;
374 } else {
375 pj_assert(!"Invalid operation type!");
376 write_op->op = PJ_IOQUEUE_OP_NONE;
377 send_rc = PJ_EBUG;
378 }
379
380 if (send_rc == PJ_SUCCESS) {
381 write_op->written += sent;
382 } else {
383 pj_assert(send_rc > 0);
384 write_op->written = -send_rc;
385 }
386
387 /* Are we finished with this buffer? */
388 if (send_rc!=PJ_SUCCESS ||
389 write_op->written == (pj_ssize_t)write_op->size ||
390 h->fd_type == pj_SOCK_DGRAM())
391 {
392 pj_bool_t has_lock;
393
394 write_op->op = PJ_IOQUEUE_OP_NONE;
395
396 if (h->fd_type != pj_SOCK_DGRAM()) {
397 /* Write completion of the whole stream. */
398 pj_list_erase(write_op);
399
400 /* Clear operation if there's no more data to send. */
401 if (pj_list_empty(&h->write_list))
402 ioqueue_remove_from_set(ioqueue, h, WRITEABLE_EVENT);
403
404 }
405
406 /* Unlock; from this point we don't need to hold key's mutex
407 * (unless concurrency is disabled, which in this case we should
408 * hold the mutex while calling the callback) */
409 if (h->allow_concurrent) {
410 /* concurrency may be changed while we're in the callback, so
411 * save it to a flag.
412 */
413 has_lock = PJ_FALSE;
414 pj_ioqueue_unlock_key(h);
415 PJ_RACE_ME(5);
416 } else {
417 #if PJ_IOQUEUE_CALLBACK_NO_LOCK
418 /* If we're not allowing concurrency, we must prevent
419 * re-entrancy in the callback.
420 */
421 if (h->write_callback_thread) {
422 /* Another thread is in the write callback for this key,
423 * just queue this write_op, that thread will invoke the
424 * callback later.
425 */
426 pj_list_push_back(&h->write_cb_list, write_op);
427 pj_ioqueue_unlock_key(h);
428 return PJ_TRUE;
429 }
430
431 /* Save the thread invoking the write callback.
432 * Note that when threading is disabled or concurrency is allowed,
433 * this will always be NULL.
434 */
435 h->write_callback_thread = pj_thread_this();
436
437 /* Do not hold mutex while invoking callback */
438 has_lock = PJ_FALSE;
439 pj_ioqueue_unlock_key(h);
440 PJ_RACE_ME(5);
441 #else
442 has_lock = PJ_TRUE;
443 #endif
444 }
445
446 /* Call callback. Do not skip when IS_CLOSING, as upper
447 * layers need the callback to release resources (e.g.,
448 * pjsip_tx_data_dec_ref). See #4878.
449 */
450 if (h->cb.on_write_complete) {
451 (*h->cb.on_write_complete)(h,
452 (pj_ioqueue_op_key_t*)write_op,
453 write_op->written);
454 }
455
456 if (has_lock) {
457 pj_ioqueue_unlock_key(h);
458 }
459
460 #if PJ_IOQUEUE_CALLBACK_NO_LOCK
461 /* If we have more pending write callback, process it now */
462 ioqueue_dispatch_write_event_no_lock(h, 0);
463 #endif
464
465 } else {
466 pj_ioqueue_unlock_key(h);
467 }
468
469 /* Done. */
470 } else {
471 /*
472 * This is normal; execution may fall here when multiple threads
473 * are signalled for the same event, but only one thread eventually
474 * able to process the event.
475 */
476 pj_ioqueue_unlock_key(h);
477
478 return PJ_FALSE;
479 }
480
481 return PJ_TRUE;
482 }
483
484
485 #if PJ_IOQUEUE_CALLBACK_NO_LOCK
486 static unsigned ioqueue_dispatch_read_event_no_lock(pj_ioqueue_key_t* h,
487 unsigned max_event)
488 {
489 unsigned event_cnt = 0;
490
491 while (1) {
492 struct read_operation *read_op = NULL;
493 void (*on_read_complete)(pj_ioqueue_key_t *key,
494 pj_ioqueue_op_key_t *op_key,
495 pj_ssize_t bytes_read);
496
497 /* Check if there is any pending read callback for this key. */
498 pj_ioqueue_lock_key(h);
499
500 if (!IS_CLOSING(h) && !pj_list_empty(&h->read_cb_list) &&
501 (max_event == 0 || event_cnt < max_event))
502 {
503 read_op = h->read_cb_list.next;
504 pj_list_erase(read_op);
505 on_read_complete = h->cb.on_read_complete;
506 } else {
507 /* No more pending callback or maximum event number is reached.
508 * Clear the callback thread and return.
509 */
510 h->read_callback_thread = NULL;
511 on_read_complete = NULL;
512 }
513
514 pj_ioqueue_unlock_key(h);
515 PJ_RACE_ME(5);
516
517 /* Invoke the callback or return */
518 if (on_read_complete) {
519 (*on_read_complete)(h, (pj_ioqueue_op_key_t*)read_op,
520 read_op->bytes_read);
521 ++event_cnt;
522 } else {
523 break;
524 }
525 }
526
527 return event_cnt;
528 }
529
530 static unsigned ioqueue_dispatch_write_event_no_lock(pj_ioqueue_key_t* h,
531 unsigned max_event)
532 {
533 unsigned event_cnt = 0;
534
535 while (1) {
536 struct write_operation *write_op = NULL;
537 void (*on_write_complete)(pj_ioqueue_key_t *key,
538 pj_ioqueue_op_key_t *op_key,
539 pj_ssize_t bytes_sent);
540
541 /* Check if there is any pending write callback for this key. */
542 pj_ioqueue_lock_key(h);
543
544 if (!pj_list_empty(&h->write_cb_list) &&
545 (max_event == 0 || event_cnt < max_event))
546 {
547 write_op = h->write_cb_list.next;
548 pj_list_erase(write_op);
549 on_write_complete = h->cb.on_write_complete;
550 } else {
551 /* No more pending callback or maximum event number is reached.
552 * Clear the callback thread and return.
553 */
554 h->write_callback_thread = NULL;
555 on_write_complete = NULL;
556 }
557
558 pj_ioqueue_unlock_key(h);
559 PJ_RACE_ME(5);
560
561 /* Invoke the callback or return */
562 if (on_write_complete) {
563 (*on_write_complete)(h, (pj_ioqueue_op_key_t*)write_op,
564 write_op->written);
565 ++event_cnt;
566 } else {
567 break;
568 }
569 }
570
571 return event_cnt;
572 }
573 #endif
574
575 /*
576 * Drain pending write callbacks during key unregistration.
577 *
578 * This ensures upper layers (e.g., SIP transport) receive on_write_complete
579 * callbacks for all pending writes, allowing them to release resources such
580 * as tdata references. Without this, pending writes are silently discarded
581 * when a key is unregistered, causing reference leaks. See #4864, #4878.
582 *
583 * Two lists must be drained in order:
584 * 1. write_cb_list (completed ops, deferred callback) - with op->written
585 * 2. write_list (pending ops, never sent) - with -PJ_ECANCELLED
586 *
587 * Must be called after key->closing is set and key is unlocked.
588 * Not used by IOCP backend (which has its own mechanism).
589 */
590 static void ioqueue_drain_pending_writes(pj_ioqueue_key_t *key)
591 {
592 #if PJ_IOQUEUE_CALLBACK_NO_LOCK
593 pj_ioqueue_lock_key(key);
594
595 if (key->write_callback_thread == pj_thread_this()) {
596 /* We are the callback thread (unregister called from within a
597 * write callback). Drain write_cb_list ourselves with success
598 * status, matching the pattern in
599 * ioqueue_dispatch_write_event_no_lock().
600 */
601 while (!pj_list_empty(&key->write_cb_list)) {
602 struct write_operation *op = key->write_cb_list.next;
603 void (*on_wr_complete)(pj_ioqueue_key_t*,
604 pj_ioqueue_op_key_t*,
605 pj_ssize_t);
606
607 pj_list_erase(op);
608 on_wr_complete = key->cb.on_write_complete;
609 if (key->grp_lock)
610 pj_grp_lock_add_ref(key->grp_lock);
611 pj_ioqueue_unlock_key(key);
612
613 if (on_wr_complete) {
614 (*on_wr_complete)(key, (pj_ioqueue_op_key_t*)op,
615 op->written);
616 }
617 if (key->grp_lock)
618 pj_grp_lock_dec_ref(key->grp_lock);
619 pj_ioqueue_lock_key(key);
620 }
621 pj_ioqueue_unlock_key(key);
622 } else if (key->write_callback_thread) {
623 /* Another thread is the callback thread. Wait for it to finish
624 * draining write_cb_list. The IS_CLOSING check has been removed
625 * from ioqueue_dispatch_write_event_no_lock() so the callback
626 * thread will continue to drain even after closing is set.
627 */
628 unsigned counter = 0;
629
630 while (key->write_callback_thread) {
631 pj_ioqueue_unlock_key(key);
632 pj_thread_sleep(10);
633 pj_ioqueue_lock_key(key);
634 if (++counter > 100) {
635 PJ_LOG(1, (THIS_FILE, "Timeout waiting for write "
636 "callback to drain on socket=%ld",
637 (long)key->fd));
638 break;
639 }
640 }
641 pj_ioqueue_unlock_key(key);
642 } else {
643 pj_ioqueue_unlock_key(key);
644 }
645 #endif
646
647 /* Walk write_list with -PJ_ECANCELLED (pending ops, never sent).
648 *
649 * Safe to walk without lock because:
650 * - closing=1 was set while key was locked, so any dispatch thread
651 * that subsequently acquires the lock sees IS_CLOSING and returns
652 * without touching write_list.
653 * - Any in-flight dispatch already dequeued its op from write_list
654 * while holding the lock, before unlocking for the callback.
655 * - pj_ioqueue_send() checks IS_CLOSING under lock, preventing
656 * new entries.
657 * - The socket fd was removed from the polling set before closing
658 * was set, so no new writable events will be dispatched.
659 */
660 while (!pj_list_empty(&key->write_list)) {
661 struct write_operation *op = key->write_list.next;
662
663 pj_list_erase(op);
664 if (key->grp_lock)
665 pj_grp_lock_add_ref(key->grp_lock);
666
667 if (key->cb.on_write_complete) {
668 (*key->cb.on_write_complete)(key, (pj_ioqueue_op_key_t*)op,
669 -(pj_ssize_t)PJ_ECANCELLED);
670 }
671 if (key->grp_lock)
672 pj_grp_lock_dec_ref(key->grp_lock);
673 }
674 }
675
676 static pj_bool_t ioqueue_dispatch_read_event( pj_ioqueue_t *ioqueue,
677 pj_ioqueue_key_t *h )
678 {
679 pj_status_t rc;
680
681 /* Try lock the key. */
682 rc = pj_ioqueue_trylock_key(h);
683 if (rc != PJ_SUCCESS) {
684 return PJ_FALSE;
685 }
686
687 if (IS_CLOSING(h)) {
688 pj_ioqueue_unlock_key(h);
689 return PJ_TRUE;
690 }
691
692 # if PJ_HAS_TCP
693 if (!pj_list_empty(&h->accept_list)) {
694
695 struct accept_operation *accept_op;
696 pj_bool_t has_lock;
697
698 /* Get one accept operation from the list. */
699 accept_op = h->accept_list.next;
700 pj_list_erase(accept_op);
701 accept_op->op = PJ_IOQUEUE_OP_NONE;
702
703 /* Clear bit in fdset if there is no more pending accept */
704 if (pj_list_empty(&h->accept_list))
705 ioqueue_remove_from_set(ioqueue, h, READABLE_EVENT);
706
707 rc=pj_sock_accept(h->fd, accept_op->accept_fd,
708 accept_op->rmt_addr, accept_op->addrlen);
709 if (rc==PJ_SUCCESS && accept_op->local_addr) {
710 rc = pj_sock_getsockname(*accept_op->accept_fd,
711 accept_op->local_addr,
712 accept_op->addrlen);
713 }
714
715 /* Unlock; from this point we don't need to hold key's mutex
716 * (unless concurrency is disabled, which in this case we should
717 * hold the mutex while calling the callback) */
718 if (h->allow_concurrent) {
719 /* concurrency may be changed while we're in the callback, so
720 * save it to a flag.
721 */
722 has_lock = PJ_FALSE;
723 pj_ioqueue_unlock_key(h);
724 PJ_RACE_ME(5);
725 } else {
726 has_lock = PJ_TRUE;
727 }
728
729 /* Call callback. */
730 if (h->cb.on_accept_complete && !IS_CLOSING(h)) {
731 (*h->cb.on_accept_complete)(h,
732 (pj_ioqueue_op_key_t*)accept_op,
733 *accept_op->accept_fd, rc);
734 }
735
736 if (has_lock) {
737 pj_ioqueue_unlock_key(h);
738 }
739 }
740 else
741 # endif
742 if (key_has_pending_read(h)) {
743 struct read_operation *read_op;
744 pj_ssize_t bytes_read;
745 pj_bool_t has_lock;
746 void (*on_read_complete)(pj_ioqueue_key_t *key,
747 pj_ioqueue_op_key_t *op_key,
748 pj_ssize_t bytes_read);
749
750 /* Get one pending read operation from the list. */
751 read_op = h->read_list.next;
752 pj_list_erase(read_op);
753
754 /* Clear fdset if there is no pending read. */
755 if (pj_list_empty(&h->read_list))
756 ioqueue_remove_from_set(ioqueue, h, READABLE_EVENT);
757
758 bytes_read = read_op->size;
759
760 if (read_op->op == PJ_IOQUEUE_OP_RECV_FROM) {
761 read_op->op = PJ_IOQUEUE_OP_NONE;
762 rc = pj_sock_recvfrom(h->fd, read_op->buf, &bytes_read,
763 read_op->flags,
764 read_op->rmt_addr,
765 read_op->rmt_addrlen);
766 } else if (read_op->op == PJ_IOQUEUE_OP_RECV) {
767 read_op->op = PJ_IOQUEUE_OP_NONE;
768 rc = pj_sock_recv(h->fd, read_op->buf, &bytes_read,
769 read_op->flags);
770 } else {
771 pj_assert(read_op->op == PJ_IOQUEUE_OP_READ);
772 read_op->op = PJ_IOQUEUE_OP_NONE;
773 /*
774 * User has specified pj_ioqueue_read().
775 * On Win32, we should do ReadFile(). But because we got
776 * here because of select() anyway, user must have put a
777 * socket descriptor on h->fd, which in this case we can
778 * just call pj_sock_recv() instead of ReadFile().
779 * On Unix, user may put a file in h->fd, so we'll have
780 * to call read() here.
781 * This may not compile on systems which doesn't have
782 * read(). That's why we only specify PJ_LINUX here so
783 * that error is easier to catch.
784 */
785 # if defined(PJ_WIN32) && PJ_WIN32 != 0 || \
786 defined(PJ_WIN64) && PJ_WIN64 != 0 || \
787 defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE != 0
788 rc = pj_sock_recv(h->fd, read_op->buf, &bytes_read,
789 read_op->flags);
790 //rc = ReadFile((HANDLE)h->fd, read_op->buf, read_op->size,
791 // &bytes_read, NULL);
792 # elif (defined(PJ_HAS_UNISTD_H) && PJ_HAS_UNISTD_H != 0)
793 bytes_read = read(h->fd, read_op->buf, bytes_read);
794 rc = (bytes_read >= 0) ? PJ_SUCCESS : pj_get_os_error();
795 # else
796 # error "Implement read() for this platform!"
797 # endif
798 }
799
800 if (rc != PJ_SUCCESS) {
801 # if (defined(PJ_WIN32) && PJ_WIN32 != 0) || \
802 (defined(PJ_WIN64) && PJ_WIN64 != 0)
803 /* On Win32, for UDP, WSAECONNRESET on the receive side
804 * indicates that previous sending has triggered ICMP Port
805 * Unreachable message.
806 * But we wouldn't know at this point which one of previous
807 * key that has triggered the error, since UDP socket can
808 * be shared!
809 * So we'll just ignore it!
810 */
811
812 if (rc == PJ_STATUS_FROM_OS(WSAECONNRESET)) {
813 //PJ_LOG(4,(THIS_FILE,
814 // "Ignored ICMP port unreach. on key=%p", h));
815 }
816 # endif
817
818 /* In any case we would report this to caller. */
819 bytes_read = -rc;
820
821 #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \
822 PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0
823 /* Special treatment for dead UDP sockets here, see ticket #1107 */
824 if (rc == PJ_STATUS_FROM_OS(ENOTCONN) && !IS_CLOSING(h) &&
825 h->fd_type==pj_SOCK_DGRAM())
826 {
827 rc = replace_udp_sock(h);
828 if (rc != PJ_SUCCESS) {
829 bytes_read = -rc;
830 }
831 }
832 #endif
833 }
834
835 read_op->bytes_read = bytes_read;
836 on_read_complete = h->cb.on_read_complete;
837
838 /* Unlock; from this point we don't need to hold key's mutex
839 * (unless concurrency is disabled, which in this case we should
840 * hold the mutex while calling the callback) */
841 if (h->allow_concurrent) {
842 /* concurrency may be changed while we're in the callback, so
843 * save it to a flag.
844 */
845 has_lock = PJ_FALSE;
846 pj_ioqueue_unlock_key(h);
847 PJ_RACE_ME(5);
848 } else {
849 #if PJ_IOQUEUE_CALLBACK_NO_LOCK
850 /* If we're not allowing concurrency, we must prevent
851 * re-entrancy in the callback.
852 */
853 if (h->read_callback_thread) {
854 /* Another thread is in the read callback for this key,
855 * just queue this read_op, that thread will invoke the
856 * callback later.
857 */
858 pj_list_push_back(&h->read_cb_list, read_op);
859 pj_ioqueue_unlock_key(h);
860 return PJ_TRUE;
861 }
862
863 /* Save the thread invoking the read callback.
864 * Note that when threading is disabled or concurrency is allowed,
865 * this will always be NULL.
866 */
867 h->read_callback_thread = pj_thread_this();
868
869 /* Do not hold mutex while invoking callback */
870 has_lock = PJ_FALSE;
871 pj_ioqueue_unlock_key(h);
872 PJ_RACE_ME(5);
873 #else
874 has_lock = PJ_TRUE;
875 #endif
876 }
877
878 /* Call callback. */
879 /* Note that concurrency may be changed while we're in the callback. */
880 if (!IS_CLOSING(h) && on_read_complete) {
881 (*on_read_complete)(h,
882 (pj_ioqueue_op_key_t*)read_op,
883 read_op->bytes_read);
884 }
885
886 if (has_lock) {
887 pj_ioqueue_unlock_key(h);
888 }
889
890 #if PJ_IOQUEUE_CALLBACK_NO_LOCK
891 /* If we have more pending read callback, process it now */
892 ioqueue_dispatch_read_event_no_lock(h, 0);
893 #endif
894
895 } else {
896 /*
897 * This is normal; execution may fall here when multiple threads
898 * are signalled for the same event, but only one thread eventually
899 * able to process the event.
900 */
901 pj_ioqueue_unlock_key(h);
902
903 return PJ_FALSE;
904 }
905
906 return PJ_TRUE;
907 }
908
909
910 static pj_bool_t ioqueue_dispatch_exception_event( pj_ioqueue_t *ioqueue,
911 pj_ioqueue_key_t *h )
912 {
913 pj_bool_t has_lock;
914 pj_status_t rc;
915
916 /* Try lock the key. */
917 rc = pj_ioqueue_trylock_key(h);
918 if (rc != PJ_SUCCESS) {
919 return PJ_FALSE;
920 }
921
922 if (!h->connecting) {
923 /* It is possible that more than one thread was woken up, thus
924 * the remaining thread will see h->connecting as zero because
925 * it has been processed by other thread.
926 */
927 pj_ioqueue_unlock_key(h);
928 return PJ_TRUE;
929 }
930
931 if (IS_CLOSING(h)) {
932 pj_ioqueue_unlock_key(h);
933 return PJ_TRUE;
934 }
935
936 /* Clear operation. */
937 h->connecting = 0;
938
939 ioqueue_remove_from_set2(ioqueue, h, WRITEABLE_EVENT|EXCEPTION_EVENT);
940
941 /* Unlock; from this point we don't need to hold key's mutex
942 * (unless concurrency is disabled, which in this case we should
943 * hold the mutex while calling the callback) */
944 if (h->allow_concurrent) {
945 /* concurrency may be changed while we're in the callback, so
946 * save it to a flag.
947 */
948 has_lock = PJ_FALSE;
949 pj_ioqueue_unlock_key(h);
950 PJ_RACE_ME(5);
951 } else {
952 has_lock = PJ_TRUE;
953 }
954
955 /* Call callback. */
956 if (h->cb.on_connect_complete && !IS_CLOSING(h)) {
957 pj_status_t status = -1;
958 #if (defined(PJ_HAS_SO_ERROR) && PJ_HAS_SO_ERROR!=0)
959 int value;
960 int vallen = sizeof(value);
961 int gs_rc = pj_sock_getsockopt(h->fd, SOL_SOCKET, SO_ERROR,
962 &value, &vallen);
963 if (gs_rc == 0) {
964 status = PJ_RETURN_OS_ERROR(value);
965 }
966 #endif
967
968 (*h->cb.on_connect_complete)(h, status);
969 }
970
971 if (has_lock) {
972 pj_ioqueue_unlock_key(h);
973 }
974
975 return PJ_TRUE;
976 }
977
978 /*
979 * pj_ioqueue_recv()
980 *
981 * Start asynchronous recv() from the socket.
982 */
983 PJ_DEF(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key,
984 pj_ioqueue_op_key_t *op_key,
985 void *buffer,
986 pj_ssize_t *length,
987 unsigned flags )
988 {
989 struct read_operation *read_op;
990
991 PJ_ASSERT_RETURN(key && op_key && buffer && length, PJ_EINVAL);
992 PJ_CHECK_STACK();
993
994 /* Check if key is closing (need to do this first before accessing
995 * other variables, since they might have been destroyed. See ticket
996 * #469).
997 */
998 if (IS_CLOSING(key))
999 return PJ_ECANCELLED;
1000
1001 read_op = (struct read_operation*)op_key;
1002 PJ_ASSERT_RETURN(read_op->op == PJ_IOQUEUE_OP_NONE, PJ_EPENDING);
1003
1004 /* Try to see if there's data immediately available.
1005 */
1006 if ((flags & PJ_IOQUEUE_ALWAYS_ASYNC) == 0) {
1007 pj_status_t status;
1008 pj_ssize_t size;
1009
1010 size = *length;
1011 status = pj_sock_recv(key->fd, buffer, &size, flags);
1012 if (status == PJ_SUCCESS) {
1013 /* Yes! Data is available! */
1014 *length = size;
1015 return PJ_SUCCESS;
1016 } else {
1017 /* If error is not EWOULDBLOCK (or EAGAIN on Linux), report
1018 * the error to caller.
1019 */
1020 if (status != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL))
1021 return status;
1022 }
1023 }
1024
1025 flags &= ~(PJ_IOQUEUE_ALWAYS_ASYNC);
1026
1027 pj_ioqueue_lock_key(key);
1028 /* Check again. Handle may have been closed after the previous check
1029 * in multithreaded app. If we add bad handle to the set it will
1030 * corrupt the ioqueue set. See #913
1031 */
1032 if (IS_CLOSING(key)) {
1033 pj_ioqueue_unlock_key(key);
1034 return PJ_ECANCELLED;
1035 }
1036
1037 /* Also check read_op->op again, this time while holding lock. */
1038 PJ_ASSERT_ON_FAIL(read_op->op == PJ_IOQUEUE_OP_NONE,
1039 {pj_ioqueue_unlock_key(key); return PJ_EPENDING;});
1040 /*
1041 * No data is immediately available.
1042 * Must schedule asynchronous operation to the ioqueue.
1043 */
1044 read_op->op = PJ_IOQUEUE_OP_RECV;
1045 read_op->buf = buffer;
1046 read_op->size = *length;
1047 read_op->flags = flags;
1048
1049 pj_list_insert_before(&key->read_list, read_op);
1050 ioqueue_add_to_set(key->ioqueue, key, READABLE_EVENT);
1051 pj_ioqueue_unlock_key(key);
1052
1053 return PJ_EPENDING;
1054 }
1055
1056 /*
1057 * pj_ioqueue_recvfrom()
1058 *
1059 * Start asynchronous recvfrom() from the socket.
1060 */
1061 PJ_DEF(pj_status_t) pj_ioqueue_recvfrom( pj_ioqueue_key_t *key,
1062 pj_ioqueue_op_key_t *op_key,
1063 void *buffer,
1064 pj_ssize_t *length,
1065 unsigned flags,
1066 pj_sockaddr_t *addr,
1067 int *addrlen)
1068 {
1069 struct read_operation *read_op;
1070
1071 PJ_ASSERT_RETURN(key && op_key && buffer && length, PJ_EINVAL);
1072 PJ_CHECK_STACK();
1073
1074 /* Check if key is closing. */
1075 if (IS_CLOSING(key))
1076 return PJ_ECANCELLED;
1077
1078 read_op = (struct read_operation*)op_key;
1079 PJ_ASSERT_RETURN(read_op->op == PJ_IOQUEUE_OP_NONE, PJ_EPENDING);
1080
1081 /* Try to see if there's data immediately available.
1082 */
1083 if ((flags & PJ_IOQUEUE_ALWAYS_ASYNC) == 0) {
1084 pj_status_t status;
1085 pj_ssize_t size;
1086
1087 size = *length;
1088 status = pj_sock_recvfrom(key->fd, buffer, &size, flags,
1089 addr, addrlen);
1090 if (status == PJ_SUCCESS) {
1091 /* Yes! Data is available! */
1092 *length = size;
1093 return PJ_SUCCESS;
1094 } else {
1095 /* If error is not EWOULDBLOCK (or EAGAIN on Linux), report
1096 * the error to caller.
1097 */
1098 if (status != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL))
1099 return status;
1100 }
1101 }
1102
1103 flags &= ~(PJ_IOQUEUE_ALWAYS_ASYNC);
1104
1105 pj_ioqueue_lock_key(key);
1106 /* Check again. Handle may have been closed after the previous check
1107 * in multithreaded app. If we add bad handle to the set it will
1108 * corrupt the ioqueue set. See #913
1109 */
1110 if (IS_CLOSING(key)) {
1111 pj_ioqueue_unlock_key(key);
1112 return PJ_ECANCELLED;
1113 }
1114
1115 /* Also check read_op->op again, this time while holding lock. */
1116 PJ_ASSERT_ON_FAIL(read_op->op == PJ_IOQUEUE_OP_NONE,
1117 {pj_ioqueue_unlock_key(key); return PJ_EPENDING;});
1118 /*
1119 * No data is immediately available.
1120 * Must schedule asynchronous operation to the ioqueue.
1121 */
1122 read_op->op = PJ_IOQUEUE_OP_RECV_FROM;
1123 read_op->buf = buffer;
1124 read_op->size = *length;
1125 read_op->flags = flags;
1126 read_op->rmt_addr = addr;
1127 read_op->rmt_addrlen = addrlen;
1128
1129 pj_list_insert_before(&key->read_list, read_op);
1130 ioqueue_add_to_set(key->ioqueue, key, READABLE_EVENT);
1131 pj_ioqueue_unlock_key(key);
1132
1133 return PJ_EPENDING;
1134 }
1135
1136 /*
1137 * pj_ioqueue_send()
1138 *
1139 * Start asynchronous send() to the descriptor.
1140 */
1141 PJ_DEF(pj_status_t) pj_ioqueue_send( pj_ioqueue_key_t *key,
1142 pj_ioqueue_op_key_t *op_key,
1143 const void *data,
1144 pj_ssize_t *length,
1145 unsigned flags)
1146 {
1147 struct write_operation *write_op;
1148 pj_status_t status;
1149 unsigned retry;
1150 pj_ssize_t sent;
1151
1152 PJ_ASSERT_RETURN(key && op_key && data && length, PJ_EINVAL);
1153 PJ_CHECK_STACK();
1154
1155 /* Check if key is closing. */
1156 if (IS_CLOSING(key))
1157 return PJ_ECANCELLED;
1158
1159 /* We can not use PJ_IOQUEUE_ALWAYS_ASYNC for socket write. */
1160 flags &= ~(PJ_IOQUEUE_ALWAYS_ASYNC);
1161
1162 #if PJ_IOQUEUE_FAST_TRACK
1163 /* Fast track:
1164 * Try to send data immediately, only if there's no pending write!
1165 * Note:
1166 * We are speculating that the list is empty here without properly
1167 * acquiring ioqueue's mutex first. This is intentional, to maximize
1168 * performance via parallelism.
1169 *
1170 * This should be safe, because:
1171 * - by convention, we require caller to make sure that the
1172 * key is not unregistered while other threads are invoking
1173 * an operation on the same key.
1174 * - pj_list_empty() is safe to be invoked by multiple threads,
1175 * even when other threads are modifying the list.
1176 */
1177 if (pj_list_empty(&key->write_list)) {
1178 /*
1179 * See if data can be sent immediately.
1180 */
1181 sent = *length;
1182 status = pj_sock_send(key->fd, data, &sent, flags);
1183 if (status == PJ_SUCCESS) {
1184 /* Success! */
1185 *length = sent;
1186 return PJ_SUCCESS;
1187 } else {
1188 /* If error is not EWOULDBLOCK (or EAGAIN on Linux), report
1189 * the error to caller.
1190 */
1191 if (status != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)) {
1192 return status;
1193 }
1194 }
1195 }
1196 #else
1197 PJ_UNUSED_ARG(status);
1198 PJ_UNUSED_ARG(sent);
1199 #endif
1200
1201 /*
1202 * Schedule asynchronous send.
1203 */
1204 write_op = (struct write_operation*)op_key;
1205
1206 /* Spin if write_op has pending operation */
1207 for (retry=0; write_op->op != 0 && retry<PENDING_RETRY; ++retry)
1208 pj_thread_sleep(0);
1209
1210 /* Last chance */
1211 if (write_op->op) {
1212 /* Unable to send packet because there is already pending write in the
1213 * write_op. We could not put the operation into the write_op
1214 * because write_op already contains a pending operation! And
1215 * we could not send the packet directly with send() either,
1216 * because that will break the order of the packet. So we can
1217 * only return error here.
1218 *
1219 * This could happen for example in multithreads program,
1220 * where polling is done by one thread, while other threads are doing
1221 * the sending only. If the polling thread runs on lower priority
1222 * than the sending thread, then it's possible that the pending
1223 * write flag is not cleared in-time because clearing is only done
1224 * during polling.
1225 *
1226 * Aplication should specify multiple write operation keys on
1227 * situation like this.
1228 */
1229 //pj_assert(!"ioqueue: there is pending operation on this key!");
1230 return PJ_EBUSY;
1231 }
1232
1233 pj_ioqueue_lock_key(key);
1234 /* Check again. Handle may have been closed after the previous check
1235 * in multithreaded app. If we add bad handle to the set it will
1236 * corrupt the ioqueue set. See #913
1237 */
1238 if (IS_CLOSING(key)) {
1239 pj_ioqueue_unlock_key(key);
1240 return PJ_ECANCELLED;
1241 }
1242
1243 /* Also check write_op->op again, this time while holding lock. */
1244 if (write_op->op) {
1245 pj_ioqueue_unlock_key(key);
1246 return PJ_EBUSY;
1247 }
1248
1249 write_op->op = PJ_IOQUEUE_OP_SEND;
1250 write_op->buf = (char*)data;
1251 write_op->size = *length;
1252 write_op->written = 0;
1253 write_op->flags = flags;
1254
1255 pj_list_insert_before(&key->write_list, write_op);
1256 ioqueue_add_to_set(key->ioqueue, key, WRITEABLE_EVENT);
1257 pj_ioqueue_unlock_key(key);
1258
1259 return PJ_EPENDING;
1260 }
1261
1262
1263 /*
1264 * pj_ioqueue_sendto()
1265 *
1266 * Start asynchronous write() to the descriptor.
1267 */
1268 PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key,
1269 pj_ioqueue_op_key_t *op_key,
1270 const void *data,
1271 pj_ssize_t *length,
1272 pj_uint32_t flags,
1273 const pj_sockaddr_t *addr,
1274 int addrlen)
1275 {
1276 struct write_operation *write_op;
1277 unsigned retry;
1278 pj_bool_t restart_retry = PJ_FALSE;
1279 pj_status_t status;
1280 pj_ssize_t sent;
1281
1282 PJ_ASSERT_RETURN(key && op_key && data && length, PJ_EINVAL);
1283 PJ_CHECK_STACK();
1284
1285 #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \
1286 PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0
1287 retry_on_restart:
1288 #else
1289 PJ_UNUSED_ARG(restart_retry);
1290 #endif
1291 /* Check if key is closing. */
1292 if (IS_CLOSING(key))
1293 return PJ_ECANCELLED;
1294
1295 /* We can not use PJ_IOQUEUE_ALWAYS_ASYNC for socket write */
1296 flags &= ~(PJ_IOQUEUE_ALWAYS_ASYNC);
1297
1298 #if PJ_IOQUEUE_FAST_TRACK
1299 /* Fast track:
1300 * Try to send data immediately, only if there's no pending write!
1301 * Note:
1302 * We are speculating that the list is empty here without properly
1303 * acquiring ioqueue's mutex first. This is intentional, to maximize
1304 * performance via parallelism.
1305 *
1306 * This should be safe, because:
1307 * - by convention, we require caller to make sure that the
1308 * key is not unregistered while other threads are invoking
1309 * an operation on the same key.
1310 * - pj_list_empty() is safe to be invoked by multiple threads,
1311 * even when other threads are modifying the list.
1312 */
1313 if (pj_list_empty(&key->write_list)) {
1314 /*
1315 * See if data can be sent immediately.
1316 */
1317 sent = *length;
1318 status = pj_sock_sendto(key->fd, data, &sent, flags, addr, addrlen);
1319 if (status == PJ_SUCCESS) {
1320 /* Success! */
1321 *length = sent;
1322 return PJ_SUCCESS;
1323 } else {
1324 /* If error is not EWOULDBLOCK (or EAGAIN on Linux), report
1325 * the error to caller.
1326 */
1327 if (status != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)) {
1328 #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \
1329 PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0
1330 /* Special treatment for dead UDP sockets here, see ticket #1107 */
1331 if (status == PJ_STATUS_FROM_OS(EPIPE) && !IS_CLOSING(key) &&
1332 key->fd_type == pj_SOCK_DGRAM())
1333 {
1334 if (!restart_retry) {
1335 PJ_PERROR(4, (THIS_FILE, status,
1336 "Send error for socket %ld, retrying",
1337 key->fd));
1338 status = replace_udp_sock(key);
1339 if (status == PJ_SUCCESS) {
1340 restart_retry = PJ_TRUE;
1341 goto retry_on_restart;
1342 }
1343 }
1344 status = PJ_ESOCKETSTOP;
1345 }
1346 #endif
1347 return status;
1348 }
1349 }
1350 }
1351 #else
1352 PJ_UNUSED_ARG(status);
1353 PJ_UNUSED_ARG(sent);
1354 #endif
1355
1356 /*
1357 * Check that address storage can hold the address parameter.
1358 */
1359 PJ_ASSERT_RETURN(addrlen <= (int)sizeof(pj_sockaddr), PJ_EBUG);
1360
1361 /*
1362 * Schedule asynchronous send.
1363 */
1364 write_op = (struct write_operation*)op_key;
1365
1366 /* Spin if write_op has pending operation */
1367 for (retry=0; write_op->op != 0 && retry<PENDING_RETRY; ++retry)
1368 pj_thread_sleep(0);
1369
1370 /* Last chance */
1371 if (write_op->op) {
1372 /* Unable to send packet because there is already pending write on the
1373 * write_op. We could not put the operation into the write_op
1374 * because write_op already contains a pending operation! And
1375 * we could not send the packet directly with sendto() either,
1376 * because that will break the order of the packet. So we can
1377 * only return error here.
1378 *
1379 * This could happen for example in multithreads program,
1380 * where polling is done by one thread, while other threads are doing
1381 * the sending only. If the polling thread runs on lower priority
1382 * than the sending thread, then it's possible that the pending
1383 * write flag is not cleared in-time because clearing is only done
1384 * during polling.
1385 *
1386 * Aplication should specify multiple write operation keys on
1387 * situation like this.
1388 */
1389 //pj_assert(!"ioqueue: there is pending operation on this key!");
1390 return PJ_EBUSY;
1391 }
1392
1393 pj_ioqueue_lock_key(key);
1394 /* Check again. Handle may have been closed after the previous check
1395 * in multithreaded app. If we add bad handle to the set it will
1396 * corrupt the ioqueue set. See #913
1397 */
1398 if (IS_CLOSING(key)) {
1399 pj_ioqueue_unlock_key(key);
1400 return PJ_ECANCELLED;
1401 }
1402
1403 /* Also check write_op->op again, this time while holding lock. */
1404 if (write_op->op) {
1405 pj_ioqueue_unlock_key(key);
1406 return PJ_EBUSY;
1407 }
1408
1409 write_op->op = PJ_IOQUEUE_OP_SEND_TO;
1410 write_op->buf = (char*)data;
1411 write_op->size = *length;
1412 write_op->written = 0;
1413 write_op->flags = flags;
1414 pj_memcpy(&write_op->rmt_addr, addr, addrlen);
1415 write_op->rmt_addrlen = addrlen;
1416
1417 pj_list_insert_before(&key->write_list, write_op);
1418 ioqueue_add_to_set(key->ioqueue, key, WRITEABLE_EVENT);
1419 pj_ioqueue_unlock_key(key);
1420
1421 return PJ_EPENDING;
1422 }
1423
1424 #if PJ_HAS_TCP
1425 /*
1426 * Initiate overlapped accept() operation.
1427 */
1428 PJ_DEF(pj_status_t) pj_ioqueue_accept( pj_ioqueue_key_t *key,
1429 pj_ioqueue_op_key_t *op_key,
1430 pj_sock_t *new_sock,
1431 pj_sockaddr_t *local,
1432 pj_sockaddr_t *remote,
1433 int *addrlen)
1434 {
1435 struct accept_operation *accept_op;
1436 pj_status_t status;
1437
1438 /* check parameters. All must be specified! */
1439 PJ_ASSERT_RETURN(key && op_key && new_sock, PJ_EINVAL);
1440
1441 /* Check if key is closing. */
1442 if (IS_CLOSING(key))
1443 return PJ_ECANCELLED;
1444
1445 accept_op = (struct accept_operation*)op_key;
1446 PJ_ASSERT_RETURN(accept_op->op == PJ_IOQUEUE_OP_NONE, PJ_EPENDING);
1447
1448 #if PJ_IOQUEUE_FAST_TRACK
1449 /* Fast track:
1450 * See if there's new connection available immediately.
1451 */
1452 if (pj_list_empty(&key->accept_list)) {
1453 status = pj_sock_accept(key->fd, new_sock, remote, addrlen);
1454 if (status == PJ_SUCCESS) {
1455 /* Yes! New connection is available! */
1456 if (local && addrlen) {
1457 status = pj_sock_getsockname(*new_sock, local, addrlen);
1458 if (status != PJ_SUCCESS) {
1459 pj_sock_close(*new_sock);
1460 *new_sock = PJ_INVALID_SOCKET;
1461 return status;
1462 }
1463 }
1464 return PJ_SUCCESS;
1465 } else {
1466 /* If error is not EWOULDBLOCK (or EAGAIN on Linux), report
1467 * the error to caller.
1468 */
1469 if (status != PJ_STATUS_FROM_OS(PJ_BLOCKING_ERROR_VAL)) {
1470 return status;
1471 }
1472 }
1473 }
1474 #else
1475 PJ_UNUSED_ARG(status);
1476 #endif
1477
1478 pj_ioqueue_lock_key(key);
1479 /* Check again. Handle may have been closed after the previous check
1480 * in multithreaded app. If we add bad handle to the set it will
1481 * corrupt the ioqueue set. See #913
1482 */
1483 if (IS_CLOSING(key)) {
1484 pj_ioqueue_unlock_key(key);
1485 return PJ_ECANCELLED;
1486 }
1487
1488 /* Also check accept_op->op again, this time while holding lock. */
1489 PJ_ASSERT_ON_FAIL(accept_op->op == PJ_IOQUEUE_OP_NONE,
1490 {pj_ioqueue_unlock_key(key); return PJ_ECANCELLED;});
1491
1492 /*
1493 * No connection is available immediately.
1494 * Schedule accept() operation to be completed when there is incoming
1495 * connection available.
1496 */
1497 accept_op->op = PJ_IOQUEUE_OP_ACCEPT;
1498 accept_op->accept_fd = new_sock;
1499 accept_op->rmt_addr = remote;
1500 accept_op->addrlen= addrlen;
1501 accept_op->local_addr = local;
1502
1503 pj_list_insert_before(&key->accept_list, accept_op);
1504 ioqueue_add_to_set(key->ioqueue, key, READABLE_EVENT);
1505 pj_ioqueue_unlock_key(key);
1506
1507 return PJ_EPENDING;
1508 }
1509
1510 /*
1511 * Initiate overlapped connect() operation (well, it's non-blocking actually,
1512 * since there's no overlapped version of connect()).
1513 */
1514 PJ_DEF(pj_status_t) pj_ioqueue_connect( pj_ioqueue_key_t *key,
1515 const pj_sockaddr_t *addr,
1516 int addrlen )
1517 {
1518 pj_status_t status;
1519
1520 /* check parameters. All must be specified! */
1521 PJ_ASSERT_RETURN(key && addr && addrlen, PJ_EINVAL);
1522
1523 /* Check if key is closing. */
1524 if (IS_CLOSING(key))
1525 return PJ_ECANCELLED;
1526
1527 /* Check if socket has not been marked for connecting */
1528 if (key->connecting != 0)
1529 return PJ_EPENDING;
1530
1531 status = pj_sock_connect(key->fd, addr, addrlen);
1532 if (status == PJ_SUCCESS) {
1533 /* Connected! */
1534 return PJ_SUCCESS;
1535 } else {
1536 if (status == PJ_STATUS_FROM_OS(PJ_BLOCKING_CONNECT_ERROR_VAL)) {
1537 /* Pending! */
1538 pj_ioqueue_lock_key(key);
1539 /* Check again. Handle may have been closed after the previous
1540 * check in multithreaded app. See #913
1541 */
1542 if (IS_CLOSING(key)) {
1543 pj_ioqueue_unlock_key(key);
1544 return PJ_ECANCELLED;
1545 }
1546 key->connecting = PJ_TRUE;
1547 ioqueue_add_to_set2(key->ioqueue, key,
1548 WRITEABLE_EVENT|EXCEPTION_EVENT);
1549 pj_ioqueue_unlock_key(key);
1550 return PJ_EPENDING;
1551 } else {
1552 /* Error! */
1553 return status;
1554 }
1555 }
1556 }
1557 #endif /* PJ_HAS_TCP */
1558
1559
1560 PJ_DEF(void) pj_ioqueue_op_key_init( pj_ioqueue_op_key_t *op_key,
1561 pj_size_t size )
1562 {
1563 pj_bzero(op_key, size);
1564 }
1565
1566
1567 /*
1568 * pj_ioqueue_is_pending()
1569 */
1570 PJ_DEF(pj_bool_t) pj_ioqueue_is_pending( pj_ioqueue_key_t *key,
1571 pj_ioqueue_op_key_t *op_key )
1572 {
1573 struct generic_operation *op_rec;
1574
1575 PJ_UNUSED_ARG(key);
1576
1577 op_rec = (struct generic_operation*)op_key;
1578 return op_rec->op != 0;
1579 }
1580
1581
1582 /*
1583 * pj_ioqueue_post_completion()
1584 */
1585 PJ_DEF(pj_status_t) pj_ioqueue_post_completion( pj_ioqueue_key_t *key,
1586 pj_ioqueue_op_key_t *op_key,
1587 pj_ssize_t bytes_status )
1588 {
1589 struct generic_operation *op_rec;
1590
1591 /*
1592 * Find the operation key in all pending operation list to
1593 * really make sure that it's still there; then call the callback.
1594 */
1595 pj_ioqueue_lock_key(key);
1596
1597 /* Find the operation in the pending read list. */
1598 op_rec = (struct generic_operation*)key->read_list.next;
1599 while (op_rec != (void*)&key->read_list) {
1600 if (op_rec == (void*)op_key) {
1601 pj_list_erase(op_rec);
1602 op_rec->op = PJ_IOQUEUE_OP_NONE;
1603 ioqueue_remove_from_set(key->ioqueue, key, READABLE_EVENT);
1604 pj_ioqueue_unlock_key(key);
1605
1606 if (key->cb.on_read_complete)
1607 (*key->cb.on_read_complete)(key, op_key, bytes_status);
1608 return PJ_SUCCESS;
1609 }
1610 op_rec = op_rec->next;
1611 }
1612
1613 /* Find the operation in the pending write list. */
1614 op_rec = (struct generic_operation*)key->write_list.next;
1615 while (op_rec != (void*)&key->write_list) {
1616 if (op_rec == (void*)op_key) {
1617 pj_list_erase(op_rec);
1618 op_rec->op = PJ_IOQUEUE_OP_NONE;
1619 ioqueue_remove_from_set(key->ioqueue, key, WRITEABLE_EVENT);
1620 pj_ioqueue_unlock_key(key);
1621
1622 if (key->cb.on_write_complete)
1623 (*key->cb.on_write_complete)(key, op_key, bytes_status);
1624 return PJ_SUCCESS;
1625 }
1626 op_rec = op_rec->next;
1627 }
1628
1629 /* Find the operation in the pending accept list. */
1630 op_rec = (struct generic_operation*)key->accept_list.next;
1631 while (op_rec != (void*)&key->accept_list) {
1632 if (op_rec == (void*)op_key) {
1633 pj_list_erase(op_rec);
1634 op_rec->op = PJ_IOQUEUE_OP_NONE;
1635 pj_ioqueue_unlock_key(key);
1636
1637 if (key->cb.on_accept_complete) {
1638 (*key->cb.on_accept_complete)(key, op_key,
1639 PJ_INVALID_SOCKET,
1640 (pj_status_t)bytes_status);
1641 }
1642 return PJ_SUCCESS;
1643 }
1644 op_rec = op_rec->next;
1645 }
1646
1647 /* Clear connecting operation. */
1648 if (key->connecting) {
1649 key->connecting = 0;
1650 ioqueue_remove_from_set2(key->ioqueue, key,
1651 WRITEABLE_EVENT|EXCEPTION_EVENT);
1652 }
1653
1654 pj_ioqueue_unlock_key(key);
1655
1656 return PJ_EINVALIDOP;
1657 }
1658
1659
1660 PJ_DEF(pj_status_t) pj_ioqueue_clear_key( pj_ioqueue_key_t *key )
1661 {
1662 PJ_ASSERT_RETURN(key, PJ_EINVAL);
1663
1664 pj_ioqueue_lock_key(key);
1665
1666 /* Reset pending lists */
1667 pj_list_init(&key->read_list);
1668 pj_list_init(&key->write_list);
1669 pj_list_init(&key->accept_list);
1670 pj_list_init(&key->read_cb_list);
1671 pj_list_init(&key->write_cb_list);
1672
1673 #if PJ_IOQUEUE_CALLBACK_NO_LOCK
1674 /* Wait until any read callback is finished */
1675 do {
1676 unsigned counter = 0;
1677
1678 while (key->read_callback_thread &&
1679 key->read_callback_thread != pj_thread_this())
1680 {
1681 /* Callback is running, unlock while waiting, since the callback
1682 * may need the lock.
1683 */
1684 pj_ioqueue_unlock_key(key);
1685 pj_thread_sleep(10);
1686 pj_ioqueue_lock_key(key);
1687
1688 /* Clear read pending list again */
1689 pj_list_init(&key->read_list);
1690
1691 /* Timeout after ~1 second */
1692 if (++counter > 100) {
1693 PJ_LOG(1,(THIS_FILE, "Timeout waiting for read callback "
1694 "to finish on socket=%ld", key->fd));
1695 break;
1696 }
1697 }
1698 } while (0);
1699
1700 /* Wait until any write callback is finished */
1701 do {
1702 unsigned counter = 0;
1703
1704 while (key->write_callback_thread &&
1705 key->write_callback_thread != pj_thread_this())
1706 {
1707 /* Callback is running, unlock while waiting, since the callback
1708 * may need the lock.
1709 */
1710 pj_ioqueue_unlock_key(key);
1711 pj_thread_sleep(10);
1712 pj_ioqueue_lock_key(key);
1713
1714 /* Clear write pending list again */
1715 pj_list_init(&key->write_list);
1716
1717 /* Timeout after ~1 second */
1718 if (++counter > 100) {
1719 PJ_LOG(1,(THIS_FILE, "Timeout waiting for write callback "
1720 "to finish on socket=%ld", key->fd));
1721 break;
1722 }
1723 }
1724 } while (0);
1725 #endif
1726
1727 key->connecting = 0;
1728
1729 /* Remove key from sets */
1730 ioqueue_remove_from_set2(key->ioqueue, key,
1731 READABLE_EVENT|WRITEABLE_EVENT|EXCEPTION_EVENT);
1732
1733 pj_ioqueue_unlock_key(key);
1734
1735 return PJ_SUCCESS;
1736
1737 }
1738
1739
1740 PJ_DEF(pj_status_t) pj_ioqueue_set_default_concurrency( pj_ioqueue_t *ioqueue,
1741 pj_bool_t allow)
1742 {
1743 PJ_ASSERT_RETURN(ioqueue != NULL, PJ_EINVAL);
1744 ioqueue->cfg.default_concurrency = allow;
1745 return PJ_SUCCESS;
1746 }
1747
1748
1749 PJ_DEF(pj_status_t) pj_ioqueue_set_concurrency(pj_ioqueue_key_t *key,
1750 pj_bool_t allow)
1751 {
1752 PJ_ASSERT_RETURN(key, PJ_EINVAL);
1753
1754 /* PJ_IOQUEUE_HAS_SAFE_UNREG must be enabled if concurrency is
1755 * disabled.
1756 */
1757 PJ_ASSERT_RETURN(allow || PJ_IOQUEUE_HAS_SAFE_UNREG, PJ_EINVAL);
1758
1759 key->allow_concurrent = allow;
1760 return PJ_SUCCESS;
1761 }
1762
1763 PJ_DEF(pj_status_t) pj_ioqueue_lock_key(pj_ioqueue_key_t *key)
1764 {
1765 if (key->grp_lock)
1766 return pj_grp_lock_acquire(key->grp_lock);
1767 else
1768 return pj_lock_acquire(key->lock);
1769 }
1770
1771 PJ_DEF(pj_status_t) pj_ioqueue_trylock_key(pj_ioqueue_key_t *key)
1772 {
1773 if (key->grp_lock)
1774 return pj_grp_lock_tryacquire(key->grp_lock);
1775 else
1776 return pj_lock_tryacquire(key->lock);
1777 }
1778
1779 PJ_DEF(pj_status_t) pj_ioqueue_unlock_key(pj_ioqueue_key_t *key)
1780 {
1781 if (key->grp_lock)
1782 return pj_grp_lock_release(key->grp_lock);
1783 else
1784 return pj_lock_release(key->lock);
1785 }
1786
1787