su_pthread_port.c 16.9 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 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
/*
 * This file is part of the Sofia-SIP package
 *
 * Copyright (C) 2005 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
 *
 */

/**@ingroup su_wait
 * @CFILE su_pthread_port.c
 *
 * OS-Independent Socket Syncronization Interface with pthreads
 *
 * This implements #su_msg_t message passing functionality using pthreads.
 *
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>
 * @author Kai Vehmanen <kai.vehmanen@nokia.com>
 *
 * @date Created: Tue Sep 14 15:51:04 1999 ppessi
 */

#include "config.h"

#include <stdlib.h>
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <errno.h>

#define su_pthread_port_s su_port_s
49
#define SU_CLONE_T su_msg_t
50 51 52 53 54 55 56 57 58 59 60

#include "sofia-sip/su.h"
#include "su_port.h"
#include "sofia-sip/su_alloc.h"

#if 1
#define PORT_LOCK_DEBUG(x)  ((void)0)
#else
#define PORT_LOCK_DEBUG(x)  printf x
#endif

61 62 63
#define SU_TASK_COPY(d, s, by) (void)((d)[0]=(s)[0], \
  (s)->sut_port?(void)su_port_incref(s->sut_port, #by):(void)0)

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
#if HAVE_SOCKETPAIR
#define SU_MBOX_SEND 1
#else
#define SU_MBOX_SEND 0
#endif

/** @internal Message box wakeup function. */
static int su_mbox_port_wakeup(su_root_magic_t *magic, /* NULL */
			       su_wait_t *w,
			       su_wakeup_arg_t *arg)
{
  char buf[32];
  su_socket_t socket = *(su_socket_t*)arg;
  su_wait_events(w, socket);
  recv(socket, buf, sizeof(buf), 0);
  return 0;
}

/**@internal
 *
 * Initializes a message port. It creates a mailbox used to wake up the
 * thread waiting on the port if needed. Currently, the mailbox is a
 * socketpair or an UDP socket connected to itself.
 */
int su_pthread_port_init(su_port_t *self, su_port_vtable_t const *vtable)
{
  SU_DEBUG_9(("su_pthread_port_init(%p, %p) called\n", self, vtable));

92 93
  if (su_base_port_init(self, vtable) == 0 &&
      su_base_port_threadsafe(self) == 0) {
94 95 96 97 98 99 100
    int af;
    su_socket_t mb = INVALID_SOCKET;
    su_wait_t wait[1] = { SU_WAIT_INIT };
    char const *why;

    self->sup_tid = pthread_self();

101 102 103 104 105 106
#if 0
    pthread_mutex_init(self->sup_runlock, NULL);
    pthread_mutex_lock(self->sup_runlock);
    pthread_cond_init(self->sup_resume, NULL);
#endif

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
#if HAVE_SOCKETPAIR
#if defined(AF_LOCAL)
    af = AF_LOCAL;
#else
    af = AF_UNIX;
#endif
    if (socketpair(af, SOCK_STREAM, 0, self->sup_mbox) == -1) {
      why = "socketpair"; goto error;
    }

    mb = self->sup_mbox[0];
    su_setblocking(self->sup_mbox[1], 0);

#else
    {
      struct sockaddr_in sin = { sizeof(struct sockaddr_in), 0 };
      socklen_t sinsize = sizeof sin;
      struct sockaddr *sa = (struct sockaddr *)&sin;

      af = PF_INET;

      self->sup_mbox[0] = mb = su_socket(af, SOCK_DGRAM, IPPROTO_UDP);
      if (mb == INVALID_SOCKET) {
	why = "socket"; goto error;
      }
  
      sin.sin_family = AF_INET;
      sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK); /* 127.1 */
      
      /* Get a port for us */
      if (bind(mb, sa, sizeof sin) == -1) {
	why = "bind"; goto error;
      }

      if (getsockname(mb, sa, &sinsize) == -1) {
	why = "getsockname"; goto error;
      }
    
      if (connect(mb, sa, sinsize) == -1) {
	why = "connect"; goto error;
      }
    }
#endif    

    su_setblocking(mb, 0);

    if (su_wait_create(wait, mb, SU_WAIT_IN) == -1) {
      why = "su_wait_create";
      goto error;
    }

    self->sup_mbox_index = su_port_register(self, NULL, wait, 
					    su_mbox_port_wakeup, 
					    (void *)self->sup_mbox, 0);

    if (self->sup_mbox_index <= 0) {
      why = "su_port_register";
      su_wait_destroy(wait);
      goto error;
    }

    SU_DEBUG_9(("%s() returns %d\n", "su_pthread_port_init", 0));

    return 0;

  error:
    su_log("%s: %s: %s\n", 
	   "su_pthread_port_init", why, su_strerror(su_errno()));
    su_pthread_port_deinit(self);
  }

  SU_DEBUG_9(("%s() returns %d\n", "su_pthread_port_init", -1));

  return -1;
}

183

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
/** @internal Deinit a base implementation of port. */
void su_pthread_port_deinit(su_port_t *self)
{
  assert(self);

  if (self->sup_mbox_index > 0)
    su_port_deregister(self, self->sup_mbox_index);
  self->sup_mbox_index = 0;

  if (self->sup_mbox[0] && self->sup_mbox[0] != INVALID_SOCKET)
    su_close(self->sup_mbox[0]); self->sup_mbox[0] = INVALID_SOCKET;
#if HAVE_SOCKETPAIR
  if (self->sup_mbox[1] && self->sup_mbox[1] != INVALID_SOCKET)
    su_close(self->sup_mbox[1]); self->sup_mbox[1] = INVALID_SOCKET;
#endif

200 201 202 203 204
#if 0
  pthread_mutex_destroy(self->sup_runlock);
  pthread_cond_destroy(self->sup_resume);
#endif

205 206 207
  su_base_port_deinit(self);
}

208

209 210 211 212 213
void su_pthread_port_lock(su_port_t *self, char const *who)
{
  PORT_LOCK_DEBUG(("%p at %s locking(%p)...",
		   (void *)pthread_self(), who, self));

214
  su_home_mutex_lock(self->sup_base->sup_home);
215 216 217 218 219 220 221

  PORT_LOCK_DEBUG((" ...%p at %s locked(%p)...", 
		   (void *)pthread_self(), who, self));
}

void su_pthread_port_unlock(su_port_t *self, char const *who)
{
222
  su_home_mutex_unlock(self->sup_base->sup_home);
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

  PORT_LOCK_DEBUG((" ...%p at %s unlocked(%p)\n", 
		   (void *)pthread_self(), who, self));
}

/** @internal Send a message to the port. */
int su_pthread_port_send(su_port_t *self, su_msg_r rmsg)
{
  int wakeup = su_base_port_send(self, rmsg);

  if (wakeup < 0)
    return -1;
  if (wakeup == 0)
    return 0;

  assert(self->sup_mbox[SU_MBOX_SEND] != INVALID_SOCKET);

  if (send(self->sup_mbox[SU_MBOX_SEND], "X", 1, 0) == -1) {
#if HAVE_SOCKETPAIR
    if (su_errno() != EWOULDBLOCK)
#endif
      su_perror("su_msg_send: send()");
  }
  return 0;
}

/** @internal
 * Checks if the calling thread owns the port object.
 *
 * @param self pointer to a port object
 *
 * @retval true (nonzero) if the calling thread owns the port,
 * @retval false (zero) otherwise.
 */
int su_pthread_port_own_thread(su_port_t const *self)
{
  return self == NULL || 
    pthread_equal(self->sup_tid, pthread_self());
}
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 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 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691

/* -- Clones ------------------------------------------------------------ */

struct clone_args
{
  su_root_t       *parent;
  su_root_magic_t *magic;
  su_root_init_f   init;
  su_root_deinit_f deinit;
  pthread_mutex_t  mutex[1];
  pthread_cond_t   cv[1];
  int              retval;
  su_msg_r         clone;
};

static void *su_pthread_port_clone_main(void *varg);
static void su_pthread_port_return_to_parent(struct clone_args *arg,
					     int retval);
static su_msg_function su_pthread_port_clone_break;

/* Structure used to synchronize parent and clone in su_clone_wait() */
struct su_pthread_port_waiting_parent {
  pthread_mutex_t deinit[1];
  pthread_mutex_t mutex[1];
  pthread_cond_t cv[1];
  int waiting;
};

/** Start a clone task by a pthread.
 *
 * @internal
 *
 * Allocates and initializes a sub-task with its own thread. The sub-task is
 * represented by clone handle to the rest of the application. The function
 * su_clone_start() returns the clone handle in @a return_clone. The clone
 * handle is used to communicate with the newly created clone task using
 * messages.
 *
 * A new #su_root_t object is created for the sub-task with the @a magic as
 * the root context pointer. Because the sub-task may or may not have its
 * own thread, all its activity must be scheduled via this root object. In
 * other words, the sub-task can be schedule
 * -# I/O events with su_root_register()
 * -# timers with su_timer_set(), su_timer_set_at() or su_timer_run()
 * -# messages with su_msg_send().
 *
 * Messages can also be used to pass information between tasks or threads.
 *
 * After the new thread has been launched, the initialization routine is
 * executed by the newly created thread. The calling thread blocks until
 * the initialization routine completes. If the initialization routine
 * returns #su_success (0), the sub-task is considered to be created
 * successfully. After the successful initialization, the sub-task continues
 * to execeute the function su_root_run().
 *
 * If the initalization function @a init fails, the sub-task (either the
 * newly created thread or the current thread executing the su_clone_start()
 * function) calls the deinitialization function, and su_clone_start()
 * returns NULL.
 *
 * @param parent   root to be cloned (may be NULL if multi-threaded)
 * @param return_clone reference to a clone [OUT]
 * @param magic    pointer to user data
 * @param init     initialization function
 * @param deinit   deinitialization function
 *
 * @return 0 if successfull, -1 upon an error.
 *
 * @sa su_root_threading(), su_clone_task(), su_clone_stop(), su_clone_wait(),
 * su_clone_forget().
 * 
 */
int su_pthread_port_start(su_root_t *parent,
			  su_clone_r return_clone,
			  su_root_magic_t *magic,
			  su_root_init_f init,
			  su_root_deinit_f deinit)
{
  struct clone_args arg = {
    /* parent: */ NULL,
    /* magic: */  NULL,
    /* init: */   NULL,
    /* deinit: */ NULL,
    /* mutex: */  { PTHREAD_MUTEX_INITIALIZER },
    /* cv: */     { PTHREAD_COND_INITIALIZER },
    /* retval: */ -1,
    /* clone: */  SU_MSG_R_INIT,
  };

  int thread_created = 0;
  pthread_t tid;

  if (parent && !parent->sur_threading)
    return su_base_port_start(parent, return_clone, magic, init, deinit);

  arg.parent = parent;
  arg.magic = magic;
  arg.init = init;
  arg.deinit = deinit;

  pthread_mutex_lock(arg.mutex);
  if (pthread_create(&tid, NULL, su_pthread_port_clone_main, &arg) == 0) {
    pthread_cond_wait(arg.cv, arg.mutex);
    thread_created = 1;
  }
  pthread_mutex_unlock(arg.mutex);

  pthread_mutex_destroy(arg.mutex);
  pthread_cond_destroy(arg.cv);

  if (arg.retval != 0) {
    if (thread_created)
      pthread_join(tid, NULL);
    return -1;
  }

  *return_clone = *arg.clone;

  return 0;
}

/** Main function for clone thread.
 *
 * @internal
 */
static void *su_pthread_port_clone_main(void *varg)
{
  struct clone_args *arg = (struct clone_args *)varg;
  su_task_r task;
  int zap;

#if SU_HAVE_WINSOCK
  su_init();
#endif

  task->sut_port = 
    arg->parent->sur_task->sut_port->sup_base->sup_vtable->
    su_port_create();

  if (task->sut_port) {
    task->sut_port->sup_thread = 1;

    task->sut_root = su_salloc(su_port_home(task->sut_port),
			       sizeof *task->sut_root);
    if (task->sut_root) {

      task->sut_root->sur_threading = 1;	/* By default */

      SU_TASK_COPY(task->sut_root->sur_parent, su_root_task(arg->parent), 
		   su_pthread_port_clone_main);
      SU_TASK_COPY(task->sut_root->sur_task, task,
		   su_pthread_port_clone_main);

      if (su_msg_create(arg->clone,
			task,
			su_root_task(arg->parent),
			su_pthread_port_clone_break,
			0) == 0) {
	task->sut_root->sur_magic = arg->magic;
	task->sut_root->sur_deinit = arg->deinit;

	if (arg->init(task->sut_root, arg->magic) == 0) {
	  su_pthread_port_return_to_parent(arg, 0), arg = NULL;

	  su_root_run(task->sut_root); /* Do the work */

	  /* Cleanup */
	  if (task->sut_port->sup_waiting_parent) {
	    struct su_pthread_port_waiting_parent *mom;

	    mom = task->sut_port->sup_waiting_parent;
	    pthread_mutex_lock(mom->mutex);
	    mom->waiting = 0;
	    pthread_cond_signal(mom->cv);
	    pthread_mutex_unlock(mom->mutex);
    
	    pthread_mutex_lock(mom->deinit);
	    su_port_getmsgs(task->sut_port);
	    pthread_mutex_unlock(mom->deinit);
	  }
	  else
	    zap = 0;
	}
	else
	  su_msg_destroy(arg->clone);

	su_root_destroy(task->sut_root);
      }
    }

    task->sut_port->sup_thread = 0;

    task->sut_port->sup_base->sup_vtable->
      su_port_decref(task->sut_port, zap, 
		     "su_pthread_port_clone_main");
  }

#if SU_HAVE_WINSOCK
  su_deinit();
#endif

  if (arg)
    su_pthread_port_return_to_parent(arg, -1);

  return NULL;			/* Exit from thread */
}

/* Signal that parent can resume execution */
static void su_pthread_port_return_to_parent(struct clone_args *arg,
					     int retval)
{
  arg->retval = retval;

  pthread_mutex_lock(arg->mutex);
  pthread_cond_signal(arg->cv);
  pthread_mutex_unlock(arg->mutex);
}

/** "Stop" message function for pthread clone.
 *
 * @sa su_clone_wait()
 * @internal 
 */
static void su_pthread_port_clone_break(su_root_magic_t *m,
					su_msg_r msg,
					su_msg_arg_t *a)
{
  su_root_t *root = su_msg_to(msg)->sut_root;

  root->sur_deiniting = 1;

  su_root_break(root);
}

/** Wait for the pthread clone to exit.
 * @internal
 */
void su_pthread_port_wait(su_clone_r rclone)
{
  su_port_t *parent, *clone;
  struct su_pthread_port_waiting_parent mom[1];
  pthread_t tid;

  parent = su_msg_from(rclone)->sut_port;
  clone = su_msg_to(rclone)->sut_port;

  if (parent == clone) {
    su_base_port_wait(rclone);
    return;
  }
  
  assert(parent); assert(clone); 
  assert(rclone[0]->sum_func == su_pthread_port_clone_break);
#if 0
  assert(!clone->sup_paused);
#endif

  tid = clone->sup_tid;

  if (!clone->sup_thread) {	/* Already died */
    su_msg_destroy(rclone);
    pthread_join(tid, NULL);
    return;  
  }

  pthread_mutex_init(mom->deinit, NULL);
  pthread_mutex_lock(mom->deinit);

  pthread_cond_init(mom->cv, NULL);
  pthread_mutex_init(mom->mutex, NULL);
  pthread_mutex_lock(mom->mutex);

  mom->waiting = 1;

  clone->sup_waiting_parent = mom;

  su_msg_send(rclone);

  while (mom->waiting)
    pthread_cond_wait(mom->cv, mom->mutex);

  /* Run all messages from clone */
  su_base_port_getmsgs_from_port(parent, clone);

  /* Wait for clone thread to exit */
  pthread_mutex_unlock(mom->deinit);
  pthread_join(tid, NULL);

  pthread_mutex_destroy(mom->deinit);

  pthread_mutex_unlock(mom->mutex);
  pthread_mutex_destroy(mom->mutex);
}

struct su_pthread_port_execute
{
  pthread_mutex_t mutex[1];
  pthread_cond_t cond[1];
  int (*function)(void *);
  void *arg;
  int value;
};

static su_msg_function _su_pthread_port_execute;

/** Execute the @a function by a pthread @a task.
 *
 * @retval 0 if successful
 * @retval -1 upon an error
 *
 * @sa su_task_execute()
 *
 * @internal
 */
int su_pthread_port_execute(su_task_r const task,
			    int (*function)(void *), void *arg,
			    int *return_value)
{
  int success;
  su_msg_r m = SU_MSG_R_INIT;
  struct su_pthread_port_execute frame = {
    { PTHREAD_MUTEX_INITIALIZER },
    { PTHREAD_COND_INITIALIZER },
    function, arg, 0
  };

  if (su_msg_create(m, task, su_task_null,
		    _su_pthread_port_execute, (sizeof &frame)) < 0)
    return -1;

  *(struct su_pthread_port_execute **)su_msg_data(m) = &frame;

  pthread_mutex_lock(frame.mutex);

  success = su_msg_send(m);

  if (success == 0)
    while (frame.function)
      pthread_cond_wait(frame.cond, frame.mutex);
  else
    su_msg_destroy(m);

  pthread_mutex_unlock(frame.mutex);
  pthread_mutex_destroy(frame.mutex);
  pthread_cond_destroy(frame.cond);

  if (return_value)
    *return_value = frame.value;

  return success;
}

static void _su_pthread_port_execute(su_root_magic_t *m,
				     su_msg_r msg,
				     su_msg_arg_t *a)
{
  struct su_pthread_port_execute *frame;
  frame = *(struct su_pthread_port_execute **)a;
  pthread_mutex_lock(frame->mutex);
  frame->value = frame->function(frame->arg);
  frame->function = NULL;	/* Mark as completed */
  pthread_cond_signal(frame->cond);
  pthread_mutex_unlock(frame->mutex);
}

#if 0				/* pausing and resuming are not used */

/** Pause the pthread port.
 *
 * This is a message function invoked by su_pthread_port_pause() and called
 * from the message dispatcher. It releases the lock sup_runlock and waits
 * until the condition variable sup_resume is signaled and sup_paused is
 * cleared by su_pthread_port_resume().
 */
static
void su_pthread_port_paused(su_root_magic_t *magic,
			    su_msg_r msg,
			    su_msg_arg_t *arg)
{
  su_port_t *self = su_msg_to(msg)->sut_port;
  self->sup_paused = 1;
  while (self->sup_paused)
    pthread_cond_wait(self->sup_resume, self->sup_runlock);
}

/** Pause a port.
 *
 * Obtain an exclusive lock on port's private data.
 *
 * @retval 0 if successful (and clone is paused)
 * @retval -1 upon an error
 */
int su_pthread_port_pause(su_port_t *self)
{
  su_msg_r m = SU_MSG_R_INIT;
  _su_task_t task[1] = {{ self, NULL }};

  if (su_msg_create(m, task, su_task_null, su_pthread_port_paused, 0) < 0)
    return -1;

  if (su_msg_send(m) < 0)
    return -1;

  if (pthread_mutex_lock(self->sup_runlock) < 0)
    return -1;

  return 0;
}

/** Resume a port.
 *
 * Give up an exclusive lock on port's private data.
 *
 * @retval 0 if successful (and clone is resumed)
 * @retval -1 upon an error
 */
int su_pthread_port_resume(su_port_t *self)
{
  assert(self && self->sup_paused);

  self->sup_paused = 0;

  if (pthread_cond_signal(self->sup_resume) < 0 ||
      pthread_mutex_unlock(self->sup_runlock) < 0)
    return -1;

  return 0;
}

#endif