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