tport_threadpool.c 20.1 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 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
  /* vtp_name 		     */ "udp",
  /* vtp_public              */ tport_type_local,
  /* vtp_pri_size            */ sizeof (tport_threadpool_t),
  /* vtp_init_primary        */ tport_threadpool_init_primary,
  /* vtp_deinit_primary      */ tport_threadpool_deinit_primary,
  /* vtp_wakeup_pri          */ NULL,
  /* vtp_connect             */ NULL,
  /* vtp_secondary_size      */ 0, /* No secondary transports! */
  /* vtp_init_secondary      */ NULL,
  /* vtp_deinit_secondary    */ NULL,
  /* vtp_shutdown            */ NULL,
  /* vtp_set_events          */ NULL,
  /* vtp_wakeup              */ NULL,
  /* vtp_recv                */ tport_recv_dgram,
  /* vtp_send                */ tport_send_dgram,
  /* vtp_deliver             */ NULL,
  /* vtp_prepare             */ tport_thread_send,
  /* vtp_keepalive           */ NULL,
  /* vtp_stun_response       */ NULL,
  /* vtp_next_secondary_timer*/ NULL,
  /* vtp_secondary_timer     */ NULL,
153 154
};

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


/** Launch threads in the tport pool. */
184 185
int tport_threadpool_init_primary(tport_primary_t *pri,
				  tp_name_t tpn[1],
186 187 188 189
				  su_addrinfo_t *ai,
				  tagi_t const *tags,
				  char const **return_culprit)
{
190
  tport_threadpool_t *tptp = (tport_threadpool_t *)pri;
191
  tport_t *tp = pri->pri_primary;
192
  threadpool_t *thrp;
193 194 195 196 197 198 199
  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;

200
  if (N == 0)
201 202 203 204 205 206 207 208
    return 0;

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

  su_setblocking(tp->tp_socket, 0);

209 210
  tptp->tptp_pool = thrp;
  tptp->tptp_poolsize = N;
211 212 213 214 215 216

  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
217
    thrp[i].thrp_tport = tptp;
218
    if (su_clone_start(pri->pri_master->mr_root,
219 220 221 222 223 224 225 226
		       thrp[i].thrp_clone,
		       thrp + i,
		       thrp_udp_init,
		       thrp_udp_deinit) < 0)
      goto error;
  }

  tp->tp_events = 0;
227

228 229 230 231 232 233 234 235 236 237 238
  return 0;

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

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

  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. */
254
  for (i = 0; i < N; i++)
255 256
    su_clone_wait(pri->pri_master->mr_root, thrp[i].thrp_clone);

257 258
  su_free(pri->pri_home, tptp), tptp->tptp_pool = NULL;
  tptp->tptp_poolsize = 0;
259 260 261 262

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

263
static int thrp_udp_init(su_root_t *root, threadpool_t *thrp)
264
{
265
  tport_t *tp = thrp->thrp_tport->tptp_primary->pri_primary;
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
  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;
}

283
static void thrp_udp_deinit(su_root_t *root, threadpool_t *thrp)
284 285 286 287 288 289
{
  if (thrp->thrp_reg)
    su_root_deregister(root, thrp->thrp_reg), thrp->thrp_reg = 0;
  su_msg_destroy(thrp->thrp_rmsg);
}

290
su_inline void
291
thrp_yield(threadpool_t *thrp)
292
{
293 294
  tport_t *tp = thrp->thrp_tport->tptp_primary->pri_primary;
  su_root_eventmask(thrp->thrp_root, thrp->thrp_reg, tp->tp_socket, 0);
295 296 297
  thrp->thrp_yield = 1;
}

298
su_inline void
299
thrp_gain(threadpool_t *thrp)
300
{
301 302 303
  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);
304 305 306
  thrp->thrp_yield = 0;
}

307 308
static int thrp_udp_event(threadpool_t *thrp,
			  su_wait_t *w,
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
			  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) {
325
	SU_DEBUG_1(("thrp_udp_event(%p): su_msg_create(): %s\n", thrp,
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
		    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;
345
    }
346 347 348 349 350 351 352 353

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

    su_wait(w, 1, 0);
  }
}

354 355
static int thrp_udp_recv_deliver(threadpool_t *thrp,
				 tport_t const *tp,
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
				 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);
384
      if (su_is_blocking(tpd->tpd_errorcode))
385
	return 0;
386
    }
387
    else if (tpd->tpd_msg) {
388
      int n = msg_extract(tpd->tpd_msg); (void)n;
389

390 391 392 393 394 395 396 397 398 399 400 401 402
      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) {
403
	SU_DEBUG_7(("tport recv queue %i: %u\n",
404
		    (int)(thrp - tp->tp_pri->tptp_pool), qlen));
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
	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
427
int thrp_udp_recv(threadpool_t *thrp, thrp_udp_deliver_t *tpd)
428 429 430 431 432 433 434 435 436
{
  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 */
437
  if (tp->tp_params->tpp_drop &&
438
      su_randint(0, 1000) < tp->tp_params->tpp_drop) {
439
    recv(s, sample, 1, 0);
440 441 442 443 444 445 446 447 448 449 450
    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) {
451
    if (su_is_blocking(su_errno()))
452 453 454 455 456 457 458
      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;
  }
459
#if !HAVE_MSG_TRUNC
460 461 462 463 464 465 466 467 468 469
  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;

470
      tpd->tpd_udvm =
471 472 473 474 475 476 477 478 479 480
	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);
481 482

      dlen = recvfrom(tp->tp_socket, data, dlen, 0,
483 484 485
		      &tpd->tpd_name->su_sa, &tpd->tpd_namelen);

      SU_CANONIZE_SOCKADDR(tpd->tpd_name);
486

487 488 489
      if (dlen < N) {
	su_seterrno(EMSGSIZE);		/* Protocol error */
	N = -1;
490
      } else if (dlen == -1)
491 492
	N = -1;
      else {
493
	input->b_avail += dlen;
494
	input->b_complete = 1;
495

496
	pthread_mutex_unlock(mutex);
497

498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
	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);
519 520
  }

521 522 523 524 525 526 527
  pthread_mutex_unlock(mutex);

  return N;
}

#if HAVE_SIGCOMP
static
528
int thrp_udvm_decompress(threadpool_t *thrp, thrp_udp_deliver_t *tpd)
529 530 531 532 533 534
{
  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;
535 536
  size_t n, m, i, dlen;
  int eos;
537
  void *data;
538
  ssize_t veclen;
539 540

  output = sigcomp_udvm_output_buffer(udvm, -1);
541

542 543 544 545 546 547
  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;
548
  }
549 550 551 552 553

  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);
554

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

557 558 559 560 561 562 563 564 565 566 567
  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 */
568

569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
    /* 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.
 */
588
static
589 590 591 592 593
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;
594
  threadpool_t *thrp = tpd->tpd_thrp;
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
  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;
  }

610
  SU_DEBUG_7(("thrp_udp_deliver(%p): got %p delay %f\n",
611 612 613 614 615 616 617 618 619
	      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;
  }

620
#if HAVE_SIGCOMP
621 622 623 624 625 626
  if (tpd->tpd_udvm) {
    sigcomp_udvm_free(tpd->tpd_udvm), tpd->tpd_udvm = NULL;
  }
#endif
}

627
static
628
void thrp_udp_deliver_report(threadpool_t *thrp,
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
			     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,
647
		      tp_name_t const *tpn,
648 649 650
		      struct sigcomp_compartment *cc,
		      unsigned mtu)
{
651

652
  threadpool_t *thrp = tp->tp_pri->tptp_pool;
653
  thrp_udp_deliver_t *tpd;
654
  int i, N = tp->tp_pri->tptp_poolsize;
655 656 657 658
  su_msg_r m;
  unsigned totalqlen = 0;
  unsigned qlen;

659
  if (!tp->tp_pri->tptp_pool)
660 661 662 663 664
    return tport_prepare_and_send(tp, msg, tpn, cc, mtu);

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

  if (thrp->thrp_killing)
665
    return (su_seterrno(ECHILD));
666 667 668

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

669
  /* Select thread with shortest queue */
670
  for (i = 1; i < N; i++) {
671
    threadpool_t *other = tp->tp_pri->tptp_pool + i;
672 673
    unsigned len = other->thrp_s_sent - other->thrp_s_recv;

674
    if (len < qlen ||
675 676 677 678 679 680 681 682 683 684 685 686 687 688
	(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) {
689
    SU_DEBUG_1(("thrp_udp_event(%p): su_msg_create(): %s\n", thrp,
690 691 692 693 694 695 696 697
		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;
698
  tpd->tpd_msg = msg_ref(msg);
699 700 701 702 703 704 705 706 707 708 709 710

#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;
  }

711
  msg_unref(msg);
712 713 714 715
  return -1;
}

/** thrp_udp_send() is run by threadpool to send the message. */
716
static
717
void thrp_udp_send(threadpool_t *thrp,
718 719 720 721 722 723 724 725 726 727 728 729 730
		   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++;

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 756 757 758 759 760
    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);
761
    if (iovused <= iovlen)
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
      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);
784
  }
785
#endif
786
  else
787 788 789 790 791 792 793 794 795
    n = tport_send_dgram(tp, msg, iov, iovused);

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

  if (iov0)
    free(iov0);
}

796
static
797 798 799 800 801
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;
802
  threadpool_t *thrp = tpd->tpd_thrp;
803 804 805 806
  tport_t *tp = thrp->thrp_tport->pri_primary;

  assert(magic != thrp);

807
  SU_DEBUG_7(("thrp_udp_send_report(%p): got %p delay %f\n",
808 809 810
	      thrp, tpd, 1000 * su_time_diff(su_now(), tpd->tpd_when)));

  if (tp->tp_master->mr_log)
811
    tport_log_msg(tp, tpd->tpd_msg, "sent", "to", tpd->tpd_when);
812 813 814 815

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

816
  msg_unref(tpd->tpd_msg);
817

818
}