su_source.c 26.8 KB
Newer Older
Pekka Pessi's avatar
Pekka Pessi committed
1 2 3 4 5 6 7
/*
 * This file is part of the Sofia-SIP package
 *
 * Copyright (C) 2005 Nokia Corporation.
 *
 * Contact: Pekka Pessi <pekka.pessi@nokia.com>
 *
8
 * This library is free software; you can redistribute it and/or
Pekka Pessi's avatar
Pekka Pessi committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 * 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
 *
 */

/**
 * @file su_source.c
27
 * @brief Wrapper for glib GSource.
28 29 30 31 32
 *  
 * Refs: 
 *  - http://sofia-sip.sourceforge.net/refdocs/su/group__su__wait.html
 *  - http://developer.gnome.org/doc/API/glib/glib-the-main-event-loop.html
 *
Pekka Pessi's avatar
Pekka Pessi committed
33 34 35 36 37 38 39 40 41 42
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>.
 * 
 * @date Created: Thu Mar  4 15:15:15 2004 ppessi
 * 
 */

#include "config.h"

#include <glib.h>

43 44 45 46 47
#if HAVE_OPEN_C
#include <glib/gthread.h>
#include <glib_global.h>
#endif

Pekka Pessi's avatar
Pekka Pessi committed
48 49 50 51 52 53
#define SU_PORT_IMPLEMENTATION 1

#define SU_MSG_ARG_T union { char anoymous[4]; }

#define su_port_s su_source_s

54
#include "sofia-sip/su_source.h"
55
#include "sofia-sip/su_glib.h"
56

57
#include "sofia-sip/su.h"
Pekka Pessi's avatar
Pekka Pessi committed
58
#include "su_port.h"
59
#include "sofia-sip/su_alloc.h"
Pekka Pessi's avatar
Pekka Pessi committed
60

61 62 63 64 65 66 67 68 69 70 71 72 73
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>

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

static su_port_t *su_source_port_create(void) __attribute__((__malloc__));
Pekka Pessi's avatar
Pekka Pessi committed
74 75 76
static gboolean su_source_prepare(GSource *gs, gint *return_tout);
static gboolean su_source_check(GSource *gs);
static gboolean su_source_dispatch(GSource *gs,
77 78
				   GSourceFunc callback,
				   gpointer user_data);
Pekka Pessi's avatar
Pekka Pessi committed
79 80 81 82 83 84 85 86 87 88 89 90
static void su_source_finalize(GSource *source);

static
GSourceFuncs su_source_funcs[1] = {{
    su_source_prepare,
    su_source_check,
    su_source_dispatch,
    su_source_finalize,
    NULL,
    NULL
  }};

91 92 93
static int su_source_port_init(su_port_t *self, su_port_vtable_t const *vtable);
static void su_source_port_deinit(su_port_t *self);

Pekka Pessi's avatar
Pekka Pessi committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
static void su_source_lock(su_port_t *self, char const *who);
static void su_source_unlock(su_port_t *self, char const *who);
static void su_source_incref(su_port_t *self, char const *who);
static void su_source_decref(su_port_t *self, int blocking, char const *who);
static struct _GSource *su_source_gsource(su_port_t *port);

static int su_source_send(su_port_t *self, su_msg_r rmsg);

static int su_source_register(su_port_t *self,
			    su_root_t *root, 
			    su_wait_t *wait, 
			    su_wakeup_f callback,
			    su_wakeup_arg_t *arg,
			    int priority);
static int su_source_unregister(su_port_t *port,
			      su_root_t *root, 
			      su_wait_t *wait,	
			      su_wakeup_f callback, 
			      su_wakeup_arg_t *arg);
static int su_source_deregister(su_port_t *self, int i);
static int su_source_unregister_all(su_port_t *self,
				  su_root_t *root);
static int su_source_eventmask(su_port_t *self, 
			     int index, int socket, int events);
static void su_source_run(su_port_t *self);
static void su_source_break(su_port_t *self);
static su_duration_t su_source_step(su_port_t *self, su_duration_t tout);
121
static int su_source_thread(su_port_t *self, enum su_port_thread_op op);
Pekka Pessi's avatar
Pekka Pessi committed
122
static int su_source_add_prepoll(su_port_t *port,
123 124 125
				 su_root_t *root, 
				 su_prepoll_f *, 
				 su_prepoll_magic_t *);
Pekka Pessi's avatar
Pekka Pessi committed
126 127 128 129
static int su_source_remove_prepoll(su_port_t *port,
				  su_root_t *root);
static int su_source_multishot(su_port_t *self, int multishot);

130 131 132 133
static char const *su_source_name(su_port_t const *self);

static 
su_port_vtable_t const su_source_port_vtable[1] =
Pekka Pessi's avatar
Pekka Pessi committed
134
  {{
135
      /* su_vtable_size: */ sizeof su_source_port_vtable,
Pekka Pessi's avatar
Pekka Pessi committed
136 137
      su_source_lock,
      su_source_unlock,
138

Pekka Pessi's avatar
Pekka Pessi committed
139 140 141 142 143 144 145 146 147 148 149 150 151 152
      su_source_incref,
      su_source_decref,

      su_source_gsource,

      su_source_send,
      su_source_register,
      su_source_unregister,
      su_source_deregister,
      su_source_unregister_all,
      su_source_eventmask,
      su_source_run,
      su_source_break,
      su_source_step,
153
      su_source_thread,
Pekka Pessi's avatar
Pekka Pessi committed
154 155
      su_source_add_prepoll,
      su_source_remove_prepoll,
156
      su_base_port_timers,
Pekka Pessi's avatar
Pekka Pessi committed
157
      su_source_multishot,
158 159 160 161 162 163 164
      /*su_source_wait_events*/ NULL,
      su_base_port_getmsgs,
      su_base_port_getmsgs_from,
      su_source_name,
      su_base_port_start_shared,
      su_base_port_wait,
      NULL,
Pekka Pessi's avatar
Pekka Pessi committed
165 166
    }};

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

Pekka Pessi's avatar
Pekka Pessi committed
172 173 174 175 176 177
/** 
 * Port is a per-thread reactor.  
 *
 * Multiple root objects executed by single thread share a su_port_t object. 
 */
struct su_source_s {
178
  su_base_port_t   sup_base[1];
Pekka Pessi's avatar
Pekka Pessi committed
179 180
  
  GThread         *sup_tid;
181 182
  GStaticMutex     sup_obtained[1];

Pekka Pessi's avatar
Pekka Pessi committed
183 184
  GStaticMutex     sup_mutex[1];

185 186
  GSource         *sup_source;	/**< Backpointer to source */
  GMainLoop       *sup_main_loop; /**< Reference to mainloop while running */
Pekka Pessi's avatar
Pekka Pessi committed
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
  
  /* Waits */
  unsigned         sup_registers; /** Counter incremented by 
				      su_port_register() or 
				      su_port_unregister()
				  */
  unsigned         sup_n_waits; 
  unsigned         sup_size_waits; 
  unsigned         sup_max_index;
  unsigned        *sup_indices; 
  su_wait_t       *sup_waits; 
  su_wakeup_f     *sup_wait_cbs; 
  su_wakeup_arg_t**sup_wait_args; 
  su_root_t      **sup_wait_roots; 
};

typedef struct _SuSource
{
  GSource    ss_source[1];
  su_port_t  ss_port[1];
} SuSource;

#define SU_SOURCE_OWN_THREAD(p)   ((p)->sup_tid == g_thread_self())

#if 1
#define SU_SOURCE_INCREF(p, f)    (g_source_ref(p->sup_source))
#define SU_SOURCE_DECREF(p, f)    (g_source_unref(p->sup_source))

#else

/* Debugging versions */
#define SU_SOURCE_INCREF(p, f)    (g_source_ref(p->sup_source), printf("incref(%p) by %s\n", (p), f))
#define SU_SOURCE_DECREF(p, f)    do { printf("decref(%p) by %s\n", (p), f), \
  g_source_unref(p->sup_source); } while(0)

#endif

#if HAVE_FUNC
#define enter (void)SU_DEBUG_9(("%s: entering\n", __func__))
#elif HAVE_FUNCTION
#define enter (void)SU_DEBUG_9(("%s: entering\n", __FUNCTION__))
#else
#define enter (void)0
#endif

232 233
/*=============== Public function definitions ===============*/

Pekka Pessi's avatar
Pekka Pessi committed
234
/** Create a root that uses GSource as reactor */
235
su_root_t *su_glib_root_create(su_root_magic_t *magic)
Pekka Pessi's avatar
Pekka Pessi committed
236
{
237
  return su_root_create_with_port(magic, su_source_port_create());
Pekka Pessi's avatar
Pekka Pessi committed
238 239
}

240 241 242 243 244 245
/** Deprecated */
su_root_t *su_root_source_create(su_root_magic_t *magic)
{
  return su_glib_root_create(magic);
}

246 247 248 249 250 251 252 253 254
/** 
 * Returns a GSource object for the root 
 *
 * Note that you need to unref the GSource with g_source_unref() 
 * before destroying the root object.
 *
 * @return NULL on error (for instance if root was not created with 
 *         su_glib_root_create())
 */
255 256 257 258 259 260 261 262
GSource *su_glib_root_gsource(su_root_t *root)
{
  g_assert(root);
  return su_root_gsource(root);
}

/*=============== Private function definitions ===============*/

263
/** Initialize source port */
264 265
static int su_source_port_init(su_port_t *self,
			       su_port_vtable_t const *vtable)
Pekka Pessi's avatar
Pekka Pessi committed
266
{
267
  GSource *gs = (GSource *)((char *)self - offsetof(SuSource, ss_port));
Pekka Pessi's avatar
Pekka Pessi committed
268

269
  self->sup_source = gs;
270 271

  g_static_mutex_init(self->sup_obtained);
Pekka Pessi's avatar
Pekka Pessi committed
272

273
  g_static_mutex_init(self->sup_mutex);
274 275 276 277 278 279 280 281 282 283

  return su_base_port_init(self, vtable);
}


static void su_source_port_deinit(su_port_t *self)
{
  su_base_port_deinit(self);

  g_static_mutex_free(self->sup_mutex);
284
  g_static_mutex_free(self->sup_obtained);
285 286

  su_home_deinit(self->sup_base->sup_home);
Pekka Pessi's avatar
Pekka Pessi committed
287 288
}

289

Pekka Pessi's avatar
Pekka Pessi committed
290 291 292 293 294 295 296
/** @internal Destroy a port. */
static 
void su_source_finalize(GSource *gs)
{
  SuSource *ss = (SuSource *)gs;
  assert(gs);
  SU_DEBUG_9(("su_source_finalize() called\n"));
297
  su_source_port_deinit(ss->ss_port);
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
}

void su_source_port_lock(su_port_t *self, char const *who)
{
  PORT_LOCK_DEBUG(("%p at %s locking(%p)...",
		   (void *)g_thread_self(), who, self));

  g_static_mutex_lock(self->sup_mutex);

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

void su_source_port_unlock(su_port_t *self, char const *who)
{
  g_static_mutex_unlock(self->sup_mutex);

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

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

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

  gmc = g_source_get_context(self->sup_source);

  if (gmc)
    g_main_context_wakeup(gmc);

  return 0;
Pekka Pessi's avatar
Pekka Pessi committed
336 337
}

338
/** @internal
339 340
 *
 * Change or query ownership of the port object.
341 342
 *
 * @param self pointer to a port object
343
 * @param op operation 
344
 *
345 346
 * @ERRORS
 * @ERROR EALREADY port already has an owner (or has no owner)
347
 */
348
static int su_source_thread(su_port_t *self, enum su_port_thread_op op)
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
  GThread *me = g_thread_self();

  switch (op) {

  case su_port_thread_op_is_obtained:
    if (self->sup_tid == me)
      return 2;
    else if (self->sup_tid)
      return 1;
    else
      return 0;

  case su_port_thread_op_release:
    if (self->sup_tid != me)
      return errno = EALREADY, -1;
    self->sup_tid = NULL;
    g_static_mutex_unlock(self->sup_obtained);
    return 0;

  case su_port_thread_op_obtain:
    if (su_home_threadsafe(su_port_home(self)) == -1)
      return -1;
    g_static_mutex_lock(self->sup_obtained);
    self->sup_tid = me;
    return 0;

  default:
    return errno = ENOSYS, -1;
  }
379 380 381 382
}

/* -- Registering and unregistering ------------------------------------- */

Pekka Pessi's avatar
Pekka Pessi committed
383 384 385
/* Seconds from 1.1.1900 to 1.1.1970 */
#define NTP_EPOCH 2208988800UL 

386
/** Prepare to wait - calculate time to next timer */
Pekka Pessi's avatar
Pekka Pessi committed
387 388 389 390 391 392 393 394
static
gboolean su_source_prepare(GSource *gs, gint *return_tout)
{
  SuSource *ss = (SuSource *)gs;
  su_port_t *self = ss->ss_port;

  enter;
  
395
  if (self->sup_base->sup_head) {
396
    *return_tout = 0;
Pekka Pessi's avatar
Pekka Pessi committed
397
    return TRUE;
398
  }
Pekka Pessi's avatar
Pekka Pessi committed
399

400
  if (self->sup_base->sup_timers) {
Pekka Pessi's avatar
Pekka Pessi committed
401 402 403 404 405 406 407 408
    su_time_t now;
    GTimeVal  gtimeval;
    su_duration_t tout;

    g_source_get_current_time(gs, &gtimeval);
    now.tv_sec = gtimeval.tv_sec + 2208988800UL;
    now.tv_usec = gtimeval.tv_usec;

409
    tout = su_timer_next_expires(self->sup_base->sup_timers, now);
Pekka Pessi's avatar
Pekka Pessi committed
410

411 412
    *return_tout = (tout < 0 || tout > (su_duration_t)G_MAXINT)?
	-1 : (gint)tout;
Pekka Pessi's avatar
Pekka Pessi committed
413

414
    return (tout == 0);
Pekka Pessi's avatar
Pekka Pessi committed
415
  }
416

Pekka Pessi's avatar
Pekka Pessi committed
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
  return FALSE;
}

static
gboolean su_source_check(GSource *gs)
{
  SuSource *ss = (SuSource *)gs;
  su_port_t *self = ss->ss_port;
  gint tout;
  unsigned i, I;

  enter;

  I = self->sup_n_waits;

Martti Mela's avatar
Martti Mela committed
432
#if SU_HAVE_POLL
Pekka Pessi's avatar
Pekka Pessi committed
433 434 435 436
  for (i = 0; i < I; i++) {
    if (self->sup_waits[i].revents)
      return TRUE;
  }
Martti Mela's avatar
Martti Mela committed
437
#endif
Pekka Pessi's avatar
Pekka Pessi committed
438 439 440 441 442 443 444 445 446 447 448 449 450 451

  return su_source_prepare(gs, &tout);
}

static 
gboolean su_source_dispatch(GSource *gs,
			    GSourceFunc callback,
			    gpointer user_data)
{
  SuSource *ss = (SuSource *)gs;
  su_port_t *self = ss->ss_port;

  enter;

452 453
  if (self->sup_base->sup_head)
    su_base_port_getmsgs(self);
Pekka Pessi's avatar
Pekka Pessi committed
454

455
  if (self->sup_base->sup_timers) {
Pekka Pessi's avatar
Pekka Pessi committed
456 457 458 459 460 461 462 463 464 465 466 467
    su_time_t now;
    GTimeVal  gtimeval;
    su_duration_t tout;
    int timers = 0;

    tout = SU_DURATION_MAX;

    g_source_get_current_time(gs, &gtimeval);

    now.tv_sec = gtimeval.tv_sec + 2208988800UL;
    now.tv_usec = gtimeval.tv_usec;

468
    timers = su_timer_expire(&self->sup_base->sup_timers, &tout, now);
Pekka Pessi's avatar
Pekka Pessi committed
469 470
  }

Martti Mela's avatar
Martti Mela committed
471
#if SU_HAVE_POLL
Pekka Pessi's avatar
Pekka Pessi committed
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
  {
    su_root_t *root;
    su_wait_t *waits = self->sup_waits;
    unsigned i, n = self->sup_n_waits;
    unsigned version = self->sup_registers;

    for (i = 0; i < n; i++) {
      if (waits[i].revents) {
	root = self->sup_wait_roots[i];
	self->sup_wait_cbs[i](root ? su_root_magic(root) : NULL, 
			      &waits[i], 
			      self->sup_wait_args[i]);
	/* Callback used su_register()/su_unregister() */
	if (version != self->sup_registers)
	  break;
      }
    }
  }
Martti Mela's avatar
Martti Mela committed
490
#endif
Pekka Pessi's avatar
Pekka Pessi committed
491 492 493 494 495 496 497 498 499

  if (!callback)
    return TRUE;

  return callback(user_data);
}

static void su_source_lock(su_port_t *self, char const *who)
{
500 501 502 503 504 505
  PORT_LOCK_DEBUG(("%p at %s locking(%p)...",
		   (void *)g_thread_self(), who, self));
  g_static_mutex_lock(self->sup_mutex);

  PORT_LOCK_DEBUG((" ...%p at %s locked(%p)...", 
		   (void *)g_thread_self(), who, self));
Pekka Pessi's avatar
Pekka Pessi committed
506 507 508 509
}

static void su_source_unlock(su_port_t *self, char const *who)
{
510 511 512 513
  g_static_mutex_unlock(self->sup_mutex);

  PORT_LOCK_DEBUG((" ...%p at %s unlocked(%p)\n", 
		   (void *)g_thread_self(), who, self));
Pekka Pessi's avatar
Pekka Pessi committed
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
}

static void su_source_incref(su_port_t *self, char const *who)
{
  SU_SOURCE_INCREF(self, who);
}

static void su_source_decref(su_port_t *self, int blocking, char const *who)
{
  /* XXX - blocking? */
  SU_SOURCE_DECREF(self, who);
}

GSource *su_source_gsource(su_port_t *self)
{
  return self->sup_source;
}

/** @internal
 *
 *  Register a @c su_wait_t object. The wait object, a callback function and
 *  a 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
 *   The function @su_source_register returns nonzero index of the wait object, 
 *   or -1 upon an error.  */
int su_source_register(su_port_t *self,
		       su_root_t *root, 
		       su_wait_t *wait, 
		       su_wakeup_f callback,
		       su_wakeup_arg_t *arg,
		       int priority)
{
  unsigned i, j, I;
  unsigned n;

  enter;
  
  assert(SU_SOURCE_OWN_THREAD(self));

  n = self->sup_n_waits;

  if (n >= self->sup_size_waits) {
    /* Reallocate size arrays */
570
    unsigned size;
Pekka Pessi's avatar
Pekka Pessi committed
571 572 573 574 575 576 577
    unsigned *indices;
    su_wait_t *waits;
    su_wakeup_f *wait_cbs;
    su_wakeup_arg_t **wait_args;
    su_root_t **wait_tasks;

    if (self->sup_size_waits == 0)
578
      size = SU_WAIT_MIN;
Pekka Pessi's avatar
Pekka Pessi committed
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 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 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 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
    else 
      size = 2 * self->sup_size_waits;

    indices = realloc(self->sup_indices, size * sizeof(*indices));
    if (indices) {
      self->sup_indices = indices;

      for (i = self->sup_size_waits; i < size; i++)
	indices[i] = UINT_MAX;
    }

    for (i = 0; i < self->sup_n_waits; i++)
      g_source_remove_poll(self->sup_source, (GPollFD*)&self->sup_waits[i]);
      
    waits = realloc(self->sup_waits, size * sizeof(*waits));
    if (waits)
      self->sup_waits = waits;

    for (i = 0; i < self->sup_n_waits; i++)
      g_source_add_poll(self->sup_source, (GPollFD*)&waits[i]);
      
    wait_cbs = realloc(self->sup_wait_cbs, size * sizeof(*wait_cbs));
    if (wait_cbs)
      self->sup_wait_cbs = wait_cbs;

    wait_args = realloc(self->sup_wait_args, size * sizeof(*wait_args));
    if (wait_args)
      self->sup_wait_args = wait_args;

    /* Add sup_wait_roots array, if needed */
    wait_tasks = realloc(self->sup_wait_roots, size * sizeof(*wait_tasks));
    if (wait_tasks) 
      self->sup_wait_roots = wait_tasks;

    if (!(indices && waits && wait_cbs && wait_args && wait_tasks)) {
      return -1;
    }

    self->sup_size_waits = size;
  }

  self->sup_n_waits++;

  if (priority > 0) {
    /* Insert */
    for (; n > 0; n--) {
      g_source_remove_poll(self->sup_source, (GPollFD*)&self->sup_waits[n-1]);
      self->sup_waits[n] = self->sup_waits[n-1];
      g_source_add_poll(self->sup_source, (GPollFD*)&self->sup_waits[n]);
      self->sup_wait_cbs[n] = self->sup_wait_cbs[n-1];
      self->sup_wait_args[n] = self->sup_wait_args[n-1];
      self->sup_wait_roots[n] = self->sup_wait_roots[n-1];	
    }
  }
  else {
    /* Append - no need to move anything */
  }

  self->sup_waits[n] = *wait;
  g_source_add_poll(self->sup_source, (GPollFD*)&self->sup_waits[n]);
  self->sup_wait_cbs[n] = callback;
  self->sup_wait_args[n] = arg;
  self->sup_wait_roots[n] = root;

  I = self->sup_max_index;

  for (i = 0; i < I; i++)  
    if (self->sup_indices[i] == UINT_MAX)
      break;
    else if (self->sup_indices[i] >= n)
      self->sup_indices[i]++;

  if (i == I) 
    self->sup_max_index++;

  if (n + 1 < self->sup_n_waits)
    for (j = i; j < I; j++)
      if (self->sup_indices[j] != UINT_MAX &&
	  self->sup_indices[j] >= n)
	self->sup_indices[j]++;

  self->sup_indices[i] = n;

  self->sup_registers++;

  return i + 1;			/* 0 is failure */
}

/** Unregister a su_wait_t object.
 *  
 *  The function su_source_unregister() unregisters a su_wait_t object. The
 *  wait object, a callback function and a argument are removed from the
 *  port object.
 * 
 * @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)
 * 
 * @return Nonzero index of the wait object, or -1 upon an error.
 */
int su_source_unregister(su_port_t *self,
			 su_root_t *root, 
			 su_wait_t *wait,	
			 su_wakeup_f callback, /* XXX - ignored */
			 su_wakeup_arg_t *arg)
{
  unsigned n, N;
  unsigned i, I, j, *indices;

  enter;
  
  assert(self);
  assert(SU_SOURCE_OWN_THREAD(self));

  i = (unsigned)-1;
  N = self->sup_n_waits;
  I = self->sup_max_index;
  indices = self->sup_indices;

  for (n = 0; n < N; n++) {
    if (SU_WAIT_CMP(wait[0], self->sup_waits[n]) != 0)
      continue;

    /* Found - delete it */
    if (indices[n] == n)
      i = n;
    else for (i = 0; i < I; i++)
      if (indices[i] == n)
	break;

    assert(i < I);

    indices[i] = UINT_MAX;

    g_source_remove_poll(self->sup_source, (GPollFD*)&self->sup_waits[n]);

    self->sup_n_waits = N = N - 1;

    if (n < N)
      for (j = 0; j < I; j++)
	if (self->sup_indices[j] != UINT_MAX &&
	    self->sup_indices[j] > n)
	  self->sup_indices[j]--;
    
    for (; n < N; n++) {
      g_source_remove_poll(self->sup_source, (GPollFD*)&self->sup_waits[n+1]);
      self->sup_waits[n] = self->sup_waits[n+1];
      g_source_add_poll(self->sup_source, (GPollFD*)&self->sup_waits[n]);
      self->sup_wait_cbs[n] = self->sup_wait_cbs[n+1];
      self->sup_wait_args[n] = self->sup_wait_args[n+1];
      self->sup_wait_roots[n] = self->sup_wait_roots[n+1];	  
    }

    i += 1;	/* 0 is failure */

    if (i == I)
      self->sup_max_index--;

    break;
  }

  self->sup_registers++;

  return (int)i;
}

/** Deregister a su_wait_t object.
 *  
 *  The function su_source_deregister() deregisters a su_wait_t registrattion. 
 *  The wait object, a callback function and a argument are removed from the
 *  port object.
 * 
 * @param self     - pointer to port object
 * @param i        - registration index
 * 
 * @return Index of the wait object, or -1 upon an error.
 */
int su_source_deregister(su_port_t *self, int i)
{
  unsigned j, n, N;
  unsigned I, *indices;
  su_wait_t wait[1];

  enter;
  
  assert(self);
  assert(SU_SOURCE_OWN_THREAD(self));

  if (i <= 0)
    return -1;

  N = self->sup_n_waits;
  I = self->sup_max_index;
  indices = self->sup_indices;

777
  assert((unsigned)i < I + 1);
Pekka Pessi's avatar
Pekka Pessi committed
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806

  n = indices[i - 1];

  if (n == UINT_MAX)
    return -1;

  self->sup_n_waits = N = N - 1;

  wait[0] = self->sup_waits[n];

  g_source_remove_poll(self->sup_source, (GPollFD*)&self->sup_waits[n]);

  if (n < N)
    for (j = 0; j < I; j++)
      if (self->sup_indices[j] != UINT_MAX &&
	  self->sup_indices[j] > n)
	self->sup_indices[j]--;

  for (; n < N; n++) {
    g_source_remove_poll(self->sup_source, (GPollFD*)&self->sup_waits[n + 1]);
    self->sup_waits[n] = self->sup_waits[n+1];
    g_source_add_poll(self->sup_source, (GPollFD*)&self->sup_waits[n]);
    self->sup_wait_cbs[n] = self->sup_wait_cbs[n+1];
    self->sup_wait_args[n] = self->sup_wait_args[n+1];
    self->sup_wait_roots[n] = self->sup_wait_roots[n+1];	  
  }

  indices[i - 1] = UINT_MAX;

807
  if ((unsigned)i == I)
Pekka Pessi's avatar
Pekka Pessi committed
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
    self->sup_max_index--;

  su_wait_destroy(wait);

  self->sup_registers++;

  return (int)i;
}

/** @internal
 * Unregister all su_wait_t objects.
 *
 * The function su_source_unregister_all() unregisters all su_wait_t objects
 * associated with given root object destroys all queued timers.
 * 
 * @param  self     - pointer to port object
 * @param  root     - pointer to root object
 * 
 * @return Number of wait objects removed.
 */
int su_source_unregister_all(su_port_t *self, 
			   su_root_t *root)
{
  unsigned i, j;
  unsigned         n_waits;
  su_wait_t       *waits;
  su_wakeup_f     *wait_cbs;
  su_wakeup_arg_t**wait_args;
  su_root_t      **wait_roots;

  enter;
  
  assert(SU_SOURCE_OWN_THREAD(self));

  n_waits    = self->sup_n_waits;
  waits      = self->sup_waits; 
  wait_cbs   = self->sup_wait_cbs; 
  wait_args  = self->sup_wait_args;
  wait_roots = self->sup_wait_roots; 
  
  for (i = j = 0; (unsigned)i < n_waits; i++) {
    if (wait_roots[i] == root) {
      /* XXX - we should free all resources associated with this */
      g_source_remove_poll(self->sup_source, (GPollFD*)&waits[i]);
      continue;
    }
    if (i != j) {
      g_source_remove_poll(self->sup_source, (GPollFD*)&waits[i]);
      waits[j] = waits[i];
      wait_cbs[j] = wait_cbs[i];
      wait_args[j] = wait_args[i];
      wait_roots[j] = wait_roots[i];
      g_source_add_poll(self->sup_source, (GPollFD*)&waits[i]);
    }
    j++;
  }
  
  self->sup_n_waits = j;
  self->sup_registers++;

  return n_waits - j;
}

/**Set mask for a registered event. @internal
 *
 * The function su_source_eventmask() sets the mask describing events that can
 * signal the registered callback.
 *
 * @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.
 */
int su_source_eventmask(su_port_t *self, int index, int socket, int events)
{
  unsigned n;
  int retval;

  enter;
  
  assert(self);
  assert(SU_SOURCE_OWN_THREAD(self));
893
  assert(0 < index && (unsigned)index <= self->sup_max_index);
Pekka Pessi's avatar
Pekka Pessi committed
894

895
  if (index <= 0 || (unsigned)index > self->sup_max_index)
Pekka Pessi's avatar
Pekka Pessi committed
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
    return -1;

  n = self->sup_indices[index - 1];

  if (n == UINT_MAX)
    return -1;

  g_source_remove_poll(self->sup_source, (GPollFD*)&self->sup_waits[n]);

  retval = su_wait_mask(&self->sup_waits[n], socket, events);

  g_source_add_poll(self->sup_source, (GPollFD*)&self->sup_waits[n]);

  return retval;
}

static
int su_source_multishot(su_port_t *self, int multishot)
{
  if (multishot == -1)
    return 1;
  else if (multishot == 0 || multishot == 1)
    return 1;			/* Always enabled */
  else 
    return (errno = EINVAL), -1;
}


/** @internal Main loop.
 * 
 * The function @c su_source_run() runs the main loop
 * 
 * The function @c su_source_run() runs until @c su_source_break() is called
 * from a callback.
 * 
 * @param self     pointer to root object
 * */
void su_source_run(su_port_t *self)
{
  GMainContext *gmc;
  GMainLoop *gml;

  enter;
  
  gmc = g_source_get_context(self->sup_source);
  if (gmc && g_main_context_acquire(gmc)) {
    gml = g_main_loop_new(gmc, TRUE);
    self->sup_main_loop = gml;
    g_main_loop_run(gml);
    g_main_loop_unref(gml);
    self->sup_main_loop = NULL;
    g_main_context_release(gmc);
  }
}

/** @internal
 * The function @c su_source_break() is used to terminate execution of @c
 * su_source_run(). It can be called from a callback function.
 * 
 * @param self     pointer to port
 * 
 */
void su_source_break(su_port_t *self)
{
  enter;
  
  if (self->sup_main_loop)
    g_main_loop_quit(self->sup_main_loop);
}

/** @internal Block until wait object is signaled or timeout.
 *
 * This function waits for wait objects and the timers associated with 
 * the root object.  When any wait object is signaled or timer is
 * expired, it invokes the callbacks. 
 * 
 *   This function returns when a callback has been invoked or @c tout
 *   milliseconds is elapsed. 
 *
 * @param self     pointer to port
 * @param tout     timeout in milliseconds
 * 
 * @Return
 *   Milliseconds to the next invocation of timer, or @c SU_WAIT_FOREVER if
 *   there are no active timers.
 */
su_duration_t su_source_step(su_port_t *self, su_duration_t tout)
{
  GMainContext *gmc;

  enter;
  
  gmc = g_source_get_context(self->sup_source);

  if (gmc && g_main_context_acquire(gmc)) {
991
    GPollFD *fds = NULL;
992 993
    gint fds_size = 0;
    gint fds_wait;
Pekka Pessi's avatar
Pekka Pessi committed
994
    gint priority = G_MAXINT;
995
    gint src_tout = -1;
Pekka Pessi's avatar
Pekka Pessi committed
996

997
    g_main_context_prepare(gmc, &priority);
Pekka Pessi's avatar
Pekka Pessi committed
998

999 1000 1001 1002 1003 1004
    fds_wait = g_main_context_query(gmc, priority, &src_tout, NULL, 0);
    while (fds_wait > fds_size) {
      fds = g_alloca(fds_wait * sizeof(fds[0]));
      fds_size = fds_wait;
      fds_wait = g_main_context_query(gmc, priority, &src_tout, fds, fds_size);
    }
Pekka Pessi's avatar
Pekka Pessi committed
1005

1006 1007
    if (src_tout >= 0 && tout > (su_duration_t)src_tout)
      tout = src_tout;
Pekka Pessi's avatar
Pekka Pessi committed
1008

1009
    su_wait((su_wait_t *)fds, fds_wait, tout);
1010

1011
    g_main_context_check(gmc, priority, fds, fds_wait);
1012 1013 1014

    g_main_context_dispatch(gmc);

Pekka Pessi's avatar
Pekka Pessi committed
1015 1016 1017 1018 1019 1020
    g_main_context_release(gmc);
  }

  return 0;
}

1021 1022 1023 1024 1025 1026 1027 1028
static int su_source_add_prepoll(su_port_t *port,
				 su_root_t *root, 
				 su_prepoll_f *prepoll, 
				 su_prepoll_magic_t *magic)
{
  /* We could call prepoll in su_source_prepare()?? */
  return -1;
}
Pekka Pessi's avatar
Pekka Pessi committed
1029

1030 1031
static int su_source_remove_prepoll(su_port_t *port,
				  su_root_t *root)
Pekka Pessi's avatar
Pekka Pessi committed
1032
{
1033
  return -1;
Pekka Pessi's avatar
Pekka Pessi committed
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
}

#if 0
/** @internal
 *  Prints out the contents of the port.
 *
 * @param self pointer to a port
 * @param f    pointer to a file (if @c NULL, uses @c stdout).
 */
void su_source_dump(su_port_t const *self, FILE *f)
{
  int i;
#define IS_WAIT_IN(x) (((x)->events & SU_WAIT_IN) ? "IN" : "")
#define IS_WAIT_OUT(x) (((x)->events & SU_WAIT_OUT) ? "OUT" : "")
#define IS_WAIT_ACCEPT(x) (((x)->events & SU_WAIT_ACCEPT) ? "ACCEPT" : "")

  if (f == NULL)
    f = stdout;

  fprintf(f, "su_port_t at %p:\n", self);
  fprintf(f, "\tport is%s running\n", self->sup_running ? "" : "not ");
  fprintf(f, "\tport tid %p\n", (void *)self->sup_tid);
  fprintf(f, "\t%d wait objects\n", self->sup_n_waits);
  for (i = 0; i < self->sup_n_waits; i++) {
    
  }
}

#endif

1064 1065 1066 1067 1068 1069 1070
/**@internal
 *
 * Allocates and initializes a reactor and message port object.
 *
 * @return
 *   If successful a pointer to the new message port is returned, otherwise
 *   NULL is returned.  
Pekka Pessi's avatar
Pekka Pessi committed
1071
 */
1072
static su_port_t *su_source_port_create(void)
Pekka Pessi's avatar
Pekka Pessi committed
1073
{
1074 1075
  SuSource *ss;
  su_port_t *self = NULL;
Pekka Pessi's avatar
Pekka Pessi committed
1076

1077
  SU_DEBUG_9(("su_source_port_create() called\n"));
Pekka Pessi's avatar
Pekka Pessi committed
1078

1079
  ss = (SuSource *)g_source_new(su_source_funcs, (sizeof *ss));
Pekka Pessi's avatar
Pekka Pessi committed
1080

1081 1082
  if (ss) {
    self = ss->ss_port;
1083
    if (su_source_port_init(self, su_source_port_vtable) < 0)
1084 1085 1086 1087
      g_source_unref(ss->ss_source), self = NULL;
  } else {
    su_perror("su_source_port_create(): g_source_new");
  }
Pekka Pessi's avatar
Pekka Pessi committed
1088

1089
  SU_DEBUG_1(("su_source_port_create() returns %p\n", (void *)self));
Pekka Pessi's avatar
Pekka Pessi committed
1090

1091
  return self;
Pekka Pessi's avatar
Pekka Pessi committed
1092 1093
}

1094
/* No su_source_port_start */
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104

/** Use su_source implementation when su_root_create() is called.
 *
 * @NEW_1_12_5
 */
void su_glib_prefer_gsource(void)
{
  su_port_prefer(su_source_port_create, NULL);
}