Home | History | Annotate | Download | only in server
      1 /* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
      2  * Use of this source code is governed by a BSD-style license that can be
      3  * found in the LICENSE file.
      4  */
      5 
      6 #ifndef _GNU_SOURCE
      7 #define _GNU_SOURCE /* for ppoll */
      8 #endif
      9 
     10 #include <dbus/dbus.h>
     11 
     12 #include <errno.h>
     13 #include <poll.h>
     14 #include <stdbool.h>
     15 #include <stdint.h>
     16 #include <stdlib.h>
     17 #include <string.h>
     18 #include <sys/socket.h>
     19 #include <syslog.h>
     20 
     21 #include "bluetooth.h"
     22 #include "cras_a2dp_endpoint.h"
     23 #include "cras_bt_adapter.h"
     24 #include "cras_bt_device.h"
     25 #include "cras_bt_constants.h"
     26 #include "cras_bt_io.h"
     27 #include "cras_bt_profile.h"
     28 #include "cras_hfp_ag_profile.h"
     29 #include "cras_hfp_slc.h"
     30 #include "cras_iodev.h"
     31 #include "cras_iodev_list.h"
     32 #include "cras_main_message.h"
     33 #include "cras_system_state.h"
     34 #include "cras_tm.h"
     35 #include "utlist.h"
     36 
     37 #define DEFAULT_HFP_MTU_BYTES 48
     38 
     39 
     40 static const unsigned int PROFILE_SWITCH_DELAY_MS = 500;
     41 
     42 /* Check profile connections every 2 seconds and rerty 30 times maximum.
     43  * Attemp to connect profiles which haven't been ready every 3 retries.
     44  */
     45 static const unsigned int CONN_WATCH_PERIOD_MS = 2000;
     46 static const unsigned int CONN_WATCH_MAX_RETRIES = 30;
     47 static const unsigned int PROFILE_CONN_RETRIES = 3;
     48 
     49 /* Object to represent a general bluetooth device, and used to
     50  * associate with some CRAS modules if it supports audio.
     51  * Members:
     52  *    conn - The dbus connection object used to send message to bluetoothd.
     53  *    object_path - Object path of the bluetooth device.
     54  *    adapter - The object path of the adapter associates with this device.
     55  *    address - The BT address of this device.
     56  *    name - The readable name of this device.
     57  *    bluetooth_class - The bluetooth class of this device.
     58  *    paired - If this device is paired.
     59  *    trusted - If this device is trusted.
     60  *    connected - If this devices is connected.
     61  *    connected_profiles - OR'ed all connected audio profiles.
     62  *    profiles - OR'ed by all audio profiles this device supports.
     63  *    bt_iodevs - The pointer to the cras_iodevs of this device.
     64  *    active_profile - The flag to indicate the active audio profile this
     65  *        device is currently using.
     66  *    conn_watch_retries - The retry count for conn_watch_timer.
     67  *    conn_watch_timer - The timer used to watch connected profiles and start
     68  *        BT audio input/ouput when all profiles are ready.
     69  *    suspend_timer - The timer used to suspend device.
     70  *    switch_profile_timer - The timer used to delay enabling iodev after
     71  *        profile switch.
     72  *    append_iodev_cb - The callback to trigger when an iodev is appended.
     73  */
     74 struct cras_bt_device {
     75 	DBusConnection *conn;
     76 	char *object_path;
     77 	char *adapter_obj_path;
     78 	char *address;
     79 	char *name;
     80 	uint32_t bluetooth_class;
     81 	int paired;
     82 	int trusted;
     83 	int connected;
     84 	enum cras_bt_device_profile connected_profiles;
     85 	enum cras_bt_device_profile profiles;
     86 	struct cras_iodev *bt_iodevs[CRAS_NUM_DIRECTIONS];
     87 	unsigned int active_profile;
     88 	int use_hardware_volume;
     89 	int conn_watch_retries;
     90 	struct cras_timer *conn_watch_timer;
     91 	struct cras_timer *suspend_timer;
     92 	struct cras_timer *switch_profile_timer;
     93 	void (*append_iodev_cb)(void *data);
     94 
     95 	struct cras_bt_device *prev, *next;
     96 };
     97 
     98 enum BT_DEVICE_COMMAND {
     99 	BT_DEVICE_CANCEL_SUSPEND,
    100 	BT_DEVICE_SCHEDULE_SUSPEND,
    101 	BT_DEVICE_SWITCH_PROFILE,
    102 	BT_DEVICE_SWITCH_PROFILE_ENABLE_DEV,
    103 };
    104 
    105 struct bt_device_msg {
    106 	struct cras_main_message header;
    107 	enum BT_DEVICE_COMMAND cmd;
    108 	struct cras_bt_device *device;
    109 	struct cras_iodev *dev;
    110 	unsigned int arg;
    111 };
    112 
    113 static struct cras_bt_device *devices;
    114 
    115 void cras_bt_device_set_append_iodev_cb(struct cras_bt_device *device,
    116 					void (*cb)(void *data))
    117 {
    118 	device->append_iodev_cb = cb;
    119 }
    120 
    121 enum cras_bt_device_profile cras_bt_device_profile_from_uuid(const char *uuid)
    122 {
    123 	if (strcmp(uuid, HSP_HS_UUID) == 0)
    124 		return CRAS_BT_DEVICE_PROFILE_HSP_HEADSET;
    125 	else if (strcmp(uuid, HSP_AG_UUID) == 0)
    126 		return CRAS_BT_DEVICE_PROFILE_HSP_AUDIOGATEWAY;
    127 	else if (strcmp(uuid, HFP_HF_UUID) == 0)
    128 		return CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE;
    129 	else if (strcmp(uuid, HFP_AG_UUID) == 0)
    130 		return CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY;
    131 	else if (strcmp(uuid, A2DP_SOURCE_UUID) == 0)
    132 		return CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE;
    133 	else if (strcmp(uuid, A2DP_SINK_UUID) == 0)
    134 		return CRAS_BT_DEVICE_PROFILE_A2DP_SINK;
    135 	else if (strcmp(uuid, AVRCP_REMOTE_UUID) == 0)
    136 		return CRAS_BT_DEVICE_PROFILE_AVRCP_REMOTE;
    137 	else if (strcmp(uuid, AVRCP_TARGET_UUID) == 0)
    138 		return CRAS_BT_DEVICE_PROFILE_AVRCP_TARGET;
    139 	else
    140 		return 0;
    141 }
    142 
    143 struct cras_bt_device *cras_bt_device_create(DBusConnection *conn,
    144 					     const char *object_path)
    145 {
    146 	struct cras_bt_device *device;
    147 
    148 	device = calloc(1, sizeof(*device));
    149 	if (device == NULL)
    150 		return NULL;
    151 
    152 	device->conn = conn;
    153 	device->object_path = strdup(object_path);
    154 	if (device->object_path == NULL) {
    155 		free(device);
    156 		return NULL;
    157 	}
    158 
    159 	DL_APPEND(devices, device);
    160 
    161 	return device;
    162 }
    163 
    164 static void on_connect_profile_reply(DBusPendingCall *pending_call, void *data)
    165 {
    166 	DBusMessage *reply;
    167 
    168 	reply = dbus_pending_call_steal_reply(pending_call);
    169 	dbus_pending_call_unref(pending_call);
    170 
    171 	if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
    172 		syslog(LOG_ERR, "Connect profile message replied error: %s",
    173 			dbus_message_get_error_name(reply));
    174 
    175 	dbus_message_unref(reply);
    176 }
    177 
    178 static void on_disconnect_reply(DBusPendingCall *pending_call, void *data)
    179 {
    180 	DBusMessage *reply;
    181 
    182 	reply = dbus_pending_call_steal_reply(pending_call);
    183 	dbus_pending_call_unref(pending_call);
    184 
    185 	if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
    186 		syslog(LOG_ERR, "Disconnect message replied error");
    187 
    188 	dbus_message_unref(reply);
    189 }
    190 
    191 int cras_bt_device_connect_profile(DBusConnection *conn,
    192 				   struct cras_bt_device *device,
    193 				   const char *uuid)
    194 {
    195 	DBusMessage *method_call;
    196 	DBusError dbus_error;
    197 	DBusPendingCall *pending_call;
    198 
    199 	method_call = dbus_message_new_method_call(
    200 			BLUEZ_SERVICE,
    201 			device->object_path,
    202 			BLUEZ_INTERFACE_DEVICE,
    203 			"ConnectProfile");
    204 	if (!method_call)
    205 		return -ENOMEM;
    206 
    207 	if (!dbus_message_append_args(method_call,
    208 				      DBUS_TYPE_STRING,
    209 				      &uuid,
    210 				      DBUS_TYPE_INVALID))
    211 		return -ENOMEM;
    212 
    213 	dbus_error_init(&dbus_error);
    214 
    215 	pending_call = NULL;
    216 	if (!dbus_connection_send_with_reply(conn,
    217 					     method_call,
    218 					     &pending_call,
    219 					     DBUS_TIMEOUT_USE_DEFAULT)) {
    220 		dbus_message_unref(method_call);
    221 		syslog(LOG_ERR, "Failed to send Disconnect message");
    222 		return -EIO;
    223 	}
    224 
    225 	dbus_message_unref(method_call);
    226 	if (!dbus_pending_call_set_notify(pending_call,
    227 					  on_connect_profile_reply,
    228 					  conn, NULL)) {
    229 		dbus_pending_call_cancel(pending_call);
    230 		dbus_pending_call_unref(pending_call);
    231 		return -EIO;
    232 	}
    233 	return 0;
    234 }
    235 
    236 int cras_bt_device_disconnect(DBusConnection *conn,
    237 			      struct cras_bt_device *device)
    238 {
    239 	DBusMessage *method_call;
    240 	DBusError dbus_error;
    241 	DBusPendingCall *pending_call;
    242 
    243 	method_call = dbus_message_new_method_call(
    244 			BLUEZ_SERVICE,
    245 			device->object_path,
    246 			BLUEZ_INTERFACE_DEVICE,
    247 			"Disconnect");
    248 	if (!method_call)
    249 		return -ENOMEM;
    250 
    251 	dbus_error_init(&dbus_error);
    252 
    253 	pending_call = NULL;
    254 	if (!dbus_connection_send_with_reply(conn,
    255 					     method_call,
    256 					     &pending_call,
    257 					     DBUS_TIMEOUT_USE_DEFAULT)) {
    258 		dbus_message_unref(method_call);
    259 		syslog(LOG_ERR, "Failed to send Disconnect message");
    260 		return -EIO;
    261 	}
    262 
    263 	dbus_message_unref(method_call);
    264 	if (!dbus_pending_call_set_notify(pending_call,
    265 					  on_disconnect_reply,
    266 					  conn, NULL)) {
    267 		dbus_pending_call_cancel(pending_call);
    268 		dbus_pending_call_unref(pending_call);
    269 		return -EIO;
    270 	}
    271 	return 0;
    272 }
    273 
    274 void cras_bt_device_destroy(struct cras_bt_device *device)
    275 {
    276 	struct cras_tm *tm = cras_system_state_get_tm();
    277 	DL_DELETE(devices, device);
    278 
    279 	if (device->conn_watch_timer)
    280 		cras_tm_cancel_timer(tm, device->conn_watch_timer);
    281 	if (device->switch_profile_timer)
    282 		cras_tm_cancel_timer(tm, device->switch_profile_timer);
    283 	if (device->suspend_timer)
    284 		cras_tm_cancel_timer(tm, device->suspend_timer);
    285 	free(device->object_path);
    286 	free(device->address);
    287 	free(device->name);
    288 	free(device);
    289 }
    290 
    291 void cras_bt_device_reset()
    292 {
    293 	while (devices) {
    294 		syslog(LOG_INFO, "Bluetooth Device: %s removed",
    295 		       devices->address);
    296 		cras_bt_device_destroy(devices);
    297 	}
    298 }
    299 
    300 
    301 struct cras_bt_device *cras_bt_device_get(const char *object_path)
    302 {
    303 	struct cras_bt_device *device;
    304 
    305 	DL_FOREACH(devices, device) {
    306 		if (strcmp(device->object_path, object_path) == 0)
    307 			return device;
    308 	}
    309 
    310 	return NULL;
    311 }
    312 
    313 size_t cras_bt_device_get_list(struct cras_bt_device ***device_list_out)
    314 {
    315 	struct cras_bt_device *device;
    316 	struct cras_bt_device **device_list = NULL;
    317 	size_t num_devices = 0;
    318 
    319 	DL_FOREACH(devices, device) {
    320 		struct cras_bt_device **tmp;
    321 
    322 		tmp = realloc(device_list,
    323 			      sizeof(device_list[0]) * (num_devices + 1));
    324 		if (!tmp) {
    325 			free(device_list);
    326 			return -ENOMEM;
    327 		}
    328 
    329 		device_list = tmp;
    330 		device_list[num_devices++] = device;
    331 	}
    332 
    333 	*device_list_out = device_list;
    334 	return num_devices;
    335 }
    336 
    337 const char *cras_bt_device_object_path(const struct cras_bt_device *device)
    338 {
    339 	return device->object_path;
    340 }
    341 
    342 struct cras_bt_adapter *cras_bt_device_adapter(
    343 	const struct cras_bt_device *device)
    344 {
    345 	return cras_bt_adapter_get(device->adapter_obj_path);
    346 }
    347 
    348 const char *cras_bt_device_address(const struct cras_bt_device *device)
    349 {
    350 	return device->address;
    351 }
    352 
    353 const char *cras_bt_device_name(const struct cras_bt_device *device)
    354 {
    355 	return device->name;
    356 }
    357 
    358 int cras_bt_device_paired(const struct cras_bt_device *device)
    359 {
    360 	return device->paired;
    361 }
    362 
    363 int cras_bt_device_trusted(const struct cras_bt_device *device)
    364 {
    365 	return device->trusted;
    366 }
    367 
    368 int cras_bt_device_connected(const struct cras_bt_device *device)
    369 {
    370 	return device->connected;
    371 }
    372 
    373 int cras_bt_device_supports_profile(const struct cras_bt_device *device,
    374 				    enum cras_bt_device_profile profile)
    375 {
    376 	return !!(device->profiles & profile);
    377 }
    378 
    379 void cras_bt_device_append_iodev(struct cras_bt_device *device,
    380 				 struct cras_iodev *iodev,
    381 				 enum cras_bt_device_profile profile)
    382 {
    383 	struct cras_iodev *bt_iodev;
    384 
    385 	bt_iodev = device->bt_iodevs[iodev->direction];
    386 
    387 	if (bt_iodev) {
    388 		cras_bt_io_append(bt_iodev, iodev, profile);
    389 	} else {
    390 		if (device->append_iodev_cb) {
    391 			device->append_iodev_cb(device);
    392 			device->append_iodev_cb = NULL;
    393 		}
    394 		device->bt_iodevs[iodev->direction] =
    395 				cras_bt_io_create(device, iodev, profile);
    396 	}
    397 }
    398 
    399 static void bt_device_switch_profile(struct cras_bt_device *device,
    400 				     struct cras_iodev *bt_iodev,
    401 				     int enable_dev);
    402 
    403 void cras_bt_device_rm_iodev(struct cras_bt_device *device,
    404 			     struct cras_iodev *iodev)
    405 {
    406 	struct cras_iodev *bt_iodev;
    407 	int rc;
    408 
    409 	bt_iodev = device->bt_iodevs[iodev->direction];
    410 	if (bt_iodev) {
    411 		unsigned try_profile;
    412 
    413 		/* Check what will the preffered profile be if we remove dev. */
    414 		try_profile = cras_bt_io_try_remove(bt_iodev, iodev);
    415 		if (!try_profile)
    416 			goto destroy_bt_io;
    417 
    418 		/* If the check result doesn't match with the active
    419 		 * profile we are currently using, switch to the
    420 		 * preffered profile before actually remove the iodev.
    421 		 */
    422 		if (!cras_bt_io_on_profile(bt_iodev, try_profile)) {
    423 			device->active_profile = try_profile;
    424 			bt_device_switch_profile(device, bt_iodev, 0);
    425 		}
    426 		rc = cras_bt_io_remove(bt_iodev, iodev);
    427 		if (rc) {
    428 			syslog(LOG_ERR, "Fail to fallback to profile %u",
    429 			       try_profile);
    430 			goto destroy_bt_io;
    431 		}
    432 	}
    433 	return;
    434 
    435 destroy_bt_io:
    436 	device->bt_iodevs[iodev->direction] = NULL;
    437 	cras_bt_io_destroy(bt_iodev);
    438 
    439 	if (!device->bt_iodevs[CRAS_STREAM_INPUT] &&
    440 	    !device->bt_iodevs[CRAS_STREAM_OUTPUT])
    441 		cras_bt_device_set_active_profile(device, 0);
    442 }
    443 
    444 void cras_bt_device_a2dp_configured(struct cras_bt_device *device)
    445 {
    446 	device->connected_profiles |= CRAS_BT_DEVICE_PROFILE_A2DP_SINK;
    447 }
    448 
    449 int cras_bt_device_has_a2dp(struct cras_bt_device *device)
    450 {
    451 	struct cras_iodev *odev = device->bt_iodevs[CRAS_STREAM_OUTPUT];
    452 
    453 	/* Check if there is an output iodev with A2DP node attached. */
    454 	return odev && cras_bt_io_get_profile(
    455 			odev, CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE);
    456 }
    457 
    458 int cras_bt_device_can_switch_to_a2dp(struct cras_bt_device *device)
    459 {
    460 	struct cras_iodev *idev = device->bt_iodevs[CRAS_STREAM_INPUT];
    461 
    462 	return cras_bt_device_has_a2dp(device) &&
    463 		(!idev || !cras_iodev_is_open(idev));
    464 }
    465 
    466 int cras_bt_device_audio_gateway_initialized(struct cras_bt_device *device)
    467 {
    468 	int rc = 0;
    469 	struct cras_tm *tm;
    470 
    471 	/* Marks HFP/HSP as connected. This is what connection watcher
    472 	 * checks. */
    473 	device->connected_profiles |=
    474 			(CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE |
    475 			 CRAS_BT_DEVICE_PROFILE_HSP_HEADSET);
    476 
    477 	/* If this is a HFP/HSP only headset, no need to wait for A2DP. */
    478 	if (!cras_bt_device_supports_profile(
    479 			device, CRAS_BT_DEVICE_PROFILE_A2DP_SINK)) {
    480 
    481 		syslog(LOG_DEBUG,
    482 		       "Start HFP audio gateway as A2DP is not supported");
    483 
    484 		rc = cras_hfp_ag_start(device);
    485 		if (rc) {
    486 			syslog(LOG_ERR, "Start audio gateway failed");
    487 			return rc;
    488 		}
    489 		if (device->conn_watch_timer) {
    490 			tm = cras_system_state_get_tm();
    491 			cras_tm_cancel_timer(tm, device->conn_watch_timer);
    492 			device->conn_watch_timer = NULL;
    493 		}
    494 	} else {
    495 		syslog(LOG_DEBUG, "HFP audio gateway is connected but A2DP "
    496 				  "is not connected yet");
    497 	}
    498 
    499 	return rc;
    500 }
    501 
    502 int cras_bt_device_get_active_profile(const struct cras_bt_device *device)
    503 {
    504 	return device->active_profile;
    505 }
    506 
    507 void cras_bt_device_set_active_profile(struct cras_bt_device *device,
    508 				       unsigned int profile)
    509 {
    510 	device->active_profile = profile;
    511 }
    512 
    513 static void cras_bt_device_log_profile(const struct cras_bt_device *device,
    514 				       enum cras_bt_device_profile profile)
    515 {
    516 	switch (profile) {
    517 	case CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE:
    518 		syslog(LOG_DEBUG, "Bluetooth Device: %s is HFP handsfree",
    519 		       device->address);
    520 		break;
    521 	case CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY:
    522 		syslog(LOG_DEBUG, "Bluetooth Device: %s is HFP audio gateway",
    523 		       device->address);
    524 		break;
    525 	case CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE:
    526 		syslog(LOG_DEBUG, "Bluetooth Device: %s is A2DP source",
    527 		       device->address);
    528 		break;
    529 	case CRAS_BT_DEVICE_PROFILE_A2DP_SINK:
    530 		syslog(LOG_DEBUG, "Bluetooth Device: %s is A2DP sink",
    531 		       device->address);
    532 		break;
    533 	case CRAS_BT_DEVICE_PROFILE_AVRCP_REMOTE:
    534 		syslog(LOG_DEBUG, "Bluetooth Device: %s is AVRCP remote",
    535 		       device->address);
    536 		break;
    537 	case CRAS_BT_DEVICE_PROFILE_AVRCP_TARGET:
    538 		syslog(LOG_DEBUG, "Bluetooth Device: %s is AVRCP target",
    539 		       device->address);
    540 		break;
    541 	case CRAS_BT_DEVICE_PROFILE_HSP_HEADSET:
    542 		syslog(LOG_DEBUG, "Bluetooth Device: %s is HSP headset",
    543 		       device->address);
    544 		break;
    545 	case CRAS_BT_DEVICE_PROFILE_HSP_AUDIOGATEWAY:
    546 		syslog(LOG_DEBUG, "Bluetooth Device: %s is HSP audio gateway",
    547 		       device->address);
    548 		break;
    549 	}
    550 }
    551 
    552 static int cras_bt_device_is_profile_connected(
    553 		const struct cras_bt_device *device,
    554 		enum cras_bt_device_profile profile)
    555 {
    556 	return !!(device->connected_profiles & profile);
    557 }
    558 
    559 static void bt_device_schedule_suspend(struct cras_bt_device *device,
    560 				       unsigned int msec);
    561 
    562 /* Callback used to periodically check if supported profiles are connected. */
    563 static void bt_device_conn_watch_cb(struct cras_timer *timer, void *arg)
    564 {
    565 	struct cras_tm *tm;
    566 	struct cras_bt_device *device = (struct cras_bt_device *)arg;
    567 
    568 	device->conn_watch_timer = NULL;
    569 
    570 	/* If A2DP is not ready, try connect it after a while. */
    571 	if (cras_bt_device_supports_profile(
    572 			device, CRAS_BT_DEVICE_PROFILE_A2DP_SINK) &&
    573 	    !cras_bt_device_is_profile_connected(
    574 			device, CRAS_BT_DEVICE_PROFILE_A2DP_SINK)) {
    575 		if (0 == device->conn_watch_retries % PROFILE_CONN_RETRIES)
    576 			cras_bt_device_connect_profile(
    577 					device->conn, device, A2DP_SINK_UUID);
    578 		goto arm_retry_timer;
    579 	}
    580 
    581 	/* If HFP is not ready, try connect it after a while. */
    582 	if (cras_bt_device_supports_profile(
    583 			device, CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE) &&
    584 	    !cras_bt_device_is_profile_connected(
    585 			device, CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE)) {
    586 		if (0 == device->conn_watch_retries % PROFILE_CONN_RETRIES)
    587 			cras_bt_device_connect_profile(
    588 					device->conn, device, HFP_HF_UUID);
    589 		goto arm_retry_timer;
    590 	}
    591 
    592 	if (cras_bt_device_is_profile_connected(
    593 			device, CRAS_BT_DEVICE_PROFILE_A2DP_SINK)) {
    594 		/* When A2DP-only device connected, suspend all HFP/HSP audio
    595 		 * gateways. */
    596 		if (!cras_bt_device_supports_profile(device,
    597 				CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE |
    598 				CRAS_BT_DEVICE_PROFILE_HSP_HEADSET))
    599 			cras_hfp_ag_suspend();
    600 
    601 		cras_a2dp_start(device);
    602 	}
    603 
    604 	if (cras_bt_device_is_profile_connected(
    605 			device, CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE))
    606 		cras_hfp_ag_start(device);
    607 	return;
    608 
    609 arm_retry_timer:
    610 
    611 	syslog(LOG_DEBUG, "conn_watch_retries: %d", device->conn_watch_retries);
    612 
    613 	if (--device->conn_watch_retries) {
    614 		tm = cras_system_state_get_tm();
    615 		device->conn_watch_timer = cras_tm_create_timer(tm,
    616 				CONN_WATCH_PERIOD_MS,
    617 				bt_device_conn_watch_cb, device);
    618 	} else {
    619 		syslog(LOG_ERR, "Connection watch timeout.");
    620 		bt_device_schedule_suspend(device, 0);
    621 	}
    622 }
    623 
    624 static void cras_bt_device_start_new_conn_watch_timer(
    625 		struct cras_bt_device *device)
    626 {
    627 	struct cras_tm *tm = cras_system_state_get_tm();
    628 
    629 	if (device->conn_watch_timer) {
    630 		cras_tm_cancel_timer(tm, device->conn_watch_timer);
    631 	}
    632 	device->conn_watch_retries = CONN_WATCH_MAX_RETRIES;
    633 	device->conn_watch_timer = cras_tm_create_timer(tm,
    634 			CONN_WATCH_PERIOD_MS,
    635 			bt_device_conn_watch_cb, device);
    636 }
    637 
    638 static void cras_bt_device_set_connected(struct cras_bt_device *device,
    639 					 int value)
    640 {
    641 	struct cras_tm *tm = cras_system_state_get_tm();
    642 
    643 	if (device->connected && !value) {
    644 		cras_bt_profile_on_device_disconnected(device);
    645 		/* Device is disconnected, resets connected profiles. */
    646 		device->connected_profiles = 0;
    647 	}
    648 
    649 	device->connected = value;
    650 
    651 	if (device->connected) {
    652 		cras_bt_device_start_new_conn_watch_timer(device);
    653 	} else if (device->conn_watch_timer) {
    654 		cras_tm_cancel_timer(tm, device->conn_watch_timer);
    655 		device->conn_watch_timer = NULL;
    656 	}
    657 }
    658 
    659 void cras_bt_device_update_properties(struct cras_bt_device *device,
    660 				      DBusMessageIter *properties_array_iter,
    661 				      DBusMessageIter *invalidated_array_iter)
    662 {
    663 
    664 	int get_profile = 0;
    665 
    666 	while (dbus_message_iter_get_arg_type(properties_array_iter) !=
    667 	       DBUS_TYPE_INVALID) {
    668 		DBusMessageIter properties_dict_iter, variant_iter;
    669 		const char *key;
    670 		int type;
    671 
    672 		dbus_message_iter_recurse(properties_array_iter,
    673 					  &properties_dict_iter);
    674 
    675 		dbus_message_iter_get_basic(&properties_dict_iter, &key);
    676 		dbus_message_iter_next(&properties_dict_iter);
    677 
    678 		dbus_message_iter_recurse(&properties_dict_iter, &variant_iter);
    679 		type = dbus_message_iter_get_arg_type(&variant_iter);
    680 
    681 		if (type == DBUS_TYPE_STRING || type == DBUS_TYPE_OBJECT_PATH) {
    682 			const char *value;
    683 
    684 			dbus_message_iter_get_basic(&variant_iter, &value);
    685 
    686 			if (strcmp(key, "Adapter") == 0) {
    687 				free(device->adapter_obj_path);
    688 				device->adapter_obj_path = strdup(value);
    689 			} else if (strcmp(key, "Address") == 0) {
    690 				free(device->address);
    691 				device->address = strdup(value);
    692 			} else if (strcmp(key, "Alias") == 0) {
    693 				free(device->name);
    694 				device->name = strdup(value);
    695 			}
    696 
    697 		} else if (type == DBUS_TYPE_UINT32) {
    698 			uint32_t value;
    699 
    700 			dbus_message_iter_get_basic(&variant_iter, &value);
    701 
    702 			if (strcmp(key, "Class") == 0)
    703 				device->bluetooth_class = value;
    704 
    705 		} else if (type == DBUS_TYPE_BOOLEAN) {
    706 			int value;
    707 
    708 			dbus_message_iter_get_basic(&variant_iter, &value);
    709 
    710 			if (strcmp(key, "Paired") == 0) {
    711 				device->paired = value;
    712 			} else if (strcmp(key, "Trusted") == 0) {
    713 				device->trusted = value;
    714 			} else if (strcmp(key, "Connected") == 0) {
    715 				cras_bt_device_set_connected(device, value);
    716 			}
    717 
    718 		} else if (strcmp(
    719 				dbus_message_iter_get_signature(&variant_iter),
    720 				"as") == 0 &&
    721 			   strcmp(key, "UUIDs") == 0) {
    722 			DBusMessageIter uuid_array_iter;
    723 
    724 			dbus_message_iter_recurse(&variant_iter,
    725 						  &uuid_array_iter);
    726 			while (dbus_message_iter_get_arg_type(
    727 				       &uuid_array_iter) != DBUS_TYPE_INVALID) {
    728 				const char *uuid;
    729 				enum cras_bt_device_profile profile;
    730 
    731 				get_profile = 1;
    732 
    733 				dbus_message_iter_get_basic(&uuid_array_iter,
    734 							    &uuid);
    735 				profile = cras_bt_device_profile_from_uuid(
    736 					uuid);
    737 
    738 				device->profiles |= profile;
    739 				cras_bt_device_log_profile(device, profile);
    740 
    741 				dbus_message_iter_next(&uuid_array_iter);
    742 			}
    743 		}
    744 
    745 		dbus_message_iter_next(properties_array_iter);
    746 	}
    747 
    748 	while (invalidated_array_iter &&
    749 	       dbus_message_iter_get_arg_type(invalidated_array_iter) !=
    750 	       DBUS_TYPE_INVALID) {
    751 		const char *key;
    752 
    753 		dbus_message_iter_get_basic(invalidated_array_iter, &key);
    754 
    755 		if (strcmp(key, "Adapter") == 0) {
    756 			free(device->adapter_obj_path);
    757 			device->adapter_obj_path = NULL;
    758 		} else if (strcmp(key, "Address") == 0) {
    759 			free(device->address);
    760 			device->address = NULL;
    761 		} else if (strcmp(key, "Alias") == 0) {
    762 			free(device->name);
    763 			device->name = NULL;
    764 		} else if (strcmp(key, "Class") == 0) {
    765 			device->bluetooth_class = 0;
    766 		} else if (strcmp(key, "Paired") == 0) {
    767 			device->paired = 0;
    768 		} else if (strcmp(key, "Trusted") == 0) {
    769 			device->trusted = 0;
    770 		} else if (strcmp(key, "Connected") == 0) {
    771 			device->connected = 0;
    772 		} else if (strcmp(key, "UUIDs") == 0) {
    773 			device->profiles = 0;
    774 		}
    775 
    776 		dbus_message_iter_next(invalidated_array_iter);
    777 	}
    778 
    779 	/* If updated properties includes profile, and device is connected,
    780 	 * we need to start connection watcher. This is needed because on
    781 	 * some bluetooth device, supported profiles do not present when
    782 	 * device interface is added and they are updated later.
    783 	 */
    784 	if (get_profile && device->connected) {
    785 		cras_bt_device_start_new_conn_watch_timer(device);
    786 	}
    787 }
    788 
    789 /* Converts bluetooth address string into sockaddr structure. The address
    790  * string is expected of the form 1A:2B:3C:4D:5E:6F, and each of the six
    791  * hex values will be parsed into sockaddr in inverse order.
    792  * Args:
    793  *    str - The string version of bluetooth address
    794  *    addr - The struct to be filled with converted address
    795  */
    796 static int bt_address(const char *str, struct sockaddr *addr)
    797 {
    798 	int i;
    799 
    800 	if (strlen(str) != 17) {
    801 		syslog(LOG_ERR, "Invalid bluetooth address %s", str);
    802 		return -1;
    803 	}
    804 
    805 	memset(addr, 0, sizeof(*addr));
    806 	addr->sa_family = AF_BLUETOOTH;
    807 	for (i = 5; i >= 0; i--) {
    808 		addr->sa_data[i] = (unsigned char)strtol(str, NULL, 16);
    809 		str += 3;
    810 	}
    811 
    812 	return 0;
    813 }
    814 
    815 int cras_bt_device_sco_connect(struct cras_bt_device *device)
    816 {
    817 	int sk = 0, err;
    818 	struct sockaddr addr;
    819 	struct cras_bt_adapter *adapter;
    820 	struct timespec timeout = { 1, 0 };
    821 	struct pollfd *pollfds;
    822 
    823 	adapter = cras_bt_device_adapter(device);
    824 	if (!adapter) {
    825 		syslog(LOG_ERR, "No adapter found for device %s at SCO connect",
    826 		       cras_bt_device_object_path(device));
    827 		goto error;
    828 	}
    829 
    830 	sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO);
    831 	if (sk < 0) {
    832 		syslog(LOG_ERR, "Failed to create socket: %s (%d)",
    833 				strerror(errno), errno);
    834 		return -errno;
    835 	}
    836 
    837 	/* Bind to local address */
    838 	if (bt_address(cras_bt_adapter_address(adapter), &addr))
    839 		goto error;
    840 	if (bind(sk, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
    841 		syslog(LOG_ERR, "Failed to bind socket: %s (%d)",
    842 				strerror(errno), errno);
    843 		goto error;
    844 	}
    845 
    846 	/* Connect to remote in nonblocking mode */
    847 	fcntl(sk, F_SETFL, O_NONBLOCK);
    848 	pollfds = (struct pollfd *)malloc(sizeof(*pollfds));
    849 	pollfds[0].fd = sk;
    850 	pollfds[0].events = POLLOUT;
    851 
    852 	if (bt_address(cras_bt_device_address(device), &addr))
    853 		goto error;
    854 	err = connect(sk, (struct sockaddr *) &addr, sizeof(addr));
    855 	if (err && errno != EINPROGRESS) {
    856 		syslog(LOG_ERR, "Failed to connect: %s (%d)",
    857 				strerror(errno), errno);
    858 		goto error;
    859 	}
    860 
    861 	err = ppoll(pollfds, 1, &timeout, NULL);
    862 	if (err <= 0) {
    863 		syslog(LOG_ERR, "Connect SCO: poll for writable timeout");
    864 		goto error;
    865 	}
    866 
    867 	if (pollfds[0].revents & (POLLERR | POLLHUP)) {
    868 		syslog(LOG_ERR, "SCO socket error, revents: %u",
    869 		       pollfds[0].revents);
    870 		bt_device_schedule_suspend(device, 0);
    871 		goto error;
    872 	}
    873 
    874 	return sk;
    875 
    876 error:
    877 	if (sk)
    878 		close(sk);
    879 	return -1;
    880 }
    881 
    882 int cras_bt_device_sco_mtu(struct cras_bt_device *device, int sco_socket)
    883 {
    884 	struct sco_options so;
    885 	socklen_t len = sizeof(so);
    886 	struct cras_bt_adapter *adapter;
    887 
    888 	adapter = cras_bt_adapter_get(device->adapter_obj_path);
    889 	if (cras_bt_adapter_on_usb(adapter))
    890 		return DEFAULT_HFP_MTU_BYTES;
    891 
    892 	if (getsockopt(sco_socket, SOL_SCO, SCO_OPTIONS, &so, &len) < 0) {
    893 		syslog(LOG_ERR, "Get SCO options error: %s", strerror(errno));
    894 		return DEFAULT_HFP_MTU_BYTES;
    895 	}
    896 	return so.mtu;
    897 }
    898 
    899 void cras_bt_device_set_use_hardware_volume(struct cras_bt_device *device,
    900 					    int use_hardware_volume)
    901 {
    902 	struct cras_iodev *iodev;
    903 
    904 	device->use_hardware_volume = use_hardware_volume;
    905 	iodev = device->bt_iodevs[CRAS_STREAM_OUTPUT];
    906 	if (iodev)
    907 		iodev->software_volume_needed = !use_hardware_volume;
    908 }
    909 
    910 int cras_bt_device_get_use_hardware_volume(struct cras_bt_device *device)
    911 {
    912 	return device->use_hardware_volume;
    913 }
    914 
    915 static void init_bt_device_msg(struct bt_device_msg *msg,
    916 			       enum BT_DEVICE_COMMAND cmd,
    917 			       struct cras_bt_device *device,
    918 			       struct cras_iodev *dev,
    919 			       unsigned int arg)
    920 {
    921 	memset(msg, 0, sizeof(*msg));
    922 	msg->header.type = CRAS_MAIN_BT;
    923 	msg->header.length = sizeof(*msg);
    924 	msg->cmd = cmd;
    925 	msg->device = device;
    926 	msg->dev = dev;
    927 	msg->arg = arg;
    928 }
    929 
    930 int cras_bt_device_cancel_suspend(struct cras_bt_device *device)
    931 {
    932 	struct bt_device_msg msg;
    933 	int rc;
    934 
    935 	init_bt_device_msg(&msg, BT_DEVICE_CANCEL_SUSPEND, device, NULL, 0);
    936 	rc = cras_main_message_send((struct cras_main_message *)&msg);
    937 	return rc;
    938 }
    939 
    940 int cras_bt_device_schedule_suspend(struct cras_bt_device *device,
    941 				    unsigned int msec)
    942 {
    943 	struct bt_device_msg msg;
    944 	int rc;
    945 
    946 	init_bt_device_msg(&msg, BT_DEVICE_SCHEDULE_SUSPEND, device,
    947 			   NULL, msec);
    948 	rc = cras_main_message_send((struct cras_main_message *)&msg);
    949 	return rc;
    950 }
    951 
    952 /* This diagram describes how the profile switching happens. When
    953  * certain conditions met, bt iodev will call the APIs below to interact
    954  * with main thread to switch to another active profile.
    955  *
    956  * Audio thread:
    957  *  +--------------------------------------------------------------+
    958  *  | bt iodev                                                     |
    959  *  |              +------------------+    +-----------------+     |
    960  *  |              | condition met to |    | open, close, or |     |
    961  *  |           +--| change profile   |<---| append profile  |<--+ |
    962  *  |           |  +------------------+    +-----------------+   | |
    963  *  +-----------|------------------------------------------------|-+
    964  *              |                                                |
    965  * Main thread: |
    966  *  +-----------|------------------------------------------------|-+
    967  *  |           |                                                | |
    968  *  |           |      +------------+     +----------------+     | |
    969  *  |           +----->| set active |---->| switch profile |-----+ |
    970  *  |                  | profile    |     +----------------+       |
    971  *  | bt device        +------------+                              |
    972  *  +--------------------------------------------------------------+
    973  */
    974 int cras_bt_device_switch_profile_enable_dev(struct cras_bt_device *device,
    975 					     struct cras_iodev *bt_iodev)
    976 {
    977 	struct bt_device_msg msg;
    978 	int rc;
    979 
    980 	init_bt_device_msg(&msg, BT_DEVICE_SWITCH_PROFILE_ENABLE_DEV,
    981 			   device, bt_iodev, 0);
    982 	rc = cras_main_message_send((struct cras_main_message *)&msg);
    983 	return rc;
    984 }
    985 
    986 int cras_bt_device_switch_profile(struct cras_bt_device *device,
    987 				  struct cras_iodev *bt_iodev)
    988 {
    989 	struct bt_device_msg msg;
    990 	int rc;
    991 
    992 	init_bt_device_msg(&msg, BT_DEVICE_SWITCH_PROFILE,
    993 			   device, bt_iodev, 0);
    994 	rc = cras_main_message_send((struct cras_main_message *)&msg);
    995 	return rc;
    996 }
    997 
    998 void cras_bt_device_iodev_buffer_size_changed(struct cras_bt_device *device)
    999 {
   1000 	struct cras_iodev *iodev;
   1001 
   1002 	iodev = device->bt_iodevs[CRAS_STREAM_INPUT];
   1003 	if (iodev && cras_iodev_is_open(iodev))
   1004 		cras_bt_io_update_buffer_size(iodev);
   1005 	iodev = device->bt_iodevs[CRAS_STREAM_OUTPUT];
   1006 	if (iodev && cras_iodev_is_open(iodev))
   1007 		cras_bt_io_update_buffer_size(iodev);
   1008 }
   1009 
   1010 static void profile_switch_delay_cb(struct cras_timer *timer, void *arg)
   1011 {
   1012 	struct cras_bt_device *device = (struct cras_bt_device *)arg;
   1013 	struct cras_iodev *iodev;
   1014 
   1015 	device->switch_profile_timer = NULL;
   1016 	iodev = device->bt_iodevs[CRAS_STREAM_OUTPUT];
   1017 	if (!iodev)
   1018 		return;
   1019 
   1020 	/*
   1021 	 * During the |PROFILE_SWITCH_DELAY_MS| time interval, BT iodev could
   1022 	 * have been enabled by others, and its active profile may have changed.
   1023 	 * If iodev has been enabled, that means it has already picked up a
   1024 	 * reasonable profile to use and audio thread is accessing iodev now.
   1025 	 * We should NOT call into update_active_node from main thread
   1026 	 * because that may mess up the active node content.
   1027 	 */
   1028 	if (cras_iodev_list_dev_is_enabled(iodev))
   1029 		return;
   1030 
   1031 	iodev->update_active_node(iodev, 0, 1);
   1032 	cras_iodev_list_enable_dev(iodev);
   1033 }
   1034 
   1035 static void bt_device_switch_profile_with_delay(struct cras_bt_device *device,
   1036 						unsigned int delay_ms)
   1037 {
   1038 	struct cras_tm *tm = cras_system_state_get_tm();
   1039 
   1040 	if (device->switch_profile_timer) {
   1041 		cras_tm_cancel_timer(tm, device->switch_profile_timer);
   1042 		device->switch_profile_timer = NULL;
   1043 	}
   1044 	device->switch_profile_timer = cras_tm_create_timer(
   1045 			tm, delay_ms, profile_switch_delay_cb, device);
   1046 }
   1047 
   1048 /* Switches associated bt iodevs to use the active profile. This is
   1049  * achieved by close the iodevs, update their active nodes, and then
   1050  * finally reopen them. */
   1051 static void bt_device_switch_profile(struct cras_bt_device *device,
   1052 				     struct cras_iodev *bt_iodev,
   1053 				     int enable_dev)
   1054 {
   1055 	struct cras_iodev *iodev;
   1056 	int was_enabled[CRAS_NUM_DIRECTIONS] = {0};
   1057 	int dir;
   1058 
   1059 	/* If a bt iodev is active, temporarily remove it from the active
   1060 	 * device list. Note that we need to check all bt_iodevs for the
   1061 	 * situation that both input and output are active while switches
   1062 	 * from HFP/HSP to A2DP.
   1063 	 */
   1064 	for (dir = 0; dir < CRAS_NUM_DIRECTIONS; dir++) {
   1065 		iodev = device->bt_iodevs[dir];
   1066 		if (!iodev)
   1067 			continue;
   1068 		was_enabled[dir] = cras_iodev_list_dev_is_enabled(iodev);
   1069 		cras_iodev_list_disable_dev(iodev, false);
   1070 	}
   1071 
   1072 	for (dir = 0; dir < CRAS_NUM_DIRECTIONS; dir++) {
   1073 		iodev = device->bt_iodevs[dir];
   1074 		if (!iodev)
   1075 			continue;
   1076 
   1077 		/* If the iodev was active or this profile switching is
   1078 		 * triggered at opening iodev, add it to active dev list.
   1079 		 * However for the output iodev, adding it back to active dev
   1080 		 * list could cause immediate switching from HFP to A2DP if
   1081 		 * there exists an output stream. Certain headset/speaker
   1082 		 * would fail to playback afterwards when the switching happens
   1083 		 * too soon, so put this task in a delayed callback.
   1084 		 */
   1085 		if (was_enabled[dir] ||
   1086 		    (enable_dev && iodev == bt_iodev)) {
   1087 			if (dir == CRAS_STREAM_INPUT) {
   1088 				iodev->update_active_node(iodev, 0, 1);
   1089 				cras_iodev_list_enable_dev(iodev);
   1090 			} else {
   1091 				bt_device_switch_profile_with_delay(
   1092 						device,
   1093 						PROFILE_SWITCH_DELAY_MS);
   1094 			}
   1095 		}
   1096 	}
   1097 }
   1098 
   1099 static void bt_device_suspend_cb(struct cras_timer *timer, void *arg)
   1100 {
   1101 	struct cras_bt_device *device = (struct cras_bt_device *)arg;
   1102 
   1103 	device->suspend_timer = NULL;
   1104 
   1105 	cras_a2dp_suspend_connected_device(device);
   1106 	cras_hfp_ag_suspend_connected_device(device);
   1107 }
   1108 
   1109 static void bt_device_schedule_suspend(struct cras_bt_device *device,
   1110 				       unsigned int msec)
   1111 {
   1112 	struct cras_tm *tm = cras_system_state_get_tm();
   1113 
   1114 	if (device->suspend_timer)
   1115 		return;
   1116 	device->suspend_timer = cras_tm_create_timer(tm, msec,
   1117 			bt_device_suspend_cb, device);
   1118 }
   1119 
   1120 static void bt_device_cancel_suspend(struct cras_bt_device *device)
   1121 {
   1122 	struct cras_tm *tm = cras_system_state_get_tm();
   1123 	if (device->suspend_timer == NULL)
   1124 		return;
   1125 	cras_tm_cancel_timer(tm, device->suspend_timer);
   1126 	device->suspend_timer = NULL;
   1127 }
   1128 
   1129 static void bt_device_process_msg(struct cras_main_message *msg, void *arg)
   1130 {
   1131 	struct bt_device_msg *bt_msg = (struct bt_device_msg *)msg;
   1132 	struct cras_bt_device *device = NULL;
   1133 
   1134 	DL_FOREACH(devices, device) {
   1135 		if (device == bt_msg->device)
   1136 			break;
   1137 	}
   1138 
   1139 	/* Do nothing if target device no longer exists. */
   1140 	if (device == NULL)
   1141 		return;
   1142 
   1143 	switch (bt_msg->cmd) {
   1144 	case BT_DEVICE_SWITCH_PROFILE:
   1145 		bt_device_switch_profile(bt_msg->device, bt_msg->dev, 0);
   1146 		break;
   1147 	case BT_DEVICE_SWITCH_PROFILE_ENABLE_DEV:
   1148 		bt_device_switch_profile(bt_msg->device, bt_msg->dev, 1);
   1149 		break;
   1150 	case BT_DEVICE_SCHEDULE_SUSPEND:
   1151 		bt_device_schedule_suspend(bt_msg->device, bt_msg->arg);
   1152 		break;
   1153 	case BT_DEVICE_CANCEL_SUSPEND:
   1154 		bt_device_cancel_suspend(bt_msg->device);
   1155 		break;
   1156 	default:
   1157 		break;
   1158 	}
   1159 }
   1160 
   1161 void cras_bt_device_start_monitor()
   1162 {
   1163 	cras_main_message_add_handler(CRAS_MAIN_BT,
   1164 				      bt_device_process_msg, NULL);
   1165 }
   1166 
   1167 void cras_bt_device_update_hardware_volume(struct cras_bt_device *device,
   1168 					   int volume)
   1169 {
   1170 	struct cras_iodev *iodev;
   1171 
   1172 	iodev = device->bt_iodevs[CRAS_STREAM_OUTPUT];
   1173 	if (iodev == NULL)
   1174 		return;
   1175 
   1176 	/* Check if this BT device is okay to use hardware volume. If not
   1177 	 * then ignore the reported volume change event.
   1178 	 */
   1179 	if (!cras_bt_device_get_use_hardware_volume(device))
   1180 		return;
   1181 
   1182 	iodev->active_node->volume = volume;
   1183 	cras_iodev_list_notify_node_volume(iodev->active_node);
   1184 }
   1185