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