Convert the PBX core to use read/write locks. This yields a nifty performance improve...
[asterisk/asterisk.git] / main / pbx.c
index 60a89e1..f129667 100644 (file)
@@ -160,7 +160,7 @@ struct ast_ignorepat {
 
 /*! \brief ast_context: An extension context */
 struct ast_context {
-       ast_mutex_t lock;                       /*!< A lock to prevent multiple threads from clobbering the context */
+       ast_rwlock_t lock;                      /*!< A lock to prevent multiple threads from clobbering the context */
        struct ast_exten *root;                 /*!< The root of the list of extensions */
        struct ast_context *next;               /*!< Link them together */
        struct ast_include *includes;           /*!< Include other contexts */
@@ -193,7 +193,9 @@ struct ast_state_cb {
 /*! \brief Structure for dial plan hints
 
   \note Hints are pointers from an extension in the dialplan to one or
-  more devices (tech/name) */
+  more devices (tech/name) 
+       - See \ref AstExtState
+*/
 struct ast_hint {
        struct ast_exten *exten;        /*!< Extension */
        int laststate;                  /*!< Last known state */
@@ -238,13 +240,13 @@ static int pbx_builtin_sayphonetic(struct ast_channel *, void *);
 int pbx_builtin_setvar(struct ast_channel *, void *);
 static int pbx_builtin_importvar(struct ast_channel *, void *);
 
-AST_MUTEX_DEFINE_STATIC(globalslock);
+AST_RWLOCK_DEFINE_STATIC(globalslock);
 static struct varshead globals = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
 
 static int autofallthrough = 1;
 
 AST_MUTEX_DEFINE_STATIC(maxcalllock);
-static int countcalls = 0;
+static int countcalls;
 
 static AST_RWLIST_HEAD_STATIC(acf_root, ast_custom_function);
 
@@ -263,7 +265,8 @@ static struct pbx_builtin {
        "Answer a channel if ringing",
        "  Answer([delay]): If the call has not been answered, this application will\n"
        "answer it. Otherwise, it has no effect on the call. If a delay is specified,\n"
-       "Asterisk will wait this number of milliseconds before answering the call.\n"
+       "Asterisk will wait this number of milliseconds before returning to\n"
+       "the dialplan after answering the call.\n"
        },
 
        { "BackGround", pbx_builtin_background,
@@ -320,8 +323,13 @@ static struct pbx_builtin {
        "calling channel to continue dialplan execution at the specified priority.\n"
        "If no specific extension, or extension and context, are specified, then this\n"
        "application will jump to the specified priority of the current extension.\n"
+       "  At least a priority is required as an argument, or the goto will return a -1,\n"
+       "and the channel and call will be terminated.\n"
        "  If the attempt to jump to another location in the dialplan is not successful,\n"
-       "then the channel will continue at the next priority of the current extension.\n"
+       "then the execution engine will try to find and execute the code in the 'i' (invalid)\n"
+       "extension in the current context. If that does not exist, it will try to execute the\n"
+       "'h' extension. If either or neither the 'h' or 'i' extensions have been defined, the\n"
+       "channel is hung up, and the execution of instructions on the channel is terminated.\n"
        },
 
        { "GotoIf", pbx_builtin_gotoif,
@@ -332,7 +340,12 @@ static struct pbx_builtin {
        "'labeliftrue' if the condition is true, or 'labeliffalse' if the condition is\n"
        "false. The labels are specified with the same syntax as used within the Goto\n"
        "application.  If the label chosen by the condition is omitted, no jump is\n"
-       "performed, but execution continues with the next priority in the dialplan.\n"
+       "performed, and the execution passes to the next instruction.\n"
+       "If the target location is bogus, and does not exist, the execution engine will try \n"
+       "to find and execute the code in the 'i' (invalid)\n"
+       "extension in the current context. If that does not exist, it will try to execute the\n"
+       "'h' extension. If either or neither the 'h' or 'i' extensions have been defined, the\n"
+       "channel is hung up, and the execution of instructions on the channel is terminated.\n"
        },
 
        { "GotoIfTime", pbx_builtin_gotoiftime,
@@ -340,6 +353,7 @@ static struct pbx_builtin {
        "  GotoIfTime(<times>|<weekdays>|<mdays>|<months>?[[context|]exten|]priority):\n"
        "This application will have the calling channel jump to the specified location\n"
        "in the dialplan if the current time matches the given time specification.\n"
+       "If the target jump location is bogus, the same actions would be taken as for Goto.\n"
        },
 
        { "ImportVar", pbx_builtin_importvar,
@@ -458,12 +472,12 @@ static struct pbx_builtin {
 
 };
 
-static struct ast_context *contexts = NULL;
-AST_MUTEX_DEFINE_STATIC(conlock);              /*!< Lock for the ast_context list */
+static struct ast_context *contexts;
+AST_RWLOCK_DEFINE_STATIC(conlock);             /*!< Lock for the ast_context list */
 
 static AST_RWLIST_HEAD_STATIC(apps, ast_app);
 
-static AST_LIST_HEAD_STATIC(switches, ast_switch);
+static AST_RWLIST_HEAD_STATIC(switches, ast_switch);
 
 static int stateid = 1;
 /* WARNING:
@@ -473,14 +487,14 @@ static int stateid = 1;
    paths that require both locks must also take them in that order.
 */
 static AST_RWLIST_HEAD_STATIC(hints, ast_hint);
-struct ast_state_cb *statecbs = NULL;
+struct ast_state_cb *statecbs;
 
 /*
    \note This function is special. It saves the stack so that no matter
    how many times it is called, it returns to the same place */
 int pbx_exec(struct ast_channel *c,            /*!< Channel */
-               struct ast_app *app,            /*!< Application */
-               void *data)                     /*!< Data for execution */
+            struct ast_app *app,               /*!< Application */
+            void *data)                        /*!< Data for execution */
 {
        int res;
 
@@ -534,12 +548,12 @@ static struct ast_switch *pbx_findswitch(const char *sw)
 {
        struct ast_switch *asw;
 
-       AST_LIST_LOCK(&switches);
-       AST_LIST_TRAVERSE(&switches, asw, list) {
+       AST_RWLIST_RDLOCK(&switches);
+       AST_RWLIST_TRAVERSE(&switches, asw, list) {
                if (!strcasecmp(asw->name, sw))
                        break;
        }
-       AST_LIST_UNLOCK(&switches);
+       AST_RWLIST_UNLOCK(&switches);
 
        return asw;
 }
@@ -861,12 +875,12 @@ int ast_extension_close(const char *pattern, const char *data, int needmore)
 struct ast_context *ast_context_find(const char *name)
 {
        struct ast_context *tmp = NULL;
-       ast_mutex_lock(&conlock);
+       ast_rdlock_contexts();
        while ( (tmp = ast_walk_contexts(tmp)) ) {
                if (!name || !strcasecmp(name, tmp->name))
                        break;
        }
-       ast_mutex_unlock(&conlock);
+       ast_unlock_contexts();
        return tmp;
 }
 
@@ -1094,7 +1108,7 @@ static char *substring(const char *value, int offset, int length, char *workspac
        return ret;
 }
 
-/*! \brief  Support for Asterisk built-in variables and functions in the dialplan
+/*! \brief  Support for Asterisk built-in variables in the dialplan
 
 \note  See also
        - \ref AstVar   Channel variables
@@ -1188,7 +1202,7 @@ void pbx_retrieve_variable(struct ast_channel *c, const char *var, char **ret, c
                if (!places[i])
                        continue;
                if (places[i] == &globals)
-                       ast_mutex_lock(&globalslock);
+                       ast_rwlock_rdlock(&globalslock);
                AST_LIST_TRAVERSE(places[i], variables, entries) {
                        if (strcasecmp(ast_var_name(variables), var)==0) {
                                s = ast_var_value(variables);
@@ -1196,7 +1210,7 @@ void pbx_retrieve_variable(struct ast_channel *c, const char *var, char **ret, c
                        }
                }
                if (places[i] == &globals)
-                       ast_mutex_unlock(&globalslock);
+                       ast_rwlock_unlock(&globalslock);
        }
        if (s == &not_found || s == NULL)
                *ret = NULL;
@@ -1405,31 +1419,33 @@ static char *func_args(char *function)
        return args;
 }
 
-int ast_func_read(struct ast_channel *chan, char *function, char *workspace, size_t len)
+int ast_func_read(struct ast_channel *chan, const char *function, char *workspace, size_t len)
 {
-       char *args = func_args(function);
-       struct ast_custom_function *acfptr = ast_custom_function_find(function);
+       char *copy = ast_strdupa(function);
+       char *args = func_args(copy);
+       struct ast_custom_function *acfptr = ast_custom_function_find(copy);
 
        if (acfptr == NULL)
-               ast_log(LOG_ERROR, "Function %s not registered\n", function);
+               ast_log(LOG_ERROR, "Function %s not registered\n", copy);
        else if (!acfptr->read)
-               ast_log(LOG_ERROR, "Function %s cannot be read\n", function);
+               ast_log(LOG_ERROR, "Function %s cannot be read\n", copy);
        else
-               return acfptr->read(chan, function, args, workspace, len);
+               return acfptr->read(chan, copy, args, workspace, len);
        return -1;
 }
 
-int ast_func_write(struct ast_channel *chan, char *function, const char *value)
+int ast_func_write(struct ast_channel *chan, const char *function, const char *value)
 {
-       char *args = func_args(function);
-       struct ast_custom_function *acfptr = ast_custom_function_find(function);
+       char *copy = ast_strdupa(function);
+       char *args = func_args(copy);
+       struct ast_custom_function *acfptr = ast_custom_function_find(copy);
 
        if (acfptr == NULL)
-               ast_log(LOG_ERROR, "Function %s not registered\n", function);
+               ast_log(LOG_ERROR, "Function %s not registered\n", copy);
        else if (!acfptr->write)
-               ast_log(LOG_ERROR, "Function %s cannot be written to\n", function);
+               ast_log(LOG_ERROR, "Function %s cannot be written to\n", copy);
        else
-               return acfptr->write(chan, function, args, value);
+               return acfptr->write(chan, copy, args, value);
 
        return -1;
 }
@@ -1455,7 +1471,7 @@ static void pbx_substitute_variables_helper_full(struct ast_channel *c, struct v
                nextexp = NULL;
                nextthing = strchr(whereweare, '$');
                if (nextthing) {
-                       switch(nextthing[1]) {
+                       switch (nextthing[1]) {
                        case '{':
                                nextvar = nextthing;
                                pos = nextvar - whereweare;
@@ -1559,7 +1575,7 @@ static void pbx_substitute_variables_helper_full(struct ast_channel *c, struct v
                        needsub = 0;
 
                        /* Find the end of it */
-                       while(brackets && *vare) {
+                       while (brackets && *vare) {
                                if ((vare[0] == '$') && (vare[1] == '[')) {
                                        needsub++;
                                        brackets++;
@@ -1627,7 +1643,7 @@ static void pbx_substitute_variables(char *passdata, int datalen, struct ast_cha
        memset(passdata, 0, datalen);
 
        /* No variables or expressions in e->data, so why scan it? */
-       if (!strchr(e->data, '$') && !strstr(e->data,"${") && !strstr(e->data,"$[") && !strstr(e->data,"$(")) {
+       if (e->data && !strchr(e->data, '$') && !strstr(e->data,"${") && !strstr(e->data,"$[") && !strstr(e->data,"$(")) {
                ast_copy_string(passdata, e->data, datalen);
                return;
        }
@@ -1656,21 +1672,21 @@ static int pbx_extension_helper(struct ast_channel *c, struct ast_context *con,
 
        int matching_action = (action == E_MATCH || action == E_CANMATCH || action == E_MATCHMORE);
 
-       ast_mutex_lock(&conlock);
+       ast_rdlock_contexts();
        e = pbx_find_extension(c, con, &q, context, exten, priority, label, callerid, action);
        if (e) {
                if (matching_action) {
-                       ast_mutex_unlock(&conlock);
+                       ast_unlock_contexts();
                        return -1;      /* success, we found it */
                } else if (action == E_FINDLABEL) { /* map the label to a priority */
                        res = e->priority;
-                       ast_mutex_unlock(&conlock);
+                       ast_unlock_contexts();
                        return res;     /* the priority we were looking for */
                } else {        /* spawn */
                        if (!e->cached_app)
                                e->cached_app = pbx_findapp(e->app);
                        app = e->cached_app;
-                       ast_mutex_unlock(&conlock);
+                       ast_unlock_contexts();
                        if (!app) {
                                ast_log(LOG_WARNING, "No application '%s' for extension (%s, %s, %d)\n", e->app, context, exten, priority);
                                return -1;
@@ -1712,7 +1728,7 @@ static int pbx_extension_helper(struct ast_channel *c, struct ast_context *con,
                        return pbx_exec(c, app, passdata);      /* 0 on success, -1 on failure */
                }
        } else if (q.swo) {     /* not found here, but in another switch */
-               ast_mutex_unlock(&conlock);
+               ast_unlock_contexts();
                if (matching_action)
                        return -1;
                else {
@@ -1723,7 +1739,7 @@ static int pbx_extension_helper(struct ast_channel *c, struct ast_context *con,
                        return q.swo->exec(c, q.foundcontext ? q.foundcontext : context, exten, priority, callerid, q.data);
                }
        } else {        /* not found anywhere, see what happened */
-               ast_mutex_unlock(&conlock);
+               ast_unlock_contexts();
                switch (q.status) {
                case STATUS_NO_CONTEXT:
                        if (!matching_action)
@@ -1756,9 +1772,9 @@ static struct ast_exten *ast_hint_extension(struct ast_channel *c, const char *c
        struct ast_exten *e;
        struct pbx_find_info q = { .stacklen = 0 }; /* the rest is set in pbx_find_context */
 
-       ast_mutex_lock(&conlock);
+       ast_rdlock_contexts();
        e = pbx_find_extension(c, NULL, &q, context, exten, PRIORITY_HINT, NULL, "", E_MATCH);
-       ast_mutex_unlock(&conlock);
+       ast_unlock_contexts();
 
        return e;
 }
@@ -2398,7 +2414,7 @@ static int __ast_pbx_run(struct ast_channel *c)
                if (c->cdr && ast_opt_end_cdr_before_h_exten)
                        ast_cdr_end(c->cdr);
                set_ext_pri(c, "h", 1);
-               while(ast_exists_extension(c, c->context, c->exten, c->priority, c->cid.cid_num)) {
+               while (ast_exists_extension(c, c->context, c->exten, c->priority, c->cid.cid_num)) {
                        if ((res = ast_spawn_extension(c, c->context, c->exten, c->priority, c->cid.cid_num))) {
                                /* Something bad happened, or a hangup has been requested. */
                                if (option_debug)
@@ -2501,8 +2517,10 @@ enum ast_pbx_result ast_pbx_start(struct ast_channel *c)
        pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
        if (ast_pthread_create(&t, &attr, pbx_thread, c)) {
                ast_log(LOG_WARNING, "Failed to create new channel thread\n");
+               pthread_attr_destroy(&attr);
                return AST_PBX_FAILED;
        }
+       pthread_attr_destroy(&attr);
 
        return AST_PBX_SUCCESS;
 }
@@ -2539,7 +2557,7 @@ static struct ast_context *find_context_locked(const char *context)
 {
        struct ast_context *c = NULL;
 
-       ast_lock_contexts();
+       ast_rdlock_contexts();
        while ( (c = ast_walk_contexts(c)) ) {
                if (!strcmp(ast_get_context_name(c), context))
                        return c;
@@ -2580,7 +2598,7 @@ int ast_context_remove_include2(struct ast_context *con, const char *include, co
        struct ast_include *i, *pi = NULL;
        int ret = -1;
 
-       ast_mutex_lock(&con->lock);
+       ast_wrlock_context(con);
 
        /* find our include */
        for (i = con->includes; i; pi = i, i = i->next) {
@@ -2598,7 +2616,8 @@ int ast_context_remove_include2(struct ast_context *con, const char *include, co
                }
        }
 
-       ast_mutex_unlock(&con->lock);
+       ast_unlock_context(con);
+
        return ret;
 }
 
@@ -2633,7 +2652,7 @@ int ast_context_remove_switch2(struct ast_context *con, const char *sw, const ch
        struct ast_sw *i;
        int ret = -1;
 
-       ast_mutex_lock(&con->lock);
+       ast_wrlock_context(con);
 
        /* walk switches */
        AST_LIST_TRAVERSE_SAFE_BEGIN(&con->alts, i, list) {
@@ -2648,7 +2667,7 @@ int ast_context_remove_switch2(struct ast_context *con, const char *sw, const ch
        }
        AST_LIST_TRAVERSE_SAFE_END
 
-       ast_mutex_unlock(&con->lock);
+       ast_unlock_context(con);
 
        return ret;
 }
@@ -2685,7 +2704,7 @@ int ast_context_remove_extension2(struct ast_context *con, const char *extension
        struct ast_exten *exten, *prev_exten = NULL;
        struct ast_exten *peer;
 
-       ast_mutex_lock(&con->lock);
+       ast_wrlock_context(con);
 
        /* scan the extension list to find matching extension-registrar */
        for (exten = con->root; exten; prev_exten = exten, exten = exten->next) {
@@ -2695,7 +2714,7 @@ int ast_context_remove_extension2(struct ast_context *con, const char *extension
        }
        if (!exten) {
                /* we can't find right extension */
-               ast_mutex_unlock(&con->lock);
+               ast_unlock_context(con);
                return -1;
        }
 
@@ -2722,7 +2741,7 @@ int ast_context_remove_extension2(struct ast_context *con, const char *extension
                                break; /* found our priority */
                }
                if (!peer) { /* not found */
-                       ast_mutex_unlock(&con->lock);
+                       ast_unlock_context(con);
                        return -1;
                }
                /* we are first priority extension? */
@@ -2747,7 +2766,7 @@ int ast_context_remove_extension2(struct ast_context *con, const char *extension
                destroy_exten(peer);
                /* XXX should we return -1 ? */
        }
-       ast_mutex_unlock(&con->lock);
+       ast_unlock_context(con);
        return 0;
 }
 
@@ -2762,7 +2781,7 @@ int ast_context_lockmacro(const char *context)
        struct ast_context *c = NULL;
        int ret = -1;
 
-       ast_lock_contexts();
+       ast_rdlock_contexts();
 
        while ((c = ast_walk_contexts(c))) {
                if (!strcmp(ast_get_context_name(c), context)) {
@@ -2790,7 +2809,7 @@ int ast_context_unlockmacro(const char *context)
        struct ast_context *c = NULL;
        int ret = -1;
 
-       ast_lock_contexts();
+       ast_rdlock_contexts();
 
        while ((c = ast_walk_contexts(c))) {
                if (!strcmp(ast_get_context_name(c), context)) {
@@ -2863,25 +2882,25 @@ int ast_register_switch(struct ast_switch *sw)
 {
        struct ast_switch *tmp;
 
-       AST_LIST_LOCK(&switches);
-       AST_LIST_TRAVERSE(&switches, tmp, list) {
+       AST_RWLIST_WRLOCK(&switches);
+       AST_RWLIST_TRAVERSE(&switches, tmp, list) {
                if (!strcasecmp(tmp->name, sw->name)) {
-                       AST_LIST_UNLOCK(&switches);
+                       AST_RWLIST_UNLOCK(&switches);
                        ast_log(LOG_WARNING, "Switch '%s' already found\n", sw->name);
                        return -1;
                }
        }
-       AST_LIST_INSERT_TAIL(&switches, sw, list);
-       AST_LIST_UNLOCK(&switches);
+       AST_RWLIST_INSERT_TAIL(&switches, sw, list);
+       AST_RWLIST_UNLOCK(&switches);
 
        return 0;
 }
 
 void ast_unregister_switch(struct ast_switch *sw)
 {
-       AST_LIST_LOCK(&switches);
-       AST_LIST_REMOVE(&switches, sw, list);
-       AST_LIST_UNLOCK(&switches);
+       AST_RWLIST_WRLOCK(&switches);
+       AST_RWLIST_REMOVE(&switches, sw, list);
+       AST_RWLIST_UNLOCK(&switches);
 }
 
 /*
@@ -3063,19 +3082,19 @@ static int handle_show_switches(int fd, int argc, char *argv[])
 {
        struct ast_switch *sw;
 
-       AST_LIST_LOCK(&switches);
+       AST_RWLIST_RDLOCK(&switches);
 
-       if (AST_LIST_EMPTY(&switches)) {
-               AST_LIST_UNLOCK(&switches);
+       if (AST_RWLIST_EMPTY(&switches)) {
+               AST_RWLIST_UNLOCK(&switches);
                ast_cli(fd, "There are no registered alternative switches\n");
                return RESULT_SUCCESS;
        }
 
        ast_cli(fd, "\n    -= Registered Asterisk Alternative Switches =-\n");
-       AST_LIST_TRAVERSE(&switches, sw, list)
+       AST_RWLIST_TRAVERSE(&switches, sw, list)
                ast_cli(fd, "%s: %s\n", sw->name, sw->description);
 
-       AST_LIST_UNLOCK(&switches);
+       AST_RWLIST_UNLOCK(&switches);
 
        return RESULT_SUCCESS;
 }
@@ -3171,7 +3190,7 @@ static char *complete_show_dialplan_context(const char *line, const char *word,
        if (pos != 2)
                return NULL;
 
-       ast_lock_contexts();
+       ast_rdlock_contexts();
 
        wordlen = strlen(word);
 
@@ -3218,7 +3237,7 @@ static int show_dialplan_helper(int fd, const char *context, const char *exten,
        struct ast_context *c = NULL;
        int res = 0, old_total_exten = dpc->total_exten;
 
-       ast_lock_contexts();
+       ast_rdlock_contexts();
 
        /* walk all contexts ... */
        while ( (c = ast_walk_contexts(c)) ) {
@@ -3233,7 +3252,7 @@ static int show_dialplan_helper(int fd, const char *context, const char *exten,
 
                dpc->context_existence = 1;
 
-               ast_lock_context(c);
+               ast_rdlock_context(c);
 
                /* are we looking for exten too? if yes, we print context
                 * only if we find our extension.
@@ -3420,21 +3439,22 @@ static int handle_show_dialplan(int fd, int argc, char *argv[])
 }
 
 /*! \brief Send ack once */
-static void manager_dpsendack(struct mansession *s, struct message *m, int *sentack)
+static void manager_dpsendack(struct mansession *s, const struct message *m)
 {
-       if (*sentack)
-               return;
        astman_send_listack(s, m, "DialPlan list will follow", "start");
-       *sentack = 1;
-       return;
 }
 
-/*! \brief Show dialplan extensions */
-static int manager_show_dialplan_helper(struct mansession *s, struct message *m, char *actionidtext, char *context, char *exten, struct dialplan_counters *dpc, struct ast_include *rinclude)
+/*! \brief Show dialplan extensions
+ * XXX this function is similar but not exactly the same as the CLI's
+ * show dialplan. Must check whether the difference is intentional or not.
+ */
+static int manager_show_dialplan_helper(struct mansession *s, const struct message *m,
+                                       const char *actionidtext, const char *context,
+                                       const char *exten, struct dialplan_counters *dpc,
+                                       struct ast_include *rinclude)
 {
        struct ast_context *c;
        int res=0, old_total_exten = dpc->total_exten;
-       int sentpositivemanagerack = 0;
 
        if (ast_strlen_zero(exten))
                exten = NULL;
@@ -3445,143 +3465,121 @@ static int manager_show_dialplan_helper(struct mansession *s, struct message *m,
                ast_log(LOG_DEBUG, "manager_show_dialplan: Context: -%s- Extension: -%s-\n", context, exten);
 
        /* try to lock contexts */
-       if (ast_lock_contexts()) {
+       if (ast_rdlock_contexts()) {
                astman_send_error(s, m, "Failed to lock contexts\r\n");
                ast_log(LOG_WARNING, "Failed to lock contexts list for manager: listdialplan\n");
                return -1;
        }
 
-       /* walk all contexts ... */
-       for (c = ast_walk_contexts(NULL); c ; c = ast_walk_contexts(c)) {
-               /* show this context? */
-               if (!context ||
-                       !strcmp(ast_get_context_name(c), context)) {
-                       dpc->context_existence = 1;
+       c = NULL;               /* walk all contexts ... */
+       while ( (c = ast_walk_contexts(c)) ) {
+               struct ast_exten *e;
+               struct ast_include *i;
+               struct ast_ignorepat *ip;
+
+               if (context && strcmp(ast_get_context_name(c), context) != 0)
+                       continue;       /* not the name we want */
+
+               dpc->context_existence = 1;
+
+               if (option_debug > 2)
+                       ast_log(LOG_DEBUG, "manager_show_dialplan: Found Context: %s \n", ast_get_context_name(c));
 
+               if (ast_rdlock_context(c)) {    /* failed to lock */
                        if (option_debug > 2)
-                               ast_log(LOG_DEBUG, "manager_show_dialplan: Found Context: %s \n", ast_get_context_name(c));
-
-                       /* try to lock context before walking in ... */
-                       if (!ast_lock_context(c)) {
-                               struct ast_exten *e;
-                               struct ast_include *i;
-                               struct ast_ignorepat *ip;
-                               struct ast_sw *sw;
-                               char buf[256], buf2[256];
-
-                               /* walk extensions in context  */
-                               for (e = ast_walk_context_extensions(c, NULL); e; e = ast_walk_context_extensions(c, e)) {
-                                       struct ast_exten *p;
-                                       int prio;
-
-                                       /* looking for extension? is this our extension? */
-                                       if (exten &&
-                                               !ast_extension_match(ast_get_extension_name(e), exten))
-                                       {
-                                               if (option_debug > 2)
-                                                       ast_log(LOG_DEBUG, "manager_show_dialplan: Skipping extension %s\n", ast_get_extension_name(e));
-                                               /* we are looking for extension and it's not our
-                                                * extension, so skip to next extension */
-                                               continue;
-                                       }
-                                       if (option_debug > 2)
-                                               ast_log(LOG_DEBUG, "manager_show_dialplan: Found Extension: %s \n", ast_get_extension_name(e));
-
-                                       dpc->extension_existence = 1;
-
-                                       /* may we print context info? */        
-                                       dpc->total_context++;
-                                       dpc->total_prio++;
-
-                                       /* write extension name and first peer */       
-                                       bzero(buf, sizeof(buf));                
-                               
-                                       dpc->total_items++;
-                                       manager_dpsendack(s, m, &sentpositivemanagerack);
-                                       astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
-                                       astman_append(s, "Context: %s\r\nExtension: %s\r\n", ast_get_context_name(c), ast_get_extension_name(e) );
-
-                                       prio = ast_get_extension_priority(e);
-                                       if (prio == PRIORITY_HINT) {
-                                               astman_append(s, "Priority: hint\r\nApplication: %s\r\n", ast_get_extension_app(e));
-                                       } else {
-                                               astman_append(s, "Priority: %d\r\nApplication: %s\r\nAppData: %s\r\n", prio, ast_get_extension_app(e), (char *) ast_get_extension_app_data(e));
-                                       }
-                                       astman_append(s, "Registrar: %s\r\n\r\n", ast_get_extension_registrar(e));
-
-                                       dpc->total_exten++;
-
-                                       /* walk next extension peers */
-                                       for (p=ast_walk_extension_priorities(e, e); p; p=ast_walk_extension_priorities(e, p)) {
-                                               dpc->total_prio++;
-                                               bzero((void *)buf2, sizeof(buf2));
-                                               bzero((void *)buf, sizeof(buf));
-                                               dpc->total_items++;
-                                               manager_dpsendack(s, m, &sentpositivemanagerack);
-                                               astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
-                                               astman_append(s, "Context: %s\r\nExtension: %s\r\n", ast_get_context_name(c), ast_get_extension_name(e) );
-
-                                               if (ast_get_extension_label(p))
-                                                       astman_append(s, "ExtensionLabel: %s\r\n", ast_get_extension_label(p));
-                                               prio = ast_get_extension_priority(p);
-                                               if (prio == PRIORITY_HINT) {
-                                                       astman_append(s, "Priority: hint\r\nApplication: %s\r\n", ast_get_extension_app(p));
-                                               } else {
-                                                       astman_append(s, "Priority: %d\r\nApplication: %s\r\nAppData: %s\r\n", prio, ast_get_extension_app(p), (char *) ast_get_extension_app_data(p));
-                                               }
-                                               astman_append(s, "Registrar: %s\r\n\r\n", ast_get_extension_registrar(e));
-                                       }
-                               }
+                               ast_log(LOG_DEBUG, "manager_show_dialplan: Failed to lock context\n");
+                       continue;
+               }
 
-                               /* walk included and write info ... */
-                               for (i = ast_walk_context_includes(c, NULL); i; i = ast_walk_context_includes(c, i)) {
-                                       if (exten) {
-                                               /* Check all includes for the requested extension */
-                                               manager_show_dialplan_helper(s, m, actionidtext, (char *)ast_get_include_name(i), exten, dpc, i);
-                                       } else {
-                                               dpc->total_items++;
-                                               manager_dpsendack(s, m, &sentpositivemanagerack);
-                                               astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
-                                               astman_append(s, "Context: %s\r\nIncludeContext: %s\r\nRegistrar: %s\r\n", ast_get_context_name(c), ast_get_include_name(i), ast_get_include_registrar(i));
-                                               astman_append(s, "\r\n");
-                                               if (option_debug > 2)
-                                                       ast_log(LOG_DEBUG, "manager_show_dialplan: Found Included context: %s \n", buf);
-                                       }
-                               }
+               /* XXX note- an empty context is not printed */
+               e = NULL;               /* walk extensions in context  */
+               while ( (e = ast_walk_context_extensions(c, e)) ) {
+                       struct ast_exten *p;
 
-                               /* walk ignore patterns and write info ... */
-                               for (ip=ast_walk_context_ignorepats(c, NULL); ip; ip=ast_walk_context_ignorepats(c, ip)) {
-                                       const char *ipname = ast_get_ignorepat_name(ip);
-                                       char ignorepat[AST_MAX_EXTENSION];
-
-                                       snprintf(ignorepat, sizeof(ignorepat), "_%s.", ipname);
-                                       if ((!exten) || ast_extension_match(ignorepat, exten)) {
-                                               dpc->total_items++;
-                                               manager_dpsendack(s, m, &sentpositivemanagerack);
-                                               astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
-                                               astman_append(s, "Context: %s\r\nIgnorePattern: %s\r\nRegistrar: %s\r\n", ast_get_context_name(c), ipname, ast_get_ignorepat_registrar(ip));
-                                               astman_append(s, "\r\n");
-                                       }
-                               }
-                               if (!rinclude) {
-                                       for (sw = ast_walk_context_switches(c, NULL); sw; sw = ast_walk_context_switches(c, sw)) {
-                                               dpc->total_items++;
-                                               manager_dpsendack(s, m, &sentpositivemanagerack);
-                                               astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
-                                               astman_append(s, "Context: %s\r\nSwitch: %s/%s\r\nRegistrar: %s\r\n", ast_get_context_name(c), ast_get_switch_name(sw), ast_get_switch_data(sw), ast_get_switch_registrar(sw)); 
-                                               astman_append(s, "\r\n");
-                                               if (option_debug > 2)
-                                                       ast_log(LOG_DEBUG, "manager_show_dialplan: Found Switch : %s \n", buf);
-                                       }
+                       /* looking for extension? is this our extension? */
+                       if (exten && !ast_extension_match(ast_get_extension_name(e), exten)) {
+                               /* not the one we are looking for, continue */
+                               if (option_debug > 2)
+                                       ast_log(LOG_DEBUG, "manager_show_dialplan: Skipping extension %s\n", ast_get_extension_name(e));
+                               continue;
+                       }
+                       if (option_debug > 2)
+                               ast_log(LOG_DEBUG, "manager_show_dialplan: Found Extension: %s \n", ast_get_extension_name(e));
+
+                       dpc->extension_existence = 1;
+
+                       /* may we print context info? */        
+                       dpc->total_context++;
+                       dpc->total_exten++;
+
+                       p = NULL;               /* walk next extension peers */
+                       while ( (p = ast_walk_extension_priorities(e, p)) ) {
+                               int prio = ast_get_extension_priority(p);
+
+                               dpc->total_prio++;
+                               if (!dpc->total_items++)
+                                       manager_dpsendack(s, m);
+                               astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
+                               astman_append(s, "Context: %s\r\nExtension: %s\r\n", ast_get_context_name(c), ast_get_extension_name(e) );
+
+                               /* XXX maybe make this conditional, if p != e ? */
+                               if (ast_get_extension_label(p))
+                                       astman_append(s, "ExtensionLabel: %s\r\n", ast_get_extension_label(p));
+
+                               if (prio == PRIORITY_HINT) {
+                                       astman_append(s, "Priority: hint\r\nApplication: %s\r\n", ast_get_extension_app(p));
+                               } else {
+                                       astman_append(s, "Priority: %d\r\nApplication: %s\r\nAppData: %s\r\n", prio, ast_get_extension_app(p), (char *) ast_get_extension_app_data(p));
                                }
-       
-                               ast_unlock_context(c);
+                               astman_append(s, "Registrar: %s\r\n\r\n", ast_get_extension_registrar(e));
+                       }
+               }
 
-                       } else if (option_debug > 2) {
-                               ast_log(LOG_DEBUG, "manager_show_dialplan: Failed to lock context\n");
+               i = NULL;               /* walk included and write info ... */
+               while ( (i = ast_walk_context_includes(c, i)) ) {
+                       if (exten) {
+                               /* Check all includes for the requested extension */
+                               manager_show_dialplan_helper(s, m, actionidtext, ast_get_include_name(i), exten, dpc, i);
+                       } else {
+                               if (!dpc->total_items++)
+                                       manager_dpsendack(s, m);
+                               astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
+                               astman_append(s, "Context: %s\r\nIncludeContext: %s\r\nRegistrar: %s\r\n", ast_get_context_name(c), ast_get_include_name(i), ast_get_include_registrar(i));
+                               astman_append(s, "\r\n");
+                               if (option_debug > 2)
+                                       ast_log(LOG_DEBUG, "manager_show_dialplan: Found Included context: %s \n", ast_get_include_name(i));
                        }
                }
-       } 
+
+               ip = NULL;      /* walk ignore patterns and write info ... */
+               while ( (ip = ast_walk_context_ignorepats(c, ip)) ) {
+                       const char *ipname = ast_get_ignorepat_name(ip);
+                       char ignorepat[AST_MAX_EXTENSION];
+
+                       snprintf(ignorepat, sizeof(ignorepat), "_%s.", ipname);
+                       if (!exten || ast_extension_match(ignorepat, exten)) {
+                               if (!dpc->total_items++)
+                                       manager_dpsendack(s, m);
+                               astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
+                               astman_append(s, "Context: %s\r\nIgnorePattern: %s\r\nRegistrar: %s\r\n", ast_get_context_name(c), ipname, ast_get_ignorepat_registrar(ip));
+                               astman_append(s, "\r\n");
+                       }
+               }
+               if (!rinclude) {
+                       struct ast_sw *sw = NULL;
+                       while ( (sw = ast_walk_context_switches(c, sw)) ) {
+                               if (!dpc->total_items++)
+                                       manager_dpsendack(s, m);
+                               astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
+                               astman_append(s, "Context: %s\r\nSwitch: %s/%s\r\nRegistrar: %s\r\n", ast_get_context_name(c), ast_get_switch_name(sw), ast_get_switch_data(sw), ast_get_switch_registrar(sw)); 
+                               astman_append(s, "\r\n");
+                               if (option_debug > 2)
+                                       ast_log(LOG_DEBUG, "manager_show_dialplan: Found Switch : %s \n", ast_get_switch_name(sw));
+                       }
+               }
+
+               ast_unlock_context(c);
+       }
        ast_unlock_contexts();
 
        if (dpc->total_exten == old_total_exten) {
@@ -3595,10 +3593,10 @@ static int manager_show_dialplan_helper(struct mansession *s, struct message *m,
 }
 
 /*! \brief  Manager listing of dial plan */
-static int manager_show_dialplan(struct mansession *s, struct message *m)
+static int manager_show_dialplan(struct mansession *s, const struct message *m)
 {
-       char *exten = NULL, *context = NULL;
-       char *id = astman_get_header(m, "ActionID");
+       const char *exten, *context;
+       const char *id = astman_get_header(m, "ActionID");
        char idtext[256];
        int res;
 
@@ -3607,7 +3605,8 @@ static int manager_show_dialplan(struct mansession *s, struct message *m)
 
        if (id && !ast_strlen_zero(id))
                snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
-
+       else
+               idtext[0] = '\0';
 
        memset(&counters, 0, sizeof(counters));
 
@@ -3663,12 +3662,12 @@ static int handle_show_globals(int fd, int argc, char *argv[])
        int i = 0;
        struct ast_var_t *newvariable;
 
-       ast_mutex_lock(&globalslock);
+       ast_rwlock_rdlock(&globalslock);
        AST_LIST_TRAVERSE (&globals, newvariable, entries) {
                i++;
                ast_cli(fd, "   %s=%s\n", ast_var_name(newvariable), ast_var_value(newvariable));
        }
-       ast_mutex_unlock(&globalslock);
+       ast_rwlock_unlock(&globalslock);
        ast_cli(fd, "\n    -- %d variables\n", i);
 
        return RESULT_SUCCESS;
@@ -3733,7 +3732,7 @@ static void unreference_cached_app(struct ast_app *app)
        struct ast_context *context = NULL;
        struct ast_exten *eroot = NULL, *e = NULL;
 
-       ast_lock_contexts();
+       ast_rdlock_contexts();
        while ((context = ast_walk_contexts(context))) {
                while ((eroot = ast_walk_context_extensions(context, eroot))) {
                        while ((e = ast_walk_extension_priorities(eroot, e))) {
@@ -3774,7 +3773,7 @@ static struct ast_context *__ast_context_create(struct ast_context **extcontexts
        int length = sizeof(struct ast_context) + strlen(name) + 1;
 
        if (!extcontexts) {
-               ast_mutex_lock(&conlock);
+               ast_wrlock_contexts();
                local_contexts = &contexts;
        } else
                local_contexts = extcontexts;
@@ -3786,12 +3785,12 @@ static struct ast_context *__ast_context_create(struct ast_context **extcontexts
                                tmp = NULL;
                        }
                        if (!extcontexts)
-                               ast_mutex_unlock(&conlock);
+                               ast_unlock_contexts();
                        return tmp;
                }
        }
        if ((tmp = ast_calloc(1, length))) {
-               ast_mutex_init(&tmp->lock);
+               ast_rwlock_init(&tmp->lock);
                ast_mutex_init(&tmp->macrolock);
                strcpy(tmp->name, name);
                tmp->root = NULL;
@@ -3807,7 +3806,7 @@ static struct ast_context *__ast_context_create(struct ast_context **extcontexts
        }
 
        if (!extcontexts)
-               ast_mutex_unlock(&conlock);
+               ast_unlock_contexts();
        return tmp;
 }
 
@@ -3852,7 +3851,7 @@ void ast_merge_contexts_and_delete(struct ast_context **extcontexts, const char
           in addition, the locks _must_ be taken in this order, because there are already
           other code paths that use this order
        */
-       ast_mutex_lock(&conlock);
+       ast_wrlock_contexts();
        AST_RWLIST_WRLOCK(&hints);
 
        /* preserve all watchers for hints associated with this registrar */
@@ -3930,7 +3929,7 @@ void ast_merge_contexts_and_delete(struct ast_context **extcontexts, const char
        }
 
        AST_RWLIST_UNLOCK(&hints);
-       ast_mutex_unlock(&conlock);
+       ast_unlock_contexts();
 
        return;
 }
@@ -4234,13 +4233,13 @@ int ast_context_add_include2(struct ast_context *con, const char *value,
        new_include->next      = NULL;
        new_include->registrar = registrar;
 
-       ast_mutex_lock(&con->lock);
+       ast_wrlock_context(con);
 
        /* ... go to last include and check if context is already included too... */
        for (i = con->includes; i; i = i->next) {
                if (!strcasecmp(i->name, new_include->name)) {
                        free(new_include);
-                       ast_mutex_unlock(&con->lock);
+                       ast_unlock_context(con);
                        errno = EEXIST;
                        return -1;
                }
@@ -4254,7 +4253,8 @@ int ast_context_add_include2(struct ast_context *con, const char *value,
                con->includes = new_include;
        if (option_verbose > 2)
                ast_verbose(VERBOSE_PREFIX_3 "Including context '%s' in context '%s'\n", new_include->name, ast_get_context_name(con));
-       ast_mutex_unlock(&con->lock);
+
+       ast_unlock_context(con);
 
        return 0;
 }
@@ -4324,13 +4324,13 @@ int ast_context_add_switch2(struct ast_context *con, const char *value,
        new_sw->registrar = registrar;
 
        /* ... try to lock this context ... */
-       ast_mutex_lock(&con->lock);
+       ast_wrlock_context(con);
 
        /* ... go to last sw and check if context is already swd too... */
        AST_LIST_TRAVERSE(&con->alts, i, list) {
                if (!strcasecmp(i->name, new_sw->name) && !strcasecmp(i->data, new_sw->data)) {
                        free(new_sw);
-                       ast_mutex_unlock(&con->lock);
+                       ast_unlock_context(con);
                        errno = EEXIST;
                        return -1;
                }
@@ -4342,7 +4342,7 @@ int ast_context_add_switch2(struct ast_context *con, const char *value,
        if (option_verbose > 2)
                ast_verbose(VERBOSE_PREFIX_3 "Including switch '%s/%s' in context '%s'\n", new_sw->name, new_sw->data, ast_get_context_name(con));
 
-       ast_mutex_unlock(&con->lock);
+       ast_unlock_context(con);
 
        return 0;
 }
@@ -4367,7 +4367,7 @@ int ast_context_remove_ignorepat2(struct ast_context *con, const char *ignorepat
 {
        struct ast_ignorepat *ip, *ipl = NULL;
 
-       ast_mutex_lock(&con->lock);
+       ast_wrlock_context(con);
 
        for (ip = con->ignorepats; ip; ip = ip->next) {
                if (!strcmp(ip->pattern, ignorepat) &&
@@ -4379,13 +4379,13 @@ int ast_context_remove_ignorepat2(struct ast_context *con, const char *ignorepat
                                con->ignorepats = ip->next;
                                free(ip);
                        }
-                       ast_mutex_unlock(&con->lock);
+                       ast_unlock_context(con);
                        return 0;
                }
                ipl = ip;
        }
 
-       ast_mutex_unlock(&con->lock);
+       ast_unlock_context(con);
        errno = EINVAL;
        return -1;
 }
@@ -4420,12 +4420,12 @@ int ast_context_add_ignorepat2(struct ast_context *con, const char *value, const
        strcpy((char *)ignorepat->pattern, value);
        ignorepat->next = NULL;
        ignorepat->registrar = registrar;
-       ast_mutex_lock(&con->lock);
+       ast_wrlock_context(con);
        for (ignorepatc = con->ignorepats; ignorepatc; ignorepatc = ignorepatc->next) {
                ignorepatl = ignorepatc;
                if (!strcasecmp(ignorepatc->pattern, value)) {
                        /* Already there */
-                       ast_mutex_unlock(&con->lock);
+                       ast_unlock_context(con);
                        errno = EEXIST;
                        return -1;
                }
@@ -4434,7 +4434,7 @@ int ast_context_add_ignorepat2(struct ast_context *con, const char *value, const
                ignorepatl->next = ignorepat;
        else
                con->ignorepats = ignorepat;
-       ast_mutex_unlock(&con->lock);
+       ast_unlock_context(con);
        return 0;
 
 }
@@ -4554,7 +4554,7 @@ static int ext_strncpy(char *dst, const char *src, int len)
        int count=0;
 
        while (*src && (count < len - 1)) {
-               switch(*src) {
+               switch (*src) {
                case ' ':
                        /*      otherwise exten => [a-b],1,... doesn't work */
                        /*              case '-': */
@@ -4572,10 +4572,6 @@ static int ext_strncpy(char *dst, const char *src, int len)
        return count;
 }
 
-static void null_datad(void *foo)
-{
-}
-
 /*! \brief add the extension in the priority chain.
  * returns 0 on success, -1 on failure
  */
@@ -4597,7 +4593,8 @@ static int add_pri(struct ast_context *con, struct ast_exten *tmp,
                   replacement?  If so, replace, otherwise, bonk. */
                if (!replace) {
                        ast_log(LOG_WARNING, "Unable to register extension '%s', priority %d in '%s', already in use\n", tmp->exten, tmp->priority, con->name);
-                       tmp->datad(tmp->data);
+                       if (tmp->datad)
+                               tmp->datad(tmp->data);
                        free(tmp);
                        return -1;
                }
@@ -4615,7 +4612,8 @@ static int add_pri(struct ast_context *con, struct ast_exten *tmp,
                if (tmp->priority == PRIORITY_HINT)
                        ast_change_hint(e,tmp);
                /* Destroy the old one */
-               e->datad(e->data);
+               if (e->datad)
+                       e->datad(e->data);
                free(e);
        } else {        /* Slip ourselves in just before e */
                tmp->peer = e;
@@ -4681,12 +4679,12 @@ int ast_add_extension2(struct ast_context *con,
        /* if we are adding a hint, and there are global variables, and the hint
           contains variable references, then expand them
        */
-       ast_mutex_lock(&globalslock);
+       ast_rwlock_rdlock(&globalslock);
        if (priority == PRIORITY_HINT && AST_LIST_FIRST(&globals) && strstr(application, "${")) {
                pbx_substitute_variables_varshead(&globals, application, expand_buf, sizeof(expand_buf));
                application = expand_buf;
        }
-       ast_mutex_unlock(&globalslock);
+       ast_rwlock_unlock(&globalslock);
 
        length = sizeof(struct ast_exten);
        length += strlen(extension) + 1;
@@ -4699,8 +4697,6 @@ int ast_add_extension2(struct ast_context *con,
                length ++;      /* just the '\0' */
 
        /* Be optimistic:  Build the extension structure first */
-       if (datad == NULL)
-               datad = null_datad;
        if (!(tmp = ast_calloc(1, length)))
                return -1;
 
@@ -4729,7 +4725,7 @@ int ast_add_extension2(struct ast_context *con,
        tmp->datad = datad;
        tmp->registrar = registrar;
 
-       ast_mutex_lock(&con->lock);
+       ast_wrlock_context(con);
        res = 0; /* some compilers will think it is uninitialized otherwise */
        for (e = con->root; e; el = e, e = e->next) {   /* scan the extension list */
                res = ext_cmp(e->exten, extension);
@@ -4748,7 +4744,7 @@ int ast_add_extension2(struct ast_context *con,
        }
        if (e && res == 0) { /* exact match, insert in the pri chain */
                res = add_pri(con, tmp, el, e, replace);
-               ast_mutex_unlock(&con->lock);
+               ast_unlock_context(con);
                if (res < 0) {
                        errno = EEXIST; /* XXX do we care ? */
                        return 0; /* XXX should we return -1 maybe ? */
@@ -4763,17 +4759,19 @@ int ast_add_extension2(struct ast_context *con,
                        el->next = tmp;
                else
                        con->root = tmp;
-               ast_mutex_unlock(&con->lock);
+               ast_unlock_context(con);
                if (tmp->priority == PRIORITY_HINT)
                        ast_add_hint(tmp);
        }
        if (option_debug) {
                if (tmp->matchcid) {
-                       ast_log(LOG_DEBUG, "Added extension '%s' priority %d (CID match '%s') to %s\n",
-                               tmp->exten, tmp->priority, tmp->cidmatch, con->name);
+                       if (option_debug)
+                               ast_log(LOG_DEBUG, "Added extension '%s' priority %d (CID match '%s') to %s\n",
+                                       tmp->exten, tmp->priority, tmp->cidmatch, con->name);
                } else {
-                       ast_log(LOG_DEBUG, "Added extension '%s' priority %d to %s\n",
-                               tmp->exten, tmp->priority, con->name);
+                       if (option_debug)
+                               ast_log(LOG_DEBUG, "Added extension '%s' priority %d to %s\n",
+                                       tmp->exten, tmp->priority, con->name);
                }
        }
        if (option_verbose > 2) {
@@ -4898,7 +4896,15 @@ int ast_pbx_outgoing_exten(const char *type, int format, void *data, int timeout
        pthread_attr_t attr;
 
        if (sync) {
-               LOAD_OH(oh);
+               oh.context = context;
+               oh.exten = exten;
+               oh.priority = priority;
+               oh.cid_num = cid_num;
+               oh.cid_name = cid_name;
+               oh.account = account;
+               oh.vars = vars;
+               oh.parent_channel = NULL;
+
                chan = __ast_request_and_dial(type, format, data, timeout, reason, cid_num, cid_name, &oh);
                if (channel) {
                        *channel = chan;
@@ -4950,7 +4956,7 @@ int ast_pbx_outgoing_exten(const char *type, int format, void *data, int timeout
                                if (option_verbose > 3)
                                        ast_verbose(VERBOSE_PREFIX_4 "Channel %s was never answered.\n", chan->name);
 
-                               if(chan->cdr) { /* update the cdr */
+                               if (chan->cdr) { /* update the cdr */
                                        /* here we update the status of the call, which sould be busy.
                                         * if that fails then we set the status to failed */
                                        if (ast_cdr_disposition(chan->cdr, chan->hangupcause))
@@ -5024,8 +5030,10 @@ int ast_pbx_outgoing_exten(const char *type, int format, void *data, int timeout
                        }
                        ast_hangup(chan);
                        res = -1;
+                       pthread_attr_destroy(&attr);
                        goto outgoing_exten_cleanup;
                }
+               pthread_attr_destroy(&attr);
                res = 0;
        }
 outgoing_exten_cleanup:
@@ -5082,7 +5090,7 @@ int ast_pbx_outgoing_app(const char *type, int format, void *data, int timeout,
                                ast_log(LOG_WARNING, "%s already has a call record??\n", chan->name);
                        } else {
                                chan->cdr = ast_cdr_alloc();   /* allocate a cdr for the channel */
-                               if(!chan->cdr) {
+                               if (!chan->cdr) {
                                        /* allocation of the cdr failed */
                                        free(chan->pbx);
                                        res = -1;
@@ -5127,6 +5135,7 @@ int ast_pbx_outgoing_app(const char *type, int format, void *data, int timeout,
                                                        if (locked_channel)
                                                                *locked_channel = chan;
                                                }
+                                               pthread_attr_destroy(&attr);
                                        }
                                }
                        } else {
@@ -5185,11 +5194,13 @@ int ast_pbx_outgoing_app(const char *type, int format, void *data, int timeout,
                                ast_channel_unlock(chan);
                        ast_hangup(chan);
                        res = -1;
+                       pthread_attr_destroy(&attr);
                        goto outgoing_app_cleanup;
                } else {
                        if (locked_channel)
                                *locked_channel = chan;
                }
+               pthread_attr_destroy(&attr);
                res = 0;
        }
 outgoing_app_cleanup:
@@ -5205,7 +5216,7 @@ void __ast_context_destroy(struct ast_context *con, const char *registrar)
        struct ast_exten *e, *el, *en;
        struct ast_ignorepat *ipi;
 
-       ast_mutex_lock(&conlock);
+       ast_wrlock_contexts();
        for (tmp = contexts; tmp; ) {
                struct ast_context *next;       /* next starting point */
                for (; tmp; tmpl = tmp, tmp = tmp->next) {
@@ -5217,7 +5228,7 @@ void __ast_context_destroy(struct ast_context *con, const char *registrar)
                }
                if (!tmp)       /* not found, we are done */
                        break;
-               ast_mutex_lock(&tmp->lock);
+               ast_wrlock_context(tmp);
                if (option_debug)
                        ast_log(LOG_DEBUG, "delete ctx %s %s\n", tmp->name, tmp->registrar);
                next = tmp->next;
@@ -5227,7 +5238,7 @@ void __ast_context_destroy(struct ast_context *con, const char *registrar)
                        contexts = next;
                /* Okay, now we're safe to let it go -- in a sense, we were
                   ready to let it go as soon as we locked it. */
-               ast_mutex_unlock(&tmp->lock);
+               ast_unlock_context(tmp);
                for (tmpi = tmp->includes; tmpi; ) { /* Free includes */
                        struct ast_include *tmpil = tmpi;
                        tmpi = tmpi->next;
@@ -5250,12 +5261,12 @@ void __ast_context_destroy(struct ast_context *con, const char *registrar)
                        e = e->next;
                        destroy_exten(el);
                }
-               ast_mutex_destroy(&tmp->lock);
+               ast_rwlock_destroy(&tmp->lock);
                free(tmp);
                /* if we have a specific match, we are done, otherwise continue */
                tmp = con ? NULL : next;
        }
-       ast_mutex_unlock(&conlock);
+       ast_unlock_contexts();
 }
 
 void ast_context_destroy(struct ast_context *con, const char *registrar)
@@ -5337,21 +5348,11 @@ static int pbx_builtin_congestion(struct ast_channel *chan, void *data)
 static int pbx_builtin_answer(struct ast_channel *chan, void *data)
 {
        int delay = 0;
-       int res;
 
-       if (chan->_state == AST_STATE_UP)
-               delay = 0;
-       else if (!ast_strlen_zero(data))
+       if ((chan->_state != AST_STATE_UP) && !ast_strlen_zero(data))
                delay = atoi(data);
 
-       res = ast_answer(chan);
-       if (res)
-               return res;
-
-       if (delay)
-               res = ast_safe_sleep(chan, delay);
-
-       return res;
+       return __ast_answer(chan, delay);
 }
 
 AST_APP_OPTIONS(resetcdr_opts, {
@@ -5586,10 +5587,10 @@ static int pbx_builtin_background(struct ast_channel *chan, void *data)
 
        AST_STANDARD_APP_ARGS(args, parse);
 
-       if (!args.lang)
+       if (ast_strlen_zero(args.lang))
                args.lang = (char *)chan->language;     /* XXX this is const */
 
-       if (!args.context)
+       if (ast_strlen_zero(args.context))
                args.context = chan->context;
 
        if (args.options) {
@@ -5656,7 +5657,7 @@ static int pbx_builtin_goto(struct ast_channel *chan, void *data)
 }
 
 
-int pbx_builtin_serialize_variables(struct ast_channel *chan, char *buf, size_t size)
+int pbx_builtin_serialize_variables(struct ast_channel *chan, struct ast_str **buf)
 {
        struct ast_var_t *variables;
        const char *var, *val;
@@ -5665,13 +5666,14 @@ int pbx_builtin_serialize_variables(struct ast_channel *chan, char *buf, size_t
        if (!chan)
                return 0;
 
-       memset(buf, 0, size);
+       (*buf)->used = 0;
+       (*buf)->str[0] = '\0';
 
        AST_LIST_TRAVERSE(&chan->varshead, variables, entries) {
                if ((var=ast_var_name(variables)) && (val=ast_var_value(variables))
                   /* && !ast_strlen_zero(var) && !ast_strlen_zero(val) */
                   ) {
-                       if (ast_build_string(&buf, &size, "%s=%s\n", var, val)) {
+                       if (ast_str_append(buf, 0, "%s=%s\n", var, val) < 0) {
                                ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
                                break;
                        } else
@@ -5699,7 +5701,7 @@ const char *pbx_builtin_getvar_helper(struct ast_channel *chan, const char *name
                if (!places[i])
                        continue;
                if (places[i] == &globals)
-                       ast_mutex_lock(&globalslock);
+                       ast_rwlock_rdlock(&globalslock);
                AST_LIST_TRAVERSE(places[i], variables, entries) {
                        if (!strcmp(name, ast_var_name(variables))) {
                                ret = ast_var_value(variables);
@@ -5707,7 +5709,7 @@ const char *pbx_builtin_getvar_helper(struct ast_channel *chan, const char *name
                        }
                }
                if (places[i] == &globals)
-                       ast_mutex_unlock(&globalslock);
+                       ast_rwlock_unlock(&globalslock);
                if (ret)
                        break;
        }
@@ -5735,10 +5737,10 @@ void pbx_builtin_pushvar_helper(struct ast_channel *chan, const char *name, cons
                        ast_verbose(VERBOSE_PREFIX_2 "Setting global variable '%s' to '%s'\n", name, value);
                newvariable = ast_var_assign(name, value);
                if (headp == &globals)
-                       ast_mutex_lock(&globalslock);
+                       ast_rwlock_wrlock(&globalslock);
                AST_LIST_INSERT_HEAD(headp, newvariable, entries);
                if (headp == &globals)
-                       ast_mutex_unlock(&globalslock);
+                       ast_rwlock_unlock(&globalslock);
        }
 }
 
@@ -5766,7 +5768,7 @@ void pbx_builtin_setvar_helper(struct ast_channel *chan, const char *name, const
        }
 
        if (headp == &globals)
-               ast_mutex_lock(&globalslock);
+               ast_rwlock_wrlock(&globalslock);
        AST_LIST_TRAVERSE (headp, newvariable, entries) {
                if (strcasecmp(ast_var_name(newvariable), nametail) == 0) {
                        /* there is already such a variable, delete it */
@@ -5784,7 +5786,7 @@ void pbx_builtin_setvar_helper(struct ast_channel *chan, const char *name, const
        }
 
        if (headp == &globals)
-               ast_mutex_unlock(&globalslock);
+               ast_rwlock_unlock(&globalslock);
 }
 
 int pbx_builtin_setvar(struct ast_channel *chan, void *data)
@@ -5862,10 +5864,10 @@ void pbx_builtin_clear_globals(void)
 {
        struct ast_var_t *vardata;
 
-       ast_mutex_lock(&globalslock);
+       ast_rwlock_wrlock(&globalslock);
        while ((vardata = AST_LIST_REMOVE_HEAD(&globals, entries)))
                ast_var_delete(vardata);
-       ast_mutex_unlock(&globalslock);
+       ast_rwlock_unlock(&globalslock);
 }
 
 int pbx_checkcondition(const char *condition)
@@ -5985,27 +5987,37 @@ int load_pbx(void)
 /*
  * Lock context list functions ...
  */
-int ast_lock_contexts()
+int ast_wrlock_contexts()
 {
-       return ast_mutex_lock(&conlock);
+       return ast_rwlock_wrlock(&conlock);
+}
+
+int ast_rdlock_contexts()
+{
+       return ast_rwlock_rdlock(&conlock);
 }
 
 int ast_unlock_contexts()
 {
-       return ast_mutex_unlock(&conlock);
+       return ast_rwlock_unlock(&conlock);
 }
 
 /*
  * Lock context ...
  */
-int ast_lock_context(struct ast_context *con)
+int ast_wrlock_context(struct ast_context *con)
+{
+       return ast_rwlock_wrlock(&con->lock);
+}
+
+int ast_rdlock_context(struct ast_context *con)
 {
-       return ast_mutex_lock(&con->lock);
+       return ast_rwlock_rdlock(&con->lock);
 }
 
 int ast_unlock_context(struct ast_context *con)
 {
-       return ast_mutex_unlock(&con->lock);
+       return ast_rwlock_unlock(&con->lock);
 }
 
 /*