xref: /linux/drivers/bluetooth/hci_h5.c (revision 70c29b35fd87f87a7b8dad6eb8d55ce54a0d549a)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *
4  *  Bluetooth HCI Three-wire UART driver
5  *
6  *  Copyright (C) 2012  Intel Corporation
7  */
8 
9 #include <linux/acpi.h>
10 #include <linux/bitrev.h>
11 #include <linux/crc-ccitt.h>
12 #include <linux/errno.h>
13 #include <linux/gpio/consumer.h>
14 #include <linux/kernel.h>
15 #include <linux/of.h>
16 #include <linux/pm_runtime.h>
17 #include <linux/serdev.h>
18 #include <linux/skbuff.h>
19 
20 #include <net/bluetooth/bluetooth.h>
21 #include <net/bluetooth/hci_core.h>
22 
23 #include "btrtl.h"
24 #include "hci_uart.h"
25 
26 #define SUSPEND_TIMEOUT_MS	6000
27 
28 #define HCI_3WIRE_ACK_PKT	0
29 #define HCI_3WIRE_LINK_PKT	15
30 
31 /* Sliding window size */
32 #define H5_TX_WIN_MAX		4
33 
34 #define H5_ACK_TIMEOUT	msecs_to_jiffies(250)
35 #define H5_SYNC_TIMEOUT	msecs_to_jiffies(100)
36 
37 /*
38  * Maximum Three-wire packet:
39  *     4 byte header + max value for 12-bit length + 2 bytes for CRC
40  */
41 #define H5_MAX_LEN (4 + 0xfff + 2)
42 
43 /* Convenience macros for reading Three-wire header values */
44 #define H5_HDR_SEQ(hdr)		((hdr)[0] & 0x07)
45 #define H5_HDR_ACK(hdr)		(((hdr)[0] >> 3) & 0x07)
46 #define H5_HDR_CRC(hdr)		(((hdr)[0] >> 6) & 0x01)
47 #define H5_HDR_RELIABLE(hdr)	(((hdr)[0] >> 7) & 0x01)
48 #define H5_HDR_PKT_TYPE(hdr)	((hdr)[1] & 0x0f)
49 #define H5_HDR_LEN(hdr)		((((hdr)[1] >> 4) & 0x0f) + ((hdr)[2] << 4))
50 
51 #define SLIP_DELIMITER	0xc0
52 #define SLIP_ESC	0xdb
53 #define SLIP_ESC_DELIM	0xdc
54 #define SLIP_ESC_ESC	0xdd
55 
56 /* H5 state flags */
57 enum {
58 	H5_RX_ESC,		/* SLIP escape mode */
59 	H5_TX_ACK_REQ,		/* Pending ack to send */
60 	H5_WAKEUP_DISABLE,	/* Device cannot wake host */
61 	H5_HW_FLOW_CONTROL,	/* Use HW flow control */
62 	H5_CRC,			/* Use CRC */
63 };
64 
65 struct h5 {
66 	/* Must be the first member, hci_serdev.c expects this. */
67 	struct hci_uart		serdev_hu;
68 
69 	struct sk_buff_head	unack;		/* Unack'ed packets queue */
70 	struct sk_buff_head	rel;		/* Reliable packets queue */
71 	struct sk_buff_head	unrel;		/* Unreliable packets queue */
72 
73 	unsigned long		flags;
74 
75 	struct sk_buff		*rx_skb;	/* Receive buffer */
76 	size_t			rx_pending;	/* Expecting more bytes */
77 	u8			rx_ack;		/* Last ack number received */
78 
79 	int			(*rx_func)(struct hci_uart *hu, u8 c);
80 
81 	struct timer_list	timer;		/* Retransmission timer */
82 	struct hci_uart		*hu;		/* Parent HCI UART */
83 
84 	u8			tx_seq;		/* Next seq number to send */
85 	u8			tx_ack;		/* Next ack number to send */
86 	u8			tx_win;		/* Sliding window size */
87 
88 	enum {
89 		H5_UNINITIALIZED,
90 		H5_INITIALIZED,
91 		H5_ACTIVE,
92 	} state;
93 
94 	enum {
95 		H5_AWAKE,
96 		H5_SLEEPING,
97 		H5_WAKING_UP,
98 	} sleep;
99 
100 	const struct h5_vnd *vnd;
101 	const char *id;
102 
103 	struct gpio_desc *enable_gpio;
104 	struct gpio_desc *device_wake_gpio;
105 };
106 
107 enum h5_driver_info {
108 	H5_INFO_WAKEUP_DISABLE = BIT(0),
109 };
110 
111 struct h5_vnd {
112 	int (*setup)(struct h5 *h5);
113 	void (*open)(struct h5 *h5);
114 	void (*close)(struct h5 *h5);
115 	int (*suspend)(struct h5 *h5);
116 	int (*resume)(struct h5 *h5);
117 	const struct acpi_gpio_mapping *acpi_gpio_map;
118 	int sizeof_priv;
119 };
120 
121 struct h5_device_data {
122 	uint32_t driver_info;
123 	struct h5_vnd *vnd;
124 };
125 
126 static void h5_reset_rx(struct h5 *h5);
127 
128 static void h5_link_control(struct hci_uart *hu, const void *data, size_t len)
129 {
130 	struct h5 *h5 = hu->priv;
131 	struct sk_buff *nskb;
132 
133 	nskb = alloc_skb(3, GFP_ATOMIC);
134 	if (!nskb)
135 		return;
136 
137 	hci_skb_pkt_type(nskb) = HCI_3WIRE_LINK_PKT;
138 
139 	skb_put_data(nskb, data, len);
140 
141 	skb_queue_tail(&h5->unrel, nskb);
142 }
143 
144 static u8 h5_cfg_field(struct h5 *h5)
145 {
146 	/* Sliding window size (first 3 bits) and CRC request (fifth bit). */
147 	return (h5->tx_win & 0x07) | 0x10;
148 }
149 
150 static void h5_timed_event(struct timer_list *t)
151 {
152 	const unsigned char sync_req[] = { 0x01, 0x7e };
153 	unsigned char conf_req[3] = { 0x03, 0xfc };
154 	struct h5 *h5 = timer_container_of(h5, t, timer);
155 	struct hci_uart *hu = h5->hu;
156 	struct sk_buff *skb;
157 	unsigned long flags;
158 
159 	BT_DBG("%s", hu->hdev->name);
160 
161 	if (h5->state == H5_UNINITIALIZED)
162 		h5_link_control(hu, sync_req, sizeof(sync_req));
163 
164 	if (h5->state == H5_INITIALIZED) {
165 		conf_req[2] = h5_cfg_field(h5);
166 		h5_link_control(hu, conf_req, sizeof(conf_req));
167 	}
168 
169 	if (h5->state != H5_ACTIVE) {
170 		mod_timer(&h5->timer, jiffies + H5_SYNC_TIMEOUT);
171 		goto wakeup;
172 	}
173 
174 	if (h5->sleep != H5_AWAKE) {
175 		h5->sleep = H5_SLEEPING;
176 		goto wakeup;
177 	}
178 
179 	BT_DBG("hu %p retransmitting %u pkts", hu, h5->unack.qlen);
180 
181 	spin_lock_irqsave_nested(&h5->unack.lock, flags, SINGLE_DEPTH_NESTING);
182 
183 	while ((skb = __skb_dequeue_tail(&h5->unack)) != NULL) {
184 		h5->tx_seq = (h5->tx_seq - 1) & 0x07;
185 		skb_queue_head(&h5->rel, skb);
186 	}
187 
188 	spin_unlock_irqrestore(&h5->unack.lock, flags);
189 
190 wakeup:
191 	hci_uart_tx_wakeup(hu);
192 }
193 
194 static void h5_peer_reset(struct hci_uart *hu)
195 {
196 	struct h5 *h5 = hu->priv;
197 
198 	bt_dev_err(hu->hdev, "Peer device has reset");
199 
200 	h5->state = H5_UNINITIALIZED;
201 
202 	timer_delete(&h5->timer);
203 
204 	skb_queue_purge(&h5->rel);
205 	skb_queue_purge(&h5->unrel);
206 	skb_queue_purge(&h5->unack);
207 
208 	h5->tx_seq = 0;
209 	h5->tx_ack = 0;
210 
211 	/* Send reset request to upper stack */
212 	hci_reset_dev(hu->hdev);
213 }
214 
215 static int h5_open(struct hci_uart *hu)
216 {
217 	struct h5 *h5;
218 
219 	BT_DBG("hu %p", hu);
220 
221 	if (hu->serdev) {
222 		h5 = serdev_device_get_drvdata(hu->serdev);
223 	} else {
224 		h5 = kzalloc_obj(*h5);
225 		if (!h5)
226 			return -ENOMEM;
227 	}
228 
229 	hu->priv = h5;
230 	h5->hu = hu;
231 
232 	skb_queue_head_init(&h5->unack);
233 	skb_queue_head_init(&h5->rel);
234 	skb_queue_head_init(&h5->unrel);
235 
236 	h5_reset_rx(h5);
237 
238 	timer_setup(&h5->timer, h5_timed_event, 0);
239 
240 	h5->tx_win = H5_TX_WIN_MAX;
241 
242 	if (h5->vnd && h5->vnd->open)
243 		h5->vnd->open(h5);
244 
245 	set_bit(HCI_UART_INIT_PENDING, &hu->hdev_flags);
246 
247 	/*
248 	 * Wait one jiffy because the UART layer won't set HCI_UART_PROTO_READY,
249 	 * which allows us to send link packets, until this function returns.
250 	 */
251 	mod_timer(&h5->timer, jiffies + 1);
252 
253 	return 0;
254 }
255 
256 static int h5_close(struct hci_uart *hu)
257 {
258 	struct h5 *h5 = hu->priv;
259 
260 	timer_delete_sync(&h5->timer);
261 
262 	skb_queue_purge(&h5->unack);
263 	skb_queue_purge(&h5->rel);
264 	skb_queue_purge(&h5->unrel);
265 
266 	kfree_skb(h5->rx_skb);
267 	h5->rx_skb = NULL;
268 
269 	if (h5->vnd && h5->vnd->close)
270 		h5->vnd->close(h5);
271 
272 	if (!hu->serdev)
273 		kfree(h5);
274 
275 	hu->priv = NULL;
276 	return 0;
277 }
278 
279 static int h5_setup(struct hci_uart *hu)
280 {
281 	struct h5 *h5 = hu->priv;
282 
283 	if (h5->vnd && h5->vnd->setup)
284 		return h5->vnd->setup(h5);
285 
286 	return 0;
287 }
288 
289 static void h5_pkt_cull(struct h5 *h5)
290 {
291 	struct sk_buff *skb, *tmp;
292 	unsigned long flags;
293 	int i, to_remove;
294 	u8 seq;
295 
296 	spin_lock_irqsave(&h5->unack.lock, flags);
297 
298 	to_remove = skb_queue_len(&h5->unack);
299 	if (to_remove == 0)
300 		goto unlock;
301 
302 	seq = h5->tx_seq;
303 
304 	while (to_remove > 0) {
305 		if (h5->rx_ack == seq)
306 			break;
307 
308 		to_remove--;
309 		seq = (seq - 1) & 0x07;
310 	}
311 
312 	if (seq != h5->rx_ack)
313 		BT_ERR("Controller acked invalid packet");
314 
315 	i = 0;
316 	skb_queue_walk_safe(&h5->unack, skb, tmp) {
317 		if (i++ >= to_remove)
318 			break;
319 
320 		__skb_unlink(skb, &h5->unack);
321 		dev_kfree_skb_irq(skb);
322 	}
323 
324 	if (skb_queue_empty(&h5->unack))
325 		timer_delete(&h5->timer);
326 
327 unlock:
328 	spin_unlock_irqrestore(&h5->unack.lock, flags);
329 }
330 
331 static void h5_handle_internal_rx(struct hci_uart *hu)
332 {
333 	struct h5 *h5 = hu->priv;
334 	const unsigned char sync_req[] = { 0x01, 0x7e };
335 	const unsigned char sync_rsp[] = { 0x02, 0x7d };
336 	unsigned char conf_req[3] = { 0x03, 0xfc };
337 	const unsigned char conf_rsp[] = { 0x04, 0x7b };
338 	const unsigned char wakeup_req[] = { 0x05, 0xfa };
339 	const unsigned char woken_req[] = { 0x06, 0xf9 };
340 	const unsigned char sleep_req[] = { 0x07, 0x78 };
341 	const unsigned char *hdr = h5->rx_skb->data;
342 	const unsigned char *data = &h5->rx_skb->data[4];
343 
344 	BT_DBG("%s", hu->hdev->name);
345 
346 	if (H5_HDR_PKT_TYPE(hdr) != HCI_3WIRE_LINK_PKT)
347 		return;
348 
349 	if (H5_HDR_LEN(hdr) < 2)
350 		return;
351 
352 	conf_req[2] = h5_cfg_field(h5);
353 
354 	if (memcmp(data, sync_req, 2) == 0) {
355 		if (h5->state == H5_ACTIVE)
356 			h5_peer_reset(hu);
357 		h5_link_control(hu, sync_rsp, 2);
358 	} else if (memcmp(data, sync_rsp, 2) == 0) {
359 		if (h5->state == H5_ACTIVE)
360 			h5_peer_reset(hu);
361 		h5->state = H5_INITIALIZED;
362 		h5_link_control(hu, conf_req, 3);
363 	} else if (memcmp(data, conf_req, 2) == 0) {
364 		h5_link_control(hu, conf_rsp, 2);
365 		h5_link_control(hu, conf_req, 3);
366 	} else if (memcmp(data, conf_rsp, 2) == 0) {
367 		if (H5_HDR_LEN(hdr) > 2) {
368 			h5->tx_win = (data[2] & 0x07);
369 			assign_bit(H5_CRC, &h5->flags, data[2] & 0x10);
370 		}
371 		BT_DBG("Three-wire init complete. tx_win %u", h5->tx_win);
372 		h5->state = H5_ACTIVE;
373 		hci_uart_init_ready(hu);
374 		return;
375 	} else if (memcmp(data, sleep_req, 2) == 0) {
376 		BT_DBG("Peer went to sleep");
377 		h5->sleep = H5_SLEEPING;
378 		return;
379 	} else if (memcmp(data, woken_req, 2) == 0) {
380 		BT_DBG("Peer woke up");
381 		h5->sleep = H5_AWAKE;
382 	} else if (memcmp(data, wakeup_req, 2) == 0) {
383 		BT_DBG("Peer requested wakeup");
384 		h5_link_control(hu, woken_req, 2);
385 		h5->sleep = H5_AWAKE;
386 	} else {
387 		BT_DBG("Link Control: 0x%02hhx 0x%02hhx", data[0], data[1]);
388 		return;
389 	}
390 
391 	hci_uart_tx_wakeup(hu);
392 }
393 
394 static void h5_complete_rx_pkt(struct hci_uart *hu)
395 {
396 	struct h5 *h5 = hu->priv;
397 	const unsigned char *hdr = h5->rx_skb->data;
398 
399 	if (H5_HDR_RELIABLE(hdr)) {
400 		h5->tx_ack = (h5->tx_ack + 1) % 8;
401 		set_bit(H5_TX_ACK_REQ, &h5->flags);
402 		hci_uart_tx_wakeup(hu);
403 	}
404 
405 	h5->rx_ack = H5_HDR_ACK(hdr);
406 
407 	h5_pkt_cull(h5);
408 
409 	switch (H5_HDR_PKT_TYPE(hdr)) {
410 	case HCI_EVENT_PKT:
411 	case HCI_ACLDATA_PKT:
412 	case HCI_SCODATA_PKT:
413 	case HCI_ISODATA_PKT:
414 		hci_skb_pkt_type(h5->rx_skb) = H5_HDR_PKT_TYPE(hdr);
415 
416 		/* Remove Three-wire header */
417 		skb_pull(h5->rx_skb, 4);
418 
419 		hci_recv_frame(hu->hdev, h5->rx_skb);
420 		h5->rx_skb = NULL;
421 
422 		break;
423 
424 	default:
425 		h5_handle_internal_rx(hu);
426 		break;
427 	}
428 
429 	h5_reset_rx(h5);
430 }
431 
432 static int h5_rx_crc(struct hci_uart *hu, unsigned char c)
433 {
434 	struct h5 *h5 = hu->priv;
435 	const unsigned char *hdr = h5->rx_skb->data;
436 	u16 crc;
437 	__be16 crc_be;
438 
439 	crc = crc_ccitt(0xffff, hdr, 4 + H5_HDR_LEN(hdr));
440 	crc = bitrev16(crc);
441 
442 	crc_be = cpu_to_be16(crc);
443 
444 	if (memcmp(&crc_be, hdr + 4 + H5_HDR_LEN(hdr), 2) != 0) {
445 		bt_dev_err(hu->hdev, "Received packet with invalid CRC");
446 		h5_reset_rx(h5);
447 	} else {
448 		/* Remove CRC bytes */
449 		skb_trim(h5->rx_skb, 4 + H5_HDR_LEN(hdr));
450 		h5_complete_rx_pkt(hu);
451 	}
452 
453 	return 0;
454 }
455 
456 static int h5_rx_payload(struct hci_uart *hu, unsigned char c)
457 {
458 	struct h5 *h5 = hu->priv;
459 	const unsigned char *hdr = h5->rx_skb->data;
460 
461 	if (H5_HDR_CRC(hdr)) {
462 		h5->rx_func = h5_rx_crc;
463 		h5->rx_pending = 2;
464 	} else {
465 		h5_complete_rx_pkt(hu);
466 	}
467 
468 	return 0;
469 }
470 
471 static int h5_rx_3wire_hdr(struct hci_uart *hu, unsigned char c)
472 {
473 	struct h5 *h5 = hu->priv;
474 	const unsigned char *hdr = h5->rx_skb->data;
475 
476 	BT_DBG("%s rx: seq %u ack %u crc %u rel %u type %u len %u",
477 	       hu->hdev->name, H5_HDR_SEQ(hdr), H5_HDR_ACK(hdr),
478 	       H5_HDR_CRC(hdr), H5_HDR_RELIABLE(hdr), H5_HDR_PKT_TYPE(hdr),
479 	       H5_HDR_LEN(hdr));
480 
481 	if (((hdr[0] + hdr[1] + hdr[2] + hdr[3]) & 0xff) != 0xff) {
482 		bt_dev_err(hu->hdev, "Invalid header checksum");
483 		h5_reset_rx(h5);
484 		return 0;
485 	}
486 
487 	if (H5_HDR_RELIABLE(hdr) && H5_HDR_SEQ(hdr) != h5->tx_ack) {
488 		bt_dev_err(hu->hdev, "Out-of-order packet arrived (%u != %u)",
489 			   H5_HDR_SEQ(hdr), h5->tx_ack);
490 		set_bit(H5_TX_ACK_REQ, &h5->flags);
491 		hci_uart_tx_wakeup(hu);
492 		h5_reset_rx(h5);
493 		return 0;
494 	}
495 
496 	if (h5->state != H5_ACTIVE &&
497 	    H5_HDR_PKT_TYPE(hdr) != HCI_3WIRE_LINK_PKT) {
498 		bt_dev_err(hu->hdev, "Non-link packet received in non-active state");
499 		h5_reset_rx(h5);
500 		return 0;
501 	}
502 
503 	h5->rx_func = h5_rx_payload;
504 	h5->rx_pending = H5_HDR_LEN(hdr);
505 
506 	return 0;
507 }
508 
509 static int h5_rx_pkt_start(struct hci_uart *hu, unsigned char c)
510 {
511 	struct h5 *h5 = hu->priv;
512 
513 	if (c == SLIP_DELIMITER)
514 		return 1;
515 
516 	h5->rx_func = h5_rx_3wire_hdr;
517 	h5->rx_pending = 4;
518 
519 	h5->rx_skb = bt_skb_alloc(H5_MAX_LEN, GFP_ATOMIC);
520 	if (!h5->rx_skb) {
521 		bt_dev_err(hu->hdev, "Can't allocate mem for new packet");
522 		h5_reset_rx(h5);
523 		return -ENOMEM;
524 	}
525 
526 	h5->rx_skb->dev = (void *)hu->hdev;
527 
528 	return 0;
529 }
530 
531 static int h5_rx_delimiter(struct hci_uart *hu, unsigned char c)
532 {
533 	struct h5 *h5 = hu->priv;
534 
535 	if (c == SLIP_DELIMITER)
536 		h5->rx_func = h5_rx_pkt_start;
537 
538 	return 1;
539 }
540 
541 static void h5_unslip_one_byte(struct h5 *h5, unsigned char c)
542 {
543 	const u8 delim = SLIP_DELIMITER, esc = SLIP_ESC;
544 	const u8 *byte = &c;
545 
546 	if (test_bit(H5_RX_ESC, &h5->flags)) {
547 		clear_bit(H5_RX_ESC, &h5->flags);
548 		switch (c) {
549 		case SLIP_ESC_DELIM:
550 			byte = &delim;
551 			break;
552 		case SLIP_ESC_ESC:
553 			byte = &esc;
554 			break;
555 		default:
556 			BT_ERR("Invalid esc byte 0x%02hhx", c);
557 			h5_reset_rx(h5);
558 			return;
559 		}
560 	} else if (c == SLIP_ESC) {
561 		set_bit(H5_RX_ESC, &h5->flags);
562 		return;
563 	}
564 
565 	skb_put_data(h5->rx_skb, byte, 1);
566 	h5->rx_pending--;
567 
568 	BT_DBG("unslipped 0x%02hhx, rx_pending %zu", *byte, h5->rx_pending);
569 }
570 
571 static void h5_reset_rx(struct h5 *h5)
572 {
573 	if (h5->rx_skb) {
574 		kfree_skb(h5->rx_skb);
575 		h5->rx_skb = NULL;
576 	}
577 
578 	h5->rx_func = h5_rx_delimiter;
579 	h5->rx_pending = 0;
580 	clear_bit(H5_RX_ESC, &h5->flags);
581 	clear_bit(H5_CRC, &h5->flags);
582 }
583 
584 static int h5_recv(struct hci_uart *hu, const void *data, int count)
585 {
586 	struct h5 *h5 = hu->priv;
587 	const unsigned char *ptr = data;
588 
589 	if (!h5)
590 		return -ENODEV;
591 
592 	BT_DBG("%s pending %zu count %d", hu->hdev->name, h5->rx_pending,
593 	       count);
594 
595 	while (count > 0) {
596 		int processed;
597 
598 		if (h5->rx_pending > 0) {
599 			if (*ptr == SLIP_DELIMITER) {
600 				bt_dev_err(hu->hdev, "Too short H5 packet");
601 				h5_reset_rx(h5);
602 				continue;
603 			}
604 
605 			h5_unslip_one_byte(h5, *ptr);
606 
607 			ptr++; count--;
608 			continue;
609 		}
610 
611 		processed = h5->rx_func(hu, *ptr);
612 		if (processed < 0)
613 			return processed;
614 
615 		ptr += processed;
616 		count -= processed;
617 	}
618 
619 	if (hu->serdev) {
620 		pm_runtime_get(&hu->serdev->dev);
621 		pm_runtime_put_autosuspend(&hu->serdev->dev);
622 	}
623 
624 	return 0;
625 }
626 
627 static int h5_enqueue(struct hci_uart *hu, struct sk_buff *skb)
628 {
629 	struct h5 *h5 = hu->priv;
630 
631 	if (skb->len > 0xfff) {
632 		bt_dev_err(hu->hdev, "Packet too long (%u bytes)", skb->len);
633 		kfree_skb(skb);
634 		return 0;
635 	}
636 
637 	if (h5->state != H5_ACTIVE) {
638 		bt_dev_err(hu->hdev, "Ignoring HCI data in non-active state");
639 		kfree_skb(skb);
640 		return 0;
641 	}
642 
643 	switch (hci_skb_pkt_type(skb)) {
644 	case HCI_ACLDATA_PKT:
645 	case HCI_COMMAND_PKT:
646 		skb_queue_tail(&h5->rel, skb);
647 		break;
648 
649 	case HCI_SCODATA_PKT:
650 	case HCI_ISODATA_PKT:
651 		skb_queue_tail(&h5->unrel, skb);
652 		break;
653 
654 	default:
655 		bt_dev_err(hu->hdev, "Unknown packet type %u", hci_skb_pkt_type(skb));
656 		kfree_skb(skb);
657 		break;
658 	}
659 
660 	if (hu->serdev) {
661 		pm_runtime_get_sync(&hu->serdev->dev);
662 		pm_runtime_put_autosuspend(&hu->serdev->dev);
663 	}
664 
665 	return 0;
666 }
667 
668 static void h5_slip_delim(struct sk_buff *skb)
669 {
670 	const char delim = SLIP_DELIMITER;
671 
672 	skb_put_data(skb, &delim, 1);
673 }
674 
675 static void h5_slip_one_byte(struct sk_buff *skb, u8 c)
676 {
677 	const char esc_delim[2] = { SLIP_ESC, SLIP_ESC_DELIM };
678 	const char esc_esc[2] = { SLIP_ESC, SLIP_ESC_ESC };
679 
680 	switch (c) {
681 	case SLIP_DELIMITER:
682 		skb_put_data(skb, &esc_delim, 2);
683 		break;
684 	case SLIP_ESC:
685 		skb_put_data(skb, &esc_esc, 2);
686 		break;
687 	default:
688 		skb_put_data(skb, &c, 1);
689 	}
690 }
691 
692 static bool valid_packet_type(u8 type)
693 {
694 	switch (type) {
695 	case HCI_ACLDATA_PKT:
696 	case HCI_COMMAND_PKT:
697 	case HCI_SCODATA_PKT:
698 	case HCI_ISODATA_PKT:
699 	case HCI_3WIRE_LINK_PKT:
700 	case HCI_3WIRE_ACK_PKT:
701 		return true;
702 	default:
703 		return false;
704 	}
705 }
706 
707 static struct sk_buff *h5_prepare_pkt(struct hci_uart *hu, u8 pkt_type,
708 				      const u8 *data, size_t len)
709 {
710 	struct h5 *h5 = hu->priv;
711 	struct sk_buff *nskb;
712 	u8 hdr[4];
713 	u16 crc;
714 	int i;
715 
716 	if (!valid_packet_type(pkt_type)) {
717 		bt_dev_err(hu->hdev, "Unknown packet type %u", pkt_type);
718 		return NULL;
719 	}
720 
721 	/*
722 	 * Max len of packet: (original len + 4 (H5 hdr) + 2 (crc)) * 2
723 	 * (because bytes 0xc0 and 0xdb are escaped, worst case is when
724 	 * the packet is all made of 0xc0 and 0xdb) + 2 (0xc0
725 	 * delimiters at start and end).
726 	 */
727 	nskb = alloc_skb((len + 6) * 2 + 2, GFP_ATOMIC);
728 	if (!nskb)
729 		return NULL;
730 
731 	hci_skb_pkt_type(nskb) = pkt_type;
732 
733 	h5_slip_delim(nskb);
734 
735 	hdr[0] = h5->tx_ack << 3;
736 	clear_bit(H5_TX_ACK_REQ, &h5->flags);
737 
738 	/* Reliable packet? */
739 	if (pkt_type == HCI_ACLDATA_PKT || pkt_type == HCI_COMMAND_PKT) {
740 		hdr[0] |= 1 << 7;
741 		hdr[0] |= (test_bit(H5_CRC, &h5->flags) && 1) << 6;
742 		hdr[0] |= h5->tx_seq;
743 		h5->tx_seq = (h5->tx_seq + 1) % 8;
744 	}
745 
746 	hdr[1] = pkt_type | ((len & 0x0f) << 4);
747 	hdr[2] = len >> 4;
748 	hdr[3] = ~((hdr[0] + hdr[1] + hdr[2]) & 0xff);
749 
750 	BT_DBG("%s tx: seq %u ack %u crc %u rel %u type %u len %u",
751 	       hu->hdev->name, H5_HDR_SEQ(hdr), H5_HDR_ACK(hdr),
752 	       H5_HDR_CRC(hdr), H5_HDR_RELIABLE(hdr), H5_HDR_PKT_TYPE(hdr),
753 	       H5_HDR_LEN(hdr));
754 
755 	for (i = 0; i < 4; i++)
756 		h5_slip_one_byte(nskb, hdr[i]);
757 
758 	for (i = 0; i < len; i++)
759 		h5_slip_one_byte(nskb, data[i]);
760 
761 	if (H5_HDR_CRC(hdr)) {
762 		crc = crc_ccitt(0xffff, hdr, 4);
763 		crc = crc_ccitt(crc, data, len);
764 		crc = bitrev16(crc);
765 
766 		h5_slip_one_byte(nskb, (crc >> 8) & 0xff);
767 		h5_slip_one_byte(nskb, crc & 0xff);
768 	}
769 
770 	h5_slip_delim(nskb);
771 
772 	return nskb;
773 }
774 
775 static struct sk_buff *h5_dequeue(struct hci_uart *hu)
776 {
777 	struct h5 *h5 = hu->priv;
778 	unsigned long flags;
779 	struct sk_buff *skb, *nskb;
780 
781 	if (h5->sleep != H5_AWAKE) {
782 		const unsigned char wakeup_req[] = { 0x05, 0xfa };
783 
784 		if (h5->sleep == H5_WAKING_UP)
785 			return NULL;
786 
787 		h5->sleep = H5_WAKING_UP;
788 		BT_DBG("Sending wakeup request");
789 
790 		mod_timer(&h5->timer, jiffies + HZ / 100);
791 		return h5_prepare_pkt(hu, HCI_3WIRE_LINK_PKT, wakeup_req, 2);
792 	}
793 
794 	skb = skb_dequeue(&h5->unrel);
795 	if (skb) {
796 		nskb = h5_prepare_pkt(hu, hci_skb_pkt_type(skb),
797 				      skb->data, skb->len);
798 		if (nskb) {
799 			kfree_skb(skb);
800 			return nskb;
801 		}
802 
803 		skb_queue_head(&h5->unrel, skb);
804 		bt_dev_err(hu->hdev, "Could not dequeue pkt because alloc_skb failed");
805 	}
806 
807 	spin_lock_irqsave_nested(&h5->unack.lock, flags, SINGLE_DEPTH_NESTING);
808 
809 	if (h5->unack.qlen >= h5->tx_win)
810 		goto unlock;
811 
812 	skb = skb_dequeue(&h5->rel);
813 	if (skb) {
814 		nskb = h5_prepare_pkt(hu, hci_skb_pkt_type(skb),
815 				      skb->data, skb->len);
816 		if (nskb) {
817 			__skb_queue_tail(&h5->unack, skb);
818 			mod_timer(&h5->timer, jiffies + H5_ACK_TIMEOUT);
819 			spin_unlock_irqrestore(&h5->unack.lock, flags);
820 			return nskb;
821 		}
822 
823 		skb_queue_head(&h5->rel, skb);
824 		bt_dev_err(hu->hdev, "Could not dequeue pkt because alloc_skb failed");
825 	}
826 
827 unlock:
828 	spin_unlock_irqrestore(&h5->unack.lock, flags);
829 
830 	if (test_bit(H5_TX_ACK_REQ, &h5->flags))
831 		return h5_prepare_pkt(hu, HCI_3WIRE_ACK_PKT, NULL, 0);
832 
833 	return NULL;
834 }
835 
836 static int h5_flush(struct hci_uart *hu)
837 {
838 	BT_DBG("hu %p", hu);
839 	return 0;
840 }
841 
842 static const struct hci_uart_proto h5p = {
843 	.id		= HCI_UART_3WIRE,
844 	.name		= "Three-wire (H5)",
845 	.open		= h5_open,
846 	.close		= h5_close,
847 	.setup		= h5_setup,
848 	.recv		= h5_recv,
849 	.enqueue	= h5_enqueue,
850 	.dequeue	= h5_dequeue,
851 	.flush		= h5_flush,
852 };
853 
854 static int h5_serdev_probe(struct serdev_device *serdev)
855 {
856 	struct device *dev = &serdev->dev;
857 	struct h5 *h5;
858 	const struct h5_device_data *data;
859 
860 	h5 = devm_kzalloc(dev, sizeof(*h5), GFP_KERNEL);
861 	if (!h5)
862 		return -ENOMEM;
863 
864 	h5->hu = &h5->serdev_hu;
865 	h5->serdev_hu.serdev = serdev;
866 	serdev_device_set_drvdata(serdev, h5);
867 
868 	if (has_acpi_companion(dev)) {
869 		const struct acpi_device_id *match;
870 
871 		match = acpi_match_device(dev->driver->acpi_match_table, dev);
872 		if (!match)
873 			return -ENODEV;
874 
875 		data = (const struct h5_device_data *)match->driver_data;
876 		h5->vnd = data->vnd;
877 		h5->id  = (char *)match->id;
878 
879 		if (h5->vnd->acpi_gpio_map)
880 			devm_acpi_dev_add_driver_gpios(dev,
881 						       h5->vnd->acpi_gpio_map);
882 	} else {
883 		data = of_device_get_match_data(dev);
884 		if (!data)
885 			return -ENODEV;
886 
887 		h5->vnd = data->vnd;
888 	}
889 
890 	if (data->driver_info & H5_INFO_WAKEUP_DISABLE)
891 		set_bit(H5_WAKEUP_DISABLE, &h5->flags);
892 
893 	h5->enable_gpio = devm_gpiod_get_optional(dev, "enable", GPIOD_OUT_LOW);
894 	if (IS_ERR(h5->enable_gpio))
895 		return PTR_ERR(h5->enable_gpio);
896 
897 	h5->device_wake_gpio = devm_gpiod_get_optional(dev, "device-wake",
898 						       GPIOD_OUT_LOW);
899 	if (IS_ERR(h5->device_wake_gpio))
900 		return PTR_ERR(h5->device_wake_gpio);
901 
902 	return hci_uart_register_device_priv(&h5->serdev_hu, &h5p,
903 					     h5->vnd->sizeof_priv);
904 }
905 
906 static void h5_serdev_remove(struct serdev_device *serdev)
907 {
908 	struct h5 *h5 = serdev_device_get_drvdata(serdev);
909 
910 	hci_uart_unregister_device(&h5->serdev_hu);
911 }
912 
913 static int __maybe_unused h5_serdev_suspend(struct device *dev)
914 {
915 	struct h5 *h5 = dev_get_drvdata(dev);
916 	int ret = 0;
917 
918 	if (h5->vnd && h5->vnd->suspend)
919 		ret = h5->vnd->suspend(h5);
920 
921 	return ret;
922 }
923 
924 static int __maybe_unused h5_serdev_resume(struct device *dev)
925 {
926 	struct h5 *h5 = dev_get_drvdata(dev);
927 	int ret = 0;
928 
929 	if (h5->vnd && h5->vnd->resume)
930 		ret = h5->vnd->resume(h5);
931 
932 	return ret;
933 }
934 
935 #ifdef CONFIG_BT_HCIUART_RTL
936 static int h5_btrtl_setup(struct h5 *h5)
937 {
938 	struct btrtl_device_info *btrtl_dev;
939 	struct sk_buff *skb;
940 	__le32 baudrate_data;
941 	u32 device_baudrate;
942 	unsigned int controller_baudrate;
943 	bool flow_control;
944 	int err;
945 
946 	btrtl_dev = btrtl_initialize(h5->hu->hdev, h5->id);
947 	if (IS_ERR(btrtl_dev))
948 		return PTR_ERR(btrtl_dev);
949 
950 	err = btrtl_get_uart_settings(h5->hu->hdev, btrtl_dev,
951 				      &controller_baudrate, &device_baudrate,
952 				      &flow_control);
953 	if (err)
954 		goto out_free;
955 
956 	baudrate_data = cpu_to_le32(device_baudrate);
957 	skb = __hci_cmd_sync(h5->hu->hdev, 0xfc17, sizeof(baudrate_data),
958 			     &baudrate_data, HCI_INIT_TIMEOUT);
959 	if (IS_ERR(skb)) {
960 		rtl_dev_err(h5->hu->hdev, "set baud rate command failed\n");
961 		err = PTR_ERR(skb);
962 		goto out_free;
963 	} else {
964 		kfree_skb(skb);
965 	}
966 	/* Give the device some time to set up the new baudrate. */
967 	usleep_range(10000, 20000);
968 
969 	serdev_device_set_baudrate(h5->hu->serdev, controller_baudrate);
970 	serdev_device_set_flow_control(h5->hu->serdev, flow_control);
971 
972 	if (flow_control)
973 		set_bit(H5_HW_FLOW_CONTROL, &h5->flags);
974 
975 	err = btrtl_download_firmware(h5->hu->hdev, btrtl_dev);
976 	/* Give the device some time before the hci-core sends it a reset */
977 	usleep_range(10000, 20000);
978 	if (err)
979 		goto out_free;
980 
981 	btrtl_set_quirks(h5->hu->hdev, btrtl_dev);
982 
983 out_free:
984 	btrtl_free(btrtl_dev);
985 
986 	return err;
987 }
988 
989 static void h5_btrtl_open(struct h5 *h5)
990 {
991 	/*
992 	 * Since h5_btrtl_resume() does a device_reprobe() the suspend handling
993 	 * done by the hci_suspend_notifier is not necessary; it actually causes
994 	 * delays and a bunch of errors to get logged, so disable it.
995 	 */
996 	if (test_bit(H5_WAKEUP_DISABLE, &h5->flags))
997 		set_bit(HCI_UART_NO_SUSPEND_NOTIFIER, &h5->hu->flags);
998 
999 	/* Devices always start with these fixed parameters */
1000 	serdev_device_set_flow_control(h5->hu->serdev, false);
1001 	serdev_device_set_parity(h5->hu->serdev, SERDEV_PARITY_EVEN);
1002 	serdev_device_set_baudrate(h5->hu->serdev, 115200);
1003 
1004 	if (!test_bit(H5_WAKEUP_DISABLE, &h5->flags)) {
1005 		pm_runtime_set_active(&h5->hu->serdev->dev);
1006 		pm_runtime_use_autosuspend(&h5->hu->serdev->dev);
1007 		pm_runtime_set_autosuspend_delay(&h5->hu->serdev->dev,
1008 						 SUSPEND_TIMEOUT_MS);
1009 		pm_runtime_enable(&h5->hu->serdev->dev);
1010 	}
1011 
1012 	/* The controller needs reset to startup */
1013 	gpiod_set_value_cansleep(h5->enable_gpio, 0);
1014 	gpiod_set_value_cansleep(h5->device_wake_gpio, 0);
1015 	msleep(100);
1016 
1017 	/* The controller needs up to 500ms to wakeup */
1018 	gpiod_set_value_cansleep(h5->enable_gpio, 1);
1019 	gpiod_set_value_cansleep(h5->device_wake_gpio, 1);
1020 	msleep(500);
1021 }
1022 
1023 static void h5_btrtl_close(struct h5 *h5)
1024 {
1025 	if (!test_bit(H5_WAKEUP_DISABLE, &h5->flags)) {
1026 		pm_runtime_dont_use_autosuspend(&h5->hu->serdev->dev);
1027 		pm_runtime_disable(&h5->hu->serdev->dev);
1028 	}
1029 
1030 	gpiod_set_value_cansleep(h5->device_wake_gpio, 0);
1031 	gpiod_set_value_cansleep(h5->enable_gpio, 0);
1032 }
1033 
1034 /* Suspend/resume support. On many devices the RTL BT device loses power during
1035  * suspend/resume, causing it to lose its firmware and all state. So we simply
1036  * turn it off on suspend and reprobe on resume. This mirrors how RTL devices
1037  * are handled in the USB driver, where the BTUSB_WAKEUP_DISABLE is used which
1038  * also causes a reprobe on resume.
1039  */
1040 static int h5_btrtl_suspend(struct h5 *h5)
1041 {
1042 	serdev_device_set_flow_control(h5->hu->serdev, false);
1043 	gpiod_set_value_cansleep(h5->device_wake_gpio, 0);
1044 
1045 	if (test_bit(H5_WAKEUP_DISABLE, &h5->flags))
1046 		gpiod_set_value_cansleep(h5->enable_gpio, 0);
1047 
1048 	return 0;
1049 }
1050 
1051 struct h5_btrtl_reprobe {
1052 	struct device *dev;
1053 	struct work_struct work;
1054 };
1055 
1056 static void h5_btrtl_reprobe_worker(struct work_struct *work)
1057 {
1058 	struct h5_btrtl_reprobe *reprobe =
1059 		container_of(work, struct h5_btrtl_reprobe, work);
1060 	int ret;
1061 
1062 	ret = device_reprobe(reprobe->dev);
1063 	if (ret && ret != -EPROBE_DEFER)
1064 		dev_err(reprobe->dev, "Reprobe error %d\n", ret);
1065 
1066 	put_device(reprobe->dev);
1067 	kfree(reprobe);
1068 	module_put(THIS_MODULE);
1069 }
1070 
1071 static int h5_btrtl_resume(struct h5 *h5)
1072 {
1073 	if (test_bit(H5_WAKEUP_DISABLE, &h5->flags)) {
1074 		struct h5_btrtl_reprobe *reprobe;
1075 
1076 		reprobe = kzalloc_obj(*reprobe);
1077 		if (!reprobe)
1078 			return -ENOMEM;
1079 
1080 		__module_get(THIS_MODULE);
1081 
1082 		INIT_WORK(&reprobe->work, h5_btrtl_reprobe_worker);
1083 		reprobe->dev = get_device(&h5->hu->serdev->dev);
1084 		queue_work(system_long_wq, &reprobe->work);
1085 	} else {
1086 		gpiod_set_value_cansleep(h5->device_wake_gpio, 1);
1087 
1088 		if (test_bit(H5_HW_FLOW_CONTROL, &h5->flags))
1089 			serdev_device_set_flow_control(h5->hu->serdev, true);
1090 	}
1091 
1092 	return 0;
1093 }
1094 
1095 static const struct acpi_gpio_params btrtl_device_wake_gpios = { 0, 0, false };
1096 static const struct acpi_gpio_params btrtl_enable_gpios = { 1, 0, false };
1097 static const struct acpi_gpio_params btrtl_host_wake_gpios = { 2, 0, false };
1098 static const struct acpi_gpio_mapping acpi_btrtl_gpios[] = {
1099 	{ "device-wake-gpios", &btrtl_device_wake_gpios, 1 },
1100 	{ "enable-gpios", &btrtl_enable_gpios, 1 },
1101 	{ "host-wake-gpios", &btrtl_host_wake_gpios, 1 },
1102 	{},
1103 };
1104 
1105 static struct h5_vnd rtl_vnd = {
1106 	.setup		= h5_btrtl_setup,
1107 	.open		= h5_btrtl_open,
1108 	.close		= h5_btrtl_close,
1109 	.suspend	= h5_btrtl_suspend,
1110 	.resume		= h5_btrtl_resume,
1111 	.acpi_gpio_map	= acpi_btrtl_gpios,
1112 	.sizeof_priv    = sizeof(struct btrealtek_data),
1113 };
1114 
1115 static const struct h5_device_data h5_data_rtl8822cs = {
1116 	.vnd = &rtl_vnd,
1117 };
1118 
1119 static const struct h5_device_data h5_data_rtl8723bs = {
1120 	.driver_info = H5_INFO_WAKEUP_DISABLE,
1121 	.vnd = &rtl_vnd,
1122 };
1123 #endif
1124 
1125 #ifdef CONFIG_ACPI
1126 static const struct acpi_device_id h5_acpi_match[] = {
1127 #ifdef CONFIG_BT_HCIUART_RTL
1128 	{ .id = "OBDA0623", .driver_data = (kernel_ulong_t)&h5_data_rtl8723bs },
1129 	{ .id = "OBDA8723", .driver_data = (kernel_ulong_t)&h5_data_rtl8723bs },
1130 #endif
1131 	{ }
1132 };
1133 MODULE_DEVICE_TABLE(acpi, h5_acpi_match);
1134 #endif
1135 
1136 static const struct dev_pm_ops h5_serdev_pm_ops = {
1137 	SET_SYSTEM_SLEEP_PM_OPS(h5_serdev_suspend, h5_serdev_resume)
1138 	SET_RUNTIME_PM_OPS(h5_serdev_suspend, h5_serdev_resume, NULL)
1139 };
1140 
1141 static const struct of_device_id rtl_bluetooth_of_match[] = {
1142 #ifdef CONFIG_BT_HCIUART_RTL
1143 	{ .compatible = "realtek,rtl8822cs-bt",
1144 	  .data = (const void *)&h5_data_rtl8822cs },
1145 	{ .compatible = "realtek,rtl8723bs-bt",
1146 	  .data = (const void *)&h5_data_rtl8723bs },
1147 	{ .compatible = "realtek,rtl8723cs-bt",
1148 	  .data = (const void *)&h5_data_rtl8723bs },
1149 	{ .compatible = "realtek,rtl8723ds-bt",
1150 	  .data = (const void *)&h5_data_rtl8723bs },
1151 #endif
1152 	{ },
1153 };
1154 MODULE_DEVICE_TABLE(of, rtl_bluetooth_of_match);
1155 
1156 static struct serdev_device_driver h5_serdev_driver = {
1157 	.probe = h5_serdev_probe,
1158 	.remove = h5_serdev_remove,
1159 	.driver = {
1160 		.name = "hci_uart_h5",
1161 		.acpi_match_table = ACPI_PTR(h5_acpi_match),
1162 		.pm = &h5_serdev_pm_ops,
1163 		.of_match_table = rtl_bluetooth_of_match,
1164 	},
1165 };
1166 
1167 int __init h5_init(void)
1168 {
1169 	serdev_device_driver_register(&h5_serdev_driver);
1170 	return hci_uart_register_proto(&h5p);
1171 }
1172 
1173 int __exit h5_deinit(void)
1174 {
1175 	serdev_device_driver_unregister(&h5_serdev_driver);
1176 	return hci_uart_unregister_proto(&h5p);
1177 }
1178