That's all, folks. Not going to update the Makefile until res_jabber is
[asterisk/asterisk.git] / main / sched.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Scheduler Routines (from cheops-NG)
22  *
23  * \author Mark Spencer <markster@digium.com>
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #ifdef DEBUG_SCHEDULER
31 #define DEBUG(a) do { \
32         if (option_debug) \
33                 DEBUG_M(a) \
34         } while (0)
35 #else
36 #define DEBUG(a) 
37 #endif
38
39 #include <sys/time.h>
40
41 #include "asterisk/sched.h"
42 #include "asterisk/channel.h"
43 #include "asterisk/lock.h"
44 #include "asterisk/utils.h"
45 #include "asterisk/linkedlists.h"
46 #include "asterisk/dlinkedlists.h"
47 #include "asterisk/hashtab.h"
48
49 struct sched {
50         AST_DLLIST_ENTRY(sched) list;
51         int id;                       /*!< ID number of event */
52         struct timeval when;          /*!< Absolute time event should take place */
53         int resched;                  /*!< When to reschedule */
54         int variable;                 /*!< Use return value from callback to reschedule */
55         const void *data;             /*!< Data */
56         ast_sched_cb callback;        /*!< Callback */
57 };
58
59 struct sched_context {
60         ast_mutex_t lock;
61         unsigned int eventcnt;                  /*!< Number of events processed */
62         unsigned int schedcnt;                  /*!< Number of outstanding schedule events */
63         unsigned int highwater;                                 /*!< highest count so far */
64         AST_DLLIST_HEAD_NOLOCK(, sched) schedq;   /*!< Schedule entry and main queue */
65         struct ast_hashtab *schedq_ht;             /*!< hash table for fast searching */
66
67 #ifdef SCHED_MAX_CACHE
68         AST_LIST_HEAD_NOLOCK(, sched) schedc;   /*!< Cache of unused schedule structures and how many */
69         unsigned int schedccnt;
70 #endif
71 };
72
73
74 /* hash routines for sched */
75
76 static int sched_cmp(const void *a, const void *b)
77 {
78         const struct sched *as = a;
79         const struct sched *bs = b;
80         return as->id != bs->id; /* return 0 on a match like strcmp would */
81 }
82
83 static unsigned int sched_hash(const void *obj)
84 {
85         const struct sched *s = obj;
86         unsigned int h = s->id;
87         return h;
88 }
89
90 struct sched_context *sched_context_create(void)
91 {
92         struct sched_context *tmp;
93
94         if (!(tmp = ast_calloc(1, sizeof(*tmp))))
95                 return NULL;
96
97         ast_mutex_init(&tmp->lock);
98         tmp->eventcnt = 1;
99         
100         tmp->schedq_ht = ast_hashtab_create(23, sched_cmp, ast_hashtab_resize_java, ast_hashtab_newsize_java, sched_hash, 1);
101         
102         return tmp;
103 }
104
105 void sched_context_destroy(struct sched_context *con)
106 {
107         struct sched *s;
108
109         ast_mutex_lock(&con->lock);
110
111 #ifdef SCHED_MAX_CACHE
112         /* Eliminate the cache */
113         while ((s = AST_LIST_REMOVE_HEAD(&con->schedc, list)))
114                 ast_free(s);
115 #endif
116
117         /* And the queue */
118         while ((s = AST_DLLIST_REMOVE_HEAD(&con->schedq, list)))
119                 ast_free(s);
120
121         ast_hashtab_destroy(con->schedq_ht, NULL);
122         con->schedq_ht = NULL;
123         
124         /* And the context */
125         ast_mutex_unlock(&con->lock);
126         ast_mutex_destroy(&con->lock);
127         ast_free(con);
128 }
129
130 static struct sched *sched_alloc(struct sched_context *con)
131 {
132         struct sched *tmp;
133
134         /*
135          * We keep a small cache of schedule entries
136          * to minimize the number of necessary malloc()'s
137          */
138 #ifdef SCHED_MAX_CACHE
139         if ((tmp = AST_LIST_REMOVE_HEAD(&con->schedc, list)))
140                 con->schedccnt--;
141         else
142 #endif
143                 tmp = ast_calloc(1, sizeof(*tmp));
144
145         return tmp;
146 }
147
148 static void sched_release(struct sched_context *con, struct sched *tmp)
149 {
150         /*
151          * Add to the cache, or just free() if we
152          * already have too many cache entries
153          */
154
155 #ifdef SCHED_MAX_CACHE   
156         if (con->schedccnt < SCHED_MAX_CACHE) {
157                 AST_LIST_INSERT_HEAD(&con->schedc, tmp, list);
158                 con->schedccnt++;
159         } else
160 #endif
161                 ast_free(tmp);
162 }
163
164 /*! \brief
165  * Return the number of milliseconds 
166  * until the next scheduled event
167  */
168 int ast_sched_wait(struct sched_context *con)
169 {
170         int ms;
171
172         DEBUG(ast_debug(1, "ast_sched_wait()\n"));
173
174         ast_mutex_lock(&con->lock);
175         if (AST_DLLIST_EMPTY(&con->schedq)) {
176                 ms = -1;
177         } else {
178                 ms = ast_tvdiff_ms(AST_DLLIST_FIRST(&con->schedq)->when, ast_tvnow());
179                 if (ms < 0)
180                         ms = 0;
181         }
182         ast_mutex_unlock(&con->lock);
183
184         return ms;
185 }
186
187
188 /*! \brief
189  * Take a sched structure and put it in the
190  * queue, such that the soonest event is
191  * first in the list. 
192  */
193 static void schedule(struct sched_context *con, struct sched *s)
194 {
195         struct sched *cur = NULL;
196         int ret;
197         int df = 0;
198         int de = 0;
199         struct sched *first = AST_DLLIST_FIRST(&con->schedq);
200         struct sched *last = AST_DLLIST_LAST(&con->schedq);
201
202         if (first)
203                 df = ast_tvdiff_us(s->when, first->when);
204         if (last)
205                 de = ast_tvdiff_us(s->when, last->when);
206
207         if (df < 0)
208                 df = -df;
209         if (de < 0)
210                 de = -de;
211
212         if (df < de) {
213                 AST_DLLIST_TRAVERSE(&con->schedq, cur, list) {
214                         if (ast_tvcmp(s->when, cur->when) == -1) {
215                                 AST_DLLIST_INSERT_BEFORE(&con->schedq, cur, s, list);
216                                 break;
217                         }
218                 }
219                 if (!cur) {
220                         AST_DLLIST_INSERT_TAIL(&con->schedq, s, list);
221                 }
222         } else {
223                 AST_DLLIST_TRAVERSE_BACKWARDS(&con->schedq, cur, list) {
224                         if (ast_tvcmp(s->when, cur->when) == 1) {
225                                 AST_DLLIST_INSERT_AFTER(&con->schedq, cur, s, list);
226                                 break;
227                         }
228                 }
229                 if (!cur) {
230                         AST_DLLIST_INSERT_HEAD(&con->schedq, s, list);
231                 }
232         }
233
234         ret = ast_hashtab_insert_safe(con->schedq_ht, s);
235         if (!ret)
236                 ast_log(LOG_WARNING,"Schedule Queue entry %d is already in table!\n",s->id);
237
238         con->schedcnt++;
239
240         if (con->schedcnt > con->highwater)
241                 con->highwater = con->schedcnt;
242 }
243
244 /*! \brief
245  * given the last event *tv and the offset in milliseconds 'when',
246  * computes the next value,
247  */
248 static int sched_settime(struct timeval *t, int when)
249 {
250         struct timeval now = ast_tvnow();
251
252         /*ast_debug(1, "TV -> %lu,%lu\n", tv->tv_sec, tv->tv_usec);*/
253         if (ast_tvzero(*t))     /* not supplied, default to now */
254                 *t = now;
255         *t = ast_tvadd(*t, ast_samp2tv(when, 1000));
256         if (ast_tvcmp(*t, now) < 0) {
257                 ast_debug(1, "Request to schedule in the past?!?!\n");
258                 *t = now;
259         }
260         return 0;
261 }
262
263 int ast_sched_replace_variable(int old_id, struct sched_context *con, int when, ast_sched_cb callback, const void *data, int variable)
264 {
265         /* 0 means the schedule item is new; do not delete */
266         if (old_id > 0) {
267                 AST_SCHED_DEL(con, old_id);
268         }
269         return ast_sched_add_variable(con, when, callback, data, variable);
270 }
271
272 /*! \brief
273  * Schedule callback(data) to happen when ms into the future
274  */
275 int ast_sched_add_variable(struct sched_context *con, int when, ast_sched_cb callback, const void *data, int variable)
276 {
277         struct sched *tmp;
278         int res = -1;
279         DEBUG(ast_debug(1, "ast_sched_add()\n"));
280         if (!when) {
281                 ast_log(LOG_NOTICE, "Scheduled event in 0 ms?\n");
282                 return -1;
283         }
284         ast_mutex_lock(&con->lock);
285         if ((tmp = sched_alloc(con))) {
286                 tmp->id = con->eventcnt++;
287                 tmp->callback = callback;
288                 tmp->data = data;
289                 tmp->resched = when;
290                 tmp->variable = variable;
291                 tmp->when = ast_tv(0, 0);
292                 if (sched_settime(&tmp->when, when)) {
293                         sched_release(con, tmp);
294                 } else {
295                         schedule(con, tmp);
296                         res = tmp->id;
297                 }
298         }
299 #ifdef DUMP_SCHEDULER
300         /* Dump contents of the context while we have the lock so nothing gets screwed up by accident. */
301         if (option_debug)
302                 ast_sched_dump(con);
303 #endif
304         ast_mutex_unlock(&con->lock);
305         return res;
306 }
307
308 int ast_sched_replace(int old_id, struct sched_context *con, int when, ast_sched_cb callback, const void *data)
309 {
310         if (old_id > -1) {
311                 AST_SCHED_DEL(con, old_id);
312         }
313         return ast_sched_add(con, when, callback, data);
314 }
315
316 int ast_sched_add(struct sched_context *con, int when, ast_sched_cb callback, const void *data)
317 {
318         return ast_sched_add_variable(con, when, callback, data, 0);
319 }
320
321 const void *ast_sched_find_data(struct sched_context *con, int id)
322 {
323         struct sched tmp,*res;
324         tmp.id = id;
325         res = ast_hashtab_lookup(con->schedq_ht, &tmp);
326         if (res)
327                 return res->data;
328         return NULL;
329 }
330         
331 /*! \brief
332  * Delete the schedule entry with number
333  * "id".  It's nearly impossible that there
334  * would be two or more in the list with that
335  * id.
336  */
337 #ifndef AST_DEVMODE
338 int ast_sched_del(struct sched_context *con, int id)
339 #else
340 int _ast_sched_del(struct sched_context *con, int id, const char *file, int line, const char *function)
341 #endif
342 {
343         struct sched *s, tmp;
344
345         DEBUG(ast_debug(1, "ast_sched_del(%d)\n", id));
346         
347         ast_mutex_lock(&con->lock);
348
349         /* OK, this is the heart of the sched performance upgrade.
350            If we have 4700 peers, we can have 4700+ entries in the
351            schedq list. searching this would take time. So, I add a 
352            hashtab to the context to keep track of each entry, by id.
353            I also leave the linked list alone, almost, --  I implement
354        a doubly-linked list instead, because it would do little good
355            to look up the id in a hashtab, and then have to run thru 
356            a couple thousand entries to remove it from the schedq list! */
357         tmp.id = id;
358         s = ast_hashtab_lookup(con->schedq_ht, &tmp);
359         if (s) {
360                 struct sched *x = AST_DLLIST_REMOVE(&con->schedq, s, list);
361                 
362                 if (!x)
363                         ast_log(LOG_WARNING,"sched entry %d not in the schedq list?\n", s->id);
364
365                 if (!ast_hashtab_remove_this_object(con->schedq_ht, s))
366                         ast_log(LOG_WARNING,"Found sched entry %d, then couldn't remove it?\n", s->id);
367                 con->schedcnt--;
368                 sched_release(con, s);
369         }
370         
371 #ifdef DUMP_SCHEDULER
372         /* Dump contents of the context while we have the lock so nothing gets screwed up by accident. */
373         if (option_debug)
374                 ast_sched_dump(con);
375 #endif
376         ast_mutex_unlock(&con->lock);
377
378         if (!s) {
379                 ast_debug(1, "Attempted to delete nonexistent schedule entry %d!\n", id);
380 #ifndef AST_DEVMODE
381                 ast_assert(s != NULL);
382 #else
383                 _ast_assert(0, "s != NULL", file, line, function);
384 #endif
385                 return -1;
386         }
387         
388         return 0;
389 }
390
391
392 char *ast_sched_report(struct sched_context *con, char *buf, int bufsiz, struct ast_cb_names *cbnames)
393 {
394         int *countlist,i;
395         struct sched *cur;
396         char buf2[1200];
397         ast_sched_cb xxx = NULL;
398         
399         buf[0] = 0;
400         sprintf(buf, " Highwater = %d\n schedcnt = %d\n", con->highwater, con->schedcnt);
401         countlist = ast_calloc(sizeof(int),cbnames->numassocs+1);
402         
403         AST_DLLIST_TRAVERSE(&con->schedq, cur, list) {
404                 /* match the callback to the cblist */
405                 for (i=0;i<cbnames->numassocs;i++) {
406                         if (cur->callback == cbnames->cblist[i])
407                                 break;
408                 }
409                 if (i < cbnames->numassocs)
410                         countlist[i]++;
411                 else {
412                         xxx = cur->callback;
413                         countlist[cbnames->numassocs]++;
414                 }
415         }
416         for (i=0;i<cbnames->numassocs;i++) {
417                 sprintf(buf2,"    %s : %d\n", cbnames->list[i], countlist[i]);
418                 strcat(buf, buf2);
419         }
420         sprintf(buf2,"   <unknown:%p> : %d\n", xxx, countlist[cbnames->numassocs]);
421         strcat( buf, buf2);
422         return buf;
423 }
424
425
426         
427 /*! \brief Dump the contents of the scheduler to LOG_DEBUG */
428 void ast_sched_dump(const struct sched_context *con)
429 {
430         struct sched *q;
431         struct timeval when = ast_tvnow();
432 #ifdef SCHED_MAX_CACHE
433         ast_debug(1, "Asterisk Schedule Dump (%d in Q, %d Total, %d Cache, %d high-water)\n", con->schedcnt, con->eventcnt - 1, con->schedccnt, con->highwater);
434 #else
435         ast_debug(1, "Asterisk Schedule Dump (%d in Q, %d Total, %d high-water)\n", con->schedcnt, con->eventcnt - 1, con->highwater);
436 #endif
437
438         ast_debug(1, "=============================================================\n");
439         ast_debug(1, "|ID    Callback          Data              Time  (sec:ms)   |\n");
440         ast_debug(1, "+-----+-----------------+-----------------+-----------------+\n");
441         AST_DLLIST_TRAVERSE(&con->schedq, q, list) {
442                 struct timeval delta = ast_tvsub(q->when, when);
443
444                 ast_debug(1, "|%.4d | %-15p | %-15p | %.6ld : %.6ld |\n", 
445                         q->id,
446                         q->callback,
447                         q->data,
448                         (long)delta.tv_sec,
449                         (long int)delta.tv_usec);
450         }
451         ast_debug(1, "=============================================================\n");
452         
453 }
454
455 /*! \brief
456  * Launch all events which need to be run at this time.
457  */
458 int ast_sched_runq(struct sched_context *con)
459 {
460         struct sched *current;
461         struct timeval when;
462         int numevents;
463         int res;
464
465         DEBUG(ast_debug(1, "ast_sched_runq()\n"));
466                 
467         ast_mutex_lock(&con->lock);
468
469         for (numevents = 0; !AST_DLLIST_EMPTY(&con->schedq); numevents++) {
470                 /* schedule all events which are going to expire within 1ms.
471                  * We only care about millisecond accuracy anyway, so this will
472                  * help us get more than one event at one time if they are very
473                  * close together.
474                  */
475                 when = ast_tvadd(ast_tvnow(), ast_tv(0, 1000));
476                 if (ast_tvcmp(AST_DLLIST_FIRST(&con->schedq)->when, when) != -1)
477                         break;
478                 
479                 current = AST_DLLIST_REMOVE_HEAD(&con->schedq, list);
480                 if (!ast_hashtab_remove_this_object(con->schedq_ht, current))
481                         ast_log(LOG_ERROR,"Sched entry %d was in the schedq list but not in the hashtab???\n", current->id);
482
483                 con->schedcnt--;
484
485                 /*
486                  * At this point, the schedule queue is still intact.  We
487                  * have removed the first event and the rest is still there,
488                  * so it's permissible for the callback to add new events, but
489                  * trying to delete itself won't work because it isn't in
490                  * the schedule queue.  If that's what it wants to do, it 
491                  * should return 0.
492                  */
493                         
494                 ast_mutex_unlock(&con->lock);
495                 res = current->callback(current->data);
496                 ast_mutex_lock(&con->lock);
497                         
498                 if (res) {
499                         /*
500                          * If they return non-zero, we should schedule them to be
501                          * run again.
502                          */
503                         if (sched_settime(&current->when, current->variable? res : current->resched)) {
504                                 sched_release(con, current);
505                         } else
506                                 schedule(con, current);
507                 } else {
508                         /* No longer needed, so release it */
509                         sched_release(con, current);
510                 }
511         }
512
513         ast_mutex_unlock(&con->lock);
514         
515         return numevents;
516 }
517
518 long ast_sched_when(struct sched_context *con,int id)
519 {
520         struct sched *s, tmp;
521         long secs = -1;
522         DEBUG(ast_debug(1, "ast_sched_when()\n"));
523
524         ast_mutex_lock(&con->lock);
525         
526         /* these next 2 lines replace a lookup loop */
527         tmp.id = id;
528         s = ast_hashtab_lookup(con->schedq_ht, &tmp);
529         
530         if (s) {
531                 struct timeval now = ast_tvnow();
532                 secs = s->when.tv_sec - now.tv_sec;
533         }
534         ast_mutex_unlock(&con->lock);
535         
536         return secs;
537 }