xref: /openbmc/linux/drivers/hid/hid-sony.c (revision 3fc41476)
1 /*
2  *  HID driver for Sony / PS2 / PS3 / PS4 BD devices.
3  *
4  *  Copyright (c) 1999 Andreas Gal
5  *  Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz>
6  *  Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc
7  *  Copyright (c) 2008 Jiri Slaby
8  *  Copyright (c) 2012 David Dillow <dave@thedillows.org>
9  *  Copyright (c) 2006-2013 Jiri Kosina
10  *  Copyright (c) 2013 Colin Leitner <colin.leitner@gmail.com>
11  *  Copyright (c) 2014-2016 Frank Praznik <frank.praznik@gmail.com>
12  *  Copyright (c) 2018 Todd Kelner
13  */
14 
15 /*
16  * This program is free software; you can redistribute it and/or modify it
17  * under the terms of the GNU General Public License as published by the Free
18  * Software Foundation; either version 2 of the License, or (at your option)
19  * any later version.
20  */
21 
22 /*
23  * NOTE: in order for the Sony PS3 BD Remote Control to be found by
24  * a Bluetooth host, the key combination Start+Enter has to be kept pressed
25  * for about 7 seconds with the Bluetooth Host Controller in discovering mode.
26  *
27  * There will be no PIN request from the device.
28  */
29 
30 #include <linux/device.h>
31 #include <linux/hid.h>
32 #include <linux/module.h>
33 #include <linux/slab.h>
34 #include <linux/leds.h>
35 #include <linux/power_supply.h>
36 #include <linux/spinlock.h>
37 #include <linux/list.h>
38 #include <linux/idr.h>
39 #include <linux/input/mt.h>
40 #include <linux/crc32.h>
41 #include <asm/unaligned.h>
42 
43 #include "hid-ids.h"
44 
45 #define VAIO_RDESC_CONSTANT       BIT(0)
46 #define SIXAXIS_CONTROLLER_USB    BIT(1)
47 #define SIXAXIS_CONTROLLER_BT     BIT(2)
48 #define BUZZ_CONTROLLER           BIT(3)
49 #define PS3REMOTE                 BIT(4)
50 #define DUALSHOCK4_CONTROLLER_USB BIT(5)
51 #define DUALSHOCK4_CONTROLLER_BT  BIT(6)
52 #define DUALSHOCK4_DONGLE         BIT(7)
53 #define MOTION_CONTROLLER_USB     BIT(8)
54 #define MOTION_CONTROLLER_BT      BIT(9)
55 #define NAVIGATION_CONTROLLER_USB BIT(10)
56 #define NAVIGATION_CONTROLLER_BT  BIT(11)
57 #define SINO_LITE_CONTROLLER      BIT(12)
58 #define FUTUREMAX_DANCE_MAT       BIT(13)
59 #define NSG_MR5U_REMOTE_BT        BIT(14)
60 #define NSG_MR7U_REMOTE_BT        BIT(15)
61 #define SHANWAN_GAMEPAD           BIT(16)
62 
63 #define SIXAXIS_CONTROLLER (SIXAXIS_CONTROLLER_USB | SIXAXIS_CONTROLLER_BT)
64 #define MOTION_CONTROLLER (MOTION_CONTROLLER_USB | MOTION_CONTROLLER_BT)
65 #define NAVIGATION_CONTROLLER (NAVIGATION_CONTROLLER_USB |\
66 				NAVIGATION_CONTROLLER_BT)
67 #define DUALSHOCK4_CONTROLLER (DUALSHOCK4_CONTROLLER_USB |\
68 				DUALSHOCK4_CONTROLLER_BT | \
69 				DUALSHOCK4_DONGLE)
70 #define SONY_LED_SUPPORT (SIXAXIS_CONTROLLER | BUZZ_CONTROLLER |\
71 				DUALSHOCK4_CONTROLLER | MOTION_CONTROLLER |\
72 				NAVIGATION_CONTROLLER)
73 #define SONY_BATTERY_SUPPORT (SIXAXIS_CONTROLLER | DUALSHOCK4_CONTROLLER |\
74 				MOTION_CONTROLLER_BT | NAVIGATION_CONTROLLER)
75 #define SONY_FF_SUPPORT (SIXAXIS_CONTROLLER | DUALSHOCK4_CONTROLLER |\
76 				MOTION_CONTROLLER)
77 #define SONY_BT_DEVICE (SIXAXIS_CONTROLLER_BT | DUALSHOCK4_CONTROLLER_BT |\
78 			MOTION_CONTROLLER_BT | NAVIGATION_CONTROLLER_BT)
79 #define NSG_MRXU_REMOTE (NSG_MR5U_REMOTE_BT | NSG_MR7U_REMOTE_BT)
80 
81 #define MAX_LEDS 4
82 #define NSG_MRXU_MAX_X 1667
83 #define NSG_MRXU_MAX_Y 1868
84 
85 
86 /* PS/3 Motion controller */
87 static u8 motion_rdesc[] = {
88 	0x05, 0x01,         /*  Usage Page (Desktop),               */
89 	0x09, 0x04,         /*  Usage (Joystick),                   */
90 	0xA1, 0x01,         /*  Collection (Application),           */
91 	0xA1, 0x02,         /*      Collection (Logical),           */
92 	0x85, 0x01,         /*          Report ID (1),              */
93 	0x75, 0x01,         /*          Report Size (1),            */
94 	0x95, 0x15,         /*          Report Count (21),          */
95 	0x15, 0x00,         /*          Logical Minimum (0),        */
96 	0x25, 0x01,         /*          Logical Maximum (1),        */
97 	0x35, 0x00,         /*          Physical Minimum (0),       */
98 	0x45, 0x01,         /*          Physical Maximum (1),       */
99 	0x05, 0x09,         /*          Usage Page (Button),        */
100 	0x19, 0x01,         /*          Usage Minimum (01h),        */
101 	0x29, 0x15,         /*          Usage Maximum (15h),        */
102 	0x81, 0x02,         /*          Input (Variable),           * Buttons */
103 	0x95, 0x0B,         /*          Report Count (11),          */
104 	0x06, 0x00, 0xFF,   /*          Usage Page (FF00h),         */
105 	0x81, 0x03,         /*          Input (Constant, Variable), * Padding */
106 	0x15, 0x00,         /*          Logical Minimum (0),        */
107 	0x26, 0xFF, 0x00,   /*          Logical Maximum (255),      */
108 	0x05, 0x01,         /*          Usage Page (Desktop),       */
109 	0xA1, 0x00,         /*          Collection (Physical),      */
110 	0x75, 0x08,         /*              Report Size (8),        */
111 	0x95, 0x01,         /*              Report Count (1),       */
112 	0x35, 0x00,         /*              Physical Minimum (0),   */
113 	0x46, 0xFF, 0x00,   /*              Physical Maximum (255), */
114 	0x09, 0x30,         /*              Usage (X),              */
115 	0x81, 0x02,         /*              Input (Variable),       * Trigger */
116 	0xC0,               /*          End Collection,             */
117 	0x06, 0x00, 0xFF,   /*          Usage Page (FF00h),         */
118 	0x75, 0x08,         /*          Report Size (8),            */
119 	0x95, 0x07,         /*          Report Count (7),           * skip 7 bytes */
120 	0x81, 0x02,         /*          Input (Variable),           */
121 	0x05, 0x01,         /*          Usage Page (Desktop),       */
122 	0x75, 0x10,         /*          Report Size (16),           */
123 	0x46, 0xFF, 0xFF,   /*          Physical Maximum (65535),   */
124 	0x27, 0xFF, 0xFF, 0x00, 0x00, /*      Logical Maximum (65535),    */
125 	0x95, 0x03,         /*          Report Count (3),           * 3x Accels */
126 	0x09, 0x33,         /*              Usage (rX),             */
127 	0x09, 0x34,         /*              Usage (rY),             */
128 	0x09, 0x35,         /*              Usage (rZ),             */
129 	0x81, 0x02,         /*          Input (Variable),           */
130 	0x06, 0x00, 0xFF,   /*          Usage Page (FF00h),         */
131 	0x95, 0x03,         /*          Report Count (3),           * Skip Accels 2nd frame */
132 	0x81, 0x02,         /*          Input (Variable),           */
133 	0x05, 0x01,         /*          Usage Page (Desktop),       */
134 	0x09, 0x01,         /*          Usage (Pointer),            */
135 	0x95, 0x03,         /*          Report Count (3),           * 3x Gyros */
136 	0x81, 0x02,         /*          Input (Variable),           */
137 	0x06, 0x00, 0xFF,   /*          Usage Page (FF00h),         */
138 	0x95, 0x03,         /*          Report Count (3),           * Skip Gyros 2nd frame */
139 	0x81, 0x02,         /*          Input (Variable),           */
140 	0x75, 0x0C,         /*          Report Size (12),           */
141 	0x46, 0xFF, 0x0F,   /*          Physical Maximum (4095),    */
142 	0x26, 0xFF, 0x0F,   /*          Logical Maximum (4095),     */
143 	0x95, 0x04,         /*          Report Count (4),           * Skip Temp and Magnetometers */
144 	0x81, 0x02,         /*          Input (Variable),           */
145 	0x75, 0x08,         /*          Report Size (8),            */
146 	0x46, 0xFF, 0x00,   /*          Physical Maximum (255),     */
147 	0x26, 0xFF, 0x00,   /*          Logical Maximum (255),      */
148 	0x95, 0x06,         /*          Report Count (6),           * Skip Timestamp and Extension Bytes */
149 	0x81, 0x02,         /*          Input (Variable),           */
150 	0x75, 0x08,         /*          Report Size (8),            */
151 	0x95, 0x30,         /*          Report Count (48),          */
152 	0x09, 0x01,         /*          Usage (Pointer),            */
153 	0x91, 0x02,         /*          Output (Variable),          */
154 	0x75, 0x08,         /*          Report Size (8),            */
155 	0x95, 0x30,         /*          Report Count (48),          */
156 	0x09, 0x01,         /*          Usage (Pointer),            */
157 	0xB1, 0x02,         /*          Feature (Variable),         */
158 	0xC0,               /*      End Collection,                 */
159 	0xA1, 0x02,         /*      Collection (Logical),           */
160 	0x85, 0x02,         /*          Report ID (2),              */
161 	0x75, 0x08,         /*          Report Size (8),            */
162 	0x95, 0x30,         /*          Report Count (48),          */
163 	0x09, 0x01,         /*          Usage (Pointer),            */
164 	0xB1, 0x02,         /*          Feature (Variable),         */
165 	0xC0,               /*      End Collection,                 */
166 	0xA1, 0x02,         /*      Collection (Logical),           */
167 	0x85, 0xEE,         /*          Report ID (238),            */
168 	0x75, 0x08,         /*          Report Size (8),            */
169 	0x95, 0x30,         /*          Report Count (48),          */
170 	0x09, 0x01,         /*          Usage (Pointer),            */
171 	0xB1, 0x02,         /*          Feature (Variable),         */
172 	0xC0,               /*      End Collection,                 */
173 	0xA1, 0x02,         /*      Collection (Logical),           */
174 	0x85, 0xEF,         /*          Report ID (239),            */
175 	0x75, 0x08,         /*          Report Size (8),            */
176 	0x95, 0x30,         /*          Report Count (48),          */
177 	0x09, 0x01,         /*          Usage (Pointer),            */
178 	0xB1, 0x02,         /*          Feature (Variable),         */
179 	0xC0,               /*      End Collection,                 */
180 	0xC0                /*  End Collection                      */
181 };
182 
183 static u8 ps3remote_rdesc[] = {
184 	0x05, 0x01,          /* GUsagePage Generic Desktop */
185 	0x09, 0x05,          /* LUsage 0x05 [Game Pad] */
186 	0xA1, 0x01,          /* MCollection Application (mouse, keyboard) */
187 
188 	 /* Use collection 1 for joypad buttons */
189 	 0xA1, 0x02,         /* MCollection Logical (interrelated data) */
190 
191 	  /*
192 	   * Ignore the 1st byte, maybe it is used for a controller
193 	   * number but it's not needed for correct operation
194 	   */
195 	  0x75, 0x08,        /* GReportSize 0x08 [8] */
196 	  0x95, 0x01,        /* GReportCount 0x01 [1] */
197 	  0x81, 0x01,        /* MInput 0x01 (Const[0] Arr[1] Abs[2]) */
198 
199 	  /*
200 	   * Bytes from 2nd to 4th are a bitmap for joypad buttons, for these
201 	   * buttons multiple keypresses are allowed
202 	   */
203 	  0x05, 0x09,        /* GUsagePage Button */
204 	  0x19, 0x01,        /* LUsageMinimum 0x01 [Button 1 (primary/trigger)] */
205 	  0x29, 0x18,        /* LUsageMaximum 0x18 [Button 24] */
206 	  0x14,              /* GLogicalMinimum [0] */
207 	  0x25, 0x01,        /* GLogicalMaximum 0x01 [1] */
208 	  0x75, 0x01,        /* GReportSize 0x01 [1] */
209 	  0x95, 0x18,        /* GReportCount 0x18 [24] */
210 	  0x81, 0x02,        /* MInput 0x02 (Data[0] Var[1] Abs[2]) */
211 
212 	  0xC0,              /* MEndCollection */
213 
214 	 /* Use collection 2 for remote control buttons */
215 	 0xA1, 0x02,         /* MCollection Logical (interrelated data) */
216 
217 	  /* 5th byte is used for remote control buttons */
218 	  0x05, 0x09,        /* GUsagePage Button */
219 	  0x18,              /* LUsageMinimum [No button pressed] */
220 	  0x29, 0xFE,        /* LUsageMaximum 0xFE [Button 254] */
221 	  0x14,              /* GLogicalMinimum [0] */
222 	  0x26, 0xFE, 0x00,  /* GLogicalMaximum 0x00FE [254] */
223 	  0x75, 0x08,        /* GReportSize 0x08 [8] */
224 	  0x95, 0x01,        /* GReportCount 0x01 [1] */
225 	  0x80,              /* MInput  */
226 
227 	  /*
228 	   * Ignore bytes from 6th to 11th, 6th to 10th are always constant at
229 	   * 0xff and 11th is for press indication
230 	   */
231 	  0x75, 0x08,        /* GReportSize 0x08 [8] */
232 	  0x95, 0x06,        /* GReportCount 0x06 [6] */
233 	  0x81, 0x01,        /* MInput 0x01 (Const[0] Arr[1] Abs[2]) */
234 
235 	  /* 12th byte is for battery strength */
236 	  0x05, 0x06,        /* GUsagePage Generic Device Controls */
237 	  0x09, 0x20,        /* LUsage 0x20 [Battery Strength] */
238 	  0x14,              /* GLogicalMinimum [0] */
239 	  0x25, 0x05,        /* GLogicalMaximum 0x05 [5] */
240 	  0x75, 0x08,        /* GReportSize 0x08 [8] */
241 	  0x95, 0x01,        /* GReportCount 0x01 [1] */
242 	  0x81, 0x02,        /* MInput 0x02 (Data[0] Var[1] Abs[2]) */
243 
244 	  0xC0,              /* MEndCollection */
245 
246 	 0xC0                /* MEndCollection [Game Pad] */
247 };
248 
249 static const unsigned int ps3remote_keymap_joypad_buttons[] = {
250 	[0x01] = KEY_SELECT,
251 	[0x02] = BTN_THUMBL,		/* L3 */
252 	[0x03] = BTN_THUMBR,		/* R3 */
253 	[0x04] = BTN_START,
254 	[0x05] = KEY_UP,
255 	[0x06] = KEY_RIGHT,
256 	[0x07] = KEY_DOWN,
257 	[0x08] = KEY_LEFT,
258 	[0x09] = BTN_TL2,		/* L2 */
259 	[0x0a] = BTN_TR2,		/* R2 */
260 	[0x0b] = BTN_TL,		/* L1 */
261 	[0x0c] = BTN_TR,		/* R1 */
262 	[0x0d] = KEY_OPTION,		/* options/triangle */
263 	[0x0e] = KEY_BACK,		/* back/circle */
264 	[0x0f] = BTN_0,			/* cross */
265 	[0x10] = KEY_SCREEN,		/* view/square */
266 	[0x11] = KEY_HOMEPAGE,		/* PS button */
267 	[0x14] = KEY_ENTER,
268 };
269 static const unsigned int ps3remote_keymap_remote_buttons[] = {
270 	[0x00] = KEY_1,
271 	[0x01] = KEY_2,
272 	[0x02] = KEY_3,
273 	[0x03] = KEY_4,
274 	[0x04] = KEY_5,
275 	[0x05] = KEY_6,
276 	[0x06] = KEY_7,
277 	[0x07] = KEY_8,
278 	[0x08] = KEY_9,
279 	[0x09] = KEY_0,
280 	[0x0e] = KEY_ESC,		/* return */
281 	[0x0f] = KEY_CLEAR,
282 	[0x16] = KEY_EJECTCD,
283 	[0x1a] = KEY_MENU,		/* top menu */
284 	[0x28] = KEY_TIME,
285 	[0x30] = KEY_PREVIOUS,
286 	[0x31] = KEY_NEXT,
287 	[0x32] = KEY_PLAY,
288 	[0x33] = KEY_REWIND,		/* scan back */
289 	[0x34] = KEY_FORWARD,		/* scan forward */
290 	[0x38] = KEY_STOP,
291 	[0x39] = KEY_PAUSE,
292 	[0x40] = KEY_CONTEXT_MENU,	/* pop up/menu */
293 	[0x60] = KEY_FRAMEBACK,		/* slow/step back */
294 	[0x61] = KEY_FRAMEFORWARD,	/* slow/step forward */
295 	[0x63] = KEY_SUBTITLE,
296 	[0x64] = KEY_AUDIO,
297 	[0x65] = KEY_ANGLE,
298 	[0x70] = KEY_INFO,		/* display */
299 	[0x80] = KEY_BLUE,
300 	[0x81] = KEY_RED,
301 	[0x82] = KEY_GREEN,
302 	[0x83] = KEY_YELLOW,
303 };
304 
305 static const unsigned int buzz_keymap[] = {
306 	/*
307 	 * The controller has 4 remote buzzers, each with one LED and 5
308 	 * buttons.
309 	 *
310 	 * We use the mapping chosen by the controller, which is:
311 	 *
312 	 * Key          Offset
313 	 * -------------------
314 	 * Buzz              1
315 	 * Blue              5
316 	 * Orange            4
317 	 * Green             3
318 	 * Yellow            2
319 	 *
320 	 * So, for example, the orange button on the third buzzer is mapped to
321 	 * BTN_TRIGGER_HAPPY14
322 	 */
323 	 [1] = BTN_TRIGGER_HAPPY1,
324 	 [2] = BTN_TRIGGER_HAPPY2,
325 	 [3] = BTN_TRIGGER_HAPPY3,
326 	 [4] = BTN_TRIGGER_HAPPY4,
327 	 [5] = BTN_TRIGGER_HAPPY5,
328 	 [6] = BTN_TRIGGER_HAPPY6,
329 	 [7] = BTN_TRIGGER_HAPPY7,
330 	 [8] = BTN_TRIGGER_HAPPY8,
331 	 [9] = BTN_TRIGGER_HAPPY9,
332 	[10] = BTN_TRIGGER_HAPPY10,
333 	[11] = BTN_TRIGGER_HAPPY11,
334 	[12] = BTN_TRIGGER_HAPPY12,
335 	[13] = BTN_TRIGGER_HAPPY13,
336 	[14] = BTN_TRIGGER_HAPPY14,
337 	[15] = BTN_TRIGGER_HAPPY15,
338 	[16] = BTN_TRIGGER_HAPPY16,
339 	[17] = BTN_TRIGGER_HAPPY17,
340 	[18] = BTN_TRIGGER_HAPPY18,
341 	[19] = BTN_TRIGGER_HAPPY19,
342 	[20] = BTN_TRIGGER_HAPPY20,
343 };
344 
345 /* The Navigation controller is a partial DS3 and uses the same HID report
346  * and hence the same keymap indices, however not not all axes/buttons
347  * are physically present. We use the same axis and button mapping as
348  * the DS3, which uses the Linux gamepad spec.
349  */
350 static const unsigned int navigation_absmap[] = {
351 	[0x30] = ABS_X,
352 	[0x31] = ABS_Y,
353 	[0x33] = ABS_Z, /* L2 */
354 };
355 
356 /* Buttons not physically available on the device, but still available
357  * in the reports are explicitly set to 0 for documentation purposes.
358  */
359 static const unsigned int navigation_keymap[] = {
360 	[0x01] = 0, /* Select */
361 	[0x02] = BTN_THUMBL, /* L3 */
362 	[0x03] = 0, /* R3 */
363 	[0x04] = 0, /* Start */
364 	[0x05] = BTN_DPAD_UP, /* Up */
365 	[0x06] = BTN_DPAD_RIGHT, /* Right */
366 	[0x07] = BTN_DPAD_DOWN, /* Down */
367 	[0x08] = BTN_DPAD_LEFT, /* Left */
368 	[0x09] = BTN_TL2, /* L2 */
369 	[0x0a] = 0, /* R2 */
370 	[0x0b] = BTN_TL, /* L1 */
371 	[0x0c] = 0, /* R1 */
372 	[0x0d] = BTN_NORTH, /* Triangle */
373 	[0x0e] = BTN_EAST, /* Circle */
374 	[0x0f] = BTN_SOUTH, /* Cross */
375 	[0x10] = BTN_WEST, /* Square */
376 	[0x11] = BTN_MODE, /* PS */
377 };
378 
379 static const unsigned int sixaxis_absmap[] = {
380 	[0x30] = ABS_X,
381 	[0x31] = ABS_Y,
382 	[0x32] = ABS_RX, /* right stick X */
383 	[0x35] = ABS_RY, /* right stick Y */
384 };
385 
386 static const unsigned int sixaxis_keymap[] = {
387 	[0x01] = BTN_SELECT, /* Select */
388 	[0x02] = BTN_THUMBL, /* L3 */
389 	[0x03] = BTN_THUMBR, /* R3 */
390 	[0x04] = BTN_START, /* Start */
391 	[0x05] = BTN_DPAD_UP, /* Up */
392 	[0x06] = BTN_DPAD_RIGHT, /* Right */
393 	[0x07] = BTN_DPAD_DOWN, /* Down */
394 	[0x08] = BTN_DPAD_LEFT, /* Left */
395 	[0x09] = BTN_TL2, /* L2 */
396 	[0x0a] = BTN_TR2, /* R2 */
397 	[0x0b] = BTN_TL, /* L1 */
398 	[0x0c] = BTN_TR, /* R1 */
399 	[0x0d] = BTN_NORTH, /* Triangle */
400 	[0x0e] = BTN_EAST, /* Circle */
401 	[0x0f] = BTN_SOUTH, /* Cross */
402 	[0x10] = BTN_WEST, /* Square */
403 	[0x11] = BTN_MODE, /* PS */
404 };
405 
406 static const unsigned int ds4_absmap[] = {
407 	[0x30] = ABS_X,
408 	[0x31] = ABS_Y,
409 	[0x32] = ABS_RX, /* right stick X */
410 	[0x33] = ABS_Z, /* L2 */
411 	[0x34] = ABS_RZ, /* R2 */
412 	[0x35] = ABS_RY, /* right stick Y */
413 };
414 
415 static const unsigned int ds4_keymap[] = {
416 	[0x1] = BTN_WEST, /* Square */
417 	[0x2] = BTN_SOUTH, /* Cross */
418 	[0x3] = BTN_EAST, /* Circle */
419 	[0x4] = BTN_NORTH, /* Triangle */
420 	[0x5] = BTN_TL, /* L1 */
421 	[0x6] = BTN_TR, /* R1 */
422 	[0x7] = BTN_TL2, /* L2 */
423 	[0x8] = BTN_TR2, /* R2 */
424 	[0x9] = BTN_SELECT, /* Share */
425 	[0xa] = BTN_START, /* Options */
426 	[0xb] = BTN_THUMBL, /* L3 */
427 	[0xc] = BTN_THUMBR, /* R3 */
428 	[0xd] = BTN_MODE, /* PS */
429 };
430 
431 static const struct {int x; int y; } ds4_hat_mapping[] = {
432 	{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1},
433 	{0, 0}
434 };
435 
436 static enum power_supply_property sony_battery_props[] = {
437 	POWER_SUPPLY_PROP_PRESENT,
438 	POWER_SUPPLY_PROP_CAPACITY,
439 	POWER_SUPPLY_PROP_SCOPE,
440 	POWER_SUPPLY_PROP_STATUS,
441 };
442 
443 struct sixaxis_led {
444 	u8 time_enabled; /* the total time the led is active (0xff means forever) */
445 	u8 duty_length;  /* how long a cycle is in deciseconds (0 means "really fast") */
446 	u8 enabled;
447 	u8 duty_off; /* % of duty_length the led is off (0xff means 100%) */
448 	u8 duty_on;  /* % of duty_length the led is on (0xff mean 100%) */
449 } __packed;
450 
451 struct sixaxis_rumble {
452 	u8 padding;
453 	u8 right_duration; /* Right motor duration (0xff means forever) */
454 	u8 right_motor_on; /* Right (small) motor on/off, only supports values of 0 or 1 (off/on) */
455 	u8 left_duration;    /* Left motor duration (0xff means forever) */
456 	u8 left_motor_force; /* left (large) motor, supports force values from 0 to 255 */
457 } __packed;
458 
459 struct sixaxis_output_report {
460 	u8 report_id;
461 	struct sixaxis_rumble rumble;
462 	u8 padding[4];
463 	u8 leds_bitmap; /* bitmap of enabled LEDs: LED_1 = 0x02, LED_2 = 0x04, ... */
464 	struct sixaxis_led led[4];    /* LEDx at (4 - x) */
465 	struct sixaxis_led _reserved; /* LED5, not actually soldered */
466 } __packed;
467 
468 union sixaxis_output_report_01 {
469 	struct sixaxis_output_report data;
470 	u8 buf[36];
471 };
472 
473 struct motion_output_report_02 {
474 	u8 type, zero;
475 	u8 r, g, b;
476 	u8 zero2;
477 	u8 rumble;
478 };
479 
480 #define DS4_FEATURE_REPORT_0x02_SIZE 37
481 #define DS4_FEATURE_REPORT_0x05_SIZE 41
482 #define DS4_FEATURE_REPORT_0x81_SIZE 7
483 #define DS4_FEATURE_REPORT_0xA3_SIZE 49
484 #define DS4_INPUT_REPORT_0x11_SIZE 78
485 #define DS4_OUTPUT_REPORT_0x05_SIZE 32
486 #define DS4_OUTPUT_REPORT_0x11_SIZE 78
487 #define SIXAXIS_REPORT_0xF2_SIZE 17
488 #define SIXAXIS_REPORT_0xF5_SIZE 8
489 #define MOTION_REPORT_0x02_SIZE 49
490 
491 /* Offsets relative to USB input report (0x1). Bluetooth (0x11) requires an
492  * additional +2.
493  */
494 #define DS4_INPUT_REPORT_AXIS_OFFSET      1
495 #define DS4_INPUT_REPORT_BUTTON_OFFSET    5
496 #define DS4_INPUT_REPORT_TIMESTAMP_OFFSET 10
497 #define DS4_INPUT_REPORT_GYRO_X_OFFSET   13
498 #define DS4_INPUT_REPORT_BATTERY_OFFSET  30
499 #define DS4_INPUT_REPORT_TOUCHPAD_OFFSET 33
500 
501 #define SENSOR_SUFFIX " Motion Sensors"
502 #define DS4_TOUCHPAD_SUFFIX " Touchpad"
503 
504 /* Default to 4ms poll interval, which is same as USB (not adjustable). */
505 #define DS4_BT_DEFAULT_POLL_INTERVAL_MS 4
506 #define DS4_BT_MAX_POLL_INTERVAL_MS 62
507 #define DS4_GYRO_RES_PER_DEG_S 1024
508 #define DS4_ACC_RES_PER_G      8192
509 
510 #define SIXAXIS_INPUT_REPORT_ACC_X_OFFSET 41
511 #define SIXAXIS_ACC_RES_PER_G 113
512 
513 static DEFINE_SPINLOCK(sony_dev_list_lock);
514 static LIST_HEAD(sony_device_list);
515 static DEFINE_IDA(sony_device_id_allocator);
516 
517 /* Used for calibration of DS4 accelerometer and gyro. */
518 struct ds4_calibration_data {
519 	int abs_code;
520 	short bias;
521 	/* Calibration requires scaling against a sensitivity value, which is a
522 	 * float. Store sensitivity as a fraction to limit floating point
523 	 * calculations until final calibration.
524 	 */
525 	int sens_numer;
526 	int sens_denom;
527 };
528 
529 enum ds4_dongle_state {
530 	DONGLE_DISCONNECTED,
531 	DONGLE_CALIBRATING,
532 	DONGLE_CONNECTED,
533 	DONGLE_DISABLED
534 };
535 
536 enum sony_worker {
537 	SONY_WORKER_STATE,
538 	SONY_WORKER_HOTPLUG
539 };
540 
541 struct sony_sc {
542 	spinlock_t lock;
543 	struct list_head list_node;
544 	struct hid_device *hdev;
545 	struct input_dev *touchpad;
546 	struct input_dev *sensor_dev;
547 	struct led_classdev *leds[MAX_LEDS];
548 	unsigned long quirks;
549 	struct work_struct hotplug_worker;
550 	struct work_struct state_worker;
551 	void (*send_output_report)(struct sony_sc *);
552 	struct power_supply *battery;
553 	struct power_supply_desc battery_desc;
554 	int device_id;
555 	unsigned fw_version;
556 	unsigned hw_version;
557 	u8 *output_report_dmabuf;
558 
559 #ifdef CONFIG_SONY_FF
560 	u8 left;
561 	u8 right;
562 #endif
563 
564 	u8 mac_address[6];
565 	u8 hotplug_worker_initialized;
566 	u8 state_worker_initialized;
567 	u8 defer_initialization;
568 	u8 cable_state;
569 	u8 battery_charging;
570 	u8 battery_capacity;
571 	u8 led_state[MAX_LEDS];
572 	u8 led_delay_on[MAX_LEDS];
573 	u8 led_delay_off[MAX_LEDS];
574 	u8 led_count;
575 
576 	bool timestamp_initialized;
577 	u16 prev_timestamp;
578 	unsigned int timestamp_us;
579 
580 	u8 ds4_bt_poll_interval;
581 	enum ds4_dongle_state ds4_dongle_state;
582 	/* DS4 calibration data */
583 	struct ds4_calibration_data ds4_calib_data[6];
584 };
585 
586 static void sony_set_leds(struct sony_sc *sc);
587 
588 static inline void sony_schedule_work(struct sony_sc *sc,
589 				      enum sony_worker which)
590 {
591 	switch (which) {
592 	case SONY_WORKER_STATE:
593 		if (!sc->defer_initialization)
594 			schedule_work(&sc->state_worker);
595 		break;
596 	case SONY_WORKER_HOTPLUG:
597 		if (sc->hotplug_worker_initialized)
598 			schedule_work(&sc->hotplug_worker);
599 		break;
600 	}
601 }
602 
603 static ssize_t ds4_show_poll_interval(struct device *dev,
604 				struct device_attribute
605 				*attr, char *buf)
606 {
607 	struct hid_device *hdev = to_hid_device(dev);
608 	struct sony_sc *sc = hid_get_drvdata(hdev);
609 
610 	return snprintf(buf, PAGE_SIZE, "%i\n", sc->ds4_bt_poll_interval);
611 }
612 
613 static ssize_t ds4_store_poll_interval(struct device *dev,
614 				struct device_attribute *attr,
615 				const char *buf, size_t count)
616 {
617 	struct hid_device *hdev = to_hid_device(dev);
618 	struct sony_sc *sc = hid_get_drvdata(hdev);
619 	unsigned long flags;
620 	u8 interval;
621 
622 	if (kstrtou8(buf, 0, &interval))
623 		return -EINVAL;
624 
625 	if (interval > DS4_BT_MAX_POLL_INTERVAL_MS)
626 		return -EINVAL;
627 
628 	spin_lock_irqsave(&sc->lock, flags);
629 	sc->ds4_bt_poll_interval = interval;
630 	spin_unlock_irqrestore(&sc->lock, flags);
631 
632 	sony_schedule_work(sc, SONY_WORKER_STATE);
633 
634 	return count;
635 }
636 
637 static DEVICE_ATTR(bt_poll_interval, 0644, ds4_show_poll_interval,
638 		ds4_store_poll_interval);
639 
640 static ssize_t sony_show_firmware_version(struct device *dev,
641 				struct device_attribute
642 				*attr, char *buf)
643 {
644 	struct hid_device *hdev = to_hid_device(dev);
645 	struct sony_sc *sc = hid_get_drvdata(hdev);
646 
647 	return snprintf(buf, PAGE_SIZE, "0x%04x\n", sc->fw_version);
648 }
649 
650 static DEVICE_ATTR(firmware_version, 0444, sony_show_firmware_version, NULL);
651 
652 static ssize_t sony_show_hardware_version(struct device *dev,
653 				struct device_attribute
654 				*attr, char *buf)
655 {
656 	struct hid_device *hdev = to_hid_device(dev);
657 	struct sony_sc *sc = hid_get_drvdata(hdev);
658 
659 	return snprintf(buf, PAGE_SIZE, "0x%04x\n", sc->hw_version);
660 }
661 
662 static DEVICE_ATTR(hardware_version, 0444, sony_show_hardware_version, NULL);
663 
664 static u8 *motion_fixup(struct hid_device *hdev, u8 *rdesc,
665 			     unsigned int *rsize)
666 {
667 	*rsize = sizeof(motion_rdesc);
668 	return motion_rdesc;
669 }
670 
671 static u8 *ps3remote_fixup(struct hid_device *hdev, u8 *rdesc,
672 			     unsigned int *rsize)
673 {
674 	*rsize = sizeof(ps3remote_rdesc);
675 	return ps3remote_rdesc;
676 }
677 
678 static int ps3remote_mapping(struct hid_device *hdev, struct hid_input *hi,
679 			     struct hid_field *field, struct hid_usage *usage,
680 			     unsigned long **bit, int *max)
681 {
682 	unsigned int key = usage->hid & HID_USAGE;
683 
684 	if ((usage->hid & HID_USAGE_PAGE) != HID_UP_BUTTON)
685 		return -1;
686 
687 	switch (usage->collection_index) {
688 	case 1:
689 		if (key >= ARRAY_SIZE(ps3remote_keymap_joypad_buttons))
690 			return -1;
691 
692 		key = ps3remote_keymap_joypad_buttons[key];
693 		if (!key)
694 			return -1;
695 		break;
696 	case 2:
697 		if (key >= ARRAY_SIZE(ps3remote_keymap_remote_buttons))
698 			return -1;
699 
700 		key = ps3remote_keymap_remote_buttons[key];
701 		if (!key)
702 			return -1;
703 		break;
704 	default:
705 		return -1;
706 	}
707 
708 	hid_map_usage_clear(hi, usage, bit, max, EV_KEY, key);
709 	return 1;
710 }
711 
712 static int navigation_mapping(struct hid_device *hdev, struct hid_input *hi,
713 			  struct hid_field *field, struct hid_usage *usage,
714 			  unsigned long **bit, int *max)
715 {
716 	if ((usage->hid & HID_USAGE_PAGE) == HID_UP_BUTTON) {
717 		unsigned int key = usage->hid & HID_USAGE;
718 
719 		if (key >= ARRAY_SIZE(sixaxis_keymap))
720 			return -1;
721 
722 		key = navigation_keymap[key];
723 		if (!key)
724 			return -1;
725 
726 		hid_map_usage_clear(hi, usage, bit, max, EV_KEY, key);
727 		return 1;
728 	} else if (usage->hid == HID_GD_POINTER) {
729 		/* See comment in sixaxis_mapping, basically the L2 (and R2)
730 		 * triggers are reported through GD Pointer.
731 		 * In addition we ignore any analog button 'axes' and only
732 		 * support digital buttons.
733 		 */
734 		switch (usage->usage_index) {
735 		case 8: /* L2 */
736 			usage->hid = HID_GD_Z;
737 			break;
738 		default:
739 			return -1;
740 		}
741 
742 		hid_map_usage_clear(hi, usage, bit, max, EV_ABS, usage->hid & 0xf);
743 		return 1;
744 	} else if ((usage->hid & HID_USAGE_PAGE) == HID_UP_GENDESK) {
745 		unsigned int abs = usage->hid & HID_USAGE;
746 
747 		if (abs >= ARRAY_SIZE(navigation_absmap))
748 			return -1;
749 
750 		abs = navigation_absmap[abs];
751 
752 		hid_map_usage_clear(hi, usage, bit, max, EV_ABS, abs);
753 		return 1;
754 	}
755 
756 	return -1;
757 }
758 
759 
760 static int sixaxis_mapping(struct hid_device *hdev, struct hid_input *hi,
761 			  struct hid_field *field, struct hid_usage *usage,
762 			  unsigned long **bit, int *max)
763 {
764 	if ((usage->hid & HID_USAGE_PAGE) == HID_UP_BUTTON) {
765 		unsigned int key = usage->hid & HID_USAGE;
766 
767 		if (key >= ARRAY_SIZE(sixaxis_keymap))
768 			return -1;
769 
770 		key = sixaxis_keymap[key];
771 		hid_map_usage_clear(hi, usage, bit, max, EV_KEY, key);
772 		return 1;
773 	} else if (usage->hid == HID_GD_POINTER) {
774 		/* The DS3 provides analog values for most buttons and even
775 		 * for HAT axes through GD Pointer. L2 and R2 are reported
776 		 * among these as well instead of as GD Z / RZ. Remap L2
777 		 * and R2 and ignore other analog 'button axes' as there is
778 		 * no good way for reporting them.
779 		 */
780 		switch (usage->usage_index) {
781 		case 8: /* L2 */
782 			usage->hid = HID_GD_Z;
783 			break;
784 		case 9: /* R2 */
785 			usage->hid = HID_GD_RZ;
786 			break;
787 		default:
788 			return -1;
789 		}
790 
791 		hid_map_usage_clear(hi, usage, bit, max, EV_ABS, usage->hid & 0xf);
792 		return 1;
793 	} else if ((usage->hid & HID_USAGE_PAGE) == HID_UP_GENDESK) {
794 		unsigned int abs = usage->hid & HID_USAGE;
795 
796 		if (abs >= ARRAY_SIZE(sixaxis_absmap))
797 			return -1;
798 
799 		abs = sixaxis_absmap[abs];
800 
801 		hid_map_usage_clear(hi, usage, bit, max, EV_ABS, abs);
802 		return 1;
803 	}
804 
805 	return -1;
806 }
807 
808 static int ds4_mapping(struct hid_device *hdev, struct hid_input *hi,
809 		       struct hid_field *field, struct hid_usage *usage,
810 		       unsigned long **bit, int *max)
811 {
812 	if ((usage->hid & HID_USAGE_PAGE) == HID_UP_BUTTON) {
813 		unsigned int key = usage->hid & HID_USAGE;
814 
815 		if (key >= ARRAY_SIZE(ds4_keymap))
816 			return -1;
817 
818 		key = ds4_keymap[key];
819 		hid_map_usage_clear(hi, usage, bit, max, EV_KEY, key);
820 		return 1;
821 	} else if ((usage->hid & HID_USAGE_PAGE) == HID_UP_GENDESK) {
822 		unsigned int abs = usage->hid & HID_USAGE;
823 
824 		/* Let the HID parser deal with the HAT. */
825 		if (usage->hid == HID_GD_HATSWITCH)
826 			return 0;
827 
828 		if (abs >= ARRAY_SIZE(ds4_absmap))
829 			return -1;
830 
831 		abs = ds4_absmap[abs];
832 		hid_map_usage_clear(hi, usage, bit, max, EV_ABS, abs);
833 		return 1;
834 	}
835 
836 	return 0;
837 }
838 
839 static u8 *sony_report_fixup(struct hid_device *hdev, u8 *rdesc,
840 		unsigned int *rsize)
841 {
842 	struct sony_sc *sc = hid_get_drvdata(hdev);
843 
844 	if (sc->quirks & (SINO_LITE_CONTROLLER | FUTUREMAX_DANCE_MAT))
845 		return rdesc;
846 
847 	/*
848 	 * Some Sony RF receivers wrongly declare the mouse pointer as a
849 	 * a constant non-data variable.
850 	 */
851 	if ((sc->quirks & VAIO_RDESC_CONSTANT) && *rsize >= 56 &&
852 	    /* usage page: generic desktop controls */
853 	    /* rdesc[0] == 0x05 && rdesc[1] == 0x01 && */
854 	    /* usage: mouse */
855 	    rdesc[2] == 0x09 && rdesc[3] == 0x02 &&
856 	    /* input (usage page for x,y axes): constant, variable, relative */
857 	    rdesc[54] == 0x81 && rdesc[55] == 0x07) {
858 		hid_info(hdev, "Fixing up Sony RF Receiver report descriptor\n");
859 		/* input: data, variable, relative */
860 		rdesc[55] = 0x06;
861 	}
862 
863 	if (sc->quirks & MOTION_CONTROLLER)
864 		return motion_fixup(hdev, rdesc, rsize);
865 
866 	if (sc->quirks & PS3REMOTE)
867 		return ps3remote_fixup(hdev, rdesc, rsize);
868 
869 	return rdesc;
870 }
871 
872 static void sixaxis_parse_report(struct sony_sc *sc, u8 *rd, int size)
873 {
874 	static const u8 sixaxis_battery_capacity[] = { 0, 1, 25, 50, 75, 100 };
875 	unsigned long flags;
876 	int offset;
877 	u8 cable_state, battery_capacity, battery_charging;
878 
879 	/*
880 	 * The sixaxis is charging if the battery value is 0xee
881 	 * and it is fully charged if the value is 0xef.
882 	 * It does not report the actual level while charging so it
883 	 * is set to 100% while charging is in progress.
884 	 */
885 	offset = (sc->quirks & MOTION_CONTROLLER) ? 12 : 30;
886 
887 	if (rd[offset] >= 0xee) {
888 		battery_capacity = 100;
889 		battery_charging = !(rd[offset] & 0x01);
890 		cable_state = 1;
891 	} else {
892 		u8 index = rd[offset] <= 5 ? rd[offset] : 5;
893 		battery_capacity = sixaxis_battery_capacity[index];
894 		battery_charging = 0;
895 		cable_state = 0;
896 	}
897 
898 	spin_lock_irqsave(&sc->lock, flags);
899 	sc->cable_state = cable_state;
900 	sc->battery_capacity = battery_capacity;
901 	sc->battery_charging = battery_charging;
902 	spin_unlock_irqrestore(&sc->lock, flags);
903 
904 	if (sc->quirks & SIXAXIS_CONTROLLER) {
905 		int val;
906 
907 		offset = SIXAXIS_INPUT_REPORT_ACC_X_OFFSET;
908 		val = ((rd[offset+1] << 8) | rd[offset]) - 511;
909 		input_report_abs(sc->sensor_dev, ABS_X, val);
910 
911 		/* Y and Z are swapped and inversed */
912 		val = 511 - ((rd[offset+5] << 8) | rd[offset+4]);
913 		input_report_abs(sc->sensor_dev, ABS_Y, val);
914 
915 		val = 511 - ((rd[offset+3] << 8) | rd[offset+2]);
916 		input_report_abs(sc->sensor_dev, ABS_Z, val);
917 
918 		input_sync(sc->sensor_dev);
919 	}
920 }
921 
922 static void dualshock4_parse_report(struct sony_sc *sc, u8 *rd, int size)
923 {
924 	struct hid_input *hidinput = list_entry(sc->hdev->inputs.next,
925 						struct hid_input, list);
926 	struct input_dev *input_dev = hidinput->input;
927 	unsigned long flags;
928 	int n, m, offset, num_touch_data, max_touch_data;
929 	u8 cable_state, battery_capacity, battery_charging;
930 	u16 timestamp;
931 
932 	/* When using Bluetooth the header is 2 bytes longer, so skip these. */
933 	int data_offset = (sc->quirks & DUALSHOCK4_CONTROLLER_BT) ? 2 : 0;
934 
935 	/* Second bit of third button byte is for the touchpad button. */
936 	offset = data_offset + DS4_INPUT_REPORT_BUTTON_OFFSET;
937 	input_report_key(sc->touchpad, BTN_LEFT, rd[offset+2] & 0x2);
938 
939 	/*
940 	 * The default behavior of the Dualshock 4 is to send reports using
941 	 * report type 1 when running over Bluetooth. However, when feature
942 	 * report 2 is requested during the controller initialization it starts
943 	 * sending input reports in report 17. Since report 17 is undefined
944 	 * in the default HID descriptor, the HID layer won't generate events.
945 	 * While it is possible (and this was done before) to fixup the HID
946 	 * descriptor to add this mapping, it was better to do this manually.
947 	 * The reason is there were various pieces software both open and closed
948 	 * source, relying on the descriptors to be the same across various
949 	 * operating systems. If the descriptors wouldn't match some
950 	 * applications e.g. games on Wine would not be able to function due
951 	 * to different descriptors, which such applications are not parsing.
952 	 */
953 	if (rd[0] == 17) {
954 		int value;
955 
956 		offset = data_offset + DS4_INPUT_REPORT_AXIS_OFFSET;
957 		input_report_abs(input_dev, ABS_X, rd[offset]);
958 		input_report_abs(input_dev, ABS_Y, rd[offset+1]);
959 		input_report_abs(input_dev, ABS_RX, rd[offset+2]);
960 		input_report_abs(input_dev, ABS_RY, rd[offset+3]);
961 
962 		value = rd[offset+4] & 0xf;
963 		if (value > 7)
964 			value = 8; /* Center 0, 0 */
965 		input_report_abs(input_dev, ABS_HAT0X, ds4_hat_mapping[value].x);
966 		input_report_abs(input_dev, ABS_HAT0Y, ds4_hat_mapping[value].y);
967 
968 		input_report_key(input_dev, BTN_WEST, rd[offset+4] & 0x10);
969 		input_report_key(input_dev, BTN_SOUTH, rd[offset+4] & 0x20);
970 		input_report_key(input_dev, BTN_EAST, rd[offset+4] & 0x40);
971 		input_report_key(input_dev, BTN_NORTH, rd[offset+4] & 0x80);
972 
973 		input_report_key(input_dev, BTN_TL, rd[offset+5] & 0x1);
974 		input_report_key(input_dev, BTN_TR, rd[offset+5] & 0x2);
975 		input_report_key(input_dev, BTN_TL2, rd[offset+5] & 0x4);
976 		input_report_key(input_dev, BTN_TR2, rd[offset+5] & 0x8);
977 		input_report_key(input_dev, BTN_SELECT, rd[offset+5] & 0x10);
978 		input_report_key(input_dev, BTN_START, rd[offset+5] & 0x20);
979 		input_report_key(input_dev, BTN_THUMBL, rd[offset+5] & 0x40);
980 		input_report_key(input_dev, BTN_THUMBR, rd[offset+5] & 0x80);
981 
982 		input_report_key(input_dev, BTN_MODE, rd[offset+6] & 0x1);
983 
984 		input_report_abs(input_dev, ABS_Z, rd[offset+7]);
985 		input_report_abs(input_dev, ABS_RZ, rd[offset+8]);
986 
987 		input_sync(input_dev);
988 	}
989 
990 	/* Convert timestamp (in 5.33us unit) to timestamp_us */
991 	offset = data_offset + DS4_INPUT_REPORT_TIMESTAMP_OFFSET;
992 	timestamp = get_unaligned_le16(&rd[offset]);
993 	if (!sc->timestamp_initialized) {
994 		sc->timestamp_us = ((unsigned int)timestamp * 16) / 3;
995 		sc->timestamp_initialized = true;
996 	} else {
997 		u16 delta;
998 
999 		if (sc->prev_timestamp > timestamp)
1000 			delta = (U16_MAX - sc->prev_timestamp + timestamp + 1);
1001 		else
1002 			delta = timestamp - sc->prev_timestamp;
1003 		sc->timestamp_us += (delta * 16) / 3;
1004 	}
1005 	sc->prev_timestamp = timestamp;
1006 	input_event(sc->sensor_dev, EV_MSC, MSC_TIMESTAMP, sc->timestamp_us);
1007 
1008 	offset = data_offset + DS4_INPUT_REPORT_GYRO_X_OFFSET;
1009 	for (n = 0; n < 6; n++) {
1010 		/* Store data in int for more precision during mult_frac. */
1011 		int raw_data = (short)((rd[offset+1] << 8) | rd[offset]);
1012 		struct ds4_calibration_data *calib = &sc->ds4_calib_data[n];
1013 
1014 		/* High precision is needed during calibration, but the
1015 		 * calibrated values are within 32-bit.
1016 		 * Note: we swap numerator 'x' and 'numer' in mult_frac for
1017 		 *       precision reasons so we don't need 64-bit.
1018 		 */
1019 		int calib_data = mult_frac(calib->sens_numer,
1020 					   raw_data - calib->bias,
1021 					   calib->sens_denom);
1022 
1023 		input_report_abs(sc->sensor_dev, calib->abs_code, calib_data);
1024 		offset += 2;
1025 	}
1026 	input_sync(sc->sensor_dev);
1027 
1028 	/*
1029 	 * The lower 4 bits of byte 30 (or 32 for BT) contain the battery level
1030 	 * and the 5th bit contains the USB cable state.
1031 	 */
1032 	offset = data_offset + DS4_INPUT_REPORT_BATTERY_OFFSET;
1033 	cable_state = (rd[offset] >> 4) & 0x01;
1034 	battery_capacity = rd[offset] & 0x0F;
1035 
1036 	/*
1037 	 * When a USB power source is connected the battery level ranges from
1038 	 * 0 to 10, and when running on battery power it ranges from 0 to 9.
1039 	 * A battery level above 10 when plugged in means charge completed.
1040 	 */
1041 	if (!cable_state || battery_capacity > 10)
1042 		battery_charging = 0;
1043 	else
1044 		battery_charging = 1;
1045 
1046 	if (!cable_state)
1047 		battery_capacity++;
1048 	if (battery_capacity > 10)
1049 		battery_capacity = 10;
1050 
1051 	battery_capacity *= 10;
1052 
1053 	spin_lock_irqsave(&sc->lock, flags);
1054 	sc->cable_state = cable_state;
1055 	sc->battery_capacity = battery_capacity;
1056 	sc->battery_charging = battery_charging;
1057 	spin_unlock_irqrestore(&sc->lock, flags);
1058 
1059 	/*
1060 	 * The Dualshock 4 multi-touch trackpad data starts at offset 33 on USB
1061 	 * and 35 on Bluetooth.
1062 	 * The first byte indicates the number of touch data in the report.
1063 	 * Trackpad data starts 2 bytes later (e.g. 35 for USB).
1064 	 */
1065 	offset = data_offset + DS4_INPUT_REPORT_TOUCHPAD_OFFSET;
1066 	max_touch_data = (sc->quirks & DUALSHOCK4_CONTROLLER_BT) ? 4 : 3;
1067 	if (rd[offset] > 0 && rd[offset] <= max_touch_data)
1068 		num_touch_data = rd[offset];
1069 	else
1070 		num_touch_data = 1;
1071 	offset += 1;
1072 
1073 	for (m = 0; m < num_touch_data; m++) {
1074 		/* Skip past timestamp */
1075 		offset += 1;
1076 
1077 		/*
1078 		 * The first 7 bits of the first byte is a counter and bit 8 is
1079 		 * a touch indicator that is 0 when pressed and 1 when not
1080 		 * pressed.
1081 		 * The next 3 bytes are two 12 bit touch coordinates, X and Y.
1082 		 * The data for the second touch is in the same format and
1083 		 * immediately follows the data for the first.
1084 		 */
1085 		for (n = 0; n < 2; n++) {
1086 			u16 x, y;
1087 			bool active;
1088 
1089 			x = rd[offset+1] | ((rd[offset+2] & 0xF) << 8);
1090 			y = ((rd[offset+2] & 0xF0) >> 4) | (rd[offset+3] << 4);
1091 
1092 			active = !(rd[offset] >> 7);
1093 			input_mt_slot(sc->touchpad, n);
1094 			input_mt_report_slot_state(sc->touchpad, MT_TOOL_FINGER, active);
1095 
1096 			if (active) {
1097 				input_report_abs(sc->touchpad, ABS_MT_POSITION_X, x);
1098 				input_report_abs(sc->touchpad, ABS_MT_POSITION_Y, y);
1099 			}
1100 
1101 			offset += 4;
1102 		}
1103 		input_mt_sync_frame(sc->touchpad);
1104 		input_sync(sc->touchpad);
1105 	}
1106 }
1107 
1108 static void nsg_mrxu_parse_report(struct sony_sc *sc, u8 *rd, int size)
1109 {
1110 	int n, offset, relx, rely;
1111 	u8 active;
1112 
1113 	/*
1114 	 * The NSG-MRxU multi-touch trackpad data starts at offset 1 and
1115 	 *   the touch-related data starts at offset 2.
1116 	 * For the first byte, bit 0 is set when touchpad button is pressed.
1117 	 * Bit 2 is set when a touch is active and the drag (Fn) key is pressed.
1118 	 * This drag key is mapped to BTN_LEFT.  It is operational only when a
1119 	 *   touch point is active.
1120 	 * Bit 4 is set when only the first touch point is active.
1121 	 * Bit 6 is set when only the second touch point is active.
1122 	 * Bits 5 and 7 are set when both touch points are active.
1123 	 * The next 3 bytes are two 12 bit X/Y coordinates for the first touch.
1124 	 * The following byte, offset 5, has the touch width and length.
1125 	 *   Bits 0-4=X (width), bits 5-7=Y (length).
1126 	 * A signed relative X coordinate is at offset 6.
1127 	 * The bytes at offset 7-9 are the second touch X/Y coordinates.
1128 	 * Offset 10 has the second touch width and length.
1129 	 * Offset 11 has the relative Y coordinate.
1130 	 */
1131 	offset = 1;
1132 
1133 	input_report_key(sc->touchpad, BTN_LEFT, rd[offset] & 0x0F);
1134 	active = (rd[offset] >> 4);
1135 	relx = (s8) rd[offset+5];
1136 	rely = ((s8) rd[offset+10]) * -1;
1137 
1138 	offset++;
1139 
1140 	for (n = 0; n < 2; n++) {
1141 		u16 x, y;
1142 		u8 contactx, contacty;
1143 
1144 		x = rd[offset] | ((rd[offset+1] & 0x0F) << 8);
1145 		y = ((rd[offset+1] & 0xF0) >> 4) | (rd[offset+2] << 4);
1146 
1147 		input_mt_slot(sc->touchpad, n);
1148 		input_mt_report_slot_state(sc->touchpad, MT_TOOL_FINGER, active & 0x03);
1149 
1150 		if (active & 0x03) {
1151 			contactx = rd[offset+3] & 0x0F;
1152 			contacty = rd[offset+3] >> 4;
1153 			input_report_abs(sc->touchpad, ABS_MT_TOUCH_MAJOR,
1154 				max(contactx, contacty));
1155 			input_report_abs(sc->touchpad, ABS_MT_TOUCH_MINOR,
1156 				min(contactx, contacty));
1157 			input_report_abs(sc->touchpad, ABS_MT_ORIENTATION,
1158 				(bool) (contactx > contacty));
1159 			input_report_abs(sc->touchpad, ABS_MT_POSITION_X, x);
1160 			input_report_abs(sc->touchpad, ABS_MT_POSITION_Y,
1161 				NSG_MRXU_MAX_Y - y);
1162 			/*
1163 			 * The relative coordinates belong to the first touch
1164 			 * point, when present, or to the second touch point
1165 			 * when the first is not active.
1166 			 */
1167 			if ((n == 0) || ((n == 1) && (active & 0x01))) {
1168 				input_report_rel(sc->touchpad, REL_X, relx);
1169 				input_report_rel(sc->touchpad, REL_Y, rely);
1170 			}
1171 		}
1172 
1173 		offset += 5;
1174 		active >>= 2;
1175 	}
1176 
1177 	input_mt_sync_frame(sc->touchpad);
1178 
1179 	input_sync(sc->touchpad);
1180 }
1181 
1182 static int sony_raw_event(struct hid_device *hdev, struct hid_report *report,
1183 		u8 *rd, int size)
1184 {
1185 	struct sony_sc *sc = hid_get_drvdata(hdev);
1186 
1187 	/*
1188 	 * Sixaxis HID report has acclerometers/gyro with MSByte first, this
1189 	 * has to be BYTE_SWAPPED before passing up to joystick interface
1190 	 */
1191 	if ((sc->quirks & SIXAXIS_CONTROLLER) && rd[0] == 0x01 && size == 49) {
1192 		/*
1193 		 * When connected via Bluetooth the Sixaxis occasionally sends
1194 		 * a report with the second byte 0xff and the rest zeroed.
1195 		 *
1196 		 * This report does not reflect the actual state of the
1197 		 * controller must be ignored to avoid generating false input
1198 		 * events.
1199 		 */
1200 		if (rd[1] == 0xff)
1201 			return -EINVAL;
1202 
1203 		swap(rd[41], rd[42]);
1204 		swap(rd[43], rd[44]);
1205 		swap(rd[45], rd[46]);
1206 		swap(rd[47], rd[48]);
1207 
1208 		sixaxis_parse_report(sc, rd, size);
1209 	} else if ((sc->quirks & MOTION_CONTROLLER_BT) && rd[0] == 0x01 && size == 49) {
1210 		sixaxis_parse_report(sc, rd, size);
1211 	} else if ((sc->quirks & NAVIGATION_CONTROLLER) && rd[0] == 0x01 &&
1212 			size == 49) {
1213 		sixaxis_parse_report(sc, rd, size);
1214 	} else if ((sc->quirks & DUALSHOCK4_CONTROLLER_USB) && rd[0] == 0x01 &&
1215 			size == 64) {
1216 		dualshock4_parse_report(sc, rd, size);
1217 	} else if (((sc->quirks & DUALSHOCK4_CONTROLLER_BT) && rd[0] == 0x11 &&
1218 			size == 78)) {
1219 		/* CRC check */
1220 		u8 bthdr = 0xA1;
1221 		u32 crc;
1222 		u32 report_crc;
1223 
1224 		crc = crc32_le(0xFFFFFFFF, &bthdr, 1);
1225 		crc = ~crc32_le(crc, rd, DS4_INPUT_REPORT_0x11_SIZE-4);
1226 		report_crc = get_unaligned_le32(&rd[DS4_INPUT_REPORT_0x11_SIZE-4]);
1227 		if (crc != report_crc) {
1228 			hid_dbg(sc->hdev, "DualShock 4 input report's CRC check failed, received crc 0x%0x != 0x%0x\n",
1229 				report_crc, crc);
1230 			return -EILSEQ;
1231 		}
1232 
1233 		dualshock4_parse_report(sc, rd, size);
1234 	} else if ((sc->quirks & DUALSHOCK4_DONGLE) && rd[0] == 0x01 &&
1235 			size == 64) {
1236 		unsigned long flags;
1237 		enum ds4_dongle_state dongle_state;
1238 
1239 		/*
1240 		 * In the case of a DS4 USB dongle, bit[2] of byte 31 indicates
1241 		 * if a DS4 is actually connected (indicated by '0').
1242 		 * For non-dongle, this bit is always 0 (connected).
1243 		 */
1244 		bool connected = (rd[31] & 0x04) ? false : true;
1245 
1246 		spin_lock_irqsave(&sc->lock, flags);
1247 		dongle_state = sc->ds4_dongle_state;
1248 		spin_unlock_irqrestore(&sc->lock, flags);
1249 
1250 		/*
1251 		 * The dongle always sends input reports even when no
1252 		 * DS4 is attached. When a DS4 is connected, we need to
1253 		 * obtain calibration data before we can use it.
1254 		 * The code below tracks dongle state and kicks of
1255 		 * calibration when needed and only allows us to process
1256 		 * input if a DS4 is actually connected.
1257 		 */
1258 		if (dongle_state == DONGLE_DISCONNECTED && connected) {
1259 			hid_info(sc->hdev, "DualShock 4 USB dongle: controller connected\n");
1260 			sony_set_leds(sc);
1261 
1262 			spin_lock_irqsave(&sc->lock, flags);
1263 			sc->ds4_dongle_state = DONGLE_CALIBRATING;
1264 			spin_unlock_irqrestore(&sc->lock, flags);
1265 
1266 			sony_schedule_work(sc, SONY_WORKER_HOTPLUG);
1267 
1268 			/* Don't process the report since we don't have
1269 			 * calibration data, but let hidraw have it anyway.
1270 			 */
1271 			return 0;
1272 		} else if ((dongle_state == DONGLE_CONNECTED ||
1273 			    dongle_state == DONGLE_DISABLED) && !connected) {
1274 			hid_info(sc->hdev, "DualShock 4 USB dongle: controller disconnected\n");
1275 
1276 			spin_lock_irqsave(&sc->lock, flags);
1277 			sc->ds4_dongle_state = DONGLE_DISCONNECTED;
1278 			spin_unlock_irqrestore(&sc->lock, flags);
1279 
1280 			/* Return 0, so hidraw can get the report. */
1281 			return 0;
1282 		} else if (dongle_state == DONGLE_CALIBRATING ||
1283 			   dongle_state == DONGLE_DISABLED ||
1284 			   dongle_state == DONGLE_DISCONNECTED) {
1285 			/* Return 0, so hidraw can get the report. */
1286 			return 0;
1287 		}
1288 
1289 		dualshock4_parse_report(sc, rd, size);
1290 
1291 	} else if ((sc->quirks & NSG_MRXU_REMOTE) && rd[0] == 0x02) {
1292 		nsg_mrxu_parse_report(sc, rd, size);
1293 		return 1;
1294 	}
1295 
1296 	if (sc->defer_initialization) {
1297 		sc->defer_initialization = 0;
1298 		sony_schedule_work(sc, SONY_WORKER_STATE);
1299 	}
1300 
1301 	return 0;
1302 }
1303 
1304 static int sony_mapping(struct hid_device *hdev, struct hid_input *hi,
1305 			struct hid_field *field, struct hid_usage *usage,
1306 			unsigned long **bit, int *max)
1307 {
1308 	struct sony_sc *sc = hid_get_drvdata(hdev);
1309 
1310 	if (sc->quirks & BUZZ_CONTROLLER) {
1311 		unsigned int key = usage->hid & HID_USAGE;
1312 
1313 		if ((usage->hid & HID_USAGE_PAGE) != HID_UP_BUTTON)
1314 			return -1;
1315 
1316 		switch (usage->collection_index) {
1317 		case 1:
1318 			if (key >= ARRAY_SIZE(buzz_keymap))
1319 				return -1;
1320 
1321 			key = buzz_keymap[key];
1322 			if (!key)
1323 				return -1;
1324 			break;
1325 		default:
1326 			return -1;
1327 		}
1328 
1329 		hid_map_usage_clear(hi, usage, bit, max, EV_KEY, key);
1330 		return 1;
1331 	}
1332 
1333 	if (sc->quirks & PS3REMOTE)
1334 		return ps3remote_mapping(hdev, hi, field, usage, bit, max);
1335 
1336 	if (sc->quirks & NAVIGATION_CONTROLLER)
1337 		return navigation_mapping(hdev, hi, field, usage, bit, max);
1338 
1339 	if (sc->quirks & SIXAXIS_CONTROLLER)
1340 		return sixaxis_mapping(hdev, hi, field, usage, bit, max);
1341 
1342 	if (sc->quirks & DUALSHOCK4_CONTROLLER)
1343 		return ds4_mapping(hdev, hi, field, usage, bit, max);
1344 
1345 
1346 	/* Let hid-core decide for the others */
1347 	return 0;
1348 }
1349 
1350 static int sony_register_touchpad(struct sony_sc *sc, int touch_count,
1351 		int w, int h, int touch_major, int touch_minor, int orientation)
1352 {
1353 	size_t name_sz;
1354 	char *name;
1355 	int ret;
1356 
1357 	sc->touchpad = devm_input_allocate_device(&sc->hdev->dev);
1358 	if (!sc->touchpad)
1359 		return -ENOMEM;
1360 
1361 	input_set_drvdata(sc->touchpad, sc);
1362 	sc->touchpad->dev.parent = &sc->hdev->dev;
1363 	sc->touchpad->phys = sc->hdev->phys;
1364 	sc->touchpad->uniq = sc->hdev->uniq;
1365 	sc->touchpad->id.bustype = sc->hdev->bus;
1366 	sc->touchpad->id.vendor = sc->hdev->vendor;
1367 	sc->touchpad->id.product = sc->hdev->product;
1368 	sc->touchpad->id.version = sc->hdev->version;
1369 
1370 	/* Append a suffix to the controller name as there are various
1371 	 * DS4 compatible non-Sony devices with different names.
1372 	 */
1373 	name_sz = strlen(sc->hdev->name) + sizeof(DS4_TOUCHPAD_SUFFIX);
1374 	name = devm_kzalloc(&sc->hdev->dev, name_sz, GFP_KERNEL);
1375 	if (!name)
1376 		return -ENOMEM;
1377 	snprintf(name, name_sz, "%s" DS4_TOUCHPAD_SUFFIX, sc->hdev->name);
1378 	sc->touchpad->name = name;
1379 
1380 	/* We map the button underneath the touchpad to BTN_LEFT. */
1381 	__set_bit(EV_KEY, sc->touchpad->evbit);
1382 	__set_bit(BTN_LEFT, sc->touchpad->keybit);
1383 	__set_bit(INPUT_PROP_BUTTONPAD, sc->touchpad->propbit);
1384 
1385 	input_set_abs_params(sc->touchpad, ABS_MT_POSITION_X, 0, w, 0, 0);
1386 	input_set_abs_params(sc->touchpad, ABS_MT_POSITION_Y, 0, h, 0, 0);
1387 
1388 	if (touch_major > 0) {
1389 		input_set_abs_params(sc->touchpad, ABS_MT_TOUCH_MAJOR,
1390 			0, touch_major, 0, 0);
1391 		if (touch_minor > 0)
1392 			input_set_abs_params(sc->touchpad, ABS_MT_TOUCH_MINOR,
1393 				0, touch_minor, 0, 0);
1394 		if (orientation > 0)
1395 			input_set_abs_params(sc->touchpad, ABS_MT_ORIENTATION,
1396 				0, orientation, 0, 0);
1397 	}
1398 
1399 	if (sc->quirks & NSG_MRXU_REMOTE) {
1400 		__set_bit(EV_REL, sc->touchpad->evbit);
1401 	}
1402 
1403 	ret = input_mt_init_slots(sc->touchpad, touch_count, INPUT_MT_POINTER);
1404 	if (ret < 0)
1405 		return ret;
1406 
1407 	ret = input_register_device(sc->touchpad);
1408 	if (ret < 0)
1409 		return ret;
1410 
1411 	return 0;
1412 }
1413 
1414 static int sony_register_sensors(struct sony_sc *sc)
1415 {
1416 	size_t name_sz;
1417 	char *name;
1418 	int ret;
1419 	int range;
1420 
1421 	sc->sensor_dev = devm_input_allocate_device(&sc->hdev->dev);
1422 	if (!sc->sensor_dev)
1423 		return -ENOMEM;
1424 
1425 	input_set_drvdata(sc->sensor_dev, sc);
1426 	sc->sensor_dev->dev.parent = &sc->hdev->dev;
1427 	sc->sensor_dev->phys = sc->hdev->phys;
1428 	sc->sensor_dev->uniq = sc->hdev->uniq;
1429 	sc->sensor_dev->id.bustype = sc->hdev->bus;
1430 	sc->sensor_dev->id.vendor = sc->hdev->vendor;
1431 	sc->sensor_dev->id.product = sc->hdev->product;
1432 	sc->sensor_dev->id.version = sc->hdev->version;
1433 
1434 	/* Append a suffix to the controller name as there are various
1435 	 * DS4 compatible non-Sony devices with different names.
1436 	 */
1437 	name_sz = strlen(sc->hdev->name) + sizeof(SENSOR_SUFFIX);
1438 	name = devm_kzalloc(&sc->hdev->dev, name_sz, GFP_KERNEL);
1439 	if (!name)
1440 		return -ENOMEM;
1441 	snprintf(name, name_sz, "%s" SENSOR_SUFFIX, sc->hdev->name);
1442 	sc->sensor_dev->name = name;
1443 
1444 	if (sc->quirks & SIXAXIS_CONTROLLER) {
1445 		/* For the DS3 we only support the accelerometer, which works
1446 		 * quite well even without calibration. The device also has
1447 		 * a 1-axis gyro, but it is very difficult to manage from within
1448 		 * the driver even to get data, the sensor is inaccurate and
1449 		 * the behavior is very different between hardware revisions.
1450 		 */
1451 		input_set_abs_params(sc->sensor_dev, ABS_X, -512, 511, 4, 0);
1452 		input_set_abs_params(sc->sensor_dev, ABS_Y, -512, 511, 4, 0);
1453 		input_set_abs_params(sc->sensor_dev, ABS_Z, -512, 511, 4, 0);
1454 		input_abs_set_res(sc->sensor_dev, ABS_X, SIXAXIS_ACC_RES_PER_G);
1455 		input_abs_set_res(sc->sensor_dev, ABS_Y, SIXAXIS_ACC_RES_PER_G);
1456 		input_abs_set_res(sc->sensor_dev, ABS_Z, SIXAXIS_ACC_RES_PER_G);
1457 	} else if (sc->quirks & DUALSHOCK4_CONTROLLER) {
1458 		range = DS4_ACC_RES_PER_G*4;
1459 		input_set_abs_params(sc->sensor_dev, ABS_X, -range, range, 16, 0);
1460 		input_set_abs_params(sc->sensor_dev, ABS_Y, -range, range, 16, 0);
1461 		input_set_abs_params(sc->sensor_dev, ABS_Z, -range, range, 16, 0);
1462 		input_abs_set_res(sc->sensor_dev, ABS_X, DS4_ACC_RES_PER_G);
1463 		input_abs_set_res(sc->sensor_dev, ABS_Y, DS4_ACC_RES_PER_G);
1464 		input_abs_set_res(sc->sensor_dev, ABS_Z, DS4_ACC_RES_PER_G);
1465 
1466 		range = DS4_GYRO_RES_PER_DEG_S*2048;
1467 		input_set_abs_params(sc->sensor_dev, ABS_RX, -range, range, 16, 0);
1468 		input_set_abs_params(sc->sensor_dev, ABS_RY, -range, range, 16, 0);
1469 		input_set_abs_params(sc->sensor_dev, ABS_RZ, -range, range, 16, 0);
1470 		input_abs_set_res(sc->sensor_dev, ABS_RX, DS4_GYRO_RES_PER_DEG_S);
1471 		input_abs_set_res(sc->sensor_dev, ABS_RY, DS4_GYRO_RES_PER_DEG_S);
1472 		input_abs_set_res(sc->sensor_dev, ABS_RZ, DS4_GYRO_RES_PER_DEG_S);
1473 
1474 		__set_bit(EV_MSC, sc->sensor_dev->evbit);
1475 		__set_bit(MSC_TIMESTAMP, sc->sensor_dev->mscbit);
1476 	}
1477 
1478 	__set_bit(INPUT_PROP_ACCELEROMETER, sc->sensor_dev->propbit);
1479 
1480 	ret = input_register_device(sc->sensor_dev);
1481 	if (ret < 0)
1482 		return ret;
1483 
1484 	return 0;
1485 }
1486 
1487 /*
1488  * Sending HID_REQ_GET_REPORT changes the operation mode of the ps3 controller
1489  * to "operational".  Without this, the ps3 controller will not report any
1490  * events.
1491  */
1492 static int sixaxis_set_operational_usb(struct hid_device *hdev)
1493 {
1494 	struct sony_sc *sc = hid_get_drvdata(hdev);
1495 	const int buf_size =
1496 		max(SIXAXIS_REPORT_0xF2_SIZE, SIXAXIS_REPORT_0xF5_SIZE);
1497 	u8 *buf;
1498 	int ret;
1499 
1500 	buf = kmalloc(buf_size, GFP_KERNEL);
1501 	if (!buf)
1502 		return -ENOMEM;
1503 
1504 	ret = hid_hw_raw_request(hdev, 0xf2, buf, SIXAXIS_REPORT_0xF2_SIZE,
1505 				 HID_FEATURE_REPORT, HID_REQ_GET_REPORT);
1506 	if (ret < 0) {
1507 		hid_err(hdev, "can't set operational mode: step 1\n");
1508 		goto out;
1509 	}
1510 
1511 	/*
1512 	 * Some compatible controllers like the Speedlink Strike FX and
1513 	 * Gasia need another query plus an USB interrupt to get operational.
1514 	 */
1515 	ret = hid_hw_raw_request(hdev, 0xf5, buf, SIXAXIS_REPORT_0xF5_SIZE,
1516 				 HID_FEATURE_REPORT, HID_REQ_GET_REPORT);
1517 	if (ret < 0) {
1518 		hid_err(hdev, "can't set operational mode: step 2\n");
1519 		goto out;
1520 	}
1521 
1522 	/*
1523 	 * But the USB interrupt would cause SHANWAN controllers to
1524 	 * start rumbling non-stop, so skip step 3 for these controllers.
1525 	 */
1526 	if (sc->quirks & SHANWAN_GAMEPAD)
1527 		goto out;
1528 
1529 	ret = hid_hw_output_report(hdev, buf, 1);
1530 	if (ret < 0) {
1531 		hid_info(hdev, "can't set operational mode: step 3, ignoring\n");
1532 		ret = 0;
1533 	}
1534 
1535 out:
1536 	kfree(buf);
1537 
1538 	return ret;
1539 }
1540 
1541 static int sixaxis_set_operational_bt(struct hid_device *hdev)
1542 {
1543 	static const u8 report[] = { 0xf4, 0x42, 0x03, 0x00, 0x00 };
1544 	u8 *buf;
1545 	int ret;
1546 
1547 	buf = kmemdup(report, sizeof(report), GFP_KERNEL);
1548 	if (!buf)
1549 		return -ENOMEM;
1550 
1551 	ret = hid_hw_raw_request(hdev, buf[0], buf, sizeof(report),
1552 				  HID_FEATURE_REPORT, HID_REQ_SET_REPORT);
1553 
1554 	kfree(buf);
1555 
1556 	return ret;
1557 }
1558 
1559 /*
1560  * Request DS4 calibration data for the motion sensors.
1561  * For Bluetooth this also affects the operating mode (see below).
1562  */
1563 static int dualshock4_get_calibration_data(struct sony_sc *sc)
1564 {
1565 	u8 *buf;
1566 	int ret;
1567 	short gyro_pitch_bias, gyro_pitch_plus, gyro_pitch_minus;
1568 	short gyro_yaw_bias, gyro_yaw_plus, gyro_yaw_minus;
1569 	short gyro_roll_bias, gyro_roll_plus, gyro_roll_minus;
1570 	short gyro_speed_plus, gyro_speed_minus;
1571 	short acc_x_plus, acc_x_minus;
1572 	short acc_y_plus, acc_y_minus;
1573 	short acc_z_plus, acc_z_minus;
1574 	int speed_2x;
1575 	int range_2g;
1576 
1577 	/* For Bluetooth we use a different request, which supports CRC.
1578 	 * Note: in Bluetooth mode feature report 0x02 also changes the state
1579 	 * of the controller, so that it sends input reports of type 0x11.
1580 	 */
1581 	if (sc->quirks & (DUALSHOCK4_CONTROLLER_USB | DUALSHOCK4_DONGLE)) {
1582 		buf = kmalloc(DS4_FEATURE_REPORT_0x02_SIZE, GFP_KERNEL);
1583 		if (!buf)
1584 			return -ENOMEM;
1585 
1586 		ret = hid_hw_raw_request(sc->hdev, 0x02, buf,
1587 					 DS4_FEATURE_REPORT_0x02_SIZE,
1588 					 HID_FEATURE_REPORT,
1589 					 HID_REQ_GET_REPORT);
1590 		if (ret < 0)
1591 			goto err_stop;
1592 	} else {
1593 		u8 bthdr = 0xA3;
1594 		u32 crc;
1595 		u32 report_crc;
1596 		int retries;
1597 
1598 		buf = kmalloc(DS4_FEATURE_REPORT_0x05_SIZE, GFP_KERNEL);
1599 		if (!buf)
1600 			return -ENOMEM;
1601 
1602 		for (retries = 0; retries < 3; retries++) {
1603 			ret = hid_hw_raw_request(sc->hdev, 0x05, buf,
1604 						 DS4_FEATURE_REPORT_0x05_SIZE,
1605 						 HID_FEATURE_REPORT,
1606 						 HID_REQ_GET_REPORT);
1607 			if (ret < 0)
1608 				goto err_stop;
1609 
1610 			/* CRC check */
1611 			crc = crc32_le(0xFFFFFFFF, &bthdr, 1);
1612 			crc = ~crc32_le(crc, buf, DS4_FEATURE_REPORT_0x05_SIZE-4);
1613 			report_crc = get_unaligned_le32(&buf[DS4_FEATURE_REPORT_0x05_SIZE-4]);
1614 			if (crc != report_crc) {
1615 				hid_warn(sc->hdev, "DualShock 4 calibration report's CRC check failed, received crc 0x%0x != 0x%0x\n",
1616 					report_crc, crc);
1617 				if (retries < 2) {
1618 					hid_warn(sc->hdev, "Retrying DualShock 4 get calibration report request\n");
1619 					continue;
1620 				} else {
1621 					ret = -EILSEQ;
1622 					goto err_stop;
1623 				}
1624 			} else {
1625 				break;
1626 			}
1627 		}
1628 	}
1629 
1630 	gyro_pitch_bias  = get_unaligned_le16(&buf[1]);
1631 	gyro_yaw_bias    = get_unaligned_le16(&buf[3]);
1632 	gyro_roll_bias   = get_unaligned_le16(&buf[5]);
1633 	if (sc->quirks & DUALSHOCK4_CONTROLLER_USB) {
1634 		gyro_pitch_plus  = get_unaligned_le16(&buf[7]);
1635 		gyro_pitch_minus = get_unaligned_le16(&buf[9]);
1636 		gyro_yaw_plus    = get_unaligned_le16(&buf[11]);
1637 		gyro_yaw_minus   = get_unaligned_le16(&buf[13]);
1638 		gyro_roll_plus   = get_unaligned_le16(&buf[15]);
1639 		gyro_roll_minus  = get_unaligned_le16(&buf[17]);
1640 	} else {
1641 		/* BT + Dongle */
1642 		gyro_pitch_plus  = get_unaligned_le16(&buf[7]);
1643 		gyro_yaw_plus    = get_unaligned_le16(&buf[9]);
1644 		gyro_roll_plus   = get_unaligned_le16(&buf[11]);
1645 		gyro_pitch_minus = get_unaligned_le16(&buf[13]);
1646 		gyro_yaw_minus   = get_unaligned_le16(&buf[15]);
1647 		gyro_roll_minus  = get_unaligned_le16(&buf[17]);
1648 	}
1649 	gyro_speed_plus  = get_unaligned_le16(&buf[19]);
1650 	gyro_speed_minus = get_unaligned_le16(&buf[21]);
1651 	acc_x_plus       = get_unaligned_le16(&buf[23]);
1652 	acc_x_minus      = get_unaligned_le16(&buf[25]);
1653 	acc_y_plus       = get_unaligned_le16(&buf[27]);
1654 	acc_y_minus      = get_unaligned_le16(&buf[29]);
1655 	acc_z_plus       = get_unaligned_le16(&buf[31]);
1656 	acc_z_minus      = get_unaligned_le16(&buf[33]);
1657 
1658 	/* Set gyroscope calibration and normalization parameters.
1659 	 * Data values will be normalized to 1/DS4_GYRO_RES_PER_DEG_S degree/s.
1660 	 */
1661 	speed_2x = (gyro_speed_plus + gyro_speed_minus);
1662 	sc->ds4_calib_data[0].abs_code = ABS_RX;
1663 	sc->ds4_calib_data[0].bias = gyro_pitch_bias;
1664 	sc->ds4_calib_data[0].sens_numer = speed_2x*DS4_GYRO_RES_PER_DEG_S;
1665 	sc->ds4_calib_data[0].sens_denom = gyro_pitch_plus - gyro_pitch_minus;
1666 
1667 	sc->ds4_calib_data[1].abs_code = ABS_RY;
1668 	sc->ds4_calib_data[1].bias = gyro_yaw_bias;
1669 	sc->ds4_calib_data[1].sens_numer = speed_2x*DS4_GYRO_RES_PER_DEG_S;
1670 	sc->ds4_calib_data[1].sens_denom = gyro_yaw_plus - gyro_yaw_minus;
1671 
1672 	sc->ds4_calib_data[2].abs_code = ABS_RZ;
1673 	sc->ds4_calib_data[2].bias = gyro_roll_bias;
1674 	sc->ds4_calib_data[2].sens_numer = speed_2x*DS4_GYRO_RES_PER_DEG_S;
1675 	sc->ds4_calib_data[2].sens_denom = gyro_roll_plus - gyro_roll_minus;
1676 
1677 	/* Set accelerometer calibration and normalization parameters.
1678 	 * Data values will be normalized to 1/DS4_ACC_RES_PER_G G.
1679 	 */
1680 	range_2g = acc_x_plus - acc_x_minus;
1681 	sc->ds4_calib_data[3].abs_code = ABS_X;
1682 	sc->ds4_calib_data[3].bias = acc_x_plus - range_2g / 2;
1683 	sc->ds4_calib_data[3].sens_numer = 2*DS4_ACC_RES_PER_G;
1684 	sc->ds4_calib_data[3].sens_denom = range_2g;
1685 
1686 	range_2g = acc_y_plus - acc_y_minus;
1687 	sc->ds4_calib_data[4].abs_code = ABS_Y;
1688 	sc->ds4_calib_data[4].bias = acc_y_plus - range_2g / 2;
1689 	sc->ds4_calib_data[4].sens_numer = 2*DS4_ACC_RES_PER_G;
1690 	sc->ds4_calib_data[4].sens_denom = range_2g;
1691 
1692 	range_2g = acc_z_plus - acc_z_minus;
1693 	sc->ds4_calib_data[5].abs_code = ABS_Z;
1694 	sc->ds4_calib_data[5].bias = acc_z_plus - range_2g / 2;
1695 	sc->ds4_calib_data[5].sens_numer = 2*DS4_ACC_RES_PER_G;
1696 	sc->ds4_calib_data[5].sens_denom = range_2g;
1697 
1698 err_stop:
1699 	kfree(buf);
1700 	return ret;
1701 }
1702 
1703 static void dualshock4_calibration_work(struct work_struct *work)
1704 {
1705 	struct sony_sc *sc = container_of(work, struct sony_sc, hotplug_worker);
1706 	unsigned long flags;
1707 	enum ds4_dongle_state dongle_state;
1708 	int ret;
1709 
1710 	ret = dualshock4_get_calibration_data(sc);
1711 	if (ret < 0) {
1712 		/* This call is very unlikely to fail for the dongle. When it
1713 		 * fails we are probably in a very bad state, so mark the
1714 		 * dongle as disabled. We will re-enable the dongle if a new
1715 		 * DS4 hotplug is detect from sony_raw_event as any issues
1716 		 * are likely resolved then (the dongle is quite stupid).
1717 		 */
1718 		hid_err(sc->hdev, "DualShock 4 USB dongle: calibration failed, disabling device\n");
1719 		dongle_state = DONGLE_DISABLED;
1720 	} else {
1721 		hid_info(sc->hdev, "DualShock 4 USB dongle: calibration completed\n");
1722 		dongle_state = DONGLE_CONNECTED;
1723 	}
1724 
1725 	spin_lock_irqsave(&sc->lock, flags);
1726 	sc->ds4_dongle_state = dongle_state;
1727 	spin_unlock_irqrestore(&sc->lock, flags);
1728 }
1729 
1730 static int dualshock4_get_version_info(struct sony_sc *sc)
1731 {
1732 	u8 *buf;
1733 	int ret;
1734 
1735 	buf = kmalloc(DS4_FEATURE_REPORT_0xA3_SIZE, GFP_KERNEL);
1736 	if (!buf)
1737 		return -ENOMEM;
1738 
1739 	ret = hid_hw_raw_request(sc->hdev, 0xA3, buf,
1740 				 DS4_FEATURE_REPORT_0xA3_SIZE,
1741 				 HID_FEATURE_REPORT,
1742 				 HID_REQ_GET_REPORT);
1743 	if (ret < 0) {
1744 		kfree(buf);
1745 		return ret;
1746 	}
1747 
1748 	sc->hw_version = get_unaligned_le16(&buf[35]);
1749 	sc->fw_version = get_unaligned_le16(&buf[41]);
1750 
1751 	kfree(buf);
1752 	return 0;
1753 }
1754 
1755 static void sixaxis_set_leds_from_id(struct sony_sc *sc)
1756 {
1757 	static const u8 sixaxis_leds[10][4] = {
1758 				{ 0x01, 0x00, 0x00, 0x00 },
1759 				{ 0x00, 0x01, 0x00, 0x00 },
1760 				{ 0x00, 0x00, 0x01, 0x00 },
1761 				{ 0x00, 0x00, 0x00, 0x01 },
1762 				{ 0x01, 0x00, 0x00, 0x01 },
1763 				{ 0x00, 0x01, 0x00, 0x01 },
1764 				{ 0x00, 0x00, 0x01, 0x01 },
1765 				{ 0x01, 0x00, 0x01, 0x01 },
1766 				{ 0x00, 0x01, 0x01, 0x01 },
1767 				{ 0x01, 0x01, 0x01, 0x01 }
1768 	};
1769 
1770 	int id = sc->device_id;
1771 
1772 	BUILD_BUG_ON(MAX_LEDS < ARRAY_SIZE(sixaxis_leds[0]));
1773 
1774 	if (id < 0)
1775 		return;
1776 
1777 	id %= 10;
1778 	memcpy(sc->led_state, sixaxis_leds[id], sizeof(sixaxis_leds[id]));
1779 }
1780 
1781 static void dualshock4_set_leds_from_id(struct sony_sc *sc)
1782 {
1783 	/* The first 4 color/index entries match what the PS4 assigns */
1784 	static const u8 color_code[7][3] = {
1785 			/* Blue   */	{ 0x00, 0x00, 0x40 },
1786 			/* Red	  */	{ 0x40, 0x00, 0x00 },
1787 			/* Green  */	{ 0x00, 0x40, 0x00 },
1788 			/* Pink   */	{ 0x20, 0x00, 0x20 },
1789 			/* Orange */	{ 0x02, 0x01, 0x00 },
1790 			/* Teal   */	{ 0x00, 0x01, 0x01 },
1791 			/* White  */	{ 0x01, 0x01, 0x01 }
1792 	};
1793 
1794 	int id = sc->device_id;
1795 
1796 	BUILD_BUG_ON(MAX_LEDS < ARRAY_SIZE(color_code[0]));
1797 
1798 	if (id < 0)
1799 		return;
1800 
1801 	id %= 7;
1802 	memcpy(sc->led_state, color_code[id], sizeof(color_code[id]));
1803 }
1804 
1805 static void buzz_set_leds(struct sony_sc *sc)
1806 {
1807 	struct hid_device *hdev = sc->hdev;
1808 	struct list_head *report_list =
1809 		&hdev->report_enum[HID_OUTPUT_REPORT].report_list;
1810 	struct hid_report *report = list_entry(report_list->next,
1811 		struct hid_report, list);
1812 	s32 *value = report->field[0]->value;
1813 
1814 	BUILD_BUG_ON(MAX_LEDS < 4);
1815 
1816 	value[0] = 0x00;
1817 	value[1] = sc->led_state[0] ? 0xff : 0x00;
1818 	value[2] = sc->led_state[1] ? 0xff : 0x00;
1819 	value[3] = sc->led_state[2] ? 0xff : 0x00;
1820 	value[4] = sc->led_state[3] ? 0xff : 0x00;
1821 	value[5] = 0x00;
1822 	value[6] = 0x00;
1823 	hid_hw_request(hdev, report, HID_REQ_SET_REPORT);
1824 }
1825 
1826 static void sony_set_leds(struct sony_sc *sc)
1827 {
1828 	if (!(sc->quirks & BUZZ_CONTROLLER))
1829 		sony_schedule_work(sc, SONY_WORKER_STATE);
1830 	else
1831 		buzz_set_leds(sc);
1832 }
1833 
1834 static void sony_led_set_brightness(struct led_classdev *led,
1835 				    enum led_brightness value)
1836 {
1837 	struct device *dev = led->dev->parent;
1838 	struct hid_device *hdev = to_hid_device(dev);
1839 	struct sony_sc *drv_data;
1840 
1841 	int n;
1842 	int force_update;
1843 
1844 	drv_data = hid_get_drvdata(hdev);
1845 	if (!drv_data) {
1846 		hid_err(hdev, "No device data\n");
1847 		return;
1848 	}
1849 
1850 	/*
1851 	 * The Sixaxis on USB will override any LED settings sent to it
1852 	 * and keep flashing all of the LEDs until the PS button is pressed.
1853 	 * Updates, even if redundant, must be always be sent to the
1854 	 * controller to avoid having to toggle the state of an LED just to
1855 	 * stop the flashing later on.
1856 	 */
1857 	force_update = !!(drv_data->quirks & SIXAXIS_CONTROLLER_USB);
1858 
1859 	for (n = 0; n < drv_data->led_count; n++) {
1860 		if (led == drv_data->leds[n] && (force_update ||
1861 			(value != drv_data->led_state[n] ||
1862 			drv_data->led_delay_on[n] ||
1863 			drv_data->led_delay_off[n]))) {
1864 
1865 			drv_data->led_state[n] = value;
1866 
1867 			/* Setting the brightness stops the blinking */
1868 			drv_data->led_delay_on[n] = 0;
1869 			drv_data->led_delay_off[n] = 0;
1870 
1871 			sony_set_leds(drv_data);
1872 			break;
1873 		}
1874 	}
1875 }
1876 
1877 static enum led_brightness sony_led_get_brightness(struct led_classdev *led)
1878 {
1879 	struct device *dev = led->dev->parent;
1880 	struct hid_device *hdev = to_hid_device(dev);
1881 	struct sony_sc *drv_data;
1882 
1883 	int n;
1884 
1885 	drv_data = hid_get_drvdata(hdev);
1886 	if (!drv_data) {
1887 		hid_err(hdev, "No device data\n");
1888 		return LED_OFF;
1889 	}
1890 
1891 	for (n = 0; n < drv_data->led_count; n++) {
1892 		if (led == drv_data->leds[n])
1893 			return drv_data->led_state[n];
1894 	}
1895 
1896 	return LED_OFF;
1897 }
1898 
1899 static int sony_led_blink_set(struct led_classdev *led, unsigned long *delay_on,
1900 				unsigned long *delay_off)
1901 {
1902 	struct device *dev = led->dev->parent;
1903 	struct hid_device *hdev = to_hid_device(dev);
1904 	struct sony_sc *drv_data = hid_get_drvdata(hdev);
1905 	int n;
1906 	u8 new_on, new_off;
1907 
1908 	if (!drv_data) {
1909 		hid_err(hdev, "No device data\n");
1910 		return -EINVAL;
1911 	}
1912 
1913 	/* Max delay is 255 deciseconds or 2550 milliseconds */
1914 	if (*delay_on > 2550)
1915 		*delay_on = 2550;
1916 	if (*delay_off > 2550)
1917 		*delay_off = 2550;
1918 
1919 	/* Blink at 1 Hz if both values are zero */
1920 	if (!*delay_on && !*delay_off)
1921 		*delay_on = *delay_off = 500;
1922 
1923 	new_on = *delay_on / 10;
1924 	new_off = *delay_off / 10;
1925 
1926 	for (n = 0; n < drv_data->led_count; n++) {
1927 		if (led == drv_data->leds[n])
1928 			break;
1929 	}
1930 
1931 	/* This LED is not registered on this device */
1932 	if (n >= drv_data->led_count)
1933 		return -EINVAL;
1934 
1935 	/* Don't schedule work if the values didn't change */
1936 	if (new_on != drv_data->led_delay_on[n] ||
1937 		new_off != drv_data->led_delay_off[n]) {
1938 		drv_data->led_delay_on[n] = new_on;
1939 		drv_data->led_delay_off[n] = new_off;
1940 		sony_schedule_work(drv_data, SONY_WORKER_STATE);
1941 	}
1942 
1943 	return 0;
1944 }
1945 
1946 static int sony_leds_init(struct sony_sc *sc)
1947 {
1948 	struct hid_device *hdev = sc->hdev;
1949 	int n, ret = 0;
1950 	int use_ds4_names;
1951 	struct led_classdev *led;
1952 	size_t name_sz;
1953 	char *name;
1954 	size_t name_len;
1955 	const char *name_fmt;
1956 	static const char * const ds4_name_str[] = { "red", "green", "blue",
1957 						  "global" };
1958 	u8 max_brightness[MAX_LEDS] = { [0 ... (MAX_LEDS - 1)] = 1 };
1959 	u8 use_hw_blink[MAX_LEDS] = { 0 };
1960 
1961 	BUG_ON(!(sc->quirks & SONY_LED_SUPPORT));
1962 
1963 	if (sc->quirks & BUZZ_CONTROLLER) {
1964 		sc->led_count = 4;
1965 		use_ds4_names = 0;
1966 		name_len = strlen("::buzz#");
1967 		name_fmt = "%s::buzz%d";
1968 		/* Validate expected report characteristics. */
1969 		if (!hid_validate_values(hdev, HID_OUTPUT_REPORT, 0, 0, 7))
1970 			return -ENODEV;
1971 	} else if (sc->quirks & DUALSHOCK4_CONTROLLER) {
1972 		dualshock4_set_leds_from_id(sc);
1973 		sc->led_state[3] = 1;
1974 		sc->led_count = 4;
1975 		memset(max_brightness, 255, 3);
1976 		use_hw_blink[3] = 1;
1977 		use_ds4_names = 1;
1978 		name_len = 0;
1979 		name_fmt = "%s:%s";
1980 	} else if (sc->quirks & MOTION_CONTROLLER) {
1981 		sc->led_count = 3;
1982 		memset(max_brightness, 255, 3);
1983 		use_ds4_names = 1;
1984 		name_len = 0;
1985 		name_fmt = "%s:%s";
1986 	} else if (sc->quirks & NAVIGATION_CONTROLLER) {
1987 		static const u8 navigation_leds[4] = {0x01, 0x00, 0x00, 0x00};
1988 
1989 		memcpy(sc->led_state, navigation_leds, sizeof(navigation_leds));
1990 		sc->led_count = 1;
1991 		memset(use_hw_blink, 1, 4);
1992 		use_ds4_names = 0;
1993 		name_len = strlen("::sony#");
1994 		name_fmt = "%s::sony%d";
1995 	} else {
1996 		sixaxis_set_leds_from_id(sc);
1997 		sc->led_count = 4;
1998 		memset(use_hw_blink, 1, 4);
1999 		use_ds4_names = 0;
2000 		name_len = strlen("::sony#");
2001 		name_fmt = "%s::sony%d";
2002 	}
2003 
2004 	/*
2005 	 * Clear LEDs as we have no way of reading their initial state. This is
2006 	 * only relevant if the driver is loaded after somebody actively set the
2007 	 * LEDs to on
2008 	 */
2009 	sony_set_leds(sc);
2010 
2011 	name_sz = strlen(dev_name(&hdev->dev)) + name_len + 1;
2012 
2013 	for (n = 0; n < sc->led_count; n++) {
2014 
2015 		if (use_ds4_names)
2016 			name_sz = strlen(dev_name(&hdev->dev)) + strlen(ds4_name_str[n]) + 2;
2017 
2018 		led = devm_kzalloc(&hdev->dev, sizeof(struct led_classdev) + name_sz, GFP_KERNEL);
2019 		if (!led) {
2020 			hid_err(hdev, "Couldn't allocate memory for LED %d\n", n);
2021 			return -ENOMEM;
2022 		}
2023 
2024 		name = (void *)(&led[1]);
2025 		if (use_ds4_names)
2026 			snprintf(name, name_sz, name_fmt, dev_name(&hdev->dev),
2027 			ds4_name_str[n]);
2028 		else
2029 			snprintf(name, name_sz, name_fmt, dev_name(&hdev->dev), n + 1);
2030 		led->name = name;
2031 		led->brightness = sc->led_state[n];
2032 		led->max_brightness = max_brightness[n];
2033 		led->flags = LED_CORE_SUSPENDRESUME;
2034 		led->brightness_get = sony_led_get_brightness;
2035 		led->brightness_set = sony_led_set_brightness;
2036 
2037 		if (use_hw_blink[n])
2038 			led->blink_set = sony_led_blink_set;
2039 
2040 		sc->leds[n] = led;
2041 
2042 		ret = devm_led_classdev_register(&hdev->dev, led);
2043 		if (ret) {
2044 			hid_err(hdev, "Failed to register LED %d\n", n);
2045 			return ret;
2046 		}
2047 	}
2048 
2049 	return 0;
2050 }
2051 
2052 static void sixaxis_send_output_report(struct sony_sc *sc)
2053 {
2054 	static const union sixaxis_output_report_01 default_report = {
2055 		.buf = {
2056 			0x01,
2057 			0x01, 0xff, 0x00, 0xff, 0x00,
2058 			0x00, 0x00, 0x00, 0x00, 0x00,
2059 			0xff, 0x27, 0x10, 0x00, 0x32,
2060 			0xff, 0x27, 0x10, 0x00, 0x32,
2061 			0xff, 0x27, 0x10, 0x00, 0x32,
2062 			0xff, 0x27, 0x10, 0x00, 0x32,
2063 			0x00, 0x00, 0x00, 0x00, 0x00
2064 		}
2065 	};
2066 	struct sixaxis_output_report *report =
2067 		(struct sixaxis_output_report *)sc->output_report_dmabuf;
2068 	int n;
2069 
2070 	/* Initialize the report with default values */
2071 	memcpy(report, &default_report, sizeof(struct sixaxis_output_report));
2072 
2073 #ifdef CONFIG_SONY_FF
2074 	report->rumble.right_motor_on = sc->right ? 1 : 0;
2075 	report->rumble.left_motor_force = sc->left;
2076 #endif
2077 
2078 	report->leds_bitmap |= sc->led_state[0] << 1;
2079 	report->leds_bitmap |= sc->led_state[1] << 2;
2080 	report->leds_bitmap |= sc->led_state[2] << 3;
2081 	report->leds_bitmap |= sc->led_state[3] << 4;
2082 
2083 	/* Set flag for all leds off, required for 3rd party INTEC controller */
2084 	if ((report->leds_bitmap & 0x1E) == 0)
2085 		report->leds_bitmap |= 0x20;
2086 
2087 	/*
2088 	 * The LEDs in the report are indexed in reverse order to their
2089 	 * corresponding light on the controller.
2090 	 * Index 0 = LED 4, index 1 = LED 3, etc...
2091 	 *
2092 	 * In the case of both delay values being zero (blinking disabled) the
2093 	 * default report values should be used or the controller LED will be
2094 	 * always off.
2095 	 */
2096 	for (n = 0; n < 4; n++) {
2097 		if (sc->led_delay_on[n] || sc->led_delay_off[n]) {
2098 			report->led[3 - n].duty_off = sc->led_delay_off[n];
2099 			report->led[3 - n].duty_on = sc->led_delay_on[n];
2100 		}
2101 	}
2102 
2103 	/* SHANWAN controllers require output reports via intr channel */
2104 	if (sc->quirks & SHANWAN_GAMEPAD)
2105 		hid_hw_output_report(sc->hdev, (u8 *)report,
2106 				sizeof(struct sixaxis_output_report));
2107 	else
2108 		hid_hw_raw_request(sc->hdev, report->report_id, (u8 *)report,
2109 				sizeof(struct sixaxis_output_report),
2110 				HID_OUTPUT_REPORT, HID_REQ_SET_REPORT);
2111 }
2112 
2113 static void dualshock4_send_output_report(struct sony_sc *sc)
2114 {
2115 	struct hid_device *hdev = sc->hdev;
2116 	u8 *buf = sc->output_report_dmabuf;
2117 	int offset;
2118 
2119 	/*
2120 	 * NOTE: The lower 6 bits of buf[1] field of the Bluetooth report
2121 	 * control the interval at which Dualshock 4 reports data:
2122 	 * 0x00 - 1ms
2123 	 * 0x01 - 1ms
2124 	 * 0x02 - 2ms
2125 	 * 0x3E - 62ms
2126 	 * 0x3F - disabled
2127 	 */
2128 	if (sc->quirks & (DUALSHOCK4_CONTROLLER_USB | DUALSHOCK4_DONGLE)) {
2129 		memset(buf, 0, DS4_OUTPUT_REPORT_0x05_SIZE);
2130 		buf[0] = 0x05;
2131 		buf[1] = 0x07; /* blink + LEDs + motor */
2132 		offset = 4;
2133 	} else {
2134 		memset(buf, 0, DS4_OUTPUT_REPORT_0x11_SIZE);
2135 		buf[0] = 0x11;
2136 		buf[1] = 0xC0 /* HID + CRC */ | sc->ds4_bt_poll_interval;
2137 		buf[3] = 0x07; /* blink + LEDs + motor */
2138 		offset = 6;
2139 	}
2140 
2141 #ifdef CONFIG_SONY_FF
2142 	buf[offset++] = sc->right;
2143 	buf[offset++] = sc->left;
2144 #else
2145 	offset += 2;
2146 #endif
2147 
2148 	/* LED 3 is the global control */
2149 	if (sc->led_state[3]) {
2150 		buf[offset++] = sc->led_state[0];
2151 		buf[offset++] = sc->led_state[1];
2152 		buf[offset++] = sc->led_state[2];
2153 	} else {
2154 		offset += 3;
2155 	}
2156 
2157 	/* If both delay values are zero the DualShock 4 disables blinking. */
2158 	buf[offset++] = sc->led_delay_on[3];
2159 	buf[offset++] = sc->led_delay_off[3];
2160 
2161 	if (sc->quirks & (DUALSHOCK4_CONTROLLER_USB | DUALSHOCK4_DONGLE))
2162 		hid_hw_output_report(hdev, buf, DS4_OUTPUT_REPORT_0x05_SIZE);
2163 	else {
2164 		/* CRC generation */
2165 		u8 bthdr = 0xA2;
2166 		u32 crc;
2167 
2168 		crc = crc32_le(0xFFFFFFFF, &bthdr, 1);
2169 		crc = ~crc32_le(crc, buf, DS4_OUTPUT_REPORT_0x11_SIZE-4);
2170 		put_unaligned_le32(crc, &buf[74]);
2171 		hid_hw_output_report(hdev, buf, DS4_OUTPUT_REPORT_0x11_SIZE);
2172 	}
2173 }
2174 
2175 static void motion_send_output_report(struct sony_sc *sc)
2176 {
2177 	struct hid_device *hdev = sc->hdev;
2178 	struct motion_output_report_02 *report =
2179 		(struct motion_output_report_02 *)sc->output_report_dmabuf;
2180 
2181 	memset(report, 0, MOTION_REPORT_0x02_SIZE);
2182 
2183 	report->type = 0x02; /* set leds */
2184 	report->r = sc->led_state[0];
2185 	report->g = sc->led_state[1];
2186 	report->b = sc->led_state[2];
2187 
2188 #ifdef CONFIG_SONY_FF
2189 	report->rumble = max(sc->right, sc->left);
2190 #endif
2191 
2192 	hid_hw_output_report(hdev, (u8 *)report, MOTION_REPORT_0x02_SIZE);
2193 }
2194 
2195 static inline void sony_send_output_report(struct sony_sc *sc)
2196 {
2197 	if (sc->send_output_report)
2198 		sc->send_output_report(sc);
2199 }
2200 
2201 static void sony_state_worker(struct work_struct *work)
2202 {
2203 	struct sony_sc *sc = container_of(work, struct sony_sc, state_worker);
2204 
2205 	sc->send_output_report(sc);
2206 }
2207 
2208 static int sony_allocate_output_report(struct sony_sc *sc)
2209 {
2210 	if ((sc->quirks & SIXAXIS_CONTROLLER) ||
2211 			(sc->quirks & NAVIGATION_CONTROLLER))
2212 		sc->output_report_dmabuf =
2213 			devm_kmalloc(&sc->hdev->dev,
2214 				sizeof(union sixaxis_output_report_01),
2215 				GFP_KERNEL);
2216 	else if (sc->quirks & DUALSHOCK4_CONTROLLER_BT)
2217 		sc->output_report_dmabuf = devm_kmalloc(&sc->hdev->dev,
2218 						DS4_OUTPUT_REPORT_0x11_SIZE,
2219 						GFP_KERNEL);
2220 	else if (sc->quirks & (DUALSHOCK4_CONTROLLER_USB | DUALSHOCK4_DONGLE))
2221 		sc->output_report_dmabuf = devm_kmalloc(&sc->hdev->dev,
2222 						DS4_OUTPUT_REPORT_0x05_SIZE,
2223 						GFP_KERNEL);
2224 	else if (sc->quirks & MOTION_CONTROLLER)
2225 		sc->output_report_dmabuf = devm_kmalloc(&sc->hdev->dev,
2226 						MOTION_REPORT_0x02_SIZE,
2227 						GFP_KERNEL);
2228 	else
2229 		return 0;
2230 
2231 	if (!sc->output_report_dmabuf)
2232 		return -ENOMEM;
2233 
2234 	return 0;
2235 }
2236 
2237 #ifdef CONFIG_SONY_FF
2238 static int sony_play_effect(struct input_dev *dev, void *data,
2239 			    struct ff_effect *effect)
2240 {
2241 	struct hid_device *hid = input_get_drvdata(dev);
2242 	struct sony_sc *sc = hid_get_drvdata(hid);
2243 
2244 	if (effect->type != FF_RUMBLE)
2245 		return 0;
2246 
2247 	sc->left = effect->u.rumble.strong_magnitude / 256;
2248 	sc->right = effect->u.rumble.weak_magnitude / 256;
2249 
2250 	sony_schedule_work(sc, SONY_WORKER_STATE);
2251 	return 0;
2252 }
2253 
2254 static int sony_init_ff(struct sony_sc *sc)
2255 {
2256 	struct hid_input *hidinput = list_entry(sc->hdev->inputs.next,
2257 						struct hid_input, list);
2258 	struct input_dev *input_dev = hidinput->input;
2259 
2260 	input_set_capability(input_dev, EV_FF, FF_RUMBLE);
2261 	return input_ff_create_memless(input_dev, NULL, sony_play_effect);
2262 }
2263 
2264 #else
2265 static int sony_init_ff(struct sony_sc *sc)
2266 {
2267 	return 0;
2268 }
2269 
2270 #endif
2271 
2272 static int sony_battery_get_property(struct power_supply *psy,
2273 				     enum power_supply_property psp,
2274 				     union power_supply_propval *val)
2275 {
2276 	struct sony_sc *sc = power_supply_get_drvdata(psy);
2277 	unsigned long flags;
2278 	int ret = 0;
2279 	u8 battery_charging, battery_capacity, cable_state;
2280 
2281 	spin_lock_irqsave(&sc->lock, flags);
2282 	battery_charging = sc->battery_charging;
2283 	battery_capacity = sc->battery_capacity;
2284 	cable_state = sc->cable_state;
2285 	spin_unlock_irqrestore(&sc->lock, flags);
2286 
2287 	switch (psp) {
2288 	case POWER_SUPPLY_PROP_PRESENT:
2289 		val->intval = 1;
2290 		break;
2291 	case POWER_SUPPLY_PROP_SCOPE:
2292 		val->intval = POWER_SUPPLY_SCOPE_DEVICE;
2293 		break;
2294 	case POWER_SUPPLY_PROP_CAPACITY:
2295 		val->intval = battery_capacity;
2296 		break;
2297 	case POWER_SUPPLY_PROP_STATUS:
2298 		if (battery_charging)
2299 			val->intval = POWER_SUPPLY_STATUS_CHARGING;
2300 		else
2301 			if (battery_capacity == 100 && cable_state)
2302 				val->intval = POWER_SUPPLY_STATUS_FULL;
2303 			else
2304 				val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
2305 		break;
2306 	default:
2307 		ret = -EINVAL;
2308 		break;
2309 	}
2310 	return ret;
2311 }
2312 
2313 static int sony_battery_probe(struct sony_sc *sc, int append_dev_id)
2314 {
2315 	const char *battery_str_fmt = append_dev_id ?
2316 		"sony_controller_battery_%pMR_%i" :
2317 		"sony_controller_battery_%pMR";
2318 	struct power_supply_config psy_cfg = { .drv_data = sc, };
2319 	struct hid_device *hdev = sc->hdev;
2320 	int ret;
2321 
2322 	/*
2323 	 * Set the default battery level to 100% to avoid low battery warnings
2324 	 * if the battery is polled before the first device report is received.
2325 	 */
2326 	sc->battery_capacity = 100;
2327 
2328 	sc->battery_desc.properties = sony_battery_props;
2329 	sc->battery_desc.num_properties = ARRAY_SIZE(sony_battery_props);
2330 	sc->battery_desc.get_property = sony_battery_get_property;
2331 	sc->battery_desc.type = POWER_SUPPLY_TYPE_BATTERY;
2332 	sc->battery_desc.use_for_apm = 0;
2333 	sc->battery_desc.name = devm_kasprintf(&hdev->dev, GFP_KERNEL,
2334 					  battery_str_fmt, sc->mac_address, sc->device_id);
2335 	if (!sc->battery_desc.name)
2336 		return -ENOMEM;
2337 
2338 	sc->battery = devm_power_supply_register(&hdev->dev, &sc->battery_desc,
2339 					    &psy_cfg);
2340 	if (IS_ERR(sc->battery)) {
2341 		ret = PTR_ERR(sc->battery);
2342 		hid_err(hdev, "Unable to register battery device\n");
2343 		return ret;
2344 	}
2345 
2346 	power_supply_powers(sc->battery, &hdev->dev);
2347 	return 0;
2348 }
2349 
2350 /*
2351  * If a controller is plugged in via USB while already connected via Bluetooth
2352  * it will show up as two devices. A global list of connected controllers and
2353  * their MAC addresses is maintained to ensure that a device is only connected
2354  * once.
2355  *
2356  * Some USB-only devices masquerade as Sixaxis controllers and all have the
2357  * same dummy Bluetooth address, so a comparison of the connection type is
2358  * required.  Devices are only rejected in the case where two devices have
2359  * matching Bluetooth addresses on different bus types.
2360  */
2361 static inline int sony_compare_connection_type(struct sony_sc *sc0,
2362 						struct sony_sc *sc1)
2363 {
2364 	const int sc0_not_bt = !(sc0->quirks & SONY_BT_DEVICE);
2365 	const int sc1_not_bt = !(sc1->quirks & SONY_BT_DEVICE);
2366 
2367 	return sc0_not_bt == sc1_not_bt;
2368 }
2369 
2370 static int sony_check_add_dev_list(struct sony_sc *sc)
2371 {
2372 	struct sony_sc *entry;
2373 	unsigned long flags;
2374 	int ret;
2375 
2376 	spin_lock_irqsave(&sony_dev_list_lock, flags);
2377 
2378 	list_for_each_entry(entry, &sony_device_list, list_node) {
2379 		ret = memcmp(sc->mac_address, entry->mac_address,
2380 				sizeof(sc->mac_address));
2381 		if (!ret) {
2382 			if (sony_compare_connection_type(sc, entry)) {
2383 				ret = 1;
2384 			} else {
2385 				ret = -EEXIST;
2386 				hid_info(sc->hdev,
2387 				"controller with MAC address %pMR already connected\n",
2388 				sc->mac_address);
2389 			}
2390 			goto unlock;
2391 		}
2392 	}
2393 
2394 	ret = 0;
2395 	list_add(&(sc->list_node), &sony_device_list);
2396 
2397 unlock:
2398 	spin_unlock_irqrestore(&sony_dev_list_lock, flags);
2399 	return ret;
2400 }
2401 
2402 static void sony_remove_dev_list(struct sony_sc *sc)
2403 {
2404 	unsigned long flags;
2405 
2406 	if (sc->list_node.next) {
2407 		spin_lock_irqsave(&sony_dev_list_lock, flags);
2408 		list_del(&(sc->list_node));
2409 		spin_unlock_irqrestore(&sony_dev_list_lock, flags);
2410 	}
2411 }
2412 
2413 static int sony_get_bt_devaddr(struct sony_sc *sc)
2414 {
2415 	int ret;
2416 
2417 	/* HIDP stores the device MAC address as a string in the uniq field. */
2418 	ret = strlen(sc->hdev->uniq);
2419 	if (ret != 17)
2420 		return -EINVAL;
2421 
2422 	ret = sscanf(sc->hdev->uniq,
2423 		"%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx",
2424 		&sc->mac_address[5], &sc->mac_address[4], &sc->mac_address[3],
2425 		&sc->mac_address[2], &sc->mac_address[1], &sc->mac_address[0]);
2426 
2427 	if (ret != 6)
2428 		return -EINVAL;
2429 
2430 	return 0;
2431 }
2432 
2433 static int sony_check_add(struct sony_sc *sc)
2434 {
2435 	u8 *buf = NULL;
2436 	int n, ret;
2437 
2438 	if ((sc->quirks & DUALSHOCK4_CONTROLLER_BT) ||
2439 	    (sc->quirks & MOTION_CONTROLLER_BT) ||
2440 	    (sc->quirks & NAVIGATION_CONTROLLER_BT) ||
2441 	    (sc->quirks & SIXAXIS_CONTROLLER_BT)) {
2442 		/*
2443 		 * sony_get_bt_devaddr() attempts to parse the Bluetooth MAC
2444 		 * address from the uniq string where HIDP stores it.
2445 		 * As uniq cannot be guaranteed to be a MAC address in all cases
2446 		 * a failure of this function should not prevent the connection.
2447 		 */
2448 		if (sony_get_bt_devaddr(sc) < 0) {
2449 			hid_warn(sc->hdev, "UNIQ does not contain a MAC address; duplicate check skipped\n");
2450 			return 0;
2451 		}
2452 	} else if (sc->quirks & (DUALSHOCK4_CONTROLLER_USB | DUALSHOCK4_DONGLE)) {
2453 		buf = kmalloc(DS4_FEATURE_REPORT_0x81_SIZE, GFP_KERNEL);
2454 		if (!buf)
2455 			return -ENOMEM;
2456 
2457 		/*
2458 		 * The MAC address of a DS4 controller connected via USB can be
2459 		 * retrieved with feature report 0x81. The address begins at
2460 		 * offset 1.
2461 		 */
2462 		ret = hid_hw_raw_request(sc->hdev, 0x81, buf,
2463 				DS4_FEATURE_REPORT_0x81_SIZE, HID_FEATURE_REPORT,
2464 				HID_REQ_GET_REPORT);
2465 
2466 		if (ret != DS4_FEATURE_REPORT_0x81_SIZE) {
2467 			hid_err(sc->hdev, "failed to retrieve feature report 0x81 with the DualShock 4 MAC address\n");
2468 			ret = ret < 0 ? ret : -EINVAL;
2469 			goto out_free;
2470 		}
2471 
2472 		memcpy(sc->mac_address, &buf[1], sizeof(sc->mac_address));
2473 
2474 		snprintf(sc->hdev->uniq, sizeof(sc->hdev->uniq),
2475 			 "%pMR", sc->mac_address);
2476 	} else if ((sc->quirks & SIXAXIS_CONTROLLER_USB) ||
2477 			(sc->quirks & NAVIGATION_CONTROLLER_USB)) {
2478 		buf = kmalloc(SIXAXIS_REPORT_0xF2_SIZE, GFP_KERNEL);
2479 		if (!buf)
2480 			return -ENOMEM;
2481 
2482 		/*
2483 		 * The MAC address of a Sixaxis controller connected via USB can
2484 		 * be retrieved with feature report 0xf2. The address begins at
2485 		 * offset 4.
2486 		 */
2487 		ret = hid_hw_raw_request(sc->hdev, 0xf2, buf,
2488 				SIXAXIS_REPORT_0xF2_SIZE, HID_FEATURE_REPORT,
2489 				HID_REQ_GET_REPORT);
2490 
2491 		if (ret != SIXAXIS_REPORT_0xF2_SIZE) {
2492 			hid_err(sc->hdev, "failed to retrieve feature report 0xf2 with the Sixaxis MAC address\n");
2493 			ret = ret < 0 ? ret : -EINVAL;
2494 			goto out_free;
2495 		}
2496 
2497 		/*
2498 		 * The Sixaxis device MAC in the report is big-endian and must
2499 		 * be byte-swapped.
2500 		 */
2501 		for (n = 0; n < 6; n++)
2502 			sc->mac_address[5-n] = buf[4+n];
2503 
2504 		snprintf(sc->hdev->uniq, sizeof(sc->hdev->uniq),
2505 			 "%pMR", sc->mac_address);
2506 	} else {
2507 		return 0;
2508 	}
2509 
2510 	ret = sony_check_add_dev_list(sc);
2511 
2512 out_free:
2513 
2514 	kfree(buf);
2515 
2516 	return ret;
2517 }
2518 
2519 static int sony_set_device_id(struct sony_sc *sc)
2520 {
2521 	int ret;
2522 
2523 	/*
2524 	 * Only DualShock 4 or Sixaxis controllers get an id.
2525 	 * All others are set to -1.
2526 	 */
2527 	if ((sc->quirks & SIXAXIS_CONTROLLER) ||
2528 	    (sc->quirks & DUALSHOCK4_CONTROLLER)) {
2529 		ret = ida_simple_get(&sony_device_id_allocator, 0, 0,
2530 					GFP_KERNEL);
2531 		if (ret < 0) {
2532 			sc->device_id = -1;
2533 			return ret;
2534 		}
2535 		sc->device_id = ret;
2536 	} else {
2537 		sc->device_id = -1;
2538 	}
2539 
2540 	return 0;
2541 }
2542 
2543 static void sony_release_device_id(struct sony_sc *sc)
2544 {
2545 	if (sc->device_id >= 0) {
2546 		ida_simple_remove(&sony_device_id_allocator, sc->device_id);
2547 		sc->device_id = -1;
2548 	}
2549 }
2550 
2551 static inline void sony_init_output_report(struct sony_sc *sc,
2552 				void (*send_output_report)(struct sony_sc *))
2553 {
2554 	sc->send_output_report = send_output_report;
2555 
2556 	if (!sc->state_worker_initialized)
2557 		INIT_WORK(&sc->state_worker, sony_state_worker);
2558 
2559 	sc->state_worker_initialized = 1;
2560 }
2561 
2562 static inline void sony_cancel_work_sync(struct sony_sc *sc)
2563 {
2564 	if (sc->hotplug_worker_initialized)
2565 		cancel_work_sync(&sc->hotplug_worker);
2566 	if (sc->state_worker_initialized)
2567 		cancel_work_sync(&sc->state_worker);
2568 }
2569 
2570 
2571 static int sony_input_configured(struct hid_device *hdev,
2572 					struct hid_input *hidinput)
2573 {
2574 	struct sony_sc *sc = hid_get_drvdata(hdev);
2575 	int append_dev_id;
2576 	int ret;
2577 
2578 	ret = sony_set_device_id(sc);
2579 	if (ret < 0) {
2580 		hid_err(hdev, "failed to allocate the device id\n");
2581 		goto err_stop;
2582 	}
2583 
2584 	ret = append_dev_id = sony_check_add(sc);
2585 	if (ret < 0)
2586 		goto err_stop;
2587 
2588 	ret = sony_allocate_output_report(sc);
2589 	if (ret < 0) {
2590 		hid_err(hdev, "failed to allocate the output report buffer\n");
2591 		goto err_stop;
2592 	}
2593 
2594 	if (sc->quirks & NAVIGATION_CONTROLLER_USB) {
2595 		/*
2596 		 * The Sony Sixaxis does not handle HID Output Reports on the
2597 		 * Interrupt EP like it could, so we need to force HID Output
2598 		 * Reports to use HID_REQ_SET_REPORT on the Control EP.
2599 		 *
2600 		 * There is also another issue about HID Output Reports via USB,
2601 		 * the Sixaxis does not want the report_id as part of the data
2602 		 * packet, so we have to discard buf[0] when sending the actual
2603 		 * control message, even for numbered reports, humpf!
2604 		 *
2605 		 * Additionally, the Sixaxis on USB isn't properly initialized
2606 		 * until the PS logo button is pressed and as such won't retain
2607 		 * any state set by an output report, so the initial
2608 		 * configuration report is deferred until the first input
2609 		 * report arrives.
2610 		 */
2611 		hdev->quirks |= HID_QUIRK_NO_OUTPUT_REPORTS_ON_INTR_EP;
2612 		hdev->quirks |= HID_QUIRK_SKIP_OUTPUT_REPORT_ID;
2613 		sc->defer_initialization = 1;
2614 
2615 		ret = sixaxis_set_operational_usb(hdev);
2616 		if (ret < 0) {
2617 			hid_err(hdev, "Failed to set controller into operational mode\n");
2618 			goto err_stop;
2619 		}
2620 
2621 		sony_init_output_report(sc, sixaxis_send_output_report);
2622 	} else if (sc->quirks & NAVIGATION_CONTROLLER_BT) {
2623 		/*
2624 		 * The Navigation controller wants output reports sent on the ctrl
2625 		 * endpoint when connected via Bluetooth.
2626 		 */
2627 		hdev->quirks |= HID_QUIRK_NO_OUTPUT_REPORTS_ON_INTR_EP;
2628 
2629 		ret = sixaxis_set_operational_bt(hdev);
2630 		if (ret < 0) {
2631 			hid_err(hdev, "Failed to set controller into operational mode\n");
2632 			goto err_stop;
2633 		}
2634 
2635 		sony_init_output_report(sc, sixaxis_send_output_report);
2636 	} else if (sc->quirks & SIXAXIS_CONTROLLER_USB) {
2637 		/*
2638 		 * The Sony Sixaxis does not handle HID Output Reports on the
2639 		 * Interrupt EP and the device only becomes active when the
2640 		 * PS button is pressed. See comment for Navigation controller
2641 		 * above for more details.
2642 		 */
2643 		hdev->quirks |= HID_QUIRK_NO_OUTPUT_REPORTS_ON_INTR_EP;
2644 		hdev->quirks |= HID_QUIRK_SKIP_OUTPUT_REPORT_ID;
2645 		sc->defer_initialization = 1;
2646 
2647 		ret = sixaxis_set_operational_usb(hdev);
2648 		if (ret < 0) {
2649 			hid_err(hdev, "Failed to set controller into operational mode\n");
2650 			goto err_stop;
2651 		}
2652 
2653 		ret = sony_register_sensors(sc);
2654 		if (ret) {
2655 			hid_err(sc->hdev,
2656 			"Unable to initialize motion sensors: %d\n", ret);
2657 			goto err_stop;
2658 		}
2659 
2660 		sony_init_output_report(sc, sixaxis_send_output_report);
2661 	} else if (sc->quirks & SIXAXIS_CONTROLLER_BT) {
2662 		/*
2663 		 * The Sixaxis wants output reports sent on the ctrl endpoint
2664 		 * when connected via Bluetooth.
2665 		 */
2666 		hdev->quirks |= HID_QUIRK_NO_OUTPUT_REPORTS_ON_INTR_EP;
2667 
2668 		ret = sixaxis_set_operational_bt(hdev);
2669 		if (ret < 0) {
2670 			hid_err(hdev, "Failed to set controller into operational mode\n");
2671 			goto err_stop;
2672 		}
2673 
2674 		ret = sony_register_sensors(sc);
2675 		if (ret) {
2676 			hid_err(sc->hdev,
2677 			"Unable to initialize motion sensors: %d\n", ret);
2678 			goto err_stop;
2679 		}
2680 
2681 		sony_init_output_report(sc, sixaxis_send_output_report);
2682 	} else if (sc->quirks & DUALSHOCK4_CONTROLLER) {
2683 		ret = dualshock4_get_calibration_data(sc);
2684 		if (ret < 0) {
2685 			hid_err(hdev, "Failed to get calibration data from Dualshock 4\n");
2686 			goto err_stop;
2687 		}
2688 
2689 		ret = dualshock4_get_version_info(sc);
2690 		if (ret < 0) {
2691 			hid_err(sc->hdev, "Failed to get version data from Dualshock 4\n");
2692 			goto err_stop;
2693 		}
2694 
2695 		ret = device_create_file(&sc->hdev->dev, &dev_attr_firmware_version);
2696 		if (ret) {
2697 			/* Make zero for cleanup reasons of sysfs entries. */
2698 			sc->fw_version = 0;
2699 			sc->hw_version = 0;
2700 			hid_err(sc->hdev, "can't create sysfs firmware_version attribute err: %d\n", ret);
2701 			goto err_stop;
2702 		}
2703 
2704 		ret = device_create_file(&sc->hdev->dev, &dev_attr_hardware_version);
2705 		if (ret) {
2706 			sc->hw_version = 0;
2707 			hid_err(sc->hdev, "can't create sysfs hardware_version attribute err: %d\n", ret);
2708 			goto err_stop;
2709 		}
2710 
2711 		/*
2712 		 * The Dualshock 4 touchpad supports 2 touches and has a
2713 		 * resolution of 1920x942 (44.86 dots/mm).
2714 		 */
2715 		ret = sony_register_touchpad(sc, 2, 1920, 942, 0, 0, 0);
2716 		if (ret) {
2717 			hid_err(sc->hdev,
2718 			"Unable to initialize multi-touch slots: %d\n",
2719 			ret);
2720 			goto err_stop;
2721 		}
2722 
2723 		ret = sony_register_sensors(sc);
2724 		if (ret) {
2725 			hid_err(sc->hdev,
2726 			"Unable to initialize motion sensors: %d\n", ret);
2727 			goto err_stop;
2728 		}
2729 
2730 		if (sc->quirks & DUALSHOCK4_CONTROLLER_BT) {
2731 			sc->ds4_bt_poll_interval = DS4_BT_DEFAULT_POLL_INTERVAL_MS;
2732 			ret = device_create_file(&sc->hdev->dev, &dev_attr_bt_poll_interval);
2733 			if (ret)
2734 				hid_warn(sc->hdev,
2735 				 "can't create sysfs bt_poll_interval attribute err: %d\n",
2736 				 ret);
2737 		}
2738 
2739 		if (sc->quirks & DUALSHOCK4_DONGLE) {
2740 			INIT_WORK(&sc->hotplug_worker, dualshock4_calibration_work);
2741 			sc->hotplug_worker_initialized = 1;
2742 			sc->ds4_dongle_state = DONGLE_DISCONNECTED;
2743 		}
2744 
2745 		sony_init_output_report(sc, dualshock4_send_output_report);
2746 	} else if (sc->quirks & NSG_MRXU_REMOTE) {
2747 		/*
2748 		 * The NSG-MRxU touchpad supports 2 touches and has a
2749 		 * resolution of 1667x1868
2750 		 */
2751 		ret = sony_register_touchpad(sc, 2,
2752 			NSG_MRXU_MAX_X, NSG_MRXU_MAX_Y, 15, 15, 1);
2753 		if (ret) {
2754 			hid_err(sc->hdev,
2755 			"Unable to initialize multi-touch slots: %d\n",
2756 			ret);
2757 			goto err_stop;
2758 		}
2759 
2760 	} else if (sc->quirks & MOTION_CONTROLLER) {
2761 		sony_init_output_report(sc, motion_send_output_report);
2762 	} else {
2763 		ret = 0;
2764 	}
2765 
2766 	if (sc->quirks & SONY_LED_SUPPORT) {
2767 		ret = sony_leds_init(sc);
2768 		if (ret < 0)
2769 			goto err_stop;
2770 	}
2771 
2772 	if (sc->quirks & SONY_BATTERY_SUPPORT) {
2773 		ret = sony_battery_probe(sc, append_dev_id);
2774 		if (ret < 0)
2775 			goto err_stop;
2776 
2777 		/* Open the device to receive reports with battery info */
2778 		ret = hid_hw_open(hdev);
2779 		if (ret < 0) {
2780 			hid_err(hdev, "hw open failed\n");
2781 			goto err_stop;
2782 		}
2783 	}
2784 
2785 	if (sc->quirks & SONY_FF_SUPPORT) {
2786 		ret = sony_init_ff(sc);
2787 		if (ret < 0)
2788 			goto err_close;
2789 	}
2790 
2791 	return 0;
2792 err_close:
2793 	hid_hw_close(hdev);
2794 err_stop:
2795 	/* Piggy back on the default ds4_bt_ poll_interval to determine
2796 	 * if we need to remove the file as we don't know for sure if we
2797 	 * executed that logic.
2798 	 */
2799 	if (sc->ds4_bt_poll_interval)
2800 		device_remove_file(&sc->hdev->dev, &dev_attr_bt_poll_interval);
2801 	if (sc->fw_version)
2802 		device_remove_file(&sc->hdev->dev, &dev_attr_firmware_version);
2803 	if (sc->hw_version)
2804 		device_remove_file(&sc->hdev->dev, &dev_attr_hardware_version);
2805 	sony_cancel_work_sync(sc);
2806 	sony_remove_dev_list(sc);
2807 	sony_release_device_id(sc);
2808 	hid_hw_stop(hdev);
2809 	return ret;
2810 }
2811 
2812 static int sony_probe(struct hid_device *hdev, const struct hid_device_id *id)
2813 {
2814 	int ret;
2815 	unsigned long quirks = id->driver_data;
2816 	struct sony_sc *sc;
2817 	unsigned int connect_mask = HID_CONNECT_DEFAULT;
2818 
2819 	if (!strcmp(hdev->name, "FutureMax Dance Mat"))
2820 		quirks |= FUTUREMAX_DANCE_MAT;
2821 
2822 	if (!strcmp(hdev->name, "SHANWAN PS3 GamePad"))
2823 		quirks |= SHANWAN_GAMEPAD;
2824 
2825 	sc = devm_kzalloc(&hdev->dev, sizeof(*sc), GFP_KERNEL);
2826 	if (sc == NULL) {
2827 		hid_err(hdev, "can't alloc sony descriptor\n");
2828 		return -ENOMEM;
2829 	}
2830 
2831 	spin_lock_init(&sc->lock);
2832 
2833 	sc->quirks = quirks;
2834 	hid_set_drvdata(hdev, sc);
2835 	sc->hdev = hdev;
2836 
2837 	ret = hid_parse(hdev);
2838 	if (ret) {
2839 		hid_err(hdev, "parse failed\n");
2840 		return ret;
2841 	}
2842 
2843 	if (sc->quirks & VAIO_RDESC_CONSTANT)
2844 		connect_mask |= HID_CONNECT_HIDDEV_FORCE;
2845 	else if (sc->quirks & SIXAXIS_CONTROLLER)
2846 		connect_mask |= HID_CONNECT_HIDDEV_FORCE;
2847 
2848 	/* Patch the hw version on DS3/4 compatible devices, so applications can
2849 	 * distinguish between the default HID mappings and the mappings defined
2850 	 * by the Linux game controller spec. This is important for the SDL2
2851 	 * library, which has a game controller database, which uses device ids
2852 	 * in combination with version as a key.
2853 	 */
2854 	if (sc->quirks & (SIXAXIS_CONTROLLER | DUALSHOCK4_CONTROLLER))
2855 		hdev->version |= 0x8000;
2856 
2857 	ret = hid_hw_start(hdev, connect_mask);
2858 	if (ret) {
2859 		hid_err(hdev, "hw start failed\n");
2860 		return ret;
2861 	}
2862 
2863 	/* sony_input_configured can fail, but this doesn't result
2864 	 * in hid_hw_start failures (intended). Check whether
2865 	 * the HID layer claimed the device else fail.
2866 	 * We don't know the actual reason for the failure, most
2867 	 * likely it is due to EEXIST in case of double connection
2868 	 * of USB and Bluetooth, but could have been due to ENOMEM
2869 	 * or other reasons as well.
2870 	 */
2871 	if (!(hdev->claimed & HID_CLAIMED_INPUT)) {
2872 		hid_err(hdev, "failed to claim input\n");
2873 		return -ENODEV;
2874 	}
2875 
2876 	return ret;
2877 }
2878 
2879 static void sony_remove(struct hid_device *hdev)
2880 {
2881 	struct sony_sc *sc = hid_get_drvdata(hdev);
2882 
2883 	hid_hw_close(hdev);
2884 
2885 	if (sc->quirks & DUALSHOCK4_CONTROLLER_BT)
2886 		device_remove_file(&sc->hdev->dev, &dev_attr_bt_poll_interval);
2887 
2888 	if (sc->fw_version)
2889 		device_remove_file(&sc->hdev->dev, &dev_attr_firmware_version);
2890 
2891 	if (sc->hw_version)
2892 		device_remove_file(&sc->hdev->dev, &dev_attr_hardware_version);
2893 
2894 	sony_cancel_work_sync(sc);
2895 
2896 	sony_remove_dev_list(sc);
2897 
2898 	sony_release_device_id(sc);
2899 
2900 	hid_hw_stop(hdev);
2901 }
2902 
2903 #ifdef CONFIG_PM
2904 
2905 static int sony_suspend(struct hid_device *hdev, pm_message_t message)
2906 {
2907 #ifdef CONFIG_SONY_FF
2908 
2909 	/* On suspend stop any running force-feedback events */
2910 	if (SONY_FF_SUPPORT) {
2911 		struct sony_sc *sc = hid_get_drvdata(hdev);
2912 
2913 		sc->left = sc->right = 0;
2914 		sony_send_output_report(sc);
2915 	}
2916 
2917 #endif
2918 	return 0;
2919 }
2920 
2921 static int sony_resume(struct hid_device *hdev)
2922 {
2923 	struct sony_sc *sc = hid_get_drvdata(hdev);
2924 
2925 	/*
2926 	 * The Sixaxis and navigation controllers on USB need to be
2927 	 * reinitialized on resume or they won't behave properly.
2928 	 */
2929 	if ((sc->quirks & SIXAXIS_CONTROLLER_USB) ||
2930 		(sc->quirks & NAVIGATION_CONTROLLER_USB)) {
2931 		sixaxis_set_operational_usb(sc->hdev);
2932 		sc->defer_initialization = 1;
2933 	}
2934 
2935 	return 0;
2936 }
2937 
2938 #endif
2939 
2940 static const struct hid_device_id sony_devices[] = {
2941 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS3_CONTROLLER),
2942 		.driver_data = SIXAXIS_CONTROLLER_USB },
2943 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_NAVIGATION_CONTROLLER),
2944 		.driver_data = NAVIGATION_CONTROLLER_USB },
2945 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_NAVIGATION_CONTROLLER),
2946 		.driver_data = NAVIGATION_CONTROLLER_BT },
2947 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_MOTION_CONTROLLER),
2948 		.driver_data = MOTION_CONTROLLER_USB },
2949 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_MOTION_CONTROLLER),
2950 		.driver_data = MOTION_CONTROLLER_BT },
2951 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS3_CONTROLLER),
2952 		.driver_data = SIXAXIS_CONTROLLER_BT },
2953 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_VAIO_VGX_MOUSE),
2954 		.driver_data = VAIO_RDESC_CONSTANT },
2955 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_VAIO_VGP_MOUSE),
2956 		.driver_data = VAIO_RDESC_CONSTANT },
2957 	/*
2958 	 * Wired Buzz Controller. Reported as Sony Hub from its USB ID and as
2959 	 * Logitech joystick from the device descriptor.
2960 	 */
2961 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_BUZZ_CONTROLLER),
2962 		.driver_data = BUZZ_CONTROLLER },
2963 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_WIRELESS_BUZZ_CONTROLLER),
2964 		.driver_data = BUZZ_CONTROLLER },
2965 	/* PS3 BD Remote Control */
2966 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS3_BDREMOTE),
2967 		.driver_data = PS3REMOTE },
2968 	/* Logitech Harmony Adapter for PS3 */
2969 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_HARMONY_PS3),
2970 		.driver_data = PS3REMOTE },
2971 	/* SMK-Link PS3 BD Remote Control */
2972 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SMK, USB_DEVICE_ID_SMK_PS3_BDREMOTE),
2973 		.driver_data = PS3REMOTE },
2974 	/* Sony Dualshock 4 controllers for PS4 */
2975 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER),
2976 		.driver_data = DUALSHOCK4_CONTROLLER_USB },
2977 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER),
2978 		.driver_data = DUALSHOCK4_CONTROLLER_BT },
2979 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER_2),
2980 		.driver_data = DUALSHOCK4_CONTROLLER_USB },
2981 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER_2),
2982 		.driver_data = DUALSHOCK4_CONTROLLER_BT },
2983 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER_DONGLE),
2984 		.driver_data = DUALSHOCK4_DONGLE },
2985 	/* Nyko Core Controller for PS3 */
2986 	{ HID_USB_DEVICE(USB_VENDOR_ID_SINO_LITE, USB_DEVICE_ID_SINO_LITE_CONTROLLER),
2987 		.driver_data = SIXAXIS_CONTROLLER_USB | SINO_LITE_CONTROLLER },
2988 	/* SMK-Link NSG-MR5U Remote Control */
2989 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SMK, USB_DEVICE_ID_SMK_NSG_MR5U_REMOTE),
2990 		.driver_data = NSG_MR5U_REMOTE_BT },
2991 	/* SMK-Link NSG-MR7U Remote Control */
2992 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SMK, USB_DEVICE_ID_SMK_NSG_MR7U_REMOTE),
2993 		.driver_data = NSG_MR7U_REMOTE_BT },
2994 	{ }
2995 };
2996 MODULE_DEVICE_TABLE(hid, sony_devices);
2997 
2998 static struct hid_driver sony_driver = {
2999 	.name             = "sony",
3000 	.id_table         = sony_devices,
3001 	.input_mapping    = sony_mapping,
3002 	.input_configured = sony_input_configured,
3003 	.probe            = sony_probe,
3004 	.remove           = sony_remove,
3005 	.report_fixup     = sony_report_fixup,
3006 	.raw_event        = sony_raw_event,
3007 
3008 #ifdef CONFIG_PM
3009 	.suspend          = sony_suspend,
3010 	.resume	          = sony_resume,
3011 	.reset_resume     = sony_resume,
3012 #endif
3013 };
3014 
3015 static int __init sony_init(void)
3016 {
3017 	dbg_hid("Sony:%s\n", __func__);
3018 
3019 	return hid_register_driver(&sony_driver);
3020 }
3021 
3022 static void __exit sony_exit(void)
3023 {
3024 	dbg_hid("Sony:%s\n", __func__);
3025 
3026 	hid_unregister_driver(&sony_driver);
3027 	ida_destroy(&sony_device_id_allocator);
3028 }
3029 module_init(sony_init);
3030 module_exit(sony_exit);
3031 
3032 MODULE_LICENSE("GPL");
3033