GNU Linux-libre 5.10.217-gnu1
[releases.git] / drivers / bluetooth / btusb.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *
4  *  Generic Bluetooth USB driver
5  *
6  *  Copyright (C) 2005-2008  Marcel Holtmann <marcel@holtmann.org>
7  */
8
9 #include <linux/dmi.h>
10 #include <linux/module.h>
11 #include <linux/usb.h>
12 #include <linux/usb/quirks.h>
13 #include <linux/firmware.h>
14 #include <linux/iopoll.h>
15 #include <linux/of_device.h>
16 #include <linux/of_irq.h>
17 #include <linux/suspend.h>
18 #include <linux/gpio/consumer.h>
19 #include <asm/unaligned.h>
20
21 #include <net/bluetooth/bluetooth.h>
22 #include <net/bluetooth/hci_core.h>
23
24 #include "btintel.h"
25 #include "btbcm.h"
26 #include "btrtl.h"
27
28 #define VERSION "0.8"
29
30 static bool disable_scofix;
31 static bool force_scofix;
32 static bool enable_autosuspend = IS_ENABLED(CONFIG_BT_HCIBTUSB_AUTOSUSPEND);
33
34 static bool reset = true;
35
36 static struct usb_driver btusb_driver;
37
38 #define BTUSB_IGNORE            0x01
39 #define BTUSB_DIGIANSWER        0x02
40 #define BTUSB_CSR               0x04
41 #define BTUSB_SNIFFER           0x08
42 #define BTUSB_BCM92035          0x10
43 #define BTUSB_BROKEN_ISOC       0x20
44 #define BTUSB_WRONG_SCO_MTU     0x40
45 #define BTUSB_ATH3012           0x80
46 #define BTUSB_INTEL             0x100
47 #define BTUSB_INTEL_BOOT        0x200
48 #define BTUSB_BCM_PATCHRAM      0x400
49 #define BTUSB_MARVELL           0x800
50 #define BTUSB_SWAVE             0x1000
51 #define BTUSB_INTEL_NEW         0x2000
52 #define BTUSB_AMP               0x4000
53 #define BTUSB_QCA_ROME          0x8000
54 #define BTUSB_BCM_APPLE         0x10000
55 #define BTUSB_REALTEK           0x20000
56 #define BTUSB_BCM2045           0x40000
57 #define BTUSB_IFNUM_2           0x80000
58 #define BTUSB_CW6622            0x100000
59 #define BTUSB_MEDIATEK          0x200000
60 #define BTUSB_WIDEBAND_SPEECH   0x400000
61 #define BTUSB_VALID_LE_STATES   0x800000
62 #define BTUSB_QCA_WCN6855       0x1000000
63
64 static const struct usb_device_id btusb_table[] = {
65         /* Generic Bluetooth USB device */
66         { USB_DEVICE_INFO(0xe0, 0x01, 0x01) },
67
68         /* Generic Bluetooth AMP device */
69         { USB_DEVICE_INFO(0xe0, 0x01, 0x04), .driver_info = BTUSB_AMP },
70
71         /* Generic Bluetooth USB interface */
72         { USB_INTERFACE_INFO(0xe0, 0x01, 0x01) },
73
74         /* Apple-specific (Broadcom) devices */
75         { USB_VENDOR_AND_INTERFACE_INFO(0x05ac, 0xff, 0x01, 0x01),
76           .driver_info = BTUSB_BCM_APPLE | BTUSB_IFNUM_2 },
77
78         /* MediaTek MT76x0E */
79         { USB_DEVICE(0x0e8d, 0x763f) },
80
81         /* Broadcom SoftSailing reporting vendor specific */
82         { USB_DEVICE(0x0a5c, 0x21e1) },
83
84         /* Apple MacBookPro 7,1 */
85         { USB_DEVICE(0x05ac, 0x8213) },
86
87         /* Apple iMac11,1 */
88         { USB_DEVICE(0x05ac, 0x8215) },
89
90         /* Apple MacBookPro6,2 */
91         { USB_DEVICE(0x05ac, 0x8218) },
92
93         /* Apple MacBookAir3,1, MacBookAir3,2 */
94         { USB_DEVICE(0x05ac, 0x821b) },
95
96         /* Apple MacBookAir4,1 */
97         { USB_DEVICE(0x05ac, 0x821f) },
98
99         /* Apple MacBookPro8,2 */
100         { USB_DEVICE(0x05ac, 0x821a) },
101
102         /* Apple MacMini5,1 */
103         { USB_DEVICE(0x05ac, 0x8281) },
104
105         /* AVM BlueFRITZ! USB v2.0 */
106         { USB_DEVICE(0x057c, 0x3800), .driver_info = BTUSB_SWAVE },
107
108         /* Bluetooth Ultraport Module from IBM */
109         { USB_DEVICE(0x04bf, 0x030a) },
110
111         /* ALPS Modules with non-standard id */
112         { USB_DEVICE(0x044e, 0x3001) },
113         { USB_DEVICE(0x044e, 0x3002) },
114
115         /* Ericsson with non-standard id */
116         { USB_DEVICE(0x0bdb, 0x1002) },
117
118         /* Canyon CN-BTU1 with HID interfaces */
119         { USB_DEVICE(0x0c10, 0x0000) },
120
121         /* Broadcom BCM20702A0 */
122         { USB_DEVICE(0x413c, 0x8197) },
123
124         /* Broadcom BCM20702B0 (Dynex/Insignia) */
125         { USB_DEVICE(0x19ff, 0x0239), .driver_info = BTUSB_BCM_PATCHRAM },
126
127         /* Broadcom BCM43142A0 (Foxconn/Lenovo) */
128         { USB_VENDOR_AND_INTERFACE_INFO(0x105b, 0xff, 0x01, 0x01),
129           .driver_info = BTUSB_BCM_PATCHRAM },
130
131         /* Broadcom BCM920703 (HTC Vive) */
132         { USB_VENDOR_AND_INTERFACE_INFO(0x0bb4, 0xff, 0x01, 0x01),
133           .driver_info = BTUSB_BCM_PATCHRAM },
134
135         /* Foxconn - Hon Hai */
136         { USB_VENDOR_AND_INTERFACE_INFO(0x0489, 0xff, 0x01, 0x01),
137           .driver_info = BTUSB_BCM_PATCHRAM },
138
139         /* Lite-On Technology - Broadcom based */
140         { USB_VENDOR_AND_INTERFACE_INFO(0x04ca, 0xff, 0x01, 0x01),
141           .driver_info = BTUSB_BCM_PATCHRAM },
142
143         /* Broadcom devices with vendor specific id */
144         { USB_VENDOR_AND_INTERFACE_INFO(0x0a5c, 0xff, 0x01, 0x01),
145           .driver_info = BTUSB_BCM_PATCHRAM },
146
147         /* ASUSTek Computer - Broadcom based */
148         { USB_VENDOR_AND_INTERFACE_INFO(0x0b05, 0xff, 0x01, 0x01),
149           .driver_info = BTUSB_BCM_PATCHRAM },
150
151         /* Belkin F8065bf - Broadcom based */
152         { USB_VENDOR_AND_INTERFACE_INFO(0x050d, 0xff, 0x01, 0x01),
153           .driver_info = BTUSB_BCM_PATCHRAM },
154
155         /* IMC Networks - Broadcom based */
156         { USB_VENDOR_AND_INTERFACE_INFO(0x13d3, 0xff, 0x01, 0x01),
157           .driver_info = BTUSB_BCM_PATCHRAM },
158
159         /* Dell Computer - Broadcom based  */
160         { USB_VENDOR_AND_INTERFACE_INFO(0x413c, 0xff, 0x01, 0x01),
161           .driver_info = BTUSB_BCM_PATCHRAM },
162
163         /* Toshiba Corp - Broadcom based */
164         { USB_VENDOR_AND_INTERFACE_INFO(0x0930, 0xff, 0x01, 0x01),
165           .driver_info = BTUSB_BCM_PATCHRAM },
166
167         /* Intel Bluetooth USB Bootloader (RAM module) */
168         { USB_DEVICE(0x8087, 0x0a5a),
169           .driver_info = BTUSB_INTEL_BOOT | BTUSB_BROKEN_ISOC },
170
171         { }     /* Terminating entry */
172 };
173
174 MODULE_DEVICE_TABLE(usb, btusb_table);
175
176 static const struct usb_device_id blacklist_table[] = {
177         /* CSR BlueCore devices */
178         { USB_DEVICE(0x0a12, 0x0001), .driver_info = BTUSB_CSR },
179
180         /* Broadcom BCM2033 without firmware */
181         { USB_DEVICE(0x0a5c, 0x2033), .driver_info = BTUSB_IGNORE },
182
183         /* Broadcom BCM2045 devices */
184         { USB_DEVICE(0x0a5c, 0x2045), .driver_info = BTUSB_BCM2045 },
185
186         /* Atheros 3011 with sflash firmware */
187         { USB_DEVICE(0x0489, 0xe027), .driver_info = BTUSB_IGNORE },
188         { USB_DEVICE(0x0489, 0xe03d), .driver_info = BTUSB_IGNORE },
189         { USB_DEVICE(0x04f2, 0xaff1), .driver_info = BTUSB_IGNORE },
190         { USB_DEVICE(0x0930, 0x0215), .driver_info = BTUSB_IGNORE },
191         { USB_DEVICE(0x0cf3, 0x3002), .driver_info = BTUSB_IGNORE },
192         { USB_DEVICE(0x0cf3, 0xe019), .driver_info = BTUSB_IGNORE },
193         { USB_DEVICE(0x13d3, 0x3304), .driver_info = BTUSB_IGNORE },
194
195         /* Atheros AR9285 Malbec with sflash firmware */
196         { USB_DEVICE(0x03f0, 0x311d), .driver_info = BTUSB_IGNORE },
197
198         /* Atheros 3012 with sflash firmware */
199         { USB_DEVICE(0x0489, 0xe04d), .driver_info = BTUSB_ATH3012 },
200         { USB_DEVICE(0x0489, 0xe04e), .driver_info = BTUSB_ATH3012 },
201         { USB_DEVICE(0x0489, 0xe056), .driver_info = BTUSB_ATH3012 },
202         { USB_DEVICE(0x0489, 0xe057), .driver_info = BTUSB_ATH3012 },
203         { USB_DEVICE(0x0489, 0xe05f), .driver_info = BTUSB_ATH3012 },
204         { USB_DEVICE(0x0489, 0xe076), .driver_info = BTUSB_ATH3012 },
205         { USB_DEVICE(0x0489, 0xe078), .driver_info = BTUSB_ATH3012 },
206         { USB_DEVICE(0x0489, 0xe095), .driver_info = BTUSB_ATH3012 },
207         { USB_DEVICE(0x04c5, 0x1330), .driver_info = BTUSB_ATH3012 },
208         { USB_DEVICE(0x04ca, 0x3004), .driver_info = BTUSB_ATH3012 },
209         { USB_DEVICE(0x04ca, 0x3005), .driver_info = BTUSB_ATH3012 },
210         { USB_DEVICE(0x04ca, 0x3006), .driver_info = BTUSB_ATH3012 },
211         { USB_DEVICE(0x04ca, 0x3007), .driver_info = BTUSB_ATH3012 },
212         { USB_DEVICE(0x04ca, 0x3008), .driver_info = BTUSB_ATH3012 },
213         { USB_DEVICE(0x04ca, 0x300b), .driver_info = BTUSB_ATH3012 },
214         { USB_DEVICE(0x04ca, 0x300d), .driver_info = BTUSB_ATH3012 },
215         { USB_DEVICE(0x04ca, 0x300f), .driver_info = BTUSB_ATH3012 },
216         { USB_DEVICE(0x04ca, 0x3010), .driver_info = BTUSB_ATH3012 },
217         { USB_DEVICE(0x04ca, 0x3014), .driver_info = BTUSB_ATH3012 },
218         { USB_DEVICE(0x04ca, 0x3018), .driver_info = BTUSB_ATH3012 },
219         { USB_DEVICE(0x0930, 0x0219), .driver_info = BTUSB_ATH3012 },
220         { USB_DEVICE(0x0930, 0x021c), .driver_info = BTUSB_ATH3012 },
221         { USB_DEVICE(0x0930, 0x0220), .driver_info = BTUSB_ATH3012 },
222         { USB_DEVICE(0x0930, 0x0227), .driver_info = BTUSB_ATH3012 },
223         { USB_DEVICE(0x0b05, 0x17d0), .driver_info = BTUSB_ATH3012 },
224         { USB_DEVICE(0x0cf3, 0x0036), .driver_info = BTUSB_ATH3012 },
225         { USB_DEVICE(0x0cf3, 0x3004), .driver_info = BTUSB_ATH3012 },
226         { USB_DEVICE(0x0cf3, 0x3008), .driver_info = BTUSB_ATH3012 },
227         { USB_DEVICE(0x0cf3, 0x311d), .driver_info = BTUSB_ATH3012 },
228         { USB_DEVICE(0x0cf3, 0x311e), .driver_info = BTUSB_ATH3012 },
229         { USB_DEVICE(0x0cf3, 0x311f), .driver_info = BTUSB_ATH3012 },
230         { USB_DEVICE(0x0cf3, 0x3121), .driver_info = BTUSB_ATH3012 },
231         { USB_DEVICE(0x0cf3, 0x817a), .driver_info = BTUSB_ATH3012 },
232         { USB_DEVICE(0x0cf3, 0x817b), .driver_info = BTUSB_ATH3012 },
233         { USB_DEVICE(0x0cf3, 0xe003), .driver_info = BTUSB_ATH3012 },
234         { USB_DEVICE(0x0cf3, 0xe004), .driver_info = BTUSB_ATH3012 },
235         { USB_DEVICE(0x0cf3, 0xe005), .driver_info = BTUSB_ATH3012 },
236         { USB_DEVICE(0x0cf3, 0xe006), .driver_info = BTUSB_ATH3012 },
237         { USB_DEVICE(0x13d3, 0x3362), .driver_info = BTUSB_ATH3012 },
238         { USB_DEVICE(0x13d3, 0x3375), .driver_info = BTUSB_ATH3012 },
239         { USB_DEVICE(0x13d3, 0x3393), .driver_info = BTUSB_ATH3012 },
240         { USB_DEVICE(0x13d3, 0x3395), .driver_info = BTUSB_ATH3012 },
241         { USB_DEVICE(0x13d3, 0x3402), .driver_info = BTUSB_ATH3012 },
242         { USB_DEVICE(0x13d3, 0x3408), .driver_info = BTUSB_ATH3012 },
243         { USB_DEVICE(0x13d3, 0x3423), .driver_info = BTUSB_ATH3012 },
244         { USB_DEVICE(0x13d3, 0x3432), .driver_info = BTUSB_ATH3012 },
245         { USB_DEVICE(0x13d3, 0x3472), .driver_info = BTUSB_ATH3012 },
246         { USB_DEVICE(0x13d3, 0x3474), .driver_info = BTUSB_ATH3012 },
247         { USB_DEVICE(0x13d3, 0x3487), .driver_info = BTUSB_ATH3012 },
248         { USB_DEVICE(0x13d3, 0x3490), .driver_info = BTUSB_ATH3012 },
249
250         /* Atheros AR5BBU12 with sflash firmware */
251         { USB_DEVICE(0x0489, 0xe02c), .driver_info = BTUSB_IGNORE },
252
253         /* Atheros AR5BBU12 with sflash firmware */
254         { USB_DEVICE(0x0489, 0xe036), .driver_info = BTUSB_ATH3012 },
255         { USB_DEVICE(0x0489, 0xe03c), .driver_info = BTUSB_ATH3012 },
256
257         /* QCA ROME chipset */
258         { USB_DEVICE(0x0cf3, 0x535b), .driver_info = BTUSB_QCA_ROME |
259                                                      BTUSB_WIDEBAND_SPEECH },
260         { USB_DEVICE(0x0cf3, 0xe007), .driver_info = BTUSB_QCA_ROME |
261                                                      BTUSB_WIDEBAND_SPEECH },
262         { USB_DEVICE(0x0cf3, 0xe009), .driver_info = BTUSB_QCA_ROME |
263                                                      BTUSB_WIDEBAND_SPEECH },
264         { USB_DEVICE(0x0cf3, 0xe010), .driver_info = BTUSB_QCA_ROME |
265                                                      BTUSB_WIDEBAND_SPEECH },
266         { USB_DEVICE(0x0cf3, 0xe300), .driver_info = BTUSB_QCA_ROME |
267                                                      BTUSB_WIDEBAND_SPEECH },
268         { USB_DEVICE(0x0cf3, 0xe301), .driver_info = BTUSB_QCA_ROME |
269                                                      BTUSB_WIDEBAND_SPEECH },
270         { USB_DEVICE(0x0cf3, 0xe360), .driver_info = BTUSB_QCA_ROME |
271                                                      BTUSB_WIDEBAND_SPEECH },
272         { USB_DEVICE(0x0cf3, 0xe500), .driver_info = BTUSB_QCA_ROME |
273                                                      BTUSB_WIDEBAND_SPEECH },
274         { USB_DEVICE(0x0489, 0xe092), .driver_info = BTUSB_QCA_ROME |
275                                                      BTUSB_WIDEBAND_SPEECH },
276         { USB_DEVICE(0x0489, 0xe09f), .driver_info = BTUSB_QCA_ROME |
277                                                      BTUSB_WIDEBAND_SPEECH },
278         { USB_DEVICE(0x0489, 0xe0a2), .driver_info = BTUSB_QCA_ROME |
279                                                      BTUSB_WIDEBAND_SPEECH },
280         { USB_DEVICE(0x04ca, 0x3011), .driver_info = BTUSB_QCA_ROME |
281                                                      BTUSB_WIDEBAND_SPEECH },
282         { USB_DEVICE(0x04ca, 0x3015), .driver_info = BTUSB_QCA_ROME |
283                                                      BTUSB_WIDEBAND_SPEECH },
284         { USB_DEVICE(0x04ca, 0x3016), .driver_info = BTUSB_QCA_ROME |
285                                                      BTUSB_WIDEBAND_SPEECH },
286         { USB_DEVICE(0x04ca, 0x301a), .driver_info = BTUSB_QCA_ROME |
287                                                      BTUSB_WIDEBAND_SPEECH },
288         { USB_DEVICE(0x04ca, 0x3021), .driver_info = BTUSB_QCA_ROME |
289                                                      BTUSB_WIDEBAND_SPEECH },
290         { USB_DEVICE(0x13d3, 0x3491), .driver_info = BTUSB_QCA_ROME |
291                                                      BTUSB_WIDEBAND_SPEECH },
292         { USB_DEVICE(0x13d3, 0x3496), .driver_info = BTUSB_QCA_ROME |
293                                                      BTUSB_WIDEBAND_SPEECH },
294         { USB_DEVICE(0x13d3, 0x3501), .driver_info = BTUSB_QCA_ROME |
295                                                      BTUSB_WIDEBAND_SPEECH },
296
297         /* QCA WCN6855 chipset */
298         { USB_DEVICE(0x0cf3, 0xe600), .driver_info = BTUSB_QCA_WCN6855 |
299                                                      BTUSB_WIDEBAND_SPEECH },
300
301         /* Broadcom BCM2035 */
302         { USB_DEVICE(0x0a5c, 0x2009), .driver_info = BTUSB_BCM92035 },
303         { USB_DEVICE(0x0a5c, 0x200a), .driver_info = BTUSB_WRONG_SCO_MTU },
304         { USB_DEVICE(0x0a5c, 0x2035), .driver_info = BTUSB_WRONG_SCO_MTU },
305
306         /* Broadcom BCM2045 */
307         { USB_DEVICE(0x0a5c, 0x2039), .driver_info = BTUSB_WRONG_SCO_MTU },
308         { USB_DEVICE(0x0a5c, 0x2101), .driver_info = BTUSB_WRONG_SCO_MTU },
309
310         /* IBM/Lenovo ThinkPad with Broadcom chip */
311         { USB_DEVICE(0x0a5c, 0x201e), .driver_info = BTUSB_WRONG_SCO_MTU },
312         { USB_DEVICE(0x0a5c, 0x2110), .driver_info = BTUSB_WRONG_SCO_MTU },
313
314         /* HP laptop with Broadcom chip */
315         { USB_DEVICE(0x03f0, 0x171d), .driver_info = BTUSB_WRONG_SCO_MTU },
316
317         /* Dell laptop with Broadcom chip */
318         { USB_DEVICE(0x413c, 0x8126), .driver_info = BTUSB_WRONG_SCO_MTU },
319
320         /* Dell Wireless 370 and 410 devices */
321         { USB_DEVICE(0x413c, 0x8152), .driver_info = BTUSB_WRONG_SCO_MTU },
322         { USB_DEVICE(0x413c, 0x8156), .driver_info = BTUSB_WRONG_SCO_MTU },
323
324         /* Belkin F8T012 and F8T013 devices */
325         { USB_DEVICE(0x050d, 0x0012), .driver_info = BTUSB_WRONG_SCO_MTU },
326         { USB_DEVICE(0x050d, 0x0013), .driver_info = BTUSB_WRONG_SCO_MTU },
327
328         /* Asus WL-BTD202 device */
329         { USB_DEVICE(0x0b05, 0x1715), .driver_info = BTUSB_WRONG_SCO_MTU },
330
331         /* Kensington Bluetooth USB adapter */
332         { USB_DEVICE(0x047d, 0x105e), .driver_info = BTUSB_WRONG_SCO_MTU },
333
334         /* RTX Telecom based adapters with buggy SCO support */
335         { USB_DEVICE(0x0400, 0x0807), .driver_info = BTUSB_BROKEN_ISOC },
336         { USB_DEVICE(0x0400, 0x080a), .driver_info = BTUSB_BROKEN_ISOC },
337
338         /* CONWISE Technology based adapters with buggy SCO support */
339         { USB_DEVICE(0x0e5e, 0x6622),
340           .driver_info = BTUSB_BROKEN_ISOC | BTUSB_CW6622},
341
342         /* Roper Class 1 Bluetooth Dongle (Silicon Wave based) */
343         { USB_DEVICE(0x1310, 0x0001), .driver_info = BTUSB_SWAVE },
344
345         /* Digianswer devices */
346         { USB_DEVICE(0x08fd, 0x0001), .driver_info = BTUSB_DIGIANSWER },
347         { USB_DEVICE(0x08fd, 0x0002), .driver_info = BTUSB_IGNORE },
348
349         /* CSR BlueCore Bluetooth Sniffer */
350         { USB_DEVICE(0x0a12, 0x0002),
351           .driver_info = BTUSB_SNIFFER | BTUSB_BROKEN_ISOC },
352
353         /* Frontline ComProbe Bluetooth Sniffer */
354         { USB_DEVICE(0x16d3, 0x0002),
355           .driver_info = BTUSB_SNIFFER | BTUSB_BROKEN_ISOC },
356
357         /* Marvell Bluetooth devices */
358         { USB_DEVICE(0x1286, 0x2044), .driver_info = BTUSB_MARVELL },
359         { USB_DEVICE(0x1286, 0x2046), .driver_info = BTUSB_MARVELL },
360         { USB_DEVICE(0x1286, 0x204e), .driver_info = BTUSB_MARVELL },
361
362         /* Intel Bluetooth devices */
363         { USB_DEVICE(0x8087, 0x0025), .driver_info = BTUSB_INTEL_NEW |
364                                                      BTUSB_WIDEBAND_SPEECH |
365                                                      BTUSB_VALID_LE_STATES },
366         { USB_DEVICE(0x8087, 0x0026), .driver_info = BTUSB_INTEL_NEW |
367                                                      BTUSB_WIDEBAND_SPEECH },
368         { USB_DEVICE(0x8087, 0x0029), .driver_info = BTUSB_INTEL_NEW |
369                                                      BTUSB_WIDEBAND_SPEECH },
370         { USB_DEVICE(0x8087, 0x0032), .driver_info = BTUSB_INTEL_NEW |
371                                                      BTUSB_WIDEBAND_SPEECH},
372         { USB_DEVICE(0x8087, 0x07da), .driver_info = BTUSB_CSR },
373         { USB_DEVICE(0x8087, 0x07dc), .driver_info = BTUSB_INTEL },
374         { USB_DEVICE(0x8087, 0x0a2a), .driver_info = BTUSB_INTEL },
375         { USB_DEVICE(0x8087, 0x0a2b), .driver_info = BTUSB_INTEL_NEW |
376                                                      BTUSB_WIDEBAND_SPEECH },
377         { USB_DEVICE(0x8087, 0x0aa7), .driver_info = BTUSB_INTEL |
378                                                      BTUSB_WIDEBAND_SPEECH },
379         { USB_DEVICE(0x8087, 0x0aaa), .driver_info = BTUSB_INTEL_NEW |
380                                                      BTUSB_WIDEBAND_SPEECH |
381                                                      BTUSB_VALID_LE_STATES },
382         { USB_DEVICE(0x10ab, 0x9309), .driver_info = BTUSB_QCA_WCN6855 |
383                                                      BTUSB_WIDEBAND_SPEECH |
384                                                      BTUSB_VALID_LE_STATES },
385         { USB_DEVICE(0x10ab, 0x9409), .driver_info = BTUSB_QCA_WCN6855 |
386                                                      BTUSB_WIDEBAND_SPEECH |
387                                                      BTUSB_VALID_LE_STATES },
388         { USB_DEVICE(0x0489, 0xe0d0), .driver_info = BTUSB_QCA_WCN6855 |
389                                                      BTUSB_WIDEBAND_SPEECH |
390                                                      BTUSB_VALID_LE_STATES },
391
392         /* Other Intel Bluetooth devices */
393         { USB_VENDOR_AND_INTERFACE_INFO(0x8087, 0xe0, 0x01, 0x01),
394           .driver_info = BTUSB_IGNORE },
395
396         /* Realtek 8821CE Bluetooth devices */
397         { USB_DEVICE(0x13d3, 0x3529), .driver_info = BTUSB_REALTEK |
398                                                      BTUSB_WIDEBAND_SPEECH },
399
400         /* Realtek 8822CE Bluetooth devices */
401         { USB_DEVICE(0x0bda, 0xb00c), .driver_info = BTUSB_REALTEK |
402                                                      BTUSB_WIDEBAND_SPEECH },
403         { USB_DEVICE(0x0bda, 0xc822), .driver_info = BTUSB_REALTEK |
404                                                      BTUSB_WIDEBAND_SPEECH },
405
406         /* Realtek 8852CE Bluetooth devices */
407         { USB_DEVICE(0x04ca, 0x4007), .driver_info = BTUSB_REALTEK |
408                                                      BTUSB_WIDEBAND_SPEECH },
409         { USB_DEVICE(0x04c5, 0x1675), .driver_info = BTUSB_REALTEK |
410                                                      BTUSB_WIDEBAND_SPEECH },
411         { USB_DEVICE(0x0cb8, 0xc558), .driver_info = BTUSB_REALTEK |
412                                                      BTUSB_WIDEBAND_SPEECH },
413         { USB_DEVICE(0x13d3, 0x3587), .driver_info = BTUSB_REALTEK |
414                                                      BTUSB_WIDEBAND_SPEECH },
415         { USB_DEVICE(0x13d3, 0x3586), .driver_info = BTUSB_REALTEK |
416                                                      BTUSB_WIDEBAND_SPEECH },
417
418         /* Realtek 8852BE Bluetooth devices */
419         { USB_DEVICE(0x0cb8, 0xc559), .driver_info = BTUSB_REALTEK |
420                                                      BTUSB_WIDEBAND_SPEECH },
421         { USB_DEVICE(0x0bda, 0x4853), .driver_info = BTUSB_REALTEK |
422                                                      BTUSB_WIDEBAND_SPEECH },
423         { USB_DEVICE(0x0bda, 0x887b), .driver_info = BTUSB_REALTEK |
424                                                      BTUSB_WIDEBAND_SPEECH },
425         { USB_DEVICE(0x0bda, 0xb85b), .driver_info = BTUSB_REALTEK |
426                                                      BTUSB_WIDEBAND_SPEECH },
427         { USB_DEVICE(0x13d3, 0x3570), .driver_info = BTUSB_REALTEK |
428                                                      BTUSB_WIDEBAND_SPEECH },
429         { USB_DEVICE(0x13d3, 0x3571), .driver_info = BTUSB_REALTEK |
430                                                      BTUSB_WIDEBAND_SPEECH },
431
432         /* Realtek Bluetooth devices */
433         { USB_VENDOR_AND_INTERFACE_INFO(0x0bda, 0xe0, 0x01, 0x01),
434           .driver_info = BTUSB_REALTEK },
435
436         /* MediaTek Bluetooth devices */
437         { USB_VENDOR_AND_INTERFACE_INFO(0x0e8d, 0xe0, 0x01, 0x01),
438           .driver_info = BTUSB_MEDIATEK |
439                          BTUSB_WIDEBAND_SPEECH |
440                          BTUSB_VALID_LE_STATES },
441
442         /* MediaTek MT7922A Bluetooth devices */
443         { USB_DEVICE(0x0489, 0xe0d8), .driver_info = BTUSB_MEDIATEK |
444                                                      BTUSB_WIDEBAND_SPEECH |
445                                                      BTUSB_VALID_LE_STATES },
446         { USB_DEVICE(0x0489, 0xe0d9), .driver_info = BTUSB_MEDIATEK |
447                                                      BTUSB_WIDEBAND_SPEECH |
448                                                      BTUSB_VALID_LE_STATES },
449         { USB_DEVICE(0x0489, 0xe0f5), .driver_info = BTUSB_MEDIATEK |
450                                                      BTUSB_WIDEBAND_SPEECH |
451                                                      BTUSB_VALID_LE_STATES },
452         { USB_DEVICE(0x13d3, 0x3568), .driver_info = BTUSB_MEDIATEK |
453                                                      BTUSB_WIDEBAND_SPEECH |
454                                                      BTUSB_VALID_LE_STATES },
455
456         /* Additional Realtek 8723AE Bluetooth devices */
457         { USB_DEVICE(0x0930, 0x021d), .driver_info = BTUSB_REALTEK },
458         { USB_DEVICE(0x13d3, 0x3394), .driver_info = BTUSB_REALTEK },
459
460         /* Additional Realtek 8723BE Bluetooth devices */
461         { USB_DEVICE(0x0489, 0xe085), .driver_info = BTUSB_REALTEK },
462         { USB_DEVICE(0x0489, 0xe08b), .driver_info = BTUSB_REALTEK },
463         { USB_DEVICE(0x13d3, 0x3410), .driver_info = BTUSB_REALTEK },
464         { USB_DEVICE(0x13d3, 0x3416), .driver_info = BTUSB_REALTEK },
465         { USB_DEVICE(0x13d3, 0x3459), .driver_info = BTUSB_REALTEK },
466         { USB_DEVICE(0x13d3, 0x3494), .driver_info = BTUSB_REALTEK },
467
468         /* Additional Realtek 8723BU Bluetooth devices */
469         { USB_DEVICE(0x7392, 0xa611), .driver_info = BTUSB_REALTEK },
470
471         /* Additional Realtek 8723DE Bluetooth devices */
472         { USB_DEVICE(0x0bda, 0xb009), .driver_info = BTUSB_REALTEK },
473         { USB_DEVICE(0x2ff8, 0xb011), .driver_info = BTUSB_REALTEK },
474
475         /* Additional Realtek 8821AE Bluetooth devices */
476         { USB_DEVICE(0x0b05, 0x17dc), .driver_info = BTUSB_REALTEK },
477         { USB_DEVICE(0x13d3, 0x3414), .driver_info = BTUSB_REALTEK },
478         { USB_DEVICE(0x13d3, 0x3458), .driver_info = BTUSB_REALTEK },
479         { USB_DEVICE(0x13d3, 0x3461), .driver_info = BTUSB_REALTEK },
480         { USB_DEVICE(0x13d3, 0x3462), .driver_info = BTUSB_REALTEK },
481
482         /* Additional Realtek 8822BE Bluetooth devices */
483         { USB_DEVICE(0x13d3, 0x3526), .driver_info = BTUSB_REALTEK },
484         { USB_DEVICE(0x0b05, 0x185c), .driver_info = BTUSB_REALTEK },
485
486         /* Additional Realtek 8822CE Bluetooth devices */
487         { USB_DEVICE(0x04ca, 0x4005), .driver_info = BTUSB_REALTEK },
488         { USB_DEVICE(0x13d3, 0x3548), .driver_info = BTUSB_REALTEK },
489
490         /* Silicon Wave based devices */
491         { USB_DEVICE(0x0c10, 0x0000), .driver_info = BTUSB_SWAVE },
492
493         { }     /* Terminating entry */
494 };
495
496 /* The Bluetooth USB module build into some devices needs to be reset on resume,
497  * this is a problem with the platform (likely shutting off all power) not with
498  * the module itself. So we use a DMI list to match known broken platforms.
499  */
500 static const struct dmi_system_id btusb_needs_reset_resume_table[] = {
501         {
502                 /* Dell OptiPlex 3060 (QCA ROME device 0cf3:e007) */
503                 .matches = {
504                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
505                         DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex 3060"),
506                 },
507         },
508         {
509                 /* Dell XPS 9360 (QCA ROME device 0cf3:e300) */
510                 .matches = {
511                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
512                         DMI_MATCH(DMI_PRODUCT_NAME, "XPS 13 9360"),
513                 },
514         },
515         {
516                 /* Dell Inspiron 5565 (QCA ROME device 0cf3:e009) */
517                 .matches = {
518                         DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
519                         DMI_MATCH(DMI_PRODUCT_NAME, "Inspiron 5565"),
520                 },
521         },
522         {}
523 };
524
525 #define BTUSB_MAX_ISOC_FRAMES   10
526
527 #define BTUSB_INTR_RUNNING      0
528 #define BTUSB_BULK_RUNNING      1
529 #define BTUSB_ISOC_RUNNING      2
530 #define BTUSB_SUSPENDING        3
531 #define BTUSB_DID_ISO_RESUME    4
532 #define BTUSB_BOOTLOADER        5
533 #define BTUSB_DOWNLOADING       6
534 #define BTUSB_FIRMWARE_LOADED   7
535 #define BTUSB_FIRMWARE_FAILED   8
536 #define BTUSB_BOOTING           9
537 #define BTUSB_DIAG_RUNNING      10
538 #define BTUSB_OOB_WAKE_ENABLED  11
539 #define BTUSB_HW_RESET_ACTIVE   12
540 #define BTUSB_TX_WAIT_VND_EVT   13
541 #define BTUSB_WAKEUP_DISABLE    14
542 #define BTUSB_USE_ALT3_FOR_WBS  15
543
544 struct btusb_data {
545         struct hci_dev       *hdev;
546         struct usb_device    *udev;
547         struct usb_interface *intf;
548         struct usb_interface *isoc;
549         struct usb_interface *diag;
550         unsigned isoc_ifnum;
551
552         unsigned long flags;
553
554         struct work_struct work;
555         struct work_struct waker;
556
557         struct usb_anchor deferred;
558         struct usb_anchor tx_anchor;
559         int tx_in_flight;
560         spinlock_t txlock;
561
562         struct usb_anchor intr_anchor;
563         struct usb_anchor bulk_anchor;
564         struct usb_anchor isoc_anchor;
565         struct usb_anchor diag_anchor;
566         struct usb_anchor ctrl_anchor;
567         spinlock_t rxlock;
568
569         struct sk_buff *evt_skb;
570         struct sk_buff *acl_skb;
571         struct sk_buff *sco_skb;
572
573         struct usb_endpoint_descriptor *intr_ep;
574         struct usb_endpoint_descriptor *bulk_tx_ep;
575         struct usb_endpoint_descriptor *bulk_rx_ep;
576         struct usb_endpoint_descriptor *isoc_tx_ep;
577         struct usb_endpoint_descriptor *isoc_rx_ep;
578         struct usb_endpoint_descriptor *diag_tx_ep;
579         struct usb_endpoint_descriptor *diag_rx_ep;
580
581         struct gpio_desc *reset_gpio;
582
583         __u8 cmdreq_type;
584         __u8 cmdreq;
585
586         unsigned int sco_num;
587         unsigned int air_mode;
588         bool usb_alt6_packet_flow;
589         int isoc_altsetting;
590         int suspend_count;
591
592         int (*recv_event)(struct hci_dev *hdev, struct sk_buff *skb);
593         int (*recv_bulk)(struct btusb_data *data, void *buffer, int count);
594
595         int (*setup_on_usb)(struct hci_dev *hdev);
596
597         int oob_wake_irq;   /* irq for out-of-band wake-on-bt */
598         unsigned cmd_timeout_cnt;
599 };
600
601 static void btusb_intel_cmd_timeout(struct hci_dev *hdev)
602 {
603         struct btusb_data *data = hci_get_drvdata(hdev);
604         struct gpio_desc *reset_gpio = data->reset_gpio;
605
606         if (++data->cmd_timeout_cnt < 5)
607                 return;
608
609         if (!reset_gpio) {
610                 bt_dev_err(hdev, "No way to reset. Ignoring and continuing");
611                 return;
612         }
613
614         /*
615          * Toggle the hard reset line if the platform provides one. The reset
616          * is going to yank the device off the USB and then replug. So doing
617          * once is enough. The cleanup is handled correctly on the way out
618          * (standard USB disconnect), and the new device is detected cleanly
619          * and bound to the driver again like it should be.
620          */
621         if (test_and_set_bit(BTUSB_HW_RESET_ACTIVE, &data->flags)) {
622                 bt_dev_err(hdev, "last reset failed? Not resetting again");
623                 return;
624         }
625
626         bt_dev_err(hdev, "Initiating HW reset via gpio");
627         gpiod_set_value_cansleep(reset_gpio, 1);
628         msleep(100);
629         gpiod_set_value_cansleep(reset_gpio, 0);
630 }
631
632 static void btusb_rtl_cmd_timeout(struct hci_dev *hdev)
633 {
634         struct btusb_data *data = hci_get_drvdata(hdev);
635         struct gpio_desc *reset_gpio = data->reset_gpio;
636
637         if (++data->cmd_timeout_cnt < 5)
638                 return;
639
640         if (!reset_gpio) {
641                 bt_dev_err(hdev, "No gpio to reset Realtek device, ignoring");
642                 return;
643         }
644
645         /* Toggle the hard reset line. The Realtek device is going to
646          * yank itself off the USB and then replug. The cleanup is handled
647          * correctly on the way out (standard USB disconnect), and the new
648          * device is detected cleanly and bound to the driver again like
649          * it should be.
650          */
651         if (test_and_set_bit(BTUSB_HW_RESET_ACTIVE, &data->flags)) {
652                 bt_dev_err(hdev, "last reset failed? Not resetting again");
653                 return;
654         }
655
656         bt_dev_err(hdev, "Reset Realtek device via gpio");
657         gpiod_set_value_cansleep(reset_gpio, 1);
658         msleep(200);
659         gpiod_set_value_cansleep(reset_gpio, 0);
660 }
661
662 static void btusb_qca_cmd_timeout(struct hci_dev *hdev)
663 {
664         struct btusb_data *data = hci_get_drvdata(hdev);
665         int err;
666
667         if (++data->cmd_timeout_cnt < 5)
668                 return;
669
670         bt_dev_err(hdev, "Multiple cmd timeouts seen. Resetting usb device.");
671         /* This is not an unbalanced PM reference since the device will reset */
672         err = usb_autopm_get_interface(data->intf);
673         if (!err)
674                 usb_queue_reset_device(data->intf);
675         else
676                 bt_dev_err(hdev, "Failed usb_autopm_get_interface with %d", err);
677 }
678
679 static inline void btusb_free_frags(struct btusb_data *data)
680 {
681         unsigned long flags;
682
683         spin_lock_irqsave(&data->rxlock, flags);
684
685         dev_kfree_skb_irq(data->evt_skb);
686         data->evt_skb = NULL;
687
688         dev_kfree_skb_irq(data->acl_skb);
689         data->acl_skb = NULL;
690
691         dev_kfree_skb_irq(data->sco_skb);
692         data->sco_skb = NULL;
693
694         spin_unlock_irqrestore(&data->rxlock, flags);
695 }
696
697 static int btusb_recv_intr(struct btusb_data *data, void *buffer, int count)
698 {
699         struct sk_buff *skb;
700         unsigned long flags;
701         int err = 0;
702
703         spin_lock_irqsave(&data->rxlock, flags);
704         skb = data->evt_skb;
705
706         while (count) {
707                 int len;
708
709                 if (!skb) {
710                         skb = bt_skb_alloc(HCI_MAX_EVENT_SIZE, GFP_ATOMIC);
711                         if (!skb) {
712                                 err = -ENOMEM;
713                                 break;
714                         }
715
716                         hci_skb_pkt_type(skb) = HCI_EVENT_PKT;
717                         hci_skb_expect(skb) = HCI_EVENT_HDR_SIZE;
718                 }
719
720                 len = min_t(uint, hci_skb_expect(skb), count);
721                 skb_put_data(skb, buffer, len);
722
723                 count -= len;
724                 buffer += len;
725                 hci_skb_expect(skb) -= len;
726
727                 if (skb->len == HCI_EVENT_HDR_SIZE) {
728                         /* Complete event header */
729                         hci_skb_expect(skb) = hci_event_hdr(skb)->plen;
730
731                         if (skb_tailroom(skb) < hci_skb_expect(skb)) {
732                                 kfree_skb(skb);
733                                 skb = NULL;
734
735                                 err = -EILSEQ;
736                                 break;
737                         }
738                 }
739
740                 if (!hci_skb_expect(skb)) {
741                         /* Complete frame */
742                         data->recv_event(data->hdev, skb);
743                         skb = NULL;
744                 }
745         }
746
747         data->evt_skb = skb;
748         spin_unlock_irqrestore(&data->rxlock, flags);
749
750         return err;
751 }
752
753 static int btusb_recv_bulk(struct btusb_data *data, void *buffer, int count)
754 {
755         struct sk_buff *skb;
756         unsigned long flags;
757         int err = 0;
758
759         spin_lock_irqsave(&data->rxlock, flags);
760         skb = data->acl_skb;
761
762         while (count) {
763                 int len;
764
765                 if (!skb) {
766                         skb = bt_skb_alloc(HCI_MAX_FRAME_SIZE, GFP_ATOMIC);
767                         if (!skb) {
768                                 err = -ENOMEM;
769                                 break;
770                         }
771
772                         hci_skb_pkt_type(skb) = HCI_ACLDATA_PKT;
773                         hci_skb_expect(skb) = HCI_ACL_HDR_SIZE;
774                 }
775
776                 len = min_t(uint, hci_skb_expect(skb), count);
777                 skb_put_data(skb, buffer, len);
778
779                 count -= len;
780                 buffer += len;
781                 hci_skb_expect(skb) -= len;
782
783                 if (skb->len == HCI_ACL_HDR_SIZE) {
784                         __le16 dlen = hci_acl_hdr(skb)->dlen;
785
786                         /* Complete ACL header */
787                         hci_skb_expect(skb) = __le16_to_cpu(dlen);
788
789                         if (skb_tailroom(skb) < hci_skb_expect(skb)) {
790                                 kfree_skb(skb);
791                                 skb = NULL;
792
793                                 err = -EILSEQ;
794                                 break;
795                         }
796                 }
797
798                 if (!hci_skb_expect(skb)) {
799                         /* Complete frame */
800                         hci_recv_frame(data->hdev, skb);
801                         skb = NULL;
802                 }
803         }
804
805         data->acl_skb = skb;
806         spin_unlock_irqrestore(&data->rxlock, flags);
807
808         return err;
809 }
810
811 static int btusb_recv_isoc(struct btusb_data *data, void *buffer, int count)
812 {
813         struct sk_buff *skb;
814         unsigned long flags;
815         int err = 0;
816
817         spin_lock_irqsave(&data->rxlock, flags);
818         skb = data->sco_skb;
819
820         while (count) {
821                 int len;
822
823                 if (!skb) {
824                         skb = bt_skb_alloc(HCI_MAX_SCO_SIZE, GFP_ATOMIC);
825                         if (!skb) {
826                                 err = -ENOMEM;
827                                 break;
828                         }
829
830                         hci_skb_pkt_type(skb) = HCI_SCODATA_PKT;
831                         hci_skb_expect(skb) = HCI_SCO_HDR_SIZE;
832                 }
833
834                 len = min_t(uint, hci_skb_expect(skb), count);
835                 skb_put_data(skb, buffer, len);
836
837                 count -= len;
838                 buffer += len;
839                 hci_skb_expect(skb) -= len;
840
841                 if (skb->len == HCI_SCO_HDR_SIZE) {
842                         /* Complete SCO header */
843                         hci_skb_expect(skb) = hci_sco_hdr(skb)->dlen;
844
845                         if (skb_tailroom(skb) < hci_skb_expect(skb)) {
846                                 kfree_skb(skb);
847                                 skb = NULL;
848
849                                 err = -EILSEQ;
850                                 break;
851                         }
852                 }
853
854                 if (!hci_skb_expect(skb)) {
855                         /* Complete frame */
856                         hci_recv_frame(data->hdev, skb);
857                         skb = NULL;
858                 }
859         }
860
861         data->sco_skb = skb;
862         spin_unlock_irqrestore(&data->rxlock, flags);
863
864         return err;
865 }
866
867 static void btusb_intr_complete(struct urb *urb)
868 {
869         struct hci_dev *hdev = urb->context;
870         struct btusb_data *data = hci_get_drvdata(hdev);
871         int err;
872
873         BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status,
874                urb->actual_length);
875
876         if (!test_bit(HCI_RUNNING, &hdev->flags))
877                 return;
878
879         if (urb->status == 0) {
880                 hdev->stat.byte_rx += urb->actual_length;
881
882                 if (btusb_recv_intr(data, urb->transfer_buffer,
883                                     urb->actual_length) < 0) {
884                         bt_dev_err(hdev, "corrupted event packet");
885                         hdev->stat.err_rx++;
886                 }
887         } else if (urb->status == -ENOENT) {
888                 /* Avoid suspend failed when usb_kill_urb */
889                 return;
890         }
891
892         if (!test_bit(BTUSB_INTR_RUNNING, &data->flags))
893                 return;
894
895         usb_mark_last_busy(data->udev);
896         usb_anchor_urb(urb, &data->intr_anchor);
897
898         err = usb_submit_urb(urb, GFP_ATOMIC);
899         if (err < 0) {
900                 /* -EPERM: urb is being killed;
901                  * -ENODEV: device got disconnected
902                  */
903                 if (err != -EPERM && err != -ENODEV)
904                         bt_dev_err(hdev, "urb %p failed to resubmit (%d)",
905                                    urb, -err);
906                 usb_unanchor_urb(urb);
907         }
908 }
909
910 static int btusb_submit_intr_urb(struct hci_dev *hdev, gfp_t mem_flags)
911 {
912         struct btusb_data *data = hci_get_drvdata(hdev);
913         struct urb *urb;
914         unsigned char *buf;
915         unsigned int pipe;
916         int err, size;
917
918         BT_DBG("%s", hdev->name);
919
920         if (!data->intr_ep)
921                 return -ENODEV;
922
923         urb = usb_alloc_urb(0, mem_flags);
924         if (!urb)
925                 return -ENOMEM;
926
927         size = le16_to_cpu(data->intr_ep->wMaxPacketSize);
928
929         buf = kmalloc(size, mem_flags);
930         if (!buf) {
931                 usb_free_urb(urb);
932                 return -ENOMEM;
933         }
934
935         pipe = usb_rcvintpipe(data->udev, data->intr_ep->bEndpointAddress);
936
937         usb_fill_int_urb(urb, data->udev, pipe, buf, size,
938                          btusb_intr_complete, hdev, data->intr_ep->bInterval);
939
940         urb->transfer_flags |= URB_FREE_BUFFER;
941
942         usb_anchor_urb(urb, &data->intr_anchor);
943
944         err = usb_submit_urb(urb, mem_flags);
945         if (err < 0) {
946                 if (err != -EPERM && err != -ENODEV)
947                         bt_dev_err(hdev, "urb %p submission failed (%d)",
948                                    urb, -err);
949                 usb_unanchor_urb(urb);
950         }
951
952         usb_free_urb(urb);
953
954         return err;
955 }
956
957 static void btusb_bulk_complete(struct urb *urb)
958 {
959         struct hci_dev *hdev = urb->context;
960         struct btusb_data *data = hci_get_drvdata(hdev);
961         int err;
962
963         BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status,
964                urb->actual_length);
965
966         if (!test_bit(HCI_RUNNING, &hdev->flags))
967                 return;
968
969         if (urb->status == 0) {
970                 hdev->stat.byte_rx += urb->actual_length;
971
972                 if (data->recv_bulk(data, urb->transfer_buffer,
973                                     urb->actual_length) < 0) {
974                         bt_dev_err(hdev, "corrupted ACL packet");
975                         hdev->stat.err_rx++;
976                 }
977         } else if (urb->status == -ENOENT) {
978                 /* Avoid suspend failed when usb_kill_urb */
979                 return;
980         }
981
982         if (!test_bit(BTUSB_BULK_RUNNING, &data->flags))
983                 return;
984
985         usb_anchor_urb(urb, &data->bulk_anchor);
986         usb_mark_last_busy(data->udev);
987
988         err = usb_submit_urb(urb, GFP_ATOMIC);
989         if (err < 0) {
990                 /* -EPERM: urb is being killed;
991                  * -ENODEV: device got disconnected
992                  */
993                 if (err != -EPERM && err != -ENODEV)
994                         bt_dev_err(hdev, "urb %p failed to resubmit (%d)",
995                                    urb, -err);
996                 usb_unanchor_urb(urb);
997         }
998 }
999
1000 static int btusb_submit_bulk_urb(struct hci_dev *hdev, gfp_t mem_flags)
1001 {
1002         struct btusb_data *data = hci_get_drvdata(hdev);
1003         struct urb *urb;
1004         unsigned char *buf;
1005         unsigned int pipe;
1006         int err, size = HCI_MAX_FRAME_SIZE;
1007
1008         BT_DBG("%s", hdev->name);
1009
1010         if (!data->bulk_rx_ep)
1011                 return -ENODEV;
1012
1013         urb = usb_alloc_urb(0, mem_flags);
1014         if (!urb)
1015                 return -ENOMEM;
1016
1017         buf = kmalloc(size, mem_flags);
1018         if (!buf) {
1019                 usb_free_urb(urb);
1020                 return -ENOMEM;
1021         }
1022
1023         pipe = usb_rcvbulkpipe(data->udev, data->bulk_rx_ep->bEndpointAddress);
1024
1025         usb_fill_bulk_urb(urb, data->udev, pipe, buf, size,
1026                           btusb_bulk_complete, hdev);
1027
1028         urb->transfer_flags |= URB_FREE_BUFFER;
1029
1030         usb_mark_last_busy(data->udev);
1031         usb_anchor_urb(urb, &data->bulk_anchor);
1032
1033         err = usb_submit_urb(urb, mem_flags);
1034         if (err < 0) {
1035                 if (err != -EPERM && err != -ENODEV)
1036                         bt_dev_err(hdev, "urb %p submission failed (%d)",
1037                                    urb, -err);
1038                 usb_unanchor_urb(urb);
1039         }
1040
1041         usb_free_urb(urb);
1042
1043         return err;
1044 }
1045
1046 static void btusb_isoc_complete(struct urb *urb)
1047 {
1048         struct hci_dev *hdev = urb->context;
1049         struct btusb_data *data = hci_get_drvdata(hdev);
1050         int i, err;
1051
1052         BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status,
1053                urb->actual_length);
1054
1055         if (!test_bit(HCI_RUNNING, &hdev->flags))
1056                 return;
1057
1058         if (urb->status == 0) {
1059                 for (i = 0; i < urb->number_of_packets; i++) {
1060                         unsigned int offset = urb->iso_frame_desc[i].offset;
1061                         unsigned int length = urb->iso_frame_desc[i].actual_length;
1062
1063                         if (urb->iso_frame_desc[i].status)
1064                                 continue;
1065
1066                         hdev->stat.byte_rx += length;
1067
1068                         if (btusb_recv_isoc(data, urb->transfer_buffer + offset,
1069                                             length) < 0) {
1070                                 bt_dev_err(hdev, "corrupted SCO packet");
1071                                 hdev->stat.err_rx++;
1072                         }
1073                 }
1074         } else if (urb->status == -ENOENT) {
1075                 /* Avoid suspend failed when usb_kill_urb */
1076                 return;
1077         }
1078
1079         if (!test_bit(BTUSB_ISOC_RUNNING, &data->flags))
1080                 return;
1081
1082         usb_anchor_urb(urb, &data->isoc_anchor);
1083
1084         err = usb_submit_urb(urb, GFP_ATOMIC);
1085         if (err < 0) {
1086                 /* -EPERM: urb is being killed;
1087                  * -ENODEV: device got disconnected
1088                  */
1089                 if (err != -EPERM && err != -ENODEV)
1090                         bt_dev_err(hdev, "urb %p failed to resubmit (%d)",
1091                                    urb, -err);
1092                 usb_unanchor_urb(urb);
1093         }
1094 }
1095
1096 static inline void __fill_isoc_descriptor_msbc(struct urb *urb, int len,
1097                                                int mtu, struct btusb_data *data)
1098 {
1099         int i, offset = 0;
1100         unsigned int interval;
1101
1102         BT_DBG("len %d mtu %d", len, mtu);
1103
1104         /* For mSBC ALT 6 setting the host will send the packet at continuous
1105          * flow. As per core spec 5, vol 4, part B, table 2.1. For ALT setting
1106          * 6 the HCI PACKET INTERVAL should be 7.5ms for every usb packets.
1107          * To maintain the rate we send 63bytes of usb packets alternatively for
1108          * 7ms and 8ms to maintain the rate as 7.5ms.
1109          */
1110         if (data->usb_alt6_packet_flow) {
1111                 interval = 7;
1112                 data->usb_alt6_packet_flow = false;
1113         } else {
1114                 interval = 6;
1115                 data->usb_alt6_packet_flow = true;
1116         }
1117
1118         for (i = 0; i < interval; i++) {
1119                 urb->iso_frame_desc[i].offset = offset;
1120                 urb->iso_frame_desc[i].length = offset;
1121         }
1122
1123         if (len && i < BTUSB_MAX_ISOC_FRAMES) {
1124                 urb->iso_frame_desc[i].offset = offset;
1125                 urb->iso_frame_desc[i].length = len;
1126                 i++;
1127         }
1128
1129         urb->number_of_packets = i;
1130 }
1131
1132 static inline void __fill_isoc_descriptor(struct urb *urb, int len, int mtu)
1133 {
1134         int i, offset = 0;
1135
1136         BT_DBG("len %d mtu %d", len, mtu);
1137
1138         for (i = 0; i < BTUSB_MAX_ISOC_FRAMES && len >= mtu;
1139                                         i++, offset += mtu, len -= mtu) {
1140                 urb->iso_frame_desc[i].offset = offset;
1141                 urb->iso_frame_desc[i].length = mtu;
1142         }
1143
1144         if (len && i < BTUSB_MAX_ISOC_FRAMES) {
1145                 urb->iso_frame_desc[i].offset = offset;
1146                 urb->iso_frame_desc[i].length = len;
1147                 i++;
1148         }
1149
1150         urb->number_of_packets = i;
1151 }
1152
1153 static int btusb_submit_isoc_urb(struct hci_dev *hdev, gfp_t mem_flags)
1154 {
1155         struct btusb_data *data = hci_get_drvdata(hdev);
1156         struct urb *urb;
1157         unsigned char *buf;
1158         unsigned int pipe;
1159         int err, size;
1160
1161         BT_DBG("%s", hdev->name);
1162
1163         if (!data->isoc_rx_ep)
1164                 return -ENODEV;
1165
1166         urb = usb_alloc_urb(BTUSB_MAX_ISOC_FRAMES, mem_flags);
1167         if (!urb)
1168                 return -ENOMEM;
1169
1170         size = le16_to_cpu(data->isoc_rx_ep->wMaxPacketSize) *
1171                                                 BTUSB_MAX_ISOC_FRAMES;
1172
1173         buf = kmalloc(size, mem_flags);
1174         if (!buf) {
1175                 usb_free_urb(urb);
1176                 return -ENOMEM;
1177         }
1178
1179         pipe = usb_rcvisocpipe(data->udev, data->isoc_rx_ep->bEndpointAddress);
1180
1181         usb_fill_int_urb(urb, data->udev, pipe, buf, size, btusb_isoc_complete,
1182                          hdev, data->isoc_rx_ep->bInterval);
1183
1184         urb->transfer_flags = URB_FREE_BUFFER | URB_ISO_ASAP;
1185
1186         __fill_isoc_descriptor(urb, size,
1187                                le16_to_cpu(data->isoc_rx_ep->wMaxPacketSize));
1188
1189         usb_anchor_urb(urb, &data->isoc_anchor);
1190
1191         err = usb_submit_urb(urb, mem_flags);
1192         if (err < 0) {
1193                 if (err != -EPERM && err != -ENODEV)
1194                         bt_dev_err(hdev, "urb %p submission failed (%d)",
1195                                    urb, -err);
1196                 usb_unanchor_urb(urb);
1197         }
1198
1199         usb_free_urb(urb);
1200
1201         return err;
1202 }
1203
1204 static void btusb_diag_complete(struct urb *urb)
1205 {
1206         struct hci_dev *hdev = urb->context;
1207         struct btusb_data *data = hci_get_drvdata(hdev);
1208         int err;
1209
1210         BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status,
1211                urb->actual_length);
1212
1213         if (urb->status == 0) {
1214                 struct sk_buff *skb;
1215
1216                 skb = bt_skb_alloc(urb->actual_length, GFP_ATOMIC);
1217                 if (skb) {
1218                         skb_put_data(skb, urb->transfer_buffer,
1219                                      urb->actual_length);
1220                         hci_recv_diag(hdev, skb);
1221                 }
1222         } else if (urb->status == -ENOENT) {
1223                 /* Avoid suspend failed when usb_kill_urb */
1224                 return;
1225         }
1226
1227         if (!test_bit(BTUSB_DIAG_RUNNING, &data->flags))
1228                 return;
1229
1230         usb_anchor_urb(urb, &data->diag_anchor);
1231         usb_mark_last_busy(data->udev);
1232
1233         err = usb_submit_urb(urb, GFP_ATOMIC);
1234         if (err < 0) {
1235                 /* -EPERM: urb is being killed;
1236                  * -ENODEV: device got disconnected
1237                  */
1238                 if (err != -EPERM && err != -ENODEV)
1239                         bt_dev_err(hdev, "urb %p failed to resubmit (%d)",
1240                                    urb, -err);
1241                 usb_unanchor_urb(urb);
1242         }
1243 }
1244
1245 static int btusb_submit_diag_urb(struct hci_dev *hdev, gfp_t mem_flags)
1246 {
1247         struct btusb_data *data = hci_get_drvdata(hdev);
1248         struct urb *urb;
1249         unsigned char *buf;
1250         unsigned int pipe;
1251         int err, size = HCI_MAX_FRAME_SIZE;
1252
1253         BT_DBG("%s", hdev->name);
1254
1255         if (!data->diag_rx_ep)
1256                 return -ENODEV;
1257
1258         urb = usb_alloc_urb(0, mem_flags);
1259         if (!urb)
1260                 return -ENOMEM;
1261
1262         buf = kmalloc(size, mem_flags);
1263         if (!buf) {
1264                 usb_free_urb(urb);
1265                 return -ENOMEM;
1266         }
1267
1268         pipe = usb_rcvbulkpipe(data->udev, data->diag_rx_ep->bEndpointAddress);
1269
1270         usb_fill_bulk_urb(urb, data->udev, pipe, buf, size,
1271                           btusb_diag_complete, hdev);
1272
1273         urb->transfer_flags |= URB_FREE_BUFFER;
1274
1275         usb_mark_last_busy(data->udev);
1276         usb_anchor_urb(urb, &data->diag_anchor);
1277
1278         err = usb_submit_urb(urb, mem_flags);
1279         if (err < 0) {
1280                 if (err != -EPERM && err != -ENODEV)
1281                         bt_dev_err(hdev, "urb %p submission failed (%d)",
1282                                    urb, -err);
1283                 usb_unanchor_urb(urb);
1284         }
1285
1286         usb_free_urb(urb);
1287
1288         return err;
1289 }
1290
1291 static void btusb_tx_complete(struct urb *urb)
1292 {
1293         struct sk_buff *skb = urb->context;
1294         struct hci_dev *hdev = (struct hci_dev *)skb->dev;
1295         struct btusb_data *data = hci_get_drvdata(hdev);
1296         unsigned long flags;
1297
1298         BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status,
1299                urb->actual_length);
1300
1301         if (!test_bit(HCI_RUNNING, &hdev->flags))
1302                 goto done;
1303
1304         if (!urb->status)
1305                 hdev->stat.byte_tx += urb->transfer_buffer_length;
1306         else
1307                 hdev->stat.err_tx++;
1308
1309 done:
1310         spin_lock_irqsave(&data->txlock, flags);
1311         data->tx_in_flight--;
1312         spin_unlock_irqrestore(&data->txlock, flags);
1313
1314         kfree(urb->setup_packet);
1315
1316         kfree_skb(skb);
1317 }
1318
1319 static void btusb_isoc_tx_complete(struct urb *urb)
1320 {
1321         struct sk_buff *skb = urb->context;
1322         struct hci_dev *hdev = (struct hci_dev *)skb->dev;
1323
1324         BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status,
1325                urb->actual_length);
1326
1327         if (!test_bit(HCI_RUNNING, &hdev->flags))
1328                 goto done;
1329
1330         if (!urb->status)
1331                 hdev->stat.byte_tx += urb->transfer_buffer_length;
1332         else
1333                 hdev->stat.err_tx++;
1334
1335 done:
1336         kfree(urb->setup_packet);
1337
1338         kfree_skb(skb);
1339 }
1340
1341 static int btusb_open(struct hci_dev *hdev)
1342 {
1343         struct btusb_data *data = hci_get_drvdata(hdev);
1344         int err;
1345
1346         BT_DBG("%s", hdev->name);
1347
1348         err = usb_autopm_get_interface(data->intf);
1349         if (err < 0)
1350                 return err;
1351
1352         /* Patching USB firmware files prior to starting any URBs of HCI path
1353          * It is more safe to use USB bulk channel for downloading USB patch
1354          */
1355         if (data->setup_on_usb) {
1356                 err = data->setup_on_usb(hdev);
1357                 if (err < 0)
1358                         goto setup_fail;
1359         }
1360
1361         data->intf->needs_remote_wakeup = 1;
1362
1363         /* Disable device remote wakeup when host is suspended
1364          * For Realtek chips, global suspend without
1365          * SET_FEATURE (DEVICE_REMOTE_WAKEUP) can save more power in device.
1366          */
1367         if (test_bit(BTUSB_WAKEUP_DISABLE, &data->flags))
1368                 device_wakeup_disable(&data->udev->dev);
1369
1370         if (test_and_set_bit(BTUSB_INTR_RUNNING, &data->flags))
1371                 goto done;
1372
1373         err = btusb_submit_intr_urb(hdev, GFP_KERNEL);
1374         if (err < 0)
1375                 goto failed;
1376
1377         err = btusb_submit_bulk_urb(hdev, GFP_KERNEL);
1378         if (err < 0) {
1379                 usb_kill_anchored_urbs(&data->intr_anchor);
1380                 goto failed;
1381         }
1382
1383         set_bit(BTUSB_BULK_RUNNING, &data->flags);
1384         btusb_submit_bulk_urb(hdev, GFP_KERNEL);
1385
1386         if (data->diag) {
1387                 if (!btusb_submit_diag_urb(hdev, GFP_KERNEL))
1388                         set_bit(BTUSB_DIAG_RUNNING, &data->flags);
1389         }
1390
1391 done:
1392         usb_autopm_put_interface(data->intf);
1393         return 0;
1394
1395 failed:
1396         clear_bit(BTUSB_INTR_RUNNING, &data->flags);
1397 setup_fail:
1398         usb_autopm_put_interface(data->intf);
1399         return err;
1400 }
1401
1402 static void btusb_stop_traffic(struct btusb_data *data)
1403 {
1404         usb_kill_anchored_urbs(&data->intr_anchor);
1405         usb_kill_anchored_urbs(&data->bulk_anchor);
1406         usb_kill_anchored_urbs(&data->isoc_anchor);
1407         usb_kill_anchored_urbs(&data->diag_anchor);
1408         usb_kill_anchored_urbs(&data->ctrl_anchor);
1409 }
1410
1411 static int btusb_close(struct hci_dev *hdev)
1412 {
1413         struct btusb_data *data = hci_get_drvdata(hdev);
1414         int err;
1415
1416         BT_DBG("%s", hdev->name);
1417
1418         cancel_work_sync(&data->work);
1419         cancel_work_sync(&data->waker);
1420
1421         clear_bit(BTUSB_ISOC_RUNNING, &data->flags);
1422         clear_bit(BTUSB_BULK_RUNNING, &data->flags);
1423         clear_bit(BTUSB_INTR_RUNNING, &data->flags);
1424         clear_bit(BTUSB_DIAG_RUNNING, &data->flags);
1425
1426         btusb_stop_traffic(data);
1427         btusb_free_frags(data);
1428
1429         err = usb_autopm_get_interface(data->intf);
1430         if (err < 0)
1431                 goto failed;
1432
1433         data->intf->needs_remote_wakeup = 0;
1434
1435         /* Enable remote wake up for auto-suspend */
1436         if (test_bit(BTUSB_WAKEUP_DISABLE, &data->flags))
1437                 data->intf->needs_remote_wakeup = 1;
1438
1439         usb_autopm_put_interface(data->intf);
1440
1441 failed:
1442         usb_scuttle_anchored_urbs(&data->deferred);
1443         return 0;
1444 }
1445
1446 static int btusb_flush(struct hci_dev *hdev)
1447 {
1448         struct btusb_data *data = hci_get_drvdata(hdev);
1449
1450         BT_DBG("%s", hdev->name);
1451
1452         usb_kill_anchored_urbs(&data->tx_anchor);
1453         btusb_free_frags(data);
1454
1455         return 0;
1456 }
1457
1458 static struct urb *alloc_ctrl_urb(struct hci_dev *hdev, struct sk_buff *skb)
1459 {
1460         struct btusb_data *data = hci_get_drvdata(hdev);
1461         struct usb_ctrlrequest *dr;
1462         struct urb *urb;
1463         unsigned int pipe;
1464
1465         urb = usb_alloc_urb(0, GFP_KERNEL);
1466         if (!urb)
1467                 return ERR_PTR(-ENOMEM);
1468
1469         dr = kmalloc(sizeof(*dr), GFP_KERNEL);
1470         if (!dr) {
1471                 usb_free_urb(urb);
1472                 return ERR_PTR(-ENOMEM);
1473         }
1474
1475         dr->bRequestType = data->cmdreq_type;
1476         dr->bRequest     = data->cmdreq;
1477         dr->wIndex       = 0;
1478         dr->wValue       = 0;
1479         dr->wLength      = __cpu_to_le16(skb->len);
1480
1481         pipe = usb_sndctrlpipe(data->udev, 0x00);
1482
1483         usb_fill_control_urb(urb, data->udev, pipe, (void *)dr,
1484                              skb->data, skb->len, btusb_tx_complete, skb);
1485
1486         skb->dev = (void *)hdev;
1487
1488         return urb;
1489 }
1490
1491 static struct urb *alloc_bulk_urb(struct hci_dev *hdev, struct sk_buff *skb)
1492 {
1493         struct btusb_data *data = hci_get_drvdata(hdev);
1494         struct urb *urb;
1495         unsigned int pipe;
1496
1497         if (!data->bulk_tx_ep)
1498                 return ERR_PTR(-ENODEV);
1499
1500         urb = usb_alloc_urb(0, GFP_KERNEL);
1501         if (!urb)
1502                 return ERR_PTR(-ENOMEM);
1503
1504         pipe = usb_sndbulkpipe(data->udev, data->bulk_tx_ep->bEndpointAddress);
1505
1506         usb_fill_bulk_urb(urb, data->udev, pipe,
1507                           skb->data, skb->len, btusb_tx_complete, skb);
1508
1509         skb->dev = (void *)hdev;
1510
1511         return urb;
1512 }
1513
1514 static struct urb *alloc_isoc_urb(struct hci_dev *hdev, struct sk_buff *skb)
1515 {
1516         struct btusb_data *data = hci_get_drvdata(hdev);
1517         struct urb *urb;
1518         unsigned int pipe;
1519
1520         if (!data->isoc_tx_ep)
1521                 return ERR_PTR(-ENODEV);
1522
1523         urb = usb_alloc_urb(BTUSB_MAX_ISOC_FRAMES, GFP_KERNEL);
1524         if (!urb)
1525                 return ERR_PTR(-ENOMEM);
1526
1527         pipe = usb_sndisocpipe(data->udev, data->isoc_tx_ep->bEndpointAddress);
1528
1529         usb_fill_int_urb(urb, data->udev, pipe,
1530                          skb->data, skb->len, btusb_isoc_tx_complete,
1531                          skb, data->isoc_tx_ep->bInterval);
1532
1533         urb->transfer_flags  = URB_ISO_ASAP;
1534
1535         if (data->isoc_altsetting == 6)
1536                 __fill_isoc_descriptor_msbc(urb, skb->len,
1537                                             le16_to_cpu(data->isoc_tx_ep->wMaxPacketSize),
1538                                             data);
1539         else
1540                 __fill_isoc_descriptor(urb, skb->len,
1541                                        le16_to_cpu(data->isoc_tx_ep->wMaxPacketSize));
1542         skb->dev = (void *)hdev;
1543
1544         return urb;
1545 }
1546
1547 static int submit_tx_urb(struct hci_dev *hdev, struct urb *urb)
1548 {
1549         struct btusb_data *data = hci_get_drvdata(hdev);
1550         int err;
1551
1552         usb_anchor_urb(urb, &data->tx_anchor);
1553
1554         err = usb_submit_urb(urb, GFP_KERNEL);
1555         if (err < 0) {
1556                 if (err != -EPERM && err != -ENODEV)
1557                         bt_dev_err(hdev, "urb %p submission failed (%d)",
1558                                    urb, -err);
1559                 kfree(urb->setup_packet);
1560                 usb_unanchor_urb(urb);
1561         } else {
1562                 usb_mark_last_busy(data->udev);
1563         }
1564
1565         usb_free_urb(urb);
1566         return err;
1567 }
1568
1569 static int submit_or_queue_tx_urb(struct hci_dev *hdev, struct urb *urb)
1570 {
1571         struct btusb_data *data = hci_get_drvdata(hdev);
1572         unsigned long flags;
1573         bool suspending;
1574
1575         spin_lock_irqsave(&data->txlock, flags);
1576         suspending = test_bit(BTUSB_SUSPENDING, &data->flags);
1577         if (!suspending)
1578                 data->tx_in_flight++;
1579         spin_unlock_irqrestore(&data->txlock, flags);
1580
1581         if (!suspending)
1582                 return submit_tx_urb(hdev, urb);
1583
1584         usb_anchor_urb(urb, &data->deferred);
1585         schedule_work(&data->waker);
1586
1587         usb_free_urb(urb);
1588         return 0;
1589 }
1590
1591 static int btusb_send_frame(struct hci_dev *hdev, struct sk_buff *skb)
1592 {
1593         struct urb *urb;
1594
1595         BT_DBG("%s", hdev->name);
1596
1597         switch (hci_skb_pkt_type(skb)) {
1598         case HCI_COMMAND_PKT:
1599                 urb = alloc_ctrl_urb(hdev, skb);
1600                 if (IS_ERR(urb))
1601                         return PTR_ERR(urb);
1602
1603                 hdev->stat.cmd_tx++;
1604                 return submit_or_queue_tx_urb(hdev, urb);
1605
1606         case HCI_ACLDATA_PKT:
1607                 urb = alloc_bulk_urb(hdev, skb);
1608                 if (IS_ERR(urb))
1609                         return PTR_ERR(urb);
1610
1611                 hdev->stat.acl_tx++;
1612                 return submit_or_queue_tx_urb(hdev, urb);
1613
1614         case HCI_SCODATA_PKT:
1615                 if (hci_conn_num(hdev, SCO_LINK) < 1)
1616                         return -ENODEV;
1617
1618                 urb = alloc_isoc_urb(hdev, skb);
1619                 if (IS_ERR(urb))
1620                         return PTR_ERR(urb);
1621
1622                 hdev->stat.sco_tx++;
1623                 return submit_tx_urb(hdev, urb);
1624         }
1625
1626         return -EILSEQ;
1627 }
1628
1629 static void btusb_notify(struct hci_dev *hdev, unsigned int evt)
1630 {
1631         struct btusb_data *data = hci_get_drvdata(hdev);
1632
1633         BT_DBG("%s evt %d", hdev->name, evt);
1634
1635         if (hci_conn_num(hdev, SCO_LINK) != data->sco_num) {
1636                 data->sco_num = hci_conn_num(hdev, SCO_LINK);
1637                 data->air_mode = evt;
1638                 schedule_work(&data->work);
1639         }
1640 }
1641
1642 static inline int __set_isoc_interface(struct hci_dev *hdev, int altsetting)
1643 {
1644         struct btusb_data *data = hci_get_drvdata(hdev);
1645         struct usb_interface *intf = data->isoc;
1646         struct usb_endpoint_descriptor *ep_desc;
1647         int i, err;
1648
1649         if (!data->isoc)
1650                 return -ENODEV;
1651
1652         err = usb_set_interface(data->udev, data->isoc_ifnum, altsetting);
1653         if (err < 0) {
1654                 bt_dev_err(hdev, "setting interface failed (%d)", -err);
1655                 return err;
1656         }
1657
1658         data->isoc_altsetting = altsetting;
1659
1660         data->isoc_tx_ep = NULL;
1661         data->isoc_rx_ep = NULL;
1662
1663         for (i = 0; i < intf->cur_altsetting->desc.bNumEndpoints; i++) {
1664                 ep_desc = &intf->cur_altsetting->endpoint[i].desc;
1665
1666                 if (!data->isoc_tx_ep && usb_endpoint_is_isoc_out(ep_desc)) {
1667                         data->isoc_tx_ep = ep_desc;
1668                         continue;
1669                 }
1670
1671                 if (!data->isoc_rx_ep && usb_endpoint_is_isoc_in(ep_desc)) {
1672                         data->isoc_rx_ep = ep_desc;
1673                         continue;
1674                 }
1675         }
1676
1677         if (!data->isoc_tx_ep || !data->isoc_rx_ep) {
1678                 bt_dev_err(hdev, "invalid SCO descriptors");
1679                 return -ENODEV;
1680         }
1681
1682         return 0;
1683 }
1684
1685 static int btusb_switch_alt_setting(struct hci_dev *hdev, int new_alts)
1686 {
1687         struct btusb_data *data = hci_get_drvdata(hdev);
1688         int err;
1689
1690         if (data->isoc_altsetting != new_alts) {
1691                 unsigned long flags;
1692
1693                 clear_bit(BTUSB_ISOC_RUNNING, &data->flags);
1694                 usb_kill_anchored_urbs(&data->isoc_anchor);
1695
1696                 /* When isochronous alternate setting needs to be
1697                  * changed, because SCO connection has been added
1698                  * or removed, a packet fragment may be left in the
1699                  * reassembling state. This could lead to wrongly
1700                  * assembled fragments.
1701                  *
1702                  * Clear outstanding fragment when selecting a new
1703                  * alternate setting.
1704                  */
1705                 spin_lock_irqsave(&data->rxlock, flags);
1706                 dev_kfree_skb_irq(data->sco_skb);
1707                 data->sco_skb = NULL;
1708                 spin_unlock_irqrestore(&data->rxlock, flags);
1709
1710                 err = __set_isoc_interface(hdev, new_alts);
1711                 if (err < 0)
1712                         return err;
1713         }
1714
1715         if (!test_and_set_bit(BTUSB_ISOC_RUNNING, &data->flags)) {
1716                 if (btusb_submit_isoc_urb(hdev, GFP_KERNEL) < 0)
1717                         clear_bit(BTUSB_ISOC_RUNNING, &data->flags);
1718                 else
1719                         btusb_submit_isoc_urb(hdev, GFP_KERNEL);
1720         }
1721
1722         return 0;
1723 }
1724
1725 static struct usb_host_interface *btusb_find_altsetting(struct btusb_data *data,
1726                                                         int alt)
1727 {
1728         struct usb_interface *intf = data->isoc;
1729         int i;
1730
1731         BT_DBG("Looking for Alt no :%d", alt);
1732
1733         if (!intf)
1734                 return NULL;
1735
1736         for (i = 0; i < intf->num_altsetting; i++) {
1737                 if (intf->altsetting[i].desc.bAlternateSetting == alt)
1738                         return &intf->altsetting[i];
1739         }
1740
1741         return NULL;
1742 }
1743
1744 static void btusb_work(struct work_struct *work)
1745 {
1746         struct btusb_data *data = container_of(work, struct btusb_data, work);
1747         struct hci_dev *hdev = data->hdev;
1748         int new_alts = 0;
1749         int err;
1750
1751         if (data->sco_num > 0) {
1752                 if (!test_bit(BTUSB_DID_ISO_RESUME, &data->flags)) {
1753                         err = usb_autopm_get_interface(data->isoc ? data->isoc : data->intf);
1754                         if (err < 0) {
1755                                 clear_bit(BTUSB_ISOC_RUNNING, &data->flags);
1756                                 usb_kill_anchored_urbs(&data->isoc_anchor);
1757                                 return;
1758                         }
1759
1760                         set_bit(BTUSB_DID_ISO_RESUME, &data->flags);
1761                 }
1762
1763                 if (data->air_mode == HCI_NOTIFY_ENABLE_SCO_CVSD) {
1764                         if (hdev->voice_setting & 0x0020) {
1765                                 static const int alts[3] = { 2, 4, 5 };
1766
1767                                 new_alts = alts[data->sco_num - 1];
1768                         } else {
1769                                 new_alts = data->sco_num;
1770                         }
1771                 } else if (data->air_mode == HCI_NOTIFY_ENABLE_SCO_TRANSP) {
1772                         /* Bluetooth USB spec recommends alt 6 (63 bytes), but
1773                          * many adapters do not support it.  Alt 1 appears to
1774                          * work for all adapters that do not have alt 6, and
1775                          * which work with WBS at all.  Some devices prefer
1776                          * alt 3 (HCI payload >= 60 Bytes let air packet
1777                          * data satisfy 60 bytes), requiring
1778                          * MTU >= 3 (packets) * 25 (size) - 3 (headers) = 72
1779                          * see also Core spec 5, vol 4, B 2.1.1 & Table 2.1.
1780                          */
1781                         if (btusb_find_altsetting(data, 6))
1782                                 new_alts = 6;
1783                         else if (btusb_find_altsetting(data, 3) &&
1784                                  hdev->sco_mtu >= 72 &&
1785                                  test_bit(BTUSB_USE_ALT3_FOR_WBS, &data->flags))
1786                                 new_alts = 3;
1787                         else
1788                                 new_alts = 1;
1789                 }
1790
1791                 if (btusb_switch_alt_setting(hdev, new_alts) < 0)
1792                         bt_dev_err(hdev, "set USB alt:(%d) failed!", new_alts);
1793         } else {
1794                 clear_bit(BTUSB_ISOC_RUNNING, &data->flags);
1795                 usb_kill_anchored_urbs(&data->isoc_anchor);
1796
1797                 __set_isoc_interface(hdev, 0);
1798                 if (test_and_clear_bit(BTUSB_DID_ISO_RESUME, &data->flags))
1799                         usb_autopm_put_interface(data->isoc ? data->isoc : data->intf);
1800         }
1801 }
1802
1803 static void btusb_waker(struct work_struct *work)
1804 {
1805         struct btusb_data *data = container_of(work, struct btusb_data, waker);
1806         int err;
1807
1808         err = usb_autopm_get_interface(data->intf);
1809         if (err < 0)
1810                 return;
1811
1812         usb_autopm_put_interface(data->intf);
1813 }
1814
1815 static int btusb_setup_bcm92035(struct hci_dev *hdev)
1816 {
1817         struct sk_buff *skb;
1818         u8 val = 0x00;
1819
1820         BT_DBG("%s", hdev->name);
1821
1822         skb = __hci_cmd_sync(hdev, 0xfc3b, 1, &val, HCI_INIT_TIMEOUT);
1823         if (IS_ERR(skb))
1824                 bt_dev_err(hdev, "BCM92035 command failed (%ld)", PTR_ERR(skb));
1825         else
1826                 kfree_skb(skb);
1827
1828         return 0;
1829 }
1830
1831 static int btusb_setup_csr(struct hci_dev *hdev)
1832 {
1833         struct btusb_data *data = hci_get_drvdata(hdev);
1834         u16 bcdDevice = le16_to_cpu(data->udev->descriptor.bcdDevice);
1835         struct hci_rp_read_local_version *rp;
1836         struct sk_buff *skb;
1837         bool is_fake = false;
1838
1839         BT_DBG("%s", hdev->name);
1840
1841         skb = __hci_cmd_sync(hdev, HCI_OP_READ_LOCAL_VERSION, 0, NULL,
1842                              HCI_INIT_TIMEOUT);
1843         if (IS_ERR(skb)) {
1844                 int err = PTR_ERR(skb);
1845                 bt_dev_err(hdev, "CSR: Local version failed (%d)", err);
1846                 return err;
1847         }
1848
1849         if (skb->len != sizeof(struct hci_rp_read_local_version)) {
1850                 bt_dev_err(hdev, "CSR: Local version length mismatch");
1851                 kfree_skb(skb);
1852                 return -EIO;
1853         }
1854
1855         rp = (struct hci_rp_read_local_version *)skb->data;
1856
1857         bt_dev_info(hdev, "CSR: Setting up dongle with HCI ver=%u rev=%04x; LMP ver=%u subver=%04x; manufacturer=%u",
1858                 le16_to_cpu(rp->hci_ver), le16_to_cpu(rp->hci_rev),
1859                 le16_to_cpu(rp->lmp_ver), le16_to_cpu(rp->lmp_subver),
1860                 le16_to_cpu(rp->manufacturer));
1861
1862         /* Detect a wide host of Chinese controllers that aren't CSR.
1863          *
1864          * Known fake bcdDevices: 0x0100, 0x0134, 0x1915, 0x2520, 0x7558, 0x8891
1865          *
1866          * The main thing they have in common is that these are really popular low-cost
1867          * options that support newer Bluetooth versions but rely on heavy VID/PID
1868          * squatting of this poor old Bluetooth 1.1 device. Even sold as such.
1869          *
1870          * We detect actual CSR devices by checking that the HCI manufacturer code
1871          * is Cambridge Silicon Radio (10) and ensuring that LMP sub-version and
1872          * HCI rev values always match. As they both store the firmware number.
1873          */
1874         if (le16_to_cpu(rp->manufacturer) != 10 ||
1875             le16_to_cpu(rp->hci_rev) != le16_to_cpu(rp->lmp_subver))
1876                 is_fake = true;
1877
1878         /* Known legit CSR firmware build numbers and their supported BT versions:
1879          * - 1.1 (0x1) -> 0x0073, 0x020d, 0x033c, 0x034e
1880          * - 1.2 (0x2) ->                 0x04d9, 0x0529
1881          * - 2.0 (0x3) ->         0x07a6, 0x07ad, 0x0c5c
1882          * - 2.1 (0x4) ->         0x149c, 0x1735, 0x1899 (0x1899 is a BlueCore4-External)
1883          * - 4.0 (0x6) ->         0x1d86, 0x2031, 0x22bb
1884          *
1885          * e.g. Real CSR dongles with LMP subversion 0x73 are old enough that
1886          *      support BT 1.1 only; so it's a dead giveaway when some
1887          *      third-party BT 4.0 dongle reuses it.
1888          */
1889         else if (le16_to_cpu(rp->lmp_subver) <= 0x034e &&
1890                  le16_to_cpu(rp->hci_ver) > BLUETOOTH_VER_1_1)
1891                 is_fake = true;
1892
1893         else if (le16_to_cpu(rp->lmp_subver) <= 0x0529 &&
1894                  le16_to_cpu(rp->hci_ver) > BLUETOOTH_VER_1_2)
1895                 is_fake = true;
1896
1897         else if (le16_to_cpu(rp->lmp_subver) <= 0x0c5c &&
1898                  le16_to_cpu(rp->hci_ver) > BLUETOOTH_VER_2_0)
1899                 is_fake = true;
1900
1901         else if (le16_to_cpu(rp->lmp_subver) <= 0x1899 &&
1902                  le16_to_cpu(rp->hci_ver) > BLUETOOTH_VER_2_1)
1903                 is_fake = true;
1904
1905         else if (le16_to_cpu(rp->lmp_subver) <= 0x22bb &&
1906                  le16_to_cpu(rp->hci_ver) > BLUETOOTH_VER_4_0)
1907                 is_fake = true;
1908
1909         /* Other clones which beat all the above checks */
1910         else if (bcdDevice == 0x0134 &&
1911                  le16_to_cpu(rp->lmp_subver) == 0x0c5c &&
1912                  le16_to_cpu(rp->hci_ver) == BLUETOOTH_VER_2_0)
1913                 is_fake = true;
1914
1915         if (is_fake) {
1916                 bt_dev_warn(hdev, "CSR: Unbranded CSR clone detected; adding workarounds...");
1917
1918                 /* Generally these clones have big discrepancies between
1919                  * advertised features and what's actually supported.
1920                  * Probably will need to be expanded in the future;
1921                  * without these the controller will lock up.
1922                  */
1923                 set_bit(HCI_QUIRK_BROKEN_STORED_LINK_KEY, &hdev->quirks);
1924                 set_bit(HCI_QUIRK_BROKEN_ERR_DATA_REPORTING, &hdev->quirks);
1925
1926                 /* Clear the reset quirk since this is not an actual
1927                  * early Bluetooth 1.1 device from CSR.
1928                  */
1929                 clear_bit(HCI_QUIRK_RESET_ON_CLOSE, &hdev->quirks);
1930                 clear_bit(HCI_QUIRK_SIMULTANEOUS_DISCOVERY, &hdev->quirks);
1931         }
1932
1933         kfree_skb(skb);
1934
1935         return 0;
1936 }
1937
1938 static const struct firmware *btusb_setup_intel_get_fw(struct hci_dev *hdev,
1939                                                        struct intel_version *ver)
1940 {
1941         const struct firmware *fw;
1942         char fwname[64];
1943         int ret;
1944
1945         snprintf(fwname, sizeof(fwname),
1946                  "/*(DEBLOBBED)*/",
1947                  ver->hw_platform, ver->hw_variant, ver->hw_revision,
1948                  ver->fw_variant,  ver->fw_revision, ver->fw_build_num,
1949                  ver->fw_build_ww, ver->fw_build_yy);
1950
1951         ret = reject_firmware(&fw, fwname, &hdev->dev);
1952         if (ret < 0) {
1953                 if (ret == -EINVAL) {
1954                         bt_dev_err(hdev, "Intel firmware file request failed (%d)",
1955                                    ret);
1956                         return NULL;
1957                 }
1958
1959                 bt_dev_err(hdev, "failed to open Intel firmware file: %s (%d)",
1960                            fwname, ret);
1961
1962                 /* If the correct firmware patch file is not found, use the
1963                  * default firmware patch file instead
1964                  */
1965                 snprintf(fwname, sizeof(fwname), "/*(DEBLOBBED)*/",
1966                          ver->hw_platform, ver->hw_variant);
1967                 if (reject_firmware(&fw, fwname, &hdev->dev) < 0) {
1968                         bt_dev_err(hdev, "failed to open default fw file: %s",
1969                                    fwname);
1970                         return NULL;
1971                 }
1972         }
1973
1974         bt_dev_info(hdev, "Intel Bluetooth firmware file: %s", fwname);
1975
1976         return fw;
1977 }
1978
1979 static int btusb_setup_intel_patching(struct hci_dev *hdev,
1980                                       const struct firmware *fw,
1981                                       const u8 **fw_ptr, int *disable_patch)
1982 {
1983         struct sk_buff *skb;
1984         struct hci_command_hdr *cmd;
1985         const u8 *cmd_param;
1986         struct hci_event_hdr *evt = NULL;
1987         const u8 *evt_param = NULL;
1988         int remain = fw->size - (*fw_ptr - fw->data);
1989
1990         /* The first byte indicates the types of the patch command or event.
1991          * 0x01 means HCI command and 0x02 is HCI event. If the first bytes
1992          * in the current firmware buffer doesn't start with 0x01 or
1993          * the size of remain buffer is smaller than HCI command header,
1994          * the firmware file is corrupted and it should stop the patching
1995          * process.
1996          */
1997         if (remain > HCI_COMMAND_HDR_SIZE && *fw_ptr[0] != 0x01) {
1998                 bt_dev_err(hdev, "Intel fw corrupted: invalid cmd read");
1999                 return -EINVAL;
2000         }
2001         (*fw_ptr)++;
2002         remain--;
2003
2004         cmd = (struct hci_command_hdr *)(*fw_ptr);
2005         *fw_ptr += sizeof(*cmd);
2006         remain -= sizeof(*cmd);
2007
2008         /* Ensure that the remain firmware data is long enough than the length
2009          * of command parameter. If not, the firmware file is corrupted.
2010          */
2011         if (remain < cmd->plen) {
2012                 bt_dev_err(hdev, "Intel fw corrupted: invalid cmd len");
2013                 return -EFAULT;
2014         }
2015
2016         /* If there is a command that loads a patch in the firmware
2017          * file, then enable the patch upon success, otherwise just
2018          * disable the manufacturer mode, for example patch activation
2019          * is not required when the default firmware patch file is used
2020          * because there are no patch data to load.
2021          */
2022         if (*disable_patch && le16_to_cpu(cmd->opcode) == 0xfc8e)
2023                 *disable_patch = 0;
2024
2025         cmd_param = *fw_ptr;
2026         *fw_ptr += cmd->plen;
2027         remain -= cmd->plen;
2028
2029         /* This reads the expected events when the above command is sent to the
2030          * device. Some vendor commands expects more than one events, for
2031          * example command status event followed by vendor specific event.
2032          * For this case, it only keeps the last expected event. so the command
2033          * can be sent with __hci_cmd_sync_ev() which returns the sk_buff of
2034          * last expected event.
2035          */
2036         while (remain > HCI_EVENT_HDR_SIZE && *fw_ptr[0] == 0x02) {
2037                 (*fw_ptr)++;
2038                 remain--;
2039
2040                 evt = (struct hci_event_hdr *)(*fw_ptr);
2041                 *fw_ptr += sizeof(*evt);
2042                 remain -= sizeof(*evt);
2043
2044                 if (remain < evt->plen) {
2045                         bt_dev_err(hdev, "Intel fw corrupted: invalid evt len");
2046                         return -EFAULT;
2047                 }
2048
2049                 evt_param = *fw_ptr;
2050                 *fw_ptr += evt->plen;
2051                 remain -= evt->plen;
2052         }
2053
2054         /* Every HCI commands in the firmware file has its correspond event.
2055          * If event is not found or remain is smaller than zero, the firmware
2056          * file is corrupted.
2057          */
2058         if (!evt || !evt_param || remain < 0) {
2059                 bt_dev_err(hdev, "Intel fw corrupted: invalid evt read");
2060                 return -EFAULT;
2061         }
2062
2063         skb = __hci_cmd_sync_ev(hdev, le16_to_cpu(cmd->opcode), cmd->plen,
2064                                 cmd_param, evt->evt, HCI_INIT_TIMEOUT);
2065         if (IS_ERR(skb)) {
2066                 bt_dev_err(hdev, "sending Intel patch command (0x%4.4x) failed (%ld)",
2067                            cmd->opcode, PTR_ERR(skb));
2068                 return PTR_ERR(skb);
2069         }
2070
2071         /* It ensures that the returned event matches the event data read from
2072          * the firmware file. At fist, it checks the length and then
2073          * the contents of the event.
2074          */
2075         if (skb->len != evt->plen) {
2076                 bt_dev_err(hdev, "mismatch event length (opcode 0x%4.4x)",
2077                            le16_to_cpu(cmd->opcode));
2078                 kfree_skb(skb);
2079                 return -EFAULT;
2080         }
2081
2082         if (memcmp(skb->data, evt_param, evt->plen)) {
2083                 bt_dev_err(hdev, "mismatch event parameter (opcode 0x%4.4x)",
2084                            le16_to_cpu(cmd->opcode));
2085                 kfree_skb(skb);
2086                 return -EFAULT;
2087         }
2088         kfree_skb(skb);
2089
2090         return 0;
2091 }
2092
2093 static int btusb_setup_intel(struct hci_dev *hdev)
2094 {
2095         struct sk_buff *skb;
2096         const struct firmware *fw;
2097         const u8 *fw_ptr;
2098         int disable_patch, err;
2099         struct intel_version ver;
2100
2101         BT_DBG("%s", hdev->name);
2102
2103         /* The controller has a bug with the first HCI command sent to it
2104          * returning number of completed commands as zero. This would stall the
2105          * command processing in the Bluetooth core.
2106          *
2107          * As a workaround, send HCI Reset command first which will reset the
2108          * number of completed commands and allow normal command processing
2109          * from now on.
2110          */
2111         skb = __hci_cmd_sync(hdev, HCI_OP_RESET, 0, NULL, HCI_INIT_TIMEOUT);
2112         if (IS_ERR(skb)) {
2113                 bt_dev_err(hdev, "sending initial HCI reset command failed (%ld)",
2114                            PTR_ERR(skb));
2115                 return PTR_ERR(skb);
2116         }
2117         kfree_skb(skb);
2118
2119         /* Read Intel specific controller version first to allow selection of
2120          * which firmware file to load.
2121          *
2122          * The returned information are hardware variant and revision plus
2123          * firmware variant, revision and build number.
2124          */
2125         err = btintel_read_version(hdev, &ver);
2126         if (err)
2127                 return err;
2128
2129         bt_dev_info(hdev, "read Intel version: %02x%02x%02x%02x%02x%02x%02x%02x%02x",
2130                     ver.hw_platform, ver.hw_variant, ver.hw_revision,
2131                     ver.fw_variant,  ver.fw_revision, ver.fw_build_num,
2132                     ver.fw_build_ww, ver.fw_build_yy, ver.fw_patch_num);
2133
2134         /* fw_patch_num indicates the version of patch the device currently
2135          * have. If there is no patch data in the device, it is always 0x00.
2136          * So, if it is other than 0x00, no need to patch the device again.
2137          */
2138         if (ver.fw_patch_num) {
2139                 bt_dev_info(hdev, "Intel device is already patched. "
2140                             "patch num: %02x", ver.fw_patch_num);
2141                 goto complete;
2142         }
2143
2144         /* Opens the firmware patch file based on the firmware version read
2145          * from the controller. If it fails to open the matching firmware
2146          * patch file, it tries to open the default firmware patch file.
2147          * If no patch file is found, allow the device to operate without
2148          * a patch.
2149          */
2150         fw = btusb_setup_intel_get_fw(hdev, &ver);
2151         if (!fw)
2152                 goto complete;
2153         fw_ptr = fw->data;
2154
2155         /* Enable the manufacturer mode of the controller.
2156          * Only while this mode is enabled, the driver can download the
2157          * firmware patch data and configuration parameters.
2158          */
2159         err = btintel_enter_mfg(hdev);
2160         if (err) {
2161                 release_firmware(fw);
2162                 return err;
2163         }
2164
2165         disable_patch = 1;
2166
2167         /* The firmware data file consists of list of Intel specific HCI
2168          * commands and its expected events. The first byte indicates the
2169          * type of the message, either HCI command or HCI event.
2170          *
2171          * It reads the command and its expected event from the firmware file,
2172          * and send to the controller. Once __hci_cmd_sync_ev() returns,
2173          * the returned event is compared with the event read from the firmware
2174          * file and it will continue until all the messages are downloaded to
2175          * the controller.
2176          *
2177          * Once the firmware patching is completed successfully,
2178          * the manufacturer mode is disabled with reset and activating the
2179          * downloaded patch.
2180          *
2181          * If the firmware patching fails, the manufacturer mode is
2182          * disabled with reset and deactivating the patch.
2183          *
2184          * If the default patch file is used, no reset is done when disabling
2185          * the manufacturer.
2186          */
2187         while (fw->size > fw_ptr - fw->data) {
2188                 int ret;
2189
2190                 ret = btusb_setup_intel_patching(hdev, fw, &fw_ptr,
2191                                                  &disable_patch);
2192                 if (ret < 0)
2193                         goto exit_mfg_deactivate;
2194         }
2195
2196         release_firmware(fw);
2197
2198         if (disable_patch)
2199                 goto exit_mfg_disable;
2200
2201         /* Patching completed successfully and disable the manufacturer mode
2202          * with reset and activate the downloaded firmware patches.
2203          */
2204         err = btintel_exit_mfg(hdev, true, true);
2205         if (err)
2206                 return err;
2207
2208         /* Need build number for downloaded fw patches in
2209          * every power-on boot
2210          */
2211        err = btintel_read_version(hdev, &ver);
2212        if (err)
2213                return err;
2214        bt_dev_info(hdev, "Intel BT fw patch 0x%02x completed & activated",
2215                    ver.fw_patch_num);
2216
2217         goto complete;
2218
2219 exit_mfg_disable:
2220         /* Disable the manufacturer mode without reset */
2221         err = btintel_exit_mfg(hdev, false, false);
2222         if (err)
2223                 return err;
2224
2225         bt_dev_info(hdev, "Intel firmware patch completed");
2226
2227         goto complete;
2228
2229 exit_mfg_deactivate:
2230         release_firmware(fw);
2231
2232         /* Patching failed. Disable the manufacturer mode with reset and
2233          * deactivate the downloaded firmware patches.
2234          */
2235         err = btintel_exit_mfg(hdev, true, false);
2236         if (err)
2237                 return err;
2238
2239         bt_dev_info(hdev, "Intel firmware patch completed and deactivated");
2240
2241 complete:
2242         /* Set the event mask for Intel specific vendor events. This enables
2243          * a few extra events that are useful during general operation.
2244          */
2245         btintel_set_event_mask_mfg(hdev, false);
2246
2247         btintel_check_bdaddr(hdev);
2248         return 0;
2249 }
2250
2251 static int inject_cmd_complete(struct hci_dev *hdev, __u16 opcode)
2252 {
2253         struct sk_buff *skb;
2254         struct hci_event_hdr *hdr;
2255         struct hci_ev_cmd_complete *evt;
2256
2257         skb = bt_skb_alloc(sizeof(*hdr) + sizeof(*evt) + 1, GFP_KERNEL);
2258         if (!skb)
2259                 return -ENOMEM;
2260
2261         hdr = skb_put(skb, sizeof(*hdr));
2262         hdr->evt = HCI_EV_CMD_COMPLETE;
2263         hdr->plen = sizeof(*evt) + 1;
2264
2265         evt = skb_put(skb, sizeof(*evt));
2266         evt->ncmd = 0x01;
2267         evt->opcode = cpu_to_le16(opcode);
2268
2269         skb_put_u8(skb, 0x00);
2270
2271         hci_skb_pkt_type(skb) = HCI_EVENT_PKT;
2272
2273         return hci_recv_frame(hdev, skb);
2274 }
2275
2276 static int btusb_recv_bulk_intel(struct btusb_data *data, void *buffer,
2277                                  int count)
2278 {
2279         /* When the device is in bootloader mode, then it can send
2280          * events via the bulk endpoint. These events are treated the
2281          * same way as the ones received from the interrupt endpoint.
2282          */
2283         if (test_bit(BTUSB_BOOTLOADER, &data->flags))
2284                 return btusb_recv_intr(data, buffer, count);
2285
2286         return btusb_recv_bulk(data, buffer, count);
2287 }
2288
2289 static void btusb_intel_bootup(struct btusb_data *data, const void *ptr,
2290                                unsigned int len)
2291 {
2292         const struct intel_bootup *evt = ptr;
2293
2294         if (len != sizeof(*evt))
2295                 return;
2296
2297         if (test_and_clear_bit(BTUSB_BOOTING, &data->flags))
2298                 wake_up_bit(&data->flags, BTUSB_BOOTING);
2299 }
2300
2301 static void btusb_intel_secure_send_result(struct btusb_data *data,
2302                                            const void *ptr, unsigned int len)
2303 {
2304         const struct intel_secure_send_result *evt = ptr;
2305
2306         if (len != sizeof(*evt))
2307                 return;
2308
2309         if (evt->result)
2310                 set_bit(BTUSB_FIRMWARE_FAILED, &data->flags);
2311
2312         if (test_and_clear_bit(BTUSB_DOWNLOADING, &data->flags) &&
2313             test_bit(BTUSB_FIRMWARE_LOADED, &data->flags))
2314                 wake_up_bit(&data->flags, BTUSB_DOWNLOADING);
2315 }
2316
2317 static int btusb_recv_event_intel(struct hci_dev *hdev, struct sk_buff *skb)
2318 {
2319         struct btusb_data *data = hci_get_drvdata(hdev);
2320
2321         if (test_bit(BTUSB_BOOTLOADER, &data->flags)) {
2322                 struct hci_event_hdr *hdr = (void *)skb->data;
2323
2324                 if (skb->len > HCI_EVENT_HDR_SIZE && hdr->evt == 0xff &&
2325                     hdr->plen > 0) {
2326                         const void *ptr = skb->data + HCI_EVENT_HDR_SIZE + 1;
2327                         unsigned int len = skb->len - HCI_EVENT_HDR_SIZE - 1;
2328
2329                         switch (skb->data[2]) {
2330                         case 0x02:
2331                                 /* When switching to the operational firmware
2332                                  * the device sends a vendor specific event
2333                                  * indicating that the bootup completed.
2334                                  */
2335                                 btusb_intel_bootup(data, ptr, len);
2336                                 break;
2337                         case 0x06:
2338                                 /* When the firmware loading completes the
2339                                  * device sends out a vendor specific event
2340                                  * indicating the result of the firmware
2341                                  * loading.
2342                                  */
2343                                 btusb_intel_secure_send_result(data, ptr, len);
2344                                 break;
2345                         }
2346                 }
2347         }
2348
2349         return hci_recv_frame(hdev, skb);
2350 }
2351
2352 static int btusb_send_frame_intel(struct hci_dev *hdev, struct sk_buff *skb)
2353 {
2354         struct btusb_data *data = hci_get_drvdata(hdev);
2355         struct urb *urb;
2356
2357         BT_DBG("%s", hdev->name);
2358
2359         switch (hci_skb_pkt_type(skb)) {
2360         case HCI_COMMAND_PKT:
2361                 if (test_bit(BTUSB_BOOTLOADER, &data->flags)) {
2362                         struct hci_command_hdr *cmd = (void *)skb->data;
2363                         __u16 opcode = le16_to_cpu(cmd->opcode);
2364
2365                         /* When in bootloader mode and the command 0xfc09
2366                          * is received, it needs to be send down the
2367                          * bulk endpoint. So allocate a bulk URB instead.
2368                          */
2369                         if (opcode == 0xfc09)
2370                                 urb = alloc_bulk_urb(hdev, skb);
2371                         else
2372                                 urb = alloc_ctrl_urb(hdev, skb);
2373
2374                         /* When the 0xfc01 command is issued to boot into
2375                          * the operational firmware, it will actually not
2376                          * send a command complete event. To keep the flow
2377                          * control working inject that event here.
2378                          */
2379                         if (opcode == 0xfc01)
2380                                 inject_cmd_complete(hdev, opcode);
2381                 } else {
2382                         urb = alloc_ctrl_urb(hdev, skb);
2383                 }
2384                 if (IS_ERR(urb))
2385                         return PTR_ERR(urb);
2386
2387                 hdev->stat.cmd_tx++;
2388                 return submit_or_queue_tx_urb(hdev, urb);
2389
2390         case HCI_ACLDATA_PKT:
2391                 urb = alloc_bulk_urb(hdev, skb);
2392                 if (IS_ERR(urb))
2393                         return PTR_ERR(urb);
2394
2395                 hdev->stat.acl_tx++;
2396                 return submit_or_queue_tx_urb(hdev, urb);
2397
2398         case HCI_SCODATA_PKT:
2399                 if (hci_conn_num(hdev, SCO_LINK) < 1)
2400                         return -ENODEV;
2401
2402                 urb = alloc_isoc_urb(hdev, skb);
2403                 if (IS_ERR(urb))
2404                         return PTR_ERR(urb);
2405
2406                 hdev->stat.sco_tx++;
2407                 return submit_tx_urb(hdev, urb);
2408         }
2409
2410         return -EILSEQ;
2411 }
2412
2413 static bool btusb_setup_intel_new_get_fw_name(struct intel_version *ver,
2414                                              struct intel_boot_params *params,
2415                                              char *fw_name, size_t len,
2416                                              const char *suffix)
2417 {
2418         switch (ver->hw_variant) {
2419         case 0x0b:      /* SfP */
2420         case 0x0c:      /* WsP */
2421                 snprintf(fw_name, len, "intel/ibt-%u-%u.%s",
2422                         le16_to_cpu(ver->hw_variant),
2423                         le16_to_cpu(params->dev_revid),
2424                         suffix);
2425                 break;
2426         case 0x11:      /* JfP */
2427         case 0x12:      /* ThP */
2428         case 0x13:      /* HrP */
2429         case 0x14:      /* CcP */
2430                 snprintf(fw_name, len, "intel/ibt-%u-%u-%u.%s",
2431                         le16_to_cpu(ver->hw_variant),
2432                         le16_to_cpu(ver->hw_revision),
2433                         le16_to_cpu(ver->fw_revision),
2434                         suffix);
2435                 break;
2436         default:
2437                 return false;
2438         }
2439         return true;
2440 }
2441
2442 static int btusb_intel_download_firmware(struct hci_dev *hdev,
2443                                          struct intel_version *ver,
2444                                          struct intel_boot_params *params,
2445                                          u32 *boot_param)
2446 {
2447         const struct firmware *fw;
2448         char fwname[64];
2449         int err;
2450         struct btusb_data *data = hci_get_drvdata(hdev);
2451
2452         if (!ver || !params)
2453                 return -EINVAL;
2454
2455         /* The hardware platform number has a fixed value of 0x37 and
2456          * for now only accept this single value.
2457          */
2458         if (ver->hw_platform != 0x37) {
2459                 bt_dev_err(hdev, "Unsupported Intel hardware platform (%u)",
2460                            ver->hw_platform);
2461                 return -EINVAL;
2462         }
2463
2464         /* Check for supported iBT hardware variants of this firmware
2465          * loading method.
2466          *
2467          * This check has been put in place to ensure correct forward
2468          * compatibility options when newer hardware variants come along.
2469          */
2470         switch (ver->hw_variant) {
2471         case 0x0b:      /* SfP */
2472         case 0x0c:      /* WsP */
2473         case 0x11:      /* JfP */
2474         case 0x12:      /* ThP */
2475         case 0x13:      /* HrP */
2476         case 0x14:      /* CcP */
2477                 break;
2478         default:
2479                 bt_dev_err(hdev, "Unsupported Intel hardware variant (%u)",
2480                            ver->hw_variant);
2481                 return -EINVAL;
2482         }
2483
2484         btintel_version_info(hdev, ver);
2485
2486         /* The firmware variant determines if the device is in bootloader
2487          * mode or is running operational firmware. The value 0x06 identifies
2488          * the bootloader and the value 0x23 identifies the operational
2489          * firmware.
2490          *
2491          * When the operational firmware is already present, then only
2492          * the check for valid Bluetooth device address is needed. This
2493          * determines if the device will be added as configured or
2494          * unconfigured controller.
2495          *
2496          * It is not possible to use the Secure Boot Parameters in this
2497          * case since that command is only available in bootloader mode.
2498          */
2499         if (ver->fw_variant == 0x23) {
2500                 clear_bit(BTUSB_BOOTLOADER, &data->flags);
2501                 btintel_check_bdaddr(hdev);
2502                 return 0;
2503         }
2504
2505         /* If the device is not in bootloader mode, then the only possible
2506          * choice is to return an error and abort the device initialization.
2507          */
2508         if (ver->fw_variant != 0x06) {
2509                 bt_dev_err(hdev, "Unsupported Intel firmware variant (%u)",
2510                            ver->fw_variant);
2511                 return -ENODEV;
2512         }
2513
2514         /* Read the secure boot parameters to identify the operating
2515          * details of the bootloader.
2516          */
2517         err = btintel_read_boot_params(hdev, params);
2518         if (err)
2519                 return err;
2520
2521         /* It is required that every single firmware fragment is acknowledged
2522          * with a command complete event. If the boot parameters indicate
2523          * that this bootloader does not send them, then abort the setup.
2524          */
2525         if (params->limited_cce != 0x00) {
2526                 bt_dev_err(hdev, "Unsupported Intel firmware loading method (%u)",
2527                            params->limited_cce);
2528                 return -EINVAL;
2529         }
2530
2531         /* If the OTP has no valid Bluetooth device address, then there will
2532          * also be no valid address for the operational firmware.
2533          */
2534         if (!bacmp(&params->otp_bdaddr, BDADDR_ANY)) {
2535                 bt_dev_info(hdev, "No device address configured");
2536                 set_bit(HCI_QUIRK_INVALID_BDADDR, &hdev->quirks);
2537         }
2538
2539         /* With this Intel bootloader only the hardware variant and device
2540          * revision information are used to select the right firmware for SfP
2541          * and WsP.
2542          *
2543          * The firmware filename is ibt-<hw_variant>-<dev_revid>.sfi.
2544          *
2545          * Currently the supported hardware variants are:
2546          *   11 (0x0b) for iBT3.0 (LnP/SfP)
2547          *   12 (0x0c) for iBT3.5 (WsP)
2548          *
2549          * For ThP/JfP and for future SKU's, the FW name varies based on HW
2550          * variant, HW revision and FW revision, as these are dependent on CNVi
2551          * and RF Combination.
2552          *
2553          *   17 (0x11) for iBT3.5 (JfP)
2554          *   18 (0x12) for iBT3.5 (ThP)
2555          *
2556          * The firmware file name for these will be
2557          * ibt-<hw_variant>-<hw_revision>-<fw_revision>.sfi.
2558          *
2559          */
2560         err = btusb_setup_intel_new_get_fw_name(ver, params, fwname,
2561                                                 sizeof(fwname), "sfi");
2562         if (!err) {
2563                 bt_dev_err(hdev, "Unsupported Intel firmware naming");
2564                 return -EINVAL;
2565         }
2566
2567         err = reject_firmware(&fw, fwname, &hdev->dev);
2568         if (err < 0) {
2569                 bt_dev_err(hdev, "Failed to load Intel firmware file (%d)", err);
2570                 return err;
2571         }
2572
2573         bt_dev_info(hdev, "Found device firmware: %s", fwname);
2574
2575         if (fw->size < 644) {
2576                 bt_dev_err(hdev, "Invalid size of firmware file (%zu)",
2577                            fw->size);
2578                 err = -EBADF;
2579                 goto done;
2580         }
2581
2582         set_bit(BTUSB_DOWNLOADING, &data->flags);
2583
2584         /* Start firmware downloading and get boot parameter */
2585         err = btintel_download_firmware(hdev, fw, boot_param);
2586         if (err < 0) {
2587                 /* When FW download fails, send Intel Reset to retry
2588                  * FW download.
2589                  */
2590                 btintel_reset_to_bootloader(hdev);
2591                 goto done;
2592         }
2593         set_bit(BTUSB_FIRMWARE_LOADED, &data->flags);
2594
2595         bt_dev_info(hdev, "Waiting for firmware download to complete");
2596
2597         /* Before switching the device into operational mode and with that
2598          * booting the loaded firmware, wait for the bootloader notification
2599          * that all fragments have been successfully received.
2600          *
2601          * When the event processing receives the notification, then the
2602          * BTUSB_DOWNLOADING flag will be cleared.
2603          *
2604          * The firmware loading should not take longer than 5 seconds
2605          * and thus just timeout if that happens and fail the setup
2606          * of this device.
2607          */
2608         err = wait_on_bit_timeout(&data->flags, BTUSB_DOWNLOADING,
2609                                   TASK_INTERRUPTIBLE,
2610                                   msecs_to_jiffies(5000));
2611         if (err == -EINTR) {
2612                 bt_dev_err(hdev, "Firmware loading interrupted");
2613                 goto done;
2614         }
2615
2616         if (err) {
2617                 bt_dev_err(hdev, "Firmware loading timeout");
2618                 err = -ETIMEDOUT;
2619                 btintel_reset_to_bootloader(hdev);
2620                 goto done;
2621         }
2622
2623         if (test_bit(BTUSB_FIRMWARE_FAILED, &data->flags)) {
2624                 bt_dev_err(hdev, "Firmware loading failed");
2625                 err = -ENOEXEC;
2626                 goto done;
2627         }
2628
2629 done:
2630         release_firmware(fw);
2631         return err;
2632 }
2633
2634 static int btusb_setup_intel_new(struct hci_dev *hdev)
2635 {
2636         struct btusb_data *data = hci_get_drvdata(hdev);
2637         struct intel_version ver;
2638         struct intel_boot_params params;
2639         u32 boot_param;
2640         char ddcname[64];
2641         ktime_t calltime, delta, rettime;
2642         unsigned long long duration;
2643         int err;
2644         struct intel_debug_features features;
2645
2646         BT_DBG("%s", hdev->name);
2647
2648         /* Set the default boot parameter to 0x0 and it is updated to
2649          * SKU specific boot parameter after reading Intel_Write_Boot_Params
2650          * command while downloading the firmware.
2651          */
2652         boot_param = 0x00000000;
2653
2654         calltime = ktime_get();
2655
2656         /* Read the Intel version information to determine if the device
2657          * is in bootloader mode or if it already has operational firmware
2658          * loaded.
2659          */
2660         err = btintel_read_version(hdev, &ver);
2661         if (err) {
2662                 bt_dev_err(hdev, "Intel Read version failed (%d)", err);
2663                 btintel_reset_to_bootloader(hdev);
2664                 return err;
2665         }
2666
2667         err = btusb_intel_download_firmware(hdev, &ver, &params, &boot_param);
2668         if (err)
2669                 return err;
2670
2671         /* controller is already having an operational firmware */
2672         if (ver.fw_variant == 0x23)
2673                 goto finish;
2674
2675         rettime = ktime_get();
2676         delta = ktime_sub(rettime, calltime);
2677         duration = (unsigned long long) ktime_to_ns(delta) >> 10;
2678
2679         bt_dev_info(hdev, "Firmware loaded in %llu usecs", duration);
2680
2681         calltime = ktime_get();
2682
2683         set_bit(BTUSB_BOOTING, &data->flags);
2684
2685         err = btintel_send_intel_reset(hdev, boot_param);
2686         if (err) {
2687                 bt_dev_err(hdev, "Intel Soft Reset failed (%d)", err);
2688                 btintel_reset_to_bootloader(hdev);
2689                 return err;
2690         }
2691
2692         /* The bootloader will not indicate when the device is ready. This
2693          * is done by the operational firmware sending bootup notification.
2694          *
2695          * Booting into operational firmware should not take longer than
2696          * 1 second. However if that happens, then just fail the setup
2697          * since something went wrong.
2698          */
2699         bt_dev_info(hdev, "Waiting for device to boot");
2700
2701         err = wait_on_bit_timeout(&data->flags, BTUSB_BOOTING,
2702                                   TASK_INTERRUPTIBLE,
2703                                   msecs_to_jiffies(1000));
2704
2705         if (err == -EINTR) {
2706                 bt_dev_err(hdev, "Device boot interrupted");
2707                 return -EINTR;
2708         }
2709
2710         if (err) {
2711                 bt_dev_err(hdev, "Device boot timeout");
2712                 btintel_reset_to_bootloader(hdev);
2713                 return -ETIMEDOUT;
2714         }
2715
2716         rettime = ktime_get();
2717         delta = ktime_sub(rettime, calltime);
2718         duration = (unsigned long long) ktime_to_ns(delta) >> 10;
2719
2720         bt_dev_info(hdev, "Device booted in %llu usecs", duration);
2721
2722         clear_bit(BTUSB_BOOTLOADER, &data->flags);
2723
2724         err = btusb_setup_intel_new_get_fw_name(&ver, &params, ddcname,
2725                                                 sizeof(ddcname), "ddc");
2726
2727         if (!err) {
2728                 bt_dev_err(hdev, "Unsupported Intel firmware naming");
2729         } else {
2730                 /* Once the device is running in operational mode, it needs to
2731                  * apply the device configuration (DDC) parameters.
2732                  *
2733                  * The device can work without DDC parameters, so even if it
2734                  * fails to load the file, no need to fail the setup.
2735                  */
2736                 btintel_load_ddc_config(hdev, ddcname);
2737         }
2738
2739         /* Read the Intel supported features and if new exception formats
2740          * supported, need to load the additional DDC config to enable.
2741          */
2742         btintel_read_debug_features(hdev, &features);
2743
2744         /* Set DDC mask for available debug features */
2745         btintel_set_debug_features(hdev, &features);
2746
2747         /* Read the Intel version information after loading the FW  */
2748         err = btintel_read_version(hdev, &ver);
2749         if (err)
2750                 return err;
2751
2752         btintel_version_info(hdev, &ver);
2753
2754 finish:
2755         /* All Intel controllers that support the Microsoft vendor
2756          * extension are using 0xFC1E for VsMsftOpCode.
2757          */
2758         switch (ver.hw_variant) {
2759         case 0x12:      /* ThP */
2760                 hci_set_msft_opcode(hdev, 0xFC1E);
2761                 break;
2762         }
2763
2764         /* Set the event mask for Intel specific vendor events. This enables
2765          * a few extra events that are useful during general operation. It
2766          * does not enable any debugging related events.
2767          *
2768          * The device will function correctly without these events enabled
2769          * and thus no need to fail the setup.
2770          */
2771         btintel_set_event_mask(hdev, false);
2772
2773         return 0;
2774 }
2775
2776 static int btusb_shutdown_intel(struct hci_dev *hdev)
2777 {
2778         struct sk_buff *skb;
2779         long ret;
2780
2781         /* In the shutdown sequence where Bluetooth is turned off followed
2782          * by WiFi being turned off, turning WiFi back on causes issue with
2783          * the RF calibration.
2784          *
2785          * To ensure that any RF activity has been stopped, issue HCI Reset
2786          * command to clear all ongoing activity including advertising,
2787          * scanning etc.
2788          */
2789         skb = __hci_cmd_sync(hdev, HCI_OP_RESET, 0, NULL, HCI_INIT_TIMEOUT);
2790         if (IS_ERR(skb)) {
2791                 ret = PTR_ERR(skb);
2792                 bt_dev_err(hdev, "HCI reset during shutdown failed");
2793                 return ret;
2794         }
2795         kfree_skb(skb);
2796
2797         /* Some platforms have an issue with BT LED when the interface is
2798          * down or BT radio is turned off, which takes 5 seconds to BT LED
2799          * goes off. This command turns off the BT LED immediately.
2800          */
2801         skb = __hci_cmd_sync(hdev, 0xfc3f, 0, NULL, HCI_INIT_TIMEOUT);
2802         if (IS_ERR(skb)) {
2803                 ret = PTR_ERR(skb);
2804                 bt_dev_err(hdev, "turning off Intel device LED failed");
2805                 return ret;
2806         }
2807         kfree_skb(skb);
2808
2809         return 0;
2810 }
2811
2812 static int btusb_shutdown_intel_new(struct hci_dev *hdev)
2813 {
2814         struct sk_buff *skb;
2815
2816         /* Send HCI Reset to the controller to stop any BT activity which
2817          * were triggered. This will help to save power and maintain the
2818          * sync b/w Host and controller
2819          */
2820         skb = __hci_cmd_sync(hdev, HCI_OP_RESET, 0, NULL, HCI_INIT_TIMEOUT);
2821         if (IS_ERR(skb)) {
2822                 bt_dev_err(hdev, "HCI reset during shutdown failed");
2823                 return PTR_ERR(skb);
2824         }
2825         kfree_skb(skb);
2826
2827         return 0;
2828 }
2829
2830 #define FIRMWARE_MT7663         "/*(DEBLOBBED)*/"
2831 #define FIRMWARE_MT7668         "/*(DEBLOBBED)*/"
2832
2833 #define HCI_WMT_MAX_EVENT_SIZE          64
2834
2835 enum {
2836         BTMTK_WMT_PATCH_DWNLD = 0x1,
2837         BTMTK_WMT_FUNC_CTRL = 0x6,
2838         BTMTK_WMT_RST = 0x7,
2839         BTMTK_WMT_SEMAPHORE = 0x17,
2840 };
2841
2842 enum {
2843         BTMTK_WMT_INVALID,
2844         BTMTK_WMT_PATCH_UNDONE,
2845         BTMTK_WMT_PATCH_PROGRESS,
2846         BTMTK_WMT_PATCH_DONE,
2847         BTMTK_WMT_ON_UNDONE,
2848         BTMTK_WMT_ON_DONE,
2849         BTMTK_WMT_ON_PROGRESS,
2850 };
2851
2852 struct btmtk_wmt_hdr {
2853         u8      dir;
2854         u8      op;
2855         __le16  dlen;
2856         u8      flag;
2857 } __packed;
2858
2859 struct btmtk_hci_wmt_cmd {
2860         struct btmtk_wmt_hdr hdr;
2861         u8 data[];
2862 } __packed;
2863
2864 struct btmtk_hci_wmt_evt {
2865         struct hci_event_hdr hhdr;
2866         struct btmtk_wmt_hdr whdr;
2867 } __packed;
2868
2869 struct btmtk_hci_wmt_evt_funcc {
2870         struct btmtk_hci_wmt_evt hwhdr;
2871         __be16 status;
2872 } __packed;
2873
2874 struct btmtk_tci_sleep {
2875         u8 mode;
2876         __le16 duration;
2877         __le16 host_duration;
2878         u8 host_wakeup_pin;
2879         u8 time_compensation;
2880 } __packed;
2881
2882 struct btmtk_hci_wmt_params {
2883         u8 op;
2884         u8 flag;
2885         u16 dlen;
2886         const void *data;
2887         u32 *status;
2888 };
2889
2890 static void btusb_mtk_wmt_recv(struct urb *urb)
2891 {
2892         struct hci_dev *hdev = urb->context;
2893         struct btusb_data *data = hci_get_drvdata(hdev);
2894         struct hci_event_hdr *hdr;
2895         struct sk_buff *skb;
2896         int err;
2897
2898         if (urb->status == 0 && urb->actual_length > 0) {
2899                 hdev->stat.byte_rx += urb->actual_length;
2900
2901                 /* WMT event shouldn't be fragmented and the size should be
2902                  * less than HCI_WMT_MAX_EVENT_SIZE.
2903                  */
2904                 skb = bt_skb_alloc(HCI_WMT_MAX_EVENT_SIZE, GFP_ATOMIC);
2905                 if (!skb) {
2906                         hdev->stat.err_rx++;
2907                         kfree(urb->setup_packet);
2908                         return;
2909                 }
2910
2911                 hci_skb_pkt_type(skb) = HCI_EVENT_PKT;
2912                 skb_put_data(skb, urb->transfer_buffer, urb->actual_length);
2913
2914                 hdr = (void *)skb->data;
2915                 /* Fix up the vendor event id with 0xff for vendor specific
2916                  * instead of 0xe4 so that event send via monitoring socket can
2917                  * be parsed properly.
2918                  */
2919                 hdr->evt = 0xff;
2920
2921                 /* When someone waits for the WMT event, the skb is being cloned
2922                  * and being processed the events from there then.
2923                  */
2924                 if (test_bit(BTUSB_TX_WAIT_VND_EVT, &data->flags)) {
2925                         data->evt_skb = skb_clone(skb, GFP_ATOMIC);
2926                         if (!data->evt_skb) {
2927                                 kfree_skb(skb);
2928                                 kfree(urb->setup_packet);
2929                                 return;
2930                         }
2931                 }
2932
2933                 err = hci_recv_frame(hdev, skb);
2934                 if (err < 0) {
2935                         kfree_skb(data->evt_skb);
2936                         data->evt_skb = NULL;
2937                         kfree(urb->setup_packet);
2938                         return;
2939                 }
2940
2941                 if (test_and_clear_bit(BTUSB_TX_WAIT_VND_EVT,
2942                                        &data->flags)) {
2943                         /* Barrier to sync with other CPUs */
2944                         smp_mb__after_atomic();
2945                         wake_up_bit(&data->flags,
2946                                     BTUSB_TX_WAIT_VND_EVT);
2947                 }
2948                 kfree(urb->setup_packet);
2949                 return;
2950         } else if (urb->status == -ENOENT) {
2951                 /* Avoid suspend failed when usb_kill_urb */
2952                 return;
2953         }
2954
2955         usb_mark_last_busy(data->udev);
2956
2957         /* The URB complete handler is still called with urb->actual_length = 0
2958          * when the event is not available, so we should keep re-submitting
2959          * URB until WMT event returns, Also, It's necessary to wait some time
2960          * between the two consecutive control URBs to relax the target device
2961          * to generate the event. Otherwise, the WMT event cannot return from
2962          * the device successfully.
2963          */
2964         udelay(500);
2965
2966         usb_anchor_urb(urb, &data->ctrl_anchor);
2967         err = usb_submit_urb(urb, GFP_ATOMIC);
2968         if (err < 0) {
2969                 kfree(urb->setup_packet);
2970                 /* -EPERM: urb is being killed;
2971                  * -ENODEV: device got disconnected
2972                  */
2973                 if (err != -EPERM && err != -ENODEV)
2974                         bt_dev_err(hdev, "urb %p failed to resubmit (%d)",
2975                                    urb, -err);
2976                 usb_unanchor_urb(urb);
2977         }
2978 }
2979
2980 static int btusb_mtk_submit_wmt_recv_urb(struct hci_dev *hdev)
2981 {
2982         struct btusb_data *data = hci_get_drvdata(hdev);
2983         struct usb_ctrlrequest *dr;
2984         unsigned char *buf;
2985         int err, size = 64;
2986         unsigned int pipe;
2987         struct urb *urb;
2988
2989         urb = usb_alloc_urb(0, GFP_KERNEL);
2990         if (!urb)
2991                 return -ENOMEM;
2992
2993         dr = kmalloc(sizeof(*dr), GFP_KERNEL);
2994         if (!dr) {
2995                 usb_free_urb(urb);
2996                 return -ENOMEM;
2997         }
2998
2999         dr->bRequestType = USB_TYPE_VENDOR | USB_DIR_IN;
3000         dr->bRequest     = 1;
3001         dr->wIndex       = cpu_to_le16(0);
3002         dr->wValue       = cpu_to_le16(48);
3003         dr->wLength      = cpu_to_le16(size);
3004
3005         buf = kmalloc(size, GFP_KERNEL);
3006         if (!buf) {
3007                 kfree(dr);
3008                 usb_free_urb(urb);
3009                 return -ENOMEM;
3010         }
3011
3012         pipe = usb_rcvctrlpipe(data->udev, 0);
3013
3014         usb_fill_control_urb(urb, data->udev, pipe, (void *)dr,
3015                              buf, size, btusb_mtk_wmt_recv, hdev);
3016
3017         urb->transfer_flags |= URB_FREE_BUFFER;
3018
3019         usb_anchor_urb(urb, &data->ctrl_anchor);
3020         err = usb_submit_urb(urb, GFP_KERNEL);
3021         if (err < 0) {
3022                 if (err != -EPERM && err != -ENODEV)
3023                         bt_dev_err(hdev, "urb %p submission failed (%d)",
3024                                    urb, -err);
3025                 usb_unanchor_urb(urb);
3026         }
3027
3028         usb_free_urb(urb);
3029
3030         return err;
3031 }
3032
3033 static int btusb_mtk_hci_wmt_sync(struct hci_dev *hdev,
3034                                   struct btmtk_hci_wmt_params *wmt_params)
3035 {
3036         struct btusb_data *data = hci_get_drvdata(hdev);
3037         struct btmtk_hci_wmt_evt_funcc *wmt_evt_funcc;
3038         u32 hlen, status = BTMTK_WMT_INVALID;
3039         struct btmtk_hci_wmt_evt *wmt_evt;
3040         struct btmtk_hci_wmt_cmd *wc;
3041         struct btmtk_wmt_hdr *hdr;
3042         int err;
3043
3044         /* Send the WMT command and wait until the WMT event returns */
3045         hlen = sizeof(*hdr) + wmt_params->dlen;
3046         if (hlen > 255)
3047                 return -EINVAL;
3048
3049         wc = kzalloc(hlen, GFP_KERNEL);
3050         if (!wc)
3051                 return -ENOMEM;
3052
3053         hdr = &wc->hdr;
3054         hdr->dir = 1;
3055         hdr->op = wmt_params->op;
3056         hdr->dlen = cpu_to_le16(wmt_params->dlen + 1);
3057         hdr->flag = wmt_params->flag;
3058         memcpy(wc->data, wmt_params->data, wmt_params->dlen);
3059
3060         set_bit(BTUSB_TX_WAIT_VND_EVT, &data->flags);
3061
3062         /* WMT cmd/event doesn't follow up the generic HCI cmd/event handling,
3063          * it needs constantly polling control pipe until the host received the
3064          * WMT event, thus, we should require to specifically acquire PM counter
3065          * on the USB to prevent the interface from entering auto suspended
3066          * while WMT cmd/event in progress.
3067          */
3068         err = usb_autopm_get_interface(data->intf);
3069         if (err < 0)
3070                 goto err_free_wc;
3071
3072         err = __hci_cmd_send(hdev, 0xfc6f, hlen, wc);
3073
3074         if (err < 0) {
3075                 clear_bit(BTUSB_TX_WAIT_VND_EVT, &data->flags);
3076                 usb_autopm_put_interface(data->intf);
3077                 goto err_free_wc;
3078         }
3079
3080         /* Submit control IN URB on demand to process the WMT event */
3081         err = btusb_mtk_submit_wmt_recv_urb(hdev);
3082
3083         usb_autopm_put_interface(data->intf);
3084
3085         if (err < 0)
3086                 return err;
3087
3088         /* The vendor specific WMT commands are all answered by a vendor
3089          * specific event and will have the Command Status or Command
3090          * Complete as with usual HCI command flow control.
3091          *
3092          * After sending the command, wait for BTUSB_TX_WAIT_VND_EVT
3093          * state to be cleared. The driver specific event receive routine
3094          * will clear that state and with that indicate completion of the
3095          * WMT command.
3096          */
3097         err = wait_on_bit_timeout(&data->flags, BTUSB_TX_WAIT_VND_EVT,
3098                                   TASK_INTERRUPTIBLE, HCI_INIT_TIMEOUT);
3099         if (err == -EINTR) {
3100                 bt_dev_err(hdev, "Execution of wmt command interrupted");
3101                 clear_bit(BTUSB_TX_WAIT_VND_EVT, &data->flags);
3102                 goto err_free_wc;
3103         }
3104
3105         if (err) {
3106                 bt_dev_err(hdev, "Execution of wmt command timed out");
3107                 clear_bit(BTUSB_TX_WAIT_VND_EVT, &data->flags);
3108                 err = -ETIMEDOUT;
3109                 goto err_free_wc;
3110         }
3111
3112         if (data->evt_skb == NULL)
3113                 goto err_free_wc;
3114
3115         /* Parse and handle the return WMT event */
3116         wmt_evt = (struct btmtk_hci_wmt_evt *)data->evt_skb->data;
3117         if (wmt_evt->whdr.op != hdr->op) {
3118                 bt_dev_err(hdev, "Wrong op received %d expected %d",
3119                            wmt_evt->whdr.op, hdr->op);
3120                 err = -EIO;
3121                 goto err_free_skb;
3122         }
3123
3124         switch (wmt_evt->whdr.op) {
3125         case BTMTK_WMT_SEMAPHORE:
3126                 if (wmt_evt->whdr.flag == 2)
3127                         status = BTMTK_WMT_PATCH_UNDONE;
3128                 else
3129                         status = BTMTK_WMT_PATCH_DONE;
3130                 break;
3131         case BTMTK_WMT_FUNC_CTRL:
3132                 wmt_evt_funcc = (struct btmtk_hci_wmt_evt_funcc *)wmt_evt;
3133                 if (be16_to_cpu(wmt_evt_funcc->status) == 0x404)
3134                         status = BTMTK_WMT_ON_DONE;
3135                 else if (be16_to_cpu(wmt_evt_funcc->status) == 0x420)
3136                         status = BTMTK_WMT_ON_PROGRESS;
3137                 else
3138                         status = BTMTK_WMT_ON_UNDONE;
3139                 break;
3140         }
3141
3142         if (wmt_params->status)
3143                 *wmt_params->status = status;
3144
3145 err_free_skb:
3146         kfree_skb(data->evt_skb);
3147         data->evt_skb = NULL;
3148 err_free_wc:
3149         kfree(wc);
3150         return err;
3151 }
3152
3153 static int btusb_mtk_setup_firmware(struct hci_dev *hdev, const char *fwname)
3154 {
3155         struct btmtk_hci_wmt_params wmt_params;
3156         const struct firmware *fw;
3157         const u8 *fw_ptr;
3158         size_t fw_size;
3159         int err, dlen;
3160         u8 flag, param;
3161
3162         err = reject_firmware(&fw, fwname, &hdev->dev);
3163         if (err < 0) {
3164                 bt_dev_err(hdev, "Failed to load firmware file (%d)", err);
3165                 return err;
3166         }
3167
3168         /* Power on data RAM the firmware relies on. */
3169         param = 1;
3170         wmt_params.op = BTMTK_WMT_FUNC_CTRL;
3171         wmt_params.flag = 3;
3172         wmt_params.dlen = sizeof(param);
3173         wmt_params.data = &param;
3174         wmt_params.status = NULL;
3175
3176         err = btusb_mtk_hci_wmt_sync(hdev, &wmt_params);
3177         if (err < 0) {
3178                 bt_dev_err(hdev, "Failed to power on data RAM (%d)", err);
3179                 goto err_release_fw;
3180         }
3181
3182         fw_ptr = fw->data;
3183         fw_size = fw->size;
3184
3185         /* The size of patch header is 30 bytes, should be skip */
3186         if (fw_size < 30) {
3187                 err = -EINVAL;
3188                 goto err_release_fw;
3189         }
3190
3191         fw_size -= 30;
3192         fw_ptr += 30;
3193         flag = 1;
3194
3195         wmt_params.op = BTMTK_WMT_PATCH_DWNLD;
3196         wmt_params.status = NULL;
3197
3198         while (fw_size > 0) {
3199                 dlen = min_t(int, 250, fw_size);
3200
3201                 /* Tell deivice the position in sequence */
3202                 if (fw_size - dlen <= 0)
3203                         flag = 3;
3204                 else if (fw_size < fw->size - 30)
3205                         flag = 2;
3206
3207                 wmt_params.flag = flag;
3208                 wmt_params.dlen = dlen;
3209                 wmt_params.data = fw_ptr;
3210
3211                 err = btusb_mtk_hci_wmt_sync(hdev, &wmt_params);
3212                 if (err < 0) {
3213                         bt_dev_err(hdev, "Failed to send wmt patch dwnld (%d)",
3214                                    err);
3215                         goto err_release_fw;
3216                 }
3217
3218                 fw_size -= dlen;
3219                 fw_ptr += dlen;
3220         }
3221
3222         wmt_params.op = BTMTK_WMT_RST;
3223         wmt_params.flag = 4;
3224         wmt_params.dlen = 0;
3225         wmt_params.data = NULL;
3226         wmt_params.status = NULL;
3227
3228         /* Activate funciton the firmware providing to */
3229         err = btusb_mtk_hci_wmt_sync(hdev, &wmt_params);
3230         if (err < 0) {
3231                 bt_dev_err(hdev, "Failed to send wmt rst (%d)", err);
3232                 goto err_release_fw;
3233         }
3234
3235         /* Wait a few moments for firmware activation done */
3236         usleep_range(10000, 12000);
3237
3238 err_release_fw:
3239         release_firmware(fw);
3240
3241         return err;
3242 }
3243
3244 static int btusb_mtk_func_query(struct hci_dev *hdev)
3245 {
3246         struct btmtk_hci_wmt_params wmt_params;
3247         int status, err;
3248         u8 param = 0;
3249
3250         /* Query whether the function is enabled */
3251         wmt_params.op = BTMTK_WMT_FUNC_CTRL;
3252         wmt_params.flag = 4;
3253         wmt_params.dlen = sizeof(param);
3254         wmt_params.data = &param;
3255         wmt_params.status = &status;
3256
3257         err = btusb_mtk_hci_wmt_sync(hdev, &wmt_params);
3258         if (err < 0) {
3259                 bt_dev_err(hdev, "Failed to query function status (%d)", err);
3260                 return err;
3261         }
3262
3263         return status;
3264 }
3265
3266 static int btusb_mtk_reg_read(struct btusb_data *data, u32 reg, u32 *val)
3267 {
3268         int pipe, err, size = sizeof(u32);
3269         void *buf;
3270
3271         buf = kzalloc(size, GFP_KERNEL);
3272         if (!buf)
3273                 return -ENOMEM;
3274
3275         pipe = usb_rcvctrlpipe(data->udev, 0);
3276         err = usb_control_msg(data->udev, pipe, 0x63,
3277                               USB_TYPE_VENDOR | USB_DIR_IN,
3278                               reg >> 16, reg & 0xffff,
3279                               buf, size, USB_CTRL_SET_TIMEOUT);
3280         if (err < 0)
3281                 goto err_free_buf;
3282
3283         *val = get_unaligned_le32(buf);
3284
3285 err_free_buf:
3286         kfree(buf);
3287
3288         return err;
3289 }
3290
3291 static int btusb_mtk_id_get(struct btusb_data *data, u32 reg, u32 *id)
3292 {
3293         return btusb_mtk_reg_read(data, reg, id);
3294 }
3295
3296 static int btusb_mtk_setup(struct hci_dev *hdev)
3297 {
3298         struct btusb_data *data = hci_get_drvdata(hdev);
3299         struct btmtk_hci_wmt_params wmt_params;
3300         ktime_t calltime, delta, rettime;
3301         struct btmtk_tci_sleep tci_sleep;
3302         unsigned long long duration;
3303         struct sk_buff *skb;
3304         const char *fwname;
3305         int err, status;
3306         u32 dev_id;
3307         u8 param;
3308
3309         calltime = ktime_get();
3310
3311         err = btusb_mtk_id_get(data, 0x80000008, &dev_id);
3312         if (err < 0) {
3313                 bt_dev_err(hdev, "Failed to get device id (%d)", err);
3314                 return err;
3315         }
3316
3317         switch (dev_id) {
3318         case 0x7663:
3319                 fwname = FIRMWARE_MT7663;
3320                 break;
3321         case 0x7668:
3322                 fwname = FIRMWARE_MT7668;
3323                 break;
3324         default:
3325                 bt_dev_err(hdev, "Unsupported support hardware variant (%08x)",
3326                            dev_id);
3327                 return -ENODEV;
3328         }
3329
3330         /* Query whether the firmware is already download */
3331         wmt_params.op = BTMTK_WMT_SEMAPHORE;
3332         wmt_params.flag = 1;
3333         wmt_params.dlen = 0;
3334         wmt_params.data = NULL;
3335         wmt_params.status = &status;
3336
3337         err = btusb_mtk_hci_wmt_sync(hdev, &wmt_params);
3338         if (err < 0) {
3339                 bt_dev_err(hdev, "Failed to query firmware status (%d)", err);
3340                 return err;
3341         }
3342
3343         if (status == BTMTK_WMT_PATCH_DONE) {
3344                 bt_dev_info(hdev, "firmware already downloaded");
3345                 goto ignore_setup_fw;
3346         }
3347
3348         /* Setup a firmware which the device definitely requires */
3349         err = btusb_mtk_setup_firmware(hdev, fwname);
3350         if (err < 0)
3351                 return err;
3352
3353 ignore_setup_fw:
3354         err = readx_poll_timeout(btusb_mtk_func_query, hdev, status,
3355                                  status < 0 || status != BTMTK_WMT_ON_PROGRESS,
3356                                  2000, 5000000);
3357         /* -ETIMEDOUT happens */
3358         if (err < 0)
3359                 return err;
3360
3361         /* The other errors happen in btusb_mtk_func_query */
3362         if (status < 0)
3363                 return status;
3364
3365         if (status == BTMTK_WMT_ON_DONE) {
3366                 bt_dev_info(hdev, "function already on");
3367                 goto ignore_func_on;
3368         }
3369
3370         /* Enable Bluetooth protocol */
3371         param = 1;
3372         wmt_params.op = BTMTK_WMT_FUNC_CTRL;
3373         wmt_params.flag = 0;
3374         wmt_params.dlen = sizeof(param);
3375         wmt_params.data = &param;
3376         wmt_params.status = NULL;
3377
3378         err = btusb_mtk_hci_wmt_sync(hdev, &wmt_params);
3379         if (err < 0) {
3380                 bt_dev_err(hdev, "Failed to send wmt func ctrl (%d)", err);
3381                 return err;
3382         }
3383
3384 ignore_func_on:
3385         /* Apply the low power environment setup */
3386         tci_sleep.mode = 0x5;
3387         tci_sleep.duration = cpu_to_le16(0x640);
3388         tci_sleep.host_duration = cpu_to_le16(0x640);
3389         tci_sleep.host_wakeup_pin = 0;
3390         tci_sleep.time_compensation = 0;
3391
3392         skb = __hci_cmd_sync(hdev, 0xfc7a, sizeof(tci_sleep), &tci_sleep,
3393                              HCI_INIT_TIMEOUT);
3394         if (IS_ERR(skb)) {
3395                 err = PTR_ERR(skb);
3396                 bt_dev_err(hdev, "Failed to apply low power setting (%d)", err);
3397                 return err;
3398         }
3399         kfree_skb(skb);
3400
3401         rettime = ktime_get();
3402         delta = ktime_sub(rettime, calltime);
3403         duration = (unsigned long long)ktime_to_ns(delta) >> 10;
3404
3405         bt_dev_info(hdev, "Device setup in %llu usecs", duration);
3406
3407         return 0;
3408 }
3409
3410 static int btusb_mtk_shutdown(struct hci_dev *hdev)
3411 {
3412         struct btmtk_hci_wmt_params wmt_params;
3413         u8 param = 0;
3414         int err;
3415
3416         /* Disable the device */
3417         wmt_params.op = BTMTK_WMT_FUNC_CTRL;
3418         wmt_params.flag = 0;
3419         wmt_params.dlen = sizeof(param);
3420         wmt_params.data = &param;
3421         wmt_params.status = NULL;
3422
3423         err = btusb_mtk_hci_wmt_sync(hdev, &wmt_params);
3424         if (err < 0) {
3425                 bt_dev_err(hdev, "Failed to send wmt func ctrl (%d)", err);
3426                 return err;
3427         }
3428
3429         return 0;
3430 }
3431
3432 /*(DEBLOBBED)*/
3433
3434 #ifdef CONFIG_PM
3435 /* Configure an out-of-band gpio as wake-up pin, if specified in device tree */
3436 static int marvell_config_oob_wake(struct hci_dev *hdev)
3437 {
3438         struct sk_buff *skb;
3439         struct btusb_data *data = hci_get_drvdata(hdev);
3440         struct device *dev = &data->udev->dev;
3441         u16 pin, gap, opcode;
3442         int ret;
3443         u8 cmd[5];
3444
3445         /* Move on if no wakeup pin specified */
3446         if (of_property_read_u16(dev->of_node, "marvell,wakeup-pin", &pin) ||
3447             of_property_read_u16(dev->of_node, "marvell,wakeup-gap-ms", &gap))
3448                 return 0;
3449
3450         /* Vendor specific command to configure a GPIO as wake-up pin */
3451         opcode = hci_opcode_pack(0x3F, 0x59);
3452         cmd[0] = opcode & 0xFF;
3453         cmd[1] = opcode >> 8;
3454         cmd[2] = 2; /* length of parameters that follow */
3455         cmd[3] = pin;
3456         cmd[4] = gap; /* time in ms, for which wakeup pin should be asserted */
3457
3458         skb = bt_skb_alloc(sizeof(cmd), GFP_KERNEL);
3459         if (!skb) {
3460                 bt_dev_err(hdev, "%s: No memory\n", __func__);
3461                 return -ENOMEM;
3462         }
3463
3464         skb_put_data(skb, cmd, sizeof(cmd));
3465         hci_skb_pkt_type(skb) = HCI_COMMAND_PKT;
3466
3467         ret = btusb_send_frame(hdev, skb);
3468         if (ret) {
3469                 bt_dev_err(hdev, "%s: configuration failed\n", __func__);
3470                 kfree_skb(skb);
3471                 return ret;
3472         }
3473
3474         return 0;
3475 }
3476 #endif
3477
3478 static int btusb_set_bdaddr_marvell(struct hci_dev *hdev,
3479                                     const bdaddr_t *bdaddr)
3480 {
3481         struct sk_buff *skb;
3482         u8 buf[8];
3483         long ret;
3484
3485         buf[0] = 0xfe;
3486         buf[1] = sizeof(bdaddr_t);
3487         memcpy(buf + 2, bdaddr, sizeof(bdaddr_t));
3488
3489         skb = __hci_cmd_sync(hdev, 0xfc22, sizeof(buf), buf, HCI_INIT_TIMEOUT);
3490         if (IS_ERR(skb)) {
3491                 ret = PTR_ERR(skb);
3492                 bt_dev_err(hdev, "changing Marvell device address failed (%ld)",
3493                            ret);
3494                 return ret;
3495         }
3496         kfree_skb(skb);
3497
3498         return 0;
3499 }
3500
3501 static int btusb_set_bdaddr_ath3012(struct hci_dev *hdev,
3502                                     const bdaddr_t *bdaddr)
3503 {
3504         struct sk_buff *skb;
3505         u8 buf[10];
3506         long ret;
3507
3508         buf[0] = 0x01;
3509         buf[1] = 0x01;
3510         buf[2] = 0x00;
3511         buf[3] = sizeof(bdaddr_t);
3512         memcpy(buf + 4, bdaddr, sizeof(bdaddr_t));
3513
3514         skb = __hci_cmd_sync(hdev, 0xfc0b, sizeof(buf), buf, HCI_INIT_TIMEOUT);
3515         if (IS_ERR(skb)) {
3516                 ret = PTR_ERR(skb);
3517                 bt_dev_err(hdev, "Change address command failed (%ld)", ret);
3518                 return ret;
3519         }
3520         kfree_skb(skb);
3521
3522         return 0;
3523 }
3524
3525 static int btusb_set_bdaddr_wcn6855(struct hci_dev *hdev,
3526                                 const bdaddr_t *bdaddr)
3527 {
3528         struct sk_buff *skb;
3529         u8 buf[6];
3530         long ret;
3531
3532         memcpy(buf, bdaddr, sizeof(bdaddr_t));
3533
3534         skb = __hci_cmd_sync_ev(hdev, 0xfc14, sizeof(buf), buf,
3535                                 HCI_EV_CMD_COMPLETE, HCI_INIT_TIMEOUT);
3536         if (IS_ERR(skb)) {
3537                 ret = PTR_ERR(skb);
3538                 bt_dev_err(hdev, "Change address command failed (%ld)", ret);
3539                 return ret;
3540         }
3541         kfree_skb(skb);
3542
3543         return 0;
3544 }
3545
3546 #define QCA_DFU_PACKET_LEN      4096
3547
3548 #define QCA_GET_TARGET_VERSION  0x09
3549 #define QCA_CHECK_STATUS        0x05
3550 #define QCA_DFU_DOWNLOAD        0x01
3551
3552 #define QCA_SYSCFG_UPDATED      0x40
3553 #define QCA_PATCH_UPDATED       0x80
3554 #define QCA_DFU_TIMEOUT         3000
3555
3556 struct qca_version {
3557         __le32  rom_version;
3558         __le32  patch_version;
3559         __le32  ram_version;
3560         __le32  ref_clock;
3561         __u8    reserved[4];
3562 } __packed;
3563
3564 struct qca_rampatch_version {
3565         __le16  rom_version_high;
3566         __le16  rom_version_low;
3567         __le16  patch_version;
3568 } __packed;
3569
3570 struct qca_device_info {
3571         u32     rom_version;
3572         u8      rampatch_hdr;   /* length of header in rampatch */
3573         u8      nvm_hdr;        /* length of header in NVM */
3574         u8      ver_offset;     /* offset of version structure in rampatch */
3575 };
3576
3577 static const struct qca_device_info qca_devices_table[] = {
3578         { 0x00000100, 20, 4,  8 }, /* Rome 1.0 */
3579         { 0x00000101, 20, 4,  8 }, /* Rome 1.1 */
3580         { 0x00000200, 28, 4, 16 }, /* Rome 2.0 */
3581         { 0x00000201, 28, 4, 16 }, /* Rome 2.1 */
3582         { 0x00000300, 28, 4, 16 }, /* Rome 3.0 */
3583         { 0x00000302, 28, 4, 16 }, /* Rome 3.2 */
3584         { 0x00130100, 40, 4, 16 }, /* WCN6855 1.0 */
3585         { 0x00130200, 40, 4, 16 }, /* WCN6855 2.0 */
3586 };
3587
3588 static int btusb_qca_send_vendor_req(struct usb_device *udev, u8 request,
3589                                      void *data, u16 size)
3590 {
3591         int pipe, err;
3592         u8 *buf;
3593
3594         buf = kmalloc(size, GFP_KERNEL);
3595         if (!buf)
3596                 return -ENOMEM;
3597
3598         /* Found some of USB hosts have IOT issues with ours so that we should
3599          * not wait until HCI layer is ready.
3600          */
3601         pipe = usb_rcvctrlpipe(udev, 0);
3602         err = usb_control_msg(udev, pipe, request, USB_TYPE_VENDOR | USB_DIR_IN,
3603                               0, 0, buf, size, USB_CTRL_SET_TIMEOUT);
3604         if (err < 0) {
3605                 dev_err(&udev->dev, "Failed to access otp area (%d)", err);
3606                 goto done;
3607         }
3608
3609         memcpy(data, buf, size);
3610
3611 done:
3612         kfree(buf);
3613
3614         return err;
3615 }
3616
3617 static int btusb_setup_qca_download_fw(struct hci_dev *hdev,
3618                                        const struct firmware *firmware,
3619                                        size_t hdr_size)
3620 {
3621         struct btusb_data *btdata = hci_get_drvdata(hdev);
3622         struct usb_device *udev = btdata->udev;
3623         size_t count, size, sent = 0;
3624         int pipe, len, err;
3625         u8 *buf;
3626
3627         buf = kmalloc(QCA_DFU_PACKET_LEN, GFP_KERNEL);
3628         if (!buf)
3629                 return -ENOMEM;
3630
3631         count = firmware->size;
3632
3633         size = min_t(size_t, count, hdr_size);
3634         memcpy(buf, firmware->data, size);
3635
3636         /* USB patches should go down to controller through USB path
3637          * because binary format fits to go down through USB channel.
3638          * USB control path is for patching headers and USB bulk is for
3639          * patch body.
3640          */
3641         pipe = usb_sndctrlpipe(udev, 0);
3642         err = usb_control_msg(udev, pipe, QCA_DFU_DOWNLOAD, USB_TYPE_VENDOR,
3643                               0, 0, buf, size, USB_CTRL_SET_TIMEOUT);
3644         if (err < 0) {
3645                 bt_dev_err(hdev, "Failed to send headers (%d)", err);
3646                 goto done;
3647         }
3648
3649         sent += size;
3650         count -= size;
3651
3652         /* ep2 need time to switch from function acl to function dfu,
3653          * so we add 20ms delay here.
3654          */
3655         msleep(20);
3656
3657         while (count) {
3658                 size = min_t(size_t, count, QCA_DFU_PACKET_LEN);
3659
3660                 memcpy(buf, firmware->data + sent, size);
3661
3662                 pipe = usb_sndbulkpipe(udev, 0x02);
3663                 err = usb_bulk_msg(udev, pipe, buf, size, &len,
3664                                    QCA_DFU_TIMEOUT);
3665                 if (err < 0) {
3666                         bt_dev_err(hdev, "Failed to send body at %zd of %zd (%d)",
3667                                    sent, firmware->size, err);
3668                         break;
3669                 }
3670
3671                 if (size != len) {
3672                         bt_dev_err(hdev, "Failed to get bulk buffer");
3673                         err = -EILSEQ;
3674                         break;
3675                 }
3676
3677                 sent  += size;
3678                 count -= size;
3679         }
3680
3681 done:
3682         kfree(buf);
3683         return err;
3684 }
3685
3686 static int btusb_setup_qca_load_rampatch(struct hci_dev *hdev,
3687                                          struct qca_version *ver,
3688                                          const struct qca_device_info *info)
3689 {
3690         struct qca_rampatch_version *rver;
3691         const struct firmware *fw;
3692         u32 ver_rom, ver_patch, rver_rom;
3693         u16 rver_rom_low, rver_rom_high, rver_patch;
3694         char fwname[64];
3695         int err;
3696
3697         ver_rom = le32_to_cpu(ver->rom_version);
3698         ver_patch = le32_to_cpu(ver->patch_version);
3699
3700         snprintf(fwname, sizeof(fwname), "/*(DEBLOBBED)*/", ver_rom);
3701
3702         err = reject_firmware(&fw, fwname, &hdev->dev);
3703         if (err) {
3704                 bt_dev_err(hdev, "failed to request rampatch file: %s (%d)",
3705                            fwname, err);
3706                 return err;
3707         }
3708
3709         bt_dev_info(hdev, "using rampatch file: %s", fwname);
3710
3711         rver = (struct qca_rampatch_version *)(fw->data + info->ver_offset);
3712         rver_rom_low = le16_to_cpu(rver->rom_version_low);
3713         rver_patch = le16_to_cpu(rver->patch_version);
3714
3715         if (ver_rom & ~0xffffU) {
3716                 rver_rom_high = le16_to_cpu(rver->rom_version_high);
3717                 rver_rom = le32_to_cpu(rver_rom_high << 16 | rver_rom_low);
3718         } else {
3719                 rver_rom = rver_rom_low;
3720         }
3721
3722         bt_dev_info(hdev, "QCA: patch rome 0x%x build 0x%x, "
3723                     "firmware rome 0x%x build 0x%x",
3724                     rver_rom, rver_patch, ver_rom, ver_patch);
3725
3726         if (rver_rom != ver_rom || rver_patch <= ver_patch) {
3727                 bt_dev_err(hdev, "rampatch file version did not match with firmware");
3728                 err = -EINVAL;
3729                 goto done;
3730         }
3731
3732         err = btusb_setup_qca_download_fw(hdev, fw, info->rampatch_hdr);
3733
3734 done:
3735         release_firmware(fw);
3736
3737         return err;
3738 }
3739
3740 static int btusb_setup_qca_load_nvm(struct hci_dev *hdev,
3741                                     struct qca_version *ver,
3742                                     const struct qca_device_info *info)
3743 {
3744         const struct firmware *fw;
3745         char fwname[64];
3746         int err;
3747
3748         snprintf(fwname, sizeof(fwname), "/*(DEBLOBBED)*/",
3749                  le32_to_cpu(ver->rom_version));
3750
3751         err = reject_firmware(&fw, fwname, &hdev->dev);
3752         if (err) {
3753                 bt_dev_err(hdev, "failed to request NVM file: %s (%d)",
3754                            fwname, err);
3755                 return err;
3756         }
3757
3758         bt_dev_info(hdev, "using NVM file: %s", fwname);
3759
3760         err = btusb_setup_qca_download_fw(hdev, fw, info->nvm_hdr);
3761
3762         release_firmware(fw);
3763
3764         return err;
3765 }
3766
3767 /* identify the ROM version and check whether patches are needed */
3768 static bool btusb_qca_need_patch(struct usb_device *udev)
3769 {
3770         struct qca_version ver;
3771
3772         if (btusb_qca_send_vendor_req(udev, QCA_GET_TARGET_VERSION, &ver,
3773                                       sizeof(ver)) < 0)
3774                 return false;
3775         /* only low ROM versions need patches */
3776         return !(le32_to_cpu(ver.rom_version) & ~0xffffU);
3777 }
3778
3779 static int btusb_setup_qca(struct hci_dev *hdev)
3780 {
3781         struct btusb_data *btdata = hci_get_drvdata(hdev);
3782         struct usb_device *udev = btdata->udev;
3783         const struct qca_device_info *info = NULL;
3784         struct qca_version ver;
3785         u32 ver_rom;
3786         u8 status;
3787         int i, err;
3788
3789         err = btusb_qca_send_vendor_req(udev, QCA_GET_TARGET_VERSION, &ver,
3790                                         sizeof(ver));
3791         if (err < 0)
3792                 return err;
3793
3794         ver_rom = le32_to_cpu(ver.rom_version);
3795
3796         for (i = 0; i < ARRAY_SIZE(qca_devices_table); i++) {
3797                 if (ver_rom == qca_devices_table[i].rom_version)
3798                         info = &qca_devices_table[i];
3799         }
3800         if (!info) {
3801                 /* If the rom_version is not matched in the qca_devices_table
3802                  * and the high ROM version is not zero, we assume this chip no
3803                  * need to load the rampatch and nvm.
3804                  */
3805                 if (ver_rom & ~0xffffU)
3806                         return 0;
3807
3808                 bt_dev_err(hdev, "don't support firmware rome 0x%x", ver_rom);
3809                 return -ENODEV;
3810         }
3811
3812         err = btusb_qca_send_vendor_req(udev, QCA_CHECK_STATUS, &status,
3813                                         sizeof(status));
3814         if (err < 0)
3815                 return err;
3816
3817         if (!(status & QCA_PATCH_UPDATED)) {
3818                 err = btusb_setup_qca_load_rampatch(hdev, &ver, info);
3819                 if (err < 0)
3820                         return err;
3821         }
3822
3823         if (!(status & QCA_SYSCFG_UPDATED)) {
3824                 err = btusb_setup_qca_load_nvm(hdev, &ver, info);
3825                 if (err < 0)
3826                         return err;
3827         }
3828
3829         return 0;
3830 }
3831
3832 static inline int __set_diag_interface(struct hci_dev *hdev)
3833 {
3834         struct btusb_data *data = hci_get_drvdata(hdev);
3835         struct usb_interface *intf = data->diag;
3836         int i;
3837
3838         if (!data->diag)
3839                 return -ENODEV;
3840
3841         data->diag_tx_ep = NULL;
3842         data->diag_rx_ep = NULL;
3843
3844         for (i = 0; i < intf->cur_altsetting->desc.bNumEndpoints; i++) {
3845                 struct usb_endpoint_descriptor *ep_desc;
3846
3847                 ep_desc = &intf->cur_altsetting->endpoint[i].desc;
3848
3849                 if (!data->diag_tx_ep && usb_endpoint_is_bulk_out(ep_desc)) {
3850                         data->diag_tx_ep = ep_desc;
3851                         continue;
3852                 }
3853
3854                 if (!data->diag_rx_ep && usb_endpoint_is_bulk_in(ep_desc)) {
3855                         data->diag_rx_ep = ep_desc;
3856                         continue;
3857                 }
3858         }
3859
3860         if (!data->diag_tx_ep || !data->diag_rx_ep) {
3861                 bt_dev_err(hdev, "invalid diagnostic descriptors");
3862                 return -ENODEV;
3863         }
3864
3865         return 0;
3866 }
3867
3868 static struct urb *alloc_diag_urb(struct hci_dev *hdev, bool enable)
3869 {
3870         struct btusb_data *data = hci_get_drvdata(hdev);
3871         struct sk_buff *skb;
3872         struct urb *urb;
3873         unsigned int pipe;
3874
3875         if (!data->diag_tx_ep)
3876                 return ERR_PTR(-ENODEV);
3877
3878         urb = usb_alloc_urb(0, GFP_KERNEL);
3879         if (!urb)
3880                 return ERR_PTR(-ENOMEM);
3881
3882         skb = bt_skb_alloc(2, GFP_KERNEL);
3883         if (!skb) {
3884                 usb_free_urb(urb);
3885                 return ERR_PTR(-ENOMEM);
3886         }
3887
3888         skb_put_u8(skb, 0xf0);
3889         skb_put_u8(skb, enable);
3890
3891         pipe = usb_sndbulkpipe(data->udev, data->diag_tx_ep->bEndpointAddress);
3892
3893         usb_fill_bulk_urb(urb, data->udev, pipe,
3894                           skb->data, skb->len, btusb_tx_complete, skb);
3895
3896         skb->dev = (void *)hdev;
3897
3898         return urb;
3899 }
3900
3901 static int btusb_bcm_set_diag(struct hci_dev *hdev, bool enable)
3902 {
3903         struct btusb_data *data = hci_get_drvdata(hdev);
3904         struct urb *urb;
3905
3906         if (!data->diag)
3907                 return -ENODEV;
3908
3909         if (!test_bit(HCI_RUNNING, &hdev->flags))
3910                 return -ENETDOWN;
3911
3912         urb = alloc_diag_urb(hdev, enable);
3913         if (IS_ERR(urb))
3914                 return PTR_ERR(urb);
3915
3916         return submit_or_queue_tx_urb(hdev, urb);
3917 }
3918
3919 #ifdef CONFIG_PM
3920 static irqreturn_t btusb_oob_wake_handler(int irq, void *priv)
3921 {
3922         struct btusb_data *data = priv;
3923
3924         pm_wakeup_event(&data->udev->dev, 0);
3925         pm_system_wakeup();
3926
3927         /* Disable only if not already disabled (keep it balanced) */
3928         if (test_and_clear_bit(BTUSB_OOB_WAKE_ENABLED, &data->flags)) {
3929                 disable_irq_nosync(irq);
3930                 disable_irq_wake(irq);
3931         }
3932         return IRQ_HANDLED;
3933 }
3934
3935 static const struct of_device_id btusb_match_table[] = {
3936         { .compatible = "usb1286,204e" },
3937         { .compatible = "usbcf3,e300" }, /* QCA6174A */
3938         { .compatible = "usb4ca,301a" }, /* QCA6174A (Lite-On) */
3939         { }
3940 };
3941 MODULE_DEVICE_TABLE(of, btusb_match_table);
3942
3943 /* Use an oob wakeup pin? */
3944 static int btusb_config_oob_wake(struct hci_dev *hdev)
3945 {
3946         struct btusb_data *data = hci_get_drvdata(hdev);
3947         struct device *dev = &data->udev->dev;
3948         int irq, ret;
3949
3950         clear_bit(BTUSB_OOB_WAKE_ENABLED, &data->flags);
3951
3952         if (!of_match_device(btusb_match_table, dev))
3953                 return 0;
3954
3955         /* Move on if no IRQ specified */
3956         irq = of_irq_get_byname(dev->of_node, "wakeup");
3957         if (irq <= 0) {
3958                 bt_dev_dbg(hdev, "%s: no OOB Wakeup IRQ in DT", __func__);
3959                 return 0;
3960         }
3961
3962         irq_set_status_flags(irq, IRQ_NOAUTOEN);
3963         ret = devm_request_irq(&hdev->dev, irq, btusb_oob_wake_handler,
3964                                0, "OOB Wake-on-BT", data);
3965         if (ret) {
3966                 bt_dev_err(hdev, "%s: IRQ request failed", __func__);
3967                 return ret;
3968         }
3969
3970         ret = device_init_wakeup(dev, true);
3971         if (ret) {
3972                 bt_dev_err(hdev, "%s: failed to init_wakeup", __func__);
3973                 return ret;
3974         }
3975
3976         data->oob_wake_irq = irq;
3977         bt_dev_info(hdev, "OOB Wake-on-BT configured at IRQ %u", irq);
3978         return 0;
3979 }
3980 #endif
3981
3982 static void btusb_check_needs_reset_resume(struct usb_interface *intf)
3983 {
3984         if (dmi_check_system(btusb_needs_reset_resume_table))
3985                 interface_to_usbdev(intf)->quirks |= USB_QUIRK_RESET_RESUME;
3986 }
3987
3988 static bool btusb_prevent_wake(struct hci_dev *hdev)
3989 {
3990         struct btusb_data *data = hci_get_drvdata(hdev);
3991
3992         if (test_bit(BTUSB_WAKEUP_DISABLE, &data->flags))
3993                 return true;
3994
3995         return !device_may_wakeup(&data->udev->dev);
3996 }
3997
3998 static int btusb_probe(struct usb_interface *intf,
3999                        const struct usb_device_id *id)
4000 {
4001         struct usb_endpoint_descriptor *ep_desc;
4002         struct gpio_desc *reset_gpio;
4003         struct btusb_data *data;
4004         struct hci_dev *hdev;
4005         unsigned ifnum_base;
4006         int i, err;
4007
4008         BT_DBG("intf %p id %p", intf, id);
4009
4010         /* interface numbers are hardcoded in the spec */
4011         if (intf->cur_altsetting->desc.bInterfaceNumber != 0) {
4012                 if (!(id->driver_info & BTUSB_IFNUM_2))
4013                         return -ENODEV;
4014                 if (intf->cur_altsetting->desc.bInterfaceNumber != 2)
4015                         return -ENODEV;
4016         }
4017
4018         ifnum_base = intf->cur_altsetting->desc.bInterfaceNumber;
4019
4020         if (!id->driver_info) {
4021                 const struct usb_device_id *match;
4022
4023                 match = usb_match_id(intf, blacklist_table);
4024                 if (match)
4025                         id = match;
4026         }
4027
4028         if (id->driver_info == BTUSB_IGNORE)
4029                 return -ENODEV;
4030
4031         if (id->driver_info & BTUSB_ATH3012) {
4032                 struct usb_device *udev = interface_to_usbdev(intf);
4033
4034                 /* Old firmware would otherwise let ath3k driver load
4035                  * patch and sysconfig files
4036                  */
4037                 if (le16_to_cpu(udev->descriptor.bcdDevice) <= 0x0001 &&
4038                     !btusb_qca_need_patch(udev))
4039                         return -ENODEV;
4040         }
4041
4042         data = devm_kzalloc(&intf->dev, sizeof(*data), GFP_KERNEL);
4043         if (!data)
4044                 return -ENOMEM;
4045
4046         for (i = 0; i < intf->cur_altsetting->desc.bNumEndpoints; i++) {
4047                 ep_desc = &intf->cur_altsetting->endpoint[i].desc;
4048
4049                 if (!data->intr_ep && usb_endpoint_is_int_in(ep_desc)) {
4050                         data->intr_ep = ep_desc;
4051                         continue;
4052                 }
4053
4054                 if (!data->bulk_tx_ep && usb_endpoint_is_bulk_out(ep_desc)) {
4055                         data->bulk_tx_ep = ep_desc;
4056                         continue;
4057                 }
4058
4059                 if (!data->bulk_rx_ep && usb_endpoint_is_bulk_in(ep_desc)) {
4060                         data->bulk_rx_ep = ep_desc;
4061                         continue;
4062                 }
4063         }
4064
4065         if (!data->intr_ep || !data->bulk_tx_ep || !data->bulk_rx_ep)
4066                 return -ENODEV;
4067
4068         if (id->driver_info & BTUSB_AMP) {
4069                 data->cmdreq_type = USB_TYPE_CLASS | 0x01;
4070                 data->cmdreq = 0x2b;
4071         } else {
4072                 data->cmdreq_type = USB_TYPE_CLASS;
4073                 data->cmdreq = 0x00;
4074         }
4075
4076         data->udev = interface_to_usbdev(intf);
4077         data->intf = intf;
4078
4079         INIT_WORK(&data->work, btusb_work);
4080         INIT_WORK(&data->waker, btusb_waker);
4081         init_usb_anchor(&data->deferred);
4082         init_usb_anchor(&data->tx_anchor);
4083         spin_lock_init(&data->txlock);
4084
4085         init_usb_anchor(&data->intr_anchor);
4086         init_usb_anchor(&data->bulk_anchor);
4087         init_usb_anchor(&data->isoc_anchor);
4088         init_usb_anchor(&data->diag_anchor);
4089         init_usb_anchor(&data->ctrl_anchor);
4090         spin_lock_init(&data->rxlock);
4091
4092         if (id->driver_info & BTUSB_INTEL_NEW) {
4093                 data->recv_event = btusb_recv_event_intel;
4094                 data->recv_bulk = btusb_recv_bulk_intel;
4095                 set_bit(BTUSB_BOOTLOADER, &data->flags);
4096         } else {
4097                 data->recv_event = hci_recv_frame;
4098                 data->recv_bulk = btusb_recv_bulk;
4099         }
4100
4101         hdev = hci_alloc_dev();
4102         if (!hdev)
4103                 return -ENOMEM;
4104
4105         hdev->bus = HCI_USB;
4106         hci_set_drvdata(hdev, data);
4107
4108         if (id->driver_info & BTUSB_AMP)
4109                 hdev->dev_type = HCI_AMP;
4110         else
4111                 hdev->dev_type = HCI_PRIMARY;
4112
4113         data->hdev = hdev;
4114
4115         SET_HCIDEV_DEV(hdev, &intf->dev);
4116
4117         reset_gpio = gpiod_get_optional(&data->udev->dev, "reset",
4118                                         GPIOD_OUT_LOW);
4119         if (IS_ERR(reset_gpio)) {
4120                 err = PTR_ERR(reset_gpio);
4121                 goto out_free_dev;
4122         } else if (reset_gpio) {
4123                 data->reset_gpio = reset_gpio;
4124         }
4125
4126         hdev->open   = btusb_open;
4127         hdev->close  = btusb_close;
4128         hdev->flush  = btusb_flush;
4129         hdev->send   = btusb_send_frame;
4130         hdev->notify = btusb_notify;
4131         hdev->prevent_wake = btusb_prevent_wake;
4132
4133 #ifdef CONFIG_PM
4134         err = btusb_config_oob_wake(hdev);
4135         if (err)
4136                 goto out_free_dev;
4137
4138         /* Marvell devices may need a specific chip configuration */
4139         if (id->driver_info & BTUSB_MARVELL && data->oob_wake_irq) {
4140                 err = marvell_config_oob_wake(hdev);
4141                 if (err)
4142                         goto out_free_dev;
4143         }
4144 #endif
4145         if (id->driver_info & BTUSB_CW6622)
4146                 set_bit(HCI_QUIRK_BROKEN_STORED_LINK_KEY, &hdev->quirks);
4147
4148         if (id->driver_info & BTUSB_BCM2045)
4149                 set_bit(HCI_QUIRK_BROKEN_STORED_LINK_KEY, &hdev->quirks);
4150
4151         if (id->driver_info & BTUSB_BCM92035)
4152                 hdev->setup = btusb_setup_bcm92035;
4153
4154         if (IS_ENABLED(CONFIG_BT_HCIBTUSB_BCM) &&
4155             (id->driver_info & BTUSB_BCM_PATCHRAM)) {
4156                 hdev->manufacturer = 15;
4157                 hdev->setup = btbcm_setup_patchram;
4158                 hdev->set_diag = btusb_bcm_set_diag;
4159                 hdev->set_bdaddr = btbcm_set_bdaddr;
4160
4161                 /* Broadcom LM_DIAG Interface numbers are hardcoded */
4162                 data->diag = usb_ifnum_to_if(data->udev, ifnum_base + 2);
4163         }
4164
4165         if (IS_ENABLED(CONFIG_BT_HCIBTUSB_BCM) &&
4166             (id->driver_info & BTUSB_BCM_APPLE)) {
4167                 hdev->manufacturer = 15;
4168                 hdev->setup = btbcm_setup_apple;
4169                 hdev->set_diag = btusb_bcm_set_diag;
4170
4171                 /* Broadcom LM_DIAG Interface numbers are hardcoded */
4172                 data->diag = usb_ifnum_to_if(data->udev, ifnum_base + 2);
4173         }
4174
4175         if (id->driver_info & BTUSB_INTEL) {
4176                 hdev->manufacturer = 2;
4177                 hdev->setup = btusb_setup_intel;
4178                 hdev->shutdown = btusb_shutdown_intel;
4179                 hdev->set_diag = btintel_set_diag_mfg;
4180                 hdev->set_bdaddr = btintel_set_bdaddr;
4181                 hdev->cmd_timeout = btusb_intel_cmd_timeout;
4182                 set_bit(HCI_QUIRK_STRICT_DUPLICATE_FILTER, &hdev->quirks);
4183                 set_bit(HCI_QUIRK_SIMULTANEOUS_DISCOVERY, &hdev->quirks);
4184                 set_bit(HCI_QUIRK_NON_PERSISTENT_DIAG, &hdev->quirks);
4185         }
4186
4187         if (id->driver_info & BTUSB_INTEL_NEW) {
4188                 hdev->manufacturer = 2;
4189                 hdev->send = btusb_send_frame_intel;
4190                 hdev->setup = btusb_setup_intel_new;
4191                 hdev->shutdown = btusb_shutdown_intel_new;
4192                 hdev->hw_error = btintel_hw_error;
4193                 hdev->set_diag = btintel_set_diag;
4194                 hdev->set_bdaddr = btintel_set_bdaddr;
4195                 hdev->cmd_timeout = btusb_intel_cmd_timeout;
4196                 set_bit(HCI_QUIRK_STRICT_DUPLICATE_FILTER, &hdev->quirks);
4197                 set_bit(HCI_QUIRK_SIMULTANEOUS_DISCOVERY, &hdev->quirks);
4198                 set_bit(HCI_QUIRK_NON_PERSISTENT_DIAG, &hdev->quirks);
4199         }
4200
4201         if (id->driver_info & BTUSB_MARVELL)
4202                 hdev->set_bdaddr = btusb_set_bdaddr_marvell;
4203
4204         if (IS_ENABLED(CONFIG_BT_HCIBTUSB_MTK) &&
4205             (id->driver_info & BTUSB_MEDIATEK)) {
4206                 hdev->setup = btusb_mtk_setup;
4207                 hdev->shutdown = btusb_mtk_shutdown;
4208                 hdev->manufacturer = 70;
4209                 set_bit(HCI_QUIRK_NON_PERSISTENT_SETUP, &hdev->quirks);
4210         }
4211
4212         if (id->driver_info & BTUSB_SWAVE) {
4213                 set_bit(HCI_QUIRK_FIXUP_INQUIRY_MODE, &hdev->quirks);
4214                 set_bit(HCI_QUIRK_BROKEN_LOCAL_COMMANDS, &hdev->quirks);
4215         }
4216
4217         if (id->driver_info & BTUSB_INTEL_BOOT) {
4218                 hdev->manufacturer = 2;
4219                 set_bit(HCI_QUIRK_RAW_DEVICE, &hdev->quirks);
4220         }
4221
4222         if (id->driver_info & BTUSB_ATH3012) {
4223                 data->setup_on_usb = btusb_setup_qca;
4224                 hdev->set_bdaddr = btusb_set_bdaddr_ath3012;
4225                 set_bit(HCI_QUIRK_SIMULTANEOUS_DISCOVERY, &hdev->quirks);
4226                 set_bit(HCI_QUIRK_STRICT_DUPLICATE_FILTER, &hdev->quirks);
4227         }
4228
4229         if (id->driver_info & BTUSB_QCA_ROME) {
4230                 data->setup_on_usb = btusb_setup_qca;
4231                 hdev->set_bdaddr = btusb_set_bdaddr_ath3012;
4232                 hdev->cmd_timeout = btusb_qca_cmd_timeout;
4233                 set_bit(HCI_QUIRK_SIMULTANEOUS_DISCOVERY, &hdev->quirks);
4234                 btusb_check_needs_reset_resume(intf);
4235         }
4236
4237         if (id->driver_info & BTUSB_QCA_WCN6855) {
4238                 data->setup_on_usb = btusb_setup_qca;
4239                 hdev->set_bdaddr = btusb_set_bdaddr_wcn6855;
4240                 hdev->cmd_timeout = btusb_qca_cmd_timeout;
4241                 set_bit(HCI_QUIRK_SIMULTANEOUS_DISCOVERY, &hdev->quirks);
4242         }
4243
4244         if (id->driver_info & BTUSB_AMP) {
4245                 /* AMP controllers do not support SCO packets */
4246                 data->isoc = NULL;
4247         } else {
4248                 /* Interface orders are hardcoded in the specification */
4249                 data->isoc = usb_ifnum_to_if(data->udev, ifnum_base + 1);
4250                 data->isoc_ifnum = ifnum_base + 1;
4251         }
4252
4253         if (IS_ENABLED(CONFIG_BT_HCIBTUSB_RTL) &&
4254             (id->driver_info & BTUSB_REALTEK)) {
4255                 hdev->setup = btrtl_setup_realtek;
4256                 hdev->shutdown = btrtl_shutdown_realtek;
4257                 hdev->cmd_timeout = btusb_rtl_cmd_timeout;
4258
4259                 /* Realtek devices lose their updated firmware over global
4260                  * suspend that means host doesn't send SET_FEATURE
4261                  * (DEVICE_REMOTE_WAKEUP)
4262                  */
4263                 set_bit(BTUSB_WAKEUP_DISABLE, &data->flags);
4264                 set_bit(BTUSB_USE_ALT3_FOR_WBS, &data->flags);
4265         }
4266
4267         if (!reset)
4268                 set_bit(HCI_QUIRK_RESET_ON_CLOSE, &hdev->quirks);
4269
4270         if (force_scofix || id->driver_info & BTUSB_WRONG_SCO_MTU) {
4271                 if (!disable_scofix)
4272                         set_bit(HCI_QUIRK_FIXUP_BUFFER_SIZE, &hdev->quirks);
4273         }
4274
4275         if (id->driver_info & BTUSB_BROKEN_ISOC)
4276                 data->isoc = NULL;
4277
4278         if (id->driver_info & BTUSB_WIDEBAND_SPEECH)
4279                 set_bit(HCI_QUIRK_WIDEBAND_SPEECH_SUPPORTED, &hdev->quirks);
4280
4281         if (id->driver_info & BTUSB_VALID_LE_STATES)
4282                 set_bit(HCI_QUIRK_VALID_LE_STATES, &hdev->quirks);
4283
4284         if (id->driver_info & BTUSB_DIGIANSWER) {
4285                 data->cmdreq_type = USB_TYPE_VENDOR;
4286                 set_bit(HCI_QUIRK_RESET_ON_CLOSE, &hdev->quirks);
4287         }
4288
4289         if (id->driver_info & BTUSB_CSR) {
4290                 struct usb_device *udev = data->udev;
4291                 u16 bcdDevice = le16_to_cpu(udev->descriptor.bcdDevice);
4292
4293                 /* Old firmware would otherwise execute USB reset */
4294                 if (bcdDevice < 0x117)
4295                         set_bit(HCI_QUIRK_RESET_ON_CLOSE, &hdev->quirks);
4296
4297                 /* This must be set first in case we disable it for fakes */
4298                 set_bit(HCI_QUIRK_SIMULTANEOUS_DISCOVERY, &hdev->quirks);
4299
4300                 /* Fake CSR devices with broken commands */
4301                 if (le16_to_cpu(udev->descriptor.idVendor)  == 0x0a12 &&
4302                     le16_to_cpu(udev->descriptor.idProduct) == 0x0001)
4303                         hdev->setup = btusb_setup_csr;
4304         }
4305
4306         if (id->driver_info & BTUSB_SNIFFER) {
4307                 struct usb_device *udev = data->udev;
4308
4309                 /* New sniffer firmware has crippled HCI interface */
4310                 if (le16_to_cpu(udev->descriptor.bcdDevice) > 0x997)
4311                         set_bit(HCI_QUIRK_RAW_DEVICE, &hdev->quirks);
4312         }
4313
4314         if (id->driver_info & BTUSB_INTEL_BOOT) {
4315                 /* A bug in the bootloader causes that interrupt interface is
4316                  * only enabled after receiving SetInterface(0, AltSetting=0).
4317                  */
4318                 err = usb_set_interface(data->udev, 0, 0);
4319                 if (err < 0) {
4320                         BT_ERR("failed to set interface 0, alt 0 %d", err);
4321                         goto out_free_dev;
4322                 }
4323         }
4324
4325         if (data->isoc) {
4326                 err = usb_driver_claim_interface(&btusb_driver,
4327                                                  data->isoc, data);
4328                 if (err < 0)
4329                         goto out_free_dev;
4330         }
4331
4332         if (IS_ENABLED(CONFIG_BT_HCIBTUSB_BCM) && data->diag) {
4333                 if (!usb_driver_claim_interface(&btusb_driver,
4334                                                 data->diag, data))
4335                         __set_diag_interface(hdev);
4336                 else
4337                         data->diag = NULL;
4338         }
4339
4340         if (enable_autosuspend)
4341                 usb_enable_autosuspend(data->udev);
4342
4343         err = hci_register_dev(hdev);
4344         if (err < 0)
4345                 goto out_free_dev;
4346
4347         usb_set_intfdata(intf, data);
4348
4349         return 0;
4350
4351 out_free_dev:
4352         if (data->reset_gpio)
4353                 gpiod_put(data->reset_gpio);
4354         hci_free_dev(hdev);
4355         return err;
4356 }
4357
4358 static void btusb_disconnect(struct usb_interface *intf)
4359 {
4360         struct btusb_data *data = usb_get_intfdata(intf);
4361         struct hci_dev *hdev;
4362
4363         BT_DBG("intf %p", intf);
4364
4365         if (!data)
4366                 return;
4367
4368         hdev = data->hdev;
4369         usb_set_intfdata(data->intf, NULL);
4370
4371         if (data->isoc)
4372                 usb_set_intfdata(data->isoc, NULL);
4373
4374         if (data->diag)
4375                 usb_set_intfdata(data->diag, NULL);
4376
4377         hci_unregister_dev(hdev);
4378
4379         if (intf == data->intf) {
4380                 if (data->isoc)
4381                         usb_driver_release_interface(&btusb_driver, data->isoc);
4382                 if (data->diag)
4383                         usb_driver_release_interface(&btusb_driver, data->diag);
4384         } else if (intf == data->isoc) {
4385                 if (data->diag)
4386                         usb_driver_release_interface(&btusb_driver, data->diag);
4387                 usb_driver_release_interface(&btusb_driver, data->intf);
4388         } else if (intf == data->diag) {
4389                 usb_driver_release_interface(&btusb_driver, data->intf);
4390                 if (data->isoc)
4391                         usb_driver_release_interface(&btusb_driver, data->isoc);
4392         }
4393
4394         if (data->oob_wake_irq)
4395                 device_init_wakeup(&data->udev->dev, false);
4396
4397         if (data->reset_gpio)
4398                 gpiod_put(data->reset_gpio);
4399
4400         hci_free_dev(hdev);
4401 }
4402
4403 #ifdef CONFIG_PM
4404 static int btusb_suspend(struct usb_interface *intf, pm_message_t message)
4405 {
4406         struct btusb_data *data = usb_get_intfdata(intf);
4407
4408         BT_DBG("intf %p", intf);
4409
4410         if (data->suspend_count++)
4411                 return 0;
4412
4413         spin_lock_irq(&data->txlock);
4414         if (!(PMSG_IS_AUTO(message) && data->tx_in_flight)) {
4415                 set_bit(BTUSB_SUSPENDING, &data->flags);
4416                 spin_unlock_irq(&data->txlock);
4417         } else {
4418                 spin_unlock_irq(&data->txlock);
4419                 data->suspend_count--;
4420                 return -EBUSY;
4421         }
4422
4423         cancel_work_sync(&data->work);
4424
4425         btusb_stop_traffic(data);
4426         usb_kill_anchored_urbs(&data->tx_anchor);
4427
4428         if (data->oob_wake_irq && device_may_wakeup(&data->udev->dev)) {
4429                 set_bit(BTUSB_OOB_WAKE_ENABLED, &data->flags);
4430                 enable_irq_wake(data->oob_wake_irq);
4431                 enable_irq(data->oob_wake_irq);
4432         }
4433
4434         /* For global suspend, Realtek devices lose the loaded fw
4435          * in them. But for autosuspend, firmware should remain.
4436          * Actually, it depends on whether the usb host sends
4437          * set feature (enable wakeup) or not.
4438          */
4439         if (test_bit(BTUSB_WAKEUP_DISABLE, &data->flags)) {
4440                 if (PMSG_IS_AUTO(message) &&
4441                     device_can_wakeup(&data->udev->dev))
4442                         data->udev->do_remote_wakeup = 1;
4443                 else if (!PMSG_IS_AUTO(message))
4444                         data->udev->reset_resume = 1;
4445         }
4446
4447         return 0;
4448 }
4449
4450 static void play_deferred(struct btusb_data *data)
4451 {
4452         struct urb *urb;
4453         int err;
4454
4455         while ((urb = usb_get_from_anchor(&data->deferred))) {
4456                 usb_anchor_urb(urb, &data->tx_anchor);
4457
4458                 err = usb_submit_urb(urb, GFP_ATOMIC);
4459                 if (err < 0) {
4460                         if (err != -EPERM && err != -ENODEV)
4461                                 BT_ERR("%s urb %p submission failed (%d)",
4462                                        data->hdev->name, urb, -err);
4463                         kfree(urb->setup_packet);
4464                         usb_unanchor_urb(urb);
4465                         usb_free_urb(urb);
4466                         break;
4467                 }
4468
4469                 data->tx_in_flight++;
4470                 usb_free_urb(urb);
4471         }
4472
4473         /* Cleanup the rest deferred urbs. */
4474         while ((urb = usb_get_from_anchor(&data->deferred))) {
4475                 kfree(urb->setup_packet);
4476                 usb_free_urb(urb);
4477         }
4478 }
4479
4480 static int btusb_resume(struct usb_interface *intf)
4481 {
4482         struct btusb_data *data = usb_get_intfdata(intf);
4483         struct hci_dev *hdev = data->hdev;
4484         int err = 0;
4485
4486         BT_DBG("intf %p", intf);
4487
4488         if (--data->suspend_count)
4489                 return 0;
4490
4491         /* Disable only if not already disabled (keep it balanced) */
4492         if (test_and_clear_bit(BTUSB_OOB_WAKE_ENABLED, &data->flags)) {
4493                 disable_irq(data->oob_wake_irq);
4494                 disable_irq_wake(data->oob_wake_irq);
4495         }
4496
4497         if (!test_bit(HCI_RUNNING, &hdev->flags))
4498                 goto done;
4499
4500         if (test_bit(BTUSB_INTR_RUNNING, &data->flags)) {
4501                 err = btusb_submit_intr_urb(hdev, GFP_NOIO);
4502                 if (err < 0) {
4503                         clear_bit(BTUSB_INTR_RUNNING, &data->flags);
4504                         goto failed;
4505                 }
4506         }
4507
4508         if (test_bit(BTUSB_BULK_RUNNING, &data->flags)) {
4509                 err = btusb_submit_bulk_urb(hdev, GFP_NOIO);
4510                 if (err < 0) {
4511                         clear_bit(BTUSB_BULK_RUNNING, &data->flags);
4512                         goto failed;
4513                 }
4514
4515                 btusb_submit_bulk_urb(hdev, GFP_NOIO);
4516         }
4517
4518         if (test_bit(BTUSB_ISOC_RUNNING, &data->flags)) {
4519                 if (btusb_submit_isoc_urb(hdev, GFP_NOIO) < 0)
4520                         clear_bit(BTUSB_ISOC_RUNNING, &data->flags);
4521                 else
4522                         btusb_submit_isoc_urb(hdev, GFP_NOIO);
4523         }
4524
4525         spin_lock_irq(&data->txlock);
4526         play_deferred(data);
4527         clear_bit(BTUSB_SUSPENDING, &data->flags);
4528         spin_unlock_irq(&data->txlock);
4529         schedule_work(&data->work);
4530
4531         return 0;
4532
4533 failed:
4534         usb_scuttle_anchored_urbs(&data->deferred);
4535 done:
4536         spin_lock_irq(&data->txlock);
4537         clear_bit(BTUSB_SUSPENDING, &data->flags);
4538         spin_unlock_irq(&data->txlock);
4539
4540         return err;
4541 }
4542 #endif
4543
4544 static struct usb_driver btusb_driver = {
4545         .name           = "btusb",
4546         .probe          = btusb_probe,
4547         .disconnect     = btusb_disconnect,
4548 #ifdef CONFIG_PM
4549         .suspend        = btusb_suspend,
4550         .resume         = btusb_resume,
4551 #endif
4552         .id_table       = btusb_table,
4553         .supports_autosuspend = 1,
4554         .disable_hub_initiated_lpm = 1,
4555 };
4556
4557 module_usb_driver(btusb_driver);
4558
4559 module_param(disable_scofix, bool, 0644);
4560 MODULE_PARM_DESC(disable_scofix, "Disable fixup of wrong SCO buffer size");
4561
4562 module_param(force_scofix, bool, 0644);
4563 MODULE_PARM_DESC(force_scofix, "Force fixup of wrong SCO buffers size");
4564
4565 module_param(enable_autosuspend, bool, 0644);
4566 MODULE_PARM_DESC(enable_autosuspend, "Enable USB autosuspend by default");
4567
4568 module_param(reset, bool, 0644);
4569 MODULE_PARM_DESC(reset, "Send HCI reset command on initialization");
4570
4571 MODULE_AUTHOR("Marcel Holtmann <marcel@holtmann.org>");
4572 MODULE_DESCRIPTION("Generic Bluetooth USB driver ver " VERSION);
4573 MODULE_VERSION(VERSION);
4574 MODULE_LICENSE("GPL");