1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (c) 2018 MediaTek Inc.
3 
4 /*
5  * Bluetooth support for MediaTek serial devices
6  *
7  * Author: Sean Wang <sean.wang@mediatek.com>
8  *
9  */
10 
11 #include <linux/unaligned.h>
12 #include <linux/atomic.h>
13 #include <linux/clk.h>
14 #include <linux/firmware.h>
15 #include <linux/gpio/consumer.h>
16 #include <linux/iopoll.h>
17 #include <linux/kernel.h>
18 #include <linux/module.h>
19 #include <linux/of.h>
20 #include <linux/pinctrl/consumer.h>
21 #include <linux/pm_runtime.h>
22 #include <linux/regulator/consumer.h>
23 #include <linux/serdev.h>
24 #include <linux/skbuff.h>
25 #include <linux/usb.h>
26 
27 #include <net/bluetooth/bluetooth.h>
28 #include <net/bluetooth/hci_core.h>
29 
30 #include "h4_recv.h"
31 #include "btmtk.h"
32 
33 #define VERSION "0.2"
34 
35 #define MTK_STP_TLR_SIZE	2
36 
37 #define BTMTKUART_TX_STATE_ACTIVE	1
38 #define BTMTKUART_TX_STATE_WAKEUP	2
39 #define BTMTKUART_TX_WAIT_VND_EVT	3
40 #define BTMTKUART_REQUIRED_WAKEUP	4
41 
42 #define BTMTKUART_FLAG_STANDALONE_HW	 BIT(0)
43 
44 struct mtk_stp_hdr {
45 	u8	prefix;
46 	__be16	dlen;
47 	u8	cs;
48 } __packed;
49 
50 struct btmtkuart_data {
51 	unsigned int flags;
52 	const char *fwname;
53 };
54 
55 struct btmtkuart_dev {
56 	struct hci_dev *hdev;
57 	struct serdev_device *serdev;
58 
59 	struct clk *clk;
60 	struct clk *osc;
61 	struct regulator *vcc;
62 	struct gpio_desc *reset;
63 	struct gpio_desc *boot;
64 	struct pinctrl *pinctrl;
65 	struct pinctrl_state *pins_runtime;
66 	struct pinctrl_state *pins_boot;
67 	speed_t	desired_speed;
68 	speed_t	curr_speed;
69 
70 	struct work_struct tx_work;
71 	unsigned long tx_state;
72 	struct sk_buff_head txq;
73 
74 	struct sk_buff *rx_skb;
75 	struct sk_buff *evt_skb;
76 
77 	u8	stp_pad[6];
78 	u8	stp_cursor;
79 	u16	stp_dlen;
80 
81 	const struct btmtkuart_data *data;
82 };
83 
84 #define btmtkuart_is_standalone(bdev)	\
85 	((bdev)->data->flags & BTMTKUART_FLAG_STANDALONE_HW)
86 #define btmtkuart_is_builtin_soc(bdev)	\
87 	!((bdev)->data->flags & BTMTKUART_FLAG_STANDALONE_HW)
88 
mtk_hci_wmt_sync(struct hci_dev * hdev,struct btmtk_hci_wmt_params * wmt_params)89 static int mtk_hci_wmt_sync(struct hci_dev *hdev,
90 			    struct btmtk_hci_wmt_params *wmt_params)
91 {
92 	struct btmtkuart_dev *bdev = hci_get_drvdata(hdev);
93 	struct btmtk_hci_wmt_evt_funcc *wmt_evt_funcc;
94 	u32 hlen, status = BTMTK_WMT_INVALID;
95 	struct btmtk_hci_wmt_evt *wmt_evt;
96 	struct btmtk_hci_wmt_cmd *wc;
97 	struct btmtk_wmt_hdr *hdr;
98 	int err;
99 
100 	/* Send the WMT command and wait until the WMT event returns */
101 	hlen = sizeof(*hdr) + wmt_params->dlen;
102 	if (hlen > 255) {
103 		err = -EINVAL;
104 		goto err_free_skb;
105 	}
106 
107 	wc = kzalloc(hlen, GFP_KERNEL);
108 	if (!wc) {
109 		err = -ENOMEM;
110 		goto err_free_skb;
111 	}
112 
113 	hdr = &wc->hdr;
114 	hdr->dir = 1;
115 	hdr->op = wmt_params->op;
116 	hdr->dlen = cpu_to_le16(wmt_params->dlen + 1);
117 	hdr->flag = wmt_params->flag;
118 	memcpy(wc->data, wmt_params->data, wmt_params->dlen);
119 
120 	set_bit(BTMTKUART_TX_WAIT_VND_EVT, &bdev->tx_state);
121 
122 	err = __hci_cmd_send(hdev, 0xfc6f, hlen, wc);
123 	if (err < 0) {
124 		clear_bit(BTMTKUART_TX_WAIT_VND_EVT, &bdev->tx_state);
125 		goto err_free_wc;
126 	}
127 
128 	/* The vendor specific WMT commands are all answered by a vendor
129 	 * specific event and will not have the Command Status or Command
130 	 * Complete as with usual HCI command flow control.
131 	 *
132 	 * After sending the command, wait for BTMTKUART_TX_WAIT_VND_EVT
133 	 * state to be cleared. The driver specific event receive routine
134 	 * will clear that state and with that indicate completion of the
135 	 * WMT command.
136 	 */
137 	err = wait_on_bit_timeout(&bdev->tx_state, BTMTKUART_TX_WAIT_VND_EVT,
138 				  TASK_INTERRUPTIBLE, HCI_INIT_TIMEOUT);
139 	if (err == -EINTR) {
140 		bt_dev_err(hdev, "Execution of wmt command interrupted");
141 		clear_bit(BTMTKUART_TX_WAIT_VND_EVT, &bdev->tx_state);
142 		goto err_free_wc;
143 	}
144 
145 	if (err) {
146 		bt_dev_err(hdev, "Execution of wmt command timed out");
147 		clear_bit(BTMTKUART_TX_WAIT_VND_EVT, &bdev->tx_state);
148 		err = -ETIMEDOUT;
149 		goto err_free_wc;
150 	}
151 
152 	/* Parse and handle the return WMT event */
153 	wmt_evt = (struct btmtk_hci_wmt_evt *)bdev->evt_skb->data;
154 	if (wmt_evt->whdr.op != hdr->op) {
155 		bt_dev_err(hdev, "Wrong op received %d expected %d",
156 			   wmt_evt->whdr.op, hdr->op);
157 		err = -EIO;
158 		goto err_free_wc;
159 	}
160 
161 	switch (wmt_evt->whdr.op) {
162 	case BTMTK_WMT_SEMAPHORE:
163 		if (wmt_evt->whdr.flag == 2)
164 			status = BTMTK_WMT_PATCH_UNDONE;
165 		else
166 			status = BTMTK_WMT_PATCH_DONE;
167 		break;
168 	case BTMTK_WMT_FUNC_CTRL:
169 		wmt_evt_funcc = (struct btmtk_hci_wmt_evt_funcc *)wmt_evt;
170 		if (be16_to_cpu(wmt_evt_funcc->status) == 0x404)
171 			status = BTMTK_WMT_ON_DONE;
172 		else if (be16_to_cpu(wmt_evt_funcc->status) == 0x420)
173 			status = BTMTK_WMT_ON_PROGRESS;
174 		else
175 			status = BTMTK_WMT_ON_UNDONE;
176 		break;
177 	}
178 
179 	if (wmt_params->status)
180 		*wmt_params->status = status;
181 
182 err_free_wc:
183 	kfree(wc);
184 err_free_skb:
185 	kfree_skb(bdev->evt_skb);
186 	bdev->evt_skb = NULL;
187 
188 	return err;
189 }
190 
btmtkuart_recv_event(struct hci_dev * hdev,struct sk_buff * skb)191 static int btmtkuart_recv_event(struct hci_dev *hdev, struct sk_buff *skb)
192 {
193 	struct btmtkuart_dev *bdev = hci_get_drvdata(hdev);
194 	struct hci_event_hdr *hdr = (void *)skb->data;
195 	int err;
196 
197 	/* When someone waits for the WMT event, the skb is being cloned
198 	 * and being processed the events from there then.
199 	 */
200 	if (test_bit(BTMTKUART_TX_WAIT_VND_EVT, &bdev->tx_state)) {
201 		bdev->evt_skb = skb_clone(skb, GFP_KERNEL);
202 		if (!bdev->evt_skb) {
203 			err = -ENOMEM;
204 			goto err_out;
205 		}
206 	}
207 
208 	err = hci_recv_frame(hdev, skb);
209 	if (err < 0)
210 		goto err_free_skb;
211 
212 	if (hdr->evt == HCI_EV_WMT) {
213 		if (test_and_clear_bit(BTMTKUART_TX_WAIT_VND_EVT,
214 				       &bdev->tx_state)) {
215 			/* Barrier to sync with other CPUs */
216 			smp_mb__after_atomic();
217 			wake_up_bit(&bdev->tx_state, BTMTKUART_TX_WAIT_VND_EVT);
218 		}
219 	}
220 
221 	return 0;
222 
223 err_free_skb:
224 	kfree_skb(bdev->evt_skb);
225 	bdev->evt_skb = NULL;
226 
227 err_out:
228 	return err;
229 }
230 
231 static const struct h4_recv_pkt mtk_recv_pkts[] = {
232 	{ H4_RECV_ACL,      .recv = hci_recv_frame },
233 	{ H4_RECV_SCO,      .recv = hci_recv_frame },
234 	{ H4_RECV_EVENT,    .recv = btmtkuart_recv_event },
235 };
236 
btmtkuart_tx_work(struct work_struct * work)237 static void btmtkuart_tx_work(struct work_struct *work)
238 {
239 	struct btmtkuart_dev *bdev = container_of(work, struct btmtkuart_dev,
240 						   tx_work);
241 	struct serdev_device *serdev = bdev->serdev;
242 	struct hci_dev *hdev = bdev->hdev;
243 
244 	while (1) {
245 		clear_bit(BTMTKUART_TX_STATE_WAKEUP, &bdev->tx_state);
246 
247 		while (1) {
248 			struct sk_buff *skb = skb_dequeue(&bdev->txq);
249 			int len;
250 
251 			if (!skb)
252 				break;
253 
254 			len = serdev_device_write_buf(serdev, skb->data,
255 						      skb->len);
256 			hdev->stat.byte_tx += len;
257 
258 			skb_pull(skb, len);
259 			if (skb->len > 0) {
260 				skb_queue_head(&bdev->txq, skb);
261 				break;
262 			}
263 
264 			switch (hci_skb_pkt_type(skb)) {
265 			case HCI_COMMAND_PKT:
266 				hdev->stat.cmd_tx++;
267 				break;
268 			case HCI_ACLDATA_PKT:
269 				hdev->stat.acl_tx++;
270 				break;
271 			case HCI_SCODATA_PKT:
272 				hdev->stat.sco_tx++;
273 				break;
274 			}
275 
276 			kfree_skb(skb);
277 		}
278 
279 		if (!test_bit(BTMTKUART_TX_STATE_WAKEUP, &bdev->tx_state))
280 			break;
281 	}
282 
283 	clear_bit(BTMTKUART_TX_STATE_ACTIVE, &bdev->tx_state);
284 }
285 
btmtkuart_tx_wakeup(struct btmtkuart_dev * bdev)286 static void btmtkuart_tx_wakeup(struct btmtkuart_dev *bdev)
287 {
288 	if (test_and_set_bit(BTMTKUART_TX_STATE_ACTIVE, &bdev->tx_state))
289 		set_bit(BTMTKUART_TX_STATE_WAKEUP, &bdev->tx_state);
290 
291 	schedule_work(&bdev->tx_work);
292 }
293 
294 static const unsigned char *
mtk_stp_split(struct btmtkuart_dev * bdev,const unsigned char * data,int count,int * sz_h4)295 mtk_stp_split(struct btmtkuart_dev *bdev, const unsigned char *data, int count,
296 	      int *sz_h4)
297 {
298 	struct mtk_stp_hdr *shdr;
299 
300 	/* The cursor is reset when all the data of STP is consumed out */
301 	if (!bdev->stp_dlen && bdev->stp_cursor >= 6)
302 		bdev->stp_cursor = 0;
303 
304 	/* Filling pad until all STP info is obtained */
305 	while (bdev->stp_cursor < 6 && count > 0) {
306 		bdev->stp_pad[bdev->stp_cursor] = *data;
307 		bdev->stp_cursor++;
308 		data++;
309 		count--;
310 	}
311 
312 	/* Retrieve STP info and have a sanity check */
313 	if (!bdev->stp_dlen && bdev->stp_cursor >= 6) {
314 		shdr = (struct mtk_stp_hdr *)&bdev->stp_pad[2];
315 		bdev->stp_dlen = be16_to_cpu(shdr->dlen) & 0x0fff;
316 
317 		/* Resync STP when unexpected data is being read */
318 		if (shdr->prefix != 0x80 || bdev->stp_dlen > 2048) {
319 			bt_dev_err(bdev->hdev, "stp format unexpect (%d, %d)",
320 				   shdr->prefix, bdev->stp_dlen);
321 			bdev->stp_cursor = 2;
322 			bdev->stp_dlen = 0;
323 		}
324 	}
325 
326 	/* Directly quit when there's no data found for H4 can process */
327 	if (count <= 0)
328 		return NULL;
329 
330 	/* Tranlate to how much the size of data H4 can handle so far */
331 	*sz_h4 = min_t(int, count, bdev->stp_dlen);
332 
333 	/* Update the remaining size of STP packet */
334 	bdev->stp_dlen -= *sz_h4;
335 
336 	/* Data points to STP payload which can be handled by H4 */
337 	return data;
338 }
339 
btmtkuart_recv(struct hci_dev * hdev,const u8 * data,size_t count)340 static void btmtkuart_recv(struct hci_dev *hdev, const u8 *data, size_t count)
341 {
342 	struct btmtkuart_dev *bdev = hci_get_drvdata(hdev);
343 	const unsigned char *p_left = data, *p_h4;
344 	int sz_left = count, sz_h4, adv;
345 	int err;
346 
347 	while (sz_left > 0) {
348 		/*  The serial data received from MT7622 BT controller is
349 		 *  at all time padded around with the STP header and tailer.
350 		 *
351 		 *  A full STP packet is looking like
352 		 *   -----------------------------------
353 		 *  | STP header  |  H:4   | STP tailer |
354 		 *   -----------------------------------
355 		 *  but it doesn't guarantee to contain a full H:4 packet which
356 		 *  means that it's possible for multiple STP packets forms a
357 		 *  full H:4 packet that means extra STP header + length doesn't
358 		 *  indicate a full H:4 frame, things can fragment. Whose length
359 		 *  recorded in STP header just shows up the most length the
360 		 *  H:4 engine can handle currently.
361 		 */
362 
363 		p_h4 = mtk_stp_split(bdev, p_left, sz_left, &sz_h4);
364 		if (!p_h4)
365 			break;
366 
367 		adv = p_h4 - p_left;
368 		sz_left -= adv;
369 		p_left += adv;
370 
371 		bdev->rx_skb = h4_recv_buf(bdev->hdev, bdev->rx_skb, p_h4,
372 					   sz_h4, mtk_recv_pkts,
373 					   ARRAY_SIZE(mtk_recv_pkts));
374 		if (IS_ERR(bdev->rx_skb)) {
375 			err = PTR_ERR(bdev->rx_skb);
376 			bt_dev_err(bdev->hdev,
377 				   "Frame reassembly failed (%d)", err);
378 			bdev->rx_skb = NULL;
379 			return;
380 		}
381 
382 		sz_left -= sz_h4;
383 		p_left += sz_h4;
384 	}
385 }
386 
btmtkuart_receive_buf(struct serdev_device * serdev,const u8 * data,size_t count)387 static size_t btmtkuart_receive_buf(struct serdev_device *serdev,
388 				    const u8 *data, size_t count)
389 {
390 	struct btmtkuart_dev *bdev = serdev_device_get_drvdata(serdev);
391 
392 	btmtkuart_recv(bdev->hdev, data, count);
393 
394 	bdev->hdev->stat.byte_rx += count;
395 
396 	return count;
397 }
398 
btmtkuart_write_wakeup(struct serdev_device * serdev)399 static void btmtkuart_write_wakeup(struct serdev_device *serdev)
400 {
401 	struct btmtkuart_dev *bdev = serdev_device_get_drvdata(serdev);
402 
403 	btmtkuart_tx_wakeup(bdev);
404 }
405 
406 static const struct serdev_device_ops btmtkuart_client_ops = {
407 	.receive_buf = btmtkuart_receive_buf,
408 	.write_wakeup = btmtkuart_write_wakeup,
409 };
410 
btmtkuart_open(struct hci_dev * hdev)411 static int btmtkuart_open(struct hci_dev *hdev)
412 {
413 	struct btmtkuart_dev *bdev = hci_get_drvdata(hdev);
414 	struct device *dev;
415 	int err;
416 
417 	err = serdev_device_open(bdev->serdev);
418 	if (err) {
419 		bt_dev_err(hdev, "Unable to open UART device %s",
420 			   dev_name(&bdev->serdev->dev));
421 		goto err_open;
422 	}
423 
424 	if (btmtkuart_is_standalone(bdev)) {
425 		if (bdev->curr_speed != bdev->desired_speed)
426 			err = serdev_device_set_baudrate(bdev->serdev,
427 							 115200);
428 		else
429 			err = serdev_device_set_baudrate(bdev->serdev,
430 							 bdev->desired_speed);
431 
432 		if (err < 0) {
433 			bt_dev_err(hdev, "Unable to set baudrate UART device %s",
434 				   dev_name(&bdev->serdev->dev));
435 			goto  err_serdev_close;
436 		}
437 
438 		serdev_device_set_flow_control(bdev->serdev, false);
439 	}
440 
441 	bdev->stp_cursor = 2;
442 	bdev->stp_dlen = 0;
443 
444 	dev = &bdev->serdev->dev;
445 
446 	/* Enable the power domain and clock the device requires */
447 	pm_runtime_enable(dev);
448 	err = pm_runtime_resume_and_get(dev);
449 	if (err < 0)
450 		goto err_disable_rpm;
451 
452 	err = clk_prepare_enable(bdev->clk);
453 	if (err < 0)
454 		goto err_put_rpm;
455 
456 	return 0;
457 
458 err_put_rpm:
459 	pm_runtime_put_sync(dev);
460 err_disable_rpm:
461 	pm_runtime_disable(dev);
462 err_serdev_close:
463 	serdev_device_close(bdev->serdev);
464 err_open:
465 	return err;
466 }
467 
btmtkuart_close(struct hci_dev * hdev)468 static int btmtkuart_close(struct hci_dev *hdev)
469 {
470 	struct btmtkuart_dev *bdev = hci_get_drvdata(hdev);
471 	struct device *dev = &bdev->serdev->dev;
472 
473 	/* Shutdown the clock and power domain the device requires */
474 	clk_disable_unprepare(bdev->clk);
475 	pm_runtime_put_sync(dev);
476 	pm_runtime_disable(dev);
477 
478 	serdev_device_close(bdev->serdev);
479 
480 	return 0;
481 }
482 
btmtkuart_flush(struct hci_dev * hdev)483 static int btmtkuart_flush(struct hci_dev *hdev)
484 {
485 	struct btmtkuart_dev *bdev = hci_get_drvdata(hdev);
486 
487 	/* Flush any pending characters */
488 	serdev_device_write_flush(bdev->serdev);
489 	skb_queue_purge(&bdev->txq);
490 
491 	cancel_work_sync(&bdev->tx_work);
492 
493 	kfree_skb(bdev->rx_skb);
494 	bdev->rx_skb = NULL;
495 
496 	bdev->stp_cursor = 2;
497 	bdev->stp_dlen = 0;
498 
499 	return 0;
500 }
501 
btmtkuart_func_query(struct hci_dev * hdev)502 static int btmtkuart_func_query(struct hci_dev *hdev)
503 {
504 	struct btmtk_hci_wmt_params wmt_params;
505 	int status, err;
506 	u8 param = 0;
507 
508 	/* Query whether the function is enabled */
509 	wmt_params.op = BTMTK_WMT_FUNC_CTRL;
510 	wmt_params.flag = 4;
511 	wmt_params.dlen = sizeof(param);
512 	wmt_params.data = &param;
513 	wmt_params.status = &status;
514 
515 	err = mtk_hci_wmt_sync(hdev, &wmt_params);
516 	if (err < 0) {
517 		bt_dev_err(hdev, "Failed to query function status (%d)", err);
518 		return err;
519 	}
520 
521 	return status;
522 }
523 
btmtkuart_change_baudrate(struct hci_dev * hdev)524 static int btmtkuart_change_baudrate(struct hci_dev *hdev)
525 {
526 	struct btmtkuart_dev *bdev = hci_get_drvdata(hdev);
527 	struct btmtk_hci_wmt_params wmt_params;
528 	__le32 baudrate;
529 	u8 param;
530 	int err;
531 
532 	/* Indicate the device to enter the probe state the host is
533 	 * ready to change a new baudrate.
534 	 */
535 	baudrate = cpu_to_le32(bdev->desired_speed);
536 	wmt_params.op = BTMTK_WMT_HIF;
537 	wmt_params.flag = 1;
538 	wmt_params.dlen = 4;
539 	wmt_params.data = &baudrate;
540 	wmt_params.status = NULL;
541 
542 	err = mtk_hci_wmt_sync(hdev, &wmt_params);
543 	if (err < 0) {
544 		bt_dev_err(hdev, "Failed to device baudrate (%d)", err);
545 		return err;
546 	}
547 
548 	err = serdev_device_set_baudrate(bdev->serdev,
549 					 bdev->desired_speed);
550 	if (err < 0) {
551 		bt_dev_err(hdev, "Failed to set up host baudrate (%d)",
552 			   err);
553 		return err;
554 	}
555 
556 	serdev_device_set_flow_control(bdev->serdev, false);
557 
558 	/* Send a dummy byte 0xff to activate the new baudrate */
559 	param = 0xff;
560 	err = serdev_device_write_buf(bdev->serdev, &param, sizeof(param));
561 	if (err < 0 || err < sizeof(param))
562 		return err;
563 
564 	serdev_device_wait_until_sent(bdev->serdev, 0);
565 
566 	/* Wait some time for the device changing baudrate done */
567 	usleep_range(20000, 22000);
568 
569 	/* Test the new baudrate */
570 	wmt_params.op = BTMTK_WMT_TEST;
571 	wmt_params.flag = 7;
572 	wmt_params.dlen = 0;
573 	wmt_params.data = NULL;
574 	wmt_params.status = NULL;
575 
576 	err = mtk_hci_wmt_sync(hdev, &wmt_params);
577 	if (err < 0) {
578 		bt_dev_err(hdev, "Failed to test new baudrate (%d)",
579 			   err);
580 		return err;
581 	}
582 
583 	bdev->curr_speed = bdev->desired_speed;
584 
585 	return 0;
586 }
587 
btmtkuart_setup(struct hci_dev * hdev)588 static int btmtkuart_setup(struct hci_dev *hdev)
589 {
590 	struct btmtkuart_dev *bdev = hci_get_drvdata(hdev);
591 	struct btmtk_hci_wmt_params wmt_params;
592 	ktime_t calltime, delta, rettime;
593 	struct btmtk_tci_sleep tci_sleep;
594 	unsigned long long duration;
595 	struct sk_buff *skb;
596 	int err, status;
597 	u8 param = 0x1;
598 
599 	calltime = ktime_get();
600 
601 	/* Wakeup MCUSYS is required for certain devices before we start to
602 	 * do any setups.
603 	 */
604 	if (test_bit(BTMTKUART_REQUIRED_WAKEUP, &bdev->tx_state)) {
605 		wmt_params.op = BTMTK_WMT_WAKEUP;
606 		wmt_params.flag = 3;
607 		wmt_params.dlen = 0;
608 		wmt_params.data = NULL;
609 		wmt_params.status = NULL;
610 
611 		err = mtk_hci_wmt_sync(hdev, &wmt_params);
612 		if (err < 0) {
613 			bt_dev_err(hdev, "Failed to wakeup the chip (%d)", err);
614 			return err;
615 		}
616 
617 		clear_bit(BTMTKUART_REQUIRED_WAKEUP, &bdev->tx_state);
618 	}
619 
620 	if (btmtkuart_is_standalone(bdev))
621 		btmtkuart_change_baudrate(hdev);
622 
623 	/* Query whether the firmware is already download */
624 	wmt_params.op = BTMTK_WMT_SEMAPHORE;
625 	wmt_params.flag = 1;
626 	wmt_params.dlen = 0;
627 	wmt_params.data = NULL;
628 	wmt_params.status = &status;
629 
630 	err = mtk_hci_wmt_sync(hdev, &wmt_params);
631 	if (err < 0) {
632 		bt_dev_err(hdev, "Failed to query firmware status (%d)", err);
633 		return err;
634 	}
635 
636 	if (status == BTMTK_WMT_PATCH_DONE) {
637 		bt_dev_info(hdev, "Firmware already downloaded");
638 		goto ignore_setup_fw;
639 	}
640 
641 	/* Setup a firmware which the device definitely requires */
642 	err = btmtk_setup_firmware(hdev, bdev->data->fwname, mtk_hci_wmt_sync);
643 	if (err < 0)
644 		return err;
645 
646 ignore_setup_fw:
647 	/* Query whether the device is already enabled */
648 	err = readx_poll_timeout(btmtkuart_func_query, hdev, status,
649 				 status < 0 || status != BTMTK_WMT_ON_PROGRESS,
650 				 2000, 5000000);
651 	/* -ETIMEDOUT happens */
652 	if (err < 0)
653 		return err;
654 
655 	/* The other errors happen in btusb_mtk_func_query */
656 	if (status < 0)
657 		return status;
658 
659 	if (status == BTMTK_WMT_ON_DONE) {
660 		bt_dev_info(hdev, "function already on");
661 		goto ignore_func_on;
662 	}
663 
664 	/* Enable Bluetooth protocol */
665 	wmt_params.op = BTMTK_WMT_FUNC_CTRL;
666 	wmt_params.flag = 0;
667 	wmt_params.dlen = sizeof(param);
668 	wmt_params.data = &param;
669 	wmt_params.status = NULL;
670 
671 	err = mtk_hci_wmt_sync(hdev, &wmt_params);
672 	if (err < 0) {
673 		bt_dev_err(hdev, "Failed to send wmt func ctrl (%d)", err);
674 		return err;
675 	}
676 
677 ignore_func_on:
678 	/* Apply the low power environment setup */
679 	tci_sleep.mode = 0x5;
680 	tci_sleep.duration = cpu_to_le16(0x640);
681 	tci_sleep.host_duration = cpu_to_le16(0x640);
682 	tci_sleep.host_wakeup_pin = 0;
683 	tci_sleep.time_compensation = 0;
684 
685 	skb = __hci_cmd_sync(hdev, 0xfc7a, sizeof(tci_sleep), &tci_sleep,
686 			     HCI_INIT_TIMEOUT);
687 	if (IS_ERR(skb)) {
688 		err = PTR_ERR(skb);
689 		bt_dev_err(hdev, "Failed to apply low power setting (%d)", err);
690 		return err;
691 	}
692 	kfree_skb(skb);
693 
694 	rettime = ktime_get();
695 	delta = ktime_sub(rettime, calltime);
696 	duration = (unsigned long long)ktime_to_ns(delta) >> 10;
697 
698 	bt_dev_info(hdev, "Device setup in %llu usecs", duration);
699 
700 	return 0;
701 }
702 
btmtkuart_shutdown(struct hci_dev * hdev)703 static int btmtkuart_shutdown(struct hci_dev *hdev)
704 {
705 	struct btmtk_hci_wmt_params wmt_params;
706 	u8 param = 0x0;
707 	int err;
708 
709 	/* Disable the device */
710 	wmt_params.op = BTMTK_WMT_FUNC_CTRL;
711 	wmt_params.flag = 0;
712 	wmt_params.dlen = sizeof(param);
713 	wmt_params.data = &param;
714 	wmt_params.status = NULL;
715 
716 	err = mtk_hci_wmt_sync(hdev, &wmt_params);
717 	if (err < 0) {
718 		bt_dev_err(hdev, "Failed to send wmt func ctrl (%d)", err);
719 		return err;
720 	}
721 
722 	return 0;
723 }
724 
btmtkuart_send_frame(struct hci_dev * hdev,struct sk_buff * skb)725 static int btmtkuart_send_frame(struct hci_dev *hdev, struct sk_buff *skb)
726 {
727 	struct btmtkuart_dev *bdev = hci_get_drvdata(hdev);
728 	struct mtk_stp_hdr *shdr;
729 	int err, dlen, type = 0;
730 
731 	/* Prepend skb with frame type */
732 	memcpy(skb_push(skb, 1), &hci_skb_pkt_type(skb), 1);
733 
734 	/* Make sure that there is enough rooms for STP header and trailer */
735 	if (unlikely(skb_headroom(skb) < sizeof(*shdr)) ||
736 	    (skb_tailroom(skb) < MTK_STP_TLR_SIZE)) {
737 		err = pskb_expand_head(skb, sizeof(*shdr), MTK_STP_TLR_SIZE,
738 				       GFP_ATOMIC);
739 		if (err < 0)
740 			return err;
741 	}
742 
743 	/* Add the STP header */
744 	dlen = skb->len;
745 	shdr = skb_push(skb, sizeof(*shdr));
746 	shdr->prefix = 0x80;
747 	shdr->dlen = cpu_to_be16((dlen & 0x0fff) | (type << 12));
748 	shdr->cs = 0;		/* MT7622 doesn't care about checksum value */
749 
750 	/* Add the STP trailer */
751 	skb_put_zero(skb, MTK_STP_TLR_SIZE);
752 
753 	skb_queue_tail(&bdev->txq, skb);
754 
755 	btmtkuart_tx_wakeup(bdev);
756 	return 0;
757 }
758 
btmtkuart_parse_dt(struct serdev_device * serdev)759 static int btmtkuart_parse_dt(struct serdev_device *serdev)
760 {
761 	struct btmtkuart_dev *bdev = serdev_device_get_drvdata(serdev);
762 	struct device_node *node = serdev->dev.of_node;
763 	u32 speed = 921600;
764 	int err;
765 
766 	if (btmtkuart_is_standalone(bdev)) {
767 		of_property_read_u32(node, "current-speed", &speed);
768 
769 		bdev->desired_speed = speed;
770 
771 		bdev->vcc = devm_regulator_get(&serdev->dev, "vcc");
772 		if (IS_ERR(bdev->vcc)) {
773 			err = PTR_ERR(bdev->vcc);
774 			return err;
775 		}
776 
777 		bdev->osc = devm_clk_get_optional(&serdev->dev, "osc");
778 		if (IS_ERR(bdev->osc)) {
779 			err = PTR_ERR(bdev->osc);
780 			return err;
781 		}
782 
783 		bdev->boot = devm_gpiod_get_optional(&serdev->dev, "boot",
784 						     GPIOD_OUT_LOW);
785 		if (IS_ERR(bdev->boot)) {
786 			err = PTR_ERR(bdev->boot);
787 			return err;
788 		}
789 
790 		bdev->pinctrl = devm_pinctrl_get(&serdev->dev);
791 		if (IS_ERR(bdev->pinctrl)) {
792 			err = PTR_ERR(bdev->pinctrl);
793 			return err;
794 		}
795 
796 		bdev->pins_boot = pinctrl_lookup_state(bdev->pinctrl,
797 						       "default");
798 		if (IS_ERR(bdev->pins_boot) && !bdev->boot) {
799 			err = PTR_ERR(bdev->pins_boot);
800 			dev_err(&serdev->dev,
801 				"Should assign RXD to LOW at boot stage\n");
802 			return err;
803 		}
804 
805 		bdev->pins_runtime = pinctrl_lookup_state(bdev->pinctrl,
806 							  "runtime");
807 		if (IS_ERR(bdev->pins_runtime)) {
808 			err = PTR_ERR(bdev->pins_runtime);
809 			return err;
810 		}
811 
812 		bdev->reset = devm_gpiod_get_optional(&serdev->dev, "reset",
813 						      GPIOD_OUT_LOW);
814 		if (IS_ERR(bdev->reset)) {
815 			err = PTR_ERR(bdev->reset);
816 			return err;
817 		}
818 	} else if (btmtkuart_is_builtin_soc(bdev)) {
819 		bdev->clk = devm_clk_get(&serdev->dev, "ref");
820 		if (IS_ERR(bdev->clk))
821 			return PTR_ERR(bdev->clk);
822 	}
823 
824 	return 0;
825 }
826 
btmtkuart_probe(struct serdev_device * serdev)827 static int btmtkuart_probe(struct serdev_device *serdev)
828 {
829 	struct btmtkuart_dev *bdev;
830 	struct hci_dev *hdev;
831 	int err;
832 
833 	bdev = devm_kzalloc(&serdev->dev, sizeof(*bdev), GFP_KERNEL);
834 	if (!bdev)
835 		return -ENOMEM;
836 
837 	bdev->data = of_device_get_match_data(&serdev->dev);
838 	if (!bdev->data)
839 		return -ENODEV;
840 
841 	bdev->serdev = serdev;
842 	serdev_device_set_drvdata(serdev, bdev);
843 
844 	serdev_device_set_client_ops(serdev, &btmtkuart_client_ops);
845 
846 	err = btmtkuart_parse_dt(serdev);
847 	if (err < 0)
848 		return err;
849 
850 	INIT_WORK(&bdev->tx_work, btmtkuart_tx_work);
851 	skb_queue_head_init(&bdev->txq);
852 
853 	/* Initialize and register HCI device */
854 	hdev = hci_alloc_dev();
855 	if (!hdev) {
856 		dev_err(&serdev->dev, "Can't allocate HCI device\n");
857 		return -ENOMEM;
858 	}
859 
860 	bdev->hdev = hdev;
861 
862 	hdev->bus = HCI_UART;
863 	hci_set_drvdata(hdev, bdev);
864 
865 	hdev->open     = btmtkuart_open;
866 	hdev->close    = btmtkuart_close;
867 	hdev->flush    = btmtkuart_flush;
868 	hdev->setup    = btmtkuart_setup;
869 	hdev->shutdown = btmtkuart_shutdown;
870 	hdev->send     = btmtkuart_send_frame;
871 	hdev->set_bdaddr = btmtk_set_bdaddr;
872 	SET_HCIDEV_DEV(hdev, &serdev->dev);
873 
874 	hdev->manufacturer = 70;
875 	set_bit(HCI_QUIRK_NON_PERSISTENT_SETUP, &hdev->quirks);
876 
877 	if (btmtkuart_is_standalone(bdev)) {
878 		err = clk_prepare_enable(bdev->osc);
879 		if (err < 0)
880 			goto err_hci_free_dev;
881 
882 		if (bdev->boot) {
883 			gpiod_set_value_cansleep(bdev->boot, 1);
884 		} else {
885 			/* Switch to the specific pin state for the booting
886 			 * requires.
887 			 */
888 			pinctrl_select_state(bdev->pinctrl, bdev->pins_boot);
889 		}
890 
891 		/* Power on */
892 		err = regulator_enable(bdev->vcc);
893 		if (err < 0)
894 			goto err_clk_disable_unprepare;
895 
896 		/* Reset if the reset-gpios is available otherwise the board
897 		 * -level design should be guaranteed.
898 		 */
899 		if (bdev->reset) {
900 			gpiod_set_value_cansleep(bdev->reset, 1);
901 			usleep_range(1000, 2000);
902 			gpiod_set_value_cansleep(bdev->reset, 0);
903 		}
904 
905 		/* Wait some time until device got ready and switch to the pin
906 		 * mode the device requires for UART transfers.
907 		 */
908 		msleep(50);
909 
910 		if (bdev->boot)
911 			devm_gpiod_put(&serdev->dev, bdev->boot);
912 
913 		pinctrl_select_state(bdev->pinctrl, bdev->pins_runtime);
914 
915 		/* A standalone device doesn't depends on power domain on SoC,
916 		 * so mark it as no callbacks.
917 		 */
918 		pm_runtime_no_callbacks(&serdev->dev);
919 
920 		set_bit(BTMTKUART_REQUIRED_WAKEUP, &bdev->tx_state);
921 	}
922 
923 	err = hci_register_dev(hdev);
924 	if (err < 0) {
925 		dev_err(&serdev->dev, "Can't register HCI device\n");
926 		goto err_regulator_disable;
927 	}
928 
929 	return 0;
930 
931 err_regulator_disable:
932 	if (btmtkuart_is_standalone(bdev))
933 		regulator_disable(bdev->vcc);
934 err_clk_disable_unprepare:
935 	if (btmtkuart_is_standalone(bdev))
936 		clk_disable_unprepare(bdev->osc);
937 err_hci_free_dev:
938 	hci_free_dev(hdev);
939 
940 	return err;
941 }
942 
btmtkuart_remove(struct serdev_device * serdev)943 static void btmtkuart_remove(struct serdev_device *serdev)
944 {
945 	struct btmtkuart_dev *bdev = serdev_device_get_drvdata(serdev);
946 	struct hci_dev *hdev = bdev->hdev;
947 
948 	if (btmtkuart_is_standalone(bdev)) {
949 		regulator_disable(bdev->vcc);
950 		clk_disable_unprepare(bdev->osc);
951 	}
952 
953 	hci_unregister_dev(hdev);
954 	hci_free_dev(hdev);
955 }
956 
957 static const struct btmtkuart_data mt7622_data __maybe_unused = {
958 	.fwname = FIRMWARE_MT7622,
959 };
960 
961 static const struct btmtkuart_data mt7663_data __maybe_unused = {
962 	.flags = BTMTKUART_FLAG_STANDALONE_HW,
963 	.fwname = FIRMWARE_MT7663,
964 };
965 
966 static const struct btmtkuart_data mt7668_data __maybe_unused = {
967 	.flags = BTMTKUART_FLAG_STANDALONE_HW,
968 	.fwname = FIRMWARE_MT7668,
969 };
970 
971 #ifdef CONFIG_OF
972 static const struct of_device_id mtk_of_match_table[] = {
973 	{ .compatible = "mediatek,mt7622-bluetooth", .data = &mt7622_data},
974 	{ .compatible = "mediatek,mt7663u-bluetooth", .data = &mt7663_data},
975 	{ .compatible = "mediatek,mt7668u-bluetooth", .data = &mt7668_data},
976 	{ }
977 };
978 MODULE_DEVICE_TABLE(of, mtk_of_match_table);
979 #endif
980 
981 static struct serdev_device_driver btmtkuart_driver = {
982 	.probe = btmtkuart_probe,
983 	.remove = btmtkuart_remove,
984 	.driver = {
985 		.name = "btmtkuart",
986 		.of_match_table = of_match_ptr(mtk_of_match_table),
987 	},
988 };
989 
990 module_serdev_device_driver(btmtkuart_driver);
991 
992 MODULE_AUTHOR("Sean Wang <sean.wang@mediatek.com>");
993 MODULE_DESCRIPTION("MediaTek Bluetooth Serial driver ver " VERSION);
994 MODULE_VERSION(VERSION);
995 MODULE_LICENSE("GPL");
996