Sat Mar 10 01:54:26 2012

Asterisk developer's documentation


sched.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2008, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief Scheduler Routines (from cheops-NG)
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  */
00025 
00026 #include "asterisk.h"
00027 
00028 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 281575 $")
00029 
00030 #ifdef DEBUG_SCHEDULER
00031 #define DEBUG(a) do { \
00032    if (option_debug) \
00033       DEBUG_M(a) \
00034    } while (0)
00035 #else
00036 #define DEBUG(a) 
00037 #endif
00038 
00039 #include <sys/time.h>
00040 
00041 #include "asterisk/sched.h"
00042 #include "asterisk/channel.h"
00043 #include "asterisk/lock.h"
00044 #include "asterisk/utils.h"
00045 #include "asterisk/linkedlists.h"
00046 #include "asterisk/dlinkedlists.h"
00047 #include "asterisk/hashtab.h"
00048 #include "asterisk/heap.h"
00049 #include "asterisk/threadstorage.h"
00050 
00051 AST_THREADSTORAGE(last_del_id);
00052 
00053 struct sched {
00054    AST_LIST_ENTRY(sched) list;
00055    int id;                       /*!< ID number of event */
00056    struct timeval when;          /*!< Absolute time event should take place */
00057    int resched;                  /*!< When to reschedule */
00058    int variable;                 /*!< Use return value from callback to reschedule */
00059    const void *data;             /*!< Data */
00060    ast_sched_cb callback;        /*!< Callback */
00061    ssize_t __heap_index;
00062 };
00063 
00064 struct sched_context {
00065    ast_mutex_t lock;
00066    unsigned int eventcnt;                  /*!< Number of events processed */
00067    unsigned int schedcnt;                  /*!< Number of outstanding schedule events */
00068    unsigned int highwater;             /*!< highest count so far */
00069    struct ast_hashtab *schedq_ht;             /*!< hash table for fast searching */
00070    struct ast_heap *sched_heap;
00071 
00072 #ifdef SCHED_MAX_CACHE
00073    AST_LIST_HEAD_NOLOCK(, sched) schedc;   /*!< Cache of unused schedule structures and how many */
00074    unsigned int schedccnt;
00075 #endif
00076 };
00077 
00078 struct ast_sched_thread {
00079    pthread_t thread;
00080    ast_mutex_t lock;
00081    ast_cond_t cond;
00082    struct sched_context *context;
00083    unsigned int stop:1;
00084 };
00085 
00086 static void *sched_run(void *data)
00087 {
00088    struct ast_sched_thread *st = data;
00089 
00090    while (!st->stop) {
00091       int ms;
00092       struct timespec ts = {
00093          .tv_sec = 0,   
00094       };
00095 
00096       ast_mutex_lock(&st->lock);
00097 
00098       if (st->stop) {
00099          ast_mutex_unlock(&st->lock);
00100          return NULL;
00101       }
00102 
00103       ms = ast_sched_wait(st->context);
00104 
00105       if (ms == -1) {
00106          ast_cond_wait(&st->cond, &st->lock);
00107       } else { 
00108          struct timeval tv;
00109          tv = ast_tvadd(ast_tvnow(), ast_samp2tv(ms, 1000));
00110          ts.tv_sec = tv.tv_sec;
00111          ts.tv_nsec = tv.tv_usec * 1000;
00112          ast_cond_timedwait(&st->cond, &st->lock, &ts);
00113       }
00114 
00115       ast_mutex_unlock(&st->lock);
00116 
00117       if (st->stop) {
00118          return NULL;
00119       }
00120 
00121       ast_sched_runq(st->context);
00122    }
00123 
00124    return NULL;
00125 }
00126 
00127 void ast_sched_thread_poke(struct ast_sched_thread *st)
00128 {
00129    ast_mutex_lock(&st->lock);
00130    ast_cond_signal(&st->cond);
00131    ast_mutex_unlock(&st->lock);
00132 }
00133 
00134 struct sched_context *ast_sched_thread_get_context(struct ast_sched_thread *st)
00135 {
00136    return st->context;
00137 }
00138 
00139 struct ast_sched_thread *ast_sched_thread_destroy(struct ast_sched_thread *st)
00140 {
00141    if (st->thread != AST_PTHREADT_NULL) {
00142       ast_mutex_lock(&st->lock);
00143       st->stop = 1;
00144       ast_cond_signal(&st->cond);
00145       ast_mutex_unlock(&st->lock);
00146       pthread_join(st->thread, NULL);
00147       st->thread = AST_PTHREADT_NULL;
00148    }
00149 
00150    ast_mutex_destroy(&st->lock);
00151    ast_cond_destroy(&st->cond);
00152 
00153    if (st->context) {
00154       sched_context_destroy(st->context);
00155       st->context = NULL;
00156    }
00157 
00158    ast_free(st);
00159 
00160    return NULL;
00161 }
00162 
00163 struct ast_sched_thread *ast_sched_thread_create(void)
00164 {
00165    struct ast_sched_thread *st;
00166 
00167    if (!(st = ast_calloc(1, sizeof(*st)))) {
00168       return NULL;
00169    }
00170 
00171    ast_mutex_init(&st->lock);
00172    ast_cond_init(&st->cond, NULL);
00173 
00174    st->thread = AST_PTHREADT_NULL;
00175 
00176    if (!(st->context = sched_context_create())) {
00177       ast_log(LOG_ERROR, "Failed to create scheduler\n");
00178       ast_sched_thread_destroy(st);
00179       return NULL;
00180    }
00181    
00182    if (ast_pthread_create_background(&st->thread, NULL, sched_run, st)) {
00183       ast_log(LOG_ERROR, "Failed to create scheduler thread\n");
00184       ast_sched_thread_destroy(st);
00185       return NULL;
00186    }
00187 
00188    return st;
00189 }
00190 
00191 int ast_sched_thread_add_variable(struct ast_sched_thread *st, int when, ast_sched_cb cb,
00192       const void *data, int variable)
00193 {
00194    int res;
00195 
00196    ast_mutex_lock(&st->lock);
00197    res = ast_sched_add_variable(st->context, when, cb, data, variable);
00198    if (res != -1) {
00199       ast_cond_signal(&st->cond);
00200    }
00201    ast_mutex_unlock(&st->lock);
00202 
00203    return res;
00204 }
00205 
00206 int ast_sched_thread_add(struct ast_sched_thread *st, int when, ast_sched_cb cb,
00207       const void *data)
00208 {
00209    int res;
00210 
00211    ast_mutex_lock(&st->lock);
00212    res = ast_sched_add(st->context, when, cb, data);
00213    if (res != -1) {
00214       ast_cond_signal(&st->cond);
00215    }
00216    ast_mutex_unlock(&st->lock);
00217 
00218    return res;
00219 }
00220 
00221 /* hash routines for sched */
00222 
00223 static int sched_cmp(const void *a, const void *b)
00224 {
00225    const struct sched *as = a;
00226    const struct sched *bs = b;
00227    return as->id != bs->id; /* return 0 on a match like strcmp would */
00228 }
00229 
00230 static unsigned int sched_hash(const void *obj)
00231 {
00232    const struct sched *s = obj;
00233    unsigned int h = s->id;
00234    return h;
00235 }
00236 
00237 static int sched_time_cmp(void *a, void *b)
00238 {
00239    return ast_tvcmp(((struct sched *) b)->when, ((struct sched *) a)->when);
00240 }
00241 
00242 struct sched_context *sched_context_create(void)
00243 {
00244    struct sched_context *tmp;
00245 
00246    if (!(tmp = ast_calloc(1, sizeof(*tmp))))
00247       return NULL;
00248 
00249    ast_mutex_init(&tmp->lock);
00250    tmp->eventcnt = 1;
00251 
00252    tmp->schedq_ht = ast_hashtab_create(23, sched_cmp, ast_hashtab_resize_java, ast_hashtab_newsize_java, sched_hash, 1);
00253 
00254    if (!(tmp->sched_heap = ast_heap_create(8, sched_time_cmp,
00255          offsetof(struct sched, __heap_index)))) {
00256       sched_context_destroy(tmp);
00257       return NULL;
00258    }
00259 
00260    return tmp;
00261 }
00262 
00263 void sched_context_destroy(struct sched_context *con)
00264 {
00265    struct sched *s;
00266 
00267    ast_mutex_lock(&con->lock);
00268 
00269 #ifdef SCHED_MAX_CACHE
00270    /* Eliminate the cache */
00271    while ((s = AST_LIST_REMOVE_HEAD(&con->schedc, list)))
00272       ast_free(s);
00273 #endif
00274 
00275    if (con->sched_heap) {
00276       while ((s = ast_heap_pop(con->sched_heap))) {
00277          ast_free(s);
00278       }
00279       ast_heap_destroy(con->sched_heap);
00280       con->sched_heap = NULL;
00281    }
00282 
00283    ast_hashtab_destroy(con->schedq_ht, NULL);
00284    con->schedq_ht = NULL;
00285    
00286    /* And the context */
00287    ast_mutex_unlock(&con->lock);
00288    ast_mutex_destroy(&con->lock);
00289    ast_free(con);
00290 }
00291 
00292 static struct sched *sched_alloc(struct sched_context *con)
00293 {
00294    struct sched *tmp;
00295 
00296    /*
00297     * We keep a small cache of schedule entries
00298     * to minimize the number of necessary malloc()'s
00299     */
00300 #ifdef SCHED_MAX_CACHE
00301    if ((tmp = AST_LIST_REMOVE_HEAD(&con->schedc, list)))
00302       con->schedccnt--;
00303    else
00304 #endif
00305       tmp = ast_calloc(1, sizeof(*tmp));
00306 
00307    return tmp;
00308 }
00309 
00310 static void sched_release(struct sched_context *con, struct sched *tmp)
00311 {
00312    /*
00313     * Add to the cache, or just free() if we
00314     * already have too many cache entries
00315     */
00316 
00317 #ifdef SCHED_MAX_CACHE   
00318    if (con->schedccnt < SCHED_MAX_CACHE) {
00319       AST_LIST_INSERT_HEAD(&con->schedc, tmp, list);
00320       con->schedccnt++;
00321    } else
00322 #endif
00323       ast_free(tmp);
00324 }
00325 
00326 /*! \brief
00327  * Return the number of milliseconds 
00328  * until the next scheduled event
00329  */
00330 int ast_sched_wait(struct sched_context *con)
00331 {
00332    int ms;
00333    struct sched *s;
00334 
00335    DEBUG(ast_debug(1, "ast_sched_wait()\n"));
00336 
00337    ast_mutex_lock(&con->lock);
00338    if ((s = ast_heap_peek(con->sched_heap, 1))) {
00339       ms = ast_tvdiff_ms(s->when, ast_tvnow());
00340       if (ms < 0) {
00341          ms = 0;
00342       }
00343    } else {
00344       ms = -1;
00345    }
00346    ast_mutex_unlock(&con->lock);
00347 
00348    return ms;
00349 }
00350 
00351 
00352 /*! \brief
00353  * Take a sched structure and put it in the
00354  * queue, such that the soonest event is
00355  * first in the list. 
00356  */
00357 static void schedule(struct sched_context *con, struct sched *s)
00358 {
00359    ast_heap_push(con->sched_heap, s);
00360 
00361    if (!ast_hashtab_insert_safe(con->schedq_ht, s)) {
00362       ast_log(LOG_WARNING,"Schedule Queue entry %d is already in table!\n", s->id);
00363    }
00364 
00365    con->schedcnt++;
00366 
00367    if (con->schedcnt > con->highwater) {
00368       con->highwater = con->schedcnt;
00369    }
00370 }
00371 
00372 /*! \brief
00373  * given the last event *tv and the offset in milliseconds 'when',
00374  * computes the next value,
00375  */
00376 static int sched_settime(struct timeval *t, int when)
00377 {
00378    struct timeval now = ast_tvnow();
00379 
00380    /*ast_debug(1, "TV -> %lu,%lu\n", tv->tv_sec, tv->tv_usec);*/
00381    if (ast_tvzero(*t))  /* not supplied, default to now */
00382       *t = now;
00383    *t = ast_tvadd(*t, ast_samp2tv(when, 1000));
00384    if (ast_tvcmp(*t, now) < 0) {
00385       *t = now;
00386    }
00387    return 0;
00388 }
00389 
00390 int ast_sched_replace_variable(int old_id, struct sched_context *con, int when, ast_sched_cb callback, const void *data, int variable)
00391 {
00392    /* 0 means the schedule item is new; do not delete */
00393    if (old_id > 0) {
00394       AST_SCHED_DEL(con, old_id);
00395    }
00396    return ast_sched_add_variable(con, when, callback, data, variable);
00397 }
00398 
00399 /*! \brief
00400  * Schedule callback(data) to happen when ms into the future
00401  */
00402 int ast_sched_add_variable(struct sched_context *con, int when, ast_sched_cb callback, const void *data, int variable)
00403 {
00404    struct sched *tmp;
00405    int res = -1;
00406 
00407    DEBUG(ast_debug(1, "ast_sched_add()\n"));
00408 
00409    ast_mutex_lock(&con->lock);
00410    if ((tmp = sched_alloc(con))) {
00411       tmp->id = con->eventcnt++;
00412       tmp->callback = callback;
00413       tmp->data = data;
00414       tmp->resched = when;
00415       tmp->variable = variable;
00416       tmp->when = ast_tv(0, 0);
00417       if (sched_settime(&tmp->when, when)) {
00418          sched_release(con, tmp);
00419       } else {
00420          schedule(con, tmp);
00421          res = tmp->id;
00422       }
00423    }
00424 #ifdef DUMP_SCHEDULER
00425    /* Dump contents of the context while we have the lock so nothing gets screwed up by accident. */
00426    if (option_debug)
00427       ast_sched_dump(con);
00428 #endif
00429    ast_mutex_unlock(&con->lock);
00430 
00431    return res;
00432 }
00433 
00434 int ast_sched_replace(int old_id, struct sched_context *con, int when, ast_sched_cb callback, const void *data)
00435 {
00436    if (old_id > -1) {
00437       AST_SCHED_DEL(con, old_id);
00438    }
00439    return ast_sched_add(con, when, callback, data);
00440 }
00441 
00442 int ast_sched_add(struct sched_context *con, int when, ast_sched_cb callback, const void *data)
00443 {
00444    return ast_sched_add_variable(con, when, callback, data, 0);
00445 }
00446 
00447 const void *ast_sched_find_data(struct sched_context *con, int id)
00448 {
00449    struct sched tmp,*res;
00450    tmp.id = id;
00451    res = ast_hashtab_lookup(con->schedq_ht, &tmp);
00452    if (res)
00453       return res->data;
00454    return NULL;
00455 }
00456 
00457 /*! \brief
00458  * Delete the schedule entry with number
00459  * "id".  It's nearly impossible that there
00460  * would be two or more in the list with that
00461  * id.
00462  */
00463 #ifndef AST_DEVMODE
00464 int ast_sched_del(struct sched_context *con, int id)
00465 #else
00466 int _ast_sched_del(struct sched_context *con, int id, const char *file, int line, const char *function)
00467 #endif
00468 {
00469    struct sched *s, tmp = {
00470       .id = id,
00471    };
00472    int *last_id = ast_threadstorage_get(&last_del_id, sizeof(int *));
00473 
00474    DEBUG(ast_debug(1, "ast_sched_del(%d)\n", id));
00475 
00476    if (id < 0) {
00477       return 0;
00478    }
00479 
00480    ast_mutex_lock(&con->lock);
00481    s = ast_hashtab_lookup(con->schedq_ht, &tmp);
00482    if (s) {
00483       if (!ast_heap_remove(con->sched_heap, s)) {
00484          ast_log(LOG_WARNING,"sched entry %d not in the sched heap?\n", s->id);
00485       }
00486 
00487       if (!ast_hashtab_remove_this_object(con->schedq_ht, s)) {
00488          ast_log(LOG_WARNING,"Found sched entry %d, then couldn't remove it?\n", s->id);
00489       }
00490 
00491       con->schedcnt--;
00492 
00493       sched_release(con, s);
00494    }
00495 
00496 #ifdef DUMP_SCHEDULER
00497    /* Dump contents of the context while we have the lock so nothing gets screwed up by accident. */
00498    if (option_debug)
00499       ast_sched_dump(con);
00500 #endif
00501    ast_mutex_unlock(&con->lock);
00502 
00503    if (!s && *last_id != id) {
00504       ast_debug(1, "Attempted to delete nonexistent schedule entry %d!\n", id);
00505 #ifndef AST_DEVMODE
00506       ast_assert(s != NULL);
00507 #else
00508       {
00509       char buf[100];
00510       snprintf(buf, sizeof(buf), "s != NULL, id=%d", id);
00511       _ast_assert(0, buf, file, line, function);
00512       }
00513 #endif
00514       *last_id = id;
00515       return -1;
00516    } else if (!s) {
00517       return -1;
00518    }
00519 
00520    return 0;
00521 }
00522 
00523 void ast_sched_report(struct sched_context *con, struct ast_str **buf, struct ast_cb_names *cbnames)
00524 {
00525    int i, x;
00526    struct sched *cur;
00527    int countlist[cbnames->numassocs + 1];
00528    size_t heap_size;
00529    
00530    memset(countlist, 0, sizeof(countlist));
00531    ast_str_set(buf, 0, " Highwater = %d\n schedcnt = %d\n", con->highwater, con->schedcnt);
00532 
00533    ast_mutex_lock(&con->lock);
00534 
00535    heap_size = ast_heap_size(con->sched_heap);
00536    for (x = 1; x <= heap_size; x++) {
00537       cur = ast_heap_peek(con->sched_heap, x);
00538       /* match the callback to the cblist */
00539       for (i = 0; i < cbnames->numassocs; i++) {
00540          if (cur->callback == cbnames->cblist[i]) {
00541             break;
00542          }
00543       }
00544       if (i < cbnames->numassocs) {
00545          countlist[i]++;
00546       } else {
00547          countlist[cbnames->numassocs]++;
00548       }
00549    }
00550 
00551    ast_mutex_unlock(&con->lock);
00552 
00553    for (i = 0; i < cbnames->numassocs; i++) {
00554       ast_str_append(buf, 0, "    %s : %d\n", cbnames->list[i], countlist[i]);
00555    }
00556 
00557    ast_str_append(buf, 0, "   <unknown> : %d\n", countlist[cbnames->numassocs]);
00558 }
00559    
00560 /*! \brief Dump the contents of the scheduler to LOG_DEBUG */
00561 void ast_sched_dump(struct sched_context *con)
00562 {
00563    struct sched *q;
00564    struct timeval when = ast_tvnow();
00565    int x;
00566    size_t heap_size;
00567 #ifdef SCHED_MAX_CACHE
00568    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);
00569 #else
00570    ast_debug(1, "Asterisk Schedule Dump (%d in Q, %d Total, %d high-water)\n", con->schedcnt, con->eventcnt - 1, con->highwater);
00571 #endif
00572 
00573    ast_debug(1, "=============================================================\n");
00574    ast_debug(1, "|ID    Callback          Data              Time  (sec:ms)   |\n");
00575    ast_debug(1, "+-----+-----------------+-----------------+-----------------+\n");
00576    ast_mutex_lock(&con->lock);
00577    heap_size = ast_heap_size(con->sched_heap);
00578    for (x = 1; x <= heap_size; x++) {
00579       struct timeval delta;
00580       q = ast_heap_peek(con->sched_heap, x);
00581       delta = ast_tvsub(q->when, when);
00582       ast_debug(1, "|%.4d | %-15p | %-15p | %.6ld : %.6ld |\n", 
00583          q->id,
00584          q->callback,
00585          q->data,
00586          (long)delta.tv_sec,
00587          (long int)delta.tv_usec);
00588    }
00589    ast_mutex_unlock(&con->lock);
00590    ast_debug(1, "=============================================================\n");
00591 }
00592 
00593 /*! \brief
00594  * Launch all events which need to be run at this time.
00595  */
00596 int ast_sched_runq(struct sched_context *con)
00597 {
00598    struct sched *current;
00599    struct timeval when;
00600    int numevents;
00601    int res;
00602 
00603    DEBUG(ast_debug(1, "ast_sched_runq()\n"));
00604       
00605    ast_mutex_lock(&con->lock);
00606 
00607    when = ast_tvadd(ast_tvnow(), ast_tv(0, 1000));
00608    for (numevents = 0; (current = ast_heap_peek(con->sched_heap, 1)); numevents++) {
00609       /* schedule all events which are going to expire within 1ms.
00610        * We only care about millisecond accuracy anyway, so this will
00611        * help us get more than one event at one time if they are very
00612        * close together.
00613        */
00614       if (ast_tvcmp(current->when, when) != -1) {
00615          break;
00616       }
00617       
00618       current = ast_heap_pop(con->sched_heap);
00619 
00620       if (!ast_hashtab_remove_this_object(con->schedq_ht, current)) {
00621          ast_log(LOG_ERROR,"Sched entry %d was in the schedq list but not in the hashtab???\n", current->id);
00622       }
00623 
00624       con->schedcnt--;
00625 
00626       /*
00627        * At this point, the schedule queue is still intact.  We
00628        * have removed the first event and the rest is still there,
00629        * so it's permissible for the callback to add new events, but
00630        * trying to delete itself won't work because it isn't in
00631        * the schedule queue.  If that's what it wants to do, it 
00632        * should return 0.
00633        */
00634          
00635       ast_mutex_unlock(&con->lock);
00636       res = current->callback(current->data);
00637       ast_mutex_lock(&con->lock);
00638          
00639       if (res) {
00640          /*
00641           * If they return non-zero, we should schedule them to be
00642           * run again.
00643           */
00644          if (sched_settime(&current->when, current->variable? res : current->resched)) {
00645             sched_release(con, current);
00646          } else {
00647             schedule(con, current);
00648          }
00649       } else {
00650          /* No longer needed, so release it */
00651          sched_release(con, current);
00652       }
00653    }
00654 
00655    ast_mutex_unlock(&con->lock);
00656    
00657    return numevents;
00658 }
00659 
00660 long ast_sched_when(struct sched_context *con,int id)
00661 {
00662    struct sched *s, tmp;
00663    long secs = -1;
00664    DEBUG(ast_debug(1, "ast_sched_when()\n"));
00665 
00666    ast_mutex_lock(&con->lock);
00667    
00668    /* these next 2 lines replace a lookup loop */
00669    tmp.id = id;
00670    s = ast_hashtab_lookup(con->schedq_ht, &tmp);
00671    
00672    if (s) {
00673       struct timeval now = ast_tvnow();
00674       secs = s->when.tv_sec - now.tv_sec;
00675    }
00676    ast_mutex_unlock(&con->lock);
00677    
00678    return secs;
00679 }

Generated on Sat Mar 10 01:54:26 2012 for Asterisk - The Open Source Telephony Project by  doxygen 1.4.7