su_select_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
/*
 * 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_select_port.c
 *
28
 * Port implementation using select().
29 30 31 32
 *
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>
 * @author Kai Vehmanen <kai.vehmanen@nokia.com>
 *
33
 * @date Created: Fri Jan 26 17:56:34 2007 ppessi
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
 */

#include "config.h"

#if HAVE_SELECT

#define su_port_s su_select_port_s

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

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

54 55 56
#if HAVE_WIN32
#error winsock select() not supported yet
#else
57 58 59 60 61 62
#if HAVE_SYS_SELECT_H
#include <sys/select.h>
#elif HAVE_SYS_TIME_H
#include <sys/time.h>
#endif

63 64 65 66 67 68 69 70 71 72 73 74
#include <sys/types.h>
#include <unistd.h>

#ifndef __NFDBITS
#define __NFDBITS (8 * sizeof (long int))
#endif

#undef FDSETSIZE
/* Size of fd set in bytes */
#define FDSETSIZE(n) (((n) + __NFDBITS - 1) / __NFDBITS * (__NFDBITS / 8))
#endif

75 76 77
/** Port based on select(). */

struct su_select_port_s {
78
  su_socket_port_t sup_base[1];
79

80 81 82 83
#define sup_home sup_base->sup_base->sup_base->sup_home

  /** epoll fd */
  int              sup_epoll;
84 85 86 87 88 89
  unsigned         sup_multishot; /**< Multishot operation? */

  unsigned         sup_registers; /** Counter incremented by 
				      su_port_register() or 
				      su_port_unregister()
				   */
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
  int              sup_n_registrations;
  int              sup_max_index; /**< Indexes are equal or smaller than this */
  int              sup_size_indices; /**< Size of allocated index table */

  /** Structure containing registration data */
  struct su_select_register {
    struct su_select_register *ser_next; /* Next in free list */
    su_wakeup_f     ser_cb; 
    su_wakeup_arg_t*ser_arg; 
    su_root_t      *ser_root; 
    int             ser_id; /** registration identifier */
    su_wait_t       ser_wait[1];
  } **sup_indices;

  int               sup_maxfd, sup_allocfd;
  
  fd_set           *sup_readfds, *sup_readfds2;
  fd_set           *sup_writefds, *sup_writefds2;
108 109
};

110 111 112
static void su_select_port_decref(su_port_t *self,
				 int blocking,
				 char const *who);
113
static int su_select_port_register(su_port_t *self,
114 115 116 117 118
				  su_root_t *root, 
				  su_wait_t *wait, 
				  su_wakeup_f callback,
				  su_wakeup_arg_t *arg,
				  int priority);
119
static int su_select_port_unregister(su_port_t *port,
120 121 122 123
				    su_root_t *root, 
				    su_wait_t *wait,	
				    su_wakeup_f callback, 
				    su_wakeup_arg_t *arg);
124 125 126
static int su_select_port_deregister(su_port_t *self, int i);
static int su_select_port_unregister_all(su_port_t *self, su_root_t *root);
static int su_select_port_eventmask(su_port_t *self, 
127 128 129
				   int index,
				   int socket,
				   int events);
130 131
static int su_select_port_multishot(su_port_t *self, int multishot);
static int su_select_port_wait_events(su_port_t *self, su_duration_t tout);
132
static char const *su_select_port_name(su_port_t const *self);
133 134 135 136 137 138 139 140 141

su_port_vtable_t const su_select_port_vtable[1] =
  {{
      /* su_vtable_size: */ sizeof su_select_port_vtable,
      su_pthread_port_lock,
      su_pthread_port_unlock,
      su_base_port_incref,
      su_select_port_decref,
      su_base_port_gsource,
142
      su_socket_port_send,
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
      su_select_port_register,
      su_select_port_unregister,
      su_select_port_deregister,
      su_select_port_unregister_all,
      su_select_port_eventmask,
      su_base_port_run,
      su_base_port_break,
      su_base_port_step,
      su_pthread_port_own_thread,
      su_base_port_add_prepoll,
      su_base_port_remove_prepoll,
      su_base_port_timers,
      su_select_port_multishot,
      su_base_port_threadsafe,
      su_base_port_yield,
      su_select_port_wait_events,
159
      su_base_port_getmsgs,
160 161 162
      su_base_port_getmsgs_from,
      su_select_port_name,
      su_base_port_start_shared,
163
      su_pthread_port_wait,
164
      su_pthread_port_execute,
165 166
    }};

167
static char const *su_select_port_name(su_port_t const *self)
168
{
169
  return "select";
170 171
}

172 173 174 175 176
static void su_select_port_decref(su_port_t *self, int blocking, char const *who)
{
  (void)su_base_port_decref(self, blocking, who);
}

177 178 179 180
static void su_select_port_deinit(void *arg)
{
  su_port_t *self = arg;

181
  SU_DEBUG_9(("%s(%p) called\n", "su_select_port_deinit", (void *)self));
182

183
  su_socket_port_deinit(self->sup_base);
184 185 186 187
}

/** @internal
 *
188
 *  Register a #su_wait_t object. The wait object, a callback function and
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
 *  an argument pointer is stored in the port object.  The callback function
 *  will be called when the wait object is signaled.
 *
 *  Please note if identical wait objects are inserted, only first one is
 *  ever signalled.
 * 
 * @param self	     pointer to port
 * @param root	     pointer to root object
 * @param waits	     pointer to wait object
 * @param callback   callback function pointer
 * @param arg	     argument given to callback function when it is invoked
 * @param priority   relative priority of the wait object 
 *              (0 is normal, 1 important, 2 realtime)
 * 
 * @return
 *   Positive index of the wait object, 
 *   or -1 upon an error.
 */
int su_select_port_register(su_port_t *self,
208 209 210 211 212
			   su_root_t *root, 
			   su_wait_t *wait, 
			   su_wakeup_f callback,
			   su_wakeup_arg_t *arg,
			   int priority)
213 214
{
  int i, j, n;
215 216 217 218 219
  struct su_select_register *ser;
  struct su_select_register **indices = self->sup_indices;
  int allocfd = self->sup_allocfd;
  fd_set *readfds = self->sup_readfds, *readfds2 = self->sup_readfds2;
  fd_set *writefds = self->sup_writefds, *writefds2 = self->sup_writefds2;
220 221 222

  assert(su_port_own_thread(self));

223
  n = self->sup_size_indices;
224 225 226 227

  if (n >= SU_WAIT_MAX)
    return su_seterrno(ENOMEM);

228
  self->sup_registers++;
229

230 231
  if (wait->fd >= allocfd) 
    allocfd += __NFDBITS;		/* long at a time */
232

233 234 235 236
  if (allocfd >= self->sup_allocfd) {
    size_t bytes = FDSETSIZE(allocfd);
    size_t bytes0 = FDSETSIZE(self->sup_allocfd);
    /* (Re)allocate fd_sets  */
237

238 239 240 241 242
    readfds = su_realloc(self->sup_home, readfds, bytes);
    if (readfds) self->sup_readfds = readfds;
    readfds2 = su_realloc(self->sup_home, readfds2, bytes);
    if (readfds2) self->sup_readfds2 = readfds2;
    if (!readfds || !readfds2)
243 244
      return -1;

245 246 247 248 249 250 251 252 253 254 255
    writefds = su_realloc(self->sup_home, writefds, bytes);
    if (writefds) self->sup_writefds = writefds;
    writefds2 = su_realloc(self->sup_home, writefds2, bytes);
    if (writefds2) self->sup_writefds2 = writefds2;
    if (!writefds || !writefds2)
      return -1;

    memset((char *)readfds + bytes0, 0, bytes - bytes0);
    memset((char *)writefds + bytes0, 0, bytes - bytes0);

    self->sup_allocfd = allocfd;
256 257
  }

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
  ser = indices[0];

  if (!ser) {
    su_home_t *h = su_port_home(self);

    i = self->sup_max_index, j = i == 0 ? 15 : i + 16;
    
    if (j >= self->sup_size_indices) {
      /* Reallocate index table */
      n = n < 1024 ? 2 * n : n + 1024;
      indices = su_realloc(h, indices, n * sizeof(indices[0]));
      if (!indices)
	return -1;
      self->sup_indices = indices;
      self->sup_size_indices = n;
273 274
    }

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
    /* Allocate registrations */
    ser = su_zalloc(h, (j - i) * (sizeof *ser));
    if (!ser)
      return -1;

    indices[0] = ser;

    for (i++; i <= j; i++) {
      ser->ser_id = i;
      ser->ser_next = i < j ? ser + 1 : NULL;
      indices[i] = ser++;
    }

    self->sup_max_index = j;

    ser = indices[0];
291 292
  }

293
  i = ser->ser_id;
294

295 296 297 298 299 300 301
  indices[0] = ser->ser_next;
  
  ser->ser_next = NULL;
  *ser->ser_wait = *wait;
  ser->ser_cb = callback;
  ser->ser_arg = arg;
  ser->ser_root = root;
302

303 304 305 306
  if (wait->events & SU_WAIT_IN)
    FD_SET(wait->fd, readfds);
  if (wait->events & SU_WAIT_OUT)
    FD_SET(wait->fd, writefds);
307

308 309
  if (wait->fd >= self->sup_maxfd)
    self->sup_maxfd = wait->fd + 1;
310

311
  self->sup_n_registrations++;
312

313
  return i;			/* return index */
314 315
}

316
static void su_select_port_update_maxfd(su_port_t *self)
317
{
318 319
  int i;
  su_socket_t maxfd = 0;
320

321 322 323 324 325 326
  for (i = 1; i <= self->sup_max_index; i++) {
    if (!self->sup_indices[i]->ser_cb)
      continue;
    if (maxfd <= self->sup_indices[i]->ser_wait->fd)
      maxfd = self->sup_indices[i]->ser_wait->fd + 1;
  }
327

328 329
  self->sup_maxfd = maxfd;
}
330

331 332 333 334 335 336 337 338 339 340
/** Deregister a su_wait_t object. */
static int su_select_port_deregister0(su_port_t *self, int i, int destroy_wait)
{
  struct su_select_register **indices = self->sup_indices;
  struct su_select_register *ser;

  ser = self->sup_indices[i];
  if (ser == NULL || ser->ser_cb == NULL) {
    su_seterrno(ENOENT);
    return -1;
341 342
  }

343
  assert(ser->ser_id == i);
344

345 346
  FD_CLR(ser->ser_wait->fd, self->sup_readfds);
  FD_CLR(ser->ser_wait->fd, self->sup_writefds);
347

348 349
  if (ser->ser_wait->fd + 1 >= self->sup_maxfd)
    self->sup_maxfd = 0;
350

351 352 353
  memset(ser, 0, sizeof *ser);
  ser->ser_id = i;
  ser->ser_next = indices[0], indices[0] = ser;
354

355
  self->sup_n_registrations--;
356 357 358 359 360 361 362 363
  self->sup_registers++;

  return i;
}


/** Unregister a su_wait_t object.
 *  
364 365 366
 * The function su_select_port_unregister() unregisters a su_wait_t object. 
 * The registration defined by the wait object, the callback function and
 * the argument pointer are removed from the port object.
367 368 369 370 371 372 373 374 375 376 377 378 379
 * 
 * @param self     - pointer to port object
 * @param root     - pointer to root object
 * @param wait     - pointer to wait object
 * @param callback - callback function pointer (may be NULL)
 * @param arg      - argument given to callback function when it is invoked 
 *                   (may be NULL)
 *
 * @deprecated Use su_select_port_deregister() instead. 
 *
 * @return Nonzero index of the wait object, or -1 upon an error.
 */
int su_select_port_unregister(su_port_t *self,
380 381 382 383
			     su_root_t *root, 
			     su_wait_t *wait,	
			     su_wakeup_f callback, /* XXX - ignored */
			     su_wakeup_arg_t *arg)
384
{
385 386 387
  int i, I;

  struct su_select_register *ser;
388 389 390 391

  assert(self);
  assert(su_port_own_thread(self));

392
  I = self->sup_max_index;
393

394 395 396 397 398 399 400
  for (i = 1; i <= I; i++) {
    ser = self->sup_indices[i];

    if (ser->ser_cb &&
	arg == ser->ser_arg &&
	SU_WAIT_CMP(wait[0], ser->ser_wait[0]) == 0)
      return su_select_port_deregister0(self, ser->ser_id, 0);
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
  }

  su_seterrno(ENOENT);

  return -1;
}

/** Deregister a su_wait_t object.
 *  
 *  Deregisters a registration by index. The wait object, a callback
 *  function and a argument are removed from the port object. The wait
 *  object is destroyed.
 * 
 * @param self     - pointer to port object
 * @param i        - registration index
 * 
 * @return Index of the wait object, or -1 upon an error.
 */
int su_select_port_deregister(su_port_t *self, int i)
{
421
  struct su_select_register *ser;
422

423
  if (i <= 0 || i > self->sup_max_index)
424 425
    return su_seterrno(EBADF);

426 427
  ser = self->sup_indices[i];
  if (!ser->ser_cb)
428 429
    return su_seterrno(EBADF);

430
  return su_select_port_deregister0(self, i, 1);
431 432 433 434
}


/** @internal
435
 * Unregister all su_wait_t objects of given su_root_t instance.
436
 *
437 438
 * The function su_select_port_unregister_all() unregisters all su_wait_t
 * objects associated with given root object.
439 440 441 442 443 444
 * 
 * @param  self     - pointer to port object
 * @param  root     - pointer to root object
 * 
 * @return Number of wait objects removed.
 */
445
int su_select_port_unregister_all(su_port_t *self, su_root_t *root)
446
{
447
  int i, I, n;
448

449
  struct su_select_register *ser;
450

451 452
  assert(self); assert(root);
  assert(su_port_own_thread(self));
453

454
  I = self->sup_max_index;
455

456 457 458
  for (i = 1, n = 0; i <= I; i++) {
    ser = self->sup_indices[i];
    if (ser->ser_root != root)
459
      continue;
460 461
    su_select_port_deregister0(self, ser->ser_id, 0);
    n++;
462 463
  }

464
  return n;
465 466 467 468
}

/**Set mask for a registered event. @internal
 *
469 470
 * The function su_select_port_eventmask() sets the mask describing events
 * that can signal the registered callback.
471 472 473 474 475 476 477 478 479
 *
 * @param port   pointer to port object
 * @param index  registration index
 * @param socket socket
 * @param events new event mask
 *
 * @retval 0 when successful,
 * @retval -1 upon an error.
 */
480 481 482
int su_select_port_eventmask(su_port_t *self,
			     int index,
			     int socket, int events)
483
{
484 485 486 487
  struct su_select_register *ser;

  if (index <= 0 || index > self->sup_max_index)
    return su_seterrno(EBADF);
488

489 490
  ser = self->sup_indices[index];
  if (!ser->ser_cb)
491
    return su_seterrno(EBADF);
492 493 494 495 496

  if (self->sup_maxfd == 0)
    su_select_port_update_maxfd(self);

  if (socket >= self->sup_maxfd)
497 498
    return su_seterrno(EBADF);

499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
  if (su_wait_mask(ser->ser_wait, socket, events) < 0)
    return -1;

  assert(socket < self->sup_maxfd);
  
  if (events & SU_WAIT_IN)
    FD_SET(socket, self->sup_readfds);
  else
    FD_CLR(socket, self->sup_readfds);

  if (events & SU_WAIT_OUT)
    FD_SET(socket, self->sup_writefds);
  else
    FD_CLR(socket, self->sup_writefds);

  return 0;
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
}

/** @internal Enable multishot mode.
 *
 * Enables, disables or queries the multishot mode for the port. The
 * multishot mode determines how the events are scheduled by port. If
 * multishot mode is enabled, port serves all the sockets that have received
 * network events. If it is disabled, only first socket event is served.
 *
 * @param self      pointer to port object
 * @param multishot multishot mode (0 => disables, 1 => enables, -1 => query)
 * 
 * @retval 0 multishot mode is disabled
 * @retval 1 multishot mode is enabled
 * @retval -1 an error occurred
 */
static
int su_select_port_multishot(su_port_t *self, int multishot)
{
  if (multishot < 0)
    return self->sup_multishot;
  else if (multishot == 0 || multishot == 1)
    return self->sup_multishot = multishot;
  else 
    return (errno = EINVAL), -1;
}


/** @internal
544
 * Wait (poll()) for wait objects in port.
545 546 547 548 549 550 551 552 553
 *
 * @param self     pointer to port
 * @param tout     timeout in milliseconds
 *
 * @return number of events handled
 */
static
int su_select_port_wait_events(su_port_t *self, su_duration_t tout)
{
554 555 556 557 558
  int j, n, events = 0;
  unsigned version = self->sup_registers;
  size_t bytes;
  struct timeval tv;
  fd_set *rset = NULL, *wset = NULL;
559

560 561
  if (self->sup_maxfd == 0)
    su_select_port_update_maxfd(self);
562

563 564 565 566 567 568 569 570 571 572 573 574
  bytes = self->sup_maxfd ? FDSETSIZE(self->sup_maxfd - 1) : 0;

  if (bytes) {
    rset = memcpy(self->sup_readfds2, self->sup_readfds, bytes);
    wset = memcpy(self->sup_writefds2, self->sup_writefds, bytes);
  }  

  tv.tv_sec = tout / 1000;
  tv.tv_usec = (tout % 1000) * 1000;

  n = select(self->sup_maxfd, rset, wset, NULL, &tv);

575
  if (n < 0) {
576 577 578
    SU_DEBUG_0(("su_select_port_wait_events(%p): %s (%d)\n",
		(void *)self, su_strerror(su_errno()), su_errno()));
    return 0;
579
  }
580 581
  else if (n == 0)
    return 0;
582

583
  for (j = 1; j <= self->sup_max_index; j++) {
584 585 586
    struct su_select_register *ser;
    su_root_magic_t *magic;
    int fd;
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
    ser = self->sup_indices[j];
    if (!ser->ser_cb)
      continue;

    fd = ser->ser_wait->fd;
    ser->ser_wait->revents = 0;

    if (ser->ser_wait->events & SU_WAIT_IN)
      if (FD_ISSET(fd, rset)) ser->ser_wait->revents |= SU_WAIT_IN, n--;
    if (ser->ser_wait->events & SU_WAIT_OUT)
      if (FD_ISSET(fd, wset)) ser->ser_wait->revents |= SU_WAIT_OUT, n--;

    if (ser->ser_wait->revents) {
      magic = ser->ser_root ? su_root_magic(ser->ser_root) : NULL;
      ser->ser_cb(magic, ser->ser_wait, ser->ser_arg);
      events++;
      if (version != self->sup_registers)
	/* Callback function used su_register()/su_deregister() */
	return events;
      if (!self->sup_multishot)
	/* Callback function used su_register()/su_deregister() */
	return events;
    }

    if (n == 0)
      break;
  }    

  assert(n == 0);

  return events;
}

/** Create a port using epoll() or poll().
622 623 624
 */
su_port_t *su_select_port_create(void)
{
625
  su_port_t *self;
626

627
  self = su_home_new(sizeof *self);
628
  if (!self)
629 630 631 632 633 634 635 636 637 638
    return NULL;

  if (su_home_destructor(su_port_home(self), su_select_port_deinit) < 0 ||
      !(self->sup_indices = 
	su_zalloc(su_port_home(self),
		  (sizeof self->sup_indices[0]) * 
		  (self->sup_size_indices = __NFDBITS)))) {
    su_home_unref(su_port_home(self));
    return NULL;
  }
639 640 641

  self->sup_multishot = SU_ENABLE_MULTISHOT_POLL;

642
  if (su_socket_port_init(self->sup_base, su_select_port_vtable) < 0)
643 644 645 646 647 648
    return su_home_unref(su_port_home(self)), NULL;

  return self;
}

int su_select_clone_start(su_root_t *parent,
649 650 651 652
			 su_clone_r return_clone,
			 su_root_magic_t *magic,
			 su_root_init_f init,
			 su_root_deinit_f deinit)
653 654 655 656 657
{
  return su_pthreaded_port_start(su_select_port_create, 
				 parent, return_clone, magic, init, deinit);
}

658

659
#endif