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