su_osx_runloop.c 45.5 KB
Newer Older
Martti Mela's avatar
Martti Mela committed
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) 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
 *
 */

25 26 27 28 29 30 31 32 33 34 35 36
/**@ingroup su_wait
 * @CFILE su_osx_runloop.c
 *
 * OS-Independent Socket Syncronization Interface.
 *
 * This looks like nth reincarnation of "reactor".  It implements the
 * poll/select/WaitForMultipleObjects and message passing functionality.
 *
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>
 * @author Kai Vehmanen <kai.vehmanen@nokia.com>
 *
 * @date Created: Tue Sep 14 15:51:04 1999 ppessi
Martti Mela's avatar
Martti Mela committed
37 38 39 40
 */

#include "config.h"

41 42 43 44 45 46 47 48
/* React to multiple events per one poll() to make sure 
 * that high-priority events can never completely mask other events.
 * Enabled by default on all platforms except WIN32 */
#ifndef WIN32
#define SU_ENABLE_MULTISHOT_POLL 1
#else
#define SU_ENABLE_MULTISHOT_POLL 0
#endif
Martti Mela's avatar
Martti Mela committed
49 50 51

#include <stdlib.h>
#include <assert.h>
52
#include <stdarg.h>
Martti Mela's avatar
Martti Mela committed
53 54 55
#include <stdio.h>
#include <string.h>
#include <limits.h>
56
#include <errno.h>
Martti Mela's avatar
Martti Mela committed
57 58 59 60 61

#define SU_PORT_IMPLEMENTATION 1

#include "sofia-sip/su.h"
#include "su_port.h"
62
#include "sofia-sip/su_osx_runloop.h"
Martti Mela's avatar
Martti Mela committed
63
#include "sofia-sip/su_alloc.h"
64 65 66 67 68 69 70 71 72 73
#include "sofia-sip/su_debug.h"

#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

Martti Mela's avatar
Martti Mela committed
74 75

#if SU_HAVE_PTHREADS
76
/* Pthread implementation */
Martti Mela's avatar
Martti Mela committed
77
#include <pthread.h>
78 79 80 81 82 83 84 85 86
#define SU_HAVE_MBOX 1
#else
#define SU_HAVE_MBOX 0
#endif

#if HAVE_SOCKETPAIR
#define MBOX_SEND  1
#else
#define MBOX_SEND  0
Martti Mela's avatar
Martti Mela committed
87 88 89 90
#endif

static su_port_t *su_osx_runloop_create(void) __attribute__((__malloc__));

91 92 93 94 95
/* Callback for CFObserver and CFSocket */
static
void cf_observer_cb(CFRunLoopObserverRef observer, 
		    CFRunLoopActivity activity, 
		    void *info);
96 97 98 99 100
static void su_port_osx_socket_cb(CFSocketRef s, 
				  CFSocketCallBackType callbackType, 
				  CFDataRef address, 
				  const void *data, 
				  void *info);
101
static CFSocketCallBackType map_poll_event_to_cf_event(int events);
102

Martti Mela's avatar
Martti Mela committed
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
static void su_port_osx_lock(su_port_t *self, char const *who);
static void su_port_osx_unlock(su_port_t *self, char const *who);
static void su_port_osx_incref(su_port_t *self, char const *who);
static void su_port_osx_decref(su_port_t *self, int blocking, char const *who);

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

static int su_port_osx_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_port_osx_unregister(su_port_t *port,
			      su_root_t *root, 
			      su_wait_t *wait,	
			      su_wakeup_f callback, 
			      su_wakeup_arg_t *arg);
121

Martti Mela's avatar
Martti Mela committed
122
static int su_port_osx_deregister(su_port_t *self, int i);
123

Martti Mela's avatar
Martti Mela committed
124
static int su_port_osx_unregister_all(su_port_t *self,
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
			   su_root_t *root);

static int su_port_osx_getmsgs(su_port_t *self);
static
int su_port_osx_eventmask(su_port_t *self, int index, int socket, int events);
static
void su_port_osx_run(su_port_t *self);
static
void su_port_osx_break(su_port_t *self);
static
su_duration_t su_port_osx_step(su_port_t *self, su_duration_t tout);

#if 0
unsigned su_port_query(su_port_t *, su_wait_t *, unsigned n_waits);
void su_port_event(su_port_t *, su_wait_t *waitobj);
#endif

static
int su_port_osx_own_thread(su_port_t const *port);
Martti Mela's avatar
Martti Mela committed
144 145

static
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
int su_port_osx_add_prepoll(su_port_t *port,
			su_root_t *root, 
			su_prepoll_f *, 
			su_prepoll_magic_t *);

static
int su_port_osx_remove_prepoll(su_port_t *port,
			   su_root_t *root);

static
su_timer_t **su_port_osx_timers(su_port_t *port);

static
int su_port_osx_multishot(su_port_t *port, int multishot);

static
int su_port_osx_threadsafe(su_port_t *port);

static
int su_port_osx_yield(su_port_t *port);

Martti Mela's avatar
Martti Mela committed
167 168 169 170 171 172 173
su_port_vtable_t const su_port_osx_vtable[1] =
  {{
      /* su_vtable_size: */ sizeof su_port_osx_vtable,
      su_port_osx_lock,
      su_port_osx_unlock,
      su_port_osx_incref,
      su_port_osx_decref,
174
      NULL /* su_port_osx_runloop */, /* XXX - was: gsource, */
Martti Mela's avatar
Martti Mela committed
175 176 177 178 179 180 181 182 183 184 185 186 187 188
      su_port_osx_send,
      su_port_osx_register,
      su_port_osx_unregister,
      su_port_osx_deregister,
      su_port_osx_unregister_all,
      su_port_osx_eventmask,
      su_port_osx_run,
      su_port_osx_break,
      su_port_osx_step,
      su_port_osx_own_thread,
      su_port_osx_add_prepoll,
      su_port_osx_remove_prepoll,
      su_port_osx_timers,
      su_port_osx_multishot,
189 190
      su_port_osx_threadsafe,
      su_port_osx_yield
Martti Mela's avatar
Martti Mela committed
191 192
    }};

193 194 195
static int su_port_osx_wait_events(su_port_t *self, su_duration_t tout);


196
/* *
Martti Mela's avatar
Martti Mela committed
197 198 199 200
 * Port is a per-thread reactor.  
 *
 * Multiple root objects executed by single thread share a su_port_t object. 
 */
201
struct su_port_s {
Martti Mela's avatar
Martti Mela committed
202
  su_home_t        sup_home[1];
203

Martti Mela's avatar
Martti Mela committed
204
  su_port_vtable_t const *sup_vtable;
205 206 207 208
  
  unsigned         sup_running;
  unsigned         sup_source_fired;

Martti Mela's avatar
Martti Mela committed
209 210 211 212

#if SU_HAVE_PTHREADS
  pthread_t        sup_tid;
  pthread_mutex_t  sup_mutex[1];
213 214 215 216
#if __CYGWIN__
  pthread_mutex_t  sup_reflock[1];
  int              sup_ref;
#else
Martti Mela's avatar
Martti Mela committed
217 218
  pthread_rwlock_t sup_ref[1];
#endif
219 220 221
#else
  int              sup_ref;
#endif
Martti Mela's avatar
Martti Mela committed
222

223 224 225 226 227
#if SU_HAVE_MBOX
  su_socket_t      sup_mbox[MBOX_SEND + 1];
  su_wait_t        sup_mbox_wait;
#endif

228 229 230
  CFRunLoopRef        sup_main_loop;
  CFRunLoopSourceRef *sup_sources;
  CFSocketRef        *sup_sockets;
Martti Mela's avatar
Martti Mela committed
231
  
232
  unsigned         sup_multishot; /**< Multishot operation? */
Martti Mela's avatar
Martti Mela committed
233 234 235 236

  unsigned         sup_registers; /** Counter incremented by 
				      su_port_register() or 
				      su_port_unregister()
237 238 239
				   */
  int              sup_n_waits; /**< Active su_wait_t in su_waits */
  int              sup_size_waits; /**< Size of allocate su_waits */
240

241
  int              sup_pri_offset; /**< Offset to prioritized waits */
242

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
#define INDEX_MAX (0x7fffffff)

  /** Indices from index returned by su_root_register() to tables below. 
   *
   * Free elements are negative. Free elements form a list, value of free
   * element is (0 - index of next free element).
   *
   * First element sup_indices[0] points to first free element. 
   */
  int             *sup_indices;

  int             *sup_reverses; /** Reverse index */
  su_wakeup_f     *sup_wait_cbs; 
  su_wakeup_arg_t**sup_wait_args; 
  su_root_t      **sup_wait_roots; 

  su_wait_t       *sup_waits; 

  /* Pre-poll callback */
  su_prepoll_f    *sup_prepoll; 
  su_prepoll_magic_t *sup_pp_magic;
  su_root_t       *sup_pp_root;
Martti Mela's avatar
Martti Mela committed
265 266 267

  /* Timer list */
  su_timer_t      *sup_timers;
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

  /* Message list - this is protected by lock  */
  su_msg_t        *sup_head;
  su_msg_t       **sup_tail;

#if 0
  int              sup_free_index;   /**< Number of first free index */
  int             *sup_indices; /** Indices to registrations */

  int             *sup_reverses; /** Reverse index */
  su_wakeup_f     *sup_wait_cbs; 
  su_wakeup_arg_t**sup_wait_args; 
  su_root_t      **sup_wait_roots; 

  su_wait_t       *sup_waits; 

  /* Pre-poll callback */
  su_prepoll_f    *sup_prepoll; 
  su_prepoll_magic_t *sup_pp_magic;
  su_root_t       *sup_pp_root;

  /* Timer list */
  su_timer_t      *sup_timers;

  /* Message list - this is protected by lock  */
  su_msg_t        *sup_head;
  su_msg_t       **sup_tail;
#endif
Martti Mela's avatar
Martti Mela committed
296 297 298
};


299 300 301 302 303 304
/* Struct for CFSocket callbacks; contains current CFSource index */
typedef struct {
  su_port_t *o_port;
  int        o_current;
  int        o_count;
} osx_magic_t;
Martti Mela's avatar
Martti Mela committed
305 306


307
#if SU_HAVE_PTHREADS
Martti Mela's avatar
Martti Mela committed
308 309
#define SU_PORT_OSX_OWN_THREAD(p)   (pthread_equal((p)->sup_tid, pthread_self()))

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
#if __CYGWIN__

/* Debugging versions */
#define SU_PORT_OSX_INITREF(p)      (pthread_mutex_init((p)->sup_reflock, NULL), printf("initref(%p)\n", (p)))
#define SU_PORT_OSX_INCREF(p, f)    (pthread_mutex_lock(p->sup_reflock), p->sup_ref++, pthread_mutex_unlock(p->sup_reflock), printf("incref(%p) by %s\n", (p), f))
#define SU_PORT_OSX_DECREF(p, f)    do {					\
    pthread_mutex_lock(p->sup_reflock);	p->sup_ref--; pthread_mutex_unlock(p->sup_reflock); \
    if ((p->sup_ref) == 0) {			\
      printf("decref(%p) to 0 by %s\n", (p), f); su_port_osx_destroy(p); }	\
    else { printf("decref(%p) to %u by %s\n", (p), p->sup_ref, f); }  } while(0)

#define SU_PORT_OSX_ZAPREF(p, f)    do { printf("zapref(%p) by %s\n", (p), f), \
    pthread_mutex_lock(p->sup_reflock);	p->sup_ref--; pthread_mutex_unlock(p->sup_reflock); \
  if ((p->sup_ref) != 0) { \
    assert(!"SU_PORT_OSX_ZAPREF"); } \
  su_port_osx_destroy(p); } while(0)

#define SU_PORT_OSX_INITLOCK(p) \
   (pthread_mutex_init((p)->sup_mutex, NULL), printf("init_lock(%p)\n", p))

#define SU_PORT_OSX_LOCK(p, f)    \
   (printf("%ld at %s locking(%p)...", pthread_self(), f, p), pthread_mutex_lock((p)->sup_mutex), printf(" ...%ld at %s locked(%p)...", pthread_self(), f, p))

#define SU_PORT_OSX_UNLOCK(p, f)  \
  (pthread_mutex_unlock((p)->sup_mutex), printf(" ...%ld at %s unlocked(%p)\n", pthread_self(), f, p))

#elif 1
Martti Mela's avatar
Martti Mela committed
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
#define SU_PORT_OSX_INITREF(p)      (pthread_rwlock_init(p->sup_ref, NULL))
#define SU_PORT_OSX_INCREF(p, f)    (pthread_rwlock_rdlock(p->sup_ref))
#define SU_PORT_OSX_DECREF(p, f)    do { pthread_rwlock_unlock(p->sup_ref); \
  if (pthread_rwlock_trywrlock(p->sup_ref) == 0) su_port_osx_destroy(p); } while(0)

#define SU_PORT_OSX_ZAPREF(p, f)    do { pthread_rwlock_unlock(p->sup_ref); \
  if (pthread_rwlock_trywrlock(p->sup_ref) != 0) { \
    assert(!"SU_PORT_OSX_ZAPREF"); pthread_rwlock_wrlock(p->sup_ref); } \
  su_port_osx_destroy(p); } while(0)

#define SU_PORT_OSX_INITLOCK(p)     (pthread_mutex_init((p)->sup_mutex, NULL))
#define SU_PORT_OSX_LOCK(p, f)      (pthread_mutex_lock((p)->sup_mutex))
#define SU_PORT_OSX_UNLOCK(p, f)    (pthread_mutex_unlock((p)->sup_mutex))

#else
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

/* Debugging versions */
#define SU_PORT_OSX_INITREF(p)      (pthread_rwlock_init((p)->sup_ref, NULL), printf("initref(%p)\n", (p)))
#define SU_PORT_OSX_INCREF(p, f)    (pthread_rwlock_rdlock(p->sup_ref), printf("incref(%p) by %s\n", (p), f))
#define SU_PORT_OSX_DECREF(p, f)    do {					\
    pthread_rwlock_unlock(p->sup_ref);					\
    if (pthread_rwlock_trywrlock(p->sup_ref) == 0) {			\
      printf("decref(%p) to 0 by %s\n", (p), f); su_port_osx_destroy(p); }	\
    else { printf("decref(%p) by %s\n", (p), f); }  } while(0)

#define SU_PORT_OSX_ZAPREF(p, f)    do { printf("zapref(%p) by %s\n", (p), f), \
  pthread_rwlock_unlock(p->sup_ref); \
  if (pthread_rwlock_trywrlock(p->sup_ref) != 0) { \
    assert(!"SU_PORT_OSX_ZAPREF"); pthread_rwlock_wrlock(p->sup_ref); } \
  su_port_osx_destroy(p); } while(0)

#define SU_PORT_OSX_INITLOCK(p) \
   (pthread_mutex_init((p)->sup_mutex, NULL), printf("init_lock(%p)\n", p))

#define SU_PORT_OSX_LOCK(p, f)    \
   (printf("%ld at %s locking(%p)...", pthread_self(), f, p), pthread_mutex_lock((p)->sup_mutex), printf(" ...%ld at %s locked(%p)...", pthread_self(), f, p))

#define SU_PORT_OSX_UNLOCK(p, f)  \
  (pthread_mutex_unlock((p)->sup_mutex), printf(" ...%ld at %s unlocked(%p)\n", pthread_self(), f, p))

#endif

#else /* !SU_HAVE_PTHREADS */

#define SU_PORT_OSX_OWN_THREAD(p)  1
#define SU_PORT_OSX_INITLOCK(p)    (void)(p)
#define SU_PORT_OSX_LOCK(p, f)      (void)(p)
#define SU_PORT_OSX_UNLOCK(p, f)    (void)(p)
#define SU_PORT_OSX_ZAPREF(p, f)    ((p)->sup_ref--)

#define SU_PORT_OSX_INITREF(p)      ((p)->sup_ref = 1)
#define SU_PORT_OSX_INCREF(p, f)    ((p)->sup_ref++)
#define SU_PORT_OSX_DECREF(p, f) \
do { if (--((p)->sup_ref) == 0) su_port_osx_destroy(p); } while (0);

Martti Mela's avatar
Martti Mela committed
392 393
#endif

394 395
#if SU_HAVE_MBOX
static int su_port_osx_wakeup(su_root_magic_t *magic, 
396 397
			  su_wait_t *w,
			  su_wakeup_arg_t *arg);
398 399
#endif

Martti Mela's avatar
Martti Mela committed
400 401
static void su_port_osx_destroy(su_port_t *self);

402 403 404 405 406 407 408 409
/** Create a reactor object.
 *
 * Allocate and initialize the instance of su_root_t.
 *
 * @param magic     pointer to user data
 *
 * @return A pointer to allocated su_root_t instance, NULL on error.
 */
Martti Mela's avatar
Martti Mela committed
410 411 412 413 414
su_root_t *su_root_osx_runloop_create(su_root_magic_t *magic)
{
  return su_root_create_with_port(magic, su_osx_runloop_create());
}

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
void osx_enabler_cb(CFSocketRef s, 
		    CFSocketCallBackType type, 
		    CFDataRef address, 
		    const void *data, 
		    void *info)
{
  CFRunLoopRef  rl;
  osx_magic_t  *magic = (osx_magic_t *) info;
  su_port_t    *self = magic->o_port;
  su_duration_t tout = 0;
  su_time_t     now = su_now();
  
  rl = CFRunLoopGetCurrent();

  if (self->sup_running) {
    
    if (self->sup_prepoll)
      self->sup_prepoll(self->sup_pp_magic, self->sup_pp_root);
    
    if (self->sup_head)
      su_port_osx_getmsgs(self);
    
    if (self->sup_timers)
      su_timer_expire(&self->sup_timers, &tout, now);
  }
  
  CFRunLoopWakeUp(rl);
  
}


Martti Mela's avatar
Martti Mela committed
447 448
/**@internal
 *
449 450 451
 * Allocates and initializes a message port. It creates a mailbox used to.
 * wake up the tasks waiting on the port if needed.  Currently, the
 * mailbox is simply an UDP socket connected to itself.
Martti Mela's avatar
Martti Mela committed
452 453 454 455 456 457 458
 *
 * @return
 *   If successful a pointer to the new message port is returned, otherwise
 *   NULL is returned.  
 */
su_port_t *su_osx_runloop_create(void)
{
459
  su_port_t *self;
Martti Mela's avatar
Martti Mela committed
460 461 462

  SU_DEBUG_9(("su_osx_runloop_create() called\n"));

463 464
  self = su_home_clone(NULL, sizeof(*self));

465 466 467 468 469 470
  if (self) {
#if SU_HAVE_MBOX
    int af;
    su_socket_t mb = INVALID_SOCKET;
    char const *why;
#endif
471 472 473 474
    CFRunLoopObserverRef cf_observer; 
    osx_magic_t *osx_magic = NULL;
    CFRunLoopObserverContext cf_observer_cntx[1] = {{0, NULL, NULL,
						     NULL, NULL}};
Martti Mela's avatar
Martti Mela committed
475 476 477

    self->sup_vtable = su_port_osx_vtable;
    
478
    SU_PORT_OSX_INITREF(self);
Martti Mela's avatar
Martti Mela committed
479 480 481
    SU_PORT_OSX_INITLOCK(self);
    self->sup_tail = &self->sup_head;

482
    self->sup_multishot = 0; /* XXX (SU_ENABLE_MULTISHOT_POLL) != 0; */
483

Martti Mela's avatar
Martti Mela committed
484 485 486
#if SU_HAVE_PTHREADS
    self->sup_tid = pthread_self();
#endif
487
  
488 489 490 491 492 493 494 495
#if SU_HAVE_MBOX
#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) {
496
      why = "su_port_osx_init: socketpair"; goto error;
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
    }

    mb = self->sup_mbox[0];
    su_setblocking(self->sup_mbox[0], 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) {
512
	why = "su_port_osx_init: socket"; goto error;
513 514 515 516 517 518 519
      }
  
      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) {
520
	why = "su_port_osx_init: bind"; goto error;
521 522 523
      }

      if (getsockname(mb, sa, &sinsize) == -1) {
524
	why = "su_port_osx_init: getsockname"; goto error;
525 526 527
      }
    
      if (connect(mb, sa, sinsize) == -1) {
528
	why = "su_port_osx_init: connect"; goto error;
529 530 531 532 533
      }
    }
#endif    

    if (su_wait_create(&self->sup_mbox_wait, mb, SU_WAIT_IN) == -1) {
534
      why = "su_port_osx_init: su_wait_create"; goto error;
535 536
    }

537 538 539
    if (su_port_osx_register(self, NULL, &self->sup_mbox_wait,
			     su_port_osx_wakeup, 
			     (su_wakeup_arg_t *)self->sup_mbox, 0)
540
	== -1) {
541
      why = "su_port_osx_create: su_port_osx_register"; goto error;
542 543
    }

544 545 546 547 548 549 550 551 552 553 554 555
    osx_magic = calloc(1, sizeof(*osx_magic));
    osx_magic->o_port = self;
    cf_observer_cntx->info = osx_magic;
    
    cf_observer =
      CFRunLoopObserverCreate(NULL, kCFRunLoopAfterWaiting | kCFRunLoopBeforeWaiting,
			      TRUE, 0, cf_observer_cb, cf_observer_cntx);
    
    CFRunLoopAddObserver(CFRunLoopGetCurrent(),
			 cf_observer,
			 kCFRunLoopDefaultMode);
    
556
    SU_DEBUG_9(("su_port_osx_create() returns %p\n", self));
557
    
Martti Mela's avatar
Martti Mela committed
558
    return self;
559
    
560 561 562 563
  error:
    su_perror(why);
    su_port_osx_destroy(self), self = NULL;
#endif
Martti Mela's avatar
Martti Mela committed
564
  }
565
  
566
  SU_DEBUG_9(("su_port_osx_create() returns %p\n", self));
567
  
568
  return self;
Martti Mela's avatar
Martti Mela committed
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

static
void cf_observer_cb(CFRunLoopObserverRef observer, 
		    CFRunLoopActivity activity, 
		    void *info)
{
  CFRunLoopRef  rl;
  osx_magic_t  *magic = (osx_magic_t *) info;
  su_port_t    *self = magic->o_port;
  su_duration_t tout = 0;
  su_time_t     now = su_now();

  rl = CFRunLoopGetCurrent();

  if (self->sup_running) {

    if (self->sup_prepoll)
      self->sup_prepoll(self->sup_pp_magic, self->sup_pp_root);
    
    if (self->sup_head)
      su_port_osx_getmsgs(self);
    
    if (self->sup_timers)
      su_timer_expire(&self->sup_timers, &tout, now);
  } else
    SU_DEBUG_9(("cf_observer_cb(): PORT IS NOT RUNNING!\n"));

  CFRunLoopWakeUp(rl);
  
  return;
}

Martti Mela's avatar
Martti Mela committed
603 604 605 606 607 608 609 610 611
/** @internal Destroy a port. */
void su_port_osx_destroy(su_port_t *self)
{
  assert(self);

  SU_DEBUG_9(("su_port_osx_destroy() called\n"));

#if SU_HAVE_MBOX
  if (self->sup_mbox[0] != INVALID_SOCKET) {
612
    su_port_osx_unregister(self, NULL, &self->sup_mbox_wait, NULL, 
Martti Mela's avatar
Martti Mela committed
613 614 615 616 617 618 619 620 621
		       (su_wakeup_arg_t *)self->sup_mbox);
    su_wait_destroy(&self->sup_mbox_wait);
    su_close(self->sup_mbox[0]); self->sup_mbox[0] = INVALID_SOCKET;
#if HAVE_SOCKETPAIR
    su_close(self->sup_mbox[1]); self->sup_mbox[1] = INVALID_SOCKET;
#endif
    SU_DEBUG_9(("su_port_osx_destroy() close mailbox\n"));
  }
#endif
622 623
  if (self->sup_sources) 
    free(self->sup_sources), self->sup_sources = NULL;
624 625 626 627
  if (self->sup_sockets) 
    free(self->sup_sockets), self->sup_sockets = NULL;
  if (self->sup_waits) 
    free(self->sup_waits), self->sup_waits = NULL;
Martti Mela's avatar
Martti Mela committed
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
  if (self->sup_wait_cbs)
    free(self->sup_wait_cbs), self->sup_wait_cbs = NULL;
  if (self->sup_wait_args)
    free(self->sup_wait_args), self->sup_wait_args = NULL;
  if (self->sup_wait_roots)
    free(self->sup_wait_roots), self->sup_wait_roots = NULL;
  if (self->sup_reverses)
    free(self->sup_reverses), self->sup_reverses = NULL;
  if (self->sup_indices)
    free(self->sup_indices), self->sup_indices = NULL;

  SU_DEBUG_9(("su_port_osx_destroy() freed registrations\n"));

  su_home_zap(self->sup_home);

  SU_DEBUG_9(("su_port_osx_destroy() returns\n"));

}

static void su_port_osx_lock(su_port_t *self, char const *who)
{
  SU_PORT_OSX_LOCK(self, who);
}

static void su_port_osx_unlock(su_port_t *self, char const *who)
{
  SU_PORT_OSX_UNLOCK(self, who);
}

static void su_port_osx_incref(su_port_t *self, char const *who)
{
  SU_PORT_OSX_INCREF(self, who);
}

static void su_port_osx_decref(su_port_t *self, int blocking, char const *who)
{
664 665 666 667 668 669
  if (blocking)
    SU_PORT_OSX_ZAPREF(self, who);
  else
    SU_PORT_OSX_DECREF(self, who);
}

670 671
static
CFSocketCallBackType map_poll_event_to_cf_event(int events)
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
{
  CFSocketCallBackType type = 0;

  if (events & SU_WAIT_IN)
    type |= kCFSocketReadCallBack;
  
  if (events & SU_WAIT_OUT)
    type |= kCFSocketWriteCallBack;
  
#if 0
  if (events & SU_WAIT_CONNECT)
    type |= kCFSocketConnectCallBack;
  
  if (events & SU_WAIT_ACCEPT)
    type |= kCFSocketAcceptCallBack;
#endif

  return type;
Martti Mela's avatar
Martti Mela committed
690 691
}

692

693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
static
int map_cf_event_to_poll_event(CFSocketCallBackType type)
{
  int event = 0;

  if (type & kCFSocketReadCallBack)
    event |= SU_WAIT_IN;
  
  if (type & kCFSocketWriteCallBack)
    event |= SU_WAIT_OUT;
  
  if (type & kCFSocketConnectCallBack)
    event |= SU_WAIT_CONNECT;
  
  if (type & kCFSocketAcceptCallBack)
    event |= SU_WAIT_ACCEPT;

  return event;
}


714 715 716 717 718 719
static
void su_port_osx_socket_cb(CFSocketRef s, 
			   CFSocketCallBackType type, 
			   CFDataRef address, 
			   const void *data, 
			   void *info)
Martti Mela's avatar
Martti Mela committed
720
{
721 722 723
  osx_magic_t       *magic = (osx_magic_t *) info;
  su_port_t         *self = magic->o_port;
  int                curr = magic->o_current;
724 725
  su_duration_t tout = 0;
  
726 727 728 729 730
#if SU_HAVE_POLL
  {
    su_root_t *root;
    su_wait_t *waits = self->sup_waits;
    int n = self->sup_indices[curr];
731
    
732
    assert(self->sup_reverses[n] == curr);
733 734 735
    
    SU_DEBUG_9(("socket_cb(%p): count %u index %d\n", self->sup_sources[n], magic->o_count, curr));
    
736 737
    waits[n].revents = map_poll_event_to_cf_event(type);

738 739 740 741
    root = self->sup_wait_roots[n];
    self->sup_wait_cbs[n](root ? su_root_magic(root) : NULL, 
			  &waits[n], 
			  self->sup_wait_args[n]);
742
    
743 744
    if (self->sup_running) {
      su_port_osx_getmsgs(self);
745
      
746 747 748
      if (self->sup_timers)
	su_timer_expire(&self->sup_timers, &tout, su_now());

749 750 751
      if (self->sup_head)
	tout = 0;

752
      /* CFRunLoopWakeUp(CFRunLoopGetCurrent()); */
753 754
    }
    
755 756 757 758
    /* Tell to run loop an su socket fired */
    self->sup_source_fired = 1;
  }
#endif
759
  
Martti Mela's avatar
Martti Mela committed
760 761
}

762 763 764 765 766 767 768 769 770 771
#if SU_HAVE_MBOX
/** @internal Message box wakeup function. */
static int su_port_osx_wakeup(su_root_magic_t *magic, /* NULL */
			      su_wait_t *w,
			      su_wakeup_arg_t *arg)
{
  char buf[32];
  su_socket_t s = *(su_socket_t *)arg;
  su_wait_events(w, s);
  recv(s, buf, sizeof(buf), 0);
772

773
  /* CFRunLoopWakeUp(CFRunLoopGetCurrent()); */
774

775 776 777 778
  return 0;
}
#endif

Martti Mela's avatar
Martti Mela committed
779 780 781
/** @internal Send a message to the port. */
int su_port_osx_send(su_port_t *self, su_msg_r rmsg)
{
782 783
  CFRunLoopRef rl;

Martti Mela's avatar
Martti Mela committed
784
  if (self) {
785
    int wakeup;
Martti Mela's avatar
Martti Mela committed
786 787

    SU_PORT_OSX_LOCK(self, "su_port_osx_send");
788 789
    
    wakeup = self->sup_head == NULL;
Martti Mela's avatar
Martti Mela committed
790

791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
    *self->sup_tail = rmsg[0]; rmsg[0] = NULL;
    self->sup_tail = &(*self->sup_tail)->sum_next;

#if SU_HAVE_MBOX
    /* if (!pthread_equal(pthread_self(), self->sup_tid)) */
    if (wakeup)
    {
      assert(self->sup_mbox[MBOX_SEND] != INVALID_SOCKET);

      if (send(self->sup_mbox[MBOX_SEND], "X", 1, 0) == -1) {
#if HAVE_SOCKETPAIR
	if (su_errno() != EWOULDBLOCK)
#endif
	  su_perror("su_msg_send: send()");
      }
    }
#endif
Martti Mela's avatar
Martti Mela committed
808 809 810 811

    SU_PORT_OSX_UNLOCK(self, "su_port_osx_send");

    rl = CFRunLoopGetCurrent();
812
    CFRunLoopWakeUp(rl);
Martti Mela's avatar
Martti Mela committed
813 814 815 816 817 818 819 820 821 822 823 824 825 826

    return 0;
  }
  else {
    su_msg_destroy(rmsg);
    return -1;
  }
}

/** @internal
 * Execute the messages in the incoming queue until the queue is empty..
 *
 * @param self - pointer to a port object
 *
827
 * @retval Number of messages sent
Martti Mela's avatar
Martti Mela committed
828 829 830
 */
int su_port_osx_getmsgs(su_port_t *self)
{
831 832 833
  int n = 0;

  if (self->sup_head) {
Martti Mela's avatar
Martti Mela committed
834
    su_msg_f f;
835
    su_msg_t *msg, *queue;
Martti Mela's avatar
Martti Mela committed
836

837 838 839 840 841 842 843 844 845 846 847
    SU_PORT_OSX_LOCK(self, "su_port_getmsgs");

    queue = self->sup_head;
    self->sup_tail = &self->sup_head;
    self->sup_head = NULL;

    SU_PORT_OSX_UNLOCK(self, "su_port_osx_getmsgs");

    for (msg = queue; msg; msg = queue) {
      queue = msg->sum_next;
      msg->sum_next = NULL;
Martti Mela's avatar
Martti Mela committed
848 849 850

      f = msg->sum_func;
      if (f) 
851 852 853
	f(SU_ROOT_MAGIC(msg->sum_to->sut_root), &msg, msg->sum_data);
      su_msg_delivery_report(&msg);
      n++;
Martti Mela's avatar
Martti Mela committed
854 855
    }

856 857
    /* Check for wait events that may have been generated by messages */
    su_port_osx_wait_events(self, 0);
Martti Mela's avatar
Martti Mela committed
858
  }
859 860

  return n;
Martti Mela's avatar
Martti Mela committed
861 862
}

863 864
static int o_count;

Martti Mela's avatar
Martti Mela committed
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
/** @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_port_osx_register returns nonzero index of the wait object, 
 *   or -1 upon an error.  */
int su_port_osx_register(su_port_t *self,
886 887 888 889 890
			 su_root_t *root, 
			 su_wait_t *wait, 
			 su_wakeup_f callback,
			 su_wakeup_arg_t *arg,
			 int priority)
Martti Mela's avatar
Martti Mela committed
891
{
892
  int i, j, n;
Martti Mela's avatar
Martti Mela committed
893
  CFRunLoopRef rl;
894 895
  CFRunLoopSourceRef *sources, source;
  CFSocketRef cf_socket, *sockets;
896
  int events = 0;
897 898 899
  osx_magic_t *osx_magic = NULL;
  CFSocketContext cf_socket_cntx[1] = {{0, NULL, NULL, NULL, NULL}};
  CFOptionFlags flags = 0;
Martti Mela's avatar
Martti Mela committed
900 901 902 903 904

  assert(SU_PORT_OSX_OWN_THREAD(self));

  n = self->sup_n_waits;

905 906 907
  if (n >= SU_WAIT_MAX)
    return su_seterrno(ENOMEM);

Martti Mela's avatar
Martti Mela committed
908 909 910
  if (n >= self->sup_size_waits) {
    /* Reallocate size arrays */
    int size;
911 912
    int *indices;
    int *reverses;
Martti Mela's avatar
Martti Mela committed
913 914 915 916 917 918
    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)
919
      size = su_root_size_hint;
Martti Mela's avatar
Martti Mela committed
920 921 922
    else 
      size = 2 * self->sup_size_waits;

923 924
    if (size < SU_WAIT_MIN)
      size = SU_WAIT_MIN;
925 926 927 928 929

    /* Too large */
    if (-3 - size > 0)
      return (errno = ENOMEM), -1;

930
    indices = realloc(self->sup_indices, (size + 1) * sizeof(*indices));
Martti Mela's avatar
Martti Mela committed
931 932 933
    if (indices) {
      self->sup_indices = indices;

934 935
      for (i = self->sup_size_waits; i <= size; i++)
	indices[i] = -1 - i;
936
    }
Martti Mela's avatar
Martti Mela committed
937

938 939 940 941 942 943
    reverses = realloc(self->sup_reverses, size * sizeof(*waits));
    if (reverses) {
      for (i = self->sup_size_waits; i < size; i++)
	reverses[i] = -1;
      self->sup_reverses = reverses;
    }
Martti Mela's avatar
Martti Mela committed
944
      
945 946 947 948
    sources = realloc(self->sup_sources, size * sizeof(*sources));
    if (sources)
      self->sup_sources = sources;

949 950 951 952 953 954 955 956
    sockets = realloc(self->sup_sockets, size * sizeof(*sockets));
    if (sockets)
      self->sup_sockets = sockets;

    waits = realloc(self->sup_waits, size * sizeof(*waits));
    if (waits)
      self->sup_waits = waits;

Martti Mela's avatar
Martti Mela committed
957 958 959 960 961 962 963 964 965 966 967 968 969
    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;

970
    if (!(indices && 
971
	  reverses && sources && sockets && waits && wait_cbs && wait_args && wait_tasks)) {
Martti Mela's avatar
Martti Mela committed
972 973 974 975 976 977
      return -1;
    }

    self->sup_size_waits = size;
  }

978
  i = -self->sup_indices[0]; assert(i <= self->sup_size_waits);
979

Martti Mela's avatar
Martti Mela committed
980 981
  if (priority > 0) {
    /* Insert */
982 983 984
    for (n = self->sup_n_waits; n > 0; n--) {
      j = self->sup_reverses[n-1]; assert(self->sup_indices[j] == n - 1);
      self->sup_indices[j] = n;
985 986
      self->sup_reverses[n] = self->sup_reverses[n-1];
      self->sup_sources[n] = self->sup_sources[n-1];
987 988
      self->sup_sockets[n] = self->sup_sockets[n-1];
      self->sup_waits[n] = self->sup_waits[n-1];
Martti Mela's avatar
Martti Mela committed
989 990 991 992
      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];	
    }
993

994
    self->sup_pri_offset++;
Martti Mela's avatar
Martti Mela committed
995 996 997
  }
  else {
    /* Append - no need to move anything */
998
    n = self->sup_n_waits;
Martti Mela's avatar
Martti Mela committed
999 1000
  }

1001 1002 1003 1004
  self->sup_n_waits++;

  self->sup_indices[0] = self->sup_indices[i];  /* Free index */
  self->sup_indices[i] = n;
1005 1006

  self->sup_reverses[n] = i;
Martti Mela's avatar
Martti Mela committed
1007 1008 1009 1010 1011
  self->sup_waits[n] = *wait;
  self->sup_wait_cbs[n] = callback;
  self->sup_wait_args[n] = arg;
  self->sup_wait_roots[n] = root;

1012
  self->sup_registers++;
Martti Mela's avatar
Martti Mela committed
1013

1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
  /* XXX -- mela: leak, leak -- free() somewheeeere */
  osx_magic = calloc(1, sizeof(*osx_magic));
  osx_magic->o_port = self;
  osx_magic->o_current = i;
  osx_magic->o_count = ++o_count;
  cf_socket_cntx->info = osx_magic;

  events = map_poll_event_to_cf_event(wait->events);

  cf_socket = CFSocketCreateWithNative(NULL,
				       (CFSocketNativeHandle) su_wait_socket(wait),
				       events, su_port_osx_socket_cb, cf_socket_cntx);

  flags = CFSocketGetSocketFlags(cf_socket);
  flags &= ~kCFSocketCloseOnInvalidate;

  CFSocketSetSocketFlags(cf_socket, flags);

  CFRetain(cf_socket);
  source = CFSocketCreateRunLoopSource(NULL, cf_socket, 0);

  SU_DEBUG_9(("source(%p): count %u index %d\n", source, o_count, i));

  rl = CFRunLoopGetCurrent();

  CFRunLoopAddSource(rl, source, kCFRunLoopDefaultMode);

  CFRetain(source);
  self->sup_sources[n] = source;
  self->sup_sockets[n] = cf_socket;

  CFRunLoopWakeUp(rl);

  /* Just like epoll, we return -1 or positive integer */

  return i;
1050
}
Martti Mela's avatar
Martti Mela committed
1051

1052 1053
/** Deregister a su_wait_t object. */
static
1054
int su_port_osx_deregister0(su_port_t *self, int i)
1055 1056
{
  CFRunLoopRef rl;
1057
  int n, N, *indices, *reverses;
Martti Mela's avatar
Martti Mela committed
1058

1059 1060 1061
  indices = self->sup_indices;
  reverses = self->sup_reverses;

1062
  n = indices[i]; assert(n >= 0); assert(i == reverses[n]);
1063

1064
  N = --self->sup_n_waits;
1065 1066
  
  rl = CFRunLoopGetCurrent();
1067 1068 1069 1070 1071
  CFSocketInvalidate(self->sup_sockets[n]);
  CFRelease(self->sup_sockets[n]);
  CFRunLoopRemoveSource(rl, self->sup_sources[n], kCFRunLoopDefaultMode);
  CFRelease(self->sup_sources[n]);

1072
  CFRunLoopWakeUp(rl);
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088

  if (n < self->sup_pri_offset) {
    int j = --self->sup_pri_offset;
    if (n != j) {
      assert(reverses[j] > 0);
      assert(indices[reverses[j]] == j);
      indices[reverses[j]] = n;
      reverses[n] = reverses[j];

      self->sup_sources[n] = self->sup_sources[j];
      self->sup_sockets[n] = self->sup_sockets[j];
      self->sup_waits[n] = self->sup_waits[j];
      self->sup_wait_cbs[n] = self->sup_wait_cbs[j];
      self->sup_wait_args[n] = self->sup_wait_args[j];
      self->sup_wait_roots[n] = self->sup_wait_roots[j];
      n = j;
1089 1090 1091
    }
  }

1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
  if (n < N) {
    assert(reverses[N] > 0);
    assert(indices[reverses[N]] == N);

    indices[reverses[N]] = n;
    reverses[n] = reverses[N];

    self->sup_sources[n] = self->sup_sources[N];
    self->sup_sockets[n] = self->sup_sockets[N];
    self->sup_waits[n] = self->sup_waits[N];
    self->sup_wait_cbs[n] = self->sup_wait_cbs[N];
    self->sup_wait_args[n] = self->sup_wait_args[N];
    self->sup_wait_roots[n] = self->sup_wait_roots[N];
    n = N;
  }


  reverses[n] = -1;
  memset(&self->sup_waits[n], 0, sizeof self->sup_waits[n]);
  self->sup_sources[n] = NULL;
  self->sup_sockets[n] = NULL;
  self->sup_wait_cbs[n] = NULL;
  self->sup_wait_args[n] = NULL;
  self->sup_wait_roots[n] = NULL;
  
  indices[i] = indices[0];
  indices[0] = -i;
Martti Mela's avatar
Martti Mela committed
1119 1120 1121

  self->sup_registers++;

1122
  return i;
Martti Mela's avatar
Martti Mela committed
1123 1124
}

1125

Martti Mela's avatar
Martti Mela committed
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
/** Unregister a su_wait_t object.
 *  
 *  The function su_port_osx_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_port_osx_unregister(su_port_t *self,
1142 1143 1144 1145
		       su_root_t *root, 
		       su_wait_t *wait,	
		       su_wakeup_f callback, /* XXX - ignored */
		       su_wakeup_arg_t *arg)
Martti Mela's avatar
Martti Mela committed
1146
{
1147
  int n, N;
Martti Mela's avatar
Martti Mela committed
1148 1149 1150 1151 1152 1153 1154

  assert(self);
  assert(SU_PORT_OSX_OWN_THREAD(self));

  N = self->sup_n_waits;

  for (n = 0; n < N; n++) {
1155
    if (SU_WAIT_CMP(wait[0], self->sup_waits[n]) == 0) {
1156
      return su_port_osx_deregister0(self, self->sup_reverses[n]);
Martti Mela's avatar
Martti Mela committed
1157 1158 1159
    }
  }

1160
  su_seterrno(ENOENT);
Martti Mela's avatar
Martti Mela committed
1161

1162
  return -1;
Martti Mela's avatar
Martti Mela committed
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
}

/** Deregister a su_wait_t object.
 *  
 *  The function su_port_osx_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_port_osx_deregister(su_port_t *self, int i)
{
1178 1179
  su_wait_t wait[1] = { SU_WAIT_INIT };
  int retval;
Martti Mela's avatar
Martti Mela committed
1180 1181 1182 1183

  assert(self);
  assert(SU_PORT_OSX_OWN_THREAD(self));

1184 1185
  if (i <= 0 || i > self->sup_size_waits)
    return su_seterrno(EBADF);
Martti Mela's avatar
Martti Mela committed
1186

1187 1188 1189 1190
  if (self->sup_indices[i] < 0)
    return su_seterrno(EBADF);
    
  retval = su_port_osx_deregister0(self, i);
Martti Mela's avatar
Martti Mela committed
1191 1192 1193

  su_wait_destroy(wait);

1194
  return retval;
Martti Mela's avatar
Martti Mela committed
1195 1196
}

1197

Martti Mela's avatar
Martti Mela committed
1198 1199 1200 1201
/** @internal
 * Unregister all su_wait_t objects.
 *
 * The function su_port_osx_unregister_all() unregisters all su_wait_t objects
1202
 * and destroys all queued timers associated with given root object.
Martti Mela's avatar
Martti Mela committed
1203 1204 1205 1206 1207 1208 1209 1210 1211
 * 
 * @param  self     - pointer to port object
 * @param  root     - pointer to root object
 * 
 * @return Number of wait objects removed.
 */
int su_port_osx_unregister_all(su_port_t *self, 
			   su_root_t *root)
{
1212 1213 1214 1215 1216 1217 1218
  int i, j, index, N;
  int                *indices, *reverses;
  su_wait_t          *waits;
  su_wakeup_f        *wait_cbs;
  su_wakeup_arg_t   **wait_args;
  su_root_t         **wait_roots;
  CFRunLoopRef        rl;
1219
  CFRunLoopSourceRef *sources;
1220
  CFSocketRef        *sockets;
Martti Mela's avatar
Martti Mela committed
1221 1222 1223

  assert(SU_PORT_OSX_OWN_THREAD(self));

1224
  N          = self->sup_n_waits;
1225 1226 1227
  indices    = self->sup_indices;
  reverses   = self->sup_reverses;
  sources    = self->sup_sources; 
1228
  sockets    = self->sup_sockets; 
Martti Mela's avatar
Martti Mela committed
1229 1230 1231 1232 1233
  waits      = self->sup_waits; 
  wait_cbs   = self->sup_wait_cbs; 
  wait_args  = self->sup_wait_args;
  wait_roots = self->sup_wait_roots; 
  
1234 1235 1236 1237 1238
  rl = CFRunLoopGetCurrent();

  for (i = j = 0; i < N; i++) {
    index = reverses[i]; assert(index > 0 && indices[index] == i);

Martti Mela's avatar
Martti Mela committed
1239
    if (wait_roots[i] == root) {
1240 1241 1242 1243 1244
      if (i < self->sup_pri_offset)
	self->sup_pri_offset--;

      indices[index] = indices[0];
      indices[0] = -index;
Martti Mela's avatar
Martti Mela committed
1245 1246
      continue;
    }
1247

1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
    if (i != j) {
      indices[index] = j;

      CFSocketInvalidate(self->sup_sockets[j]);
      CFRelease(self->sup_sockets[j]);
      CFRunLoopRemoveSource(rl, sources[j], kCFRunLoopDefaultMode);
      CFRelease(sources[j]);

      reverses[j]   = reverses[i];
      sources[j]    = sources[i];
      sockets[j]    = sockets[i];
      waits[j]      = waits[i];
      wait_cbs[j]   = wait_cbs[i];
      wait_args[j]  = wait_args[i];
      wait_roots[j] = wait_roots[i];
    }
1264
    
Martti Mela's avatar
Martti Mela committed
1265 1266
    j++;
  }
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287

  /* Prepare for removing CFSources */
  for (i = j; i < N; i++) {
    reverses[i] = -1;

    CFSocketInvalidate(self->sup_sockets[i]);
    CFRelease(self->sup_sockets[i]);
    CFRunLoopRemoveSource(rl, sources[i], kCFRunLoopDefaultMode);
    CFRunLoopSourceInvalidate(sources[i]);

    sources[i] = NULL;
    sockets[i] = NULL;
    wait_cbs[i] = NULL;
    wait_args[i] = NULL;
    wait_roots[i] = NULL;
  }
  memset(&waits[j], 0, (char *)&waits[N] - (char *)&waits[j]);

  /* Tell run loop things have changed */
  CFRunLoopWakeUp(rl);

Martti Mela's avatar
Martti Mela committed
1288 1289 1290
  self->sup_n_waits = j;
  self->sup_registers++;

1291
  return N - j;
Martti Mela's avatar
Martti Mela committed
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
}

/**Set mask for a registered event. @internal
 *
 * The function su_port_osx_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_port_osx_eventmask(su_port_t *self, int index, int socket, int events)
{
1309
  int n, ret;
Martti Mela's avatar
Martti Mela committed
1310 1311 1312 1313

  assert(self);
  assert(SU_PORT_OSX_OWN_THREAD(self));

1314
  if (index <= 0 || index > self->sup_size_waits)
1315 1316
    return su_seterrno(EBADF);
  n = self->sup_indices[index];
1317
  if (n < 0)
1318
    return su_seterrno(EBADF);
Martti Mela's avatar
Martti Mela committed
1319

1320 1321 1322 1323 1324 1325
  ret = su_wait_mask(&self->sup_waits[n], socket, events);

  CFSocketSetSocketFlags(self->sup_sockets[n],
			 map_poll_event_to_cf_event(events));
  
  return ret;
Martti Mela's avatar
Martti Mela committed
1326 1327
}

1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
/** @internal
 *
 *  Copies the su_wait_t objects from the port. The number of wait objects
 *  can be found out by calling su_port_osx_query() with @a n_waits as zero.
 * 
 * @note This function is called only by friends.
 *
 * @param self     - pointer to port object
 * @param waits    - pointer to array to which wait objects are copied
 * @param n_waits  - number of wait objects fitting in array waits
 *
 * @return Number of wait objects, or 0 upon an error.
 */
unsigned su_port_osx_query(su_port_t *self, su_wait_t *waits, unsigned n_waits)
{
  unsigned n;

  assert(SU_PORT_OSX_OWN_THREAD(self));

  n = self->sup_n_waits;

  if (n_waits != 0) {
    if (waits && n_waits >= n)
      memcpy(waits, self->sup_waits, n * sizeof(*waits));
    else
      n = 0;
  }

  return n;
}

/** @internal Enable multishot mode.
 *
 * The function su_port_osx_multishot() 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 disables, 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
 */
Martti Mela's avatar
Martti Mela committed
1374 1375
int su_port_osx_multishot(su_port_t *self, int multishot)
{
1376 1377
  if (multishot < 0)
    return self->sup_multishot;
Martti Mela's avatar
Martti Mela committed
1378
  else if (multishot == 0 || multishot == 1)
1379
    return self->sup_multishot = multishot;
Martti Mela's avatar
Martti Mela committed
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
  else 
    return (errno = EINVAL), -1;
}

/** @internal Enable threadsafe operation. */
static
int su_port_osx_threadsafe(su_port_t *port)
{
  return su_home_threadsafe(port->sup_home);
}

1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
/** Prepare root to be run on OSX Run Loop.
 * The function @c su_root_osx_prepare_run() sets @c su_root_t
 * object to be callable by the application's run loop. This
 * function is to be used instead of @c su_root_run() for OSX
 * applications using Core Foundation's Run Loop.
 * The function @c su_root_osx_prepare_run() returns immmediately.
 * 
 * @param self     pointer to root object
 * 
 */
void su_root_osx_prepare_run(su_root_t *root)
{
  su_port_t *self = root->sur_task->sut_port;
  CFRunLoopRef rl;
  su_duration_t tout = 0;

  assert(SU_PORT_OSX_OWN_THREAD(self));

  enter;

  self->sup_running = 1;
  rl = CFRunLoopGetCurrent();

  if (self->sup_prepoll)
    self->sup_prepoll(self->sup_pp_magic, self->sup_pp_root);

  if (self->sup_head)
    su_port_osx_getmsgs(self);
  
  if (self->sup_timers)
    su_timer_expire(&self->sup_timers, &tout, su_now());

  if (!self->sup_running)
    return;

  CFRetain(rl);
  self->sup_main_loop = rl;

  return;
}

Martti Mela's avatar
Martti Mela committed
1432 1433
/** @internal Main loop.
 * 
1434 1435 1436
 * The function @c su_port_osx_run() waits for wait objects and the timers
 * associated with the port object.  When any wait object is signaled or
 * timer is expired, it invokes the callbacks, and returns waiting.
Martti Mela's avatar
Martti Mela committed
1437 1438 1439 1440
 * 
 * The function @c su_port_osx_run() runs until @c su_port_osx_break() is called
 * from a callback.
 * 
1441 1442 1443
 * @param self     pointer to port object
 * 
 */
Martti Mela's avatar
Martti Mela committed
1444 1445
void su_port_osx_run(su_port_t *self)
{
1446
  CFRunLoopRef rl;
1447 1448 1449
  su_duration_t tout = 0;

  assert(SU_PORT_OSX_OWN_THREAD(self));
Martti Mela's avatar
Martti Mela committed
1450 1451 1452

  enter;

1453
  self->sup_running = 1;
1454
  rl = CFRunLoopGetCurrent();
1455

1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
  if (self->sup_prepoll)
    self->sup_prepoll(self->sup_pp_magic, self->sup_pp_root);

  if (self->sup_head)
    su_port_osx_getmsgs(self);
  
  if (self->sup_timers)
    su_timer_expire(&self->sup_timers, &tout, su_now());

  if (!self->sup_running)
    return;

1468 1469
  CFRetain(rl);
  self->sup_main_loop = rl;
Martti Mela's avatar
Martti Mela committed
1470

1471 1472 1473
  /* if there are messages do a quick wait */
  if (self->sup_head)
    tout = 0;
1474

1475
  CFRunLoopRun();
1476

1477
  self->sup_main_loop = NULL;
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526

}

#if tuning
/* This version can help tuning... */
void su_port_osx_run_tune(su_port_t *self)
{
  int i;
  int timers = 0, messages = 0, events = 0;
  su_duration_t tout = 0, tout0;
  su_time_t started = su_now(), woken = started, bedtime = woken;

  assert(SU_PORT_OSX_OWN_THREAD(self));

  for (self->sup_running = 1; self->sup_running;) {
    tout0 = tout, tout = 2000;

    timers = 0, messages = 0;

    if (self->sup_prepoll)
      self->sup_prepoll(self->sup_pp_magic, self->sup_pp_root);

    if (self->sup_head)
      messages = su_port_osx_getmsgs(self);

    if (self->sup_timers)
      timers = su_timer_expire(&self->sup_timers, &tout, su_now());

    if (!self->sup_running)
      break;

    if (self->sup_head)      /* if there are messages do a quick wait */
      tout = 0;

    bedtime = su_now();

    events = su_port_osx_wait_events(self, tout);

    woken = su_now();

    if (messages || timers || events)
      SU_DEBUG_1(("su_port_osx_run(%p): %.6f: %u messages %u timers %u "
		  "events slept %.6f/%.3f\n",
		  self, su_time_diff(woken, started), messages, timers, events,
		  su_time_diff(woken, bedtime), tout0 * 1e-3));

    if (!self->sup_running)
      break;
  }
Martti Mela's avatar
Martti Mela committed
1527
}
1528
#endif
Martti Mela's avatar
Martti Mela committed
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540

/** @internal
 * The function @c su_port_osx_break() is used to terminate execution of @c
 * su_port_osx_run(). It can be called from a callback function.
 * 
 * @param self     pointer to port
 * 
 */
void su_port_osx_break(su_port_t *self)
{
  if (self->sup_main_loop)
    CFRunLoopStop(self->sup_main_loop);
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611

  self->sup_running = 0; 
}

/** @internal
 * The function @c su_port_osx_wait_events() is used to poll() for wait objects
 *
 * @param self     pointer to port
 * @param tout     timeout in milliseconds
 *
 * @return number of events handled
 */
static
int su_port_osx_wait_events(su_port_t *self, su_duration_t tout)
{
  int i, events = 0;
  su_wait_t *waits = self->sup_waits;
  unsigned n = self->sup_n_waits;
#if HAVE_POLL
  unsigned version = self->sup_registers;
#endif
  su_root_t *root;

  i = su_wait(waits, n, tout);

  if (i >= 0 && (unsigned)i < n) {
#if HAVE_POLL			
    /* poll() can return events for multiple wait objects */
    if (self->sup_multishot) {
      for (; 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]);
          events++;
          /* Callback function used su_register()/su_deregister() */
          if (version != self->sup_registers)
            break;
        }
      }
    }
#else /* !HAVE_POLL */
    if (0) {
    }
#endif
    else {
      root = self->sup_wait_roots[i];
      self->sup_wait_cbs[i](root ? su_root_magic(root) : NULL,
                            &self->sup_waits[i],
                            self->sup_wait_args[i]);
      events++;
    }
  }

  return events;
}

/** @internal 
 * Used to check wait events in callbacks that take lots of time
 *
 * This function does a timeout 0 poll() and runs wait objects.
 *
 * @param port     pointer to port
 *
 * @return number of events handled
 */
static
int su_port_osx_yield(su_port_t *port)
{
  return su_port_osx_wait_events(port, 0);
Martti Mela's avatar
Martti Mela committed
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
}

/** @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
 * 
1626
 * @return
Martti Mela's avatar
Martti Mela committed
1627 1628 1629 1630 1631 1632
 *   Milliseconds to the next invocation of timer, or @c SU_WAIT_FOREVER if
 *   there are no active timers.
 */
su_duration_t su_port_osx_step(su_port_t *self, su_duration_t tout)
{
  CFRunLoopRef rl;
1633 1634
  su_time_t now = su_now();
  CFAbsoluteTime start;
Martti Mela's avatar
Martti Mela committed
1635 1636
  int ret, timeout = tout > INT32_MAX ? INT32_MAX : tout;

1637
  assert(SU_PORT_OSX_OWN_THREAD(self));
Martti Mela's avatar
Martti Mela committed
1638 1639 1640 1641 1642 1643

  rl = CFRunLoopGetCurrent();

  if (!rl)
    return -1;

1644
  CFRunLoopWakeUp(rl);
Martti Mela's avatar
Martti Mela committed
1645 1646 1647 1648

  if (tout < timeout)
    timeout = tout;

1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
  if (self->sup_prepoll)
    self->sup_prepoll(self->sup_pp_magic, self->sup_pp_root);

  if (self->sup_head)
    su_port_osx_getmsgs(self);

  if (self->sup_timers)
    su_timer_expire(&self->sup_timers, &tout, now);

  /* if there are messages do a quick wait */
  if (self->sup_head)
    tout = 0;

Martti Mela's avatar
Martti Mela committed
1662 1663 1664 1665 1666 1667 1668
  start = CFAbsoluteTimeGetCurrent();
  for (;;) {
    /* Run loop with only one pass, indicate if a source was processed */
    ret = CFRunLoopRunInMode(kCFRunLoopDefaultMode,
			     0,
			     TRUE);

1669 1670 1671 1672 1673 1674 1675 1676
    /* Ok, one of our sources was fired */
    if (self->sup_source_fired == 1) {
      self->sup_source_fired = 0;
      break;
    }

    /* Check how long to run this loop */
    if (CFAbsoluteTimeGetCurrent() >= start + timeout / 1000)
Martti Mela's avatar
Martti Mela committed
1677 1678
      break;
  }
1679 1680 1681 1682 1683 1684
  
  if (self->sup_head)
    su_port_osx_getmsgs(self);

  if (self->sup_timers)
    su_timer_expire(&self->sup_timers, &tout, su_now());
Martti Mela's avatar
Martti Mela committed
1685

1686 1687
  if (self->sup_head)
    tout = 0;
Martti Mela's avatar
Martti Mela committed
1688

1689
  return tout;
Martti Mela's avatar
Martti Mela committed
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722
}


/** @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_port_osx_own_thread(su_port_t const *self)
{
  return self == NULL || SU_PORT_OSX_OWN_THREAD(self);
}

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

1723
  fprintf(f, "su_port_osx_t at %p:\n", self);
Martti Mela's avatar
Martti Mela committed
1724
  fprintf(f, "\tport is%s running\n", self->sup_running ? "" : "not ");
1725
#if SU_HAVE_PTHREADS
Martti Mela's avatar
Martti Mela committed
1726
  fprintf(f, "\tport tid %p\n", (void *)self->sup_tid);
1727 1728 1729 1730 1731 1732 1733
#endif
#if SU_HAVE_MBOX
  fprintf(f, "\tport mbox %d (%s%s%s)\n", self->sup_mbox[0],
	  IS_WAIT_IN(&self->sup_mbox_wait),
	  IS_WAIT_OUT(&self->sup_mbox_wait),
	  IS_WAIT_ACCEPT(&self->sup_mbox_wait));
#endif
Martti Mela's avatar
Martti Mela committed
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
  fprintf(f, "\t%d wait objects\n", self->sup_n_waits);
  for (i = 0; i < self->sup_n_waits; i++) {
    
  }
}

#endif

/* =========================================================================
 * Pre-poll() callback
 */

int su_port_osx_add_prepoll(su_port_t *port,
			su_root_t *root, 
			su_prepoll_f *callback, 
			su_prepoll_magic_t *magic)
{
  if (port->sup_prepoll)
    return -1;

  port->sup_prepoll = callback;
  port->sup_pp_magic = magic;
  port->sup_pp_root = root;

  return 0;
}

int su_port_osx_remove_prepoll(su_port_t *port,
			   su_root_t *root)
{
  if (port->sup_pp_root != root)
    return -1;

  port->sup_prepoll = NULL;
  port->sup_pp_magic = NULL;
  port->sup_pp_root = NULL;

  return 0;
}

/* =========================================================================
 * Timers
 */

static
su_timer_t **su_port_osx_timers(su_port_t *self)
{
  return &self->sup_timers;
}
1783