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