blob: 931a57fa2a7339ac6bc1c8ddd2d9a846a6e2f3a9 [file] [log] [blame]
Alexandre Lision94f06ba2013-12-09 16:28:33 -05001/* $Id$ */
Tristan Matthews0a329cc2013-07-17 13:20:14 -04002/*
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
7 * solution.
8 *
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
12 *
13 * ACE is Copyright (C)1993-2006 Douglas C. Schmidt <d.schmidt@vanderbilt.edu>
14 *
15 * GNU Public License:
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.
20 *
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.
25 *
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
29 */
30#include <pj/timer.h>
31#include <pj/pool.h>
32#include <pj/os.h>
33#include <pj/string.h>
34#include <pj/assert.h>
35#include <pj/errno.h>
36#include <pj/lock.h>
37#include <pj/log.h>
38#include <pj/rand.h>
39
40#define THIS_FILE "timer.c"
41
42#define HEAP_PARENT(X) (X == 0 ? 0 : (((X) - 1) / 2))
43#define HEAP_LEFT(X) (((X)+(X))+1)
44
45
46#define DEFAULT_MAX_TIMED_OUT_PER_POLL (64)
47
48enum
49{
50 F_DONT_CALL = 1,
51 F_DONT_ASSERT = 2,
52 F_SET_ID = 4
53};
54
55
56/**
57 * The implementation of timer heap.
58 */
59struct pj_timer_heap_t
60{
61 /** Pool from which the timer heap resize will get the storage from */
62 pj_pool_t *pool;
63
64 /** Maximum size of the heap. */
65 pj_size_t max_size;
66
67 /** Current size of the heap. */
68 pj_size_t cur_size;
69
70 /** Max timed out entries to process per poll. */
71 unsigned max_entries_per_poll;
72
73 /** Lock object. */
74 pj_lock_t *lock;
75
76 /** Autodelete lock. */
77 pj_bool_t auto_delete_lock;
78
79 /**
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
83 * array.
84 */
85 pj_timer_entry **heap;
86
87 /**
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.
96 */
97 pj_timer_id_t *timer_ids;
98
99 /**
100 * "Pointer" to the first element in the freelist contained within
101 * the <timer_ids_> array, which is organized as a stack.
102 */
103 pj_timer_id_t timer_ids_freelist;
104
105 /** Callback to be called when a timer expires. */
106 pj_timer_heap_callback *callback;
107
108};
109
110
111
112PJ_INLINE(void) lock_timer_heap( pj_timer_heap_t *ht )
113{
114 if (ht->lock) {
115 pj_lock_acquire(ht->lock);
116 }
117}
118
119PJ_INLINE(void) unlock_timer_heap( pj_timer_heap_t *ht )
120{
121 if (ht->lock) {
122 pj_lock_release(ht->lock);
123 }
124}
125
126
127static void copy_node( pj_timer_heap_t *ht, pj_size_t slot,
128 pj_timer_entry *moved_node )
129{
130 PJ_CHECK_STACK();
131
132 // Insert <moved_node> into its new location in the heap.
133 ht->heap[slot] = moved_node;
134
135 // Update the corresponding slot in the parallel <timer_ids_> array.
136 ht->timer_ids[moved_node->_timer_id] = (int)slot;
137}
138
139static pj_timer_id_t pop_freelist( pj_timer_heap_t *ht )
140{
141 // We need to truncate this to <int> for backwards compatibility.
142 pj_timer_id_t new_id = ht->timer_ids_freelist;
143
144 PJ_CHECK_STACK();
145
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];
150
151 return new_id;
152
153}
154
155static void push_freelist (pj_timer_heap_t *ht, pj_timer_id_t old_id)
156{
157 PJ_CHECK_STACK();
158
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;
163}
164
165
166static void reheap_down(pj_timer_heap_t *ht, pj_timer_entry *moved_node,
167 size_t slot, size_t child)
168{
169 PJ_CHECK_STACK();
170
171 // Restore the heap property after a deletion.
172
173 while (child < ht->cur_size)
174 {
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))
178 child++;
179
180 // Perform a <copy> if the child has a larger timeout value than
181 // the <moved_node>.
182 if (PJ_TIME_VAL_LT(ht->heap[child]->_timer_value, moved_node->_timer_value))
183 {
184 copy_node( ht, slot, ht->heap[child]);
185 slot = child;
186 child = HEAP_LEFT(child);
187 }
188 else
189 // We've found our location in the heap.
190 break;
191 }
192
193 copy_node( ht, slot, moved_node);
194}
195
196static void reheap_up( pj_timer_heap_t *ht, pj_timer_entry *moved_node,
197 size_t slot, size_t parent)
198{
199 // Restore the heap property after an insertion.
200
201 while (slot > 0)
202 {
203 // If the parent node is greater than the <moved_node> we need
204 // to copy it down.
205 if (PJ_TIME_VAL_LT(moved_node->_timer_value, ht->heap[parent]->_timer_value))
206 {
207 copy_node(ht, slot, ht->heap[parent]);
208 slot = parent;
209 parent = HEAP_PARENT(slot);
210 }
211 else
212 break;
213 }
214
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);
218}
219
220
221static pj_timer_entry * remove_node( pj_timer_heap_t *ht, size_t slot)
222{
223 pj_timer_entry *removed_node = ht->heap[slot];
224
225 // Return this timer id to the freelist.
226 push_freelist( ht, removed_node->_timer_id );
227
228 // Decrement the size of the heap by one since we're removing the
229 // "slot"th node.
230 ht->cur_size--;
231
232 // Set the ID
233 removed_node->_timer_id = -1;
234
235 // Only try to reheapify if we're not deleting the last entry.
236
237 if (slot < ht->cur_size)
238 {
239 pj_size_t parent;
240 pj_timer_entry *moved_node = ht->heap[ht->cur_size];
241
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);
245
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);
249
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));
252 else
253 reheap_up( ht, moved_node, slot, parent);
254 }
255
256 return removed_node;
257}
258
259static void grow_heap(pj_timer_heap_t *ht)
260{
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;
264 pj_size_t i;
265
266 // First grow the heap itself.
267
268 pj_timer_entry **new_heap = 0;
269
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_;
274 ht->heap = new_heap;
275
276 // Grow the array of timer ids.
277
278 new_timer_ids = 0;
279 new_timer_ids = (pj_timer_id_t*)
280 pj_pool_alloc(ht->pool, new_size * sizeof(pj_timer_id_t));
281
282 memcpy( new_timer_ids, ht->timer_ids, ht->max_size * sizeof(pj_timer_id_t));
283
284 //delete [] timer_ids_;
285 ht->timer_ids = new_timer_ids;
286
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));
290
291 ht->max_size = new_size;
292}
293
294static void insert_node(pj_timer_heap_t *ht, pj_timer_entry *new_node)
295{
296 if (ht->cur_size + 2 >= ht->max_size)
297 grow_heap(ht);
298
299 reheap_up( ht, new_node, ht->cur_size, HEAP_PARENT(ht->cur_size));
300 ht->cur_size++;
301}
302
303
304static pj_status_t schedule_entry( pj_timer_heap_t *ht,
305 pj_timer_entry *entry,
306 const pj_time_val *future_time )
307{
308 if (ht->cur_size < ht->max_size)
309 {
310 // Obtain the next unique sequence number.
311 // Set the entry
312 entry->_timer_id = pop_freelist(ht);
313 entry->_timer_value = *future_time;
314 insert_node( ht, entry);
315 return 0;
316 }
317 else
318 return -1;
319}
320
321
322static int cancel( pj_timer_heap_t *ht,
323 pj_timer_entry *entry,
324 unsigned flags)
325{
326 long timer_node_slot;
327
328 PJ_CHECK_STACK();
329
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)
332 return 0;
333
334 timer_node_slot = ht->timer_ids[entry->_timer_id];
335
336 if (timer_node_slot < 0) // Check to see if timer_id is still valid.
337 return 0;
338
339 if (entry != ht->heap[timer_node_slot])
340 {
341 if ((flags & F_DONT_ASSERT) == 0)
342 pj_assert(entry == ht->heap[timer_node_slot]);
343 return 0;
344 }
345 else
346 {
347 remove_node( ht, timer_node_slot);
348
349 if ((flags & F_DONT_CALL) == 0)
350 // Call the close hook.
351 (*ht->callback)(ht, entry);
352 return 1;
353 }
354}
355
356
357/*
358 * Calculate memory size required to create a timer heap.
359 */
360PJ_DEF(pj_size_t) pj_timer_heap_mem_size(pj_size_t count)
361{
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: */
367 132;
368}
369
370/*
371 * Create a new timer heap.
372 */
373PJ_DEF(pj_status_t) pj_timer_heap_create( pj_pool_t *pool,
374 pj_size_t size,
375 pj_timer_heap_t **p_heap)
376{
377 pj_timer_heap_t *ht;
378 pj_size_t i;
379
380 PJ_ASSERT_RETURN(pool && p_heap, PJ_EINVAL);
381
382 *p_heap = NULL;
383
384 /* Magic? */
385 size += 2;
386
387 /* Allocate timer heap data structure from the pool */
388 ht = PJ_POOL_ALLOC_T(pool, pj_timer_heap_t);
389 if (!ht)
390 return PJ_ENOMEM;
391
392 /* Initialize timer heap sizes */
393 ht->max_size = size;
394 ht->cur_size = 0;
395 ht->max_entries_per_poll = DEFAULT_MAX_TIMED_OUT_PER_POLL;
396 ht->timer_ids_freelist = 1;
397 ht->pool = pool;
398
399 /* Lock. */
400 ht->lock = NULL;
401 ht->auto_delete_lock = 0;
402
403 // Create the heap array.
404 ht->heap = (pj_timer_entry**)
405 pj_pool_alloc(pool, sizeof(pj_timer_entry*) * size);
406 if (!ht->heap)
407 return PJ_ENOMEM;
408
409 // Create the parallel
410 ht->timer_ids = (pj_timer_id_t *)
411 pj_pool_alloc( pool, sizeof(pj_timer_id_t) * size);
412 if (!ht->timer_ids)
413 return PJ_ENOMEM;
414
415 // Initialize the "freelist," which uses negative values to
416 // distinguish freelist elements from "pointers" into the <heap_>
417 // array.
418 for (i=0; i<size; ++i)
419 ht->timer_ids[i] = -((pj_timer_id_t) (i + 1));
420
421 *p_heap = ht;
422 return PJ_SUCCESS;
423}
424
425PJ_DEF(void) pj_timer_heap_destroy( pj_timer_heap_t *ht )
426{
427 if (ht->lock && ht->auto_delete_lock) {
428 pj_lock_destroy(ht->lock);
429 ht->lock = NULL;
430 }
431}
432
433PJ_DEF(void) pj_timer_heap_set_lock( pj_timer_heap_t *ht,
434 pj_lock_t *lock,
435 pj_bool_t auto_del )
436{
437 if (ht->lock && ht->auto_delete_lock)
438 pj_lock_destroy(ht->lock);
439
440 ht->lock = lock;
441 ht->auto_delete_lock = auto_del;
442}
443
444
445PJ_DEF(unsigned) pj_timer_heap_set_max_timed_out_per_poll(pj_timer_heap_t *ht,
446 unsigned count )
447{
448 unsigned old_count = ht->max_entries_per_poll;
449 ht->max_entries_per_poll = count;
450 return old_count;
451}
452
453PJ_DEF(pj_timer_entry*) pj_timer_entry_init( pj_timer_entry *entry,
454 int id,
455 void *user_data,
456 pj_timer_heap_callback *cb )
457{
458 pj_assert(entry && cb);
459
460 entry->_timer_id = -1;
461 entry->id = id;
462 entry->user_data = user_data;
463 entry->cb = cb;
464 entry->_grp_lock = NULL;
465
466 return entry;
467}
468
Alexandre Lision94f06ba2013-12-09 16:28:33 -0500469PJ_DEF(pj_bool_t) pj_timer_entry_running( pj_timer_entry *entry )
470{
471 return (entry->_timer_id >= 1);
472}
473
Tristan Matthews0a329cc2013-07-17 13:20:14 -0400474#if PJ_TIMER_DEBUG
475static pj_status_t schedule_w_grp_lock_dbg(pj_timer_heap_t *ht,
476 pj_timer_entry *entry,
477 const pj_time_val *delay,
478 pj_bool_t set_id,
479 int id_val,
480 pj_grp_lock_t *grp_lock,
481 const char *src_file,
482 int src_line)
483#else
484static pj_status_t schedule_w_grp_lock(pj_timer_heap_t *ht,
485 pj_timer_entry *entry,
486 const pj_time_val *delay,
487 pj_bool_t set_id,
488 int id_val,
489 pj_grp_lock_t *grp_lock)
490#endif
491{
492 pj_status_t status;
493 pj_time_val expires;
494
495 PJ_ASSERT_RETURN(ht && entry && delay, PJ_EINVAL);
496 PJ_ASSERT_RETURN(entry->cb != NULL, PJ_EINVAL);
497
498 /* Prevent same entry from being scheduled more than once */
499 PJ_ASSERT_RETURN(entry->_timer_id < 1, PJ_EINVALIDOP);
500
501#if PJ_TIMER_DEBUG
502 entry->src_file = src_file;
503 entry->src_line = src_line;
504#endif
505 pj_gettickcount(&expires);
506 PJ_TIME_VAL_ADD(expires, *delay);
507
508 lock_timer_heap(ht);
509 status = schedule_entry(ht, entry, &expires);
510 if (status == PJ_SUCCESS) {
511 if (set_id)
512 entry->id = id_val;
513 entry->_grp_lock = grp_lock;
514 if (entry->_grp_lock) {
515 pj_grp_lock_add_ref(entry->_grp_lock);
516 }
517 }
518 unlock_timer_heap(ht);
519
520 return status;
521}
522
523
524#if PJ_TIMER_DEBUG
525PJ_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,
529 int src_line)
530{
531 return schedule_w_grp_lock_dbg(ht, entry, delay, PJ_FALSE, 1, NULL,
532 src_file, src_line);
533}
534
535PJ_DEF(pj_status_t) pj_timer_heap_schedule_w_grp_lock_dbg(
536 pj_timer_heap_t *ht,
537 pj_timer_entry *entry,
538 const pj_time_val *delay,
539 int id_val,
540 pj_grp_lock_t *grp_lock,
541 const char *src_file,
542 int src_line)
543{
544 return schedule_w_grp_lock_dbg(ht, entry, delay, PJ_TRUE, id_val,
545 grp_lock, src_file, src_line);
546}
547
548#else
549PJ_DEF(pj_status_t) pj_timer_heap_schedule( pj_timer_heap_t *ht,
550 pj_timer_entry *entry,
551 const pj_time_val *delay)
552{
553 return schedule_w_grp_lock(ht, entry, delay, PJ_FALSE, 1, NULL);
554}
555
556PJ_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,
559 int id_val,
560 pj_grp_lock_t *grp_lock)
561{
562 return schedule_w_grp_lock(ht, entry, delay, PJ_TRUE, id_val, grp_lock);
563}
564#endif
565
566static int cancel_timer(pj_timer_heap_t *ht,
567 pj_timer_entry *entry,
568 unsigned flags,
569 int id_val)
570{
571 int count;
572
573 PJ_ASSERT_RETURN(ht && entry, PJ_EINVAL);
574
575 lock_timer_heap(ht);
576 count = cancel(ht, entry, flags | F_DONT_CALL);
577 if (flags & F_SET_ID) {
578 entry->id = id_val;
579 }
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);
584 }
585 unlock_timer_heap(ht);
586
587 return count;
588}
589
590PJ_DEF(int) pj_timer_heap_cancel( pj_timer_heap_t *ht,
591 pj_timer_entry *entry)
592{
593 return cancel_timer(ht, entry, 0, 0);
594}
595
596PJ_DEF(int) pj_timer_heap_cancel_if_active(pj_timer_heap_t *ht,
597 pj_timer_entry *entry,
598 int id_val)
599{
600 return cancel_timer(ht, entry, F_SET_ID | F_DONT_ASSERT, id_val);
601}
602
603PJ_DEF(unsigned) pj_timer_heap_poll( pj_timer_heap_t *ht,
604 pj_time_val *next_delay )
605{
606 pj_time_val now;
607 unsigned count;
608
609 PJ_ASSERT_RETURN(ht, 0);
610
611 lock_timer_heap(ht);
612 if (!ht->cur_size && next_delay) {
613 next_delay->sec = next_delay->msec = PJ_MAXINT32;
614 unlock_timer_heap(ht);
615 return 0;
616 }
617
618 count = 0;
619 pj_gettickcount(&now);
620
621 while ( ht->cur_size &&
622 PJ_TIME_VAL_LTE(ht->heap[0]->_timer_value, now) &&
623 count < ht->max_entries_per_poll )
624 {
625 pj_timer_entry *node = remove_node(ht, 0);
626 pj_grp_lock_t *grp_lock;
627
628 ++count;
629
630 grp_lock = node->_grp_lock;
631 node->_grp_lock = NULL;
632
633 unlock_timer_heap(ht);
634
635 PJ_RACE_ME(5);
636
637 if (node->cb)
638 (*node->cb)(ht, node);
639
640 if (grp_lock)
641 pj_grp_lock_dec_ref(grp_lock);
642
643 lock_timer_heap(ht);
644 }
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;
652 }
653 unlock_timer_heap(ht);
654
655 return count;
656}
657
658PJ_DEF(pj_size_t) pj_timer_heap_count( pj_timer_heap_t *ht )
659{
660 PJ_ASSERT_RETURN(ht, 0);
661
662 return ht->cur_size;
663}
664
665PJ_DEF(pj_status_t) pj_timer_heap_earliest_time( pj_timer_heap_t * ht,
666 pj_time_val *timeval)
667{
668 pj_assert(ht->cur_size != 0);
669 if (ht->cur_size == 0)
670 return PJ_ENOTFOUND;
671
672 lock_timer_heap(ht);
673 *timeval = ht->heap[0]->_timer_value;
674 unlock_timer_heap(ht);
675
676 return PJ_SUCCESS;
677}
678
679#if PJ_TIMER_DEBUG
680PJ_DEF(void) pj_timer_heap_dump(pj_timer_heap_t *ht)
681{
682 lock_timer_heap(ht);
683
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));
687
688 if (ht->cur_size) {
689 unsigned i;
690 pj_time_val now;
691
692 PJ_LOG(3,(THIS_FILE, " Entries: "));
693 PJ_LOG(3,(THIS_FILE, " _id\tId\tElapsed\tSource"));
694 PJ_LOG(3,(THIS_FILE, " ----------------------------------"));
695
696 pj_gettickcount(&now);
697
698 for (i=0; i<(unsigned)ht->cur_size; ++i) {
699 pj_timer_entry *e = ht->heap[i];
700 pj_time_val delta;
701
702 if (PJ_TIME_VAL_LTE(e->_timer_value, now))
703 delta.sec = delta.msec = 0;
704 else {
705 delta = e->_timer_value;
706 PJ_TIME_VAL_SUB(delta, now);
707 }
708
709 PJ_LOG(3,(THIS_FILE, " %d\t%d\t%d.%03d\t%s:%d",
710 e->_timer_id, e->id,
711 (int)delta.sec, (int)delta.msec,
712 e->src_file, e->src_line));
713 }
714 }
715
716 unlock_timer_heap(ht);
717}
718#endif
719