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