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_log.h"
27 #include "cras_bt_io.h"
28 #include "cras_bt_profile.h"
29 #include "cras_hfp_ag_profile.h"
30 #include "cras_hfp_slc.h"
31 #include "cras_iodev.h"
32 #include "cras_iodev_list.h"
33 #include "cras_main_message.h"
34 #include "cras_server_metrics.h"
35 #include "cras_system_state.h"
36 #include "cras_tm.h"
37 #include "sfh.h"
38 #include "utlist.h"
39 
40 /*
41  * Bluetooth Core 5.0 spec, vol 4, part B, section 2 describes
42  * the recommended HCI packet size in one USB transfer for CVSD
43  * and MSBC codec.
44  */
45 #define USB_MSBC_PKT_SIZE 60
46 #define USB_CVSD_PKT_SIZE 48
47 #define DEFAULT_SCO_PKT_SIZE USB_CVSD_PKT_SIZE
48 
49 static const unsigned int PROFILE_SWITCH_DELAY_MS = 500;
50 static const unsigned int PROFILE_DROP_SUSPEND_DELAY_MS = 5000;
51 
52 /* Check profile connections every 2 seconds and rerty 30 times maximum.
53  * Attemp to connect profiles which haven't been ready every 3 retries.
54  */
55 static const unsigned int CONN_WATCH_PERIOD_MS = 2000;
56 static const unsigned int CONN_WATCH_MAX_RETRIES = 30;
57 
58 /* This is used when a critical SCO failure happens and is worth scheduling a
59  * suspend in case for some reason BT headset stays connected in baseband and
60  * confuses user.
61  */
62 static const unsigned int SCO_SUSPEND_DELAY_MS = 5000;
63 
64 static const unsigned int CRAS_SUPPORTED_PROFILES =
65 	CRAS_BT_DEVICE_PROFILE_A2DP_SINK | CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE;
66 
67 /* Object to represent a general bluetooth device, and used to
68  * associate with some CRAS modules if it supports audio.
69  * Members:
70  *    conn - The dbus connection object used to send message to bluetoothd.
71  *    object_path - Object path of the bluetooth device.
72  *    adapter - The object path of the adapter associates with this device.
73  *    address - The BT address of this device.
74  *    name - The readable name of this device.
75  *    bluetooth_class - The bluetooth class of this device.
76  *    paired - If this device is paired.
77  *    trusted - If this device is trusted.
78  *    connected - If this devices is connected.
79  *    connected_profiles - OR'ed all connected audio profiles.
80  *    profiles - OR'ed by all audio profiles this device supports.
81  *    hidden_profiles - OR'ed by all audio profiles this device actually
82  *        supports but is not scanned by BlueZ.
83  *    bt_iodevs - The pointer to the cras_iodevs of this device.
84  *    active_profile - The flag to indicate the active audio profile this
85  *        device is currently using.
86  *    conn_watch_retries - The retry count for conn_watch_timer.
87  *    conn_watch_timer - The timer used to watch connected profiles and start
88  *        BT audio input/ouput when all profiles are ready.
89  *    suspend_timer - The timer used to suspend device.
90  *    switch_profile_timer - The timer used to delay enabling iodev after
91  *        profile switch.
92  *    sco_fd - The file descriptor of the SCO connection.
93  *    sco_ref_count - The reference counts of the SCO connection.
94  *    suspend_reason - The reason code for why suspend is scheduled.
95  *    stable_id - The unique and persistent id of this bt_device.
96  */
97 struct cras_bt_device {
98 	DBusConnection *conn;
99 	char *object_path;
100 	char *adapter_obj_path;
101 	char *address;
102 	char *name;
103 	uint32_t bluetooth_class;
104 	int paired;
105 	int trusted;
106 	int connected;
107 	unsigned int connected_profiles;
108 	unsigned int profiles;
109 	unsigned int hidden_profiles;
110 	struct cras_iodev *bt_iodevs[CRAS_NUM_DIRECTIONS];
111 	unsigned int active_profile;
112 	int use_hardware_volume;
113 	int conn_watch_retries;
114 	struct cras_timer *conn_watch_timer;
115 	struct cras_timer *suspend_timer;
116 	struct cras_timer *switch_profile_timer;
117 	int sco_fd;
118 	size_t sco_ref_count;
119 	enum cras_bt_device_suspend_reason suspend_reason;
120 	unsigned int stable_id;
121 
122 	struct cras_bt_device *prev, *next;
123 };
124 
125 enum BT_DEVICE_COMMAND {
126 	BT_DEVICE_CANCEL_SUSPEND,
127 	BT_DEVICE_SCHEDULE_SUSPEND,
128 	BT_DEVICE_SWITCH_PROFILE,
129 	BT_DEVICE_SWITCH_PROFILE_ENABLE_DEV,
130 };
131 
132 struct bt_device_msg {
133 	struct cras_main_message header;
134 	enum BT_DEVICE_COMMAND cmd;
135 	struct cras_bt_device *device;
136 	struct cras_iodev *dev;
137 	unsigned int arg1;
138 	unsigned int arg2;
139 };
140 
141 static struct cras_bt_device *devices;
142 
cras_bt_device_profile_from_uuid(const char * uuid)143 enum cras_bt_device_profile cras_bt_device_profile_from_uuid(const char *uuid)
144 {
145 	if (strcmp(uuid, HSP_HS_UUID) == 0)
146 		return CRAS_BT_DEVICE_PROFILE_HSP_HEADSET;
147 	else if (strcmp(uuid, HSP_AG_UUID) == 0)
148 		return CRAS_BT_DEVICE_PROFILE_HSP_AUDIOGATEWAY;
149 	else if (strcmp(uuid, HFP_HF_UUID) == 0)
150 		return CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE;
151 	else if (strcmp(uuid, HFP_AG_UUID) == 0)
152 		return CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY;
153 	else if (strcmp(uuid, A2DP_SOURCE_UUID) == 0)
154 		return CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE;
155 	else if (strcmp(uuid, A2DP_SINK_UUID) == 0)
156 		return CRAS_BT_DEVICE_PROFILE_A2DP_SINK;
157 	else if (strcmp(uuid, AVRCP_REMOTE_UUID) == 0)
158 		return CRAS_BT_DEVICE_PROFILE_AVRCP_REMOTE;
159 	else if (strcmp(uuid, AVRCP_TARGET_UUID) == 0)
160 		return CRAS_BT_DEVICE_PROFILE_AVRCP_TARGET;
161 	else
162 		return 0;
163 }
164 
cras_bt_device_create(DBusConnection * conn,const char * object_path)165 struct cras_bt_device *cras_bt_device_create(DBusConnection *conn,
166 					     const char *object_path)
167 {
168 	struct cras_bt_device *device;
169 
170 	device = calloc(1, sizeof(*device));
171 	if (device == NULL)
172 		return NULL;
173 
174 	device->conn = conn;
175 	device->object_path = strdup(object_path);
176 	if (device->object_path == NULL) {
177 		free(device);
178 		return NULL;
179 	}
180 	device->stable_id =
181 		SuperFastHash(device->object_path, strlen(device->object_path),
182 			      strlen(device->object_path));
183 
184 	DL_APPEND(devices, device);
185 
186 	return device;
187 }
188 
on_connect_profile_reply(DBusPendingCall * pending_call,void * data)189 static void on_connect_profile_reply(DBusPendingCall *pending_call, void *data)
190 {
191 	DBusMessage *reply;
192 
193 	reply = dbus_pending_call_steal_reply(pending_call);
194 	dbus_pending_call_unref(pending_call);
195 
196 	if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
197 		syslog(LOG_ERR, "Connect profile message replied error: %s",
198 		       dbus_message_get_error_name(reply));
199 
200 	dbus_message_unref(reply);
201 }
202 
on_disconnect_reply(DBusPendingCall * pending_call,void * data)203 static void on_disconnect_reply(DBusPendingCall *pending_call, void *data)
204 {
205 	DBusMessage *reply;
206 
207 	reply = dbus_pending_call_steal_reply(pending_call);
208 	dbus_pending_call_unref(pending_call);
209 
210 	if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
211 		syslog(LOG_ERR, "Disconnect message replied error");
212 
213 	dbus_message_unref(reply);
214 }
215 
cras_bt_device_connect_profile(DBusConnection * conn,struct cras_bt_device * device,const char * uuid)216 int cras_bt_device_connect_profile(DBusConnection *conn,
217 				   struct cras_bt_device *device,
218 				   const char *uuid)
219 {
220 	DBusMessage *method_call;
221 	DBusError dbus_error;
222 	DBusPendingCall *pending_call;
223 
224 	method_call =
225 		dbus_message_new_method_call(BLUEZ_SERVICE, device->object_path,
226 					     BLUEZ_INTERFACE_DEVICE,
227 					     "ConnectProfile");
228 	if (!method_call)
229 		return -ENOMEM;
230 
231 	if (!dbus_message_append_args(method_call, DBUS_TYPE_STRING, &uuid,
232 				      DBUS_TYPE_INVALID))
233 		return -ENOMEM;
234 
235 	dbus_error_init(&dbus_error);
236 
237 	pending_call = NULL;
238 	if (!dbus_connection_send_with_reply(conn, method_call, &pending_call,
239 					     DBUS_TIMEOUT_USE_DEFAULT)) {
240 		dbus_message_unref(method_call);
241 		syslog(LOG_ERR, "Failed to send Disconnect message");
242 		return -EIO;
243 	}
244 
245 	dbus_message_unref(method_call);
246 	if (!dbus_pending_call_set_notify(
247 		    pending_call, on_connect_profile_reply, conn, NULL)) {
248 		dbus_pending_call_cancel(pending_call);
249 		dbus_pending_call_unref(pending_call);
250 		return -EIO;
251 	}
252 	return 0;
253 }
254 
cras_bt_device_disconnect(DBusConnection * conn,struct cras_bt_device * device)255 int cras_bt_device_disconnect(DBusConnection *conn,
256 			      struct cras_bt_device *device)
257 {
258 	DBusMessage *method_call;
259 	DBusError dbus_error;
260 	DBusPendingCall *pending_call;
261 
262 	method_call =
263 		dbus_message_new_method_call(BLUEZ_SERVICE, device->object_path,
264 					     BLUEZ_INTERFACE_DEVICE,
265 					     "Disconnect");
266 	if (!method_call)
267 		return -ENOMEM;
268 
269 	dbus_error_init(&dbus_error);
270 
271 	pending_call = NULL;
272 	if (!dbus_connection_send_with_reply(conn, method_call, &pending_call,
273 					     DBUS_TIMEOUT_USE_DEFAULT)) {
274 		dbus_message_unref(method_call);
275 		syslog(LOG_ERR, "Failed to send Disconnect message");
276 		return -EIO;
277 	}
278 
279 	dbus_message_unref(method_call);
280 	if (!dbus_pending_call_set_notify(pending_call, on_disconnect_reply,
281 					  conn, NULL)) {
282 		dbus_pending_call_cancel(pending_call);
283 		dbus_pending_call_unref(pending_call);
284 		return -EIO;
285 	}
286 	return 0;
287 }
288 
cras_bt_device_destroy(struct cras_bt_device * device)289 static void cras_bt_device_destroy(struct cras_bt_device *device)
290 {
291 	struct cras_tm *tm = cras_system_state_get_tm();
292 	DL_DELETE(devices, device);
293 
294 	if (device->conn_watch_timer)
295 		cras_tm_cancel_timer(tm, device->conn_watch_timer);
296 	if (device->switch_profile_timer)
297 		cras_tm_cancel_timer(tm, device->switch_profile_timer);
298 	if (device->suspend_timer)
299 		cras_tm_cancel_timer(tm, device->suspend_timer);
300 	free(device->adapter_obj_path);
301 	free(device->object_path);
302 	free(device->address);
303 	free(device->name);
304 	free(device);
305 }
306 
cras_bt_device_remove(struct cras_bt_device * device)307 void cras_bt_device_remove(struct cras_bt_device *device)
308 {
309 	/*
310 	 * We expect BT stack to disconnect this device before removing it,
311 	 * but it may not the case if there's issue at BT side. Print error
312 	 * log whenever this happens.
313 	 */
314 	if (device->connected)
315 		syslog(LOG_ERR, "Removing dev with connected profiles %u",
316 		       device->connected_profiles);
317 	/*
318 	 * Possibly clean up the associated A2DP and HFP AG iodevs that are
319 	 * still accessing this device.
320 	 */
321 	cras_a2dp_suspend_connected_device(device);
322 	cras_hfp_ag_suspend_connected_device(device);
323 	cras_bt_device_destroy(device);
324 }
325 
cras_bt_device_reset()326 void cras_bt_device_reset()
327 {
328 	while (devices) {
329 		syslog(LOG_INFO, "Bluetooth Device: %s removed",
330 		       devices->address);
331 		cras_bt_device_destroy(devices);
332 	}
333 }
334 
cras_bt_device_get(const char * object_path)335 struct cras_bt_device *cras_bt_device_get(const char *object_path)
336 {
337 	struct cras_bt_device *device;
338 
339 	DL_FOREACH (devices, device) {
340 		if (strcmp(device->object_path, object_path) == 0)
341 			return device;
342 	}
343 
344 	return NULL;
345 }
346 
cras_bt_device_object_path(const struct cras_bt_device * device)347 const char *cras_bt_device_object_path(const struct cras_bt_device *device)
348 {
349 	return device->object_path;
350 }
351 
cras_bt_device_get_stable_id(const struct cras_bt_device * device)352 int cras_bt_device_get_stable_id(const struct cras_bt_device *device)
353 {
354 	return device->stable_id;
355 }
356 
357 struct cras_bt_adapter *
cras_bt_device_adapter(const struct cras_bt_device * device)358 cras_bt_device_adapter(const struct cras_bt_device *device)
359 {
360 	return cras_bt_adapter_get(device->adapter_obj_path);
361 }
362 
cras_bt_device_address(const struct cras_bt_device * device)363 const char *cras_bt_device_address(const struct cras_bt_device *device)
364 {
365 	return device->address;
366 }
367 
cras_bt_device_name(const struct cras_bt_device * device)368 const char *cras_bt_device_name(const struct cras_bt_device *device)
369 {
370 	return device->name;
371 }
372 
cras_bt_device_paired(const struct cras_bt_device * device)373 int cras_bt_device_paired(const struct cras_bt_device *device)
374 {
375 	return device->paired;
376 }
377 
cras_bt_device_trusted(const struct cras_bt_device * device)378 int cras_bt_device_trusted(const struct cras_bt_device *device)
379 {
380 	return device->trusted;
381 }
382 
cras_bt_device_connected(const struct cras_bt_device * device)383 int cras_bt_device_connected(const struct cras_bt_device *device)
384 {
385 	return device->connected;
386 }
387 
cras_bt_device_supports_profile(const struct cras_bt_device * device,enum cras_bt_device_profile profile)388 int cras_bt_device_supports_profile(const struct cras_bt_device *device,
389 				    enum cras_bt_device_profile profile)
390 {
391 	return !!(device->profiles & profile);
392 }
393 
cras_bt_device_append_iodev(struct cras_bt_device * device,struct cras_iodev * iodev,enum cras_bt_device_profile profile)394 void cras_bt_device_append_iodev(struct cras_bt_device *device,
395 				 struct cras_iodev *iodev,
396 				 enum cras_bt_device_profile profile)
397 {
398 	struct cras_iodev *bt_iodev;
399 
400 	bt_iodev = device->bt_iodevs[iodev->direction];
401 
402 	if (bt_iodev) {
403 		cras_bt_io_append(bt_iodev, iodev, profile);
404 	} else {
405 		device->bt_iodevs[iodev->direction] =
406 			cras_bt_io_create(device, iodev, profile);
407 	}
408 }
409 
410 /*
411  * Sets the audio nodes to 'plugged' means UI can select it and open it
412  * for streams. Sets to 'unplugged' to hide these nodes from UI, when device
413  * disconnects in progress.
414  */
bt_device_set_nodes_plugged(struct cras_bt_device * device,int plugged)415 static void bt_device_set_nodes_plugged(struct cras_bt_device *device,
416 					int plugged)
417 {
418 	struct cras_iodev *iodev;
419 
420 	iodev = device->bt_iodevs[CRAS_STREAM_INPUT];
421 	if (iodev)
422 		cras_iodev_set_node_plugged(iodev->active_node, plugged);
423 
424 	iodev = device->bt_iodevs[CRAS_STREAM_OUTPUT];
425 	if (iodev)
426 		cras_iodev_set_node_plugged(iodev->active_node, plugged);
427 }
428 
429 static void bt_device_switch_profile(struct cras_bt_device *device,
430 				     struct cras_iodev *bt_iodev,
431 				     int enable_dev);
432 
cras_bt_device_rm_iodev(struct cras_bt_device * device,struct cras_iodev * iodev)433 void cras_bt_device_rm_iodev(struct cras_bt_device *device,
434 			     struct cras_iodev *iodev)
435 {
436 	struct cras_iodev *bt_iodev;
437 	int rc;
438 
439 	bt_device_set_nodes_plugged(device, 0);
440 
441 	bt_iodev = device->bt_iodevs[iodev->direction];
442 	if (bt_iodev) {
443 		unsigned try_profile;
444 
445 		/* Check what will the preffered profile be if we remove dev. */
446 		try_profile = cras_bt_io_try_remove(bt_iodev, iodev);
447 		if (!try_profile)
448 			goto destroy_bt_io;
449 
450 		/* If the check result doesn't match with the active
451 		 * profile we are currently using, switch to the
452 		 * preffered profile before actually remove the iodev.
453 		 */
454 		if (!cras_bt_io_on_profile(bt_iodev, try_profile)) {
455 			device->active_profile = try_profile;
456 			bt_device_switch_profile(device, bt_iodev, 0);
457 		}
458 		rc = cras_bt_io_remove(bt_iodev, iodev);
459 		if (rc) {
460 			syslog(LOG_ERR, "Fail to fallback to profile %u",
461 			       try_profile);
462 			goto destroy_bt_io;
463 		}
464 	}
465 	return;
466 
467 destroy_bt_io:
468 	device->bt_iodevs[iodev->direction] = NULL;
469 	cras_bt_io_destroy(bt_iodev);
470 
471 	if (!device->bt_iodevs[CRAS_STREAM_INPUT] &&
472 	    !device->bt_iodevs[CRAS_STREAM_OUTPUT])
473 		cras_bt_device_set_active_profile(device, 0);
474 }
475 
cras_bt_device_a2dp_configured(struct cras_bt_device * device)476 void cras_bt_device_a2dp_configured(struct cras_bt_device *device)
477 {
478 	BTLOG(btlog, BT_A2DP_CONFIGURED, device->connected_profiles, 0);
479 	device->connected_profiles |= CRAS_BT_DEVICE_PROFILE_A2DP_SINK;
480 }
481 
cras_bt_device_has_a2dp(struct cras_bt_device * device)482 int cras_bt_device_has_a2dp(struct cras_bt_device *device)
483 {
484 	struct cras_iodev *odev = device->bt_iodevs[CRAS_STREAM_OUTPUT];
485 
486 	/* Check if there is an output iodev with A2DP node attached. */
487 	return odev &&
488 	       cras_bt_io_get_profile(odev, CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE);
489 }
490 
cras_bt_device_can_switch_to_a2dp(struct cras_bt_device * device)491 int cras_bt_device_can_switch_to_a2dp(struct cras_bt_device *device)
492 {
493 	struct cras_iodev *idev = device->bt_iodevs[CRAS_STREAM_INPUT];
494 
495 	return cras_bt_device_has_a2dp(device) &&
496 	       (!idev || !cras_iodev_is_open(idev));
497 }
498 
bt_device_remove_conflict(struct cras_bt_device * device)499 static void bt_device_remove_conflict(struct cras_bt_device *device)
500 {
501 	struct cras_bt_device *connected;
502 
503 	/* Suspend other HFP audio gateways that conflict with device. */
504 	cras_hfp_ag_remove_conflict(device);
505 
506 	/* Check if there's conflict A2DP headset and suspend it. */
507 	connected = cras_a2dp_connected_device();
508 	if (connected && (connected != device))
509 		cras_a2dp_suspend_connected_device(connected);
510 }
511 
512 static void bt_device_conn_watch_cb(struct cras_timer *timer, void *arg);
513 
cras_bt_device_audio_gateway_initialized(struct cras_bt_device * device)514 int cras_bt_device_audio_gateway_initialized(struct cras_bt_device *device)
515 {
516 	BTLOG(btlog, BT_AUDIO_GATEWAY_INIT, device->profiles, 0);
517 	/* Marks HFP/HSP as connected. This is what connection watcher
518 	 * checks. */
519 	device->connected_profiles |= (CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE |
520 				       CRAS_BT_DEVICE_PROFILE_HSP_HEADSET);
521 
522 	/* If device connects HFP but not reporting correct UUID, manually add
523 	 * it to allow CRAS to enumerate audio node for it. We're seeing this
524 	 * behavior on qualification test software. */
525 	if (!cras_bt_device_supports_profile(
526 		    device, CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE)) {
527 		unsigned int profiles =
528 			device->profiles | CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE;
529 		cras_bt_device_set_supported_profiles(device, profiles);
530 		device->hidden_profiles |= CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE;
531 		bt_device_conn_watch_cb(NULL, (void *)device);
532 	}
533 
534 	return 0;
535 }
536 
537 unsigned int
cras_bt_device_get_active_profile(const struct cras_bt_device * device)538 cras_bt_device_get_active_profile(const struct cras_bt_device *device)
539 {
540 	return device->active_profile;
541 }
542 
cras_bt_device_set_active_profile(struct cras_bt_device * device,unsigned int profile)543 void cras_bt_device_set_active_profile(struct cras_bt_device *device,
544 				       unsigned int profile)
545 {
546 	device->active_profile = profile;
547 }
548 
cras_bt_device_log_profile(const struct cras_bt_device * device,enum cras_bt_device_profile profile)549 static void cras_bt_device_log_profile(const struct cras_bt_device *device,
550 				       enum cras_bt_device_profile profile)
551 {
552 	switch (profile) {
553 	case CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE:
554 		syslog(LOG_DEBUG, "Bluetooth Device: %s is HFP handsfree",
555 		       device->address);
556 		break;
557 	case CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY:
558 		syslog(LOG_DEBUG, "Bluetooth Device: %s is HFP audio gateway",
559 		       device->address);
560 		break;
561 	case CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE:
562 		syslog(LOG_DEBUG, "Bluetooth Device: %s is A2DP source",
563 		       device->address);
564 		break;
565 	case CRAS_BT_DEVICE_PROFILE_A2DP_SINK:
566 		syslog(LOG_DEBUG, "Bluetooth Device: %s is A2DP sink",
567 		       device->address);
568 		break;
569 	case CRAS_BT_DEVICE_PROFILE_AVRCP_REMOTE:
570 		syslog(LOG_DEBUG, "Bluetooth Device: %s is AVRCP remote",
571 		       device->address);
572 		break;
573 	case CRAS_BT_DEVICE_PROFILE_AVRCP_TARGET:
574 		syslog(LOG_DEBUG, "Bluetooth Device: %s is AVRCP target",
575 		       device->address);
576 		break;
577 	case CRAS_BT_DEVICE_PROFILE_HSP_HEADSET:
578 		syslog(LOG_DEBUG, "Bluetooth Device: %s is HSP headset",
579 		       device->address);
580 		break;
581 	case CRAS_BT_DEVICE_PROFILE_HSP_AUDIOGATEWAY:
582 		syslog(LOG_DEBUG, "Bluetooth Device: %s is HSP audio gateway",
583 		       device->address);
584 		break;
585 	}
586 }
587 
cras_bt_device_log_profiles(const struct cras_bt_device * device,unsigned int profiles)588 static void cras_bt_device_log_profiles(const struct cras_bt_device *device,
589 					unsigned int profiles)
590 {
591 	unsigned int profile;
592 
593 	while (profiles) {
594 		/* Get the LSB of profiles */
595 		profile = profiles & -profiles;
596 		cras_bt_device_log_profile(device, profile);
597 		profiles ^= profile;
598 	}
599 }
600 
601 static int
cras_bt_device_is_profile_connected(const struct cras_bt_device * device,enum cras_bt_device_profile profile)602 cras_bt_device_is_profile_connected(const struct cras_bt_device *device,
603 				    enum cras_bt_device_profile profile)
604 {
605 	return !!(device->connected_profiles & profile);
606 }
607 
608 static void
609 bt_device_schedule_suspend(struct cras_bt_device *device, unsigned int msec,
610 			   enum cras_bt_device_suspend_reason suspend_reason);
611 
612 /* Callback used to periodically check if supported profiles are connected. */
bt_device_conn_watch_cb(struct cras_timer * timer,void * arg)613 static void bt_device_conn_watch_cb(struct cras_timer *timer, void *arg)
614 {
615 	struct cras_tm *tm;
616 	struct cras_bt_device *device = (struct cras_bt_device *)arg;
617 	int rc;
618 	bool a2dp_supported;
619 	bool a2dp_connected;
620 	bool hfp_supported;
621 	bool hfp_connected;
622 
623 	BTLOG(btlog, BT_DEV_CONN_WATCH_CB, device->conn_watch_retries,
624 	      device->profiles);
625 	device->conn_watch_timer = NULL;
626 
627 	/* Skip the callback if it is not an audio device. */
628 	if (!device->profiles)
629 		return;
630 
631 	a2dp_supported = cras_bt_device_supports_profile(
632 		device, CRAS_BT_DEVICE_PROFILE_A2DP_SINK);
633 	a2dp_connected = cras_bt_device_is_profile_connected(
634 		device, CRAS_BT_DEVICE_PROFILE_A2DP_SINK);
635 	hfp_supported = cras_bt_device_supports_profile(
636 		device, CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE);
637 	hfp_connected = cras_bt_device_is_profile_connected(
638 		device, CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE);
639 
640 	/* If not both A2DP and HFP are supported, simply wait for BlueZ
641 	 * to notify us about the new connection.
642 	 * Otherwise, when seeing one but not the other profile is connected,
643 	 * send message to ask BlueZ to connect the pending one.
644 	 */
645 	if (a2dp_supported && hfp_supported) {
646 		/* If both a2dp and hfp are not connected, do nothing. BlueZ
647 		 * should be responsible to notify connection of one profile.
648 		 */
649 		if (!a2dp_connected && hfp_connected)
650 			cras_bt_device_connect_profile(device->conn, device,
651 						       A2DP_SINK_UUID);
652 		if (a2dp_connected && !hfp_connected)
653 			cras_bt_device_connect_profile(device->conn, device,
654 						       HFP_HF_UUID);
655 	}
656 
657 	if (a2dp_supported != a2dp_connected || hfp_supported != hfp_connected)
658 		goto arm_retry_timer;
659 
660 	/* Expected profiles are all connected, no more connection watch
661 	 * callback will be scheduled.
662 	 * Base on the decision that we expose only the latest connected
663 	 * BT audio device to user, treat all other connected devices as
664 	 * conflict and remove them before we start A2DP/HFP of this device.
665 	 */
666 	bt_device_remove_conflict(device);
667 
668 	if (cras_bt_device_is_profile_connected(
669 		    device, CRAS_BT_DEVICE_PROFILE_A2DP_SINK))
670 		cras_a2dp_start(device);
671 
672 	if (cras_bt_device_is_profile_connected(
673 		    device, CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE)) {
674 		rc = cras_hfp_ag_start(device);
675 		if (rc) {
676 			syslog(LOG_ERR, "Start audio gateway failed, rc %d",
677 			       rc);
678 			bt_device_schedule_suspend(device, 0,
679 						   HFP_AG_START_FAILURE);
680 		}
681 	}
682 	bt_device_set_nodes_plugged(device, 1);
683 	return;
684 
685 arm_retry_timer:
686 
687 	syslog(LOG_DEBUG, "conn_watch_retries: %d", device->conn_watch_retries);
688 
689 	if (--device->conn_watch_retries) {
690 		tm = cras_system_state_get_tm();
691 		device->conn_watch_timer =
692 			cras_tm_create_timer(tm, CONN_WATCH_PERIOD_MS,
693 					     bt_device_conn_watch_cb, device);
694 	} else {
695 		syslog(LOG_ERR, "Connection watch timeout.");
696 		bt_device_schedule_suspend(device, 0, CONN_WATCH_TIME_OUT);
697 	}
698 }
699 
700 static void
cras_bt_device_start_new_conn_watch_timer(struct cras_bt_device * device)701 cras_bt_device_start_new_conn_watch_timer(struct cras_bt_device *device)
702 {
703 	struct cras_tm *tm = cras_system_state_get_tm();
704 
705 	if (device->conn_watch_timer) {
706 		cras_tm_cancel_timer(tm, device->conn_watch_timer);
707 	}
708 	device->conn_watch_retries = CONN_WATCH_MAX_RETRIES;
709 	device->conn_watch_timer = cras_tm_create_timer(
710 		tm, CONN_WATCH_PERIOD_MS, bt_device_conn_watch_cb, device);
711 }
712 
713 static void bt_device_cancel_suspend(struct cras_bt_device *device);
714 
cras_bt_device_set_connected(struct cras_bt_device * device,int value)715 void cras_bt_device_set_connected(struct cras_bt_device *device, int value)
716 {
717 	struct cras_tm *tm = cras_system_state_get_tm();
718 	if (!device->connected && value) {
719 		BTLOG(btlog, BT_DEV_CONNECTED, device->profiles,
720 		      device->stable_id);
721 	}
722 
723 	if (device->connected && !value) {
724 		BTLOG(btlog, BT_DEV_DISCONNECTED, device->profiles,
725 		      device->stable_id);
726 		cras_bt_profile_on_device_disconnected(device);
727 		/* Device is disconnected, resets connected profiles and the
728 		 * suspend timer which scheduled earlier. */
729 		device->connected_profiles = 0;
730 		bt_device_cancel_suspend(device);
731 	}
732 
733 	device->connected = value;
734 
735 	if (!device->connected && device->conn_watch_timer) {
736 		cras_tm_cancel_timer(tm, device->conn_watch_timer);
737 		device->conn_watch_timer = NULL;
738 	}
739 }
740 
cras_bt_device_notify_profile_dropped(struct cras_bt_device * device,enum cras_bt_device_profile profile)741 void cras_bt_device_notify_profile_dropped(struct cras_bt_device *device,
742 					   enum cras_bt_device_profile profile)
743 {
744 	device->connected_profiles &= ~profile;
745 
746 	/* Do nothing if device already disconnected. */
747 	if (!device->connected)
748 		return;
749 
750 	/* If any profile, a2dp or hfp/hsp, has dropped for some reason,
751 	 * we shall make sure this device is fully disconnected within
752 	 * given time so that user does not see a headset stay connected
753 	 * but works with partial function.
754 	 */
755 	bt_device_schedule_suspend(device, PROFILE_DROP_SUSPEND_DELAY_MS,
756 				   UNEXPECTED_PROFILE_DROP);
757 }
758 
759 /* Refresh the list of known supported profiles.
760  * Args:
761  *    device - The BT device holding scanned profiles bitmap.
762  *    profiles - The OR'ed profiles the device claims to support as is notified
763  *               by BlueZ.
764  * Returns:
765  *    The OR'ed profiles that are both supported by Cras and isn't previously
766  *    supported by the device.
767  */
cras_bt_device_set_supported_profiles(struct cras_bt_device * device,unsigned int profiles)768 int cras_bt_device_set_supported_profiles(struct cras_bt_device *device,
769 					  unsigned int profiles)
770 {
771 	/* Do nothing if no new profiles. */
772 	if ((device->profiles & profiles) == profiles)
773 		return 0;
774 
775 	unsigned int new_profiles = profiles & ~device->profiles;
776 
777 	/* Log this event as we might need to re-intialize the BT audio nodes
778 	 * if new audio profile is reported for already connected device. */
779 	if (device->connected && (new_profiles & CRAS_SUPPORTED_PROFILES))
780 		BTLOG(btlog, BT_NEW_AUDIO_PROFILE_AFTER_CONNECT,
781 		      device->profiles, new_profiles);
782 	cras_bt_device_log_profiles(device, new_profiles);
783 	device->profiles = profiles | device->hidden_profiles;
784 
785 	return (new_profiles & CRAS_SUPPORTED_PROFILES);
786 }
787 
cras_bt_device_update_properties(struct cras_bt_device * device,DBusMessageIter * properties_array_iter,DBusMessageIter * invalidated_array_iter)788 void cras_bt_device_update_properties(struct cras_bt_device *device,
789 				      DBusMessageIter *properties_array_iter,
790 				      DBusMessageIter *invalidated_array_iter)
791 {
792 	int watch_needed = 0;
793 	while (dbus_message_iter_get_arg_type(properties_array_iter) !=
794 	       DBUS_TYPE_INVALID) {
795 		DBusMessageIter properties_dict_iter, variant_iter;
796 		const char *key;
797 		int type;
798 
799 		dbus_message_iter_recurse(properties_array_iter,
800 					  &properties_dict_iter);
801 
802 		dbus_message_iter_get_basic(&properties_dict_iter, &key);
803 		dbus_message_iter_next(&properties_dict_iter);
804 
805 		dbus_message_iter_recurse(&properties_dict_iter, &variant_iter);
806 		type = dbus_message_iter_get_arg_type(&variant_iter);
807 
808 		if (type == DBUS_TYPE_STRING || type == DBUS_TYPE_OBJECT_PATH) {
809 			const char *value;
810 
811 			dbus_message_iter_get_basic(&variant_iter, &value);
812 
813 			if (strcmp(key, "Adapter") == 0) {
814 				free(device->adapter_obj_path);
815 				device->adapter_obj_path = strdup(value);
816 			} else if (strcmp(key, "Address") == 0) {
817 				free(device->address);
818 				device->address = strdup(value);
819 			} else if (strcmp(key, "Alias") == 0) {
820 				free(device->name);
821 				device->name = strdup(value);
822 			}
823 
824 		} else if (type == DBUS_TYPE_UINT32) {
825 			uint32_t value;
826 
827 			dbus_message_iter_get_basic(&variant_iter, &value);
828 
829 			if (strcmp(key, "Class") == 0)
830 				device->bluetooth_class = value;
831 
832 		} else if (type == DBUS_TYPE_BOOLEAN) {
833 			int value;
834 
835 			dbus_message_iter_get_basic(&variant_iter, &value);
836 
837 			if (strcmp(key, "Paired") == 0) {
838 				device->paired = value;
839 			} else if (strcmp(key, "Trusted") == 0) {
840 				device->trusted = value;
841 			} else if (strcmp(key, "Connected") == 0) {
842 				cras_bt_device_set_connected(device, value);
843 				watch_needed = device->connected &&
844 					       cras_bt_device_supports_profile(
845 						       device,
846 						       CRAS_SUPPORTED_PROFILES);
847 			}
848 
849 		} else if (strcmp(dbus_message_iter_get_signature(&variant_iter),
850 				  "as") == 0 &&
851 			   strcmp(key, "UUIDs") == 0) {
852 			DBusMessageIter uuid_array_iter;
853 			unsigned int profiles = 0;
854 
855 			dbus_message_iter_recurse(&variant_iter,
856 						  &uuid_array_iter);
857 			while (dbus_message_iter_get_arg_type(
858 				       &uuid_array_iter) != DBUS_TYPE_INVALID) {
859 				const char *uuid;
860 
861 				dbus_message_iter_get_basic(&uuid_array_iter,
862 							    &uuid);
863 				profiles |=
864 					cras_bt_device_profile_from_uuid(uuid);
865 
866 				dbus_message_iter_next(&uuid_array_iter);
867 			}
868 
869 			/* If updated properties includes new audio profile and
870 			 * device is connected, we need to start connection
871 			 * watcher. This is needed because on some bluetooth
872 			 * devices, supported profiles do not present when
873 			 * device interface is added and they are updated later.
874 			 */
875 			if (cras_bt_device_set_supported_profiles(device,
876 								  profiles))
877 				watch_needed = device->connected;
878 		}
879 
880 		dbus_message_iter_next(properties_array_iter);
881 	}
882 
883 	while (invalidated_array_iter &&
884 	       dbus_message_iter_get_arg_type(invalidated_array_iter) !=
885 		       DBUS_TYPE_INVALID) {
886 		const char *key;
887 
888 		dbus_message_iter_get_basic(invalidated_array_iter, &key);
889 
890 		if (strcmp(key, "Adapter") == 0) {
891 			free(device->adapter_obj_path);
892 			device->adapter_obj_path = NULL;
893 		} else if (strcmp(key, "Address") == 0) {
894 			free(device->address);
895 			device->address = NULL;
896 		} else if (strcmp(key, "Alias") == 0) {
897 			free(device->name);
898 			device->name = NULL;
899 		} else if (strcmp(key, "Class") == 0) {
900 			device->bluetooth_class = 0;
901 		} else if (strcmp(key, "Paired") == 0) {
902 			device->paired = 0;
903 		} else if (strcmp(key, "Trusted") == 0) {
904 			device->trusted = 0;
905 		} else if (strcmp(key, "Connected") == 0) {
906 			device->connected = 0;
907 		} else if (strcmp(key, "UUIDs") == 0) {
908 			device->profiles = device->hidden_profiles;
909 		}
910 
911 		dbus_message_iter_next(invalidated_array_iter);
912 	}
913 
914 	if (watch_needed)
915 		cras_bt_device_start_new_conn_watch_timer(device);
916 }
917 
918 /* Converts bluetooth address string into sockaddr structure. The address
919  * string is expected of the form 1A:2B:3C:4D:5E:6F, and each of the six
920  * hex values will be parsed into sockaddr in inverse order.
921  * Args:
922  *    str - The string version of bluetooth address
923  *    addr - The struct to be filled with converted address
924  */
bt_address(const char * str,struct sockaddr * addr)925 static int bt_address(const char *str, struct sockaddr *addr)
926 {
927 	int i;
928 
929 	if (strlen(str) != 17) {
930 		syslog(LOG_ERR, "Invalid bluetooth address %s", str);
931 		return -1;
932 	}
933 
934 	memset(addr, 0, sizeof(*addr));
935 	addr->sa_family = AF_BLUETOOTH;
936 	for (i = 5; i >= 0; i--) {
937 		addr->sa_data[i] = (unsigned char)strtol(str, NULL, 16);
938 		str += 3;
939 	}
940 
941 	return 0;
942 }
943 
944 /* Apply codec specific settings to the socket fd. */
apply_codec_settings(int fd,uint8_t codec)945 static int apply_codec_settings(int fd, uint8_t codec)
946 {
947 	struct bt_voice voice;
948 	uint32_t pkt_status;
949 
950 	memset(&voice, 0, sizeof(voice));
951 	if (codec == HFP_CODEC_ID_CVSD)
952 		return 0;
953 
954 	if (codec != HFP_CODEC_ID_MSBC) {
955 		syslog(LOG_ERR, "Unsupported codec %d", codec);
956 		return -1;
957 	}
958 
959 	voice.setting = BT_VOICE_TRANSPARENT;
960 
961 	if (setsockopt(fd, SOL_BLUETOOTH, BT_VOICE, &voice, sizeof(voice)) <
962 	    0) {
963 		syslog(LOG_ERR, "Failed to apply voice setting");
964 		return -1;
965 	}
966 
967 	pkt_status = 1;
968 	if (setsockopt(fd, SOL_BLUETOOTH, BT_PKT_STATUS, &pkt_status,
969 		       sizeof(pkt_status))) {
970 		syslog(LOG_ERR, "Failed to enable BT_PKT_STATUS");
971 	}
972 	return 0;
973 }
974 
cras_bt_device_sco_connect(struct cras_bt_device * device,int codec)975 int cras_bt_device_sco_connect(struct cras_bt_device *device, int codec)
976 {
977 	int sk = 0, err;
978 	struct sockaddr addr;
979 	struct cras_bt_adapter *adapter;
980 	struct timespec timeout = { 1, 0 };
981 	struct pollfd pollfd;
982 
983 	adapter = cras_bt_device_adapter(device);
984 	if (!adapter) {
985 		syslog(LOG_ERR, "No adapter found for device %s at SCO connect",
986 		       cras_bt_device_object_path(device));
987 		goto error;
988 	}
989 
990 	sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET | O_NONBLOCK | SOCK_CLOEXEC,
991 		    BTPROTO_SCO);
992 	if (sk < 0) {
993 		syslog(LOG_ERR, "Failed to create socket: %s (%d)",
994 		       strerror(errno), errno);
995 		cras_server_metrics_hfp_sco_connection_error(
996 			CRAS_METRICS_SCO_SKT_OPEN_ERROR);
997 		return -errno;
998 	}
999 
1000 	/* Bind to local address */
1001 	if (bt_address(cras_bt_adapter_address(adapter), &addr))
1002 		goto error;
1003 	if (bind(sk, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
1004 		syslog(LOG_ERR, "Failed to bind socket: %s (%d)",
1005 		       strerror(errno), errno);
1006 		goto error;
1007 	}
1008 
1009 	/* Connect to remote in nonblocking mode */
1010 	fcntl(sk, F_SETFL, O_NONBLOCK);
1011 
1012 	if (bt_address(cras_bt_device_address(device), &addr))
1013 		goto error;
1014 
1015 	err = apply_codec_settings(sk, codec);
1016 	if (err)
1017 		goto error;
1018 
1019 	err = connect(sk, (struct sockaddr *)&addr, sizeof(addr));
1020 	if (err && errno != EINPROGRESS) {
1021 		syslog(LOG_ERR, "Failed to connect: %s (%d)", strerror(errno),
1022 		       errno);
1023 		cras_server_metrics_hfp_sco_connection_error(
1024 			CRAS_METRICS_SCO_SKT_CONNECT_ERROR);
1025 		goto error;
1026 	}
1027 
1028 	pollfd.fd = sk;
1029 	pollfd.events = POLLOUT;
1030 
1031 	err = ppoll(&pollfd, 1, &timeout, NULL);
1032 	if (err <= 0) {
1033 		syslog(LOG_ERR, "Connect SCO: poll for writable timeout");
1034 		cras_server_metrics_hfp_sco_connection_error(
1035 			CRAS_METRICS_SCO_SKT_POLL_TIMEOUT);
1036 		goto error;
1037 	}
1038 
1039 	if (pollfd.revents & (POLLERR | POLLHUP)) {
1040 		syslog(LOG_ERR,
1041 		       "SCO socket error, revents: %u. Suspend in %u seconds",
1042 		       pollfd.revents, SCO_SUSPEND_DELAY_MS);
1043 		cras_server_metrics_hfp_sco_connection_error(
1044 			CRAS_METRICS_SCO_SKT_POLL_ERR_HUP);
1045 		bt_device_schedule_suspend(device, SCO_SUSPEND_DELAY_MS,
1046 					   HFP_SCO_SOCKET_ERROR);
1047 		goto error;
1048 	}
1049 
1050 	cras_server_metrics_hfp_sco_connection_error(
1051 		CRAS_METRICS_SCO_SKT_SUCCESS);
1052 	BTLOG(btlog, BT_SCO_CONNECT, 1, sk);
1053 	return sk;
1054 
1055 error:
1056 	BTLOG(btlog, BT_SCO_CONNECT, 0, sk);
1057 	if (sk)
1058 		close(sk);
1059 	return -1;
1060 }
1061 
cras_bt_device_sco_packet_size(struct cras_bt_device * device,int sco_socket,int codec)1062 int cras_bt_device_sco_packet_size(struct cras_bt_device *device,
1063 				   int sco_socket, int codec)
1064 {
1065 	struct sco_options so;
1066 	socklen_t len = sizeof(so);
1067 	struct cras_bt_adapter *adapter;
1068 	uint32_t wbs_pkt_len = 0;
1069 	socklen_t optlen = sizeof(wbs_pkt_len);
1070 
1071 	adapter = cras_bt_adapter_get(device->adapter_obj_path);
1072 
1073 	if (cras_bt_adapter_on_usb(adapter)) {
1074 		if (codec == HFP_CODEC_ID_MSBC) {
1075 			/* BT_SNDMTU and BT_RCVMTU return the same value. */
1076 			if (getsockopt(sco_socket, SOL_BLUETOOTH, BT_SNDMTU,
1077 				       &wbs_pkt_len, &optlen))
1078 				syslog(LOG_ERR, "Failed to get BT_SNDMTU");
1079 
1080 			return (wbs_pkt_len > 0) ? wbs_pkt_len :
1081 						   USB_MSBC_PKT_SIZE;
1082 		} else {
1083 			return USB_CVSD_PKT_SIZE;
1084 		}
1085 	}
1086 
1087 	/* For non-USB cases, query the SCO MTU from driver. */
1088 	if (getsockopt(sco_socket, SOL_SCO, SCO_OPTIONS, &so, &len) < 0) {
1089 		syslog(LOG_ERR, "Get SCO options error: %s", strerror(errno));
1090 		return DEFAULT_SCO_PKT_SIZE;
1091 	}
1092 	return so.mtu;
1093 }
1094 
cras_bt_device_set_use_hardware_volume(struct cras_bt_device * device,int use_hardware_volume)1095 void cras_bt_device_set_use_hardware_volume(struct cras_bt_device *device,
1096 					    int use_hardware_volume)
1097 {
1098 	struct cras_iodev *iodev;
1099 
1100 	device->use_hardware_volume = use_hardware_volume;
1101 	iodev = device->bt_iodevs[CRAS_STREAM_OUTPUT];
1102 	if (iodev)
1103 		iodev->software_volume_needed = !use_hardware_volume;
1104 }
1105 
cras_bt_device_get_use_hardware_volume(struct cras_bt_device * device)1106 int cras_bt_device_get_use_hardware_volume(struct cras_bt_device *device)
1107 {
1108 	return device->use_hardware_volume;
1109 }
1110 
init_bt_device_msg(struct bt_device_msg * msg,enum BT_DEVICE_COMMAND cmd,struct cras_bt_device * device,struct cras_iodev * dev,unsigned int arg1,unsigned int arg2)1111 static void init_bt_device_msg(struct bt_device_msg *msg,
1112 			       enum BT_DEVICE_COMMAND cmd,
1113 			       struct cras_bt_device *device,
1114 			       struct cras_iodev *dev, unsigned int arg1,
1115 			       unsigned int arg2)
1116 {
1117 	memset(msg, 0, sizeof(*msg));
1118 	msg->header.type = CRAS_MAIN_BT;
1119 	msg->header.length = sizeof(*msg);
1120 	msg->cmd = cmd;
1121 	msg->device = device;
1122 	msg->dev = dev;
1123 	msg->arg1 = arg1;
1124 	msg->arg2 = arg2;
1125 }
1126 
cras_bt_device_cancel_suspend(struct cras_bt_device * device)1127 int cras_bt_device_cancel_suspend(struct cras_bt_device *device)
1128 {
1129 	struct bt_device_msg msg;
1130 	int rc;
1131 
1132 	init_bt_device_msg(&msg, BT_DEVICE_CANCEL_SUSPEND, device, NULL, 0, 0);
1133 	rc = cras_main_message_send((struct cras_main_message *)&msg);
1134 	return rc;
1135 }
1136 
cras_bt_device_schedule_suspend(struct cras_bt_device * device,unsigned int msec,enum cras_bt_device_suspend_reason suspend_reason)1137 int cras_bt_device_schedule_suspend(
1138 	struct cras_bt_device *device, unsigned int msec,
1139 	enum cras_bt_device_suspend_reason suspend_reason)
1140 {
1141 	struct bt_device_msg msg;
1142 	int rc;
1143 
1144 	init_bt_device_msg(&msg, BT_DEVICE_SCHEDULE_SUSPEND, device, NULL, msec,
1145 			   suspend_reason);
1146 	rc = cras_main_message_send((struct cras_main_message *)&msg);
1147 	return rc;
1148 }
1149 
1150 /* This diagram describes how the profile switching happens. When
1151  * certain conditions met, bt iodev will call the APIs below to interact
1152  * with main thread to switch to another active profile.
1153  *
1154  * Audio thread:
1155  *  +--------------------------------------------------------------+
1156  *  | bt iodev                                                     |
1157  *  |              +------------------+    +-----------------+     |
1158  *  |              | condition met to |    | open, close, or |     |
1159  *  |           +--| change profile   |<---| append profile  |<--+ |
1160  *  |           |  +------------------+    +-----------------+   | |
1161  *  +-----------|------------------------------------------------|-+
1162  *              |                                                |
1163  * Main thread: |
1164  *  +-----------|------------------------------------------------|-+
1165  *  |           |                                                | |
1166  *  |           |      +------------+     +----------------+     | |
1167  *  |           +----->| set active |---->| switch profile |-----+ |
1168  *  |                  | profile    |     +----------------+       |
1169  *  | bt device        +------------+                              |
1170  *  +--------------------------------------------------------------+
1171  */
cras_bt_device_switch_profile_enable_dev(struct cras_bt_device * device,struct cras_iodev * bt_iodev)1172 int cras_bt_device_switch_profile_enable_dev(struct cras_bt_device *device,
1173 					     struct cras_iodev *bt_iodev)
1174 {
1175 	struct bt_device_msg msg;
1176 	int rc;
1177 
1178 	init_bt_device_msg(&msg, BT_DEVICE_SWITCH_PROFILE_ENABLE_DEV, device,
1179 			   bt_iodev, 0, 0);
1180 	rc = cras_main_message_send((struct cras_main_message *)&msg);
1181 	return rc;
1182 }
1183 
cras_bt_device_switch_profile(struct cras_bt_device * device,struct cras_iodev * bt_iodev)1184 int cras_bt_device_switch_profile(struct cras_bt_device *device,
1185 				  struct cras_iodev *bt_iodev)
1186 {
1187 	struct bt_device_msg msg;
1188 	int rc;
1189 
1190 	init_bt_device_msg(&msg, BT_DEVICE_SWITCH_PROFILE, device, bt_iodev, 0,
1191 			   0);
1192 	rc = cras_main_message_send((struct cras_main_message *)&msg);
1193 	return rc;
1194 }
1195 
profile_switch_delay_cb(struct cras_timer * timer,void * arg)1196 static void profile_switch_delay_cb(struct cras_timer *timer, void *arg)
1197 {
1198 	struct cras_bt_device *device = (struct cras_bt_device *)arg;
1199 	struct cras_iodev *iodev;
1200 
1201 	device->switch_profile_timer = NULL;
1202 	iodev = device->bt_iodevs[CRAS_STREAM_OUTPUT];
1203 	if (!iodev)
1204 		return;
1205 
1206 	/*
1207 	 * During the |PROFILE_SWITCH_DELAY_MS| time interval, BT iodev could
1208 	 * have been enabled by others, and its active profile may have changed.
1209 	 * If iodev has been enabled, that means it has already picked up a
1210 	 * reasonable profile to use and audio thread is accessing iodev now.
1211 	 * We should NOT call into update_active_node from main thread
1212 	 * because that may mess up the active node content.
1213 	 */
1214 	iodev->update_active_node(iodev, 0, 1);
1215 	cras_iodev_list_resume_dev(iodev->info.idx);
1216 }
1217 
bt_device_switch_profile_with_delay(struct cras_bt_device * device,unsigned int delay_ms)1218 static void bt_device_switch_profile_with_delay(struct cras_bt_device *device,
1219 						unsigned int delay_ms)
1220 {
1221 	struct cras_tm *tm = cras_system_state_get_tm();
1222 
1223 	if (device->switch_profile_timer) {
1224 		cras_tm_cancel_timer(tm, device->switch_profile_timer);
1225 		device->switch_profile_timer = NULL;
1226 	}
1227 	device->switch_profile_timer = cras_tm_create_timer(
1228 		tm, delay_ms, profile_switch_delay_cb, device);
1229 }
1230 
1231 /* Switches associated bt iodevs to use the active profile. This is
1232  * achieved by close the iodevs, update their active nodes, and then
1233  * finally reopen them. */
bt_device_switch_profile(struct cras_bt_device * device,struct cras_iodev * bt_iodev,int enable_dev)1234 static void bt_device_switch_profile(struct cras_bt_device *device,
1235 				     struct cras_iodev *bt_iodev,
1236 				     int enable_dev)
1237 {
1238 	struct cras_iodev *iodev;
1239 	int dir;
1240 
1241 	/* If a bt iodev is active, temporarily force close it.
1242 	 * Note that we need to check all bt_iodevs for the situation that both
1243 	 * input and output are active while switches from HFP/HSP to A2DP.
1244 	 */
1245 	for (dir = 0; dir < CRAS_NUM_DIRECTIONS; dir++) {
1246 		iodev = device->bt_iodevs[dir];
1247 		if (!iodev)
1248 			continue;
1249 		cras_iodev_list_suspend_dev(iodev->info.idx);
1250 	}
1251 
1252 	for (dir = 0; dir < CRAS_NUM_DIRECTIONS; dir++) {
1253 		iodev = device->bt_iodevs[dir];
1254 		if (!iodev)
1255 			continue;
1256 
1257 		/* If the iodev was active or this profile switching is
1258 		 * triggered at opening iodev, add it to active dev list.
1259 		 * However for the output iodev, adding it back to active dev
1260 		 * list could cause immediate switching from HFP to A2DP if
1261 		 * there exists an output stream. Certain headset/speaker
1262 		 * would fail to playback afterwards when the switching happens
1263 		 * too soon, so put this task in a delayed callback.
1264 		 */
1265 		if (dir == CRAS_STREAM_INPUT) {
1266 			iodev->update_active_node(iodev, 0, 1);
1267 			cras_iodev_list_resume_dev(iodev->info.idx);
1268 		} else {
1269 			bt_device_switch_profile_with_delay(
1270 				device, PROFILE_SWITCH_DELAY_MS);
1271 		}
1272 	}
1273 }
1274 
bt_device_suspend_cb(struct cras_timer * timer,void * arg)1275 static void bt_device_suspend_cb(struct cras_timer *timer, void *arg)
1276 {
1277 	struct cras_bt_device *device = (struct cras_bt_device *)arg;
1278 
1279 	BTLOG(btlog, BT_DEV_SUSPEND_CB, device->profiles,
1280 	      device->suspend_reason);
1281 	device->suspend_timer = NULL;
1282 
1283 	/* Error log the reason so we can track them in user reports. */
1284 	switch (device->suspend_reason) {
1285 	case A2DP_LONG_TX_FAILURE:
1286 		syslog(LOG_ERR, "Suspend dev: A2DP long Tx failure");
1287 		break;
1288 	case A2DP_TX_FATAL_ERROR:
1289 		syslog(LOG_ERR, "Suspend dev: A2DP Tx fatal error");
1290 		break;
1291 	case CONN_WATCH_TIME_OUT:
1292 		syslog(LOG_ERR, "Suspend dev: Conn watch times out");
1293 		break;
1294 	case HFP_SCO_SOCKET_ERROR:
1295 		syslog(LOG_ERR, "Suspend dev: SCO socket error");
1296 		break;
1297 	case HFP_AG_START_FAILURE:
1298 		syslog(LOG_ERR, "Suspend dev: HFP AG start failure");
1299 		break;
1300 	case UNEXPECTED_PROFILE_DROP:
1301 		syslog(LOG_ERR, "Suspend dev: Unexpected profile drop");
1302 		break;
1303 	}
1304 
1305 	cras_a2dp_suspend_connected_device(device);
1306 	cras_hfp_ag_suspend_connected_device(device);
1307 	cras_bt_device_disconnect(device->conn, device);
1308 }
1309 
1310 static void
bt_device_schedule_suspend(struct cras_bt_device * device,unsigned int msec,enum cras_bt_device_suspend_reason suspend_reason)1311 bt_device_schedule_suspend(struct cras_bt_device *device, unsigned int msec,
1312 			   enum cras_bt_device_suspend_reason suspend_reason)
1313 {
1314 	struct cras_tm *tm = cras_system_state_get_tm();
1315 
1316 	if (device->suspend_timer)
1317 		return;
1318 	device->suspend_reason = suspend_reason;
1319 	device->suspend_timer =
1320 		cras_tm_create_timer(tm, msec, bt_device_suspend_cb, device);
1321 }
1322 
bt_device_cancel_suspend(struct cras_bt_device * device)1323 static void bt_device_cancel_suspend(struct cras_bt_device *device)
1324 {
1325 	struct cras_tm *tm = cras_system_state_get_tm();
1326 	if (device->suspend_timer == NULL)
1327 		return;
1328 	cras_tm_cancel_timer(tm, device->suspend_timer);
1329 	device->suspend_timer = NULL;
1330 }
1331 
bt_device_process_msg(struct cras_main_message * msg,void * arg)1332 static void bt_device_process_msg(struct cras_main_message *msg, void *arg)
1333 {
1334 	struct bt_device_msg *bt_msg = (struct bt_device_msg *)msg;
1335 	struct cras_bt_device *device = NULL;
1336 
1337 	DL_FOREACH (devices, device) {
1338 		if (device == bt_msg->device)
1339 			break;
1340 	}
1341 
1342 	/* Do nothing if target device no longer exists. */
1343 	if (device == NULL)
1344 		return;
1345 
1346 	switch (bt_msg->cmd) {
1347 	case BT_DEVICE_SWITCH_PROFILE:
1348 		bt_device_switch_profile(bt_msg->device, bt_msg->dev, 0);
1349 		break;
1350 	case BT_DEVICE_SWITCH_PROFILE_ENABLE_DEV:
1351 		bt_device_switch_profile(bt_msg->device, bt_msg->dev, 1);
1352 		break;
1353 	case BT_DEVICE_SCHEDULE_SUSPEND:
1354 		bt_device_schedule_suspend(bt_msg->device, bt_msg->arg1,
1355 					   bt_msg->arg2);
1356 		break;
1357 	case BT_DEVICE_CANCEL_SUSPEND:
1358 		bt_device_cancel_suspend(bt_msg->device);
1359 		break;
1360 	default:
1361 		break;
1362 	}
1363 }
1364 
cras_bt_device_start_monitor()1365 void cras_bt_device_start_monitor()
1366 {
1367 	cras_main_message_add_handler(CRAS_MAIN_BT, bt_device_process_msg,
1368 				      NULL);
1369 }
1370 
cras_bt_device_update_hardware_volume(struct cras_bt_device * device,int volume)1371 void cras_bt_device_update_hardware_volume(struct cras_bt_device *device,
1372 					   int volume)
1373 {
1374 	struct cras_iodev *iodev;
1375 
1376 	iodev = device->bt_iodevs[CRAS_STREAM_OUTPUT];
1377 	if (iodev == NULL)
1378 		return;
1379 
1380 	/* Check if this BT device is okay to use hardware volume. If not
1381 	 * then ignore the reported volume change event.
1382 	 */
1383 	if (!cras_bt_device_get_use_hardware_volume(device))
1384 		return;
1385 
1386 	iodev->active_node->volume = volume;
1387 	cras_iodev_list_notify_node_volume(iodev->active_node);
1388 }
1389 
cras_bt_device_get_sco(struct cras_bt_device * device,int codec)1390 int cras_bt_device_get_sco(struct cras_bt_device *device, int codec)
1391 {
1392 	if (device->sco_ref_count == 0) {
1393 		device->sco_fd = cras_bt_device_sco_connect(device, codec);
1394 		if (device->sco_fd < 0)
1395 			return device->sco_fd;
1396 	}
1397 
1398 	++device->sco_ref_count;
1399 	return 0;
1400 }
1401 
cras_bt_device_put_sco(struct cras_bt_device * device)1402 void cras_bt_device_put_sco(struct cras_bt_device *device)
1403 {
1404 	if (device->sco_ref_count == 0)
1405 		return;
1406 
1407 	if (--device->sco_ref_count == 0)
1408 		close(device->sco_fd);
1409 }
1410