issue #5622
[asterisk/asterisk.git] / 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  */
24
25 #ifdef DEBUG_SCHEDULER
26 #define DEBUG(a) DEBUG_M(a)
27 #else
28 #define DEBUG(a) 
29 #endif
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <sys/time.h>
34 #include <unistd.h>
35 #include <string.h>
36
37 #include "asterisk.h"
38
39 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
40
41 #include "asterisk/sched.h"
42 #include "asterisk/logger.h"
43 #include "asterisk/channel.h"
44 #include "asterisk/lock.h"
45 #include "asterisk/utils.h"
46
47 /* Determine if a is sooner than b */
48 #define SOONER(a,b) (((b).tv_sec > (a).tv_sec) || \
49                                          (((b).tv_sec == (a).tv_sec) && ((b).tv_usec > (a).tv_usec)))
50
51 struct sched {
52         struct sched *next;             /* Next event in the list */
53         int id;                         /* ID number of event */
54         struct timeval when;            /* Absolute time event should take place */
55         int resched;                    /* When to reschedule */
56         int variable;           /* Use return value from callback to reschedule */
57         void *data;                     /* Data */
58         ast_sched_cb callback;          /* Callback */
59 };
60
61 struct sched_context {
62         ast_mutex_t lock;
63         /* Number of events processed */
64         int eventcnt;
65
66         /* Number of outstanding schedule events */
67         int schedcnt;
68
69         /* Schedule entry and main queue */
70         struct sched *schedq;
71
72 #ifdef SCHED_MAX_CACHE
73         /* Cache of unused schedule structures and how many */
74         struct sched *schedc;
75         int schedccnt;
76 #endif
77 };
78
79 struct sched_context *sched_context_create(void)
80 {
81         struct sched_context *tmp;
82         tmp = malloc(sizeof(struct sched_context));
83         if (tmp) {
84                 memset(tmp, 0, sizeof(struct sched_context));
85                 ast_mutex_init(&tmp->lock);
86                 tmp->eventcnt = 1;
87                 tmp->schedcnt = 0;
88                 tmp->schedq = NULL;
89 #ifdef SCHED_MAX_CACHE
90                 tmp->schedc = NULL;
91                 tmp->schedccnt = 0;
92 #endif
93         }
94         return tmp;
95 }
96
97 void sched_context_destroy(struct sched_context *con)
98 {
99         struct sched *s, *sl;
100         ast_mutex_lock(&con->lock);
101 #ifdef SCHED_MAX_CACHE
102         /* Eliminate the cache */
103         s = con->schedc;
104         while(s) {
105                 sl = s;
106                 s = s->next;
107                 free(sl);
108         }
109 #endif
110         /* And the queue */
111         s = con->schedq;
112         while(s) {
113                 sl = s;
114                 s = s->next;
115                 free(sl);
116         }
117         /* And the context */
118         ast_mutex_unlock(&con->lock);
119         ast_mutex_destroy(&con->lock);
120         free(con);
121 }
122
123 static struct sched *sched_alloc(struct sched_context *con)
124 {
125         /*
126          * We keep a small cache of schedule entries
127          * to minimize the number of necessary malloc()'s
128          */
129         struct sched *tmp;
130 #ifdef SCHED_MAX_CACHE
131         if (con->schedc) {
132                 tmp = con->schedc;
133                 con->schedc = con->schedc->next;
134                 con->schedccnt--;
135         } else
136 #endif
137                 tmp = malloc(sizeof(struct sched));
138         return tmp;
139 }
140
141 static void sched_release(struct sched_context *con, struct sched *tmp)
142 {
143         /*
144          * Add to the cache, or just free() if we
145          * already have too many cache entries
146          */
147
148 #ifdef SCHED_MAX_CACHE   
149         if (con->schedccnt < SCHED_MAX_CACHE) {
150                 tmp->next = con->schedc;
151                 con->schedc = tmp;
152                 con->schedccnt++;
153         } else
154 #endif
155                 free(tmp);
156 }
157
158 int ast_sched_wait(struct sched_context *con)
159 {
160         /*
161          * Return the number of milliseconds 
162          * until the next scheduled event
163          */
164         int ms;
165         DEBUG(ast_log(LOG_DEBUG, "ast_sched_wait()\n"));
166         ast_mutex_lock(&con->lock);
167         if (!con->schedq) {
168                 ms = -1;
169         } else {
170                 ms = ast_tvdiff_ms(con->schedq->when, ast_tvnow());
171                 if (ms < 0)
172                         ms = 0;
173         }
174         ast_mutex_unlock(&con->lock);
175         return ms;
176         
177 }
178
179
180 static void schedule(struct sched_context *con, struct sched *s)
181 {
182         /*
183          * Take a sched structure and put it in the
184          * queue, such that the soonest event is
185          * first in the list. 
186          */
187          
188         struct sched *last=NULL;
189         struct sched *current=con->schedq;
190         while(current) {
191                 if (SOONER(s->when, current->when))
192                         break;
193                 last = current;
194                 current = current->next;
195         }
196         /* Insert this event into the schedule */
197         s->next = current;
198         if (last) 
199                 last->next = s;
200         else
201                 con->schedq = s;
202         con->schedcnt++;
203 }
204
205 /*
206  * given the last event *tv and the offset in milliseconds 'when',
207  * computes the next value,
208  */
209 static int sched_settime(struct timeval *tv, int when)
210 {
211         struct timeval now = ast_tvnow();
212
213         /*ast_log(LOG_DEBUG, "TV -> %lu,%lu\n", tv->tv_sec, tv->tv_usec);*/
214         if (ast_tvzero(*tv))    /* not supplied, default to now */
215                 *tv = now;
216         *tv = ast_tvadd(*tv, ast_samp2tv(when, 1000));
217         if (ast_tvcmp(*tv, now) < 0) {
218                 ast_log(LOG_DEBUG, "Request to schedule in the past?!?!\n");
219                 *tv = now;
220         }
221         return 0;
222 }
223
224
225 int ast_sched_add_variable(struct sched_context *con, int when, ast_sched_cb callback, void *data, int variable)
226 {
227         /*
228          * Schedule callback(data) to happen when ms into the future
229          */
230         struct sched *tmp;
231         int res = -1;
232         DEBUG(ast_log(LOG_DEBUG, "ast_sched_add()\n"));
233         if (!when) {
234                 ast_log(LOG_NOTICE, "Scheduled event in 0 ms?\n");
235                 return -1;
236         }
237         ast_mutex_lock(&con->lock);
238         if ((tmp = sched_alloc(con))) {
239                 tmp->id = con->eventcnt++;
240                 tmp->callback = callback;
241                 tmp->data = data;
242                 tmp->resched = when;
243                 tmp->variable = variable;
244                 tmp->when = ast_tv(0, 0);
245                 if (sched_settime(&tmp->when, when)) {
246                         sched_release(con, tmp);
247                 } else {
248                         schedule(con, tmp);
249                         res = tmp->id;
250                 }
251         }
252 #ifdef DUMP_SCHEDULER
253         /* Dump contents of the context while we have the lock so nothing gets screwed up by accident. */
254         ast_sched_dump(con);
255 #endif
256         ast_mutex_unlock(&con->lock);
257         return res;
258 }
259
260 int ast_sched_add(struct sched_context *con, int when, ast_sched_cb callback, void *data)
261 {
262         return ast_sched_add_variable(con, when, callback, data, 0);
263 }
264
265 int ast_sched_del(struct sched_context *con, int id)
266 {
267         /*
268          * Delete the schedule entry with number
269          * "id".  It's nearly impossible that there
270          * would be two or more in the list with that
271          * id.
272          */
273         struct sched *last=NULL, *s;
274         DEBUG(ast_log(LOG_DEBUG, "ast_sched_del()\n"));
275         ast_mutex_lock(&con->lock);
276         s = con->schedq;
277         while(s) {
278                 if (s->id == id) {
279                         if (last)
280                                 last->next = s->next;
281                         else
282                                 con->schedq = s->next;
283                         con->schedcnt--;
284                         sched_release(con, s);
285                         break;
286                 }
287                 last = s;
288                 s = s->next;
289         }
290 #ifdef DUMP_SCHEDULER
291         /* Dump contents of the context while we have the lock so nothing gets screwed up by accident. */
292         ast_sched_dump(con);
293 #endif
294         ast_mutex_unlock(&con->lock);
295         if (!s) {
296                 ast_log(LOG_NOTICE, "Attempted to delete nonexistent schedule entry %d!\n", id);
297 #ifdef DO_CRASH
298                 CRASH;
299 #endif
300                 return -1;
301         } else
302                 return 0;
303 }
304
305 void ast_sched_dump(const struct sched_context *con)
306 {
307         /*
308          * Dump the contents of the scheduler to
309          * stderr
310          */
311         struct sched *q;
312         struct timeval tv = ast_tvnow();
313 #ifdef SCHED_MAX_CACHE
314         ast_log(LOG_DEBUG, "Asterisk Schedule Dump (%d in Q, %d Total, %d Cache)\n", con->schedcnt, con->eventcnt - 1, con->schedccnt);
315 #else
316         ast_log(LOG_DEBUG, "Asterisk Schedule Dump (%d in Q, %d Total)\n", con->schedcnt, con->eventcnt - 1);
317 #endif
318
319         ast_log(LOG_DEBUG, "=============================================================\n");
320         ast_log(LOG_DEBUG, "|ID    Callback          Data              Time  (sec:ms)   |\n");
321         ast_log(LOG_DEBUG, "+-----+-----------------+-----------------+-----------------+\n");
322         for (q = con->schedq; q; q = q->next) {
323                 struct timeval delta =  ast_tvsub(q->when, tv);
324
325                 ast_log(LOG_DEBUG, "|%.4d | %-15p | %-15p | %.6ld : %.6ld |\n", 
326                         q->id,
327                         q->callback,
328                         q->data,
329                         delta.tv_sec,
330                         (long int)delta.tv_usec);
331         }
332         ast_log(LOG_DEBUG, "=============================================================\n");
333         
334 }
335
336 int ast_sched_runq(struct sched_context *con)
337 {
338         /*
339          * Launch all events which need to be run at this time.
340          */
341         struct sched *current;
342         struct timeval tv;
343         int x=0;
344         int res;
345         DEBUG(ast_log(LOG_DEBUG, "ast_sched_runq()\n"));
346                 
347         ast_mutex_lock(&con->lock);
348         for(;;) {
349                 if (!con->schedq)
350                         break;
351                 
352                 /* schedule all events which are going to expire within 1ms.
353                  * We only care about millisecond accuracy anyway, so this will
354                  * help us get more than one event at one time if they are very
355                  * close together.
356                  */
357                 tv = ast_tvadd(ast_tvnow(), ast_tv(0, 1000));
358                 if (SOONER(con->schedq->when, tv)) {
359                         current = con->schedq;
360                         con->schedq = con->schedq->next;
361                         con->schedcnt--;
362
363                         /*
364                          * At this point, the schedule queue is still intact.  We
365                          * have removed the first event and the rest is still there,
366                          * so it's permissible for the callback to add new events, but
367                          * trying to delete itself won't work because it isn't in
368                          * the schedule queue.  If that's what it wants to do, it 
369                          * should return 0.
370                          */
371                         
372                         ast_mutex_unlock(&con->lock);
373                         res = current->callback(current->data);
374                         ast_mutex_lock(&con->lock);
375                         
376                         if (res) {
377                                 /*
378                                  * If they return non-zero, we should schedule them to be
379                                  * run again.
380                                  */
381                                 if (sched_settime(&current->when, current->variable? res : current->resched)) {
382                                         sched_release(con, current);
383                                 } else
384                                         schedule(con, current);
385                         } else {
386                                 /* No longer needed, so release it */
387                                 sched_release(con, current);
388                         }
389                         x++;
390                 } else
391                         break;
392         }
393         ast_mutex_unlock(&con->lock);
394         return x;
395 }
396
397 long ast_sched_when(struct sched_context *con,int id)
398 {
399         struct sched *s;
400         long secs;
401         DEBUG(ast_log(LOG_DEBUG, "ast_sched_when()\n"));
402
403         ast_mutex_lock(&con->lock);
404         s=con->schedq;
405         while (s!=NULL) {
406                 if (s->id==id) break;
407                 s=s->next;
408         }
409         secs=-1;
410         if (s!=NULL) {
411                 struct timeval now = ast_tvnow();
412                 secs=s->when.tv_sec-now.tv_sec;
413         }
414         ast_mutex_unlock(&con->lock);
415         return secs;
416 }