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