xref: /openbmc/linux/drivers/hid/hid-sony.c (revision 69481059)
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 	hid_hw_raw_request(sc->hdev, report->report_id, (u8 *)report,
2104 			sizeof(struct sixaxis_output_report),
2105 			HID_OUTPUT_REPORT, HID_REQ_SET_REPORT);
2106 }
2107 
2108 static void dualshock4_send_output_report(struct sony_sc *sc)
2109 {
2110 	struct hid_device *hdev = sc->hdev;
2111 	u8 *buf = sc->output_report_dmabuf;
2112 	int offset;
2113 
2114 	/*
2115 	 * NOTE: The lower 6 bits of buf[1] field of the Bluetooth report
2116 	 * control the interval at which Dualshock 4 reports data:
2117 	 * 0x00 - 1ms
2118 	 * 0x01 - 1ms
2119 	 * 0x02 - 2ms
2120 	 * 0x3E - 62ms
2121 	 * 0x3F - disabled
2122 	 */
2123 	if (sc->quirks & (DUALSHOCK4_CONTROLLER_USB | DUALSHOCK4_DONGLE)) {
2124 		memset(buf, 0, DS4_OUTPUT_REPORT_0x05_SIZE);
2125 		buf[0] = 0x05;
2126 		buf[1] = 0x07; /* blink + LEDs + motor */
2127 		offset = 4;
2128 	} else {
2129 		memset(buf, 0, DS4_OUTPUT_REPORT_0x11_SIZE);
2130 		buf[0] = 0x11;
2131 		buf[1] = 0xC0 /* HID + CRC */ | sc->ds4_bt_poll_interval;
2132 		buf[3] = 0x07; /* blink + LEDs + motor */
2133 		offset = 6;
2134 	}
2135 
2136 #ifdef CONFIG_SONY_FF
2137 	buf[offset++] = sc->right;
2138 	buf[offset++] = sc->left;
2139 #else
2140 	offset += 2;
2141 #endif
2142 
2143 	/* LED 3 is the global control */
2144 	if (sc->led_state[3]) {
2145 		buf[offset++] = sc->led_state[0];
2146 		buf[offset++] = sc->led_state[1];
2147 		buf[offset++] = sc->led_state[2];
2148 	} else {
2149 		offset += 3;
2150 	}
2151 
2152 	/* If both delay values are zero the DualShock 4 disables blinking. */
2153 	buf[offset++] = sc->led_delay_on[3];
2154 	buf[offset++] = sc->led_delay_off[3];
2155 
2156 	if (sc->quirks & (DUALSHOCK4_CONTROLLER_USB | DUALSHOCK4_DONGLE))
2157 		hid_hw_output_report(hdev, buf, DS4_OUTPUT_REPORT_0x05_SIZE);
2158 	else {
2159 		/* CRC generation */
2160 		u8 bthdr = 0xA2;
2161 		u32 crc;
2162 
2163 		crc = crc32_le(0xFFFFFFFF, &bthdr, 1);
2164 		crc = ~crc32_le(crc, buf, DS4_OUTPUT_REPORT_0x11_SIZE-4);
2165 		put_unaligned_le32(crc, &buf[74]);
2166 		hid_hw_output_report(hdev, buf, DS4_OUTPUT_REPORT_0x11_SIZE);
2167 	}
2168 }
2169 
2170 static void motion_send_output_report(struct sony_sc *sc)
2171 {
2172 	struct hid_device *hdev = sc->hdev;
2173 	struct motion_output_report_02 *report =
2174 		(struct motion_output_report_02 *)sc->output_report_dmabuf;
2175 
2176 	memset(report, 0, MOTION_REPORT_0x02_SIZE);
2177 
2178 	report->type = 0x02; /* set leds */
2179 	report->r = sc->led_state[0];
2180 	report->g = sc->led_state[1];
2181 	report->b = sc->led_state[2];
2182 
2183 #ifdef CONFIG_SONY_FF
2184 	report->rumble = max(sc->right, sc->left);
2185 #endif
2186 
2187 	hid_hw_output_report(hdev, (u8 *)report, MOTION_REPORT_0x02_SIZE);
2188 }
2189 
2190 static inline void sony_send_output_report(struct sony_sc *sc)
2191 {
2192 	if (sc->send_output_report)
2193 		sc->send_output_report(sc);
2194 }
2195 
2196 static void sony_state_worker(struct work_struct *work)
2197 {
2198 	struct sony_sc *sc = container_of(work, struct sony_sc, state_worker);
2199 
2200 	sc->send_output_report(sc);
2201 }
2202 
2203 static int sony_allocate_output_report(struct sony_sc *sc)
2204 {
2205 	if ((sc->quirks & SIXAXIS_CONTROLLER) ||
2206 			(sc->quirks & NAVIGATION_CONTROLLER))
2207 		sc->output_report_dmabuf =
2208 			devm_kmalloc(&sc->hdev->dev,
2209 				sizeof(union sixaxis_output_report_01),
2210 				GFP_KERNEL);
2211 	else if (sc->quirks & DUALSHOCK4_CONTROLLER_BT)
2212 		sc->output_report_dmabuf = devm_kmalloc(&sc->hdev->dev,
2213 						DS4_OUTPUT_REPORT_0x11_SIZE,
2214 						GFP_KERNEL);
2215 	else if (sc->quirks & (DUALSHOCK4_CONTROLLER_USB | DUALSHOCK4_DONGLE))
2216 		sc->output_report_dmabuf = devm_kmalloc(&sc->hdev->dev,
2217 						DS4_OUTPUT_REPORT_0x05_SIZE,
2218 						GFP_KERNEL);
2219 	else if (sc->quirks & MOTION_CONTROLLER)
2220 		sc->output_report_dmabuf = devm_kmalloc(&sc->hdev->dev,
2221 						MOTION_REPORT_0x02_SIZE,
2222 						GFP_KERNEL);
2223 	else
2224 		return 0;
2225 
2226 	if (!sc->output_report_dmabuf)
2227 		return -ENOMEM;
2228 
2229 	return 0;
2230 }
2231 
2232 #ifdef CONFIG_SONY_FF
2233 static int sony_play_effect(struct input_dev *dev, void *data,
2234 			    struct ff_effect *effect)
2235 {
2236 	struct hid_device *hid = input_get_drvdata(dev);
2237 	struct sony_sc *sc = hid_get_drvdata(hid);
2238 
2239 	if (effect->type != FF_RUMBLE)
2240 		return 0;
2241 
2242 	sc->left = effect->u.rumble.strong_magnitude / 256;
2243 	sc->right = effect->u.rumble.weak_magnitude / 256;
2244 
2245 	sony_schedule_work(sc, SONY_WORKER_STATE);
2246 	return 0;
2247 }
2248 
2249 static int sony_init_ff(struct sony_sc *sc)
2250 {
2251 	struct hid_input *hidinput = list_entry(sc->hdev->inputs.next,
2252 						struct hid_input, list);
2253 	struct input_dev *input_dev = hidinput->input;
2254 
2255 	input_set_capability(input_dev, EV_FF, FF_RUMBLE);
2256 	return input_ff_create_memless(input_dev, NULL, sony_play_effect);
2257 }
2258 
2259 #else
2260 static int sony_init_ff(struct sony_sc *sc)
2261 {
2262 	return 0;
2263 }
2264 
2265 #endif
2266 
2267 static int sony_battery_get_property(struct power_supply *psy,
2268 				     enum power_supply_property psp,
2269 				     union power_supply_propval *val)
2270 {
2271 	struct sony_sc *sc = power_supply_get_drvdata(psy);
2272 	unsigned long flags;
2273 	int ret = 0;
2274 	u8 battery_charging, battery_capacity, cable_state;
2275 
2276 	spin_lock_irqsave(&sc->lock, flags);
2277 	battery_charging = sc->battery_charging;
2278 	battery_capacity = sc->battery_capacity;
2279 	cable_state = sc->cable_state;
2280 	spin_unlock_irqrestore(&sc->lock, flags);
2281 
2282 	switch (psp) {
2283 	case POWER_SUPPLY_PROP_PRESENT:
2284 		val->intval = 1;
2285 		break;
2286 	case POWER_SUPPLY_PROP_SCOPE:
2287 		val->intval = POWER_SUPPLY_SCOPE_DEVICE;
2288 		break;
2289 	case POWER_SUPPLY_PROP_CAPACITY:
2290 		val->intval = battery_capacity;
2291 		break;
2292 	case POWER_SUPPLY_PROP_STATUS:
2293 		if (battery_charging)
2294 			val->intval = POWER_SUPPLY_STATUS_CHARGING;
2295 		else
2296 			if (battery_capacity == 100 && cable_state)
2297 				val->intval = POWER_SUPPLY_STATUS_FULL;
2298 			else
2299 				val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
2300 		break;
2301 	default:
2302 		ret = -EINVAL;
2303 		break;
2304 	}
2305 	return ret;
2306 }
2307 
2308 static int sony_battery_probe(struct sony_sc *sc, int append_dev_id)
2309 {
2310 	const char *battery_str_fmt = append_dev_id ?
2311 		"sony_controller_battery_%pMR_%i" :
2312 		"sony_controller_battery_%pMR";
2313 	struct power_supply_config psy_cfg = { .drv_data = sc, };
2314 	struct hid_device *hdev = sc->hdev;
2315 	int ret;
2316 
2317 	/*
2318 	 * Set the default battery level to 100% to avoid low battery warnings
2319 	 * if the battery is polled before the first device report is received.
2320 	 */
2321 	sc->battery_capacity = 100;
2322 
2323 	sc->battery_desc.properties = sony_battery_props;
2324 	sc->battery_desc.num_properties = ARRAY_SIZE(sony_battery_props);
2325 	sc->battery_desc.get_property = sony_battery_get_property;
2326 	sc->battery_desc.type = POWER_SUPPLY_TYPE_BATTERY;
2327 	sc->battery_desc.use_for_apm = 0;
2328 	sc->battery_desc.name = devm_kasprintf(&hdev->dev, GFP_KERNEL,
2329 					  battery_str_fmt, sc->mac_address, sc->device_id);
2330 	if (!sc->battery_desc.name)
2331 		return -ENOMEM;
2332 
2333 	sc->battery = devm_power_supply_register(&hdev->dev, &sc->battery_desc,
2334 					    &psy_cfg);
2335 	if (IS_ERR(sc->battery)) {
2336 		ret = PTR_ERR(sc->battery);
2337 		hid_err(hdev, "Unable to register battery device\n");
2338 		return ret;
2339 	}
2340 
2341 	power_supply_powers(sc->battery, &hdev->dev);
2342 	return 0;
2343 }
2344 
2345 /*
2346  * If a controller is plugged in via USB while already connected via Bluetooth
2347  * it will show up as two devices. A global list of connected controllers and
2348  * their MAC addresses is maintained to ensure that a device is only connected
2349  * once.
2350  *
2351  * Some USB-only devices masquerade as Sixaxis controllers and all have the
2352  * same dummy Bluetooth address, so a comparison of the connection type is
2353  * required.  Devices are only rejected in the case where two devices have
2354  * matching Bluetooth addresses on different bus types.
2355  */
2356 static inline int sony_compare_connection_type(struct sony_sc *sc0,
2357 						struct sony_sc *sc1)
2358 {
2359 	const int sc0_not_bt = !(sc0->quirks & SONY_BT_DEVICE);
2360 	const int sc1_not_bt = !(sc1->quirks & SONY_BT_DEVICE);
2361 
2362 	return sc0_not_bt == sc1_not_bt;
2363 }
2364 
2365 static int sony_check_add_dev_list(struct sony_sc *sc)
2366 {
2367 	struct sony_sc *entry;
2368 	unsigned long flags;
2369 	int ret;
2370 
2371 	spin_lock_irqsave(&sony_dev_list_lock, flags);
2372 
2373 	list_for_each_entry(entry, &sony_device_list, list_node) {
2374 		ret = memcmp(sc->mac_address, entry->mac_address,
2375 				sizeof(sc->mac_address));
2376 		if (!ret) {
2377 			if (sony_compare_connection_type(sc, entry)) {
2378 				ret = 1;
2379 			} else {
2380 				ret = -EEXIST;
2381 				hid_info(sc->hdev,
2382 				"controller with MAC address %pMR already connected\n",
2383 				sc->mac_address);
2384 			}
2385 			goto unlock;
2386 		}
2387 	}
2388 
2389 	ret = 0;
2390 	list_add(&(sc->list_node), &sony_device_list);
2391 
2392 unlock:
2393 	spin_unlock_irqrestore(&sony_dev_list_lock, flags);
2394 	return ret;
2395 }
2396 
2397 static void sony_remove_dev_list(struct sony_sc *sc)
2398 {
2399 	unsigned long flags;
2400 
2401 	if (sc->list_node.next) {
2402 		spin_lock_irqsave(&sony_dev_list_lock, flags);
2403 		list_del(&(sc->list_node));
2404 		spin_unlock_irqrestore(&sony_dev_list_lock, flags);
2405 	}
2406 }
2407 
2408 static int sony_get_bt_devaddr(struct sony_sc *sc)
2409 {
2410 	int ret;
2411 
2412 	/* HIDP stores the device MAC address as a string in the uniq field. */
2413 	ret = strlen(sc->hdev->uniq);
2414 	if (ret != 17)
2415 		return -EINVAL;
2416 
2417 	ret = sscanf(sc->hdev->uniq,
2418 		"%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx",
2419 		&sc->mac_address[5], &sc->mac_address[4], &sc->mac_address[3],
2420 		&sc->mac_address[2], &sc->mac_address[1], &sc->mac_address[0]);
2421 
2422 	if (ret != 6)
2423 		return -EINVAL;
2424 
2425 	return 0;
2426 }
2427 
2428 static int sony_check_add(struct sony_sc *sc)
2429 {
2430 	u8 *buf = NULL;
2431 	int n, ret;
2432 
2433 	if ((sc->quirks & DUALSHOCK4_CONTROLLER_BT) ||
2434 	    (sc->quirks & MOTION_CONTROLLER_BT) ||
2435 	    (sc->quirks & NAVIGATION_CONTROLLER_BT) ||
2436 	    (sc->quirks & SIXAXIS_CONTROLLER_BT)) {
2437 		/*
2438 		 * sony_get_bt_devaddr() attempts to parse the Bluetooth MAC
2439 		 * address from the uniq string where HIDP stores it.
2440 		 * As uniq cannot be guaranteed to be a MAC address in all cases
2441 		 * a failure of this function should not prevent the connection.
2442 		 */
2443 		if (sony_get_bt_devaddr(sc) < 0) {
2444 			hid_warn(sc->hdev, "UNIQ does not contain a MAC address; duplicate check skipped\n");
2445 			return 0;
2446 		}
2447 	} else if (sc->quirks & (DUALSHOCK4_CONTROLLER_USB | DUALSHOCK4_DONGLE)) {
2448 		buf = kmalloc(DS4_FEATURE_REPORT_0x81_SIZE, GFP_KERNEL);
2449 		if (!buf)
2450 			return -ENOMEM;
2451 
2452 		/*
2453 		 * The MAC address of a DS4 controller connected via USB can be
2454 		 * retrieved with feature report 0x81. The address begins at
2455 		 * offset 1.
2456 		 */
2457 		ret = hid_hw_raw_request(sc->hdev, 0x81, buf,
2458 				DS4_FEATURE_REPORT_0x81_SIZE, HID_FEATURE_REPORT,
2459 				HID_REQ_GET_REPORT);
2460 
2461 		if (ret != DS4_FEATURE_REPORT_0x81_SIZE) {
2462 			hid_err(sc->hdev, "failed to retrieve feature report 0x81 with the DualShock 4 MAC address\n");
2463 			ret = ret < 0 ? ret : -EINVAL;
2464 			goto out_free;
2465 		}
2466 
2467 		memcpy(sc->mac_address, &buf[1], sizeof(sc->mac_address));
2468 
2469 		snprintf(sc->hdev->uniq, sizeof(sc->hdev->uniq),
2470 			 "%pMR", sc->mac_address);
2471 	} else if ((sc->quirks & SIXAXIS_CONTROLLER_USB) ||
2472 			(sc->quirks & NAVIGATION_CONTROLLER_USB)) {
2473 		buf = kmalloc(SIXAXIS_REPORT_0xF2_SIZE, GFP_KERNEL);
2474 		if (!buf)
2475 			return -ENOMEM;
2476 
2477 		/*
2478 		 * The MAC address of a Sixaxis controller connected via USB can
2479 		 * be retrieved with feature report 0xf2. The address begins at
2480 		 * offset 4.
2481 		 */
2482 		ret = hid_hw_raw_request(sc->hdev, 0xf2, buf,
2483 				SIXAXIS_REPORT_0xF2_SIZE, HID_FEATURE_REPORT,
2484 				HID_REQ_GET_REPORT);
2485 
2486 		if (ret != SIXAXIS_REPORT_0xF2_SIZE) {
2487 			hid_err(sc->hdev, "failed to retrieve feature report 0xf2 with the Sixaxis MAC address\n");
2488 			ret = ret < 0 ? ret : -EINVAL;
2489 			goto out_free;
2490 		}
2491 
2492 		/*
2493 		 * The Sixaxis device MAC in the report is big-endian and must
2494 		 * be byte-swapped.
2495 		 */
2496 		for (n = 0; n < 6; n++)
2497 			sc->mac_address[5-n] = buf[4+n];
2498 
2499 		snprintf(sc->hdev->uniq, sizeof(sc->hdev->uniq),
2500 			 "%pMR", sc->mac_address);
2501 	} else {
2502 		return 0;
2503 	}
2504 
2505 	ret = sony_check_add_dev_list(sc);
2506 
2507 out_free:
2508 
2509 	kfree(buf);
2510 
2511 	return ret;
2512 }
2513 
2514 static int sony_set_device_id(struct sony_sc *sc)
2515 {
2516 	int ret;
2517 
2518 	/*
2519 	 * Only DualShock 4 or Sixaxis controllers get an id.
2520 	 * All others are set to -1.
2521 	 */
2522 	if ((sc->quirks & SIXAXIS_CONTROLLER) ||
2523 	    (sc->quirks & DUALSHOCK4_CONTROLLER)) {
2524 		ret = ida_simple_get(&sony_device_id_allocator, 0, 0,
2525 					GFP_KERNEL);
2526 		if (ret < 0) {
2527 			sc->device_id = -1;
2528 			return ret;
2529 		}
2530 		sc->device_id = ret;
2531 	} else {
2532 		sc->device_id = -1;
2533 	}
2534 
2535 	return 0;
2536 }
2537 
2538 static void sony_release_device_id(struct sony_sc *sc)
2539 {
2540 	if (sc->device_id >= 0) {
2541 		ida_simple_remove(&sony_device_id_allocator, sc->device_id);
2542 		sc->device_id = -1;
2543 	}
2544 }
2545 
2546 static inline void sony_init_output_report(struct sony_sc *sc,
2547 				void (*send_output_report)(struct sony_sc *))
2548 {
2549 	sc->send_output_report = send_output_report;
2550 
2551 	if (!sc->state_worker_initialized)
2552 		INIT_WORK(&sc->state_worker, sony_state_worker);
2553 
2554 	sc->state_worker_initialized = 1;
2555 }
2556 
2557 static inline void sony_cancel_work_sync(struct sony_sc *sc)
2558 {
2559 	if (sc->hotplug_worker_initialized)
2560 		cancel_work_sync(&sc->hotplug_worker);
2561 	if (sc->state_worker_initialized)
2562 		cancel_work_sync(&sc->state_worker);
2563 }
2564 
2565 
2566 static int sony_input_configured(struct hid_device *hdev,
2567 					struct hid_input *hidinput)
2568 {
2569 	struct sony_sc *sc = hid_get_drvdata(hdev);
2570 	int append_dev_id;
2571 	int ret;
2572 
2573 	ret = sony_set_device_id(sc);
2574 	if (ret < 0) {
2575 		hid_err(hdev, "failed to allocate the device id\n");
2576 		goto err_stop;
2577 	}
2578 
2579 	ret = append_dev_id = sony_check_add(sc);
2580 	if (ret < 0)
2581 		goto err_stop;
2582 
2583 	ret = sony_allocate_output_report(sc);
2584 	if (ret < 0) {
2585 		hid_err(hdev, "failed to allocate the output report buffer\n");
2586 		goto err_stop;
2587 	}
2588 
2589 	if (sc->quirks & NAVIGATION_CONTROLLER_USB) {
2590 		/*
2591 		 * The Sony Sixaxis does not handle HID Output Reports on the
2592 		 * Interrupt EP like it could, so we need to force HID Output
2593 		 * Reports to use HID_REQ_SET_REPORT on the Control EP.
2594 		 *
2595 		 * There is also another issue about HID Output Reports via USB,
2596 		 * the Sixaxis does not want the report_id as part of the data
2597 		 * packet, so we have to discard buf[0] when sending the actual
2598 		 * control message, even for numbered reports, humpf!
2599 		 *
2600 		 * Additionally, the Sixaxis on USB isn't properly initialized
2601 		 * until the PS logo button is pressed and as such won't retain
2602 		 * any state set by an output report, so the initial
2603 		 * configuration report is deferred until the first input
2604 		 * report arrives.
2605 		 */
2606 		hdev->quirks |= HID_QUIRK_NO_OUTPUT_REPORTS_ON_INTR_EP;
2607 		hdev->quirks |= HID_QUIRK_SKIP_OUTPUT_REPORT_ID;
2608 		sc->defer_initialization = 1;
2609 
2610 		ret = sixaxis_set_operational_usb(hdev);
2611 		if (ret < 0) {
2612 			hid_err(hdev, "Failed to set controller into operational mode\n");
2613 			goto err_stop;
2614 		}
2615 
2616 		sony_init_output_report(sc, sixaxis_send_output_report);
2617 	} else if (sc->quirks & NAVIGATION_CONTROLLER_BT) {
2618 		/*
2619 		 * The Navigation controller wants output reports sent on the ctrl
2620 		 * endpoint when connected via Bluetooth.
2621 		 */
2622 		hdev->quirks |= HID_QUIRK_NO_OUTPUT_REPORTS_ON_INTR_EP;
2623 
2624 		ret = sixaxis_set_operational_bt(hdev);
2625 		if (ret < 0) {
2626 			hid_err(hdev, "Failed to set controller into operational mode\n");
2627 			goto err_stop;
2628 		}
2629 
2630 		sony_init_output_report(sc, sixaxis_send_output_report);
2631 	} else if (sc->quirks & SIXAXIS_CONTROLLER_USB) {
2632 		/*
2633 		 * The Sony Sixaxis does not handle HID Output Reports on the
2634 		 * Interrupt EP and the device only becomes active when the
2635 		 * PS button is pressed. See comment for Navigation controller
2636 		 * above for more details.
2637 		 */
2638 		hdev->quirks |= HID_QUIRK_NO_OUTPUT_REPORTS_ON_INTR_EP;
2639 		hdev->quirks |= HID_QUIRK_SKIP_OUTPUT_REPORT_ID;
2640 		sc->defer_initialization = 1;
2641 
2642 		ret = sixaxis_set_operational_usb(hdev);
2643 		if (ret < 0) {
2644 			hid_err(hdev, "Failed to set controller into operational mode\n");
2645 			goto err_stop;
2646 		}
2647 
2648 		ret = sony_register_sensors(sc);
2649 		if (ret) {
2650 			hid_err(sc->hdev,
2651 			"Unable to initialize motion sensors: %d\n", ret);
2652 			goto err_stop;
2653 		}
2654 
2655 		sony_init_output_report(sc, sixaxis_send_output_report);
2656 	} else if (sc->quirks & SIXAXIS_CONTROLLER_BT) {
2657 		/*
2658 		 * The Sixaxis wants output reports sent on the ctrl endpoint
2659 		 * when connected via Bluetooth.
2660 		 */
2661 		hdev->quirks |= HID_QUIRK_NO_OUTPUT_REPORTS_ON_INTR_EP;
2662 
2663 		ret = sixaxis_set_operational_bt(hdev);
2664 		if (ret < 0) {
2665 			hid_err(hdev, "Failed to set controller into operational mode\n");
2666 			goto err_stop;
2667 		}
2668 
2669 		ret = sony_register_sensors(sc);
2670 		if (ret) {
2671 			hid_err(sc->hdev,
2672 			"Unable to initialize motion sensors: %d\n", ret);
2673 			goto err_stop;
2674 		}
2675 
2676 		sony_init_output_report(sc, sixaxis_send_output_report);
2677 	} else if (sc->quirks & DUALSHOCK4_CONTROLLER) {
2678 		ret = dualshock4_get_calibration_data(sc);
2679 		if (ret < 0) {
2680 			hid_err(hdev, "Failed to get calibration data from Dualshock 4\n");
2681 			goto err_stop;
2682 		}
2683 
2684 		ret = dualshock4_get_version_info(sc);
2685 		if (ret < 0) {
2686 			hid_err(sc->hdev, "Failed to get version data from Dualshock 4\n");
2687 			goto err_stop;
2688 		}
2689 
2690 		ret = device_create_file(&sc->hdev->dev, &dev_attr_firmware_version);
2691 		if (ret) {
2692 			/* Make zero for cleanup reasons of sysfs entries. */
2693 			sc->fw_version = 0;
2694 			sc->hw_version = 0;
2695 			hid_err(sc->hdev, "can't create sysfs firmware_version attribute err: %d\n", ret);
2696 			goto err_stop;
2697 		}
2698 
2699 		ret = device_create_file(&sc->hdev->dev, &dev_attr_hardware_version);
2700 		if (ret) {
2701 			sc->hw_version = 0;
2702 			hid_err(sc->hdev, "can't create sysfs hardware_version attribute err: %d\n", ret);
2703 			goto err_stop;
2704 		}
2705 
2706 		/*
2707 		 * The Dualshock 4 touchpad supports 2 touches and has a
2708 		 * resolution of 1920x942 (44.86 dots/mm).
2709 		 */
2710 		ret = sony_register_touchpad(sc, 2, 1920, 942, 0, 0, 0);
2711 		if (ret) {
2712 			hid_err(sc->hdev,
2713 			"Unable to initialize multi-touch slots: %d\n",
2714 			ret);
2715 			goto err_stop;
2716 		}
2717 
2718 		ret = sony_register_sensors(sc);
2719 		if (ret) {
2720 			hid_err(sc->hdev,
2721 			"Unable to initialize motion sensors: %d\n", ret);
2722 			goto err_stop;
2723 		}
2724 
2725 		if (sc->quirks & DUALSHOCK4_CONTROLLER_BT) {
2726 			sc->ds4_bt_poll_interval = DS4_BT_DEFAULT_POLL_INTERVAL_MS;
2727 			ret = device_create_file(&sc->hdev->dev, &dev_attr_bt_poll_interval);
2728 			if (ret)
2729 				hid_warn(sc->hdev,
2730 				 "can't create sysfs bt_poll_interval attribute err: %d\n",
2731 				 ret);
2732 		}
2733 
2734 		if (sc->quirks & DUALSHOCK4_DONGLE) {
2735 			INIT_WORK(&sc->hotplug_worker, dualshock4_calibration_work);
2736 			sc->hotplug_worker_initialized = 1;
2737 			sc->ds4_dongle_state = DONGLE_DISCONNECTED;
2738 		}
2739 
2740 		sony_init_output_report(sc, dualshock4_send_output_report);
2741 	} else if (sc->quirks & NSG_MRXU_REMOTE) {
2742 		/*
2743 		 * The NSG-MRxU touchpad supports 2 touches and has a
2744 		 * resolution of 1667x1868
2745 		 */
2746 		ret = sony_register_touchpad(sc, 2,
2747 			NSG_MRXU_MAX_X, NSG_MRXU_MAX_Y, 15, 15, 1);
2748 		if (ret) {
2749 			hid_err(sc->hdev,
2750 			"Unable to initialize multi-touch slots: %d\n",
2751 			ret);
2752 			goto err_stop;
2753 		}
2754 
2755 	} else if (sc->quirks & MOTION_CONTROLLER) {
2756 		sony_init_output_report(sc, motion_send_output_report);
2757 	} else {
2758 		ret = 0;
2759 	}
2760 
2761 	if (sc->quirks & SONY_LED_SUPPORT) {
2762 		ret = sony_leds_init(sc);
2763 		if (ret < 0)
2764 			goto err_stop;
2765 	}
2766 
2767 	if (sc->quirks & SONY_BATTERY_SUPPORT) {
2768 		ret = sony_battery_probe(sc, append_dev_id);
2769 		if (ret < 0)
2770 			goto err_stop;
2771 
2772 		/* Open the device to receive reports with battery info */
2773 		ret = hid_hw_open(hdev);
2774 		if (ret < 0) {
2775 			hid_err(hdev, "hw open failed\n");
2776 			goto err_stop;
2777 		}
2778 	}
2779 
2780 	if (sc->quirks & SONY_FF_SUPPORT) {
2781 		ret = sony_init_ff(sc);
2782 		if (ret < 0)
2783 			goto err_close;
2784 	}
2785 
2786 	return 0;
2787 err_close:
2788 	hid_hw_close(hdev);
2789 err_stop:
2790 	/* Piggy back on the default ds4_bt_ poll_interval to determine
2791 	 * if we need to remove the file as we don't know for sure if we
2792 	 * executed that logic.
2793 	 */
2794 	if (sc->ds4_bt_poll_interval)
2795 		device_remove_file(&sc->hdev->dev, &dev_attr_bt_poll_interval);
2796 	if (sc->fw_version)
2797 		device_remove_file(&sc->hdev->dev, &dev_attr_firmware_version);
2798 	if (sc->hw_version)
2799 		device_remove_file(&sc->hdev->dev, &dev_attr_hardware_version);
2800 	sony_cancel_work_sync(sc);
2801 	sony_remove_dev_list(sc);
2802 	sony_release_device_id(sc);
2803 	hid_hw_stop(hdev);
2804 	return ret;
2805 }
2806 
2807 static int sony_probe(struct hid_device *hdev, const struct hid_device_id *id)
2808 {
2809 	int ret;
2810 	unsigned long quirks = id->driver_data;
2811 	struct sony_sc *sc;
2812 	unsigned int connect_mask = HID_CONNECT_DEFAULT;
2813 
2814 	if (!strcmp(hdev->name, "FutureMax Dance Mat"))
2815 		quirks |= FUTUREMAX_DANCE_MAT;
2816 
2817 	if (!strcmp(hdev->name, "SHANWAN PS3 GamePad"))
2818 		quirks |= SHANWAN_GAMEPAD;
2819 
2820 	sc = devm_kzalloc(&hdev->dev, sizeof(*sc), GFP_KERNEL);
2821 	if (sc == NULL) {
2822 		hid_err(hdev, "can't alloc sony descriptor\n");
2823 		return -ENOMEM;
2824 	}
2825 
2826 	spin_lock_init(&sc->lock);
2827 
2828 	sc->quirks = quirks;
2829 	hid_set_drvdata(hdev, sc);
2830 	sc->hdev = hdev;
2831 
2832 	ret = hid_parse(hdev);
2833 	if (ret) {
2834 		hid_err(hdev, "parse failed\n");
2835 		return ret;
2836 	}
2837 
2838 	if (sc->quirks & VAIO_RDESC_CONSTANT)
2839 		connect_mask |= HID_CONNECT_HIDDEV_FORCE;
2840 	else if (sc->quirks & SIXAXIS_CONTROLLER)
2841 		connect_mask |= HID_CONNECT_HIDDEV_FORCE;
2842 
2843 	/* Patch the hw version on DS3/4 compatible devices, so applications can
2844 	 * distinguish between the default HID mappings and the mappings defined
2845 	 * by the Linux game controller spec. This is important for the SDL2
2846 	 * library, which has a game controller database, which uses device ids
2847 	 * in combination with version as a key.
2848 	 */
2849 	if (sc->quirks & (SIXAXIS_CONTROLLER | DUALSHOCK4_CONTROLLER))
2850 		hdev->version |= 0x8000;
2851 
2852 	ret = hid_hw_start(hdev, connect_mask);
2853 	if (ret) {
2854 		hid_err(hdev, "hw start failed\n");
2855 		return ret;
2856 	}
2857 
2858 	/* sony_input_configured can fail, but this doesn't result
2859 	 * in hid_hw_start failures (intended). Check whether
2860 	 * the HID layer claimed the device else fail.
2861 	 * We don't know the actual reason for the failure, most
2862 	 * likely it is due to EEXIST in case of double connection
2863 	 * of USB and Bluetooth, but could have been due to ENOMEM
2864 	 * or other reasons as well.
2865 	 */
2866 	if (!(hdev->claimed & HID_CLAIMED_INPUT)) {
2867 		hid_err(hdev, "failed to claim input\n");
2868 		return -ENODEV;
2869 	}
2870 
2871 	return ret;
2872 }
2873 
2874 static void sony_remove(struct hid_device *hdev)
2875 {
2876 	struct sony_sc *sc = hid_get_drvdata(hdev);
2877 
2878 	hid_hw_close(hdev);
2879 
2880 	if (sc->quirks & DUALSHOCK4_CONTROLLER_BT)
2881 		device_remove_file(&sc->hdev->dev, &dev_attr_bt_poll_interval);
2882 
2883 	if (sc->fw_version)
2884 		device_remove_file(&sc->hdev->dev, &dev_attr_firmware_version);
2885 
2886 	if (sc->hw_version)
2887 		device_remove_file(&sc->hdev->dev, &dev_attr_hardware_version);
2888 
2889 	sony_cancel_work_sync(sc);
2890 
2891 	sony_remove_dev_list(sc);
2892 
2893 	sony_release_device_id(sc);
2894 
2895 	hid_hw_stop(hdev);
2896 }
2897 
2898 #ifdef CONFIG_PM
2899 
2900 static int sony_suspend(struct hid_device *hdev, pm_message_t message)
2901 {
2902 #ifdef CONFIG_SONY_FF
2903 
2904 	/* On suspend stop any running force-feedback events */
2905 	if (SONY_FF_SUPPORT) {
2906 		struct sony_sc *sc = hid_get_drvdata(hdev);
2907 
2908 		sc->left = sc->right = 0;
2909 		sony_send_output_report(sc);
2910 	}
2911 
2912 #endif
2913 	return 0;
2914 }
2915 
2916 static int sony_resume(struct hid_device *hdev)
2917 {
2918 	struct sony_sc *sc = hid_get_drvdata(hdev);
2919 
2920 	/*
2921 	 * The Sixaxis and navigation controllers on USB need to be
2922 	 * reinitialized on resume or they won't behave properly.
2923 	 */
2924 	if ((sc->quirks & SIXAXIS_CONTROLLER_USB) ||
2925 		(sc->quirks & NAVIGATION_CONTROLLER_USB)) {
2926 		sixaxis_set_operational_usb(sc->hdev);
2927 		sc->defer_initialization = 1;
2928 	}
2929 
2930 	return 0;
2931 }
2932 
2933 #endif
2934 
2935 static const struct hid_device_id sony_devices[] = {
2936 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS3_CONTROLLER),
2937 		.driver_data = SIXAXIS_CONTROLLER_USB },
2938 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_NAVIGATION_CONTROLLER),
2939 		.driver_data = NAVIGATION_CONTROLLER_USB },
2940 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_NAVIGATION_CONTROLLER),
2941 		.driver_data = NAVIGATION_CONTROLLER_BT },
2942 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_MOTION_CONTROLLER),
2943 		.driver_data = MOTION_CONTROLLER_USB },
2944 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_MOTION_CONTROLLER),
2945 		.driver_data = MOTION_CONTROLLER_BT },
2946 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS3_CONTROLLER),
2947 		.driver_data = SIXAXIS_CONTROLLER_BT },
2948 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_VAIO_VGX_MOUSE),
2949 		.driver_data = VAIO_RDESC_CONSTANT },
2950 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_VAIO_VGP_MOUSE),
2951 		.driver_data = VAIO_RDESC_CONSTANT },
2952 	/*
2953 	 * Wired Buzz Controller. Reported as Sony Hub from its USB ID and as
2954 	 * Logitech joystick from the device descriptor.
2955 	 */
2956 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_BUZZ_CONTROLLER),
2957 		.driver_data = BUZZ_CONTROLLER },
2958 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_WIRELESS_BUZZ_CONTROLLER),
2959 		.driver_data = BUZZ_CONTROLLER },
2960 	/* PS3 BD Remote Control */
2961 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS3_BDREMOTE),
2962 		.driver_data = PS3REMOTE },
2963 	/* Logitech Harmony Adapter for PS3 */
2964 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_HARMONY_PS3),
2965 		.driver_data = PS3REMOTE },
2966 	/* SMK-Link PS3 BD Remote Control */
2967 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SMK, USB_DEVICE_ID_SMK_PS3_BDREMOTE),
2968 		.driver_data = PS3REMOTE },
2969 	/* Sony Dualshock 4 controllers for PS4 */
2970 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER),
2971 		.driver_data = DUALSHOCK4_CONTROLLER_USB },
2972 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER),
2973 		.driver_data = DUALSHOCK4_CONTROLLER_BT },
2974 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER_2),
2975 		.driver_data = DUALSHOCK4_CONTROLLER_USB },
2976 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER_2),
2977 		.driver_data = DUALSHOCK4_CONTROLLER_BT },
2978 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER_DONGLE),
2979 		.driver_data = DUALSHOCK4_DONGLE },
2980 	/* Nyko Core Controller for PS3 */
2981 	{ HID_USB_DEVICE(USB_VENDOR_ID_SINO_LITE, USB_DEVICE_ID_SINO_LITE_CONTROLLER),
2982 		.driver_data = SIXAXIS_CONTROLLER_USB | SINO_LITE_CONTROLLER },
2983 	/* SMK-Link NSG-MR5U Remote Control */
2984 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SMK, USB_DEVICE_ID_SMK_NSG_MR5U_REMOTE),
2985 		.driver_data = NSG_MR5U_REMOTE_BT },
2986 	/* SMK-Link NSG-MR7U Remote Control */
2987 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SMK, USB_DEVICE_ID_SMK_NSG_MR7U_REMOTE),
2988 		.driver_data = NSG_MR7U_REMOTE_BT },
2989 	{ }
2990 };
2991 MODULE_DEVICE_TABLE(hid, sony_devices);
2992 
2993 static struct hid_driver sony_driver = {
2994 	.name             = "sony",
2995 	.id_table         = sony_devices,
2996 	.input_mapping    = sony_mapping,
2997 	.input_configured = sony_input_configured,
2998 	.probe            = sony_probe,
2999 	.remove           = sony_remove,
3000 	.report_fixup     = sony_report_fixup,
3001 	.raw_event        = sony_raw_event,
3002 
3003 #ifdef CONFIG_PM
3004 	.suspend          = sony_suspend,
3005 	.resume	          = sony_resume,
3006 	.reset_resume     = sony_resume,
3007 #endif
3008 };
3009 
3010 static int __init sony_init(void)
3011 {
3012 	dbg_hid("Sony:%s\n", __func__);
3013 
3014 	return hid_register_driver(&sony_driver);
3015 }
3016 
3017 static void __exit sony_exit(void)
3018 {
3019 	dbg_hid("Sony:%s\n", __func__);
3020 
3021 	hid_unregister_driver(&sony_driver);
3022 	ida_destroy(&sony_device_id_allocator);
3023 }
3024 module_init(sony_init);
3025 module_exit(sony_exit);
3026 
3027 MODULE_LICENSE("GPL");
3028