Index: channels/chan_mobile.c
===================================================================
--- channels/chan_mobile.c	(revision 785)
+++ channels/chan_mobile.c	(working copy)
@@ -69,6 +69,7 @@
 #include <asterisk/dsp.h>
 #include <asterisk/app.h>
 #include <asterisk/manager.h>
+#include <asterisk/io.h>
 
 #define MBL_CONFIG "mobile.conf"
 
@@ -82,6 +83,11 @@
 static pthread_t discovery_thread = AST_PTHREADT_NULL;	/* The discovery thread */
 static sdp_session_t *sdp_session;
 
+AST_MUTEX_DEFINE_STATIC(unload_mutex);
+static int unloading_flag = 0;
+static inline int check_unloading();
+static inline void set_unloading();
+
 enum mbl_type {
 	MBL_TYPE_PHONE,
 	MBL_TYPE_HEADSET
@@ -119,7 +125,11 @@
 	bdaddr_t addr;					/* adddress of adapter */
 	unsigned int inuse:1;				/* are we in use ? */
 	unsigned int alignment_detection:1;		/* do alignment detection on this adpater? */
-	int sco_socket;
+	struct io_context *io;				/*!< io context for audio connections */
+	struct io_context *accept_io;			/*!< io context for sco listener */
+	int *sco_id;					/*!< the io context id of the sco listener socket */
+	int sco_socket;					/*!< sco listener socket */
+	pthread_t sco_listener_thread;			/*!< sco listener thread */
 	AST_LIST_ENTRY(adapter_pvt) entry;
 };
 
@@ -143,7 +153,6 @@
 	int io_save_len;
 	int io_pipe[2];
 	int sco_socket;					/* sco socket descriptor */
-	pthread_t sco_listener_thread;			/* inbound sco listener for this device */
 	enum mbl_state state;				/* monitor thread current state */
 	pthread_t monitor_thread;			/* monitor thread handle */
 	char dial_number[AST_MAX_EXTENSION];		/* number for the monitor thread to dial */
@@ -222,7 +231,9 @@
 
 static int sco_connect(bdaddr_t src, bdaddr_t dst);
 static int sco_write(int s, char *buf, int len);
-static int sco_read(int s, char *buf, int len);
+static int sco_read(int *id, int fd, short events, void *data);
+static int sco_accept(int *id, int fd, short events, void *data);
+static int sco_bind(struct adapter_pvt *adapter);
 
 static void *do_sco_listen(void *data);
 static int sdp_search(char *addr, int profile);
@@ -684,10 +695,7 @@
 	close(pvt->io_pipe[0]);
 	close(pvt->io_pipe[1]);
 
-	if (pvt->type == MBL_TYPE_HEADSET && pvt->sco_socket != -1) {
-		close(pvt->sco_socket);
-		pvt->sco_socket = -1;
-	}
+	close(pvt->sco_socket);
 
 	if ((pvt->state == MBL_STATE_INCOMING || pvt->state == MBL_STATE_OUTGOING || pvt->state == MBL_STATE_DIAL1 || pvt->state == MBL_STATE_RING3) && pvt->type == MBL_TYPE_PHONE) {
 		if (pvt->do_hangup) {
@@ -816,8 +824,8 @@
 {
 
 	struct mbl_pvt *pvt = ast->tech_pvt;
-	int i, r, io_need, num_frames;
-	char *pfr, buf[DEVICE_FRAME_SIZE];
+	int i, io_need, num_frames;
+	char *pfr;
 
 	ast_debug(2, "*** mbl_write\n");
 
@@ -830,12 +838,6 @@
 		io_need = DEVICE_FRAME_SIZE - pvt->io_save_len;
 		memcpy(pvt->io_save_buf + pvt->io_save_len, frame->data.ptr, io_need);
 		sco_write(pvt->sco_socket, pvt->io_save_buf, DEVICE_FRAME_SIZE);
-		if ((r = sco_read(pvt->sco_socket, buf, DEVICE_FRAME_SIZE))) {
-			if (pvt->do_alignment_detection)
-				do_alignment_detection(pvt, buf, r);
-			if (ast->_state == AST_STATE_UP)	/* Dont queue the audio in the pipe if the call is not up yet. just toss it. */
-				sco_write(pvt->io_pipe[1], buf, r);
-		}
 	}
 
 	num_frames = (frame->datalen - io_need) / DEVICE_FRAME_SIZE;
@@ -843,12 +845,6 @@
 
 	for (i=0; i<num_frames; i++) {
 		sco_write(pvt->sco_socket, pfr, DEVICE_FRAME_SIZE);
-		if ((r = sco_read(pvt->sco_socket, buf, DEVICE_FRAME_SIZE))) {
-			if (pvt->do_alignment_detection)
-				do_alignment_detection(pvt, buf, r);
-			if (ast->_state == AST_STATE_UP)
-				sco_write(pvt->io_pipe[1], buf, r);
-		}
 		pfr += DEVICE_FRAME_SIZE;
 	}
 
@@ -1101,7 +1097,7 @@
 
 /*
 
-	sco helpers
+	sco helpers and callbacks
 
 */
 
@@ -1161,28 +1157,134 @@
 
 }
 
-static int sco_read(int s, char *buf, int len)
+/*!
+ * \brief Read data from the given sco connection.
+ * This function is an ast_io callback function that will read data from the
+ * given sco socket and write it to the corrisponding pvt io_pipe.
+ */
+static int sco_read(int *id, int fd, short events, void *data)
 {
+	struct mbl_pvt *pvt = (struct mbl_pvt *) data;
+	int res;
+	char buf[DEVICE_FRAME_SIZE];
+	
+	ast_debug(2, "sco_read()\n");
 
-	int r;
-
-	if (s == -1) {
-		ast_debug(2, "sco_read() not ready\n");
+	if ((res = read(fd, buf, DEVICE_FRAME_SIZE)) <= 0) {
+		ast_debug(2, "error reading sco audio data\n");
+		close(fd);
+		/* don't set pvt->sco_sock = -1 here, there may already be a
+		 * new pvt->sco_sock */
 		return 0;
 	}
 
-	ast_debug(2, "sco_read()\n");
+	if (pvt->do_alignment_detection)
+		do_alignment_detection(pvt, buf, res);
 
-	r = read(s, buf, len);
-	if (r == -1) {
-		ast_debug(2, "sco_read() error %d\n", errno);
+	if (pvt->owner && pvt->owner->_state == AST_STATE_UP)
+		write(pvt->io_pipe[1], buf, res);
+
+	return 1;
+}
+
+/*!
+ * \brief Accept SCO connections.
+ * This function is an ast_io callback function used to accept incoming sco
+ * audio connections.
+ */
+static int sco_accept(int *id, int fd, short events, void *data)
+{
+	struct adapter_pvt *adapter = (struct adapter_pvt *) data;
+	struct sockaddr_sco addr;
+	socklen_t addrlen;
+	struct mbl_pvt *pvt;
+	socklen_t len;
+	char saddr[18];
+	struct sco_options so;
+	int sock;
+					
+	addrlen = sizeof(struct sockaddr_sco);
+	if ((sock = accept(fd, (struct sockaddr *)&addr, &addrlen)) == -1) {
+		ast_log(LOG_ERROR, "error accepting audio connection on adapter %s\n", adapter->id);
 		return 0;
 	}
 
-	return r;
+	len = sizeof(so);
+	getsockopt(sock, SOL_SCO, SCO_OPTIONS, &so, &len);
 
+	ba2str(&addr.sco_bdaddr, saddr);
+	ast_debug(1, "Incoming Audio Connection from device %s MTU is %d\n", saddr, so.mtu);
+
+	/* figure out which device this sco connection belongs to */
+	pvt = NULL;
+	AST_RWLIST_RDLOCK(&devices);
+	AST_RWLIST_TRAVERSE(&devices, pvt, entry) {
+		if (!bacmp(&pvt->addr, &addr.sco_bdaddr)) 
+			break;
+	}
+	AST_RWLIST_UNLOCK(&devices);
+	if (!pvt) {
+		ast_log(LOG_WARNING, "could not find device for incoming audio connection\n");
+		close(sock);
+		return 1;
+	}
+
+	if (pvt->sco_socket != -1) {
+		close(pvt->sco_socket);
+		pvt->sco_socket = -1;
+	}
+
+	pvt->sco_socket = sock;
+	if (!ast_io_add(adapter->io, sock, sco_read, AST_IO_IN, pvt)) {
+		ast_log(LOG_ERROR, "error monitoring new incoming audio connection\n");
+		close(pvt->sco_socket);
+		pvt->sco_socket = -1;
+		return 1;
+	}
+
+	return 1;
 }
 
+/*!
+ * \brief Bind an SCO listener socket for the given adapter.
+ * \param adapter an adapter_pvt
+ * \return -1 on error, non zero on success
+ */
+static int sco_bind(struct adapter_pvt *adapter)
+{
+	struct sockaddr_sco addr;
+	int opt = 1;
+
+	if ((adapter->sco_socket = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO)) < 0) {
+		ast_log(LOG_ERROR, "Unable to create sco listener socket for adapter %s.\n", adapter->id);
+		goto e_return;
+	}
+	
+	memset(&addr, 0, sizeof(addr));
+	addr.sco_family = AF_BLUETOOTH;
+	bacpy(&addr.sco_bdaddr, &adapter->addr);
+	if (bind(adapter->sco_socket, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
+		ast_log(LOG_ERROR, "Unable to bind sco listener socket. (%d)\n", errno);
+		goto e_close_socket;
+	}
+	if (setsockopt(adapter->sco_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1) {
+		ast_log(LOG_ERROR, "Unable to setsockopt sco listener socket.\n");
+		goto e_close_socket;
+	}
+	if (listen(adapter->sco_socket, 5) < 0) {
+		ast_log(LOG_ERROR, "Unable to listen sco listener socket.\n");
+		goto e_close_socket;
+	}
+
+	return adapter->sco_socket;
+
+e_close_socket:
+	close(adapter->sco_socket);
+	adapter->sco_socket = -1;
+e_return:
+	return -1;
+}
+
 /*
 
 	sdp helpers
@@ -1667,20 +1769,12 @@
 
 	}
 
-	if (pvt->rfcomm_socket > -1)
-		close(pvt->rfcomm_socket);
-	if (pvt->sco_socket > -1)
-		close(pvt->sco_socket);
+	close(pvt->rfcomm_socket);
+	close(pvt->sco_socket);
 	pvt->sco_socket = -1;
+
 	pvt->connected = 0;
-	pvt->monitor_thread = AST_PTHREADT_NULL;
 
-	pthread_cancel(pvt->sco_listener_thread);
-	pthread_join(pvt->sco_listener_thread, NULL);
-	pvt->sco_listener_thread = AST_PTHREADT_NULL;
-
-	close(pvt->adapter->sco_socket);
-
 	manager_event(EVENT_FLAG_SYSTEM, "MobileStatus", "Status: Disconnect\r\nDevice: %s\r\n", pvt->id);
 
 	pvt->adapter->inuse = 0;
@@ -1696,17 +1790,27 @@
 	char monitor = 1;
 	char buf[256];
 	int s, t;
+	struct io_context *io = NULL;
 
+	if (!(io = io_context_create())) {
+		ast_log(LOG_ERROR, "Unable to create I/O context for headset audio connections\n");
+		goto e_cleanup;
+	}
+
 	pvt->state = MBL_STATE_PREIDLE;
 
 	while (monitor) {
 
 		if (pvt->state == MBL_STATE_RING2)
-			t = 2;
+			t = 2000;
 		else
-			t = 1;
-		s = rfcomm_read(pvt, buf, 0, t);
+			t = 1000;
 
+		/* wait for audio first, then check for rfcomm data */
+		if (!(s = ast_io_wait(io, t)))
+			s = rfcomm_read(pvt, buf, 0, 0);
+
+
 		if ((s > 0) && (buf[0] != 0x0) && (buf[0] != '\r')) {
 			ast_debug(1, "rfcomm_read() (%s) [%s]\n", pvt->id, buf);
 			switch (pvt->state) {
@@ -1756,13 +1860,14 @@
 
 	}
 
-	if (pvt->rfcomm_socket > -1)
-		close(pvt->rfcomm_socket);
-	if (pvt->sco_socket > -1)
-		close(pvt->sco_socket);
+e_cleanup:
+	if (io)
+		io_context_destroy(io);
+
+	close(pvt->rfcomm_socket);
+	close(pvt->sco_socket);
 	pvt->sco_socket = -1;
 	pvt->connected = 0;
-	pvt->monitor_thread = AST_PTHREADT_NULL;
 
 	manager_event(EVENT_FLAG_SYSTEM, "MobileStatus", "Status: Disconnect\r\nDevice: %s\r\n", pvt->id);
 
@@ -1780,11 +1885,6 @@
 			pvt->monitor_thread = AST_PTHREADT_NULL;
 			return 0;
 		}
-		/* we are a phone, so spin the sco listener on the adapter as well */
-		if (ast_pthread_create_background(&pvt->sco_listener_thread, NULL, do_sco_listen, pvt->adapter) < 0) {
-			ast_log(LOG_ERROR, "Unable to create sco listener thread for device %s.\n", pvt->id);
-		}
-
 	} else {
 		if (ast_pthread_create_background(&pvt->monitor_thread, NULL, do_monitor_headset, pvt) < 0) {
 			pvt->monitor_thread = AST_PTHREADT_NULL;
@@ -1832,92 +1932,169 @@
 	return NULL;
 }
 
+/*!
+ * \brief Service new and existing SCO connections.
+ * This thread accepts new sco connections and handles audio data.  There is
+ * one do_sco_listen thread for each adapter.
+ */
 static void *do_sco_listen(void *data)
 {
-
-	int ns;
-	struct sockaddr_sco addr;
-	char saddr[18];
-	struct sco_options so;
-	socklen_t len;
-	int opt = 1;
-	socklen_t addrlen;
-	struct mbl_pvt *pvt;
 	struct adapter_pvt *adapter = (struct adapter_pvt *) data;
+	int res;
 
-	if ((adapter->sco_socket = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO)) < 0) {
-		ast_log(LOG_ERROR, "Unable to create sco listener socket.\n");
-		return NULL;
+	while (!check_unloading()) {
+		/* check for new sco connections */
+		if ((res = ast_io_wait(adapter->accept_io, 0)) == -1) {
+			/* handle errors */
+			ast_log(LOG_ERROR, "ast_io_wait() failed for adapter %s\n", adapter->id);
+			break;
+		}
+
+		/* handle audio data */
+		if ((res = ast_io_wait(adapter->io, 1)) == -1) {
+			ast_log(LOG_ERROR, "ast_io_wait() failed for audio on adapter %s\n", adapter->id);
+			break;
+		}
 	}
-	memset(&addr, 0, sizeof(addr));
-	addr.sco_family = AF_BLUETOOTH;
-	bacpy(&addr.sco_bdaddr, &adapter->addr);
-	if (bind(adapter->sco_socket, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
-		ast_log(LOG_ERROR, "Unable to bind sco listener socket. (%d)\n", errno);
-		close(adapter->sco_socket);
-		return NULL;
+	
+	return NULL;
+}
+
+/*
+
+	Module
+
+*/
+
+/*!
+ * \brief Load an adapter from the configuration file.
+ * \param cfg the config to load the adapter from
+ * \param cat the adapter to load
+ *
+ * This function loads the given adapter and starts the sco listener thread for
+ * that adapter.
+ *
+ * \return NULL on error, a pointer to the adapter that was loaded on success
+ */
+static struct adapter_pvt *mbl_load_adapter(struct ast_config *cfg, const char *cat)
+{
+	const char *id, *address;
+	struct adapter_pvt *adapter;
+	struct ast_variable *v;
+	struct hci_dev_req dr;
+	uint16_t vs;
+
+	id = ast_variable_retrieve(cfg, cat, "id");
+	address = ast_variable_retrieve(cfg, cat, "address");
+
+	if (ast_strlen_zero(id) || ast_strlen_zero(address)) {
+		ast_log(LOG_ERROR, "Skipping adapter. Missing id or address settings.\n");
+		goto e_return;
 	}
-	if (setsockopt(adapter->sco_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1) {
-		ast_log(LOG_ERROR, "Unable to setsockopt sco listener socket.\n");
-		close(adapter->sco_socket);
-		return NULL;
+
+	ast_debug(1, "Reading configuration for adapter %s %s.\n", id, address);
+
+	if (!(adapter = ast_calloc(1, sizeof(*adapter)))) {
+		ast_log(LOG_ERROR, "Skipping adapter %s. Error allocating memory.\n", id);
+		goto e_return;
 	}
-	if (listen(adapter->sco_socket, 5) < 0) {
-		ast_log(LOG_ERROR, "Unable to listen sco listener socket.\n");
-		close(adapter->sco_socket);
-		return NULL;
+
+	ast_copy_string(adapter->id, id, sizeof(adapter->id));
+	str2ba(address, &adapter->addr);
+
+	/* attempt to connect to the adapter */
+	adapter->dev_id = hci_devid(address);
+	adapter->hci_socket = hci_open_dev(adapter->dev_id);
+	if (adapter->dev_id < 0 || adapter->hci_socket < 0) {
+		ast_log(LOG_ERROR, "Skipping adapter %s. Unable to communicate with adapter.\n", adapter->id);
+		goto e_free_adapter;
 	}
-	while (1) {
-		ast_debug(1, "About to accept() socket.\n");
-		addrlen = sizeof(struct sockaddr_sco);
-		if ((ns = accept(adapter->sco_socket, (struct sockaddr *)&addr, &addrlen)) > -1) {
-			ast_debug(1, "accept()ed socket.\n");
-			len = sizeof(so);
-			getsockopt(ns, SOL_SCO, SCO_OPTIONS, &so, &len);
 
-			ba2str(&addr.sco_bdaddr, saddr);
-			ast_debug(1, "Incoming Audio Connection from device %s MTU is %d\n", saddr, so.mtu);
+	/* check voice setting */
+	hci_read_voice_setting(adapter->hci_socket, &vs, 1000);
+	vs = htobs(vs);
+	if (vs != 0x0060) {
+		ast_log(LOG_ERROR, "Skipping adapter %s. Voice setting must be 0x0060 - see 'man hciconfig' for details.\n", adapter->id);
+		goto e_hci_close_dev;
+	}
 
-			pvt = NULL;
-			AST_RWLIST_RDLOCK(&devices);
-			AST_RWLIST_TRAVERSE(&devices, pvt, entry) {
-				if (!bacmp(&pvt->addr, &addr.sco_bdaddr)) 
-					break;
+	for (v = ast_variable_browse(cfg, cat); v; v = v->next) {
+		if (!strcasecmp(v->name, "forcemaster")) {
+			if (ast_true(v->value)) {
+				dr.dev_id = adapter->dev_id;
+				if (hci_strtolm("master", &dr.dev_opt)) {
+					if (ioctl(adapter->hci_socket, HCISETLINKMODE, (unsigned long) &dr) < 0) {
+						ast_log(LOG_WARNING, "Unable to set adapter %s link mode to MASTER. Ignoring 'forcemaster' option.\n", adapter->id);
+					}
+				}
 			}
-			AST_RWLIST_UNLOCK(&devices);
-			if (pvt) {
-				if (pvt->sco_socket != -1)
-					close(pvt->sco_socket);
-				pvt->sco_socket = ns;
-			} else
-				ast_debug(1, "Could not find device for incoming Audio Connection.\n");
-		} else {
-			 ast_log(LOG_ERROR, "accept() failed %d\n", errno);
+		} else if (!strcasecmp(v->name, "alignmentdetection")) {
+			adapter->alignment_detection = ast_true(v->value);
 		}
 	}
 
-	return NULL;
+	/* create io contexts */
+	if (!(adapter->accept_io = io_context_create())) {
+		ast_log(LOG_ERROR, "Unable to create I/O context for audio connection listener\n");
+		goto e_hci_close_dev;
+	}
 
-}
+	if (!(adapter->io = io_context_create())) {
+		ast_log(LOG_ERROR, "Unable to create I/O context for audio connections\n");
+		goto e_destroy_accept_io;
+	}
 
-/*
+	/* bind the sco listener socket */
+	if (sco_bind(adapter) < 0) {
+		ast_log(LOG_ERROR, "Skipping adapter %s. Error binding audio connection listerner socket.\n", adapter->id);
+		goto e_destroy_io;
+	}
 
-	Module
+	/* add the socket to the io context */
+	if (!(adapter->sco_id = ast_io_add(adapter->accept_io, adapter->sco_socket, sco_accept, AST_IO_IN, adapter))) {
+		ast_log(LOG_ERROR, "Skipping adapter %s. Error adding listener socket to I/O context.\n", adapter->id);
+		goto e_close_sco;
+	}
 
-*/
+	/* start the sco listener for this adapter */
+	if (ast_pthread_create_background(&adapter->sco_listener_thread, NULL, do_sco_listen, adapter)) {
+		ast_log(LOG_ERROR, "Skipping adapter %s. Error creating audio connection listerner thread.\n", adapter->id);
+		goto e_remove_sco;
+	}
 
+	/* add the adapter to our global list */
+	AST_RWLIST_WRLOCK(&adapters);
+	AST_RWLIST_INSERT_HEAD(&adapters, adapter, entry);
+	AST_RWLIST_UNLOCK(&adapters);
+	ast_debug(1, "Loaded adapter %s %s.\n", adapter->id, address);
+
+	return adapter;
+
+e_remove_sco:
+	ast_io_remove(adapter->accept_io, adapter->sco_id);
+e_close_sco:
+	close(adapter->sco_socket);
+e_destroy_io:
+	io_context_destroy(adapter->io);
+e_destroy_accept_io:
+	io_context_destroy(adapter->accept_io);
+e_hci_close_dev:
+	hci_close_dev(adapter->hci_socket);
+e_free_adapter:
+	ast_free(adapter);
+e_return:
+	return NULL;
+}
+
 static int mbl_load_config(void)
 {
 
 	struct ast_config *cfg = NULL;
 	char *cat = NULL;
 	struct ast_variable *var;
-	const char *id, *address, *useadapter, *port, *context, *type, *skip, *group, *master, *nocallsetup, *aligndetect, *blackberry;
+	const char *address, *useadapter, *port, *context, *type, *skip, *group, *nocallsetup, *blackberry;
 	struct mbl_pvt *pvt;
 	struct adapter_pvt *adapter;
-	uint16_t vs;
-	struct hci_dev_req dr;
-	char nadapters = 0;
 	struct ast_flags config_flags = { 0 };
 
 	cfg = ast_config_load(MBL_CONFIG, config_flags);
@@ -1929,58 +2106,14 @@
 			discovery_interval = atoi(var->value);
 	}
 
-	/* load adapters first */
-	cat = ast_category_browse(cfg, NULL);
-	while (cat) {
+	/* load adapters */
+	for (cat = ast_category_browse(cfg, NULL); cat; cat = ast_category_browse(cfg, cat)) {
 		if (!strcasecmp(cat, "adapter")) {
-			id = ast_variable_retrieve(cfg, cat, "id");
-			address = ast_variable_retrieve(cfg, cat, "address");
-			master = ast_variable_retrieve(cfg, cat, "forcemaster");
-			aligndetect = ast_variable_retrieve(cfg, cat, "alignmentdetection");
-			ast_debug(1, "Loading adapter %s %s.\n", id, address);
-			if (!ast_strlen_zero(id) && !ast_strlen_zero(address)) {
-				if ((adapter = ast_calloc(1, sizeof(*adapter)))) {
-					ast_copy_string(adapter->id, id, sizeof(adapter->id));
-					str2ba(address, &adapter->addr);
-					if (!ast_strlen_zero(aligndetect)) {
-						if (*aligndetect == 'Y' || *aligndetect == 'y')
-							adapter->alignment_detection = 1;
-					}
-					adapter->dev_id = hci_devid(address);
-					adapter->hci_socket = hci_open_dev(adapter->dev_id);
-					if (adapter->dev_id < 0 || adapter->hci_socket < 0) {
-						ast_log(LOG_ERROR, "Unable to open adapter %s. It won't be enabled.\n", adapter->id);
-						ast_free(adapter);
-					} else {
-						if ((master) && (*master)) {
-							dr.dev_id = adapter->dev_id;
-							if (hci_strtolm("master", &dr.dev_opt)) {
-								if (ioctl(adapter->hci_socket, HCISETLINKMODE, (unsigned long) &dr) < 0) {
-									ast_log(LOG_WARNING, "Unable to set adapter %s link mode to MASTER.\n", adapter->id);
-								}
-							}
-						}
-						hci_read_voice_setting(adapter->hci_socket, &vs, 1000);
-						vs = htobs(vs);
-						if (vs != 0x0060) {
-							ast_log(LOG_ERROR, "Incorrect voice setting for adapter %s, it must be 0x0060 - see 'man hciconfig' for details.\n", adapter->id);
-							hci_close_dev(adapter->hci_socket);
-							ast_free(adapter);
-						} else {
-							AST_RWLIST_WRLOCK(&adapters);
-							AST_RWLIST_INSERT_HEAD(&adapters, adapter, entry);
-							AST_RWLIST_UNLOCK(&adapters);
-							nadapters++;
-						}
-					}
-				}
-			} else
-				ast_log(LOG_ERROR, "id/address missing for adapter %s. It won't be enabled.\n", cat);
+			mbl_load_adapter(cfg, cat);
 		}
-		cat = ast_category_browse(cfg, cat);
 	}
 
-	if (!nadapters) {
+	if (AST_RWLIST_EMPTY(&adapters)) {
 		ast_log(LOG_WARNING, "***********************************************************************\n");
 		ast_log(LOG_WARNING, "No Adapters defined. Please review mobile.conf. See sample for details.\n");
 		ast_log(LOG_WARNING, "***********************************************************************\n");
@@ -2031,7 +2164,6 @@
 					pvt->rfcomm_port = atoi(port);
 					pvt->sco_socket = -1;
 					pvt->monitor_thread = AST_PTHREADT_NULL;
-					pvt->sco_listener_thread = AST_PTHREADT_NULL;
 					if (!ast_strlen_zero(nocallsetup)) {
 						if ((*nocallsetup == 'y') || (*nocallsetup == 'Y')) {
 							pvt->no_callsetup = 1;
@@ -2061,9 +2193,33 @@
 	ast_config_destroy(cfg);
 
 	return 1;
+}
 
+/*
+ * \brief Check if the module is unloading.
+ * \retval 0 not unloading
+ * \retval 1 unloading
+ */
+static inline int check_unloading()
+{
+	int res;
+	ast_mutex_lock(&unload_mutex);
+	res = unloading_flag;
+	ast_mutex_unlock(&unload_mutex);
+
+	return res;
 }
 
+/*
+ * \brief Set the unloading flag.
+ */
+static inline void set_unloading()
+{
+	ast_mutex_lock(&unload_mutex);
+	unloading_flag = 1;
+	ast_mutex_unlock(&unload_mutex);
+}
+
 static int unload_module(void)
 {
 
@@ -2073,12 +2229,23 @@
 	/* First, take us out of the channel loop */
 	ast_channel_unregister(&mbl_tech);
 
+	/* signal everyone we are unloading */
+	set_unloading();
+
 	/* Kill the discovery thread */
 	if (discovery_thread != AST_PTHREADT_NULL) {
 		pthread_cancel(discovery_thread);
 		pthread_join(discovery_thread, NULL);
 	}
 
+	/* stop the sco listener threads */
+	AST_RWLIST_WRLOCK(&adapters);
+	AST_RWLIST_TRAVERSE(&adapters, adapter, entry) {
+		pthread_kill(adapter->sco_listener_thread, SIGURG);
+		pthread_join(adapter->sco_listener_thread, NULL);
+	}
+	AST_RWLIST_UNLOCK(&adapters);
+	
 	/* Destroy the device list */
 	AST_RWLIST_WRLOCK(&devices);
 	while ((pvt = AST_RWLIST_REMOVE_HEAD(&devices, entry))) {
@@ -2086,16 +2253,9 @@
 			pthread_cancel(pvt->monitor_thread);
 			pthread_join(pvt->monitor_thread, NULL);
 		}
-		if (pvt->sco_listener_thread != AST_PTHREADT_NULL) {
-			pthread_cancel(pvt->sco_listener_thread);
-			pthread_join(pvt->sco_listener_thread, NULL);
-		}
 		if (pvt->sco_socket > -1) {
 			close(pvt->sco_socket);
 		}
-		if (pvt->adapter->sco_socket > -1) {
-			close(pvt->adapter->sco_socket);
-		}
 		if (pvt->rfcomm_socket > -1) {
 			close(pvt->rfcomm_socket);
 		}
@@ -2107,6 +2267,9 @@
 	/* Destroy the adapter list */
 	AST_RWLIST_WRLOCK(&adapters);
 	while ((adapter = AST_RWLIST_REMOVE_HEAD(&adapters, entry))) {
+		close(adapter->sco_socket);
+		io_context_destroy(adapter->io);
+		io_context_destroy(adapter->accept_io);
 		hci_close_dev(adapter->hci_socket);
 		ast_free(adapter);
 	}
