tport_threadpool.c 19.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*
 * This file is part of the Sofia-SIP package
 *
 * Copyright (C) 2006 Nokia Corporation.
 *
 * Contact: Pekka Pessi <pekka.pessi@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

25
/**@CFILE tport_threadpool.c Multithreading transport
26 27 28 29 30 31 32 33 34 35 36
 *
 * See tport.docs for more detailed description of tport interface.
 *
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>
 * @author Martti Mela <Martti.Mela@nokia.com>
 *
 * @date Created: Fri Mar 24 08:45:49 EET 2006 ppessi
 */

#include "config.h"

37
#undef HAVE_SIGCOMP
38 39 40 41 42 43 44 45 46 47 48 49 50

#define SU_ROOT_MAGIC_T         struct tport_threadpool
#define SU_WAKEUP_ARG_T         struct tport_s
#define SU_MSG_ARG_T            union tport_su_msg_arg

#include "tport_internal.h"

#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <errno.h>
#include <limits.h>

51 52 53 54 55 56 57
#if HAVE_FUNC
#elif HAVE_FUNCTION
#define __func__ __FUNCTION__
#else
static char const __func__[] = "tport_threadpool";
#endif

58 59
/* ==== Thread pools =================================================== */

60
typedef struct threadpool threadpool_t;
61

62 63 64 65 66 67 68
typedef struct {
  tport_primary_t tptp_primary;
  threadpool_t   *tptp_pool;   /**< Worker threads */
  unsigned        tptp_poolsize;
} tport_threadpool_t;

struct threadpool
69 70 71
{
  /* Shared */
  su_clone_r thrp_clone;
72
  tport_threadpool_t *thrp_tport;
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

  int        thrp_killing; /* Threadpool is being killed */

  /* Private variables */
  su_root_t    *thrp_root;
  int           thrp_reg;
  struct sigcomp_compartment *thrp_compartment;
  su_msg_r   thrp_rmsg;

  /* Slave thread counters */
  int        thrp_r_sent;
  int        thrp_s_recv;

  unsigned   thrp_rcvd_msgs;
  unsigned   thrp_rcvd_bytes;

  /* Master thread counters */
  int        thrp_s_sent;
  int        thrp_r_recv;

  int        thrp_yield;
};

96
typedef struct
97
{
98
  threadpool_t *tpd_thrp;
99 100 101 102 103 104 105 106 107 108 109 110 111 112
  int  tpd_errorcode;
  msg_t *tpd_msg;
  su_time_t tpd_when;
  unsigned tpd_mtu;
#if HAVE_SIGCOMP
  struct sigcomp_compartment *tpd_cc;
#endif
  struct sigcomp_udvm *tpd_udvm;
  socklen_t tpd_namelen;
  su_sockaddr_t tpd_name[1];
} thrp_udp_deliver_t;

union tport_su_msg_arg
{
113
  threadpool_t   *thrp;
114 115 116
  thrp_udp_deliver_t thrp_udp_deliver[1];
};

117 118 119
int tport_threadpool_init_primary(tport_primary_t *,
				  tp_name_t tpn[1],
				  su_addrinfo_t *,
120 121 122 123 124 125
				  tagi_t const *,
				  char const **return_culprit);
static void tport_threadpool_deinit_primary(tport_primary_t *pri);

static int tport_thread_send(tport_t *tp,
			     msg_t *msg,
126
			     tp_name_t const *tpn,
127 128 129
			     struct sigcomp_compartment *cc,
			     unsigned mtu);

130
tport_vtable_t const tport_threadpool_vtable =
131 132
{
  "udp", tport_type_local,
133
  sizeof (tport_threadpool_t),
134 135 136 137
  tport_threadpool_init_primary,
  tport_threadpool_deinit_primary,
  NULL,
  NULL,
138
  0,				/* No secondary transports! */
139 140 141 142 143 144 145 146 147 148 149
  NULL,
  NULL,
  NULL,
  NULL,
  NULL,
  tport_recv_dgram,
  tport_send_dgram,
  NULL,
  tport_thread_send
};

150 151
static int thrp_udp_init(su_root_t *, threadpool_t *);
static void thrp_udp_deinit(su_root_t *, threadpool_t *);
152 153
static int thrp_udp_event(threadpool_t *thrp,
			    su_wait_t *w,
154
			    tport_t *_tp);
155 156
static int thrp_udp_recv_deliver(threadpool_t *thrp,
				 tport_t const *tp,
157 158
				 thrp_udp_deliver_t *tpd,
				 int events);
159
static int thrp_udp_recv(threadpool_t *thrp, thrp_udp_deliver_t *tpd);
160
#if HAVE_SIGCOMP
161
static int thrp_udvm_decompress(threadpool_t *thrp,
162 163
				thrp_udp_deliver_t *tpd);
#endif
164
static void thrp_udp_deliver(threadpool_t *thrp,
165 166
			     su_msg_r msg,
			     union tport_su_msg_arg *arg);
167
static void thrp_udp_deliver_report(threadpool_t *thrp,
168 169
				    su_msg_r m,
				    union tport_su_msg_arg *arg);
170
static void thrp_udp_send(threadpool_t *thrp,
171 172
			  su_msg_r msg,
			  union tport_su_msg_arg *arg);
173
static void thrp_udp_send_report(threadpool_t *thrp,
174 175 176 177 178
				 su_msg_r msg,
				 union tport_su_msg_arg *arg);


/** Launch threads in the tport pool. */
179 180
int tport_threadpool_init_primary(tport_primary_t *pri,
				  tp_name_t tpn[1],
181 182 183 184
				  su_addrinfo_t *ai,
				  tagi_t const *tags,
				  char const **return_culprit)
{
185
  tport_threadpool_t *tptp = (tport_threadpool_t *)pri;
186
  tport_t *tp = pri->pri_primary;
187
  threadpool_t *thrp;
188 189 190 191 192 193 194
  int i, N = tp->tp_params->tpp_thrpsize;

  assert(ai->ai_socktype == SOCK_DGRAM);

  if (tport_udp_init_primary(pri, tpn, ai, tags, return_culprit) < 0)
    return -1;

195
  if (N == 0)
196 197 198 199 200 201 202 203
    return 0;

  thrp = su_zalloc(tp->tp_home, (sizeof *thrp) * N);
  if (!thrp)
    return -1;

  su_setblocking(tp->tp_socket, 0);

204 205
  tptp->tptp_pool = thrp;
  tptp->tptp_poolsize = N;
206 207 208 209 210 211

  for (i = 0; i < N; i++) {
#if HAVE_SIGCOMP
    if (tport_has_sigcomp(tp))
      thrp[i].thrp_compartment = tport_primary_compartment(tp->tp_master);
#endif
212
    thrp[i].thrp_tport = tptp;
213
    if (su_clone_start(pri->pri_master->mr_root,
214 215 216 217 218 219 220 221
		       thrp[i].thrp_clone,
		       thrp + i,
		       thrp_udp_init,
		       thrp_udp_deinit) < 0)
      goto error;
  }

  tp->tp_events = 0;
222

223 224 225 226 227 228 229 230 231 232 233
  return 0;

 error:
  assert(!"tport_launch_threadpool");
  return -1;
}

/** Kill threads in the tport pool.
 *
 * @note Executed by stack thread only.
 */
234
static
235 236
void tport_threadpool_deinit_primary(tport_primary_t *pri)
{
237 238 239
  tport_threadpool_t *tptp = (tport_threadpool_t *)pri;
  threadpool_t *thrp = tptp->tptp_pool;
  int i, N = pri->tptp_poolsize;
240 241 242 243 244 245 246 247 248

  if (!thrp)
    return;

  /* Prevent application from using these. */
  for (i = 0; i < N; i++)
    thrp[i].thrp_killing = 1;

  /* Stop every task in the threadpool. */
249
  for (i = 0; i < N; i++)
250 251
    su_clone_wait(pri->pri_master->mr_root, thrp[i].thrp_clone);

252 253
  su_free(pri->pri_home, tptp), tptp->tptp_pool = NULL;
  tptp->tptp_poolsize = 0;
254 255 256 257

  SU_DEBUG_3(("%s(%p): zapped threadpool\n", __func__, pri));
}

258
static int thrp_udp_init(su_root_t *root, threadpool_t *thrp)
259
{
260
  tport_t *tp = thrp->thrp_tport->tptp_primary->pri_primary;
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
  su_wait_t wait[1];

  assert(tp);

  thrp->thrp_root = root;

  if (su_wait_create(wait, tp->tp_socket, SU_WAIT_IN | SU_WAIT_ERR) < 0)
    return -1;

  thrp->thrp_reg = su_root_register(root, wait, thrp_udp_event, tp, 0);

  if (thrp->thrp_reg  == -1)
    return -1;

  return 0;
}

278
static void thrp_udp_deinit(su_root_t *root, threadpool_t *thrp)
279 280 281 282 283 284
{
  if (thrp->thrp_reg)
    su_root_deregister(root, thrp->thrp_reg), thrp->thrp_reg = 0;
  su_msg_destroy(thrp->thrp_rmsg);
}

285
su_inline void
286
thrp_yield(threadpool_t *thrp)
287
{
288 289
  tport_t *tp = thrp->thrp_tport->tptp_primary->pri_primary;
  su_root_eventmask(thrp->thrp_root, thrp->thrp_reg, tp->tp_socket, 0);
290 291 292
  thrp->thrp_yield = 1;
}

293
su_inline void
294
thrp_gain(threadpool_t *thrp)
295
{
296 297 298
  tport_t *tp = thrp->thrp_tport->tptp_primary->pri_primary;
  int events = SU_WAIT_IN | SU_WAIT_ERR;
  su_root_eventmask(thrp->thrp_root, thrp->thrp_reg, tp->tp_socket, events);
299 300 301
  thrp->thrp_yield = 0;
}

302 303
static int thrp_udp_event(threadpool_t *thrp,
			  su_wait_t *w,
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
			  tport_t *tp)
{
#if HAVE_POLL
  assert(w->fd == tp->tp_socket);
#endif

  for (;;) {
    thrp_udp_deliver_t *tpd;
    int events;

    if (!*thrp->thrp_rmsg) {
      if (su_msg_create(thrp->thrp_rmsg,
			su_root_parent(thrp->thrp_root),
			su_root_task(thrp->thrp_root),
			thrp_udp_deliver,
			sizeof (*tpd)) == -1) {
320
	SU_DEBUG_1(("thrp_udp_event(%p): su_msg_create(): %s\n", thrp,
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
		    strerror(errno)));
	return 0;
      }
    }

    tpd = su_msg_data(thrp->thrp_rmsg)->thrp_udp_deliver; assert(tpd);
    tpd->tpd_thrp = thrp;

    events = su_wait_events(w, tp->tp_socket);
    if (!events)
      return 0;

    thrp_udp_recv_deliver(thrp, tp, tpd, events);

    if (*thrp->thrp_rmsg) {
      SU_DEBUG_7(("thrp_udp_event(%p): no msg sent\n", thrp));
      tpd = su_msg_data(thrp->thrp_rmsg)->thrp_udp_deliver;
      memset(tpd, 0, sizeof *tpd);
      return 0;
340
    }
341 342 343 344 345 346 347 348

    if (thrp->thrp_yield || (thrp->thrp_s_sent - thrp->thrp_s_recv) > 0)
      return 0;

    su_wait(w, 1, 0);
  }
}

349 350
static int thrp_udp_recv_deliver(threadpool_t *thrp,
				 tport_t const *tp,
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
				 thrp_udp_deliver_t *tpd,
				 int events)
{
  unsigned qlen = thrp->thrp_r_sent - thrp->thrp_r_recv;

  SU_DEBUG_7(("thrp_udp_event(%p): events%s%s%s%s for %p\n", thrp,
	      events & SU_WAIT_IN ? " IN" : "",
	      events & SU_WAIT_HUP ? " HUP" : "",
	      events & SU_WAIT_OUT ? " OUT" : "",
	      events & SU_WAIT_ERR ? " ERR" : "",
	      tpd));

  if (events & SU_WAIT_ERR) {
    tpd->tpd_errorcode = tport_udp_error(tp, tpd->tpd_name);
    if (tpd->tpd_errorcode) {
      if (thrp->thrp_yield)
	su_msg_report(thrp->thrp_rmsg, thrp_udp_deliver_report);
      tpd->tpd_when = su_now();
      su_msg_send(thrp->thrp_rmsg);
      thrp->thrp_r_sent++;
      return 0;
    }
  }

  if (events & SU_WAIT_IN) {
    if (thrp_udp_recv(thrp, tpd) < 0) {
      tpd->tpd_errorcode = su_errno();
      assert(tpd->tpd_errorcode);
379
      if (su_is_blocking(tpd->tpd_errorcode))
380
	return 0;
381
    }
382
    else if (tpd->tpd_msg) {
383
      int n = msg_extract(tpd->tpd_msg); (void)n;
384

385 386 387 388 389 390 391 392 393 394 395 396 397
      thrp->thrp_rcvd_msgs++;
      thrp->thrp_rcvd_bytes += msg_size(tpd->tpd_msg);
    }

#if HAVE_SIGCOMP
    if (tpd->tpd_udvm && !tpd->tpd_msg)
      sigcomp_udvm_free(tpd->tpd_udvm), tpd->tpd_udvm = NULL;
#endif

    assert(!tpd->tpd_msg || !tpd->tpd_errorcode);

    if (tpd->tpd_msg || tpd->tpd_errorcode) {
      if (qlen >= tp->tp_params->tpp_thrprqsize) {
398
	SU_DEBUG_7(("tport recv queue %i: %u\n",
399
		    (int)(thrp - tp->tp_pri->tptp_pool), qlen));
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
	thrp_yield(thrp);
      }

      if (qlen >= tp->tp_params->tpp_thrprqsize / 2)
	su_msg_report(thrp->thrp_rmsg, thrp_udp_deliver_report);
      tpd->tpd_when = su_now();
      su_msg_send(thrp->thrp_rmsg);
      thrp->thrp_r_sent++;
      return 0;
    }
  }

  return 0;
}

#include <pthread.h>

/** Mutex for reading from socket */
static pthread_mutex_t mutex[1] = { PTHREAD_MUTEX_INITIALIZER };

/** Receive a UDP packet by threadpool. */
static
422
int thrp_udp_recv(threadpool_t *thrp, thrp_udp_deliver_t *tpd)
423 424 425 426 427 428 429 430 431
{
  tport_t const *tp = thrp->thrp_tport->pri_primary;
  unsigned char sample[2];
  int N;
  int s = tp->tp_socket;

  pthread_mutex_lock(mutex);

  /* Simulate packet loss */
432
  if (tp->tp_params->tpp_drop &&
433
      su_randint(0, 1000) < tp->tp_params->tpp_drop) {
434
    recv(s, sample, 1, 0);
435 436 437 438 439 440 441 442 443 444 445
    pthread_mutex_unlock(mutex);
    SU_DEBUG_3(("tport(%p): simulated packet loss!\n", tp));
    return 0;
  }

  /* Peek for first two bytes in message:
     determine if this is stun, sigcomp or sip
  */
  N = recv(s, sample, sizeof sample, MSG_PEEK | MSG_TRUNC);

  if (N < 0) {
446
    if (su_is_blocking(su_errno()))
447 448 449 450 451 452 453
      N = 0;
  }
  else if (N <= 1) {
    SU_DEBUG_1(("%s(%p): runt of %u bytes\n", "thrp_udp_recv", thrp, N));
    recv(s, sample, sizeof sample, 0);
    N = 0;
  }
454
#if !HAVE_MSG_TRUNC
455 456 457 458 459 460 461 462 463 464
  else if ((N = su_getmsgsize(tp->tp_socket)) < 0)
    ;
#endif
  else if ((sample[0] & 0xf8) == 0xf8) {
#if HAVE_SIGCOMP
    if (thrp->thrp_compartment) {
      struct sigcomp_buffer *input;
      void *data;
      int dlen;

465
      tpd->tpd_udvm =
466 467 468 469 470 471 472 473 474 475
	sigcomp_udvm_create_for_compartment(thrp->thrp_compartment);
      input = sigcomp_udvm_input_buffer(tpd->tpd_udvm, N); assert(input);

      data = input->b_data + input->b_avail;
      dlen = input->b_size - input->b_avail;

      if (dlen < N)
	dlen = 0;

      tpd->tpd_namelen = sizeof(tpd->tpd_name);
476 477

      dlen = recvfrom(tp->tp_socket, data, dlen, 0,
478 479 480
		      &tpd->tpd_name->su_sa, &tpd->tpd_namelen);

      SU_CANONIZE_SOCKADDR(tpd->tpd_name);
481

482 483 484
      if (dlen < N) {
	su_seterrno(EMSGSIZE);		/* Protocol error */
	N = -1;
485
      } else if (dlen == -1)
486 487
	N = -1;
      else {
488
	input->b_avail += dlen;
489
	input->b_complete = 1;
490

491
	pthread_mutex_unlock(mutex);
492

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
	N = thrp_udvm_decompress(thrp, tpd);

	if (N == -1)
	  /* Do not report decompression errors as ICMP errors */
	  memset(tpd->tpd_name, 0, tpd->tpd_namelen);

	return N;
      }
      pthread_mutex_unlock(mutex);
      return N;
    }
#endif
    recv(s, sample, 1, 0);
    pthread_mutex_unlock(mutex);
    /* XXX - send NACK ? */
    su_seterrno(EBADMSG);
    N = -1;
  }
  else {
    /* receive as usual */
    N = tport_recv_dgram_r(tp, &tpd->tpd_msg, N);
514 515
  }

516 517 518 519 520 521 522
  pthread_mutex_unlock(mutex);

  return N;
}

#if HAVE_SIGCOMP
static
523
int thrp_udvm_decompress(threadpool_t *thrp, thrp_udp_deliver_t *tpd)
524 525 526 527 528 529
{
  struct sigcomp_udvm *udvm = tpd->tpd_udvm;
  struct sigcomp_buffer *output;
  msg_iovec_t iovec[msg_n_fragments] = {{ 0 }};
  su_addrinfo_t *ai;
  tport_t *tp = thrp->thrp_tport->pri_primary;
530 531
  size_t n, m, i, dlen;
  int eos;
532
  void *data;
533
  ssize_t veclen;
534 535

  output = sigcomp_udvm_output_buffer(udvm, -1);
536

537 538 539 540 541 542
  if (sigcomp_udvm_decompress(udvm, output, NULL) < 0) {
    int error = sigcomp_udvm_errno(udvm);
    SU_DEBUG_3(("%s: UDVM error %d: %s\n", __func__,
		error, sigcomp_udvm_strerror(udvm)));
    su_seterrno(EREMOTEIO);
    return -1;
543
  }
544 545 546 547 548

  data = output->b_data + output->b_used;
  dlen = output->b_avail - output->b_used;
  /* XXX - if a message is larger than default output size... */
  eos = output->b_complete; assert(output->b_complete);
549

550
  veclen = tport_recv_iovec(tp, &tpd->tpd_msg, iovec, dlen, eos);
551

552 553 554 555 556 557 558 559 560 561 562
  if (veclen <= 0) {
    n = -1;
  } else {
    for (i = 0, n = 0; i < veclen; i++) {
      m = iovec[i].mv_len; assert(dlen >= n + m);
      memcpy(iovec[i].mv_base, data + n, m);
      n += m;
    }
    assert(dlen == n);

    msg_recv_commit(tpd->tpd_msg, dlen, eos);    /* Mark buffer as used */
563

564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
    /* Message address */
    ai = msg_addrinfo(tpd->tpd_msg);
    ai->ai_flags |= TP_AI_COMPRESSED;
    ai->ai_family = tpd->tpd_name->su_sa.sa_family;
    ai->ai_socktype = SOCK_DGRAM;
    ai->ai_protocol = IPPROTO_UDP;
    memcpy(ai->ai_addr, tpd->tpd_name, ai->ai_addrlen = tpd->tpd_namelen);

    SU_DEBUG_9(("%s(%p): sigcomp msg sz = %d\n", __func__, tp, n));
  }

  return n;
}
#endif

/** Deliver message from threadpool to the stack
 *
 * @note Executed by stack thread only.
 */
583
static
584 585 586 587 588
void thrp_udp_deliver(su_root_magic_t *magic,
		      su_msg_r m,
		      union tport_su_msg_arg *arg)
{
  thrp_udp_deliver_t *tpd = arg->thrp_udp_deliver;
589
  threadpool_t *thrp = tpd->tpd_thrp;
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
  tport_t *tp = thrp->thrp_tport->pri_primary;
  su_time_t now = su_now();

  assert(magic != thrp);

  thrp->thrp_r_recv++;

  if (thrp->thrp_killing) {
#if HAVE_SIGCOMP
    sigcomp_udvm_free(tpd->tpd_udvm), tpd->tpd_udvm = NULL;
#endif
    msg_destroy(tpd->tpd_msg);
    return;
  }

605
  SU_DEBUG_7(("thrp_udp_deliver(%p): got %p delay %f\n",
606 607 608 609 610 611 612 613 614
	      thrp, tpd, 1000 * su_time_diff(now, tpd->tpd_when)));

  if (tpd->tpd_errorcode)
    tport_error_report(tp, tpd->tpd_errorcode, tpd->tpd_name);
  else if (tpd->tpd_msg) {
    tport_deliver(tp, tpd->tpd_msg, NULL, &tpd->tpd_udvm, tpd->tpd_when);
    tp->tp_rlogged = NULL;
  }

615
#if HAVE_SIGCOMP
616 617 618 619 620 621
  if (tpd->tpd_udvm) {
    sigcomp_udvm_free(tpd->tpd_udvm), tpd->tpd_udvm = NULL;
  }
#endif
}

622
static
623
void thrp_udp_deliver_report(threadpool_t *thrp,
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
			     su_msg_r m,
			     union tport_su_msg_arg *arg)
{
  if (thrp->thrp_yield) {
    int qlen = thrp->thrp_r_sent - thrp->thrp_r_recv;
    int qsize = thrp->thrp_tport->pri_params->tpp_thrprqsize;
    if (qlen == 0 || qlen < qsize / 2)
      thrp_gain(thrp);
  }
}

/** Send a message to network using threadpool.
 *
 * @note Executed by stack thread only.
 */
static
int tport_thread_send(tport_t *tp,
		      msg_t *msg,
642
		      tp_name_t const *tpn,
643 644 645
		      struct sigcomp_compartment *cc,
		      unsigned mtu)
{
646

647
  threadpool_t *thrp = tp->tp_pri->tptp_pool;
648
  thrp_udp_deliver_t *tpd;
649
  int i, N = tp->tp_pri->tptp_poolsize;
650 651 652 653
  su_msg_r m;
  unsigned totalqlen = 0;
  unsigned qlen;

654
  if (!tp->tp_pri->tptp_pool)
655 656 657 658 659 660 661 662 663
    return tport_prepare_and_send(tp, msg, tpn, cc, mtu);

  SU_DEBUG_9(("tport_thread_send()\n"));

  if (thrp->thrp_killing)
    return (su_seterrno(ECHILD)), -1;

  qlen = totalqlen = thrp->thrp_s_sent - thrp->thrp_s_recv;

664
  /* Select thread with shortest queue */
665
  for (i = 1; i < N; i++) {
666
    threadpool_t *other = tp->tp_pri->tptp_pool + i;
667 668
    unsigned len = other->thrp_s_sent - other->thrp_s_recv;

669
    if (len < qlen ||
670 671 672 673 674 675 676 677 678 679 680 681 682 683
	(len == qlen && (other->thrp_s_sent - thrp->thrp_s_sent) < 0))
      thrp = other, qlen = len;

    totalqlen += len;
  }

  if (totalqlen >= N * tp->tp_params->tpp_qsize)
    SU_DEBUG_3(("tport send queue: %u (shortest %u)\n", totalqlen, qlen));

  if (su_msg_create(m,
		    su_clone_task(thrp->thrp_clone),
		    su_root_task(tp->tp_master->mr_root),
		    thrp_udp_send,
		    sizeof (*tpd)) != su_success) {
684
    SU_DEBUG_1(("thrp_udp_event(%p): su_msg_create(): %s\n", thrp,
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
		strerror(errno)));
    return -1;
  }

  tpd = su_msg_data(m)->thrp_udp_deliver;
  tpd->tpd_thrp = thrp;
  tpd->tpd_when = su_now();
  tpd->tpd_mtu = mtu;
  tpd->tpd_msg = msg_ref_create(msg);

#if HAVE_SIGCOMP
  tpd->tpd_cc = cc;
#endif

  su_msg_report(m, thrp_udp_send_report);

  if (su_msg_send(m) == su_success) {
    thrp->thrp_s_sent++;
    return 0;
  }

  msg_ref_destroy(msg);
  return -1;
}

/** thrp_udp_send() is run by threadpool to send the message. */
711
static
712
void thrp_udp_send(threadpool_t *thrp,
713 714 715 716 717 718 719 720 721 722 723 724 725
		   su_msg_r m,
		   union tport_su_msg_arg *arg)
{
  thrp_udp_deliver_t *tpd = arg->thrp_udp_deliver;
  tport_t *tp = thrp->thrp_tport->pri_primary;
  msg_t *msg = tpd->tpd_msg;
  msg_iovec_t *iov, auto_iov[40], *iov0 = NULL;
  int iovlen, iovused, n;

  assert(thrp == tpd->tpd_thrp);

  thrp->thrp_s_recv++;

726
  {
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
    double delay = 1000 * su_time_diff(su_now(), tpd->tpd_when);
    if (delay > 100)
      SU_DEBUG_3(("thrp_udp_deliver(%p): got %p delay %f\n", thrp, tpd, delay));
    else
      SU_DEBUG_7(("thrp_udp_deliver(%p): got %p delay %f\n", thrp, tpd, delay));
  }

  if (!msg) {
    tpd->tpd_errorcode = EINVAL;
    return;
  }

  /* Prepare message for sending - i.e., encode it */
  if (msg_prepare(msg) < 0) {
    tpd->tpd_errorcode = errno;
    return;
  }

  if (tpd->tpd_mtu != 0 && msg_size(msg) > tpd->tpd_mtu) {
    tpd->tpd_errorcode = EMSGSIZE;
    return;
  }

  /* Use initially the I/O vector from stack */
  iov = auto_iov, iovlen = sizeof(auto_iov)/sizeof(auto_iov[0]);

  /* Get a iovec for message contents */
  for (;;) {
    iovused = msg_iovec(msg, iov, iovlen);
756
    if (iovused <= iovlen)
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
      break;

    iov = iov0 = realloc(iov0, sizeof(*iov) * iovused);
    iovlen = iovused;

    if (iov0 == NULL) {
      tpd->tpd_errorcode = errno;
      return;
    }
  }

  assert(iovused > 0);

  tpd->tpd_when = su_now();

  if (0)
    ;
#if HAVE_SIGCOMP
  else if (tpd->tpd_cc) {
    tport_sigcomp_t sc[1] = {{ NULL }};

    n = tport_sigcomp_vsend(tp, msg, iov, iovused, tpd->tpd_cc, sc);
779
  }
780
#endif
781
  else
782 783 784 785 786 787 788 789 790
    n = tport_send_dgram(tp, msg, iov, iovused);

  if (n == -1)
    tpd->tpd_errorcode = su_errno();

  if (iov0)
    free(iov0);
}

791
static
792 793 794 795 796
void thrp_udp_send_report(su_root_magic_t *magic,
			  su_msg_r msg,
			  union tport_su_msg_arg *arg)
{
  thrp_udp_deliver_t *tpd = arg->thrp_udp_deliver;
797
  threadpool_t *thrp = tpd->tpd_thrp;
798 799 800 801
  tport_t *tp = thrp->thrp_tport->pri_primary;

  assert(magic != thrp);

802
  SU_DEBUG_7(("thrp_udp_send_report(%p): got %p delay %f\n",
803 804 805
	      thrp, tpd, 1000 * su_time_diff(su_now(), tpd->tpd_when)));

  if (tp->tp_master->mr_log)
806
    tport_log_msg(tp, tpd->tpd_msg, "sent", "to", tpd->tpd_when);
807 808 809 810 811 812

  if (tpd->tpd_errorcode)
    tport_error_report(tp, tpd->tpd_errorcode, msg_addr(tpd->tpd_msg));

  msg_ref_destroy(tpd->tpd_msg);
}