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