1
/* $Id: timer.c 4359 2013-02-21 11:18:36Z bennylp $ */
3
* The PJLIB's timer heap is based (or more correctly, copied and modied)
4
* from ACE library by Douglas C. Schmidt. ACE is an excellent OO framework
5
* that implements many core patterns for concurrent communication software.
6
* If you're looking for C++ alternative of PJLIB, then ACE is your best
9
* You may use this file according to ACE open source terms or PJLIB open
10
* source terms. You can find the fine ACE library at:
11
* http://www.cs.wustl.edu/~schmidt/ACE.html
13
* ACE is Copyright (C)1993-2006 Douglas C. Schmidt <d.schmidt@vanderbilt.edu>
16
* This program is free software; you can redistribute it and/or modify
17
* it under the terms of the GNU General Public License as published by
18
* the Free Software Foundation; either version 2 of the License, or
19
* (at your option) any later version.
21
* This program is distributed in the hope that it will be useful,
22
* but WITHOUT ANY WARRANTY; without even the implied warranty of
23
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24
* GNU General Public License for more details.
26
* You should have received a copy of the GNU General Public License
27
* along with this program; if not, write to the Free Software
28
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
33
#include <pj/string.h>
34
#include <pj/assert.h>
40
#define THIS_FILE "timer.c"
42
#define HEAP_PARENT(X) (X == 0 ? 0 : (((X) - 1) / 2))
43
#define HEAP_LEFT(X) (((X)+(X))+1)
46
#define DEFAULT_MAX_TIMED_OUT_PER_POLL (64)
50
* The implementation of timer heap.
52
struct pj_timer_heap_t
54
/** Pool from which the timer heap resize will get the storage from */
57
/** Maximum size of the heap. */
60
/** Current size of the heap. */
63
/** Max timed out entries to process per poll. */
64
unsigned max_entries_per_poll;
69
/** Autodelete lock. */
70
pj_bool_t auto_delete_lock;
73
* Current contents of the Heap, which is organized as a "heap" of
74
* pj_timer_entry *'s. In this context, a heap is a "partially
75
* ordered, almost complete" binary tree, which is stored in an
78
pj_timer_entry **heap;
81
* An array of "pointers" that allows each pj_timer_entry in the
82
* <heap_> to be located in O(1) time. Basically, <timer_id_[i]>
83
* contains the slot in the <heap_> array where an pj_timer_entry
84
* with timer id <i> resides. Thus, the timer id passed back from
85
* <schedule_entry> is really an slot into the <timer_ids> array. The
86
* <timer_ids_> array serves two purposes: negative values are
87
* treated as "pointers" for the <freelist_>, whereas positive
88
* values are treated as "pointers" into the <heap_> array.
90
pj_timer_id_t *timer_ids;
93
* "Pointer" to the first element in the freelist contained within
94
* the <timer_ids_> array, which is organized as a stack.
96
pj_timer_id_t timer_ids_freelist;
98
/** Callback to be called when a timer expires. */
99
pj_timer_heap_callback *callback;
105
PJ_INLINE(void) lock_timer_heap( pj_timer_heap_t *ht )
108
pj_lock_acquire(ht->lock);
112
PJ_INLINE(void) unlock_timer_heap( pj_timer_heap_t *ht )
115
pj_lock_release(ht->lock);
120
static void copy_node( pj_timer_heap_t *ht, int slot, pj_timer_entry *moved_node )
124
// Insert <moved_node> into its new location in the heap.
125
ht->heap[slot] = moved_node;
127
// Update the corresponding slot in the parallel <timer_ids_> array.
128
ht->timer_ids[moved_node->_timer_id] = slot;
131
static pj_timer_id_t pop_freelist( pj_timer_heap_t *ht )
133
// We need to truncate this to <int> for backwards compatibility.
134
pj_timer_id_t new_id = ht->timer_ids_freelist;
138
// The freelist values in the <timer_ids_> are negative, so we need
139
// to negate them to get the next freelist "pointer."
140
ht->timer_ids_freelist =
141
-ht->timer_ids[ht->timer_ids_freelist];
147
static void push_freelist (pj_timer_heap_t *ht, pj_timer_id_t old_id)
151
// The freelist values in the <timer_ids_> are negative, so we need
152
// to negate them to get the next freelist "pointer."
153
ht->timer_ids[old_id] = -ht->timer_ids_freelist;
154
ht->timer_ids_freelist = old_id;
158
static void reheap_down(pj_timer_heap_t *ht, pj_timer_entry *moved_node,
159
size_t slot, size_t child)
163
// Restore the heap property after a deletion.
165
while (child < ht->cur_size)
167
// Choose the smaller of the two children.
168
if (child + 1 < ht->cur_size
169
&& PJ_TIME_VAL_LT(ht->heap[child + 1]->_timer_value, ht->heap[child]->_timer_value))
172
// Perform a <copy> if the child has a larger timeout value than
174
if (PJ_TIME_VAL_LT(ht->heap[child]->_timer_value, moved_node->_timer_value))
176
copy_node( ht, slot, ht->heap[child]);
178
child = HEAP_LEFT(child);
181
// We've found our location in the heap.
185
copy_node( ht, slot, moved_node);
188
static void reheap_up( pj_timer_heap_t *ht, pj_timer_entry *moved_node,
189
size_t slot, size_t parent)
191
// Restore the heap property after an insertion.
195
// If the parent node is greater than the <moved_node> we need
197
if (PJ_TIME_VAL_LT(moved_node->_timer_value, ht->heap[parent]->_timer_value))
199
copy_node(ht, slot, ht->heap[parent]);
201
parent = HEAP_PARENT(slot);
207
// Insert the new node into its proper resting place in the heap and
208
// update the corresponding slot in the parallel <timer_ids> array.
209
copy_node(ht, slot, moved_node);
213
static pj_timer_entry * remove_node( pj_timer_heap_t *ht, size_t slot)
215
pj_timer_entry *removed_node = ht->heap[slot];
217
// Return this timer id to the freelist.
218
push_freelist( ht, removed_node->_timer_id );
220
// Decrement the size of the heap by one since we're removing the
225
removed_node->_timer_id = -1;
227
// Only try to reheapify if we're not deleting the last entry.
229
if (slot < ht->cur_size)
232
pj_timer_entry *moved_node = ht->heap[ht->cur_size];
234
// Move the end node to the location being removed and update
235
// the corresponding slot in the parallel <timer_ids> array.
236
copy_node( ht, slot, moved_node);
238
// If the <moved_node->time_value_> is great than or equal its
239
// parent it needs be moved down the heap.
240
parent = HEAP_PARENT (slot);
242
if (PJ_TIME_VAL_GTE(moved_node->_timer_value, ht->heap[parent]->_timer_value))
243
reheap_down( ht, moved_node, slot, HEAP_LEFT(slot));
245
reheap_up( ht, moved_node, slot, parent);
251
static void grow_heap(pj_timer_heap_t *ht)
253
// All the containers will double in size from max_size_
254
size_t new_size = ht->max_size * 2;
255
pj_timer_id_t *new_timer_ids;
258
// First grow the heap itself.
260
pj_timer_entry **new_heap = 0;
262
new_heap = (pj_timer_entry**)
263
pj_pool_alloc(ht->pool, sizeof(pj_timer_entry*) * new_size);
264
memcpy(new_heap, ht->heap, ht->max_size * sizeof(pj_timer_entry*));
265
//delete [] this->heap_;
268
// Grow the array of timer ids.
271
new_timer_ids = (pj_timer_id_t*)
272
pj_pool_alloc(ht->pool, new_size * sizeof(pj_timer_id_t));
274
memcpy( new_timer_ids, ht->timer_ids, ht->max_size * sizeof(pj_timer_id_t));
276
//delete [] timer_ids_;
277
ht->timer_ids = new_timer_ids;
279
// And add the new elements to the end of the "freelist".
280
for (i = ht->max_size; i < new_size; i++)
281
ht->timer_ids[i] = -((pj_timer_id_t) (i + 1));
283
ht->max_size = new_size;
286
static void insert_node(pj_timer_heap_t *ht, pj_timer_entry *new_node)
288
if (ht->cur_size + 2 >= ht->max_size)
291
reheap_up( ht, new_node, ht->cur_size, HEAP_PARENT(ht->cur_size));
296
static pj_status_t schedule_entry( pj_timer_heap_t *ht,
297
pj_timer_entry *entry,
298
const pj_time_val *future_time )
300
if (ht->cur_size < ht->max_size)
302
// Obtain the next unique sequence number.
304
entry->_timer_id = pop_freelist(ht);
305
entry->_timer_value = *future_time;
306
insert_node( ht, entry);
314
static int cancel( pj_timer_heap_t *ht,
315
pj_timer_entry *entry,
318
long timer_node_slot;
322
// Check to see if the timer_id is out of range
323
if (entry->_timer_id < 0 || (pj_size_t)entry->_timer_id > ht->max_size)
326
timer_node_slot = ht->timer_ids[entry->_timer_id];
328
if (timer_node_slot < 0) // Check to see if timer_id is still valid.
331
if (entry != ht->heap[timer_node_slot])
333
pj_assert(entry == ht->heap[timer_node_slot]);
338
remove_node( ht, timer_node_slot);
341
// Call the close hook.
342
(*ht->callback)(ht, entry);
349
* Calculate memory size required to create a timer heap.
351
PJ_DEF(pj_size_t) pj_timer_heap_mem_size(pj_size_t count)
353
return /* size of the timer heap itself: */
354
sizeof(pj_timer_heap_t) +
355
/* size of each entry: */
356
(count+2) * (sizeof(pj_timer_entry*)+sizeof(pj_timer_id_t)) +
357
/* lock, pool etc: */
362
* Create a new timer heap.
364
PJ_DEF(pj_status_t) pj_timer_heap_create( pj_pool_t *pool,
366
pj_timer_heap_t **p_heap)
371
PJ_ASSERT_RETURN(pool && p_heap, PJ_EINVAL);
378
/* Allocate timer heap data structure from the pool */
379
ht = PJ_POOL_ALLOC_T(pool, pj_timer_heap_t);
383
/* Initialize timer heap sizes */
386
ht->max_entries_per_poll = DEFAULT_MAX_TIMED_OUT_PER_POLL;
387
ht->timer_ids_freelist = 1;
392
ht->auto_delete_lock = 0;
394
// Create the heap array.
395
ht->heap = (pj_timer_entry**)
396
pj_pool_alloc(pool, sizeof(pj_timer_entry*) * size);
400
// Create the parallel
401
ht->timer_ids = (pj_timer_id_t *)
402
pj_pool_alloc( pool, sizeof(pj_timer_id_t) * size);
406
// Initialize the "freelist," which uses negative values to
407
// distinguish freelist elements from "pointers" into the <heap_>
409
for (i=0; i<size; ++i)
410
ht->timer_ids[i] = -((pj_timer_id_t) (i + 1));
416
PJ_DEF(void) pj_timer_heap_destroy( pj_timer_heap_t *ht )
418
if (ht->lock && ht->auto_delete_lock) {
419
pj_lock_destroy(ht->lock);
424
PJ_DEF(void) pj_timer_heap_set_lock( pj_timer_heap_t *ht,
428
if (ht->lock && ht->auto_delete_lock)
429
pj_lock_destroy(ht->lock);
432
ht->auto_delete_lock = auto_del;
436
PJ_DEF(unsigned) pj_timer_heap_set_max_timed_out_per_poll(pj_timer_heap_t *ht,
439
unsigned old_count = ht->max_entries_per_poll;
440
ht->max_entries_per_poll = count;
444
PJ_DEF(pj_timer_entry*) pj_timer_entry_init( pj_timer_entry *entry,
447
pj_timer_heap_callback *cb )
449
pj_assert(entry && cb);
451
entry->_timer_id = -1;
453
entry->user_data = user_data;
455
entry->_grp_lock = NULL;
461
static pj_status_t schedule_w_grp_lock_dbg(pj_timer_heap_t *ht,
462
pj_timer_entry *entry,
463
const pj_time_val *delay,
466
pj_grp_lock_t *grp_lock,
467
const char *src_file,
470
static pj_status_t schedule_w_grp_lock(pj_timer_heap_t *ht,
471
pj_timer_entry *entry,
472
const pj_time_val *delay,
475
pj_grp_lock_t *grp_lock)
481
PJ_ASSERT_RETURN(ht && entry && delay, PJ_EINVAL);
482
PJ_ASSERT_RETURN(entry->cb != NULL, PJ_EINVAL);
484
/* Prevent same entry from being scheduled more than once */
485
PJ_ASSERT_RETURN(entry->_timer_id < 1, PJ_EINVALIDOP);
488
entry->src_file = src_file;
489
entry->src_line = src_line;
491
pj_gettickcount(&expires);
492
PJ_TIME_VAL_ADD(expires, *delay);
495
status = schedule_entry(ht, entry, &expires);
496
if (status == PJ_SUCCESS) {
499
entry->_grp_lock = grp_lock;
500
if (entry->_grp_lock) {
501
pj_grp_lock_add_ref(entry->_grp_lock);
504
unlock_timer_heap(ht);
511
PJ_DEF(pj_status_t) pj_timer_heap_schedule_dbg( pj_timer_heap_t *ht,
512
pj_timer_entry *entry,
513
const pj_time_val *delay,
514
const char *src_file,
517
return schedule_w_grp_lock_dbg(ht, entry, delay, PJ_FALSE, 1, NULL,
521
PJ_DEF(pj_status_t) pj_timer_heap_schedule_w_grp_lock_dbg(
523
pj_timer_entry *entry,
524
const pj_time_val *delay,
526
pj_grp_lock_t *grp_lock,
527
const char *src_file,
530
return schedule_w_grp_lock_dbg(ht, entry, delay, PJ_TRUE, id_val,
531
grp_lock, src_file, src_line);
535
PJ_DEF(pj_status_t) pj_timer_heap_schedule( pj_timer_heap_t *ht,
536
pj_timer_entry *entry,
537
const pj_time_val *delay)
539
return schedule_w_grp_lock(ht, entry, delay, PJ_FALSE, 1, NULL);
542
PJ_DEF(pj_status_t) pj_timer_heap_schedule_w_grp_lock(pj_timer_heap_t *ht,
543
pj_timer_entry *entry,
544
const pj_time_val *delay,
546
pj_grp_lock_t *grp_lock)
548
return schedule_w_grp_lock(ht, entry, delay, PJ_TRUE, id_val, grp_lock);
552
static int cancel_timer(pj_timer_heap_t *ht,
553
pj_timer_entry *entry,
559
PJ_ASSERT_RETURN(ht && entry, PJ_EINVAL);
562
count = cancel(ht, entry, 1);
566
if (entry->_grp_lock) {
567
pj_grp_lock_t *grp_lock = entry->_grp_lock;
568
entry->_grp_lock = NULL;
569
pj_grp_lock_dec_ref(grp_lock);
571
unlock_timer_heap(ht);
576
PJ_DEF(int) pj_timer_heap_cancel( pj_timer_heap_t *ht,
577
pj_timer_entry *entry)
579
return cancel_timer(ht, entry, PJ_FALSE, 0);
582
PJ_DEF(int) pj_timer_heap_cancel_if_active(pj_timer_heap_t *ht,
583
pj_timer_entry *entry,
586
return cancel_timer(ht, entry, PJ_TRUE, id_val);
589
PJ_DEF(unsigned) pj_timer_heap_poll( pj_timer_heap_t *ht,
590
pj_time_val *next_delay )
595
PJ_ASSERT_RETURN(ht, 0);
598
if (!ht->cur_size && next_delay) {
599
next_delay->sec = next_delay->msec = PJ_MAXINT32;
600
unlock_timer_heap(ht);
605
pj_gettickcount(&now);
607
while ( ht->cur_size &&
608
PJ_TIME_VAL_LTE(ht->heap[0]->_timer_value, now) &&
609
count < ht->max_entries_per_poll )
611
pj_timer_entry *node = remove_node(ht, 0);
612
pj_grp_lock_t *grp_lock;
616
grp_lock = node->_grp_lock;
617
node->_grp_lock = NULL;
619
unlock_timer_heap(ht);
624
(*node->cb)(ht, node);
627
pj_grp_lock_dec_ref(grp_lock);
631
if (ht->cur_size && next_delay) {
632
*next_delay = ht->heap[0]->_timer_value;
633
PJ_TIME_VAL_SUB(*next_delay, now);
634
if (next_delay->sec < 0 || next_delay->msec < 0)
635
next_delay->sec = next_delay->msec = 0;
636
} else if (next_delay) {
637
next_delay->sec = next_delay->msec = PJ_MAXINT32;
639
unlock_timer_heap(ht);
644
PJ_DEF(pj_size_t) pj_timer_heap_count( pj_timer_heap_t *ht )
646
PJ_ASSERT_RETURN(ht, 0);
651
PJ_DEF(pj_status_t) pj_timer_heap_earliest_time( pj_timer_heap_t * ht,
652
pj_time_val *timeval)
654
pj_assert(ht->cur_size != 0);
655
if (ht->cur_size == 0)
659
*timeval = ht->heap[0]->_timer_value;
660
unlock_timer_heap(ht);
666
PJ_DEF(void) pj_timer_heap_dump(pj_timer_heap_t *ht)
670
PJ_LOG(3,(THIS_FILE, "Dumping timer heap:"));
671
PJ_LOG(3,(THIS_FILE, " Cur size: %d entries, max: %d",
672
(int)ht->cur_size, (int)ht->max_size));
678
PJ_LOG(3,(THIS_FILE, " Entries: "));
679
PJ_LOG(3,(THIS_FILE, " _id\tId\tElapsed\tSource"));
680
PJ_LOG(3,(THIS_FILE, " ----------------------------------"));
682
pj_gettickcount(&now);
684
for (i=0; i<(unsigned)ht->cur_size; ++i) {
685
pj_timer_entry *e = ht->heap[i];
688
if (PJ_TIME_VAL_LTE(e->_timer_value, now))
689
delta.sec = delta.msec = 0;
691
delta = e->_timer_value;
692
PJ_TIME_VAL_SUB(delta, now);
695
PJ_LOG(3,(THIS_FILE, " %d\t%d\t%d.%03d\t%s:%d",
697
(int)delta.sec, (int)delta.msec,
698
e->src_file, e->src_line));
702
unlock_timer_heap(ht);