margo.c 33 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11

/*
 * (C) 2015 The University of Chicago
 * 
 * See COPYRIGHT in top-level directory.
 */

#include <assert.h>
#include <unistd.h>
#include <errno.h>
#include <abt.h>
12 13 14

#include <margo-config.h>
#ifdef HAVE_ABT_SNOOZER
15
#include <abt-snoozer.h>
16
#endif
17
#include <time.h>
Philip Carns's avatar
Philip Carns committed
18
#include <math.h>
19 20

#include "margo.h"
21
#include "margo-timer.h"
Philip Carns's avatar
Philip Carns committed
22
#include "utlist.h"
23
#include "uthash.h"
24

25
#define DEFAULT_MERCURY_PROGRESS_TIMEOUT_UB 100 /* 100 milliseconds */
Shane Snyder's avatar
Shane Snyder committed
26
#define DEFAULT_MERCURY_HANDLE_CACHE_SIZE 32
27

28 29 30 31 32 33 34 35 36 37 38 39 40
struct mplex_key
{
    hg_id_t id;
    uint32_t mplex_id;
};

struct mplex_element
{
    struct mplex_key key;
    ABT_pool pool;
    UT_hash_handle hh;
};

Philip Carns's avatar
Philip Carns committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
struct diag_data
{
    double min;
    double max;
    double cumulative;
    int count;
};

#define __DIAG_UPDATE(__data, __time)\
do {\
    __data.count++; \
    __data.cumulative += (__time); \
    if((__time) > __data.max) __data.max = (__time); \
    if((__time) < __data.min) __data.min = (__time); \
} while(0)

Shane Snyder's avatar
Shane Snyder committed
57 58 59 60 61 62 63
struct margo_handle_cache_el
{
    hg_handle_t handle;
    UT_hash_handle hh; /* in-use hash link */
    struct margo_handle_cache_el *next; /* free list link */
};

64 65
struct margo_instance
{
Shane Snyder's avatar
Shane Snyder committed
66
    /* mercury/argobots state */
67 68
    hg_context_t *hg_context;
    hg_class_t *hg_class;
69 70 71
    ABT_pool handler_pool;
    ABT_pool progress_pool;

72
    /* internal to margo for this particular instance */
73
    int margo_init;
74 75
    ABT_thread hg_progress_tid;
    int hg_progress_shutdown_flag;
76
    ABT_xstream progress_xstream;
77 78 79
    int owns_progress_pool;
    ABT_xstream *rpc_xstreams;
    int num_handler_pool_threads;
80
    unsigned int hg_progress_timeout_ub;
81 82 83

    /* control logic for callers waiting on margo to be finalized */
    int finalize_flag;
84
    int refcount;
85 86 87
    ABT_mutex finalize_mutex;
    ABT_cond finalize_cond;

88 89
    /* hash table to track multiplexed rpcs registered with margo */
    struct mplex_element *mplex_table;
Philip Carns's avatar
Philip Carns committed
90

Shane Snyder's avatar
Shane Snyder committed
91 92 93
    /* linked list of free hg handles and a hash of in-use handles */
    struct margo_handle_cache_el *free_handle_list;
    struct margo_handle_cache_el *used_handle_hash;
94
    ABT_mutex handle_cache_mtx; /* mutex protecting access to above caches */
Shane Snyder's avatar
Shane Snyder committed
95

Philip Carns's avatar
Philip Carns committed
96 97 98 99 100 101 102 103 104 105 106
    /* optional diagnostics data tracking */
    /* NOTE: technically the following fields are subject to races if they
     * are updated from more than one thread at a time.  We will be careful
     * to only update the counters from the progress_fn,
     * which will serialize access.
     */
    int diag_enabled;
    struct diag_data diag_trigger_elapsed;
    struct diag_data diag_progress_elapsed_zero_timeout;
    struct diag_data diag_progress_elapsed_nonzero_timeout;
    struct diag_data diag_progress_timeout_value;
107 108
};

109 110 111 112 113
struct margo_cb_arg
{
    ABT_eventual *eventual;
};

114 115 116 117 118 119
struct margo_rpc_data
{
	margo_instance_id mid;
	void* user_data;
	void (*user_free_callback)(void *);
};
120

121
static void hg_progress_fn(void* foo);
122
static void margo_rpc_data_free(void* ptr);
123

Shane Snyder's avatar
Shane Snyder committed
124 125 126 127 128 129 130
static hg_return_t margo_handle_cache_init(margo_instance_id mid);
static void margo_handle_cache_destroy(margo_instance_id mid);
static hg_return_t margo_handle_cache_get(margo_instance_id mid,
    hg_addr_t addr, hg_id_t id, hg_handle_t *handle);
static hg_return_t margo_handle_cache_put(margo_instance_id mid,
    hg_handle_t handle);

131
margo_instance_id margo_init(const char *addr_str, int mode,
132
    int use_progress_thread, int rpc_thread_count)
133
{
134 135 136 137 138
    ABT_xstream progress_xstream = ABT_XSTREAM_NULL;
    ABT_pool progress_pool = ABT_POOL_NULL;
    ABT_xstream *rpc_xstreams = NULL;
    ABT_xstream rpc_xstream = ABT_XSTREAM_NULL;
    ABT_pool rpc_pool = ABT_POOL_NULL;
139 140
    hg_class_t *hg_class = NULL;
    hg_context_t *hg_context = NULL;
141
    int listen_flag = (mode == MARGO_CLIENT_MODE) ? HG_FALSE : HG_TRUE;
142
    int i;
143 144 145
    int ret;
    struct margo_instance *mid = MARGO_INSTANCE_NULL;

146
    if(mode != MARGO_CLIENT_MODE && mode != MARGO_SERVER_MODE) goto err;
147

148 149 150
    ret = ABT_init(0, NULL); /* XXX: argc/argv not currently used by ABT ... */
    if(ret != 0) goto err;

151
    /* set caller (self) ES to idle without polling */
152
#ifdef HAVE_ABT_SNOOZER
153 154
    ret = ABT_snoozer_xstream_self_set();
    if(ret != 0) goto err;
155
#endif
156 157 158

    if (use_progress_thread)
    {
159
#ifdef HAVE_ABT_SNOOZER
160
        ret = ABT_snoozer_xstream_create(1, &progress_pool, &progress_xstream);
161 162 163 164 165 166 167
		if (ret != ABT_SUCCESS) goto err;
#else
		ret = ABT_xstream_create(ABT_SCHED_NULL, &progress_xstream);
		if (ret != ABT_SUCCESS) goto err;
		ret = ABT_xstream_get_main_pools(progress_xstream, 1, &progress_pool);
		if (ret != ABT_SUCCESS) goto err;
#endif
168 169 170 171 172 173 174 175 176
    }
    else
    {
        ret = ABT_xstream_self(&progress_xstream);
        if (ret != ABT_SUCCESS) goto err;
        ret = ABT_xstream_get_main_pools(progress_xstream, 1, &progress_pool);
        if (ret != ABT_SUCCESS) goto err;
    }

177
    if (rpc_thread_count > 0)
178
    {
179 180
        rpc_xstreams = calloc(rpc_thread_count, sizeof(*rpc_xstreams));
        if (rpc_xstreams == NULL) goto err;
181
#ifdef HAVE_ABT_SNOOZER
182 183 184
        ret = ABT_snoozer_xstream_create(rpc_thread_count, &rpc_pool,
                rpc_xstreams);
        if (ret != ABT_SUCCESS) goto err;
185
#else
186 187 188 189 190
        int j;
        ret = ABT_pool_create_basic(ABT_POOL_FIFO, ABT_POOL_ACCESS_MPMC, ABT_TRUE, &rpc_pool);
        if (ret != ABT_SUCCESS) goto err;
        for(j=0; j<rpc_thread_count; j++) {
            ret = ABT_xstream_create(ABT_SCHED_NULL, rpc_xstreams+j);
191 192
            if (ret != ABT_SUCCESS) goto err;
        }
193 194 195 196 197 198 199 200 201 202 203 204
#endif
    }
    else if (rpc_thread_count == 0)
    {
        ret = ABT_xstream_self(&rpc_xstream);
        if (ret != ABT_SUCCESS) goto err;
        ret = ABT_xstream_get_main_pools(rpc_xstream, 1, &rpc_pool);
        if (ret != ABT_SUCCESS) goto err;
    }
    else
    {
        rpc_pool = progress_pool;
205 206
    }

207 208 209 210 211 212
    hg_class = HG_Init(addr_str, listen_flag);
    if(!hg_class) goto err;

    hg_context = HG_Context_create(hg_class);
    if(!hg_context) goto err;

213 214 215
    mid = margo_init_pool(progress_pool, rpc_pool, hg_context);
    if (mid == MARGO_INSTANCE_NULL) goto err;

216
    mid->margo_init = 1;
217 218 219
    mid->owns_progress_pool = use_progress_thread;
    mid->progress_xstream = progress_xstream;
    mid->num_handler_pool_threads = rpc_thread_count < 0 ? 0 : rpc_thread_count;
220
    mid->rpc_xstreams = rpc_xstreams;
221

222 223 224
    return mid;

err:
225 226 227 228 229 230 231
    if(mid)
    {
        margo_timer_instance_finalize(mid);
        ABT_mutex_free(&mid->finalize_mutex);
        ABT_cond_free(&mid->finalize_cond);
        free(mid);
    }
232 233 234 235 236 237 238 239 240 241 242 243 244 245
    if (use_progress_thread && progress_xstream != ABT_XSTREAM_NULL)
    {
        ABT_xstream_join(progress_xstream);
        ABT_xstream_free(&progress_xstream);
    }
    if (rpc_thread_count > 0 && rpc_xstreams != NULL)
    {
        for (i = 0; i < rpc_thread_count; i++)
        {
            ABT_xstream_join(rpc_xstreams[i]);
            ABT_xstream_free(&rpc_xstreams[i]);
        }
        free(rpc_xstreams);
    }
246 247 248 249 250
    if(hg_context)
        HG_Context_destroy(hg_context);
    if(hg_class)
        HG_Finalize(hg_class);
    ABT_finalize();
251 252 253 254
    return MARGO_INSTANCE_NULL;
}

margo_instance_id margo_init_pool(ABT_pool progress_pool, ABT_pool handler_pool,
255
    hg_context_t *hg_context)
256 257
{
    int ret;
Shane Snyder's avatar
Shane Snyder committed
258
    hg_return_t hret;
259 260 261
    struct margo_instance *mid;

    mid = malloc(sizeof(*mid));
262
    if(!mid) goto err;
263
    memset(mid, 0, sizeof(*mid));
264

265 266 267
    ABT_mutex_create(&mid->finalize_mutex);
    ABT_cond_create(&mid->finalize_cond);

268 269
    mid->progress_pool = progress_pool;
    mid->handler_pool = handler_pool;
270
    mid->hg_class = HG_Context_get_class(hg_context);
271
    mid->hg_context = hg_context;
272
    mid->hg_progress_timeout_ub = DEFAULT_MERCURY_PROGRESS_TIMEOUT_UB;
273
    mid->refcount = 1;
274

275
    ret = margo_timer_instance_init(mid);
276
    if(ret != 0) goto err;
277

Shane Snyder's avatar
Shane Snyder committed
278 279 280 281
    /* initialize the handle cache */
    hret = margo_handle_cache_init(mid);
    if(hret != HG_SUCCESS) goto err;

282
    ret = ABT_thread_create(mid->progress_pool, hg_progress_fn, mid, 
283
        ABT_THREAD_ATTR_NULL, &mid->hg_progress_tid);
284 285
    if(ret != 0) goto err;

286 287
    return mid;

288 289
err:
    if(mid)
290
    {
Shane Snyder's avatar
Shane Snyder committed
291
        margo_handle_cache_destroy(mid);
292 293 294
        margo_timer_instance_finalize(mid);
        ABT_mutex_free(&mid->finalize_mutex);
        ABT_cond_free(&mid->finalize_cond);
295
        free(mid);
296
    }
297
    return MARGO_INSTANCE_NULL;
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
static void margo_cleanup(margo_instance_id mid)
{
    int i;

    margo_timer_instance_finalize(mid);

    ABT_mutex_free(&mid->finalize_mutex);
    ABT_cond_free(&mid->finalize_cond);

    if (mid->owns_progress_pool)
    {
        ABT_xstream_join(mid->progress_xstream);
        ABT_xstream_free(&mid->progress_xstream);
    }

    if (mid->num_handler_pool_threads > 0)
    {
        for (i = 0; i < mid->num_handler_pool_threads; i++)
        {
            ABT_xstream_join(mid->rpc_xstreams[i]);
            ABT_xstream_free(&mid->rpc_xstreams[i]);
        }
        free(mid->rpc_xstreams);
    }

Shane Snyder's avatar
Shane Snyder committed
325 326
    margo_handle_cache_destroy(mid);

327 328 329 330 331 332 333 334 335
    if (mid->margo_init)
    {
        if (mid->hg_context)
            HG_Context_destroy(mid->hg_context);
        if (mid->hg_class)
            HG_Finalize(mid->hg_class);
        ABT_finalize();
    }

336 337 338
    free(mid);
}

339
void margo_finalize(margo_instance_id mid)
340
{
341
    int do_cleanup;
342

343
    /* tell progress thread to wrap things up */
344
    mid->hg_progress_shutdown_flag = 1;
345 346

    /* wait for it to shutdown cleanly */
347 348
    ABT_thread_join(mid->hg_progress_tid);
    ABT_thread_free(&mid->hg_progress_tid);
349

350 351 352 353
    ABT_mutex_lock(mid->finalize_mutex);
    mid->finalize_flag = 1;
    ABT_cond_broadcast(mid->finalize_cond);

354 355
    mid->refcount--;
    do_cleanup = mid->refcount == 0;
356

357 358 359 360 361 362 363
    ABT_mutex_unlock(mid->finalize_mutex);

    /* if there was noone waiting on the finalize at the time of the finalize
     * broadcast, then we're safe to clean up. Otherwise, let the finalizer do
     * it */
    if (do_cleanup)
        margo_cleanup(mid);
364 365 366 367 368 369

    return;
}

void margo_wait_for_finalize(margo_instance_id mid)
{
370
    int do_cleanup;
371 372 373

    ABT_mutex_lock(mid->finalize_mutex);

374
        mid->refcount++;
375 376 377 378
            
        while(!mid->finalize_flag)
            ABT_cond_wait(mid->finalize_cond, mid->finalize_mutex);

379 380 381
        mid->refcount--;
        do_cleanup = mid->refcount == 0;

382
    ABT_mutex_unlock(mid->finalize_mutex);
383 384 385 386

    if (do_cleanup)
        margo_cleanup(mid);

387 388 389
    return;
}

390 391
hg_id_t margo_register_name(margo_instance_id mid, const char *func_name,
    hg_proc_cb_t in_proc_cb, hg_proc_cb_t out_proc_cb, hg_rpc_cb_t rpc_cb)
392
{
393 394 395
	struct margo_rpc_data* margo_data;
    hg_return_t hret;
    hg_id_t id;
396

397 398 399
    id = HG_Register_name(mid->hg_class, func_name, in_proc_cb, out_proc_cb, rpc_cb);
    if(id <= 0)
        return(0);
400

401 402 403 404 405 406 407 408 409 410 411 412
	/* register the margo data with the RPC */
    margo_data = (struct margo_rpc_data*)HG_Registered_data(mid->hg_class, id);
    if(!margo_data)
    {
        margo_data = (struct margo_rpc_data*)malloc(sizeof(struct margo_rpc_data));
        if(!margo_data)
            return(0);
        margo_data->mid = mid;
        margo_data->user_data = NULL;
        margo_data->user_free_callback = NULL;
        hret = HG_Register_data(mid->hg_class, id, margo_data, margo_rpc_data_free);
        if(hret != HG_SUCCESS)
413
        {
414 415
            free(margo_data);
            return(0);
416
        }
417 418
    }

419
	return(id);
420 421
}

422 423 424
hg_id_t margo_register_name_mplex(margo_instance_id mid, const char *func_name,
    hg_proc_cb_t in_proc_cb, hg_proc_cb_t out_proc_cb, hg_rpc_cb_t rpc_cb,
    uint32_t mplex_id, ABT_pool pool)
425
{
426 427 428
    struct mplex_key key;
    struct mplex_element *element;
    hg_id_t id;
429

430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
    id = margo_register_name(mid, func_name, in_proc_cb, out_proc_cb, rpc_cb);
    if(id <= 0)
        return(0);

    /* nothing to do, we'll let the handler pool take this directly */
    if(mplex_id == MARGO_DEFAULT_MPLEX_ID)
        return(id);

    memset(&key, 0, sizeof(key));
    key.id = id;
    key.mplex_id = mplex_id;

    HASH_FIND(hh, mid->mplex_table, &key, sizeof(key), element);
    if(element)
        return(id);

    element = malloc(sizeof(*element));
    if(!element)
        return(0);
    element->key = key;
    element->pool = pool;

    HASH_ADD(hh, mid->mplex_table, key, sizeof(key), element);

    return(id);
455 456
}

457 458
hg_return_t margo_registered_name(margo_instance_id mid, const char *func_name,
    hg_id_t *id, hg_bool_t *flag)
459
{
460
    return(HG_Registered_name(mid->hg_class, func_name, id, flag));
461 462
}

463 464 465 466 467 468 469
hg_return_t margo_register_data(
    margo_instance_id mid,
    hg_id_t id,
    void *data,
    void (*free_callback)(void *)) 
{
	struct margo_rpc_data* margo_data 
470
		= (struct margo_rpc_data*) HG_Registered_data(mid->hg_class, id);
471 472 473 474 475 476 477 478 479 480 481 482 483 484
	if(!margo_data) return HG_OTHER_ERROR;
	margo_data->user_data = data;
	margo_data->user_free_callback = free_callback;
	return HG_SUCCESS;
}

void* margo_registered_data(margo_instance_id mid, hg_id_t id)
{
	struct margo_rpc_data* data
		= (struct margo_rpc_data*) HG_Registered_data(margo_get_class(mid), id);
	if(!data) return NULL;
	else return data->user_data;
}

485 486 487 488
hg_return_t margo_registered_disable_response(
    margo_instance_id mid,
    hg_id_t id,
    int disable_flag)
489
{
490
    return(HG_Registered_disable_response(mid->hg_class, id, disable_flag));
491
}
492

493
struct lookup_cb_evt
494
{
495
    hg_return_t hret;
496 497 498 499 500 501
    hg_addr_t addr;
};

static hg_return_t margo_addr_lookup_cb(const struct hg_cb_info *info)
{
    struct lookup_cb_evt evt;
502
    evt.hret = info->ret;
503
    evt.addr = info->info.lookup.addr;
504
    struct margo_cb_arg* arg = info->arg;
505 506

    /* propagate return code out through eventual */
507 508
    ABT_eventual_set(*(arg->eventual), &evt, sizeof(evt));

509 510 511
    return(HG_SUCCESS);
}

512 513 514 515
hg_return_t margo_addr_lookup(
    margo_instance_id mid,
    const char   *name,
    hg_addr_t    *addr)
516
{
517
    hg_return_t hret;
518 519 520 521
    struct lookup_cb_evt *evt;
    ABT_eventual eventual;
    int ret;
    struct margo_cb_arg arg;
522

523 524 525 526 527 528 529
    ret = ABT_eventual_create(sizeof(*evt), &eventual);
    if(ret != 0)
    {
        return(HG_NOMEM_ERROR);        
    }

    arg.eventual = &eventual;
530

531
    hret = HG_Addr_lookup(mid->hg_context, margo_addr_lookup_cb,
532
        &arg, name, HG_OP_ID_IGNORE);
533
    if(hret == HG_SUCCESS)
534 535 536
    {
        ABT_eventual_wait(eventual, (void**)&evt);
        *addr = evt->addr;
537
        hret = evt->hret;
538 539 540 541
    }

    ABT_eventual_free(&eventual);

542
    return(hret);
543 544 545 546 547
}

hg_return_t margo_addr_free(
    margo_instance_id mid,
    hg_addr_t addr)
548
{
549 550
    return(HG_Addr_free(mid->hg_class, addr));
}
551

552 553 554 555 556
hg_return_t margo_addr_self(
    margo_instance_id mid,
    hg_addr_t *addr)
{
    return(HG_Addr_self(mid->hg_class, addr));
557 558
}

559 560 561 562 563 564 565 566 567
hg_return_t margo_addr_dup(
    margo_instance_id mid,
    hg_addr_t addr,
    hg_addr_t *new_addr)
{
    return(HG_Addr_dup(mid->hg_class, addr, new_addr));
}

hg_return_t margo_addr_to_string(
568
    margo_instance_id mid,
569 570 571 572 573 574 575 576 577 578
    char *buf,
    hg_size_t *buf_size,
    hg_addr_t addr)
{
    return(HG_Addr_to_string(mid->hg_class, buf, buf_size, addr));
}

hg_return_t margo_create(margo_instance_id mid, hg_addr_t addr,
    hg_id_t id, hg_handle_t *handle)
{
579
    hg_return_t hret = HG_OTHER_ERROR;
Shane Snyder's avatar
Shane Snyder committed
580 581 582 583 584 585 586 587

    /* look for a handle to reuse */
    hret = margo_handle_cache_get(mid, addr, id, handle);
    if(hret != HG_SUCCESS)
    {
        /* else try creating a new handle */
        hret = HG_Create(mid->hg_context, addr, id, handle);
    }
588

Shane Snyder's avatar
Shane Snyder committed
589
    return hret;
590 591
}

592
hg_return_t margo_destroy(hg_handle_t handle)
593
{
594
    margo_instance_id mid;
595
    hg_return_t hret = HG_OTHER_ERROR;
Shane Snyder's avatar
Shane Snyder committed
596

597 598 599
    /* use the handle to get the associated mid */
    mid = margo_hg_handle_get_instance(handle);

Shane Snyder's avatar
Shane Snyder committed
600 601 602 603 604 605 606
    /* recycle this handle if it came from the handle cache */
    hret = margo_handle_cache_put(mid, handle);
    if(hret != HG_SUCCESS)
    {
        /* else destroy the handle manually */
        hret = HG_Destroy(handle);
    }
607

Shane Snyder's avatar
Shane Snyder committed
608
    return hret;
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
}

static hg_return_t margo_cb(const struct hg_cb_info *info)
{
    hg_return_t hret = info->ret;
    struct margo_cb_arg* arg = info->arg;

    /* propagate return code out through eventual */
    ABT_eventual_set(*(arg->eventual), &hret, sizeof(hret));
    
    return(HG_SUCCESS);
}

hg_return_t margo_forward(
    hg_handle_t handle,
    void *in_struct)
{
    hg_return_t hret = HG_TIMEOUT;
627
    ABT_eventual eventual;
628
    int ret;
629
    hg_return_t* waited_hret;
630
    struct margo_cb_arg arg;
631 632 633 634 635 636 637

    ret = ABT_eventual_create(sizeof(hret), &eventual);
    if(ret != 0)
    {
        return(HG_NOMEM_ERROR);        
    }

638
    arg.eventual = &eventual;
639

640
    hret = HG_Forward(handle, margo_cb, &arg, in_struct);
641
    if(hret == HG_SUCCESS)
642 643 644 645 646 647 648 649
    {
        ABT_eventual_wait(eventual, (void**)&waited_hret);
        hret = *waited_hret;
    }

    ABT_eventual_free(&eventual);

    return(hret);
650 651
}

652 653 654 655
typedef struct
{
    hg_handle_t handle;
} margo_forward_timeout_cb_dat;
656

657 658 659 660 661 662 663 664 665 666 667
static void margo_forward_timeout_cb(void *arg)
{
    margo_forward_timeout_cb_dat *timeout_cb_dat =
        (margo_forward_timeout_cb_dat *)arg;

    /* cancel the Mercury op if the forward timed out */
    HG_Cancel(timeout_cb_dat->handle);
    return;
}

hg_return_t margo_forward_timed(
668
    hg_handle_t handle,
669 670
    void *in_struct,
    double timeout_ms)
671 672
{
    int ret;
673
    hg_return_t hret;
674
    margo_instance_id mid;
675
    ABT_eventual eventual;
676
    hg_return_t* waited_hret;
677 678
    margo_timer_t forward_timer;
    margo_forward_timeout_cb_dat timeout_cb_dat;
679
    struct margo_cb_arg arg;
680 681 682 683 684 685 686

    ret = ABT_eventual_create(sizeof(hret), &eventual);
    if(ret != 0)
    {
        return(HG_NOMEM_ERROR);        
    }

687 688 689
    /* use the handle to get the associated mid */
    mid = margo_hg_handle_get_instance(handle);

690 691 692 693 694
    /* set a timer object to expire when this forward times out */
    timeout_cb_dat.handle = handle;
    margo_timer_init(mid, &forward_timer, margo_forward_timeout_cb,
        &timeout_cb_dat, timeout_ms);

695
    arg.eventual = &eventual;
696

697
    hret = HG_Forward(handle, margo_cb, &arg, in_struct);
698
    if(hret == HG_SUCCESS)
Jonathan Jenkins's avatar
Jonathan Jenkins committed
699 700 701 702 703
    {
        ABT_eventual_wait(eventual, (void**)&waited_hret);
        hret = *waited_hret;
    }

704 705 706 707 708 709 710 711
    /* convert HG_CANCELED to HG_TIMEOUT to indicate op timed out */
    if(hret == HG_CANCELED)
        hret = HG_TIMEOUT;

    /* remove timer if it is still in place (i.e., not timed out) */
    if(hret != HG_TIMEOUT)
        margo_timer_destroy(mid, &forward_timer);

Jonathan Jenkins's avatar
Jonathan Jenkins committed
712 713 714 715 716 717 718 719 720 721 722 723 724
    ABT_eventual_free(&eventual);

    return(hret);
}

hg_return_t margo_respond(
    hg_handle_t handle,
    void *out_struct)
{
    hg_return_t hret = HG_TIMEOUT;
    ABT_eventual eventual;
    int ret;
    hg_return_t* waited_hret;
725
    struct margo_cb_arg arg;
Jonathan Jenkins's avatar
Jonathan Jenkins committed
726 727 728 729 730 731 732

    ret = ABT_eventual_create(sizeof(hret), &eventual);
    if(ret != 0)
    {
        return(HG_NOMEM_ERROR);
    }

733
    arg.eventual = &eventual;
734

735
    hret = HG_Respond(handle, margo_cb, &arg, out_struct);
736
    if(hret == HG_SUCCESS)
737 738 739 740 741 742 743 744 745 746
    {
        ABT_eventual_wait(eventual, (void**)&waited_hret);
        hret = *waited_hret;
    }

    ABT_eventual_free(&eventual);

    return(hret);
}

747 748 749 750 751 752 753
hg_return_t margo_bulk_create(
    margo_instance_id mid,
    hg_uint32_t count,
    void **buf_ptrs,
    const hg_size_t *buf_sizes,
    hg_uint8_t flags,
    hg_bulk_t *handle)
754
{
755 756 757
    return(HG_Bulk_create(mid->hg_class, count,
        buf_ptrs, buf_sizes, flags, handle));
}
758

759 760 761 762
hg_return_t margo_bulk_free(
    hg_bulk_t handle)
{
    return(HG_Bulk_free(handle));
763 764
}

765 766 767 768 769 770 771 772
hg_return_t margo_bulk_deserialize(
    margo_instance_id mid,
    hg_bulk_t *handle,
    const void *buf,
    hg_size_t buf_size)
{
    return(HG_Bulk_deserialize(mid->hg_class, handle, buf, buf_size));
}
773

774
/* TODO: currently identical to a vanilla margo_cb -- consider reusing that */
775 776 777 778
static hg_return_t margo_bulk_transfer_cb(const struct hg_cb_info *info)
{
    hg_return_t hret = info->ret;
    struct margo_cb_arg* arg = info->arg;
779

780

781 782 783 784
    /* propagate return code out through eventual */
    ABT_eventual_set(*(arg->eventual), &hret, sizeof(hret));
    
    return(HG_SUCCESS);
785 786
}

787
hg_return_t margo_bulk_transfer(
788
    margo_instance_id mid,
789
    hg_bulk_op_t op,
790
    hg_addr_t origin_addr,
791 792 793 794
    hg_bulk_t origin_handle,
    size_t origin_offset,
    hg_bulk_t local_handle,
    size_t local_offset,
795
    size_t size)
796 797 798 799 800
{
    hg_return_t hret = HG_TIMEOUT;
    hg_return_t *waited_hret;
    ABT_eventual eventual;
    int ret;
801
    struct margo_cb_arg arg;
802 803 804 805 806 807 808

    ret = ABT_eventual_create(sizeof(hret), &eventual);
    if(ret != 0)
    {
        return(HG_NOMEM_ERROR);        
    }

809
    arg.eventual = &eventual;
810

811
    hret = HG_Bulk_transfer(mid->hg_context, margo_bulk_transfer_cb,
812
        &arg, op, origin_addr, origin_handle, origin_offset, local_handle,
813
        local_offset, size, HG_OP_ID_IGNORE);
814
    if(hret == HG_SUCCESS)
815 816 817 818 819 820 821 822 823 824
    {
        ABT_eventual_wait(eventual, (void**)&waited_hret);
        hret = *waited_hret;
    }

    ABT_eventual_free(&eventual);

    return(hret);
}

825 826 827 828
typedef struct
{
    ABT_mutex mutex;
    ABT_cond cond;
829
    char is_asleep;
830 831 832 833 834 835 836 837 838
} margo_thread_sleep_cb_dat;

static void margo_thread_sleep_cb(void *arg)
{
    margo_thread_sleep_cb_dat *sleep_cb_dat =
        (margo_thread_sleep_cb_dat *)arg;

    /* wake up the sleeping thread */
    ABT_mutex_lock(sleep_cb_dat->mutex);
839
    sleep_cb_dat->is_asleep = 0;
840 841 842 843 844 845 846
    ABT_cond_signal(sleep_cb_dat->cond);
    ABT_mutex_unlock(sleep_cb_dat->mutex);

    return;
}

void margo_thread_sleep(
847
    margo_instance_id mid,
848 849 850 851 852 853 854 855
    double timeout_ms)
{
    margo_timer_t sleep_timer;
    margo_thread_sleep_cb_dat sleep_cb_dat;

    /* set data needed for sleep callback */
    ABT_mutex_create(&(sleep_cb_dat.mutex));
    ABT_cond_create(&(sleep_cb_dat.cond));
856
    sleep_cb_dat.is_asleep = 1;
857 858

    /* initialize the sleep timer */
859
    margo_timer_init(mid, &sleep_timer, margo_thread_sleep_cb,
860 861 862 863
        &sleep_cb_dat, timeout_ms);

    /* yield thread for specified timeout */
    ABT_mutex_lock(sleep_cb_dat.mutex);
864 865
    while(sleep_cb_dat.is_asleep)
        ABT_cond_wait(sleep_cb_dat.cond, sleep_cb_dat.mutex);
866 867
    ABT_mutex_unlock(sleep_cb_dat.mutex);

868 869 870 871
    /* clean up */
    ABT_mutex_free(&sleep_cb_dat.mutex);
    ABT_cond_free(&sleep_cb_dat.cond);

872 873 874
    return;
}

875
ABT_pool* margo_get_handler_pool(margo_instance_id mid)
876
{
877 878
    return(&mid->handler_pool);
}
879

880 881 882 883
hg_context_t* margo_get_context(margo_instance_id mid)
{
    return(mid->hg_context);
}
884

885 886 887
hg_class_t* margo_get_class(margo_instance_id mid)
{
    return(mid->hg_class);
888
}
Philip Carns's avatar
Philip Carns committed
889

890
margo_instance_id margo_hg_handle_get_instance(hg_handle_t h)
891
{
892 893
	const struct hg_info* info = HG_Get_info(h);
	if(!info) return MARGO_INSTANCE_NULL;
894 895 896 897 898
    return margo_hg_info_get_instance(info);
}

margo_instance_id margo_hg_info_get_instance(const struct hg_info *info)
{
899 900 901 902
	struct margo_rpc_data* data = 
		(struct margo_rpc_data*) HG_Registered_data(info->hg_class, info->id);
	if(!data) return MARGO_INSTANCE_NULL;
	return data->mid;
903 904
}

905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
int margo_lookup_mplex(margo_instance_id mid, hg_id_t id, uint32_t mplex_id, ABT_pool *pool)
{
    struct mplex_key key;
    struct mplex_element *element;

    if(!mplex_id)
    {
        *pool = mid->handler_pool;
        return(0);
    }

    memset(&key, 0, sizeof(key));
    key.id = id;
    key.mplex_id = mplex_id;

    HASH_FIND(hh, mid->mplex_table, &key, sizeof(key), element);
    if(!element)
        return(-1);

Philip Carns's avatar
Philip Carns committed
924 925
    assert(element->key.id == id && element->key.mplex_id == mplex_id);

926 927 928 929 930
    *pool = element->pool;

    return(0);
}

931
static void margo_rpc_data_free(void* ptr)
Philip Carns's avatar
Philip Carns committed
932
{
933 934 935 936 937 938
	struct margo_rpc_data* data = (struct margo_rpc_data*) ptr;
	if(data->user_data && data->user_free_callback) {
		data->user_free_callback(data->user_data);
	}
	free(ptr);
}
939

940 941 942 943 944 945 946
/* dedicated thread function to drive Mercury progress */
static void hg_progress_fn(void* foo)
{
    int ret;
    unsigned int actual_count;
    struct margo_instance *mid = (struct margo_instance *)foo;
    size_t size;
947
    unsigned int hg_progress_timeout = mid->hg_progress_timeout_ub;
948 949
    double next_timer_exp;
    int trigger_happened;
950 951
    double tm1, tm2;
    int diag_enabled = 0;
952

953 954 955 956
    while(!mid->hg_progress_shutdown_flag)
    {
        trigger_happened = 0;
        do {
957 958 959 960
            /* save value of instance diag variable, in case it is modified
             * while we are in loop 
             */
            diag_enabled = mid->diag_enabled;
961

962
            if(diag_enabled) tm1 = ABT_get_wtime();
963
            ret = HG_Trigger(mid->hg_context, 0, 1, &actual_count);
964 965 966 967 968
            if(diag_enabled)
            {
                tm2 = ABT_get_wtime();
                __DIAG_UPDATE(mid->diag_trigger_elapsed, (tm2-tm1));
            }
969

970 971 972
            if(ret == HG_SUCCESS && actual_count > 0)
                trigger_happened = 1;
        } while((ret == HG_SUCCESS) && actual_count && !mid->hg_progress_shutdown_flag);
973

974 975
        if(trigger_happened)
            ABT_thread_yield();
976

977
        ABT_pool_get_size(mid->progress_pool, &size);
978
        /* Are there any other threads executing in this pool that are *not*
979 980 981 982
         * blocked ?  If so then, we can't sleep here or else those threads 
         * will not get a chance to execute.
         * TODO: check is ABT_pool_get_size returns the number of ULT/tasks
         * that can be executed including this one, or not including this one.
983
         */
984
        if(size > 0)
985 986 987 988 989 990 991 992
        {
            /* TODO: this is being executed more than is necessary (i.e.
             * in cases where there are other legitimate ULTs eligible
             * for execution that are not blocking on any events, Margo
             * or otherwise). Maybe we need an abt scheduling tweak here
             * to make sure that this ULT is the lowest priority in that
             * scenario.
             */
993
            if(diag_enabled) tm1 = ABT_get_wtime();
994
            ret = HG_Progress(mid->hg_context, 0);
995 996 997 998 999 1000
            if(diag_enabled)
            {
                tm2 = ABT_get_wtime();
                __DIAG_UPDATE(mid->diag_progress_elapsed_zero_timeout, (tm2-tm1));
                __DIAG_UPDATE(mid->diag_progress_timeout_value, 0);
            }
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
            if(ret == HG_SUCCESS)
            {
                /* Mercury completed something; loop around to trigger
                 * callbacks 
                 */
            }
            else if(ret == HG_TIMEOUT)
            {
                /* No completion; yield here to allow other ULTs to run */
                ABT_thread_yield();
            }
            else
            {
                /* TODO: error handling */
                fprintf(stderr, "WARNING: unexpected return code (%d) from HG_Progress()\n", ret);
            }
        }
        else
        {
1020
            hg_progress_timeout = mid->hg_progress_timeout_ub;
1021 1022 1023 1024 1025 1026 1027 1028 1029
            ret = margo_timer_get_next_expiration(mid, &next_timer_exp);
            if(ret == 0)
            {
                /* there is a queued timer, don't block long enough
                 * to keep this timer waiting
                 */
                if(next_timer_exp >= 0.0)
                {
                    next_timer_exp *= 1000; /* convert to milliseconds */
1030
                    if(next_timer_exp < mid->hg_progress_timeout_ub)
1031 1032 1033 1034 1035 1036 1037
                        hg_progress_timeout = (unsigned int)next_timer_exp;
                }
                else
                {
                    hg_progress_timeout = 0;
                }
            }
1038
            if(diag_enabled) tm1 = ABT_get_wtime();
1039
            ret = HG_Progress(mid->hg_context, hg_progress_timeout);
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
            if(diag_enabled)
            {
                tm2 = ABT_get_wtime();
                if(hg_progress_timeout == 0)
                    __DIAG_UPDATE(mid->diag_progress_elapsed_zero_timeout, (tm2-tm1));
                else
                    __DIAG_UPDATE(mid->diag_progress_elapsed_nonzero_timeout, (tm2-tm1));
                    
                __DIAG_UPDATE(mid->diag_progress_timeout_value, hg_progress_timeout);
            }
1050 1051 1052 1053 1054 1055
            if(ret != HG_SUCCESS && ret != HG_TIMEOUT)
            {
                /* TODO: error handling */
                fprintf(stderr, "WARNING: unexpected return code (%d) from HG_Progress()\n", ret);
            }
        }
1056

1057 1058 1059
        /* check for any expired timers */
        margo_check_timers(mid);
    }
1060

1061
    return;
Philip Carns's avatar
Philip Carns committed
1062
}
Philip Carns's avatar
Philip Carns committed
1063 1064 1065 1066 1067 1068 1069


void margo_diag_start(margo_instance_id mid)
{
    mid->diag_enabled = 1;
}

1070
static void print_diag_data(FILE *file, const char* name, const char *description, struct diag_data *data)
Philip Carns's avatar
Philip Carns committed
1071
{
1072 1073 1074 1075 1076 1077 1078 1079
    double avg;

    fprintf(file, "# %s\n", description);
    if(data->count != 0)
        avg = data->cumulative/data->count;
    else
        avg = 0;
    fprintf(file, "%s\t%.9f\t%.9f\t%.9f\t%d\n", name, avg, data->min, data->max, data->count);
Philip Carns's avatar
Philip Carns committed
1080 1081 1082
    return;
}

1083
void margo_diag_dump(margo_instance_id mid, const char* file, int uniquify)
Philip Carns's avatar
Philip Carns committed
1084 1085 1086
{
    FILE *outfile;
    time_t ltime;
1087
    char revised_file_name[256] = {0};
Philip Carns's avatar
Philip Carns committed
1088 1089 1090

    assert(mid->diag_enabled);

1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
    if(uniquify)
    {
        char hostname[128] = {0};
        int pid;

        gethostname(hostname, 128);
        pid = getpid();

        sprintf(revised_file_name, "%s-%s-%d", file, hostname, pid);
    }
    else
    {
        sprintf(revised_file_name, "%s", file);
    }

Philip Carns's avatar
Philip Carns committed
1106 1107 1108 1109 1110 1111
    if(strcmp("-", file) == 0)
    {
        outfile = stdout;
    }
    else
    {
1112
        outfile = fopen(revised_file_name, "a");
Philip Carns's avatar
Philip Carns committed
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
        if(!outfile)
        {
            perror("fopen");
            return;
        }
    }

    /* TODO: retrieve self addr and include in output */
    /* TODO: support pattern substitution in file name to create unique
     * output files per process
     */

    time(&ltime);
    fprintf(outfile, "# Margo diagnostics\n");
    fprintf(outfile, "# %s\n", ctime(&ltime));
    fprintf(outfile, "# <stat>\t<avg>\t<min>\t<max>\t<count>\n");
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
    print_diag_data(outfile, "trigger_elapsed", 
        "Time consumed by HG_Trigger()", 
        &mid->diag_trigger_elapsed);
    print_diag_data(outfile, "progress_elapsed_zero_timeout", 
        "Time consumed by HG_Progress() when called with timeout==0", 
        &mid->diag_progress_elapsed_zero_timeout);
    print_diag_data(outfile, "progress_elapsed_nonzero_timeout", 
        "Time consumed by HG_Progress() when called with timeout!=0", 
        &mid->diag_progress_elapsed_nonzero_timeout);
    print_diag_data(outfile, "progress_timeout_value", 
        "Timeout values passed to HG_Progress()", 
        &mid->diag_progress_timeout_value);
Philip Carns's avatar
Philip Carns committed
1141 1142 1143 1144 1145 1146

    if(outfile != stdout)
        fclose(outfile);
    
    return;
}
1147

1148
void margo_set_param(margo_instance_id mid, int option, const void *param)
1149 1150 1151
{
    switch(option)
    {
1152
        case MARGO_PARAM_PROGRESS_TIMEOUT_UB:
1153 1154 1155 1156 1157 1158 1159
            mid->hg_progress_timeout_ub = (*((const unsigned int*)param));
            break;
    }

    return;
}

1160
void margo_get_param(margo_instance_id mid, int option, void *param)
1161 1162 1163 1164
{

    switch(option)
    {
1165
        case MARGO_PARAM_PROGRESS_TIMEOUT_UB:
1166 1167 1168 1169 1170 1171
            (*((unsigned int*)param)) = mid->hg_progress_timeout_ub;
            break;
    }

    return;
}
Shane Snyder's avatar
Shane Snyder committed
1172 1173 1174 1175 1176 1177

static hg_return_t margo_handle_cache_init(margo_instance_id mid)
{
    int i;
    struct margo_handle_cache_el *el;
    hg_return_t hret = HG_SUCCESS;
1178

1179
    ABT_mutex_create(&(mid->handle_cache_mtx));
Shane Snyder's avatar
Shane Snyder committed
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218

    for(i = 0; i < DEFAULT_MERCURY_HANDLE_CACHE_SIZE; i++)
    {
        el = malloc(sizeof(*el));
        if(!el)
        {
            hret = HG_NOMEM_ERROR;
            margo_handle_cache_destroy(mid);
            break;
        }

        /* create handle with NULL_ADDRs, we will reset later to valid addrs */
        hret = HG_Create(mid->hg_context, HG_ADDR_NULL, 0, &el->handle);
        if(hret != HG_SUCCESS)
        {
            free(el);
            margo_handle_cache_destroy(mid);
            break;
        }

        /* add to the free list */
        LL_PREPEND(mid->free_handle_list, el);
    }

    return hret;
}

static void margo_handle_cache_destroy(margo_instance_id mid)
{
    struct margo_handle_cache_el *el, *tmp;

    /* only free handle list elements -- handles in hash are still in use */
    LL_FOREACH_SAFE(mid->free_handle_list, el, tmp)
    {
        LL_DELETE(mid->free_handle_list, el);
        HG_Destroy(el->handle);
        free(el);
    }

1219
    ABT_mutex_free(&mid->handle_cache_mtx);
1220

Shane Snyder's avatar
Shane Snyder committed
1221 1222 1223 1224 1225 1226 1227
    return;
}

static hg_return_t margo_handle_cache_get(margo_instance_id mid,
    hg_addr_t addr, hg_id_t id, hg_handle_t *handle)
{
    struct margo_handle_cache_el *el;
1228 1229 1230
    hg_return_t hret = HG_SUCCESS;

    ABT_mutex_lock(mid->handle_cache_mtx);
Shane Snyder's avatar
Shane Snyder committed
1231 1232 1233 1234

    if(!mid->free_handle_list)
    {
        /* if no available handles, just fall through */
1235 1236
        hret = HG_OTHER_ERROR;
        goto finish;
Shane Snyder's avatar
Shane Snyder committed
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
    }

    /* pop first element from the free handle list */
    el = mid->free_handle_list;
    LL_DELETE(mid->free_handle_list, el);

    /* reset handle */
    hret = HG_Reset(el->handle, addr, id);
    if(hret == HG_SUCCESS)
    {
        /* put on in-use list and pass back handle */
        HASH_ADD(hh, mid->used_handle_hash, handle, sizeof(hg_handle_t), el);
        *handle = el->handle;
    }
1251 1252 1253 1254 1255
    else
    {
        /* reset failed, add handle back to the free list */
        LL_APPEND(mid->free_handle_list, el);
    }
Shane Snyder's avatar
Shane Snyder committed
1256

1257 1258
finish:
    ABT_mutex_unlock(mid->handle_cache_mtx);
Shane Snyder's avatar
Shane Snyder committed
1259 1260 1261 1262 1263 1264 1265
    return hret;
}

static hg_return_t margo_handle_cache_put(margo_instance_id mid,
    hg_handle_t handle)
{
    struct margo_handle_cache_el *el;
1266 1267 1268
    hg_return_t hret = HG_SUCCESS;

    ABT_mutex_lock(mid->handle_cache_mtx);
Shane Snyder's avatar
Shane Snyder committed
1269 1270 1271 1272 1273 1274

    /* look for handle in the in-use hash */
    HASH_FIND(hh, mid->used_handle_hash, &handle, sizeof(hg_handle_t), el);
    if(!el)
    {
        /* this handle was manually allocated -- just fall through */
1275 1276
        hret = HG_OTHER_ERROR;
        goto finish;
Shane Snyder's avatar
Shane Snyder committed
1277 1278 1279 1280 1281 1282 1283 1284
    }

    /* remove from the in-use hash */
    HASH_DELETE(hh, mid->used_handle_hash, el);

    /* add to the tail of the free handle list */
    LL_APPEND(mid->free_handle_list, el);

1285 1286 1287
finish:
    ABT_mutex_unlock(mid->handle_cache_mtx);
    return hret;
Shane Snyder's avatar
Shane Snyder committed
1288
}