memory leaks: Memory leak cleanup patch by Corey Farrell (second set)
[asterisk/asterisk.git] / channels / chan_dahdi.c
index a31c8e7..b682994 100644 (file)
@@ -102,6 +102,7 @@ ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 #include "asterisk/callerid.h"
 #include "asterisk/adsi.h"
 #include "asterisk/cli.h"
+#include "asterisk/pickup.h"
 #include "asterisk/features.h"
 #include "asterisk/musiconhold.h"
 #include "asterisk/say.h"
@@ -118,7 +119,6 @@ ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 #include "asterisk/abstract_jb.h"
 #include "asterisk/smdi.h"
 #include "asterisk/astobj.h"
-#include "asterisk/event.h"
 #include "asterisk/devicestate.h"
 #include "asterisk/paths.h"
 #include "asterisk/ccss.h"
@@ -460,6 +460,8 @@ static const char config[] = "chan_dahdi.conf";
 static int num_cadence = 4;
 static int user_has_defined_cadences = 0;
 
+static int has_pseudo;
+
 static struct dahdi_ring_cadence cadences[NUM_CADENCE_MAX] = {
        { { 125, 125, 2000, 4000 } },                   /*!< Quick chirp followed by normal ring */
        { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /*!< British style ring */
@@ -551,7 +553,7 @@ static int restart_monitor(void);
 
 static int dahdi_sendtext(struct ast_channel *c, const char *text);
 
-static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_topic *topic, struct stasis_message *msg)
+static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_message *msg)
 {
        /* This module does not handle MWI in an event-based manner.  However, it
         * subscribes to MWI for each mailbox that is configured so that the core
@@ -816,6 +818,18 @@ struct dahdi_chan_conf {
         * \note Set from the "smdiport" string read in from chan_dahdi.conf
         */
        char smdi_port[SMDI_MAX_FILENAME_LEN];
+
+       /*!
+        * \brief Don't create channels below this number
+        * \note by default is 0 (no limit)
+        */
+       int wanted_channels_start;
+
+       /*!
+        * \brief Don't create channels above this number (infinity by default)
+        * \note by default is 0 (special value that means "no limit").
+        */
+       int wanted_channels_end;
 };
 
 /*! returns a new dahdi_chan_conf with default values (by-value) */
@@ -1741,7 +1755,7 @@ static void my_get_and_handle_alarms(void *pvt)
 
 static void *my_get_sigpvt_bridged_channel(struct ast_channel *chan)
 {
-       struct ast_channel *bridged = ast_bridged_channel(chan);
+       RAII_VAR(struct ast_channel *, bridged, ast_channel_bridge_peer(chan), ast_channel_cleanup);
 
        if (bridged && ast_channel_tech(bridged) == &dahdi_tech) {
                struct dahdi_pvt *p = ast_channel_tech_pvt(bridged);
@@ -2632,7 +2646,7 @@ static int sig_pri_tone_to_dahditone(enum sig_pri_tone tone)
 #endif /* defined(HAVE_PRI) */
 
 #if defined(HAVE_PRI)
-static int pri_destroy_dchan(struct sig_pri_span *pri);
+static void pri_destroy_span(struct sig_pri_span *pri);
 
 static void my_handle_dchan_exception(struct sig_pri_span *pri, int index)
 {
@@ -2662,7 +2676,7 @@ static void my_handle_dchan_exception(struct sig_pri_span *pri, int index)
                pri_event_noalarm(pri, index, 0);
                break;
        case DAHDI_EVENT_REMOVED:
-               pri_destroy_dchan(pri);
+               pri_destroy_span(pri);
                break;
        default:
                break;
@@ -3672,6 +3686,7 @@ static void dahdi_r2_on_call_disconnect(openr2_chan_t *r2chan, openr2_call_disco
        snprintf(cause_str, sizeof(cause_str), "R2 DISCONNECT (%s)", openr2_proto_get_disconnect_string(cause));
        datalen += strlen(cause_str);
        cause_code = ast_alloca(datalen);
+       memset(cause_code, 0, datalen);
        cause_code->ast_cause = dahdi_r2_cause_to_ast_cause(cause);
        ast_copy_string(cause_code->chan_name, ast_channel_name(p->owner), AST_CHANNEL_NAME);
        ast_copy_string(cause_code->code, cause_str, datalen + 1 - sizeof(*cause_code));
@@ -4511,6 +4526,15 @@ void dahdi_ec_disable(struct dahdi_pvt *p)
        p->echocanon = 0;
 }
 
+static int set_hwgain(int fd, float gain, int tx_direction)
+{
+       struct dahdi_hwgain hwgain;
+
+       hwgain.newgain = gain * 10.0;
+       hwgain.tx = tx_direction;
+       return ioctl(fd, DAHDI_SET_HWGAIN, &hwgain) < 0;
+}
+
 /* perform a dynamic range compression transform on the given sample */
 static int drc_sample(int sample, float drc)
 {
@@ -8895,6 +8919,8 @@ static struct ast_channel *dahdi_new(struct dahdi_pvt *i, int state, int startpb
                return NULL;
        }
 
+       ast_channel_stage_snapshot(tmp);
+
        if (callid) {
                ast_channel_callid_set(tmp, callid);
        }
@@ -9072,6 +9098,8 @@ static struct ast_channel *dahdi_new(struct dahdi_pvt *i, int state, int startpb
        for (v = i->vars ; v ; v = v->next)
                pbx_builtin_setvar_helper(tmp, v->name, v->value);
 
+       ast_channel_stage_snapshot_done(tmp);
+
        ast_module_ref(ast_module_info->self);
 
        dahdi_ami_channel_event(i, tmp);
@@ -9231,10 +9259,6 @@ static void *analog_ss_thread(void *data)
        int idx;
        struct ast_format tmpfmt;
        RAII_VAR(struct ast_features_pickup_config *, pickup_cfg, NULL, ao2_cleanup);
-       RAII_VAR(struct ast_parking_bridge_feature_fn_table *, parking_provider,
-               ast_parking_get_bridge_features(),
-               ao2_cleanup);
-       int is_exten_parking;
        const char *pickupexten;
 
        ast_mutex_lock(&ss_thread_lock);
@@ -9548,6 +9572,8 @@ static void *analog_ss_thread(void *data)
                if (p->subs[SUB_THREEWAY].owner)
                        timeout = 999999;
                while (len < AST_MAX_EXTENSION-1) {
+                       int is_exten_parking = 0;
+
                        /* Read digit unless it's supposed to be immediate, in which case the
                           only answer is 's' */
                        if (p->immediate)
@@ -9570,7 +9596,9 @@ static void *analog_ss_thread(void *data)
                        } else {
                                tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALTONE);
                        }
-                       is_exten_parking = (parking_provider ? parking_provider->parking_is_exten_park(ast_channel_context(chan), exten) : 0);
+                       if (ast_parking_provider_registered()) {
+                               is_exten_parking = ast_parking_is_exten_park(ast_channel_context(chan), exten);
+                       }
                        if (ast_exists_extension(chan, ast_channel_context(chan), exten, 1, p->cid_num) && !is_exten_parking) {
                                if (!res || !ast_matchmore_extension(chan, ast_channel_context(chan), exten, 1, p->cid_num)) {
                                        if (getforward) {
@@ -9707,16 +9735,34 @@ static void *analog_ss_thread(void *data)
                                getforward = 0;
                                memset(exten, 0, sizeof(exten));
                                len = 0;
-                       } else if ((p->transfer || p->canpark) && is_exten_parking &&
-                                               p->subs[SUB_THREEWAY].owner) {
-                               RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
-                               /* This is a three way call, the main call being a real channel,
-                                       and we're parking the first call. */
-                               ast_channel_lock(chan);
-                               bridge_channel = ast_channel_get_bridge_channel(chan);
-                               ast_channel_unlock(chan);
-                               if (bridge_channel && !parking_provider->parking_blind_transfer_park(bridge_channel, ast_channel_context(chan), exten)) {
-                                       ast_verb(3, "Parking call to '%s'\n", ast_channel_name(chan));
+                       } else if ((p->transfer || p->canpark) && is_exten_parking
+                               && p->subs[SUB_THREEWAY].owner) {
+                               struct ast_bridge_channel *bridge_channel;
+
+                               /*
+                                * This is a three way call, the main call being a real channel,
+                                * and we're parking the first call.
+                                */
+                               ast_channel_lock(p->subs[SUB_THREEWAY].owner);
+                               bridge_channel = ast_channel_get_bridge_channel(p->subs[SUB_THREEWAY].owner);
+                               ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
+                               if (bridge_channel) {
+                                       if (!ast_parking_blind_transfer_park(bridge_channel, ast_channel_context(chan), exten)) {
+                                               /*
+                                                * Swap things around between the three-way and real call so we
+                                                * can hear where the channel got parked.
+                                                */
+                                               ast_mutex_lock(&p->lock);
+                                               p->owner = p->subs[SUB_THREEWAY].owner;
+                                               swap_subs(p, SUB_THREEWAY, SUB_REAL);
+                                               ast_mutex_unlock(&p->lock);
+
+                                               ast_verb(3, "%s: Parked call\n", ast_channel_name(chan));
+                                               ast_hangup(chan);
+                                               ao2_ref(bridge_channel, -1);
+                                               goto quit;
+                                       }
+                                       ao2_ref(bridge_channel, -1);
                                }
                                break;
                        } else if (p->hidecallerid && !strcmp(exten, "*82")) {
@@ -9736,12 +9782,15 @@ static void *analog_ss_thread(void *data)
                                struct ast_channel *nbridge =
                                        p->subs[SUB_THREEWAY].owner;
                                struct dahdi_pvt *pbridge = NULL;
+                               RAII_VAR(struct ast_channel *, bridged, nbridge ? ast_channel_bridge_peer(nbridge) : NULL, ast_channel_cleanup);
+
                                /* set up the private struct of the bridged one, if any */
-                               if (nbridge && ast_bridged_channel(nbridge))
-                                       pbridge = ast_channel_tech_pvt(ast_bridged_channel(nbridge));
+                               if (nbridge && bridged) {
+                                       pbridge = ast_channel_tech_pvt(bridged);
+                               }
                                if (nbridge && pbridge &&
                                        (ast_channel_tech(nbridge) == &dahdi_tech) &&
-                                       (ast_channel_tech(ast_bridged_channel(nbridge)) == &dahdi_tech) &&
+                                       (ast_channel_tech(bridged) == &dahdi_tech) &&
                                        ISTRUNK(pbridge)) {
                                        int func = DAHDI_FLASH;
                                        /* Clear out the dial buffer */
@@ -10732,29 +10781,121 @@ static int mwi_send_process_event(struct dahdi_pvt * pvt, int event)
        return handled;
 }
 
-/* destroy a DAHDI channel, identified by its number */
-static int dahdi_destroy_channel_bynum(int channel)
+/* destroy a range DAHDI channels, identified by their number */
+static void dahdi_destroy_channel_range(int start, int end)
 {
        struct dahdi_pvt *cur;
+       struct dahdi_pvt *next;
+       int destroyed_first = 0;
+       int destroyed_last = 0;
 
        ast_mutex_lock(&iflock);
-       for (cur = iflist; cur; cur = cur->next) {
-               if (cur->channel == channel) {
+       ast_debug(1, "range: %d-%d\n", start, end);
+       for (cur = iflist; cur; cur = next) {
+               next = cur->next;
+               if (cur->channel >= start && cur->channel <= end) {
                        int x = DAHDI_FLASH;
 
+                       if (cur->channel > destroyed_last) {
+                               destroyed_last = cur->channel;
+                       }
+                       if (destroyed_first < 1 || cur->channel < destroyed_first) {
+                               destroyed_first = cur->channel;
+                       }
+                       ast_debug(3, "Destroying %d\n", cur->channel);
                        /* important to create an event for dahdi_wait_event to register so that all analog_ss_threads terminate */
                        ioctl(cur->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
 
                        destroy_channel(cur, 1);
-                       ast_mutex_unlock(&iflock);
                        ast_module_unref(ast_module_info->self);
-                       return RESULT_SUCCESS;
                }
        }
        ast_mutex_unlock(&iflock);
-       return RESULT_FAILURE;
+       if (destroyed_first > start || destroyed_last < end) {
+               ast_debug(1, "Asked to destroy %d-%d, destroyed %d-%d,\n",
+                       start, end, destroyed_first, destroyed_last);
+       }
 }
 
+static int setup_dahdi(int reload);
+static int setup_dahdi_int(int reload, struct dahdi_chan_conf *default_conf, struct dahdi_chan_conf *base_conf, struct dahdi_chan_conf *conf);
+
+/*!
+ * \internal
+ * \brief create a range of new DAHDI channels
+ *
+ * \param start first channel in the range
+ * \param end last channel in the range
+ *
+ * \retval RESULT_SUCCESS on success.
+ * \retval RESULT_FAILURE on error.
+ */
+static int dahdi_create_channel_range(int start, int end)
+{
+       struct dahdi_pvt *cur;
+       struct dahdi_chan_conf default_conf = dahdi_chan_conf_default();
+       struct dahdi_chan_conf base_conf = dahdi_chan_conf_default();
+       struct dahdi_chan_conf conf = dahdi_chan_conf_default();
+       int i, x;
+       int ret = RESULT_FAILURE; /* be pessimistic */
+
+       ast_debug(1, "channel range caps: %d - %d\n", start, end);
+       ast_mutex_lock(&iflock);
+       for (cur = iflist; cur; cur = cur->next) {
+               if (cur->channel >= start && cur->channel <= end) {
+                       ast_log(LOG_ERROR,
+                               "channel range %d-%d is occupied\n",
+                               start, end);
+                       goto out;
+               }
+       }
+       for (x = 0; x < NUM_SPANS; x++) {
+#ifdef HAVE_PRI
+               struct dahdi_pri *pri = pris + x;
+
+               if (!pris[x].pri.pvts[0]) {
+                       break;
+               }
+               for (i = 0; i < SIG_PRI_NUM_DCHANS; i++) {
+                       int channo = pri->dchannels[i];
+
+                       if (!channo) {
+                               break;
+                       }
+                       if (!pri->pri.fds[i]) {
+                               break;
+                       }
+                       if (channo >= start && channo <= end) {
+                               ast_log(LOG_ERROR,
+                                               "channel range %d-%d is occupied by span %d\n",
+                                               start, end, x + 1);
+                               goto out;
+                       }
+               }
+#endif
+       }
+       if (!default_conf.chan.cc_params || !base_conf.chan.cc_params ||
+               !conf.chan.cc_params) {
+               goto out;
+       }
+       default_conf.wanted_channels_start = start;
+       base_conf.wanted_channels_start = start;
+       conf.wanted_channels_start = start;
+       default_conf.wanted_channels_end = end;
+       base_conf.wanted_channels_end = end;
+       conf.wanted_channels_end = end;
+       if (setup_dahdi_int(0, &default_conf, &base_conf, &conf) == 0) {
+               ret = RESULT_SUCCESS;
+       }
+out:
+       ast_cc_config_params_destroy(default_conf.chan.cc_params);
+       ast_cc_config_params_destroy(base_conf.chan.cc_params);
+       ast_cc_config_params_destroy(conf.chan.cc_params);
+       ast_mutex_unlock(&iflock);
+       return ret;
+}
+
+
 static struct dahdi_pvt *handle_init_event(struct dahdi_pvt *i, int event)
 {
        int res;
@@ -11014,6 +11155,11 @@ static struct dahdi_pvt *handle_init_event(struct dahdi_pvt *i, int event)
        return NULL;
 }
 
+static void monitor_pfds_clean(void *arg) {
+       struct pollfd **pfds = arg;
+       ast_free(*pfds);
+}
+
 static void *do_monitor(void *data)
 {
        int count, res, res2, spoint, pollres=0;
@@ -11037,6 +11183,7 @@ static void *do_monitor(void *data)
 #endif
        pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
 
+       pthread_cleanup_push(monitor_pfds_clean, &pfds);
        for (;;) {
                /* Lock the interface list */
                ast_mutex_lock(&iflock);
@@ -11120,11 +11267,7 @@ static void *do_monitor(void *data)
                doomed = NULL;
                for (i = iflist;; i = i->next) {
                        if (doomed) {
-                               int res;
-                               res = dahdi_destroy_channel_bynum(doomed->channel);
-                               if (res != RESULT_SUCCESS) {
-                                       ast_log(LOG_WARNING, "Couldn't find channel to destroy, hopefully another destroy operation just happened.\n");
-                               }
+                               dahdi_destroy_channel_range(doomed->channel, doomed->channel);
                                doomed = NULL;
                        }
                        if (!i) {
@@ -11296,6 +11439,7 @@ static void *do_monitor(void *data)
                ast_mutex_unlock(&iflock);
        }
        /* Never reached */
+       pthread_cleanup_pop(1);
        return NULL;
 
 }
@@ -12323,6 +12467,10 @@ static struct dahdi_pvt *mkintf(int channel, const struct dahdi_chan_conf *conf,
                                }
                        }
                }
+               tmp->hwrxgain_enabled = conf->chan.hwrxgain_enabled;
+               tmp->hwtxgain_enabled = conf->chan.hwtxgain_enabled;
+               tmp->hwrxgain = conf->chan.hwrxgain;
+               tmp->hwtxgain = conf->chan.hwtxgain;
                tmp->cid_rxgain = conf->chan.cid_rxgain;
                tmp->rxgain = conf->chan.rxgain;
                tmp->txgain = conf->chan.txgain;
@@ -12330,6 +12478,12 @@ static struct dahdi_pvt *mkintf(int channel, const struct dahdi_chan_conf *conf,
                tmp->rxdrc = conf->chan.rxdrc;
                tmp->tonezone = conf->chan.tonezone;
                if (tmp->subs[SUB_REAL].dfd > -1) {
+                       if (tmp->hwrxgain_enabled) {
+                               tmp->hwrxgain_enabled = !set_hwgain(tmp->subs[SUB_REAL].dfd, tmp->hwrxgain, 0);
+                       }
+                       if (tmp->hwtxgain_enabled) {
+                               tmp->hwtxgain_enabled = !set_hwgain(tmp->subs[SUB_REAL].dfd, tmp->hwtxgain, 1);
+                       }
                        set_actual_gain(tmp->subs[SUB_REAL].dfd, tmp->rxgain, tmp->txgain, tmp->rxdrc, tmp->txdrc, tmp->law);
                        if (tmp->dsp)
                                ast_dsp_set_digitmode(tmp->dsp, DSP_DIGITMODE_DTMF | tmp->dtmfrelax);
@@ -13570,10 +13724,21 @@ static int prepare_pri(struct dahdi_pri *pri)
        for (i = 0; i < SIG_PRI_NUM_DCHANS; i++) {
                if (!pri->dchannels[i])
                        break;
+               if (pri->pri.fds[i] >= 0) {
+                       /* A partial range addition. Not a complete setup. */
+                       break;
+               }
                pri->pri.fds[i] = open("/dev/dahdi/channel", O_RDWR);
+               if ((pri->pri.fds[i] < 0)) {
+                       ast_log(LOG_ERROR, "Unable to open D-channel (fd=%d) (%s)\n",
+                               pri->pri.fds[i], strerror(errno));
+                       return -1;
+               }
                x = pri->dchannels[i];
-               if ((pri->pri.fds[i] < 0) || (ioctl(pri->pri.fds[i],DAHDI_SPECIFY,&x) == -1)) {
-                       ast_log(LOG_ERROR, "Unable to open D-channel %d (%s)\n", x, strerror(errno));
+               res = ioctl(pri->pri.fds[i], DAHDI_SPECIFY, &x);
+               if (res) {
+                       dahdi_close_pri_fd(pri, i);
+                       ast_log(LOG_ERROR, "Unable to SPECIFY channel %d (%s)\n", x, strerror(errno));
                        return -1;
                }
                memset(&p, 0, sizeof(p));
@@ -13974,22 +14139,45 @@ static char *handle_pri_show_spans(struct ast_cli_entry *e, int cmd, struct ast_
  *
  * \param pri the pri span
  *
- * \return TRUE if the span was valid and we attempted destroying.
- *
  * Shuts down a span and destroys its D-Channel. Further destruction
  * of the B-channels using dahdi_destroy_channel() would probably be required
  * for the B-Channels.
  */
-static int pri_destroy_dchan(struct sig_pri_span *pri)
+static void pri_destroy_span(struct sig_pri_span *pri)
 {
        int i;
+       int res;
+       int cancel_code;
        struct dahdi_pri* dahdi_pri;
+       pthread_t master = pri->master;
 
-       if (!pri->master || (pri->master == AST_PTHREADT_NULL)) {
-               return 0;
+       if (!master || (master == AST_PTHREADT_NULL)) {
+               return;
        }
-       pthread_cancel(pri->master);
-       pthread_join(pri->master, NULL);
+       ast_debug(2, "About to destroy DAHDI channels of span %d.\n", pri->span);
+       for (i = 0; i < pri->numchans; i++) {
+               int channel;
+               struct sig_pri_chan *pvt = pri->pvts[i];
+
+               if (!pvt) {
+                       continue;
+               }
+               channel = pvt->channel;
+               ast_debug(2, "About to destroy B-channel %d.\n", channel);
+               dahdi_destroy_channel_range(channel, channel);
+       }
+
+       cancel_code = pthread_cancel(master);
+       pthread_kill(master, SIGURG);
+       ast_debug(4,
+               "Waiting to join thread of span %d "
+               "with pid=%p cancel_code=%d\n",
+               pri->span, (void *)master, cancel_code);
+       res = pthread_join(master, NULL);
+       if (res != 0) {
+               ast_log(LOG_NOTICE, "pthread_join failed: %d\n", res);
+       }
+       pri->master = AST_PTHREADT_NULL;
 
        /* The 'struct dahdi_pri' that contains our 'struct sig_pri_span' */
        dahdi_pri = container_of(pri, struct dahdi_pri, pri);
@@ -13997,17 +14185,16 @@ static int pri_destroy_dchan(struct sig_pri_span *pri)
                ast_debug(4, "closing pri_fd %d\n", i);
                dahdi_close_pri_fd(dahdi_pri, i);
        }
-       pri->pri = NULL;
+       sig_pri_init_pri(pri);
        ast_debug(1, "PRI span %d destroyed\n", pri->span);
-       return 1;
 }
 
 static char *handle_pri_destroy_span(struct ast_cli_entry *e, int cmd,
                struct ast_cli_args *a)
 {
        int span;
-       int i;
        int res;
+       struct sig_pri_span *pri;
 
        switch (cmd) {
        case CLI_INIT:
@@ -14031,25 +14218,13 @@ static char *handle_pri_destroy_span(struct ast_cli_entry *e, int cmd,
                        a->argv[3], 1, NUM_SPANS);
                return CLI_SUCCESS;
        }
-       if (!pris[span - 1].pri.pri) {
+       pri = &pris[span - 1].pri;
+       if (!pri->pri) {
                ast_cli(a->fd, "No PRI running on span %d\n", span);
                return CLI_SUCCESS;
        }
 
-       for (i = 0; i < pris[span - 1].pri.numchans; i++) {
-               int channel;
-               struct sig_pri_chan *pvt = pris[span - 1].pri.pvts[i];
-
-               if (!pvt) {
-                       continue;
-               }
-               channel = pvt->channel;
-               ast_debug(2, "About to destroy B-channel %d.\n", channel);
-               dahdi_destroy_channel_bynum(channel);
-       }
-       ast_debug(2, "About to destroy D-channel of span %d.\n", span);
-       pri_destroy_dchan(&pris[span - 1].pri);
-
+       pri_destroy_span(pri);
        return CLI_SUCCESS;
 }
 
@@ -14501,26 +14676,97 @@ static struct ast_cli_entry dahdi_mfcr2_cli[] = {
 
 #endif /* HAVE_OPENR2 */
 
-static char *dahdi_destroy_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+static char *dahdi_destroy_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
-       int channel;
-       int ret;
+       int start;
+       int end;
        switch (cmd) {
        case CLI_INIT:
-               e->command = "dahdi destroy channel";
+               e->command = "dahdi destroy channels";
                e->usage =
-                       "Usage: dahdi destroy channel <chan num>\n"
+                       "Usage: dahdi destroy channels <from_channel> [<to_channel>]\n"
                        "       DON'T USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING.  Immediately removes a given channel, whether it is in use or not\n";
                return NULL;
        case CLI_GENERATE:
                return NULL;
        }
-       if (a->argc != 4)
+       if ((a->argc < 4) || a->argc > 5) {
                return CLI_SHOWUSAGE;
+       }
+       start = atoi(a->argv[3]);
+       if (start < 1) {
+               ast_cli(a->fd, "Invalid starting channel number %s.\n",
+                               a->argv[4]);
+               return CLI_FAILURE;
+       }
+       if (a->argc == 5) {
+               end = atoi(a->argv[4]);
+               if (end < 1) {
+                       ast_cli(a->fd, "Invalid ending channel number %s.\n",
+                                       a->argv[4]);
+                       return CLI_FAILURE;
+               }
+       } else {
+               end = start;
+       }
 
-       channel = atoi(a->argv[3]);
-       ret = dahdi_destroy_channel_bynum(channel);
-       return ( RESULT_SUCCESS == ret ) ? CLI_SUCCESS : CLI_FAILURE;
+       if (end < start) {
+               ast_cli(a->fd,
+                       "range end (%d) is smaller than range start (%d)\n",
+                       end, start);
+               return CLI_FAILURE;
+       }
+       dahdi_destroy_channel_range(start, end);
+       return CLI_SUCCESS;
+}
+
+static char *dahdi_create_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+{
+       int start;
+       int end;
+       int ret;
+
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "dahdi create channels";
+               e->usage = "Usage: dahdi create channels <from> [<to>] - a range of channels\n"
+                          "       dahdi create channels new           - add channels not yet created\n"
+                          "For ISDN  and SS7 the range should include complete spans.\n";
+               return NULL;
+       case CLI_GENERATE:
+               return NULL;
+       }
+       if ((a->argc < 4) || a->argc > 5) {
+               return CLI_SHOWUSAGE;
+       }
+       if (a->argc == 4 && !strcmp(a->argv[3], "new")) {
+               ret = dahdi_create_channel_range(0, 0);
+               return (RESULT_SUCCESS == ret) ? CLI_SUCCESS : CLI_FAILURE;
+       }
+       start = atoi(a->argv[3]);
+       if (start <= 0) {
+               ast_cli(a->fd, "Invalid starting channel number '%s'.\n",
+                               a->argv[3]);
+               return CLI_FAILURE;
+       }
+       if (a->argc == 5) {
+               end = atoi(a->argv[4]);
+               if (end <= 0) {
+                       ast_cli(a->fd, "Invalid ending channel number '%s'.\n",
+                                       a->argv[4]);
+                       return CLI_FAILURE;
+               }
+       } else {
+               end = start;
+       }
+       if (end < start) {
+               ast_cli(a->fd,
+                       "range end (%d) is smaller than range start (%d)\n",
+                       end, start);
+               return CLI_FAILURE;
+       }
+       ret = dahdi_create_channel_range(start, end);
+       return (RESULT_SUCCESS == ret) ? CLI_SUCCESS : CLI_FAILURE;
 }
 
 static void dahdi_softhangup_all(void)
@@ -14551,7 +14797,6 @@ retry:
        ast_mutex_unlock(&iflock);
 }
 
-static int setup_dahdi(int reload);
 static int dahdi_restart(void)
 {
 #if defined(HAVE_PRI) || defined(HAVE_SS7)
@@ -14791,6 +15036,8 @@ static char *dahdi_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli
        struct dahdi_confinfo ci;
        struct dahdi_params ps;
        int x;
+       char hwrxgain[15];
+       char hwtxgain[15];
 
        switch (cmd) {
        case CLI_INIT:
@@ -14864,7 +15111,18 @@ static char *dahdi_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli
                        ast_cli(a->fd, "Default law: %s\n", tmp->law_default == DAHDI_LAW_MULAW ? "ulaw" : tmp->law_default == DAHDI_LAW_ALAW ? "alaw" : "unknown");
                        ast_cli(a->fd, "Fax Handled: %s\n", tmp->faxhandled ? "yes" : "no");
                        ast_cli(a->fd, "Pulse phone: %s\n", tmp->pulsedial ? "yes" : "no");
-                       ast_cli(a->fd, "Gains (RX/TX): %.2f/%.2f\n", tmp->rxgain, tmp->txgain);
+                       if (tmp->hwrxgain_enabled) {
+                               snprintf(hwrxgain, sizeof(hwrxgain), "%.1f", tmp->hwrxgain);
+                       } else {
+                               ast_copy_string(hwrxgain, "Disabled", sizeof(hwrxgain));
+                       }
+                       if (tmp->hwtxgain_enabled) {
+                               snprintf(hwtxgain, sizeof(hwtxgain), "%.1f", tmp->hwtxgain);
+                       } else {
+                               ast_copy_string(hwtxgain, "Disabled", sizeof(hwtxgain));
+                       }
+                       ast_cli(a->fd, "HW Gains (RX/TX): %s/%s\n", hwrxgain, hwtxgain);
+                       ast_cli(a->fd, "SW Gains (RX/TX): %.2f/%.2f\n", tmp->rxgain, tmp->txgain);
                        ast_cli(a->fd, "Dynamic Range Compression (RX/TX): %.2f/%.2f\n", tmp->rxdrc, tmp->txdrc);
                        ast_cli(a->fd, "DND: %s\n", dahdi_dnd(tmp, -1) ? "yes" : "no");
                        ast_cli(a->fd, "Echo Cancellation:\n");
@@ -15130,22 +15388,26 @@ static char *dahdi_show_version(struct ast_cli_entry *e, int cmd, struct ast_cli
 static char *dahdi_set_hwgain(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
        int channel;
-       int gain;
+       float gain;
        int tx;
-       struct dahdi_hwgain hwgain;
        struct dahdi_pvt *tmp = NULL;
 
        switch (cmd) {
        case CLI_INIT:
-               e->command = "dahdi set hwgain";
+               e->command = "dahdi set hwgain {rx|tx}";
                e->usage =
                        "Usage: dahdi set hwgain <rx|tx> <chan#> <gain>\n"
-                       "       Sets the hardware gain on a a given channel, overriding the\n"
-                       "   value provided at module loadtime, whether the channel is in\n"
-                       "   use or not.  Changes take effect immediately.\n"
+                       "   Sets the hardware gain on a given channel and overrides the\n"
+                       "   value provided at module loadtime.  Changes take effect\n"
+                       "   immediately whether the channel is in use or not.\n"
+                       "\n"
                        "   <rx|tx> which direction do you want to change (relative to our module)\n"
                        "   <chan num> is the channel number relative to the device\n"
-                       "   <gain> is the gain in dB (e.g. -3.5 for -3.5dB)\n";
+                       "   <gain> is the gain in dB (e.g. -3.5 for -3.5dB)\n"
+                       "\n"
+                       "   Please note:\n"
+                       "   * hwgain is only supportable by hardware with analog ports because\n"
+                       "     hwgain works on the analog side of an analog-digital conversion.\n";
                return NULL;
        case CLI_GENERATE:
                return NULL;
@@ -15162,7 +15424,7 @@ static char *dahdi_set_hwgain(struct ast_cli_entry *e, int cmd, struct ast_cli_a
                return CLI_SHOWUSAGE;
 
        channel = atoi(a->argv[4]);
-       gain = atof(a->argv[5])*10.0;
+       gain = atof(a->argv[5]);
 
        ast_mutex_lock(&iflock);
 
@@ -15174,15 +15436,21 @@ static char *dahdi_set_hwgain(struct ast_cli_entry *e, int cmd, struct ast_cli_a
                if (tmp->subs[SUB_REAL].dfd == -1)
                        break;
 
-               hwgain.newgain = gain;
-               hwgain.tx = tx;
-               if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_SET_HWGAIN, &hwgain) < 0) {
+               if (set_hwgain(tmp->subs[SUB_REAL].dfd, gain, tx)) {
                        ast_cli(a->fd, "Unable to set the hardware gain for channel %d: %s\n", channel, strerror(errno));
                        ast_mutex_unlock(&iflock);
                        return CLI_FAILURE;
                }
-               ast_cli(a->fd, "hardware %s gain set to %d (%.1f dB) on channel %d\n",
-                       tx ? "tx" : "rx", gain, (float)gain/10.0, channel);
+               ast_cli(a->fd, "Hardware %s gain set to %.1f dB on channel %d.\n",
+                       tx ? "tx" : "rx", gain, channel);
+
+               if (tx) {
+                       tmp->hwtxgain_enabled = 1;
+                       tmp->hwtxgain = gain;
+               } else {
+                       tmp->hwrxgain_enabled = 1;
+                       tmp->hwrxgain = gain;
+               }
                break;
        }
 
@@ -15206,12 +15474,13 @@ static char *dahdi_set_swgain(struct ast_cli_entry *e, int cmd, struct ast_cli_a
 
        switch (cmd) {
        case CLI_INIT:
-               e->command = "dahdi set swgain";
+               e->command = "dahdi set swgain {rx|tx}";
                e->usage =
                        "Usage: dahdi set swgain <rx|tx> <chan#> <gain>\n"
-                       "       Sets the software gain on a a given channel, overriding the\n"
-                       "   value provided at module loadtime, whether the channel is in\n"
-                       "   use or not.  Changes take effect immediately.\n"
+                       "   Sets the software gain on a given channel and overrides the\n"
+                       "   value provided at module loadtime.  Changes take effect\n"
+                       "   immediately whether the channel is in use or not.\n"
+                       "\n"
                        "   <rx|tx> which direction do you want to change (relative to our module)\n"
                        "   <chan num> is the channel number relative to the device\n"
                        "   <gain> is the gain in dB (e.g. -3.5 for -3.5dB)\n";
@@ -15253,8 +15522,14 @@ static char *dahdi_set_swgain(struct ast_cli_entry *e, int cmd, struct ast_cli_a
                        return CLI_FAILURE;
                }
 
-               ast_cli(a->fd, "software %s gain set to %.1f on channel %d\n",
+               ast_cli(a->fd, "Software %s gain set to %.2f dB on channel %d.\n",
                        tx ? "tx" : "rx", gain, channel);
+
+               if (tx) {
+                       tmp->txgain = gain;
+               } else {
+                       tmp->rxgain = gain;
+               }
                break;
        }
        ast_mutex_unlock(&iflock);
@@ -15328,7 +15603,8 @@ static struct ast_cli_entry dahdi_cli[] = {
        AST_CLI_DEFINE(handle_dahdi_show_cadences, "List cadences"),
        AST_CLI_DEFINE(dahdi_show_channels, "Show active DAHDI channels"),
        AST_CLI_DEFINE(dahdi_show_channel, "Show information on a channel"),
-       AST_CLI_DEFINE(dahdi_destroy_channel, "Destroy a channel"),
+       AST_CLI_DEFINE(dahdi_destroy_channels, "Destroy channels"),
+       AST_CLI_DEFINE(dahdi_create_channels, "Create channels"),
        AST_CLI_DEFINE(dahdi_restart_cmd, "Fully restart DAHDI channels"),
        AST_CLI_DEFINE(dahdi_show_status, "Show all DAHDI cards status"),
        AST_CLI_DEFINE(dahdi_show_version, "Show the DAHDI version in use"),
@@ -16227,8 +16503,10 @@ static int __unload_module(void)
 
 #ifdef HAVE_PRI
        for (i = 0; i < NUM_SPANS; i++) {
-               if (pris[i].pri.master != AST_PTHREADT_NULL)
+               if (pris[i].pri.master != AST_PTHREADT_NULL) {
                        pthread_cancel(pris[i].pri.master);
+                       pthread_kill(pris[i].pri.master, SIGURG);
+               }
        }
        ast_cli_unregister_multiple(dahdi_pri_cli, ARRAY_LEN(dahdi_pri_cli));
        ast_unregister_application(dahdi_send_keypad_facility_app);
@@ -16238,9 +16516,11 @@ static int __unload_module(void)
 #endif
 #if defined(HAVE_SS7)
        for (i = 0; i < NUM_SPANS; i++) {
-               if (linksets[i].ss7.master != AST_PTHREADT_NULL)
+               if (linksets[i].ss7.master != AST_PTHREADT_NULL) {
                        pthread_cancel(linksets[i].ss7.master);
+                       pthread_kill(linksets[i].ss7.master, SIGURG);
                }
+       }
        ast_cli_unregister_multiple(dahdi_ss7_cli, ARRAY_LEN(dahdi_ss7_cli));
 #endif /* defined(HAVE_SS7) */
 #if defined(HAVE_OPENR2)
@@ -16284,8 +16564,9 @@ static int __unload_module(void)
 
 #if defined(HAVE_PRI)
        for (i = 0; i < NUM_SPANS; i++) {
-               if (pris[i].pri.master && (pris[i].pri.master != AST_PTHREADT_NULL))
+               if (pris[i].pri.master && (pris[i].pri.master != AST_PTHREADT_NULL)) {
                        pthread_join(pris[i].pri.master, NULL);
+               }
                for (j = 0; j < SIG_PRI_NUM_DCHANS; j++) {
                        dahdi_close_pri_fd(&(pris[i]), j);
                }
@@ -16300,8 +16581,9 @@ static int __unload_module(void)
 
 #if defined(HAVE_SS7)
        for (i = 0; i < NUM_SPANS; i++) {
-               if (linksets[i].ss7.master && (linksets[i].ss7.master != AST_PTHREADT_NULL))
+               if (linksets[i].ss7.master && (linksets[i].ss7.master != AST_PTHREADT_NULL)) {
                        pthread_join(linksets[i].ss7.master, NULL);
+               }
                for (j = 0; j < SIG_SS7_NUM_DCHANS; j++) {
                        dahdi_close_ss7_fd(&(linksets[i]), j);
                }
@@ -16355,7 +16637,7 @@ static char *parse_spanchan(char *chanstr, char **subdir)
        return p;
 }
 
-static int build_channels(struct dahdi_chan_conf *conf, const char *value, int reload, int lineno, int *found_pseudo)
+static int build_channels(struct dahdi_chan_conf *conf, const char *value, int reload, int lineno)
 {
        char *c, *chan;
        char *subdir;
@@ -16378,8 +16660,6 @@ static int build_channels(struct dahdi_chan_conf *conf, const char *value, int r
                        finish = start;
                } else if (!strcasecmp(chan, "pseudo")) {
                        finish = start = CHAN_PSEUDO;
-                       if (found_pseudo)
-                               *found_pseudo = 1;
                } else {
                        ast_log(LOG_ERROR, "Syntax error parsing '%s' at '%s'\n", value, chan);
                        return -1;
@@ -16409,6 +16689,12 @@ static int build_channels(struct dahdi_chan_conf *conf, const char *value, int r
                                        }
                                }
                        }
+                       if (conf->wanted_channels_start &&
+                               (real_channel < conf->wanted_channels_start ||
+                                real_channel > conf->wanted_channels_end)
+                          ) {
+                               continue;
+                       }
                        tmp = mkintf(real_channel, conf, reload);
 
                        if (tmp) {
@@ -16418,6 +16704,9 @@ static int build_channels(struct dahdi_chan_conf *conf, const char *value, int r
                                                (reload == 1) ? "reconfigure" : "register", value);
                                return -1;
                        }
+                       if (real_channel == CHAN_PSEUDO) {
+                               has_pseudo = 1;
+                       }
                }
        }
 
@@ -16604,7 +16893,6 @@ static int process_dahdi(struct dahdi_chan_conf *confp, const char *cat, struct
 {
        struct dahdi_pvt *tmp;
        int y;
-       int found_pseudo = 0;
        struct ast_variable *dahdichan = NULL;
 
        for (; v; v = v->next) {
@@ -16617,7 +16905,7 @@ static int process_dahdi(struct dahdi_chan_conf *confp, const char *cat, struct
                                ast_log(LOG_WARNING, "Channel '%s' ignored.\n", v->value);
                                continue;
                        }
-                       if (build_channels(confp, v->value, reload, v->lineno, &found_pseudo)) {
+                       if (build_channels(confp, v->value, reload, v->lineno)) {
                                if (confp->ignore_failed_channels) {
                                        ast_log(LOG_WARNING, "Channel '%s' failure ignored: ignore_failed_channels.\n", v->value);
                                        continue;
@@ -16838,6 +17126,24 @@ static int process_dahdi(struct dahdi_chan_conf *confp, const char *cat, struct
                        if (ast_true(v->value)) {
                                confp->chan.mwimonitor_fsk = 1;
                        }
+               } else if (!strcasecmp(v->name, "hwrxgain")) {
+                       confp->chan.hwrxgain_enabled = 0;
+                       if (strcasecmp(v->value, "disabled")) {
+                               if (sscanf(v->value, "%30f", &confp->chan.hwrxgain) == 1) {
+                                       confp->chan.hwrxgain_enabled = 1;
+                               } else {
+                                       ast_log(LOG_WARNING, "Invalid hwrxgain: %s at line %d.\n", v->value, v->lineno);
+                               }
+                       }
+               } else if (!strcasecmp(v->name, "hwtxgain")) {
+                       confp->chan.hwtxgain_enabled = 0;
+                       if (strcasecmp(v->value, "disabled")) {
+                               if (sscanf(v->value, "%30f", &confp->chan.hwtxgain) == 1) {
+                                       confp->chan.hwtxgain_enabled = 1;
+                               } else {
+                                       ast_log(LOG_WARNING, "Invalid hwtxgain: %s at line %d.\n", v->value, v->lineno);
+                               }
+                       }
                } else if (!strcasecmp(v->name, "cid_rxgain")) {
                        if (sscanf(v->value, "%30f", &confp->chan.cid_rxgain) != 1) {
                                ast_log(LOG_WARNING, "Invalid cid_rxgain: %s at line %d.\n", v->value, v->lineno);
@@ -17750,8 +18056,7 @@ static int process_dahdi(struct dahdi_chan_conf *confp, const char *cat, struct
 
        if (dahdichan) {
                /* Process the deferred dahdichan value. */
-               if (build_channels(confp, dahdichan->value, reload, dahdichan->lineno,
-                       &found_pseudo)) {
+               if (build_channels(confp, dahdichan->value, reload, dahdichan->lineno)) {
                        if (confp->ignore_failed_channels) {
                                ast_log(LOG_WARNING,
                                        "Dahdichan '%s' failure ignored: ignore_failed_channels.\n",
@@ -17774,7 +18079,7 @@ static int process_dahdi(struct dahdi_chan_conf *confp, const char *cat, struct
 
        /*< \todo why check for the pseudo in the per-channel section.
         * Any actual use for manual setup of the pseudo channel? */
-       if (!found_pseudo && reload != 1 && !(options & PROC_DAHDI_OPT_NOCHAN)) {
+       if (!has_pseudo && reload != 1 && !(options & PROC_DAHDI_OPT_NOCHAN)) {
                /* use the default configuration for a channel, so
                   that any settings from real configured channels
                   don't "leak" into the pseudo channel config
@@ -17788,6 +18093,7 @@ static int process_dahdi(struct dahdi_chan_conf *confp, const char *cat, struct
                }
                if (tmp) {
                        ast_verb(3, "Automatically generated pseudo channel\n");
+                       has_pseudo = 1;
                } else {
                        ast_log(LOG_WARNING, "Unable to register pseudo channel!\n");
                }
@@ -18067,7 +18373,8 @@ static int setup_dahdi_int(int reload, struct dahdi_chan_conf *default_conf, str
        if (reload != 1) {
                int x;
                for (x = 0; x < NUM_SPANS; x++) {
-                       if (pris[x].pri.pvts[0]) {
+                       if (pris[x].pri.pvts[0] &&
+                                       pris[x].pri.master == AST_PTHREADT_NULL) {
                                prepare_pri(pris + x);
                                if (sig_pri_start_pri(&pris[x].pri)) {
                                        ast_log(LOG_ERROR, "Unable to start D-channel on span %d\n", x + 1);
@@ -18317,7 +18624,7 @@ static int load_module(void)
                return AST_MODULE_LOAD_FAILURE;
        }
 
-       if (!(dahdi_tech.capabilities = ast_format_cap_alloc())) {
+       if (!(dahdi_tech.capabilities = ast_format_cap_alloc(0))) {
                return AST_MODULE_LOAD_FAILURE;
        }
        ast_format_cap_add(dahdi_tech.capabilities, ast_format_set(&tmpfmt, AST_FORMAT_SLINEAR, 0));