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