1
/* $Id: timer.c 4567 2013-07-19 06:31:28Z 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)
57
* The implementation of timer heap.
59
struct pj_timer_heap_t
61
/** Pool from which the timer heap resize will get the storage from */
64
/** Maximum size of the heap. */
67
/** Current size of the heap. */
70
/** Max timed out entries to process per poll. */
71
unsigned max_entries_per_poll;
76
/** Autodelete lock. */
77
pj_bool_t auto_delete_lock;
80
* Current contents of the Heap, which is organized as a "heap" of
81
* pj_timer_entry *'s. In this context, a heap is a "partially
82
* ordered, almost complete" binary tree, which is stored in an
85
pj_timer_entry **heap;
88
* An array of "pointers" that allows each pj_timer_entry in the
89
* <heap_> to be located in O(1) time. Basically, <timer_id_[i]>
90
* contains the slot in the <heap_> array where an pj_timer_entry
91
* with timer id <i> resides. Thus, the timer id passed back from
92
* <schedule_entry> is really an slot into the <timer_ids> array. The
93
* <timer_ids_> array serves two purposes: negative values are
94
* treated as "pointers" for the <freelist_>, whereas positive
95
* values are treated as "pointers" into the <heap_> array.
97
pj_timer_id_t *timer_ids;
100
* "Pointer" to the first element in the freelist contained within
101
* the <timer_ids_> array, which is organized as a stack.
103
pj_timer_id_t timer_ids_freelist;
105
/** Callback to be called when a timer expires. */
106
pj_timer_heap_callback *callback;
112
PJ_INLINE(void) lock_timer_heap( pj_timer_heap_t *ht )
115
pj_lock_acquire(ht->lock);
119
PJ_INLINE(void) unlock_timer_heap( pj_timer_heap_t *ht )
122
pj_lock_release(ht->lock);
127
static void copy_node( pj_timer_heap_t *ht, pj_size_t slot,
128
pj_timer_entry *moved_node )
132
// Insert <moved_node> into its new location in the heap.
133
ht->heap[slot] = moved_node;
135
// Update the corresponding slot in the parallel <timer_ids_> array.
136
ht->timer_ids[moved_node->_timer_id] = (int)slot;
139
static pj_timer_id_t pop_freelist( pj_timer_heap_t *ht )
141
// We need to truncate this to <int> for backwards compatibility.
142
pj_timer_id_t new_id = ht->timer_ids_freelist;
146
// The freelist values in the <timer_ids_> are negative, so we need
147
// to negate them to get the next freelist "pointer."
148
ht->timer_ids_freelist =
149
-ht->timer_ids[ht->timer_ids_freelist];
155
static void push_freelist (pj_timer_heap_t *ht, pj_timer_id_t old_id)
159
// The freelist values in the <timer_ids_> are negative, so we need
160
// to negate them to get the next freelist "pointer."
161
ht->timer_ids[old_id] = -ht->timer_ids_freelist;
162
ht->timer_ids_freelist = old_id;
166
static void reheap_down(pj_timer_heap_t *ht, pj_timer_entry *moved_node,
167
size_t slot, size_t child)
171
// Restore the heap property after a deletion.
173
while (child < ht->cur_size)
175
// Choose the smaller of the two children.
176
if (child + 1 < ht->cur_size
177
&& PJ_TIME_VAL_LT(ht->heap[child + 1]->_timer_value, ht->heap[child]->_timer_value))
180
// Perform a <copy> if the child has a larger timeout value than
182
if (PJ_TIME_VAL_LT(ht->heap[child]->_timer_value, moved_node->_timer_value))
184
copy_node( ht, slot, ht->heap[child]);
186
child = HEAP_LEFT(child);
189
// We've found our location in the heap.
193
copy_node( ht, slot, moved_node);
196
static void reheap_up( pj_timer_heap_t *ht, pj_timer_entry *moved_node,
197
size_t slot, size_t parent)
199
// Restore the heap property after an insertion.
203
// If the parent node is greater than the <moved_node> we need
205
if (PJ_TIME_VAL_LT(moved_node->_timer_value, ht->heap[parent]->_timer_value))
207
copy_node(ht, slot, ht->heap[parent]);
209
parent = HEAP_PARENT(slot);
215
// Insert the new node into its proper resting place in the heap and
216
// update the corresponding slot in the parallel <timer_ids> array.
217
copy_node(ht, slot, moved_node);
221
static pj_timer_entry * remove_node( pj_timer_heap_t *ht, size_t slot)
223
pj_timer_entry *removed_node = ht->heap[slot];
225
// Return this timer id to the freelist.
226
push_freelist( ht, removed_node->_timer_id );
228
// Decrement the size of the heap by one since we're removing the
233
removed_node->_timer_id = -1;
235
// Only try to reheapify if we're not deleting the last entry.
237
if (slot < ht->cur_size)
240
pj_timer_entry *moved_node = ht->heap[ht->cur_size];
242
// Move the end node to the location being removed and update
243
// the corresponding slot in the parallel <timer_ids> array.
244
copy_node( ht, slot, moved_node);
246
// If the <moved_node->time_value_> is great than or equal its
247
// parent it needs be moved down the heap.
248
parent = HEAP_PARENT (slot);
250
if (PJ_TIME_VAL_GTE(moved_node->_timer_value, ht->heap[parent]->_timer_value))
251
reheap_down( ht, moved_node, slot, HEAP_LEFT(slot));
253
reheap_up( ht, moved_node, slot, parent);
259
static void grow_heap(pj_timer_heap_t *ht)
261
// All the containers will double in size from max_size_
262
size_t new_size = ht->max_size * 2;
263
pj_timer_id_t *new_timer_ids;
266
// First grow the heap itself.
268
pj_timer_entry **new_heap = 0;
270
new_heap = (pj_timer_entry**)
271
pj_pool_alloc(ht->pool, sizeof(pj_timer_entry*) * new_size);
272
memcpy(new_heap, ht->heap, ht->max_size * sizeof(pj_timer_entry*));
273
//delete [] this->heap_;
276
// Grow the array of timer ids.
279
new_timer_ids = (pj_timer_id_t*)
280
pj_pool_alloc(ht->pool, new_size * sizeof(pj_timer_id_t));
282
memcpy( new_timer_ids, ht->timer_ids, ht->max_size * sizeof(pj_timer_id_t));
284
//delete [] timer_ids_;
285
ht->timer_ids = new_timer_ids;
287
// And add the new elements to the end of the "freelist".
288
for (i = ht->max_size; i < new_size; i++)
289
ht->timer_ids[i] = -((pj_timer_id_t) (i + 1));
291
ht->max_size = new_size;
294
static void insert_node(pj_timer_heap_t *ht, pj_timer_entry *new_node)
296
if (ht->cur_size + 2 >= ht->max_size)
299
reheap_up( ht, new_node, ht->cur_size, HEAP_PARENT(ht->cur_size));
304
static pj_status_t schedule_entry( pj_timer_heap_t *ht,
305
pj_timer_entry *entry,
306
const pj_time_val *future_time )
308
if (ht->cur_size < ht->max_size)
310
// Obtain the next unique sequence number.
312
entry->_timer_id = pop_freelist(ht);
313
entry->_timer_value = *future_time;
314
insert_node( ht, entry);
322
static int cancel( pj_timer_heap_t *ht,
323
pj_timer_entry *entry,
326
long timer_node_slot;
330
// Check to see if the timer_id is out of range
331
if (entry->_timer_id < 0 || (pj_size_t)entry->_timer_id > ht->max_size)
334
timer_node_slot = ht->timer_ids[entry->_timer_id];
336
if (timer_node_slot < 0) // Check to see if timer_id is still valid.
339
if (entry != ht->heap[timer_node_slot])
341
if ((flags & F_DONT_ASSERT) == 0)
342
pj_assert(entry == ht->heap[timer_node_slot]);
347
remove_node( ht, timer_node_slot);
349
if ((flags & F_DONT_CALL) == 0)
350
// Call the close hook.
351
(*ht->callback)(ht, entry);
358
* Calculate memory size required to create a timer heap.
360
PJ_DEF(pj_size_t) pj_timer_heap_mem_size(pj_size_t count)
362
return /* size of the timer heap itself: */
363
sizeof(pj_timer_heap_t) +
364
/* size of each entry: */
365
(count+2) * (sizeof(pj_timer_entry*)+sizeof(pj_timer_id_t)) +
366
/* lock, pool etc: */
371
* Create a new timer heap.
373
PJ_DEF(pj_status_t) pj_timer_heap_create( pj_pool_t *pool,
375
pj_timer_heap_t **p_heap)
380
PJ_ASSERT_RETURN(pool && p_heap, PJ_EINVAL);
387
/* Allocate timer heap data structure from the pool */
388
ht = PJ_POOL_ALLOC_T(pool, pj_timer_heap_t);
392
/* Initialize timer heap sizes */
395
ht->max_entries_per_poll = DEFAULT_MAX_TIMED_OUT_PER_POLL;
396
ht->timer_ids_freelist = 1;
401
ht->auto_delete_lock = 0;
403
// Create the heap array.
404
ht->heap = (pj_timer_entry**)
405
pj_pool_alloc(pool, sizeof(pj_timer_entry*) * size);
409
// Create the parallel
410
ht->timer_ids = (pj_timer_id_t *)
411
pj_pool_alloc( pool, sizeof(pj_timer_id_t) * size);
415
// Initialize the "freelist," which uses negative values to
416
// distinguish freelist elements from "pointers" into the <heap_>
418
for (i=0; i<size; ++i)
419
ht->timer_ids[i] = -((pj_timer_id_t) (i + 1));
425
PJ_DEF(void) pj_timer_heap_destroy( pj_timer_heap_t *ht )
427
if (ht->lock && ht->auto_delete_lock) {
428
pj_lock_destroy(ht->lock);
433
PJ_DEF(void) pj_timer_heap_set_lock( pj_timer_heap_t *ht,
437
if (ht->lock && ht->auto_delete_lock)
438
pj_lock_destroy(ht->lock);
441
ht->auto_delete_lock = auto_del;
445
PJ_DEF(unsigned) pj_timer_heap_set_max_timed_out_per_poll(pj_timer_heap_t *ht,
448
unsigned old_count = ht->max_entries_per_poll;
449
ht->max_entries_per_poll = count;
453
PJ_DEF(pj_timer_entry*) pj_timer_entry_init( pj_timer_entry *entry,
456
pj_timer_heap_callback *cb )
458
pj_assert(entry && cb);
460
entry->_timer_id = -1;
462
entry->user_data = user_data;
464
entry->_grp_lock = NULL;
469
PJ_DEF(pj_bool_t) pj_timer_entry_running( pj_timer_entry *entry )
471
return (entry->_timer_id >= 1);
475
static pj_status_t schedule_w_grp_lock_dbg(pj_timer_heap_t *ht,
476
pj_timer_entry *entry,
477
const pj_time_val *delay,
480
pj_grp_lock_t *grp_lock,
481
const char *src_file,
484
static pj_status_t schedule_w_grp_lock(pj_timer_heap_t *ht,
485
pj_timer_entry *entry,
486
const pj_time_val *delay,
489
pj_grp_lock_t *grp_lock)
495
PJ_ASSERT_RETURN(ht && entry && delay, PJ_EINVAL);
496
PJ_ASSERT_RETURN(entry->cb != NULL, PJ_EINVAL);
498
/* Prevent same entry from being scheduled more than once */
499
PJ_ASSERT_RETURN(entry->_timer_id < 1, PJ_EINVALIDOP);
502
entry->src_file = src_file;
503
entry->src_line = src_line;
505
pj_gettickcount(&expires);
506
PJ_TIME_VAL_ADD(expires, *delay);
509
status = schedule_entry(ht, entry, &expires);
510
if (status == PJ_SUCCESS) {
513
entry->_grp_lock = grp_lock;
514
if (entry->_grp_lock) {
515
pj_grp_lock_add_ref(entry->_grp_lock);
518
unlock_timer_heap(ht);
525
PJ_DEF(pj_status_t) pj_timer_heap_schedule_dbg( pj_timer_heap_t *ht,
526
pj_timer_entry *entry,
527
const pj_time_val *delay,
528
const char *src_file,
531
return schedule_w_grp_lock_dbg(ht, entry, delay, PJ_FALSE, 1, NULL,
535
PJ_DEF(pj_status_t) pj_timer_heap_schedule_w_grp_lock_dbg(
537
pj_timer_entry *entry,
538
const pj_time_val *delay,
540
pj_grp_lock_t *grp_lock,
541
const char *src_file,
544
return schedule_w_grp_lock_dbg(ht, entry, delay, PJ_TRUE, id_val,
545
grp_lock, src_file, src_line);
549
PJ_DEF(pj_status_t) pj_timer_heap_schedule( pj_timer_heap_t *ht,
550
pj_timer_entry *entry,
551
const pj_time_val *delay)
553
return schedule_w_grp_lock(ht, entry, delay, PJ_FALSE, 1, NULL);
556
PJ_DEF(pj_status_t) pj_timer_heap_schedule_w_grp_lock(pj_timer_heap_t *ht,
557
pj_timer_entry *entry,
558
const pj_time_val *delay,
560
pj_grp_lock_t *grp_lock)
562
return schedule_w_grp_lock(ht, entry, delay, PJ_TRUE, id_val, grp_lock);
566
static int cancel_timer(pj_timer_heap_t *ht,
567
pj_timer_entry *entry,
573
PJ_ASSERT_RETURN(ht && entry, PJ_EINVAL);
576
count = cancel(ht, entry, flags | F_DONT_CALL);
577
if (flags & F_SET_ID) {
580
if (entry->_grp_lock) {
581
pj_grp_lock_t *grp_lock = entry->_grp_lock;
582
entry->_grp_lock = NULL;
583
pj_grp_lock_dec_ref(grp_lock);
585
unlock_timer_heap(ht);
590
PJ_DEF(int) pj_timer_heap_cancel( pj_timer_heap_t *ht,
591
pj_timer_entry *entry)
593
return cancel_timer(ht, entry, 0, 0);
596
PJ_DEF(int) pj_timer_heap_cancel_if_active(pj_timer_heap_t *ht,
597
pj_timer_entry *entry,
600
return cancel_timer(ht, entry, F_SET_ID | F_DONT_ASSERT, id_val);
603
PJ_DEF(unsigned) pj_timer_heap_poll( pj_timer_heap_t *ht,
604
pj_time_val *next_delay )
609
PJ_ASSERT_RETURN(ht, 0);
612
if (!ht->cur_size && next_delay) {
613
next_delay->sec = next_delay->msec = PJ_MAXINT32;
614
unlock_timer_heap(ht);
619
pj_gettickcount(&now);
621
while ( ht->cur_size &&
622
PJ_TIME_VAL_LTE(ht->heap[0]->_timer_value, now) &&
623
count < ht->max_entries_per_poll )
625
pj_timer_entry *node = remove_node(ht, 0);
626
pj_grp_lock_t *grp_lock;
630
grp_lock = node->_grp_lock;
631
node->_grp_lock = NULL;
633
unlock_timer_heap(ht);
638
(*node->cb)(ht, node);
641
pj_grp_lock_dec_ref(grp_lock);
645
if (ht->cur_size && next_delay) {
646
*next_delay = ht->heap[0]->_timer_value;
647
PJ_TIME_VAL_SUB(*next_delay, now);
648
if (next_delay->sec < 0 || next_delay->msec < 0)
649
next_delay->sec = next_delay->msec = 0;
650
} else if (next_delay) {
651
next_delay->sec = next_delay->msec = PJ_MAXINT32;
653
unlock_timer_heap(ht);
658
PJ_DEF(pj_size_t) pj_timer_heap_count( pj_timer_heap_t *ht )
660
PJ_ASSERT_RETURN(ht, 0);
665
PJ_DEF(pj_status_t) pj_timer_heap_earliest_time( pj_timer_heap_t * ht,
666
pj_time_val *timeval)
668
pj_assert(ht->cur_size != 0);
669
if (ht->cur_size == 0)
673
*timeval = ht->heap[0]->_timer_value;
674
unlock_timer_heap(ht);
680
PJ_DEF(void) pj_timer_heap_dump(pj_timer_heap_t *ht)
684
PJ_LOG(3,(THIS_FILE, "Dumping timer heap:"));
685
PJ_LOG(3,(THIS_FILE, " Cur size: %d entries, max: %d",
686
(int)ht->cur_size, (int)ht->max_size));
692
PJ_LOG(3,(THIS_FILE, " Entries: "));
693
PJ_LOG(3,(THIS_FILE, " _id\tId\tElapsed\tSource"));
694
PJ_LOG(3,(THIS_FILE, " ----------------------------------"));
696
pj_gettickcount(&now);
698
for (i=0; i<(unsigned)ht->cur_size; ++i) {
699
pj_timer_entry *e = ht->heap[i];
702
if (PJ_TIME_VAL_LTE(e->_timer_value, now))
703
delta.sec = delta.msec = 0;
705
delta = e->_timer_value;
706
PJ_TIME_VAL_SUB(delta, now);
709
PJ_LOG(3,(THIS_FILE, " %d\t%d\t%d.%03d\t%s:%d",
711
(int)delta.sec, (int)delta.msec,
712
e->src_file, e->src_line));
716
unlock_timer_heap(ht);