blob: e96a3e54714a5fcce7271d67c590ec5262a3f197 [file] [log] [blame]
Benny Prijono9033e312005-11-21 02:08:39 +00001/* $Id$ */
2/*
Benny Prijono411b2be2006-08-10 08:45:17 +00003 * 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.
Benny Prijono9033e312005-11-21 02:08:39 +00008 *
Benny Prijono411b2be2006-08-10 08:45:17 +00009 * 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:
Benny Prijono9033e312005-11-21 02:08:39 +000016 * 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
38#define HEAP_PARENT(X) (X == 0 ? 0 : (((X) - 1) / 2))
39#define HEAP_LEFT(X) (((X)+(X))+1)
40
41
42#define DEFAULT_MAX_TIMED_OUT_PER_POLL (64)
43
44
45/**
46 * The implementation of timer heap.
47 */
48struct pj_timer_heap_t
49{
50 /** Pool from which the timer heap resize will get the storage from */
51 pj_pool_t *pool;
52
53 /** Maximum size of the heap. */
54 pj_size_t max_size;
55
56 /** Current size of the heap. */
57 pj_size_t cur_size;
58
59 /** Max timed out entries to process per poll. */
60 unsigned max_entries_per_poll;
61
62 /** Lock object. */
63 pj_lock_t *lock;
64
65 /** Autodelete lock. */
66 pj_bool_t auto_delete_lock;
67
68 /**
69 * Current contents of the Heap, which is organized as a "heap" of
70 * pj_timer_entry *'s. In this context, a heap is a "partially
71 * ordered, almost complete" binary tree, which is stored in an
72 * array.
73 */
74 pj_timer_entry **heap;
75
76 /**
77 * An array of "pointers" that allows each pj_timer_entry in the
78 * <heap_> to be located in O(1) time. Basically, <timer_id_[i]>
79 * contains the slot in the <heap_> array where an pj_timer_entry
80 * with timer id <i> resides. Thus, the timer id passed back from
81 * <schedule_entry> is really an slot into the <timer_ids> array. The
82 * <timer_ids_> array serves two purposes: negative values are
83 * treated as "pointers" for the <freelist_>, whereas positive
84 * values are treated as "pointers" into the <heap_> array.
85 */
86 pj_timer_id_t *timer_ids;
87
88 /**
89 * "Pointer" to the first element in the freelist contained within
90 * the <timer_ids_> array, which is organized as a stack.
91 */
92 pj_timer_id_t timer_ids_freelist;
93
94 /** Callback to be called when a timer expires. */
95 pj_timer_heap_callback *callback;
96
97};
98
99
100
101PJ_INLINE(void) lock_timer_heap( pj_timer_heap_t *ht )
102{
103 if (ht->lock) {
104 pj_lock_acquire(ht->lock);
105 }
106}
107
108PJ_INLINE(void) unlock_timer_heap( pj_timer_heap_t *ht )
109{
110 if (ht->lock) {
111 pj_lock_release(ht->lock);
112 }
113}
114
115
116static void copy_node( pj_timer_heap_t *ht, int slot, pj_timer_entry *moved_node )
117{
118 PJ_CHECK_STACK();
119
120 // Insert <moved_node> into its new location in the heap.
121 ht->heap[slot] = moved_node;
122
123 // Update the corresponding slot in the parallel <timer_ids_> array.
124 ht->timer_ids[moved_node->_timer_id] = slot;
125}
126
127static pj_timer_id_t pop_freelist( pj_timer_heap_t *ht )
128{
129 // We need to truncate this to <int> for backwards compatibility.
130 pj_timer_id_t new_id = ht->timer_ids_freelist;
131
132 PJ_CHECK_STACK();
133
134 // The freelist values in the <timer_ids_> are negative, so we need
135 // to negate them to get the next freelist "pointer."
136 ht->timer_ids_freelist =
137 -ht->timer_ids[ht->timer_ids_freelist];
138
139 return new_id;
140
141}
142
143static void push_freelist (pj_timer_heap_t *ht, pj_timer_id_t old_id)
144{
145 PJ_CHECK_STACK();
146
147 // The freelist values in the <timer_ids_> are negative, so we need
148 // to negate them to get the next freelist "pointer."
149 ht->timer_ids[old_id] = -ht->timer_ids_freelist;
150 ht->timer_ids_freelist = old_id;
151}
152
153
154static void reheap_down(pj_timer_heap_t *ht, pj_timer_entry *moved_node,
155 size_t slot, size_t child)
156{
157 PJ_CHECK_STACK();
158
159 // Restore the heap property after a deletion.
160
161 while (child < ht->cur_size)
162 {
163 // Choose the smaller of the two children.
164 if (child + 1 < ht->cur_size
165 && PJ_TIME_VAL_LT(ht->heap[child + 1]->_timer_value, ht->heap[child]->_timer_value))
166 child++;
167
168 // Perform a <copy> if the child has a larger timeout value than
169 // the <moved_node>.
170 if (PJ_TIME_VAL_LT(ht->heap[child]->_timer_value, moved_node->_timer_value))
171 {
172 copy_node( ht, slot, ht->heap[child]);
173 slot = child;
174 child = HEAP_LEFT(child);
175 }
176 else
177 // We've found our location in the heap.
178 break;
179 }
180
181 copy_node( ht, slot, moved_node);
182}
183
184static void reheap_up( pj_timer_heap_t *ht, pj_timer_entry *moved_node,
185 size_t slot, size_t parent)
186{
187 // Restore the heap property after an insertion.
188
189 while (slot > 0)
190 {
191 // If the parent node is greater than the <moved_node> we need
192 // to copy it down.
193 if (PJ_TIME_VAL_LT(moved_node->_timer_value, ht->heap[parent]->_timer_value))
194 {
195 copy_node(ht, slot, ht->heap[parent]);
196 slot = parent;
197 parent = HEAP_PARENT(slot);
198 }
199 else
200 break;
201 }
202
203 // Insert the new node into its proper resting place in the heap and
204 // update the corresponding slot in the parallel <timer_ids> array.
205 copy_node(ht, slot, moved_node);
206}
207
208
209static pj_timer_entry * remove_node( pj_timer_heap_t *ht, size_t slot)
210{
211 pj_timer_entry *removed_node = ht->heap[slot];
212
213 // Return this timer id to the freelist.
214 push_freelist( ht, removed_node->_timer_id );
215
216 // Decrement the size of the heap by one since we're removing the
217 // "slot"th node.
218 ht->cur_size--;
219
220 // Set the ID
221 removed_node->_timer_id = -1;
222
223 // Only try to reheapify if we're not deleting the last entry.
224
225 if (slot < ht->cur_size)
226 {
227 int parent;
228 pj_timer_entry *moved_node = ht->heap[ht->cur_size];
229
230 // Move the end node to the location being removed and update
231 // the corresponding slot in the parallel <timer_ids> array.
232 copy_node( ht, slot, moved_node);
233
234 // If the <moved_node->time_value_> is great than or equal its
235 // parent it needs be moved down the heap.
236 parent = HEAP_PARENT (slot);
237
238 if (PJ_TIME_VAL_GTE(moved_node->_timer_value, ht->heap[parent]->_timer_value))
239 reheap_down( ht, moved_node, slot, HEAP_LEFT(slot));
240 else
241 reheap_up( ht, moved_node, slot, parent);
242 }
243
244 return removed_node;
245}
246
247static void grow_heap(pj_timer_heap_t *ht)
248{
249 // All the containers will double in size from max_size_
250 size_t new_size = ht->max_size * 2;
251 pj_timer_id_t *new_timer_ids;
252 pj_size_t i;
253
254 // First grow the heap itself.
255
256 pj_timer_entry **new_heap = 0;
257
258 new_heap = pj_pool_alloc(ht->pool, sizeof(pj_timer_entry*) * new_size);
259 memcpy(new_heap, ht->heap, ht->max_size * sizeof(pj_timer_entry*));
260 //delete [] this->heap_;
261 ht->heap = new_heap;
262
263 // Grow the array of timer ids.
264
265 new_timer_ids = 0;
266 new_timer_ids = pj_pool_alloc(ht->pool, new_size * sizeof(pj_timer_id_t));
267
268 memcpy( new_timer_ids, ht->timer_ids, ht->max_size * sizeof(pj_timer_id_t));
269
270 //delete [] timer_ids_;
271 ht->timer_ids = new_timer_ids;
272
273 // And add the new elements to the end of the "freelist".
274 for (i = ht->max_size; i < new_size; i++)
275 ht->timer_ids[i] = -((pj_timer_id_t) (i + 1));
276
277 ht->max_size = new_size;
278}
279
280static void insert_node(pj_timer_heap_t *ht, pj_timer_entry *new_node)
281{
282 if (ht->cur_size + 2 >= ht->max_size)
283 grow_heap(ht);
284
285 reheap_up( ht, new_node, ht->cur_size, HEAP_PARENT(ht->cur_size));
286 ht->cur_size++;
287}
288
289
290static pj_status_t schedule_entry( pj_timer_heap_t *ht,
291 pj_timer_entry *entry,
292 const pj_time_val *future_time )
293{
294 if (ht->cur_size < ht->max_size)
295 {
296 // Obtain the next unique sequence number.
297 // Set the entry
298 entry->_timer_id = pop_freelist(ht);
299 entry->_timer_value = *future_time;
300 insert_node( ht, entry);
301 return 0;
302 }
303 else
304 return -1;
305}
306
307
308static int cancel( pj_timer_heap_t *ht,
309 pj_timer_entry *entry,
310 int dont_call)
311{
312 long timer_node_slot;
313
314 PJ_CHECK_STACK();
315
316 // Check to see if the timer_id is out of range
317 if (entry->_timer_id < 0 || (pj_size_t)entry->_timer_id > ht->max_size)
318 return 0;
319
320 timer_node_slot = ht->timer_ids[entry->_timer_id];
321
322 if (timer_node_slot < 0) // Check to see if timer_id is still valid.
323 return 0;
324
325 if (entry != ht->heap[timer_node_slot])
326 {
327 pj_assert(entry == ht->heap[timer_node_slot]);
328 return 0;
329 }
330 else
331 {
332 remove_node( ht, timer_node_slot);
333
334 if (dont_call == 0)
335 // Call the close hook.
336 (*ht->callback)(ht, entry);
337 return 1;
338 }
339}
340
341
342/*
343 * Calculate memory size required to create a timer heap.
344 */
345PJ_DEF(pj_size_t) pj_timer_heap_mem_size(pj_size_t count)
346{
347 return /* size of the timer heap itself: */
348 sizeof(pj_timer_heap_t) +
349 /* size of each entry: */
350 (count+2) * (sizeof(pj_timer_entry*)+sizeof(pj_timer_id_t)) +
351 /* lock, pool etc: */
352 132;
353}
354
355/*
356 * Create a new timer heap.
357 */
358PJ_DEF(pj_status_t) pj_timer_heap_create( pj_pool_t *pool,
359 pj_size_t size,
360 pj_timer_heap_t **p_heap)
361{
362 pj_timer_heap_t *ht;
363 pj_size_t i;
364
365 PJ_ASSERT_RETURN(pool && p_heap, PJ_EINVAL);
366
367 *p_heap = NULL;
368
369 /* Magic? */
370 size += 2;
371
372 /* Allocate timer heap data structure from the pool */
373 ht = pj_pool_alloc(pool, sizeof(pj_timer_heap_t));
374 if (!ht)
375 return PJ_ENOMEM;
376
377 /* Initialize timer heap sizes */
378 ht->max_size = size;
379 ht->cur_size = 0;
380 ht->max_entries_per_poll = DEFAULT_MAX_TIMED_OUT_PER_POLL;
381 ht->timer_ids_freelist = 1;
382 ht->pool = pool;
383
384 /* Lock. */
385 ht->lock = NULL;
386 ht->auto_delete_lock = 0;
387
388 // Create the heap array.
389 ht->heap = pj_pool_alloc(pool, sizeof(pj_timer_entry*) * size);
390 if (!ht->heap)
391 return PJ_ENOMEM;
392
393 // Create the parallel
394 ht->timer_ids = pj_pool_alloc( pool, sizeof(pj_timer_id_t) * size);
395 if (!ht->timer_ids)
396 return PJ_ENOMEM;
397
398 // Initialize the "freelist," which uses negative values to
399 // distinguish freelist elements from "pointers" into the <heap_>
400 // array.
401 for (i=0; i<size; ++i)
402 ht->timer_ids[i] = -((pj_timer_id_t) (i + 1));
403
404 *p_heap = ht;
405 return PJ_SUCCESS;
406}
407
408PJ_DEF(void) pj_timer_heap_destroy( pj_timer_heap_t *ht )
409{
410 if (ht->lock && ht->auto_delete_lock) {
411 pj_lock_destroy(ht->lock);
412 ht->lock = NULL;
413 }
414}
415
416PJ_DEF(void) pj_timer_heap_set_lock( pj_timer_heap_t *ht,
417 pj_lock_t *lock,
418 pj_bool_t auto_del )
419{
420 if (ht->lock && ht->auto_delete_lock)
421 pj_lock_destroy(ht->lock);
422
423 ht->lock = lock;
424 ht->auto_delete_lock = auto_del;
425}
426
427
428PJ_DEF(unsigned) pj_timer_heap_set_max_timed_out_per_poll(pj_timer_heap_t *ht,
429 unsigned count )
430{
431 unsigned old_count = ht->max_entries_per_poll;
432 ht->max_entries_per_poll = count;
433 return old_count;
434}
435
436PJ_DEF(pj_timer_entry*) pj_timer_entry_init( pj_timer_entry *entry,
437 int id,
438 void *user_data,
439 pj_timer_heap_callback *cb )
440{
441 pj_assert(entry && cb);
442
443 entry->id = id;
444 entry->user_data = user_data;
445 entry->cb = cb;
446
447 return entry;
448}
449
450PJ_DEF(pj_status_t) pj_timer_heap_schedule( pj_timer_heap_t *ht,
451 pj_timer_entry *entry,
452 const pj_time_val *delay)
453{
454 pj_status_t status;
455 pj_time_val expires;
456
457 PJ_ASSERT_RETURN(ht && entry && delay, PJ_EINVAL);
Benny Prijono30a48c62006-01-08 23:55:09 +0000458 PJ_ASSERT_RETURN(entry->cb != NULL, PJ_EINVAL);
Benny Prijono9033e312005-11-21 02:08:39 +0000459
Benny Prijonoa915cd12006-02-19 01:28:55 +0000460 /* Prevent same entry from being scheduled more than once */
461 PJ_ASSERT_RETURN(entry->_timer_id < 1, PJ_EINVALIDOP);
462
Benny Prijono9033e312005-11-21 02:08:39 +0000463 pj_gettimeofday(&expires);
464 PJ_TIME_VAL_ADD(expires, *delay);
465
466 lock_timer_heap(ht);
467 status = schedule_entry(ht, entry, &expires);
468 unlock_timer_heap(ht);
469
470 return status;
471}
472
473PJ_DEF(int) pj_timer_heap_cancel( pj_timer_heap_t *ht,
474 pj_timer_entry *entry)
475{
476 int count;
477
478 PJ_ASSERT_RETURN(ht && entry, PJ_EINVAL);
479
480 lock_timer_heap(ht);
481 count = cancel(ht, entry, 1);
482 unlock_timer_heap(ht);
483
484 return count;
485}
486
487PJ_DEF(unsigned) pj_timer_heap_poll( pj_timer_heap_t *ht,
488 pj_time_val *next_delay )
489{
490 pj_time_val now;
491 unsigned count;
492
493 PJ_ASSERT_RETURN(ht, 0);
494
495 if (!ht->cur_size && next_delay) {
496 next_delay->sec = next_delay->msec = PJ_MAXINT32;
497 return 0;
498 }
499
500 count = 0;
501 pj_gettimeofday(&now);
502
503 lock_timer_heap(ht);
504 while ( ht->cur_size &&
505 PJ_TIME_VAL_LTE(ht->heap[0]->_timer_value, now) &&
506 count < ht->max_entries_per_poll )
507 {
508 pj_timer_entry *node = remove_node(ht, 0);
509 ++count;
510
511 unlock_timer_heap(ht);
Benny Prijono30a48c62006-01-08 23:55:09 +0000512 if (node->cb)
513 (*node->cb)(ht, node);
Benny Prijono9033e312005-11-21 02:08:39 +0000514 lock_timer_heap(ht);
515 }
516 if (ht->cur_size && next_delay) {
517 *next_delay = ht->heap[0]->_timer_value;
518 PJ_TIME_VAL_SUB(*next_delay, now);
Benny Prijono64920812006-03-01 19:27:06 +0000519 if (next_delay->sec < 0 || next_delay->msec < 0)
520 next_delay->sec = next_delay->msec = 0;
Benny Prijono9033e312005-11-21 02:08:39 +0000521 } else if (next_delay) {
522 next_delay->sec = next_delay->msec = PJ_MAXINT32;
523 }
524 unlock_timer_heap(ht);
525
526 return count;
527}
528
529PJ_DEF(pj_size_t) pj_timer_heap_count( pj_timer_heap_t *ht )
530{
531 PJ_ASSERT_RETURN(ht, 0);
532
533 return ht->cur_size;
534}
535
536PJ_DEF(pj_status_t) pj_timer_heap_earliest_time( pj_timer_heap_t * ht,
537 pj_time_val *timeval)
538{
539 pj_assert(ht->cur_size != 0);
540 if (ht->cur_size == 0)
541 return PJ_ENOTFOUND;
542
543 lock_timer_heap(ht);
544 *timeval = ht->heap[0]->_timer_value;
545 unlock_timer_heap(ht);
546
547 return PJ_SUCCESS;
548}
549