blob: 04e318e2b045eff361f44ee16e35e5132c394252 [file] [log] [blame]
Tristan Matthews0a329cc2013-07-17 13:20:14 -04001/* $Id: timer.c 4537 2013-06-19 06:47:43Z riza $ */
2/*
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
469#if PJ_TIMER_DEBUG
470static pj_status_t schedule_w_grp_lock_dbg(pj_timer_heap_t *ht,
471 pj_timer_entry *entry,
472 const pj_time_val *delay,
473 pj_bool_t set_id,
474 int id_val,
475 pj_grp_lock_t *grp_lock,
476 const char *src_file,
477 int src_line)
478#else
479static pj_status_t schedule_w_grp_lock(pj_timer_heap_t *ht,
480 pj_timer_entry *entry,
481 const pj_time_val *delay,
482 pj_bool_t set_id,
483 int id_val,
484 pj_grp_lock_t *grp_lock)
485#endif
486{
487 pj_status_t status;
488 pj_time_val expires;
489
490 PJ_ASSERT_RETURN(ht && entry && delay, PJ_EINVAL);
491 PJ_ASSERT_RETURN(entry->cb != NULL, PJ_EINVAL);
492
493 /* Prevent same entry from being scheduled more than once */
494 PJ_ASSERT_RETURN(entry->_timer_id < 1, PJ_EINVALIDOP);
495
496#if PJ_TIMER_DEBUG
497 entry->src_file = src_file;
498 entry->src_line = src_line;
499#endif
500 pj_gettickcount(&expires);
501 PJ_TIME_VAL_ADD(expires, *delay);
502
503 lock_timer_heap(ht);
504 status = schedule_entry(ht, entry, &expires);
505 if (status == PJ_SUCCESS) {
506 if (set_id)
507 entry->id = id_val;
508 entry->_grp_lock = grp_lock;
509 if (entry->_grp_lock) {
510 pj_grp_lock_add_ref(entry->_grp_lock);
511 }
512 }
513 unlock_timer_heap(ht);
514
515 return status;
516}
517
518
519#if PJ_TIMER_DEBUG
520PJ_DEF(pj_status_t) pj_timer_heap_schedule_dbg( pj_timer_heap_t *ht,
521 pj_timer_entry *entry,
522 const pj_time_val *delay,
523 const char *src_file,
524 int src_line)
525{
526 return schedule_w_grp_lock_dbg(ht, entry, delay, PJ_FALSE, 1, NULL,
527 src_file, src_line);
528}
529
530PJ_DEF(pj_status_t) pj_timer_heap_schedule_w_grp_lock_dbg(
531 pj_timer_heap_t *ht,
532 pj_timer_entry *entry,
533 const pj_time_val *delay,
534 int id_val,
535 pj_grp_lock_t *grp_lock,
536 const char *src_file,
537 int src_line)
538{
539 return schedule_w_grp_lock_dbg(ht, entry, delay, PJ_TRUE, id_val,
540 grp_lock, src_file, src_line);
541}
542
543#else
544PJ_DEF(pj_status_t) pj_timer_heap_schedule( pj_timer_heap_t *ht,
545 pj_timer_entry *entry,
546 const pj_time_val *delay)
547{
548 return schedule_w_grp_lock(ht, entry, delay, PJ_FALSE, 1, NULL);
549}
550
551PJ_DEF(pj_status_t) pj_timer_heap_schedule_w_grp_lock(pj_timer_heap_t *ht,
552 pj_timer_entry *entry,
553 const pj_time_val *delay,
554 int id_val,
555 pj_grp_lock_t *grp_lock)
556{
557 return schedule_w_grp_lock(ht, entry, delay, PJ_TRUE, id_val, grp_lock);
558}
559#endif
560
561static int cancel_timer(pj_timer_heap_t *ht,
562 pj_timer_entry *entry,
563 unsigned flags,
564 int id_val)
565{
566 int count;
567
568 PJ_ASSERT_RETURN(ht && entry, PJ_EINVAL);
569
570 lock_timer_heap(ht);
571 count = cancel(ht, entry, flags | F_DONT_CALL);
572 if (flags & F_SET_ID) {
573 entry->id = id_val;
574 }
575 if (entry->_grp_lock) {
576 pj_grp_lock_t *grp_lock = entry->_grp_lock;
577 entry->_grp_lock = NULL;
578 pj_grp_lock_dec_ref(grp_lock);
579 }
580 unlock_timer_heap(ht);
581
582 return count;
583}
584
585PJ_DEF(int) pj_timer_heap_cancel( pj_timer_heap_t *ht,
586 pj_timer_entry *entry)
587{
588 return cancel_timer(ht, entry, 0, 0);
589}
590
591PJ_DEF(int) pj_timer_heap_cancel_if_active(pj_timer_heap_t *ht,
592 pj_timer_entry *entry,
593 int id_val)
594{
595 return cancel_timer(ht, entry, F_SET_ID | F_DONT_ASSERT, id_val);
596}
597
598PJ_DEF(unsigned) pj_timer_heap_poll( pj_timer_heap_t *ht,
599 pj_time_val *next_delay )
600{
601 pj_time_val now;
602 unsigned count;
603
604 PJ_ASSERT_RETURN(ht, 0);
605
606 lock_timer_heap(ht);
607 if (!ht->cur_size && next_delay) {
608 next_delay->sec = next_delay->msec = PJ_MAXINT32;
609 unlock_timer_heap(ht);
610 return 0;
611 }
612
613 count = 0;
614 pj_gettickcount(&now);
615
616 while ( ht->cur_size &&
617 PJ_TIME_VAL_LTE(ht->heap[0]->_timer_value, now) &&
618 count < ht->max_entries_per_poll )
619 {
620 pj_timer_entry *node = remove_node(ht, 0);
621 pj_grp_lock_t *grp_lock;
622
623 ++count;
624
625 grp_lock = node->_grp_lock;
626 node->_grp_lock = NULL;
627
628 unlock_timer_heap(ht);
629
630 PJ_RACE_ME(5);
631
632 if (node->cb)
633 (*node->cb)(ht, node);
634
635 if (grp_lock)
636 pj_grp_lock_dec_ref(grp_lock);
637
638 lock_timer_heap(ht);
639 }
640 if (ht->cur_size && next_delay) {
641 *next_delay = ht->heap[0]->_timer_value;
642 PJ_TIME_VAL_SUB(*next_delay, now);
643 if (next_delay->sec < 0 || next_delay->msec < 0)
644 next_delay->sec = next_delay->msec = 0;
645 } else if (next_delay) {
646 next_delay->sec = next_delay->msec = PJ_MAXINT32;
647 }
648 unlock_timer_heap(ht);
649
650 return count;
651}
652
653PJ_DEF(pj_size_t) pj_timer_heap_count( pj_timer_heap_t *ht )
654{
655 PJ_ASSERT_RETURN(ht, 0);
656
657 return ht->cur_size;
658}
659
660PJ_DEF(pj_status_t) pj_timer_heap_earliest_time( pj_timer_heap_t * ht,
661 pj_time_val *timeval)
662{
663 pj_assert(ht->cur_size != 0);
664 if (ht->cur_size == 0)
665 return PJ_ENOTFOUND;
666
667 lock_timer_heap(ht);
668 *timeval = ht->heap[0]->_timer_value;
669 unlock_timer_heap(ht);
670
671 return PJ_SUCCESS;
672}
673
674#if PJ_TIMER_DEBUG
675PJ_DEF(void) pj_timer_heap_dump(pj_timer_heap_t *ht)
676{
677 lock_timer_heap(ht);
678
679 PJ_LOG(3,(THIS_FILE, "Dumping timer heap:"));
680 PJ_LOG(3,(THIS_FILE, " Cur size: %d entries, max: %d",
681 (int)ht->cur_size, (int)ht->max_size));
682
683 if (ht->cur_size) {
684 unsigned i;
685 pj_time_val now;
686
687 PJ_LOG(3,(THIS_FILE, " Entries: "));
688 PJ_LOG(3,(THIS_FILE, " _id\tId\tElapsed\tSource"));
689 PJ_LOG(3,(THIS_FILE, " ----------------------------------"));
690
691 pj_gettickcount(&now);
692
693 for (i=0; i<(unsigned)ht->cur_size; ++i) {
694 pj_timer_entry *e = ht->heap[i];
695 pj_time_val delta;
696
697 if (PJ_TIME_VAL_LTE(e->_timer_value, now))
698 delta.sec = delta.msec = 0;
699 else {
700 delta = e->_timer_value;
701 PJ_TIME_VAL_SUB(delta, now);
702 }
703
704 PJ_LOG(3,(THIS_FILE, " %d\t%d\t%d.%03d\t%s:%d",
705 e->_timer_id, e->id,
706 (int)delta.sec, (int)delta.msec,
707 e->src_file, e->src_line));
708 }
709 }
710
711 unlock_timer_heap(ht);
712}
713#endif
714