xref: /linux/drivers/hid/hid-playstation.c (revision cd4f494ba535e848e2d299707d363de84e61a518)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  HID driver for Sony DualSense(TM) controller.
4  *
5  *  Copyright (c) 2020-2022 Sony Interactive Entertainment
6  */
7 
8 #include <linux/bitfield.h>
9 #include <linux/bits.h>
10 #include <linux/cleanup.h>
11 #include <linux/crc32.h>
12 #include <linux/device.h>
13 #include <linux/hid.h>
14 #include <linux/idr.h>
15 #include <linux/input/mt.h>
16 #include <linux/leds.h>
17 #include <linux/led-class-multicolor.h>
18 #include <linux/module.h>
19 
20 #include <linux/unaligned.h>
21 
22 #include "hid-ids.h"
23 
24 /* List of connected playstation devices. */
25 static DEFINE_MUTEX(ps_devices_lock);
26 static LIST_HEAD(ps_devices_list);
27 
28 static DEFINE_IDA(ps_player_id_allocator);
29 
30 #define HID_PLAYSTATION_VERSION_PATCH 0x8000
31 
32 enum PS_TYPE {
33 	PS_TYPE_PS4_DUALSHOCK4,
34 	PS_TYPE_PS5_DUALSENSE,
35 };
36 
37 /* Base class for playstation devices. */
38 struct ps_device {
39 	struct list_head list;
40 	struct hid_device *hdev;
41 	spinlock_t lock; /* Sync between event handler and workqueue */
42 
43 	u32 player_id;
44 
45 	struct power_supply_desc battery_desc;
46 	struct power_supply *battery;
47 	u8 battery_capacity;
48 	int battery_status;
49 
50 	const char *input_dev_name; /* Name of primary input device. */
51 	u8 mac_address[6]; /* Note: stored in little endian order. */
52 	u32 hw_version;
53 	u32 fw_version;
54 
55 	int (*parse_report)(struct ps_device *dev, struct hid_report *report, u8 *data, int size);
56 	void (*remove)(struct ps_device *dev);
57 };
58 
59 /* Calibration data for playstation motion sensors. */
60 struct ps_calibration_data {
61 	int abs_code;
62 	short bias;
63 	int sens_numer;
64 	int sens_denom;
65 };
66 
67 struct ps_led_info {
68 	const char *name;
69 	const char *color;
70 	int max_brightness;
71 	enum led_brightness (*brightness_get)(struct led_classdev *cdev);
72 	int (*brightness_set)(struct led_classdev *cdev, enum led_brightness);
73 	int (*blink_set)(struct led_classdev *led, unsigned long *on, unsigned long *off);
74 };
75 
76 /* Seed values for DualShock4 / DualSense CRC32 for different report types. */
77 #define PS_INPUT_CRC32_SEED	0xA1
78 #define PS_OUTPUT_CRC32_SEED	0xA2
79 #define PS_FEATURE_CRC32_SEED	0xA3
80 
81 #define DS_INPUT_REPORT_USB			0x01
82 #define DS_INPUT_REPORT_USB_SIZE		64
83 #define DS_INPUT_REPORT_BT			0x31
84 #define DS_INPUT_REPORT_BT_SIZE			78
85 #define DS_OUTPUT_REPORT_USB			0x02
86 #define DS_OUTPUT_REPORT_USB_SIZE		63
87 #define DS_OUTPUT_REPORT_BT			0x31
88 #define DS_OUTPUT_REPORT_BT_SIZE		78
89 
90 #define DS_FEATURE_REPORT_CALIBRATION		0x05
91 #define DS_FEATURE_REPORT_CALIBRATION_SIZE	41
92 #define DS_FEATURE_REPORT_PAIRING_INFO		0x09
93 #define DS_FEATURE_REPORT_PAIRING_INFO_SIZE	20
94 #define DS_FEATURE_REPORT_FIRMWARE_INFO		0x20
95 #define DS_FEATURE_REPORT_FIRMWARE_INFO_SIZE	64
96 
97 /* Button masks for DualSense input report. */
98 #define DS_BUTTONS0_HAT_SWITCH	GENMASK(3, 0)
99 #define DS_BUTTONS0_SQUARE	BIT(4)
100 #define DS_BUTTONS0_CROSS	BIT(5)
101 #define DS_BUTTONS0_CIRCLE	BIT(6)
102 #define DS_BUTTONS0_TRIANGLE	BIT(7)
103 #define DS_BUTTONS1_L1		BIT(0)
104 #define DS_BUTTONS1_R1		BIT(1)
105 #define DS_BUTTONS1_L2		BIT(2)
106 #define DS_BUTTONS1_R2		BIT(3)
107 #define DS_BUTTONS1_CREATE	BIT(4)
108 #define DS_BUTTONS1_OPTIONS	BIT(5)
109 #define DS_BUTTONS1_L3		BIT(6)
110 #define DS_BUTTONS1_R3		BIT(7)
111 #define DS_BUTTONS2_PS_HOME	BIT(0)
112 #define DS_BUTTONS2_TOUCHPAD	BIT(1)
113 #define DS_BUTTONS2_MIC_MUTE	BIT(2)
114 
115 /* DualSense Edge extra buttons in buttons[2], bits 4-7. */
116 #define DS_EDGE_BUTTONS_FN1		BIT(4)
117 #define DS_EDGE_BUTTONS_FN2		BIT(5)
118 #define DS_EDGE_BUTTONS_LEFT_PADDLE	BIT(6)
119 #define DS_EDGE_BUTTONS_RIGHT_PADDLE	BIT(7)
120 
121 /* Status fields of DualSense input report. */
122 #define DS_STATUS0_BATTERY_CAPACITY		GENMASK(3, 0)
123 #define DS_STATUS0_CHARGING			GENMASK(7, 4)
124 #define DS_STATUS1_HP_DETECT			BIT(0)
125 #define DS_STATUS1_MIC_DETECT			BIT(1)
126 #define DS_STATUS1_JACK_DETECT			(DS_STATUS1_HP_DETECT | DS_STATUS1_MIC_DETECT)
127 #define DS_STATUS1_MIC_MUTE			BIT(2)
128 
129 /* Feature version from DualSense Firmware Info report. */
130 #define DS_FEATURE_VERSION_MINOR		GENMASK(7, 0)
131 #define DS_FEATURE_VERSION_MAJOR		GENMASK(15, 8)
132 #define DS_FEATURE_VERSION(major, minor)	(FIELD_PREP(DS_FEATURE_VERSION_MAJOR, major) | \
133 						 FIELD_PREP(DS_FEATURE_VERSION_MINOR, minor))
134 /*
135  * Status of a DualSense touch point contact.
136  * Contact IDs, with highest bit set are 'inactive'
137  * and any associated data is then invalid.
138  */
139 #define DS_TOUCH_POINT_INACTIVE			BIT(7)
140 #define DS_TOUCH_POINT_X_LO			GENMASK(7, 0)
141 #define DS_TOUCH_POINT_X_HI			GENMASK(11, 8)
142 #define DS_TOUCH_POINT_X(hi, lo)		(FIELD_PREP(DS_TOUCH_POINT_X_HI, hi) | \
143 						 FIELD_PREP(DS_TOUCH_POINT_X_LO, lo))
144 #define DS_TOUCH_POINT_Y_LO			GENMASK(3, 0)
145 #define DS_TOUCH_POINT_Y_HI			GENMASK(11, 4)
146 #define DS_TOUCH_POINT_Y(hi, lo)		(FIELD_PREP(DS_TOUCH_POINT_Y_HI, hi) | \
147 						 FIELD_PREP(DS_TOUCH_POINT_Y_LO, lo))
148 
149  /* Magic value required in tag field of Bluetooth output report. */
150 #define DS_OUTPUT_TAG				0x10
151 #define DS_OUTPUT_SEQ_TAG			GENMASK(3, 0)
152 #define DS_OUTPUT_SEQ_NO			GENMASK(7, 4)
153 /* Flags for DualSense output report. */
154 #define DS_OUTPUT_VALID_FLAG0_COMPATIBLE_VIBRATION		BIT(0)
155 #define DS_OUTPUT_VALID_FLAG0_HAPTICS_SELECT			BIT(1)
156 #define DS_OUTPUT_VALID_FLAG0_SPEAKER_VOLUME_ENABLE		BIT(5)
157 #define DS_OUTPUT_VALID_FLAG0_MIC_VOLUME_ENABLE			BIT(6)
158 #define DS_OUTPUT_VALID_FLAG0_AUDIO_CONTROL_ENABLE		BIT(7)
159 #define DS_OUTPUT_VALID_FLAG1_MIC_MUTE_LED_CONTROL_ENABLE	BIT(0)
160 #define DS_OUTPUT_VALID_FLAG1_POWER_SAVE_CONTROL_ENABLE		BIT(1)
161 #define DS_OUTPUT_VALID_FLAG1_LIGHTBAR_CONTROL_ENABLE		BIT(2)
162 #define DS_OUTPUT_VALID_FLAG1_RELEASE_LEDS			BIT(3)
163 #define DS_OUTPUT_VALID_FLAG1_PLAYER_INDICATOR_CONTROL_ENABLE	BIT(4)
164 #define DS_OUTPUT_VALID_FLAG1_AUDIO_CONTROL2_ENABLE		BIT(7)
165 #define DS_OUTPUT_VALID_FLAG2_LIGHTBAR_SETUP_CONTROL_ENABLE	BIT(1)
166 #define DS_OUTPUT_VALID_FLAG2_COMPATIBLE_VIBRATION2		BIT(2)
167 #define DS_OUTPUT_AUDIO_FLAGS_OUTPUT_PATH_SEL			GENMASK(5, 4)
168 #define DS_OUTPUT_AUDIO_FLAGS2_SP_PREAMP_GAIN			GENMASK(2, 0)
169 #define DS_OUTPUT_POWER_SAVE_CONTROL_MIC_MUTE			BIT(4)
170 #define DS_OUTPUT_LIGHTBAR_SETUP_LIGHT_OUT			BIT(1)
171 
172 /* DualSense hardware limits */
173 #define DS_ACC_RES_PER_G	8192
174 #define DS_ACC_RANGE		(4 * DS_ACC_RES_PER_G)
175 #define DS_GYRO_RES_PER_DEG_S	1024
176 #define DS_GYRO_RANGE		(2048 * DS_GYRO_RES_PER_DEG_S)
177 #define DS_TOUCHPAD_WIDTH	1920
178 #define DS_TOUCHPAD_HEIGHT	1080
179 
180 struct dualsense {
181 	struct ps_device base;
182 	struct input_dev *gamepad;
183 	struct input_dev *sensors;
184 	struct input_dev *touchpad;
185 	struct input_dev *jack;
186 
187 	/* True if this is a DualSense Edge (product 0x0df2). */
188 	bool is_edge;
189 
190 	/* Update version is used as a feature/capability version. */
191 	u16 update_version;
192 
193 	/* Calibration data for accelerometer and gyroscope. */
194 	struct ps_calibration_data accel_calib_data[3];
195 	struct ps_calibration_data gyro_calib_data[3];
196 
197 	/* Timestamp for sensor data */
198 	bool sensor_timestamp_initialized;
199 	u32 prev_sensor_timestamp;
200 	u32 sensor_timestamp_us;
201 
202 	/* Compatible rumble state */
203 	bool use_vibration_v2;
204 	bool update_rumble;
205 	u8 motor_left;
206 	u8 motor_right;
207 
208 	/* RGB lightbar */
209 	struct led_classdev_mc lightbar;
210 	bool update_lightbar;
211 	u8 lightbar_red;
212 	u8 lightbar_green;
213 	u8 lightbar_blue;
214 
215 	/* Audio Jack plugged state */
216 	u8 plugged_state;
217 	u8 prev_plugged_state;
218 	bool prev_plugged_state_valid;
219 
220 	/* Microphone */
221 	bool update_mic_mute;
222 	bool mic_muted;
223 	bool last_btn_mic_state;
224 
225 	/* Player leds */
226 	bool update_player_leds;
227 	u8 player_leds_state;
228 	struct led_classdev player_leds[5];
229 
230 	struct work_struct output_worker;
231 	bool output_worker_initialized;
232 	void *output_report_dmabuf;
233 	u8 output_seq; /* Sequence number for output report. */
234 };
235 
236 struct dualsense_touch_point {
237 	u8 contact;
238 	u8 x_lo;
239 	u8 x_hi:4, y_lo:4;
240 	u8 y_hi;
241 } __packed;
242 static_assert(sizeof(struct dualsense_touch_point) == 4);
243 
244 /* Main DualSense input report excluding any BT/USB specific headers. */
245 struct dualsense_input_report {
246 	u8 x, y;
247 	u8 rx, ry;
248 	u8 z, rz;
249 	u8 seq_number;
250 	u8 buttons[4];
251 	u8 reserved[4];
252 
253 	/* Motion sensors */
254 	__le16 gyro[3]; /* x, y, z */
255 	__le16 accel[3]; /* x, y, z */
256 	__le32 sensor_timestamp;
257 	u8 reserved2;
258 
259 	/* Touchpad */
260 	struct dualsense_touch_point points[2];
261 
262 	u8 reserved3[12];
263 	u8 status[3];
264 	u8 reserved4[8];
265 } __packed;
266 /* Common input report size shared equals the size of the USB report minus 1 byte for ReportID. */
267 static_assert(sizeof(struct dualsense_input_report) == DS_INPUT_REPORT_USB_SIZE - 1);
268 
269 /* Common data between DualSense BT/USB main output report. */
270 struct dualsense_output_report_common {
271 	u8 valid_flag0;
272 	u8 valid_flag1;
273 
274 	/* For DualShock 4 compatibility mode. */
275 	u8 motor_right;
276 	u8 motor_left;
277 
278 	/* Audio controls */
279 	u8 headphone_volume;	/* 0x0 - 0x7f */
280 	u8 speaker_volume;	/* 0x0 - 0xff */
281 	u8 mic_volume;		/* 0x0 - 0x40 */
282 	u8 audio_control;
283 	u8 mute_button_led;
284 
285 	u8 power_save_control;
286 	u8 reserved2[27];
287 	u8 audio_control2;
288 
289 	/* LEDs and lightbar */
290 	u8 valid_flag2;
291 	u8 reserved3[2];
292 	u8 lightbar_setup;
293 	u8 led_brightness;
294 	u8 player_leds;
295 	u8 lightbar_red;
296 	u8 lightbar_green;
297 	u8 lightbar_blue;
298 } __packed;
299 static_assert(sizeof(struct dualsense_output_report_common) == 47);
300 
301 struct dualsense_output_report_bt {
302 	u8 report_id; /* 0x31 */
303 	u8 seq_tag;
304 	u8 tag;
305 	struct dualsense_output_report_common common;
306 	u8 reserved[24];
307 	__le32 crc32;
308 } __packed;
309 static_assert(sizeof(struct dualsense_output_report_bt) == DS_OUTPUT_REPORT_BT_SIZE);
310 
311 struct dualsense_output_report_usb {
312 	u8 report_id; /* 0x02 */
313 	struct dualsense_output_report_common common;
314 	u8 reserved[15];
315 } __packed;
316 static_assert(sizeof(struct dualsense_output_report_usb) == DS_OUTPUT_REPORT_USB_SIZE);
317 
318 /*
319  * The DualSense has a main output report used to control most features. It is
320  * largely the same between Bluetooth and USB except for different headers and CRC.
321  * This structure hide the differences between the two to simplify sending output reports.
322  */
323 struct dualsense_output_report {
324 	u8 *data; /* Start of data */
325 	u8 len; /* Size of output report */
326 
327 	/* Points to Bluetooth data payload in case for a Bluetooth report else NULL. */
328 	struct dualsense_output_report_bt *bt;
329 	/* Points to USB data payload in case for a USB report else NULL. */
330 	struct dualsense_output_report_usb *usb;
331 	/* Points to common section of report, so past any headers. */
332 	struct dualsense_output_report_common *common;
333 };
334 
335 #define DS4_INPUT_REPORT_USB			0x01
336 #define DS4_INPUT_REPORT_USB_SIZE		64
337 #define DS4_INPUT_REPORT_BT_MINIMAL		0x01
338 #define DS4_INPUT_REPORT_BT_MINIMAL_SIZE	10
339 #define DS4_INPUT_REPORT_BT			0x11
340 #define DS4_INPUT_REPORT_BT_SIZE		78
341 #define DS4_OUTPUT_REPORT_USB			0x05
342 #define DS4_OUTPUT_REPORT_USB_SIZE		32
343 #define DS4_OUTPUT_REPORT_BT			0x11
344 #define DS4_OUTPUT_REPORT_BT_SIZE		78
345 
346 #define DS4_FEATURE_REPORT_CALIBRATION		0x02
347 #define DS4_FEATURE_REPORT_CALIBRATION_SIZE	37
348 #define DS4_FEATURE_REPORT_CALIBRATION_BT	0x05
349 #define DS4_FEATURE_REPORT_CALIBRATION_BT_SIZE	41
350 #define DS4_FEATURE_REPORT_FIRMWARE_INFO	0xa3
351 #define DS4_FEATURE_REPORT_FIRMWARE_INFO_SIZE	49
352 #define DS4_FEATURE_REPORT_PAIRING_INFO		0x12
353 #define DS4_FEATURE_REPORT_PAIRING_INFO_SIZE	16
354 
355 /*
356  * Status of a DualShock4 touch point contact.
357  * Contact IDs, with highest bit set are 'inactive'
358  * and any associated data is then invalid.
359  */
360 #define DS4_TOUCH_POINT_INACTIVE	BIT(7)
361 #define DS4_TOUCH_POINT_X(hi, lo)	DS_TOUCH_POINT_X(hi, lo)
362 #define DS4_TOUCH_POINT_Y(hi, lo)	DS_TOUCH_POINT_Y(hi, lo)
363 
364 /* Status field of DualShock4 input report. */
365 #define DS4_STATUS0_BATTERY_CAPACITY	GENMASK(3, 0)
366 #define DS4_STATUS0_CABLE_STATE		BIT(4)
367 /* Battery status within batery_status field. */
368 #define DS4_BATTERY_STATUS_FULL		11
369 /* Status1 bit2 contains dongle connection state:
370  * 0 = connected
371  * 1 = disconnected
372  */
373 #define DS4_STATUS1_DONGLE_STATE	BIT(2)
374 
375 /* The lower 6 bits of hw_control of the Bluetooth main output report
376  * control the interval at which Dualshock 4 reports data:
377  * 0x00 - 1ms
378  * 0x01 - 1ms
379  * 0x02 - 2ms
380  * 0x3E - 62ms
381  * 0x3F - disabled
382  */
383 #define DS4_OUTPUT_HWCTL_BT_POLL_MASK	0x3F
384 /* Default to 4ms poll interval, which is same as USB (not adjustable). */
385 #define DS4_BT_DEFAULT_POLL_INTERVAL_MS	4
386 #define DS4_OUTPUT_HWCTL_CRC32		0x40
387 #define DS4_OUTPUT_HWCTL_HID		0x80
388 
389 /* Flags for DualShock4 output report. */
390 #define DS4_OUTPUT_VALID_FLAG0_MOTOR		0x01
391 #define DS4_OUTPUT_VALID_FLAG0_LED		0x02
392 #define DS4_OUTPUT_VALID_FLAG0_LED_BLINK	0x04
393 
394 /* DualShock4 hardware limits */
395 #define DS4_ACC_RES_PER_G	8192
396 #define DS4_ACC_RANGE		(4 * DS_ACC_RES_PER_G)
397 #define DS4_GYRO_RES_PER_DEG_S	1024
398 #define DS4_GYRO_RANGE		(2048 * DS_GYRO_RES_PER_DEG_S)
399 #define DS4_LIGHTBAR_MAX_BLINK	255 /* 255 centiseconds */
400 #define DS4_TOUCHPAD_WIDTH	1920
401 #define DS4_TOUCHPAD_HEIGHT	942
402 
403 enum dualshock4_dongle_state {
404 	DONGLE_DISCONNECTED,
405 	DONGLE_CALIBRATING,
406 	DONGLE_CONNECTED,
407 	DONGLE_DISABLED
408 };
409 
410 struct dualshock4 {
411 	struct ps_device base;
412 	struct input_dev *gamepad;
413 	struct input_dev *sensors;
414 	struct input_dev *touchpad;
415 
416 	/* Calibration data for accelerometer and gyroscope. */
417 	struct ps_calibration_data accel_calib_data[3];
418 	struct ps_calibration_data gyro_calib_data[3];
419 
420 	/* Only used on dongle to track state transitions. */
421 	enum dualshock4_dongle_state dongle_state;
422 	/* Used during calibration. */
423 	struct work_struct dongle_hotplug_worker;
424 
425 	/* Timestamp for sensor data */
426 	bool sensor_timestamp_initialized;
427 	u32 prev_sensor_timestamp;
428 	u32 sensor_timestamp_us;
429 
430 	/* Bluetooth poll interval */
431 	bool update_bt_poll_interval;
432 	u8 bt_poll_interval;
433 
434 	bool update_rumble;
435 	u8 motor_left;
436 	u8 motor_right;
437 
438 	/* Lightbar leds */
439 	bool update_lightbar;
440 	bool update_lightbar_blink;
441 	bool lightbar_enabled; /* For use by global LED control. */
442 	u8 lightbar_red;
443 	u8 lightbar_green;
444 	u8 lightbar_blue;
445 	u8 lightbar_blink_on; /* In increments of 10ms. */
446 	u8 lightbar_blink_off; /* In increments of 10ms. */
447 	struct led_classdev lightbar_leds[4];
448 
449 	struct work_struct output_worker;
450 	bool output_worker_initialized;
451 	void *output_report_dmabuf;
452 };
453 
454 struct dualshock4_touch_point {
455 	u8 contact;
456 	u8 x_lo;
457 	u8 x_hi:4, y_lo:4;
458 	u8 y_hi;
459 } __packed;
460 static_assert(sizeof(struct dualshock4_touch_point) == 4);
461 
462 struct dualshock4_touch_report {
463 	u8 timestamp;
464 	struct dualshock4_touch_point points[2];
465 } __packed;
466 static_assert(sizeof(struct dualshock4_touch_report) == 9);
467 
468 /* Main DualShock4 input report excluding any BT/USB specific headers. */
469 struct dualshock4_input_report_common {
470 	u8 x, y;
471 	u8 rx, ry;
472 	u8 buttons[3];
473 	u8 z, rz;
474 
475 	/* Motion sensors */
476 	__le16 sensor_timestamp;
477 	u8 sensor_temperature;
478 	__le16 gyro[3]; /* x, y, z */
479 	__le16 accel[3]; /* x, y, z */
480 	u8 reserved2[5];
481 
482 	u8 status[2];
483 	u8 reserved3;
484 } __packed;
485 static_assert(sizeof(struct dualshock4_input_report_common) == 32);
486 
487 struct dualshock4_input_report_usb {
488 	u8 report_id; /* 0x01 */
489 	struct dualshock4_input_report_common common;
490 	u8 num_touch_reports;
491 	struct dualshock4_touch_report touch_reports[3];
492 	u8 reserved[3];
493 } __packed;
494 static_assert(sizeof(struct dualshock4_input_report_usb) == DS4_INPUT_REPORT_USB_SIZE);
495 
496 struct dualshock4_input_report_bt {
497 	u8 report_id; /* 0x11 */
498 	u8 reserved[2];
499 	struct dualshock4_input_report_common common;
500 	u8 num_touch_reports;
501 	struct dualshock4_touch_report touch_reports[4]; /* BT has 4 compared to 3 for USB */
502 	u8 reserved2[2];
503 	__le32 crc32;
504 } __packed;
505 static_assert(sizeof(struct dualshock4_input_report_bt) == DS4_INPUT_REPORT_BT_SIZE);
506 
507 /* Common data between Bluetooth and USB DualShock4 output reports. */
508 struct dualshock4_output_report_common {
509 	u8 valid_flag0;
510 	u8 valid_flag1;
511 
512 	u8 reserved;
513 
514 	u8 motor_right;
515 	u8 motor_left;
516 
517 	u8 lightbar_red;
518 	u8 lightbar_green;
519 	u8 lightbar_blue;
520 	u8 lightbar_blink_on;
521 	u8 lightbar_blink_off;
522 } __packed;
523 
524 struct dualshock4_output_report_usb {
525 	u8 report_id; /* 0x5 */
526 	struct dualshock4_output_report_common common;
527 	u8 reserved[21];
528 } __packed;
529 static_assert(sizeof(struct dualshock4_output_report_usb) == DS4_OUTPUT_REPORT_USB_SIZE);
530 
531 struct dualshock4_output_report_bt {
532 	u8 report_id; /* 0x11 */
533 	u8 hw_control;
534 	u8 audio_control;
535 	struct dualshock4_output_report_common common;
536 	u8 reserved[61];
537 	__le32 crc32;
538 } __packed;
539 static_assert(sizeof(struct dualshock4_output_report_bt) == DS4_OUTPUT_REPORT_BT_SIZE);
540 
541 /*
542  * The DualShock4 has a main output report used to control most features. It is
543  * largely the same between Bluetooth and USB except for different headers and CRC.
544  * This structure hide the differences between the two to simplify sending output reports.
545  */
546 struct dualshock4_output_report {
547 	u8 *data; /* Start of data */
548 	u8 len; /* Size of output report */
549 
550 	/* Points to Bluetooth data payload in case for a Bluetooth report else NULL. */
551 	struct dualshock4_output_report_bt *bt;
552 	/* Points to USB data payload in case for a USB report else NULL. */
553 	struct dualshock4_output_report_usb *usb;
554 	/* Points to common section of report, so past any headers. */
555 	struct dualshock4_output_report_common *common;
556 };
557 
558 /*
559  * Common gamepad buttons across DualShock 3 / 4 and DualSense.
560  * Note: for device with a touchpad, touchpad button is not included
561  *        as it will be part of the touchpad device.
562  */
563 static const int ps_gamepad_buttons[] = {
564 	BTN_WEST, /* Square */
565 	BTN_NORTH, /* Triangle */
566 	BTN_EAST, /* Circle */
567 	BTN_SOUTH, /* Cross */
568 	BTN_TL, /* L1 */
569 	BTN_TR, /* R1 */
570 	BTN_TL2, /* L2 */
571 	BTN_TR2, /* R2 */
572 	BTN_SELECT, /* Create (PS5) / Share (PS4) */
573 	BTN_START, /* Option */
574 	BTN_THUMBL, /* L3 */
575 	BTN_THUMBR, /* R3 */
576 	BTN_MODE, /* PS Home */
577 };
578 
579 static const struct {int x; int y; } ps_gamepad_hat_mapping[] = {
580 	{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1},
581 	{0, 0},
582 };
583 
584 static int dualshock4_get_calibration_data(struct dualshock4 *ds4);
585 static inline void dualsense_schedule_work(struct dualsense *ds);
586 static inline void dualshock4_schedule_work(struct dualshock4 *ds4);
587 static void dualsense_set_lightbar(struct dualsense *ds, u8 red, u8 green, u8 blue);
588 static void dualshock4_set_default_lightbar_colors(struct dualshock4 *ds4);
589 
590 /*
591  * Add a new ps_device to ps_devices if it doesn't exist.
592  * Return error on duplicate device, which can happen if the same
593  * device is connected using both Bluetooth and USB.
594  */
595 static int ps_devices_list_add(struct ps_device *dev)
596 {
597 	struct ps_device *entry;
598 
599 	guard(mutex)(&ps_devices_lock);
600 
601 	list_for_each_entry(entry, &ps_devices_list, list) {
602 		if (!memcmp(entry->mac_address, dev->mac_address, sizeof(dev->mac_address))) {
603 			hid_err(dev->hdev, "Duplicate device found for MAC address %pMR.\n",
604 				dev->mac_address);
605 			return -EEXIST;
606 		}
607 	}
608 
609 	list_add_tail(&dev->list, &ps_devices_list);
610 	return 0;
611 }
612 
613 static int ps_devices_list_remove(struct ps_device *dev)
614 {
615 	guard(mutex)(&ps_devices_lock);
616 
617 	list_del(&dev->list);
618 	return 0;
619 }
620 
621 static int ps_device_set_player_id(struct ps_device *dev)
622 {
623 	int ret = ida_alloc(&ps_player_id_allocator, GFP_KERNEL);
624 
625 	if (ret < 0)
626 		return ret;
627 
628 	dev->player_id = ret;
629 	return 0;
630 }
631 
632 static void ps_device_release_player_id(struct ps_device *dev)
633 {
634 	ida_free(&ps_player_id_allocator, dev->player_id);
635 
636 	dev->player_id = U32_MAX;
637 }
638 
639 static struct input_dev *ps_allocate_input_dev(struct hid_device *hdev,
640 					       const char *name_suffix)
641 {
642 	struct input_dev *input_dev;
643 
644 	input_dev = devm_input_allocate_device(&hdev->dev);
645 	if (!input_dev)
646 		return ERR_PTR(-ENOMEM);
647 
648 	input_dev->id.bustype = hdev->bus;
649 	input_dev->id.vendor = hdev->vendor;
650 	input_dev->id.product = hdev->product;
651 	input_dev->id.version = hdev->version;
652 	input_dev->uniq = hdev->uniq;
653 
654 	if (name_suffix) {
655 		input_dev->name = devm_kasprintf(&hdev->dev, GFP_KERNEL, "%s %s",
656 						 hdev->name, name_suffix);
657 		if (!input_dev->name)
658 			return ERR_PTR(-ENOMEM);
659 	} else {
660 		input_dev->name = hdev->name;
661 	}
662 
663 	input_set_drvdata(input_dev, hdev);
664 
665 	return input_dev;
666 }
667 
668 static enum power_supply_property ps_power_supply_props[] = {
669 	POWER_SUPPLY_PROP_STATUS,
670 	POWER_SUPPLY_PROP_PRESENT,
671 	POWER_SUPPLY_PROP_CAPACITY,
672 	POWER_SUPPLY_PROP_SCOPE,
673 };
674 
675 static int ps_battery_get_property(struct power_supply *psy,
676 				   enum power_supply_property psp,
677 				   union power_supply_propval *val)
678 {
679 	struct ps_device *dev = power_supply_get_drvdata(psy);
680 	u8 battery_capacity;
681 	int battery_status;
682 	int ret = 0;
683 
684 	scoped_guard(spinlock_irqsave, &dev->lock) {
685 		battery_capacity = dev->battery_capacity;
686 		battery_status = dev->battery_status;
687 	}
688 
689 	switch (psp) {
690 	case POWER_SUPPLY_PROP_STATUS:
691 		val->intval = battery_status;
692 		break;
693 	case POWER_SUPPLY_PROP_PRESENT:
694 		val->intval = 1;
695 		break;
696 	case POWER_SUPPLY_PROP_CAPACITY:
697 		val->intval = battery_capacity;
698 		break;
699 	case POWER_SUPPLY_PROP_SCOPE:
700 		val->intval = POWER_SUPPLY_SCOPE_DEVICE;
701 		break;
702 	default:
703 		ret = -EINVAL;
704 		break;
705 	}
706 
707 	return ret;
708 }
709 
710 static int ps_device_register_battery(struct ps_device *dev)
711 {
712 	struct power_supply *battery;
713 	struct power_supply_config battery_cfg = { .drv_data = dev };
714 	int ret;
715 
716 	dev->battery_desc.type = POWER_SUPPLY_TYPE_BATTERY;
717 	dev->battery_desc.properties = ps_power_supply_props;
718 	dev->battery_desc.num_properties = ARRAY_SIZE(ps_power_supply_props);
719 	dev->battery_desc.get_property = ps_battery_get_property;
720 	dev->battery_desc.name = devm_kasprintf(&dev->hdev->dev, GFP_KERNEL,
721 						"ps-controller-battery-%pMR", dev->mac_address);
722 	if (!dev->battery_desc.name)
723 		return -ENOMEM;
724 
725 	battery = devm_power_supply_register(&dev->hdev->dev, &dev->battery_desc, &battery_cfg);
726 	if (IS_ERR(battery)) {
727 		ret = PTR_ERR(battery);
728 		hid_err(dev->hdev, "Unable to register battery device: %d\n", ret);
729 		return ret;
730 	}
731 	dev->battery = battery;
732 
733 	ret = power_supply_powers(dev->battery, &dev->hdev->dev);
734 	if (ret) {
735 		hid_err(dev->hdev, "Unable to activate battery device: %d\n", ret);
736 		return ret;
737 	}
738 
739 	return 0;
740 }
741 
742 /* Compute crc32 of HID data and compare against expected CRC. */
743 static bool ps_check_crc32(u8 seed, u8 *data, size_t len, u32 report_crc)
744 {
745 	u32 crc;
746 
747 	crc = crc32_le(0xFFFFFFFF, &seed, 1);
748 	crc = ~crc32_le(crc, data, len);
749 
750 	return crc == report_crc;
751 }
752 
753 static struct input_dev *
754 ps_gamepad_create(struct hid_device *hdev,
755 		  int (*play_effect)(struct input_dev *, void *, struct ff_effect *))
756 {
757 	struct input_dev *gamepad;
758 	unsigned int i;
759 	int ret;
760 
761 	gamepad = ps_allocate_input_dev(hdev, NULL);
762 	if (IS_ERR(gamepad))
763 		return ERR_CAST(gamepad);
764 
765 	/* Set initial resting state for joysticks to 128 (center) */
766 	input_set_abs_params(gamepad, ABS_X, 0, 255, 0, 0);
767 	gamepad->absinfo[ABS_X].value = 128;
768 	input_set_abs_params(gamepad, ABS_Y, 0, 255, 0, 0);
769 	gamepad->absinfo[ABS_Y].value = 128;
770 	input_set_abs_params(gamepad, ABS_Z, 0, 255, 0, 0);
771 	input_set_abs_params(gamepad, ABS_RX, 0, 255, 0, 0);
772 	gamepad->absinfo[ABS_RX].value = 128;
773 	input_set_abs_params(gamepad, ABS_RY, 0, 255, 0, 0);
774 	gamepad->absinfo[ABS_RY].value = 128;
775 	input_set_abs_params(gamepad, ABS_RZ, 0, 255, 0, 0);
776 
777 	input_set_abs_params(gamepad, ABS_HAT0X, -1, 1, 0, 0);
778 	input_set_abs_params(gamepad, ABS_HAT0Y, -1, 1, 0, 0);
779 
780 	for (i = 0; i < ARRAY_SIZE(ps_gamepad_buttons); i++)
781 		input_set_capability(gamepad, EV_KEY, ps_gamepad_buttons[i]);
782 
783 #if IS_ENABLED(CONFIG_PLAYSTATION_FF)
784 	if (play_effect) {
785 		input_set_capability(gamepad, EV_FF, FF_RUMBLE);
786 		ret = input_ff_create_memless(gamepad, NULL, play_effect);
787 		if (ret)
788 			return ERR_PTR(ret);
789 	}
790 #endif
791 
792 	ret = input_register_device(gamepad);
793 	if (ret)
794 		return ERR_PTR(ret);
795 
796 	return gamepad;
797 }
798 
799 static int ps_get_report(struct hid_device *hdev, u8 report_id, u8 *buf,
800 			 size_t size, bool check_crc)
801 {
802 	int ret;
803 
804 	ret = hid_hw_raw_request(hdev, report_id, buf, size, HID_FEATURE_REPORT,
805 				 HID_REQ_GET_REPORT);
806 	if (ret < 0) {
807 		hid_err(hdev, "Failed to retrieve feature with reportID %d: %d\n", report_id, ret);
808 		return ret;
809 	}
810 
811 	if (ret != size) {
812 		hid_err(hdev, "Invalid byte count transferred, expected %zu got %d\n", size, ret);
813 		return -EINVAL;
814 	}
815 
816 	if (buf[0] != report_id) {
817 		hid_err(hdev, "Invalid reportID received, expected %d got %d\n", report_id, buf[0]);
818 		return -EINVAL;
819 	}
820 
821 	if (hdev->bus == BUS_BLUETOOTH && check_crc) {
822 		/* Last 4 bytes contains crc32. */
823 		u8 crc_offset = size - 4;
824 		u32 report_crc = get_unaligned_le32(&buf[crc_offset]);
825 
826 		if (!ps_check_crc32(PS_FEATURE_CRC32_SEED, buf, crc_offset, report_crc)) {
827 			hid_err(hdev, "CRC check failed for reportID=%d\n", report_id);
828 			return -EILSEQ;
829 		}
830 	}
831 
832 	return 0;
833 }
834 
835 static int ps_led_register(struct ps_device *ps_dev, struct led_classdev *led,
836 			   const struct ps_led_info *led_info)
837 {
838 	int ret;
839 
840 	if (led_info->name) {
841 		led->name = devm_kasprintf(&ps_dev->hdev->dev, GFP_KERNEL, "%s:%s:%s",
842 					   ps_dev->input_dev_name, led_info->color,
843 					   led_info->name);
844 	} else {
845 		/* Backwards compatible mode for hid-sony, but not compliant
846 		 * with LED class spec.
847 		 */
848 		led->name = devm_kasprintf(&ps_dev->hdev->dev, GFP_KERNEL, "%s:%s",
849 					   ps_dev->input_dev_name, led_info->color);
850 	}
851 
852 	if (!led->name)
853 		return -ENOMEM;
854 
855 	led->brightness = 0;
856 	led->max_brightness = led_info->max_brightness;
857 	led->flags = LED_CORE_SUSPENDRESUME;
858 	led->brightness_get = led_info->brightness_get;
859 	led->brightness_set_blocking = led_info->brightness_set;
860 	led->blink_set = led_info->blink_set;
861 
862 	ret = devm_led_classdev_register(&ps_dev->hdev->dev, led);
863 	if (ret) {
864 		hid_err(ps_dev->hdev, "Failed to register LED %s: %d\n", led_info->name, ret);
865 		return ret;
866 	}
867 
868 	return 0;
869 }
870 
871 /* Register a DualSense/DualShock4 RGB lightbar represented by a multicolor LED. */
872 static int ps_lightbar_register(struct ps_device *ps_dev, struct led_classdev_mc *lightbar_mc_dev,
873 				int (*brightness_set)(struct led_classdev *, enum led_brightness))
874 {
875 	struct hid_device *hdev = ps_dev->hdev;
876 	struct mc_subled *mc_led_info;
877 	struct led_classdev *led_cdev;
878 	int ret;
879 
880 	mc_led_info = devm_kmalloc_array(&hdev->dev, 3, sizeof(*mc_led_info),
881 					 GFP_KERNEL | __GFP_ZERO);
882 	if (!mc_led_info)
883 		return -ENOMEM;
884 
885 	mc_led_info[0].color_index = LED_COLOR_ID_RED;
886 	mc_led_info[1].color_index = LED_COLOR_ID_GREEN;
887 	mc_led_info[2].color_index = LED_COLOR_ID_BLUE;
888 
889 	lightbar_mc_dev->subled_info = mc_led_info;
890 	lightbar_mc_dev->num_colors = 3;
891 
892 	led_cdev = &lightbar_mc_dev->led_cdev;
893 	led_cdev->name = devm_kasprintf(&hdev->dev, GFP_KERNEL, "%s:rgb:indicator",
894 					ps_dev->input_dev_name);
895 	if (!led_cdev->name)
896 		return -ENOMEM;
897 	led_cdev->brightness = 255;
898 	led_cdev->max_brightness = 255;
899 	led_cdev->brightness_set_blocking = brightness_set;
900 
901 	ret = devm_led_classdev_multicolor_register(&hdev->dev, lightbar_mc_dev);
902 	if (ret < 0) {
903 		hid_err(hdev, "Cannot register multicolor LED device\n");
904 		return ret;
905 	}
906 
907 	return 0;
908 }
909 
910 static struct input_dev *ps_sensors_create(struct hid_device *hdev, int accel_range,
911 					   int accel_res, int gyro_range, int gyro_res)
912 {
913 	struct input_dev *sensors;
914 	int ret;
915 
916 	sensors = ps_allocate_input_dev(hdev, "Motion Sensors");
917 	if (IS_ERR(sensors))
918 		return ERR_CAST(sensors);
919 
920 	__set_bit(INPUT_PROP_ACCELEROMETER, sensors->propbit);
921 	__set_bit(EV_MSC, sensors->evbit);
922 	__set_bit(MSC_TIMESTAMP, sensors->mscbit);
923 
924 	/* Accelerometer */
925 	input_set_abs_params(sensors, ABS_X, -accel_range, accel_range, 16, 0);
926 	input_set_abs_params(sensors, ABS_Y, -accel_range, accel_range, 16, 0);
927 	input_set_abs_params(sensors, ABS_Z, -accel_range, accel_range, 16, 0);
928 	input_abs_set_res(sensors, ABS_X, accel_res);
929 	input_abs_set_res(sensors, ABS_Y, accel_res);
930 	input_abs_set_res(sensors, ABS_Z, accel_res);
931 
932 	/* Gyroscope */
933 	input_set_abs_params(sensors, ABS_RX, -gyro_range, gyro_range, 16, 0);
934 	input_set_abs_params(sensors, ABS_RY, -gyro_range, gyro_range, 16, 0);
935 	input_set_abs_params(sensors, ABS_RZ, -gyro_range, gyro_range, 16, 0);
936 	input_abs_set_res(sensors, ABS_RX, gyro_res);
937 	input_abs_set_res(sensors, ABS_RY, gyro_res);
938 	input_abs_set_res(sensors, ABS_RZ, gyro_res);
939 
940 	ret = input_register_device(sensors);
941 	if (ret)
942 		return ERR_PTR(ret);
943 
944 	return sensors;
945 }
946 
947 static struct input_dev *ps_touchpad_create(struct hid_device *hdev, int width,
948 					    int height, unsigned int num_contacts)
949 {
950 	struct input_dev *touchpad;
951 	int ret;
952 
953 	touchpad = ps_allocate_input_dev(hdev, "Touchpad");
954 	if (IS_ERR(touchpad))
955 		return ERR_CAST(touchpad);
956 
957 	/* Map button underneath touchpad to BTN_LEFT. */
958 	input_set_capability(touchpad, EV_KEY, BTN_LEFT);
959 	__set_bit(INPUT_PROP_BUTTONPAD, touchpad->propbit);
960 
961 	input_set_abs_params(touchpad, ABS_MT_POSITION_X, 0, width - 1, 0, 0);
962 	input_set_abs_params(touchpad, ABS_MT_POSITION_Y, 0, height - 1, 0, 0);
963 
964 	ret = input_mt_init_slots(touchpad, num_contacts, INPUT_MT_POINTER);
965 	if (ret)
966 		return ERR_PTR(ret);
967 
968 	ret = input_register_device(touchpad);
969 	if (ret)
970 		return ERR_PTR(ret);
971 
972 	return touchpad;
973 }
974 
975 static struct input_dev *ps_headset_jack_create(struct hid_device *hdev)
976 {
977 	struct input_dev *jack;
978 	int ret;
979 
980 	jack = ps_allocate_input_dev(hdev, "Headset Jack");
981 	if (IS_ERR(jack))
982 		return ERR_CAST(jack);
983 
984 	input_set_capability(jack, EV_SW, SW_HEADPHONE_INSERT);
985 	input_set_capability(jack, EV_SW, SW_MICROPHONE_INSERT);
986 
987 	ret = input_register_device(jack);
988 	if (ret)
989 		return ERR_PTR(ret);
990 
991 	return jack;
992 }
993 
994 static ssize_t firmware_version_show(struct device *dev,
995 				     struct device_attribute *attr, char *buf)
996 {
997 	struct hid_device *hdev = to_hid_device(dev);
998 	struct ps_device *ps_dev = hid_get_drvdata(hdev);
999 
1000 	return sysfs_emit(buf, "0x%08x\n", ps_dev->fw_version);
1001 }
1002 
1003 static DEVICE_ATTR_RO(firmware_version);
1004 
1005 static ssize_t hardware_version_show(struct device *dev,
1006 				     struct device_attribute *attr, char *buf)
1007 {
1008 	struct hid_device *hdev = to_hid_device(dev);
1009 	struct ps_device *ps_dev = hid_get_drvdata(hdev);
1010 
1011 	return sysfs_emit(buf, "0x%08x\n", ps_dev->hw_version);
1012 }
1013 
1014 static DEVICE_ATTR_RO(hardware_version);
1015 
1016 static struct attribute *ps_device_attrs[] = {
1017 	&dev_attr_firmware_version.attr,
1018 	&dev_attr_hardware_version.attr,
1019 	NULL
1020 };
1021 ATTRIBUTE_GROUPS(ps_device);
1022 
1023 static int dualsense_get_calibration_data(struct dualsense *ds)
1024 {
1025 	struct hid_device *hdev = ds->base.hdev;
1026 	short gyro_pitch_bias, gyro_pitch_plus, gyro_pitch_minus;
1027 	short gyro_yaw_bias, gyro_yaw_plus, gyro_yaw_minus;
1028 	short gyro_roll_bias, gyro_roll_plus, gyro_roll_minus;
1029 	short gyro_speed_plus, gyro_speed_minus;
1030 	short acc_x_plus, acc_x_minus;
1031 	short acc_y_plus, acc_y_minus;
1032 	short acc_z_plus, acc_z_minus;
1033 	int speed_2x;
1034 	int range_2g;
1035 	int ret = 0;
1036 	int i;
1037 	u8 *buf;
1038 
1039 	buf = kzalloc(DS_FEATURE_REPORT_CALIBRATION_SIZE, GFP_KERNEL);
1040 	if (!buf)
1041 		return -ENOMEM;
1042 
1043 	ret = ps_get_report(ds->base.hdev, DS_FEATURE_REPORT_CALIBRATION, buf,
1044 			    DS_FEATURE_REPORT_CALIBRATION_SIZE, true);
1045 	if (ret) {
1046 		hid_err(ds->base.hdev, "Failed to retrieve DualSense calibration info: %d\n", ret);
1047 		goto err_free;
1048 	}
1049 
1050 	gyro_pitch_bias  = get_unaligned_le16(&buf[1]);
1051 	gyro_yaw_bias    = get_unaligned_le16(&buf[3]);
1052 	gyro_roll_bias   = get_unaligned_le16(&buf[5]);
1053 	gyro_pitch_plus  = get_unaligned_le16(&buf[7]);
1054 	gyro_pitch_minus = get_unaligned_le16(&buf[9]);
1055 	gyro_yaw_plus    = get_unaligned_le16(&buf[11]);
1056 	gyro_yaw_minus   = get_unaligned_le16(&buf[13]);
1057 	gyro_roll_plus   = get_unaligned_le16(&buf[15]);
1058 	gyro_roll_minus  = get_unaligned_le16(&buf[17]);
1059 	gyro_speed_plus  = get_unaligned_le16(&buf[19]);
1060 	gyro_speed_minus = get_unaligned_le16(&buf[21]);
1061 	acc_x_plus       = get_unaligned_le16(&buf[23]);
1062 	acc_x_minus      = get_unaligned_le16(&buf[25]);
1063 	acc_y_plus       = get_unaligned_le16(&buf[27]);
1064 	acc_y_minus      = get_unaligned_le16(&buf[29]);
1065 	acc_z_plus       = get_unaligned_le16(&buf[31]);
1066 	acc_z_minus      = get_unaligned_le16(&buf[33]);
1067 
1068 	/*
1069 	 * Set gyroscope calibration and normalization parameters.
1070 	 * Data values will be normalized to 1/DS_GYRO_RES_PER_DEG_S degree/s.
1071 	 */
1072 	speed_2x = (gyro_speed_plus + gyro_speed_minus);
1073 	ds->gyro_calib_data[0].abs_code = ABS_RX;
1074 	ds->gyro_calib_data[0].bias = 0;
1075 	ds->gyro_calib_data[0].sens_numer = speed_2x * DS_GYRO_RES_PER_DEG_S;
1076 	ds->gyro_calib_data[0].sens_denom = abs(gyro_pitch_plus - gyro_pitch_bias) +
1077 			abs(gyro_pitch_minus - gyro_pitch_bias);
1078 
1079 	ds->gyro_calib_data[1].abs_code = ABS_RY;
1080 	ds->gyro_calib_data[1].bias = 0;
1081 	ds->gyro_calib_data[1].sens_numer = speed_2x * DS_GYRO_RES_PER_DEG_S;
1082 	ds->gyro_calib_data[1].sens_denom = abs(gyro_yaw_plus - gyro_yaw_bias) +
1083 			abs(gyro_yaw_minus - gyro_yaw_bias);
1084 
1085 	ds->gyro_calib_data[2].abs_code = ABS_RZ;
1086 	ds->gyro_calib_data[2].bias = 0;
1087 	ds->gyro_calib_data[2].sens_numer = speed_2x * DS_GYRO_RES_PER_DEG_S;
1088 	ds->gyro_calib_data[2].sens_denom = abs(gyro_roll_plus - gyro_roll_bias) +
1089 			abs(gyro_roll_minus - gyro_roll_bias);
1090 
1091 	/*
1092 	 * Sanity check gyro calibration data. This is needed to prevent crashes
1093 	 * during report handling of virtual, clone or broken devices not implementing
1094 	 * calibration data properly.
1095 	 */
1096 	for (i = 0; i < ARRAY_SIZE(ds->gyro_calib_data); i++) {
1097 		if (ds->gyro_calib_data[i].sens_denom == 0) {
1098 			hid_warn(hdev,
1099 				 "Invalid gyro calibration data for axis (%d), disabling calibration.",
1100 				 ds->gyro_calib_data[i].abs_code);
1101 			ds->gyro_calib_data[i].bias = 0;
1102 			ds->gyro_calib_data[i].sens_numer = DS_GYRO_RANGE;
1103 			ds->gyro_calib_data[i].sens_denom = S16_MAX;
1104 		}
1105 	}
1106 
1107 	/*
1108 	 * Set accelerometer calibration and normalization parameters.
1109 	 * Data values will be normalized to 1/DS_ACC_RES_PER_G g.
1110 	 */
1111 	range_2g = acc_x_plus - acc_x_minus;
1112 	ds->accel_calib_data[0].abs_code = ABS_X;
1113 	ds->accel_calib_data[0].bias = acc_x_plus - range_2g / 2;
1114 	ds->accel_calib_data[0].sens_numer = 2 * DS_ACC_RES_PER_G;
1115 	ds->accel_calib_data[0].sens_denom = range_2g;
1116 
1117 	range_2g = acc_y_plus - acc_y_minus;
1118 	ds->accel_calib_data[1].abs_code = ABS_Y;
1119 	ds->accel_calib_data[1].bias = acc_y_plus - range_2g / 2;
1120 	ds->accel_calib_data[1].sens_numer = 2 * DS_ACC_RES_PER_G;
1121 	ds->accel_calib_data[1].sens_denom = range_2g;
1122 
1123 	range_2g = acc_z_plus - acc_z_minus;
1124 	ds->accel_calib_data[2].abs_code = ABS_Z;
1125 	ds->accel_calib_data[2].bias = acc_z_plus - range_2g / 2;
1126 	ds->accel_calib_data[2].sens_numer = 2 * DS_ACC_RES_PER_G;
1127 	ds->accel_calib_data[2].sens_denom = range_2g;
1128 
1129 	/*
1130 	 * Sanity check accelerometer calibration data. This is needed to prevent crashes
1131 	 * during report handling of virtual, clone or broken devices not implementing calibration
1132 	 * data properly.
1133 	 */
1134 	for (i = 0; i < ARRAY_SIZE(ds->accel_calib_data); i++) {
1135 		if (ds->accel_calib_data[i].sens_denom == 0) {
1136 			hid_warn(hdev,
1137 				 "Invalid accelerometer calibration data for axis (%d), disabling calibration.",
1138 				 ds->accel_calib_data[i].abs_code);
1139 			ds->accel_calib_data[i].bias = 0;
1140 			ds->accel_calib_data[i].sens_numer = DS_ACC_RANGE;
1141 			ds->accel_calib_data[i].sens_denom = S16_MAX;
1142 		}
1143 	}
1144 
1145 err_free:
1146 	kfree(buf);
1147 	return ret;
1148 }
1149 
1150 static int dualsense_get_firmware_info(struct dualsense *ds)
1151 {
1152 	u8 *buf;
1153 	int ret;
1154 
1155 	buf = kzalloc(DS_FEATURE_REPORT_FIRMWARE_INFO_SIZE, GFP_KERNEL);
1156 	if (!buf)
1157 		return -ENOMEM;
1158 
1159 	ret = ps_get_report(ds->base.hdev, DS_FEATURE_REPORT_FIRMWARE_INFO, buf,
1160 			    DS_FEATURE_REPORT_FIRMWARE_INFO_SIZE, true);
1161 	if (ret) {
1162 		hid_err(ds->base.hdev, "Failed to retrieve DualSense firmware info: %d\n", ret);
1163 		goto err_free;
1164 	}
1165 
1166 	ds->base.hw_version = get_unaligned_le32(&buf[24]);
1167 	ds->base.fw_version = get_unaligned_le32(&buf[28]);
1168 
1169 	/* Update version is some kind of feature version. It is distinct from
1170 	 * the firmware version as there can be many different variations of a
1171 	 * controller over time with the same physical shell, but with different
1172 	 * PCBs and other internal changes. The update version (internal name) is
1173 	 * used as a means to detect what features are available and change behavior.
1174 	 * Note: the version is different between DualSense and DualSense Edge.
1175 	 */
1176 	ds->update_version = get_unaligned_le16(&buf[44]);
1177 
1178 err_free:
1179 	kfree(buf);
1180 	return ret;
1181 }
1182 
1183 static int dualsense_get_mac_address(struct dualsense *ds)
1184 {
1185 	u8 *buf;
1186 	int ret = 0;
1187 
1188 	buf = kzalloc(DS_FEATURE_REPORT_PAIRING_INFO_SIZE, GFP_KERNEL);
1189 	if (!buf)
1190 		return -ENOMEM;
1191 
1192 	ret = ps_get_report(ds->base.hdev, DS_FEATURE_REPORT_PAIRING_INFO, buf,
1193 			    DS_FEATURE_REPORT_PAIRING_INFO_SIZE, true);
1194 	if (ret) {
1195 		hid_err(ds->base.hdev, "Failed to retrieve DualSense pairing info: %d\n", ret);
1196 		goto err_free;
1197 	}
1198 
1199 	memcpy(ds->base.mac_address, &buf[1], sizeof(ds->base.mac_address));
1200 
1201 err_free:
1202 	kfree(buf);
1203 	return ret;
1204 }
1205 
1206 static int dualsense_lightbar_set_brightness(struct led_classdev *cdev,
1207 					     enum led_brightness brightness)
1208 {
1209 	struct led_classdev_mc *mc_cdev = lcdev_to_mccdev(cdev);
1210 	struct dualsense *ds = container_of(mc_cdev, struct dualsense, lightbar);
1211 	u8 red, green, blue;
1212 
1213 	led_mc_calc_color_components(mc_cdev, brightness);
1214 	red = mc_cdev->subled_info[0].brightness;
1215 	green = mc_cdev->subled_info[1].brightness;
1216 	blue = mc_cdev->subled_info[2].brightness;
1217 
1218 	dualsense_set_lightbar(ds, red, green, blue);
1219 	return 0;
1220 }
1221 
1222 static enum led_brightness dualsense_player_led_get_brightness(struct led_classdev *led)
1223 {
1224 	struct hid_device *hdev = to_hid_device(led->dev->parent);
1225 	struct dualsense *ds = hid_get_drvdata(hdev);
1226 
1227 	return !!(ds->player_leds_state & BIT(led - ds->player_leds));
1228 }
1229 
1230 static int dualsense_player_led_set_brightness(struct led_classdev *led, enum led_brightness value)
1231 {
1232 	struct hid_device *hdev = to_hid_device(led->dev->parent);
1233 	struct dualsense *ds = hid_get_drvdata(hdev);
1234 	unsigned int led_index;
1235 
1236 	scoped_guard(spinlock_irqsave, &ds->base.lock) {
1237 		led_index = led - ds->player_leds;
1238 		if (value == LED_OFF)
1239 			ds->player_leds_state &= ~BIT(led_index);
1240 		else
1241 			ds->player_leds_state |= BIT(led_index);
1242 
1243 		ds->update_player_leds = true;
1244 	}
1245 
1246 	dualsense_schedule_work(ds);
1247 
1248 	return 0;
1249 }
1250 
1251 static void dualsense_init_output_report(struct dualsense *ds,
1252 					 struct dualsense_output_report *rp, void *buf)
1253 {
1254 	struct hid_device *hdev = ds->base.hdev;
1255 
1256 	if (hdev->bus == BUS_BLUETOOTH) {
1257 		struct dualsense_output_report_bt *bt = buf;
1258 
1259 		memset(bt, 0, sizeof(*bt));
1260 		bt->report_id = DS_OUTPUT_REPORT_BT;
1261 		bt->tag = DS_OUTPUT_TAG; /* Tag must be set. Exact meaning is unclear. */
1262 
1263 		/*
1264 		 * Highest 4-bit is a sequence number, which needs to be increased
1265 		 * every report. Lowest 4-bit is tag and can be zero for now.
1266 		 */
1267 		bt->seq_tag = FIELD_PREP(DS_OUTPUT_SEQ_NO, ds->output_seq) |
1268 			      FIELD_PREP(DS_OUTPUT_SEQ_TAG, 0x0);
1269 		if (++ds->output_seq == 16)
1270 			ds->output_seq = 0;
1271 
1272 		rp->data = buf;
1273 		rp->len = sizeof(*bt);
1274 		rp->bt = bt;
1275 		rp->usb = NULL;
1276 		rp->common = &bt->common;
1277 	} else { /* USB */
1278 		struct dualsense_output_report_usb *usb = buf;
1279 
1280 		memset(usb, 0, sizeof(*usb));
1281 		usb->report_id = DS_OUTPUT_REPORT_USB;
1282 
1283 		rp->data = buf;
1284 		rp->len = sizeof(*usb);
1285 		rp->bt = NULL;
1286 		rp->usb = usb;
1287 		rp->common = &usb->common;
1288 	}
1289 }
1290 
1291 static inline void dualsense_schedule_work(struct dualsense *ds)
1292 {
1293 	/* Using scoped_guard() instead of guard() to make sparse happy */
1294 	scoped_guard(spinlock_irqsave, &ds->base.lock)
1295 		if (ds->output_worker_initialized)
1296 			schedule_work(&ds->output_worker);
1297 }
1298 
1299 /*
1300  * Helper function to send DualSense output reports. Applies a CRC at the end of a report
1301  * for Bluetooth reports.
1302  */
1303 static void dualsense_send_output_report(struct dualsense *ds,
1304 					 struct dualsense_output_report *report)
1305 {
1306 	struct hid_device *hdev = ds->base.hdev;
1307 
1308 	/* Bluetooth packets need to be signed with a CRC in the last 4 bytes. */
1309 	if (report->bt) {
1310 		u32 crc;
1311 		u8 seed = PS_OUTPUT_CRC32_SEED;
1312 
1313 		crc = crc32_le(0xFFFFFFFF, &seed, 1);
1314 		crc = ~crc32_le(crc, report->data, report->len - 4);
1315 
1316 		report->bt->crc32 = cpu_to_le32(crc);
1317 	}
1318 
1319 	hid_hw_output_report(hdev, report->data, report->len);
1320 }
1321 
1322 static void dualsense_output_worker(struct work_struct *work)
1323 {
1324 	struct dualsense *ds = container_of(work, struct dualsense, output_worker);
1325 	struct dualsense_output_report report;
1326 	struct dualsense_output_report_common *common;
1327 
1328 	dualsense_init_output_report(ds, &report, ds->output_report_dmabuf);
1329 	common = report.common;
1330 
1331 	scoped_guard(spinlock_irqsave, &ds->base.lock) {
1332 		if (ds->update_rumble) {
1333 			/* Select classic rumble style haptics and enable it. */
1334 			common->valid_flag0 |= DS_OUTPUT_VALID_FLAG0_HAPTICS_SELECT;
1335 			if (ds->use_vibration_v2)
1336 				common->valid_flag2 |= DS_OUTPUT_VALID_FLAG2_COMPATIBLE_VIBRATION2;
1337 			else
1338 				common->valid_flag0 |= DS_OUTPUT_VALID_FLAG0_COMPATIBLE_VIBRATION;
1339 			common->motor_left = ds->motor_left;
1340 			common->motor_right = ds->motor_right;
1341 			ds->update_rumble = false;
1342 		}
1343 
1344 		if (ds->update_lightbar) {
1345 			common->valid_flag1 |= DS_OUTPUT_VALID_FLAG1_LIGHTBAR_CONTROL_ENABLE;
1346 			common->lightbar_red = ds->lightbar_red;
1347 			common->lightbar_green = ds->lightbar_green;
1348 			common->lightbar_blue = ds->lightbar_blue;
1349 
1350 			ds->update_lightbar = false;
1351 		}
1352 
1353 		if (ds->update_player_leds) {
1354 			common->valid_flag1 |=
1355 				DS_OUTPUT_VALID_FLAG1_PLAYER_INDICATOR_CONTROL_ENABLE;
1356 			common->player_leds = ds->player_leds_state;
1357 
1358 			ds->update_player_leds = false;
1359 		}
1360 
1361 		if (ds->plugged_state != ds->prev_plugged_state) {
1362 			u8 val = ds->plugged_state & DS_STATUS1_HP_DETECT;
1363 
1364 			if (val != (ds->prev_plugged_state & DS_STATUS1_HP_DETECT)) {
1365 				common->valid_flag0 = DS_OUTPUT_VALID_FLAG0_AUDIO_CONTROL_ENABLE;
1366 				/*
1367 				 *  _--------> Output path setup in audio_flag0
1368 				 * /  _------> Headphone (HP) Left channel sink
1369 				 * | /  _----> Headphone (HP) Right channel sink
1370 				 * | | /  _--> Internal Speaker (SP) sink
1371 				 * | | | /
1372 				 * | | | |     L/R - Left/Right channel source
1373 				 * 0 L-R X       X - Unrouted (muted) channel source
1374 				 * 1 L-L X
1375 				 * 2 L-L R
1376 				 * 3 X-X R
1377 				 */
1378 				if (val) {
1379 					/* Mute SP and route L+R channels to HP */
1380 					common->audio_control = 0;
1381 				} else {
1382 					/* Mute HP and route R channel to SP */
1383 					common->audio_control =
1384 						FIELD_PREP(DS_OUTPUT_AUDIO_FLAGS_OUTPUT_PATH_SEL,
1385 							   0x3);
1386 					/*
1387 					 * Set SP hardware volume to 100%.
1388 					 * Note the accepted range seems to be [0x3d..0x64]
1389 					 */
1390 					common->valid_flag0 |=
1391 						DS_OUTPUT_VALID_FLAG0_SPEAKER_VOLUME_ENABLE;
1392 					common->speaker_volume = 0x64;
1393 					/* Set SP preamp gain to +6dB */
1394 					common->valid_flag1 =
1395 						DS_OUTPUT_VALID_FLAG1_AUDIO_CONTROL2_ENABLE;
1396 					common->audio_control2 =
1397 						FIELD_PREP(DS_OUTPUT_AUDIO_FLAGS2_SP_PREAMP_GAIN,
1398 							   0x2);
1399 				}
1400 
1401 				input_report_switch(ds->jack, SW_HEADPHONE_INSERT, val);
1402 			}
1403 
1404 			val = ds->plugged_state & DS_STATUS1_MIC_DETECT;
1405 			if (val != (ds->prev_plugged_state & DS_STATUS1_MIC_DETECT))
1406 				input_report_switch(ds->jack, SW_MICROPHONE_INSERT, val);
1407 
1408 			input_sync(ds->jack);
1409 			ds->prev_plugged_state = ds->plugged_state;
1410 		}
1411 
1412 		if (ds->update_mic_mute) {
1413 			common->valid_flag1 |= DS_OUTPUT_VALID_FLAG1_MIC_MUTE_LED_CONTROL_ENABLE;
1414 			common->mute_button_led = ds->mic_muted;
1415 
1416 			if (ds->mic_muted) {
1417 				/* Disable microphone */
1418 				common->valid_flag1 |=
1419 					DS_OUTPUT_VALID_FLAG1_POWER_SAVE_CONTROL_ENABLE;
1420 				common->power_save_control |= DS_OUTPUT_POWER_SAVE_CONTROL_MIC_MUTE;
1421 			} else {
1422 				/* Enable microphone */
1423 				common->valid_flag1 |=
1424 					DS_OUTPUT_VALID_FLAG1_POWER_SAVE_CONTROL_ENABLE;
1425 				common->power_save_control &=
1426 					~DS_OUTPUT_POWER_SAVE_CONTROL_MIC_MUTE;
1427 			}
1428 
1429 			ds->update_mic_mute = false;
1430 		}
1431 	}
1432 
1433 	dualsense_send_output_report(ds, &report);
1434 }
1435 
1436 static int dualsense_parse_report(struct ps_device *ps_dev, struct hid_report *report,
1437 				  u8 *data, int size)
1438 {
1439 	struct hid_device *hdev = ps_dev->hdev;
1440 	struct dualsense *ds = container_of(ps_dev, struct dualsense, base);
1441 	struct dualsense_input_report *ds_report;
1442 	u8 battery_data, battery_capacity, charging_status, value;
1443 	int battery_status;
1444 	u32 sensor_timestamp;
1445 	bool btn_mic_state;
1446 	int i;
1447 
1448 	/*
1449 	 * DualSense in USB uses the full HID report for reportID 1, but
1450 	 * Bluetooth uses a minimal HID report for reportID 1 and reports
1451 	 * the full report using reportID 49.
1452 	 */
1453 	if (hdev->bus == BUS_USB && report->id == DS_INPUT_REPORT_USB &&
1454 	    size == DS_INPUT_REPORT_USB_SIZE) {
1455 		ds_report = (struct dualsense_input_report *)&data[1];
1456 	} else if (hdev->bus == BUS_BLUETOOTH && report->id == DS_INPUT_REPORT_BT &&
1457 		   size == DS_INPUT_REPORT_BT_SIZE) {
1458 		/* Last 4 bytes of input report contain crc32 */
1459 		u32 report_crc = get_unaligned_le32(&data[size - 4]);
1460 
1461 		if (!ps_check_crc32(PS_INPUT_CRC32_SEED, data, size - 4, report_crc)) {
1462 			hid_err(hdev, "DualSense input CRC's check failed\n");
1463 			return -EILSEQ;
1464 		}
1465 
1466 		ds_report = (struct dualsense_input_report *)&data[2];
1467 	} else {
1468 		hid_err(hdev, "Unhandled reportID=%d\n", report->id);
1469 		return -1;
1470 	}
1471 
1472 	input_report_abs(ds->gamepad, ABS_X,  ds_report->x);
1473 	input_report_abs(ds->gamepad, ABS_Y,  ds_report->y);
1474 	input_report_abs(ds->gamepad, ABS_RX, ds_report->rx);
1475 	input_report_abs(ds->gamepad, ABS_RY, ds_report->ry);
1476 	input_report_abs(ds->gamepad, ABS_Z,  ds_report->z);
1477 	input_report_abs(ds->gamepad, ABS_RZ, ds_report->rz);
1478 
1479 	value = ds_report->buttons[0] & DS_BUTTONS0_HAT_SWITCH;
1480 	if (value >= ARRAY_SIZE(ps_gamepad_hat_mapping))
1481 		value = 8; /* center */
1482 	input_report_abs(ds->gamepad, ABS_HAT0X, ps_gamepad_hat_mapping[value].x);
1483 	input_report_abs(ds->gamepad, ABS_HAT0Y, ps_gamepad_hat_mapping[value].y);
1484 
1485 	input_report_key(ds->gamepad, BTN_WEST,   ds_report->buttons[0] & DS_BUTTONS0_SQUARE);
1486 	input_report_key(ds->gamepad, BTN_SOUTH,  ds_report->buttons[0] & DS_BUTTONS0_CROSS);
1487 	input_report_key(ds->gamepad, BTN_EAST,   ds_report->buttons[0] & DS_BUTTONS0_CIRCLE);
1488 	input_report_key(ds->gamepad, BTN_NORTH,  ds_report->buttons[0] & DS_BUTTONS0_TRIANGLE);
1489 	input_report_key(ds->gamepad, BTN_TL,     ds_report->buttons[1] & DS_BUTTONS1_L1);
1490 	input_report_key(ds->gamepad, BTN_TR,     ds_report->buttons[1] & DS_BUTTONS1_R1);
1491 	input_report_key(ds->gamepad, BTN_TL2,    ds_report->buttons[1] & DS_BUTTONS1_L2);
1492 	input_report_key(ds->gamepad, BTN_TR2,    ds_report->buttons[1] & DS_BUTTONS1_R2);
1493 	input_report_key(ds->gamepad, BTN_SELECT, ds_report->buttons[1] & DS_BUTTONS1_CREATE);
1494 	input_report_key(ds->gamepad, BTN_START,  ds_report->buttons[1] & DS_BUTTONS1_OPTIONS);
1495 	input_report_key(ds->gamepad, BTN_THUMBL, ds_report->buttons[1] & DS_BUTTONS1_L3);
1496 	input_report_key(ds->gamepad, BTN_THUMBR, ds_report->buttons[1] & DS_BUTTONS1_R3);
1497 	input_report_key(ds->gamepad, BTN_MODE,   ds_report->buttons[2] & DS_BUTTONS2_PS_HOME);
1498 
1499 	if (ds->is_edge) {
1500 		input_report_key(ds->gamepad, BTN_TRIGGER_HAPPY1,
1501 				 ds_report->buttons[2] & DS_EDGE_BUTTONS_FN1);
1502 		input_report_key(ds->gamepad, BTN_TRIGGER_HAPPY2,
1503 				 ds_report->buttons[2] & DS_EDGE_BUTTONS_FN2);
1504 		input_report_key(ds->gamepad, BTN_TRIGGER_HAPPY3,
1505 				 ds_report->buttons[2] & DS_EDGE_BUTTONS_LEFT_PADDLE);
1506 		input_report_key(ds->gamepad, BTN_TRIGGER_HAPPY4,
1507 				 ds_report->buttons[2] & DS_EDGE_BUTTONS_RIGHT_PADDLE);
1508 	}
1509 
1510 	input_sync(ds->gamepad);
1511 
1512 	/*
1513 	 * The DualSense has an internal microphone, which can be muted through a mute button
1514 	 * on the device. The driver is expected to read the button state and program the device
1515 	 * to mute/unmute audio at the hardware level.
1516 	 */
1517 	btn_mic_state = !!(ds_report->buttons[2] & DS_BUTTONS2_MIC_MUTE);
1518 	if (btn_mic_state && !ds->last_btn_mic_state) {
1519 		scoped_guard(spinlock_irqsave, &ps_dev->lock) {
1520 			ds->update_mic_mute = true;
1521 			ds->mic_muted = !ds->mic_muted; /* toggle */
1522 		}
1523 
1524 		/* Schedule updating of microphone state at hardware level. */
1525 		dualsense_schedule_work(ds);
1526 	}
1527 	ds->last_btn_mic_state = btn_mic_state;
1528 
1529 	/*
1530 	 * Parse HP/MIC plugged state data for USB use case, since Bluetooth
1531 	 * audio is currently not supported.
1532 	 */
1533 	if (hdev->bus == BUS_USB) {
1534 		value = ds_report->status[1] & DS_STATUS1_JACK_DETECT;
1535 
1536 		if (!ds->prev_plugged_state_valid) {
1537 			/* Initial handling of the plugged state report */
1538 			scoped_guard(spinlock_irqsave, &ps_dev->lock) {
1539 				ds->plugged_state = (~value) & DS_STATUS1_JACK_DETECT;
1540 				ds->prev_plugged_state_valid = true;
1541 			}
1542 		}
1543 
1544 		if (value != ds->plugged_state) {
1545 			scoped_guard(spinlock_irqsave, &ps_dev->lock) {
1546 				ds->prev_plugged_state = ds->plugged_state;
1547 				ds->plugged_state = value;
1548 			}
1549 
1550 			/* Schedule audio routing towards active endpoint. */
1551 			dualsense_schedule_work(ds);
1552 		}
1553 	}
1554 
1555 	/* Parse and calibrate gyroscope data. */
1556 	for (i = 0; i < ARRAY_SIZE(ds_report->gyro); i++) {
1557 		int raw_data = (short)le16_to_cpu(ds_report->gyro[i]);
1558 		int calib_data = mult_frac(ds->gyro_calib_data[i].sens_numer,
1559 					   raw_data, ds->gyro_calib_data[i].sens_denom);
1560 
1561 		input_report_abs(ds->sensors, ds->gyro_calib_data[i].abs_code, calib_data);
1562 	}
1563 
1564 	/* Parse and calibrate accelerometer data. */
1565 	for (i = 0; i < ARRAY_SIZE(ds_report->accel); i++) {
1566 		int raw_data = (short)le16_to_cpu(ds_report->accel[i]);
1567 		int calib_data = mult_frac(ds->accel_calib_data[i].sens_numer,
1568 					   raw_data - ds->accel_calib_data[i].bias,
1569 					   ds->accel_calib_data[i].sens_denom);
1570 
1571 		input_report_abs(ds->sensors, ds->accel_calib_data[i].abs_code, calib_data);
1572 	}
1573 
1574 	/* Convert timestamp (in 0.33us unit) to timestamp_us */
1575 	sensor_timestamp = le32_to_cpu(ds_report->sensor_timestamp);
1576 	if (!ds->sensor_timestamp_initialized) {
1577 		ds->sensor_timestamp_us = DIV_ROUND_CLOSEST(sensor_timestamp, 3);
1578 		ds->sensor_timestamp_initialized = true;
1579 	} else {
1580 		u32 delta;
1581 
1582 		if (ds->prev_sensor_timestamp > sensor_timestamp)
1583 			delta = (U32_MAX - ds->prev_sensor_timestamp + sensor_timestamp + 1);
1584 		else
1585 			delta = sensor_timestamp - ds->prev_sensor_timestamp;
1586 		ds->sensor_timestamp_us += DIV_ROUND_CLOSEST(delta, 3);
1587 	}
1588 	ds->prev_sensor_timestamp = sensor_timestamp;
1589 	input_event(ds->sensors, EV_MSC, MSC_TIMESTAMP, ds->sensor_timestamp_us);
1590 	input_sync(ds->sensors);
1591 
1592 	for (i = 0; i < ARRAY_SIZE(ds_report->points); i++) {
1593 		struct dualsense_touch_point *point = &ds_report->points[i];
1594 		bool active = (point->contact & DS_TOUCH_POINT_INACTIVE) ? false : true;
1595 
1596 		input_mt_slot(ds->touchpad, i);
1597 		input_mt_report_slot_state(ds->touchpad, MT_TOOL_FINGER, active);
1598 
1599 		if (active) {
1600 			input_report_abs(ds->touchpad, ABS_MT_POSITION_X,
1601 					 DS_TOUCH_POINT_X(point->x_hi, point->x_lo));
1602 			input_report_abs(ds->touchpad, ABS_MT_POSITION_Y,
1603 					 DS_TOUCH_POINT_Y(point->y_hi, point->y_lo));
1604 		}
1605 	}
1606 	input_mt_sync_frame(ds->touchpad);
1607 	input_report_key(ds->touchpad, BTN_LEFT, ds_report->buttons[2] & DS_BUTTONS2_TOUCHPAD);
1608 	input_sync(ds->touchpad);
1609 
1610 	battery_data = FIELD_GET(DS_STATUS0_BATTERY_CAPACITY, ds_report->status[0]);
1611 	charging_status = FIELD_GET(DS_STATUS0_CHARGING, ds_report->status[0]);
1612 
1613 	switch (charging_status) {
1614 	case 0x0:
1615 		/*
1616 		 * Each unit of battery data corresponds to 10%
1617 		 * 0 = 0-9%, 1 = 10-19%, .. and 10 = 100%
1618 		 */
1619 		battery_capacity = min(battery_data * 10 + 5, 100);
1620 		battery_status = POWER_SUPPLY_STATUS_DISCHARGING;
1621 		break;
1622 	case 0x1:
1623 		battery_capacity = min(battery_data * 10 + 5, 100);
1624 		battery_status = POWER_SUPPLY_STATUS_CHARGING;
1625 		break;
1626 	case 0x2:
1627 		battery_capacity = 100;
1628 		battery_status = POWER_SUPPLY_STATUS_FULL;
1629 		break;
1630 	case 0xa: /* voltage or temperature out of range */
1631 	case 0xb: /* temperature error */
1632 		battery_capacity = 0;
1633 		battery_status = POWER_SUPPLY_STATUS_NOT_CHARGING;
1634 		break;
1635 	case 0xf: /* charging error */
1636 	default:
1637 		battery_capacity = 0;
1638 		battery_status = POWER_SUPPLY_STATUS_UNKNOWN;
1639 	}
1640 
1641 	scoped_guard(spinlock_irqsave, &ps_dev->lock) {
1642 		ps_dev->battery_capacity = battery_capacity;
1643 		ps_dev->battery_status = battery_status;
1644 	}
1645 
1646 	return 0;
1647 }
1648 
1649 static int dualsense_play_effect(struct input_dev *dev, void *data, struct ff_effect *effect)
1650 {
1651 	struct hid_device *hdev = input_get_drvdata(dev);
1652 	struct dualsense *ds = hid_get_drvdata(hdev);
1653 
1654 	if (effect->type != FF_RUMBLE)
1655 		return 0;
1656 
1657 	scoped_guard(spinlock_irqsave, &ds->base.lock) {
1658 		ds->update_rumble = true;
1659 		ds->motor_left = effect->u.rumble.strong_magnitude / 256;
1660 		ds->motor_right = effect->u.rumble.weak_magnitude / 256;
1661 	}
1662 
1663 	dualsense_schedule_work(ds);
1664 	return 0;
1665 }
1666 
1667 static void dualsense_remove(struct ps_device *ps_dev)
1668 {
1669 	struct dualsense *ds = container_of(ps_dev, struct dualsense, base);
1670 
1671 	scoped_guard(spinlock_irqsave, &ds->base.lock)
1672 		ds->output_worker_initialized = false;
1673 
1674 	cancel_work_sync(&ds->output_worker);
1675 }
1676 
1677 static int dualsense_reset_leds(struct dualsense *ds)
1678 {
1679 	struct dualsense_output_report report;
1680 	struct dualsense_output_report_bt *buf;
1681 
1682 	buf = kzalloc_obj(*buf);
1683 	if (!buf)
1684 		return -ENOMEM;
1685 
1686 	dualsense_init_output_report(ds, &report, buf);
1687 	/*
1688 	 * On Bluetooth the DualSense outputs an animation on the lightbar
1689 	 * during startup and maintains a color afterwards. We need to explicitly
1690 	 * reconfigure the lightbar before we can do any programming later on.
1691 	 * In USB the lightbar is not on by default, but redoing the setup there
1692 	 * doesn't hurt.
1693 	 */
1694 	report.common->valid_flag2 = DS_OUTPUT_VALID_FLAG2_LIGHTBAR_SETUP_CONTROL_ENABLE;
1695 	report.common->lightbar_setup = DS_OUTPUT_LIGHTBAR_SETUP_LIGHT_OUT; /* Fade light out. */
1696 	dualsense_send_output_report(ds, &report);
1697 
1698 	kfree(buf);
1699 	return 0;
1700 }
1701 
1702 static void dualsense_set_lightbar(struct dualsense *ds, u8 red, u8 green, u8 blue)
1703 {
1704 	scoped_guard(spinlock_irqsave, &ds->base.lock) {
1705 		ds->update_lightbar = true;
1706 		ds->lightbar_red = red;
1707 		ds->lightbar_green = green;
1708 		ds->lightbar_blue = blue;
1709 	}
1710 
1711 	dualsense_schedule_work(ds);
1712 }
1713 
1714 static void dualsense_set_player_leds(struct dualsense *ds)
1715 {
1716 	/*
1717 	 * The DualSense controller has a row of 5 LEDs used for player ids.
1718 	 * Behavior on the PlayStation 5 console is to center the player id
1719 	 * across the LEDs, so e.g. player 1 would be "--x--" with x being 'on'.
1720 	 * Follow a similar mapping here.
1721 	 */
1722 	static const int player_ids[5] = {
1723 		BIT(2),
1724 		BIT(3) | BIT(1),
1725 		BIT(4) | BIT(2) | BIT(0),
1726 		BIT(4) | BIT(3) | BIT(1) | BIT(0),
1727 		BIT(4) | BIT(3) | BIT(2) | BIT(1) | BIT(0)
1728 	};
1729 
1730 	u8 player_id = ds->base.player_id % ARRAY_SIZE(player_ids);
1731 
1732 	ds->update_player_leds = true;
1733 	ds->player_leds_state = player_ids[player_id];
1734 	dualsense_schedule_work(ds);
1735 }
1736 
1737 static struct ps_device *dualsense_create(struct hid_device *hdev)
1738 {
1739 	struct dualsense *ds;
1740 	struct ps_device *ps_dev;
1741 	u8 max_output_report_size;
1742 	int i, ret;
1743 
1744 	static const struct ps_led_info player_leds_info[] = {
1745 		{ LED_FUNCTION_PLAYER1, "white", 1, dualsense_player_led_get_brightness,
1746 				dualsense_player_led_set_brightness },
1747 		{ LED_FUNCTION_PLAYER2, "white", 1, dualsense_player_led_get_brightness,
1748 				dualsense_player_led_set_brightness },
1749 		{ LED_FUNCTION_PLAYER3, "white", 1, dualsense_player_led_get_brightness,
1750 				dualsense_player_led_set_brightness },
1751 		{ LED_FUNCTION_PLAYER4, "white", 1, dualsense_player_led_get_brightness,
1752 				dualsense_player_led_set_brightness },
1753 		{ LED_FUNCTION_PLAYER5, "white", 1, dualsense_player_led_get_brightness,
1754 				dualsense_player_led_set_brightness }
1755 	};
1756 
1757 	ds = devm_kzalloc(&hdev->dev, sizeof(*ds), GFP_KERNEL);
1758 	if (!ds)
1759 		return ERR_PTR(-ENOMEM);
1760 
1761 	/*
1762 	 * Patch version to allow userspace to distinguish between
1763 	 * hid-generic vs hid-playstation axis and button mapping.
1764 	 */
1765 	hdev->version |= HID_PLAYSTATION_VERSION_PATCH;
1766 
1767 	ps_dev = &ds->base;
1768 	ps_dev->hdev = hdev;
1769 	spin_lock_init(&ps_dev->lock);
1770 	ps_dev->battery_capacity = 100; /* initial value until parse_report. */
1771 	ps_dev->battery_status = POWER_SUPPLY_STATUS_UNKNOWN;
1772 	ps_dev->parse_report = dualsense_parse_report;
1773 	ps_dev->remove = dualsense_remove;
1774 	INIT_WORK(&ds->output_worker, dualsense_output_worker);
1775 	ds->output_worker_initialized = true;
1776 	hid_set_drvdata(hdev, ds);
1777 
1778 	max_output_report_size = sizeof(struct dualsense_output_report_bt);
1779 	ds->output_report_dmabuf = devm_kzalloc(&hdev->dev, max_output_report_size, GFP_KERNEL);
1780 	if (!ds->output_report_dmabuf)
1781 		return ERR_PTR(-ENOMEM);
1782 
1783 	ret = dualsense_get_mac_address(ds);
1784 	if (ret) {
1785 		hid_err(hdev, "Failed to get MAC address from DualSense\n");
1786 		return ERR_PTR(ret);
1787 	}
1788 	snprintf(hdev->uniq, sizeof(hdev->uniq), "%pMR", ds->base.mac_address);
1789 
1790 	ret = dualsense_get_firmware_info(ds);
1791 	if (ret) {
1792 		hid_err(hdev, "Failed to get firmware info from DualSense\n");
1793 		return ERR_PTR(ret);
1794 	}
1795 
1796 	/* Original DualSense firmware simulated classic controller rumble through
1797 	 * its new haptics hardware. It felt different from classic rumble users
1798 	 * were used to. Since then new firmwares were introduced to change behavior
1799 	 * and make this new 'v2' behavior default on PlayStation and other platforms.
1800 	 * The original DualSense requires a new enough firmware as bundled with PS5
1801 	 * software released in 2021. DualSense edge supports it out of the box.
1802 	 * Both devices also support the old mode, but it is not really used.
1803 	 */
1804 	if (hdev->product == USB_DEVICE_ID_SONY_PS5_CONTROLLER) {
1805 		/* Feature version 2.21 introduced new vibration method. */
1806 		ds->use_vibration_v2 = ds->update_version >= DS_FEATURE_VERSION(2, 21);
1807 	} else if (hdev->product == USB_DEVICE_ID_SONY_PS5_CONTROLLER_2) {
1808 		ds->use_vibration_v2 = true;
1809 		ds->is_edge = true;
1810 	}
1811 
1812 	ret = ps_devices_list_add(ps_dev);
1813 	if (ret)
1814 		return ERR_PTR(ret);
1815 
1816 	ret = dualsense_get_calibration_data(ds);
1817 	if (ret) {
1818 		hid_err(hdev, "Failed to get calibration data from DualSense\n");
1819 		goto err;
1820 	}
1821 
1822 	ds->gamepad = ps_gamepad_create(hdev, dualsense_play_effect);
1823 	if (IS_ERR(ds->gamepad)) {
1824 		ret = PTR_ERR(ds->gamepad);
1825 		goto err;
1826 	}
1827 
1828 	/* Register DualSense Edge back paddle and Fn buttons. */
1829 	if (ds->is_edge) {
1830 		input_set_capability(ds->gamepad, EV_KEY, BTN_TRIGGER_HAPPY1);
1831 		input_set_capability(ds->gamepad, EV_KEY, BTN_TRIGGER_HAPPY2);
1832 		input_set_capability(ds->gamepad, EV_KEY, BTN_TRIGGER_HAPPY3);
1833 		input_set_capability(ds->gamepad, EV_KEY, BTN_TRIGGER_HAPPY4);
1834 	}
1835 
1836 	/* Use gamepad input device name as primary device name for e.g. LEDs */
1837 	ps_dev->input_dev_name = dev_name(&ds->gamepad->dev);
1838 
1839 	ds->sensors = ps_sensors_create(hdev, DS_ACC_RANGE, DS_ACC_RES_PER_G,
1840 					DS_GYRO_RANGE, DS_GYRO_RES_PER_DEG_S);
1841 	if (IS_ERR(ds->sensors)) {
1842 		ret = PTR_ERR(ds->sensors);
1843 		goto err;
1844 	}
1845 
1846 	ds->touchpad = ps_touchpad_create(hdev, DS_TOUCHPAD_WIDTH, DS_TOUCHPAD_HEIGHT, 2);
1847 	if (IS_ERR(ds->touchpad)) {
1848 		ret = PTR_ERR(ds->touchpad);
1849 		goto err;
1850 	}
1851 
1852 	/* Bluetooth audio is currently not supported. */
1853 	if (hdev->bus == BUS_USB) {
1854 		ds->jack = ps_headset_jack_create(hdev);
1855 		if (IS_ERR(ds->jack)) {
1856 			ret = PTR_ERR(ds->jack);
1857 			goto err;
1858 		}
1859 	}
1860 
1861 	ret = ps_device_register_battery(ps_dev);
1862 	if (ret)
1863 		goto err;
1864 
1865 	/*
1866 	 * The hardware may have control over the LEDs (e.g. in Bluetooth on startup).
1867 	 * Reset the LEDs (lightbar, mute, player leds), so we can control them
1868 	 * from software.
1869 	 */
1870 	ret = dualsense_reset_leds(ds);
1871 	if (ret)
1872 		goto err;
1873 
1874 	ret = ps_lightbar_register(ps_dev, &ds->lightbar, dualsense_lightbar_set_brightness);
1875 	if (ret)
1876 		goto err;
1877 
1878 	/* Set default lightbar color. */
1879 	dualsense_set_lightbar(ds, 0, 0, 128); /* blue */
1880 
1881 	for (i = 0; i < ARRAY_SIZE(player_leds_info); i++) {
1882 		const struct ps_led_info *led_info = &player_leds_info[i];
1883 
1884 		ret = ps_led_register(ps_dev, &ds->player_leds[i], led_info);
1885 		if (ret < 0)
1886 			goto err;
1887 	}
1888 
1889 	ret = ps_device_set_player_id(ps_dev);
1890 	if (ret) {
1891 		hid_err(hdev, "Failed to assign player id for DualSense: %d\n", ret);
1892 		goto err;
1893 	}
1894 
1895 	/* Set player LEDs to our player id. */
1896 	dualsense_set_player_leds(ds);
1897 
1898 	/*
1899 	 * Reporting hardware and firmware is important as there are frequent updates, which
1900 	 * can change behavior.
1901 	 */
1902 	hid_info(hdev, "Registered DualSense controller hw_version=0x%08x fw_version=0x%08x\n",
1903 		 ds->base.hw_version, ds->base.fw_version);
1904 
1905 	return &ds->base;
1906 
1907 err:
1908 	ps_devices_list_remove(ps_dev);
1909 	return ERR_PTR(ret);
1910 }
1911 
1912 static void dualshock4_dongle_calibration_work(struct work_struct *work)
1913 {
1914 	struct dualshock4 *ds4 = container_of(work, struct dualshock4, dongle_hotplug_worker);
1915 	enum dualshock4_dongle_state dongle_state;
1916 	int ret;
1917 
1918 	ret = dualshock4_get_calibration_data(ds4);
1919 	if (ret < 0) {
1920 		/* This call is very unlikely to fail for the dongle. When it
1921 		 * fails we are probably in a very bad state, so mark the
1922 		 * dongle as disabled. We will re-enable the dongle if a new
1923 		 * DS4 hotplug is detect from sony_raw_event as any issues
1924 		 * are likely resolved then (the dongle is quite stupid).
1925 		 */
1926 		hid_err(ds4->base.hdev,
1927 			"DualShock 4 USB dongle: calibration failed, disabling device\n");
1928 		dongle_state = DONGLE_DISABLED;
1929 	} else {
1930 		hid_info(ds4->base.hdev, "DualShock 4 USB dongle: calibration completed\n");
1931 		dongle_state = DONGLE_CONNECTED;
1932 	}
1933 
1934 	scoped_guard(spinlock_irqsave, &ds4->base.lock)
1935 		ds4->dongle_state = dongle_state;
1936 }
1937 
1938 static int dualshock4_get_calibration_data(struct dualshock4 *ds4)
1939 {
1940 	struct hid_device *hdev = ds4->base.hdev;
1941 	short gyro_pitch_bias, gyro_pitch_plus, gyro_pitch_minus;
1942 	short gyro_yaw_bias, gyro_yaw_plus, gyro_yaw_minus;
1943 	short gyro_roll_bias, gyro_roll_plus, gyro_roll_minus;
1944 	short gyro_speed_plus, gyro_speed_minus;
1945 	short acc_x_plus, acc_x_minus;
1946 	short acc_y_plus, acc_y_minus;
1947 	short acc_z_plus, acc_z_minus;
1948 	int speed_2x;
1949 	int range_2g;
1950 	int ret = 0;
1951 	int i;
1952 	u8 *buf;
1953 
1954 	if (ds4->base.hdev->bus == BUS_USB) {
1955 		int retries;
1956 
1957 		buf = kzalloc(DS4_FEATURE_REPORT_CALIBRATION_SIZE, GFP_KERNEL);
1958 		if (!buf) {
1959 			ret = -ENOMEM;
1960 			goto transfer_failed;
1961 		}
1962 
1963 		/* We should normally receive the feature report data we asked
1964 		 * for, but hidraw applications such as Steam can issue feature
1965 		 * reports as well. In particular for Dongle reconnects, Steam
1966 		 * and this function are competing resulting in often receiving
1967 		 * data for a different HID report, so retry a few times.
1968 		 */
1969 		for (retries = 0; retries < 3; retries++) {
1970 			ret = ps_get_report(hdev, DS4_FEATURE_REPORT_CALIBRATION, buf,
1971 					    DS4_FEATURE_REPORT_CALIBRATION_SIZE, true);
1972 			if (ret) {
1973 				if (retries < 2) {
1974 					hid_warn(hdev,
1975 						 "Retrying DualShock 4 get calibration report (0x02) request\n");
1976 					continue;
1977 				}
1978 
1979 				hid_warn(hdev,
1980 					 "Failed to retrieve DualShock4 calibration info: %d\n",
1981 					 ret);
1982 				ret = -EILSEQ;
1983 				kfree(buf);
1984 				goto transfer_failed;
1985 			} else {
1986 				break;
1987 			}
1988 		}
1989 	} else { /* Bluetooth */
1990 		buf = kzalloc(DS4_FEATURE_REPORT_CALIBRATION_BT_SIZE, GFP_KERNEL);
1991 		if (!buf) {
1992 			ret = -ENOMEM;
1993 			goto transfer_failed;
1994 		}
1995 
1996 		ret = ps_get_report(hdev, DS4_FEATURE_REPORT_CALIBRATION_BT, buf,
1997 				    DS4_FEATURE_REPORT_CALIBRATION_BT_SIZE, true);
1998 
1999 		if (ret) {
2000 			hid_warn(hdev, "Failed to retrieve DualShock4 calibration info: %d\n", ret);
2001 			kfree(buf);
2002 			goto transfer_failed;
2003 		}
2004 	}
2005 
2006 	/* Transfer succeeded - parse the calibration data received. */
2007 	gyro_pitch_bias  = get_unaligned_le16(&buf[1]);
2008 	gyro_yaw_bias    = get_unaligned_le16(&buf[3]);
2009 	gyro_roll_bias   = get_unaligned_le16(&buf[5]);
2010 	if (ds4->base.hdev->bus == BUS_USB) {
2011 		gyro_pitch_plus  = get_unaligned_le16(&buf[7]);
2012 		gyro_pitch_minus = get_unaligned_le16(&buf[9]);
2013 		gyro_yaw_plus    = get_unaligned_le16(&buf[11]);
2014 		gyro_yaw_minus   = get_unaligned_le16(&buf[13]);
2015 		gyro_roll_plus   = get_unaligned_le16(&buf[15]);
2016 		gyro_roll_minus  = get_unaligned_le16(&buf[17]);
2017 	} else {
2018 		/* BT + Dongle */
2019 		gyro_pitch_plus  = get_unaligned_le16(&buf[7]);
2020 		gyro_yaw_plus    = get_unaligned_le16(&buf[9]);
2021 		gyro_roll_plus   = get_unaligned_le16(&buf[11]);
2022 		gyro_pitch_minus = get_unaligned_le16(&buf[13]);
2023 		gyro_yaw_minus   = get_unaligned_le16(&buf[15]);
2024 		gyro_roll_minus  = get_unaligned_le16(&buf[17]);
2025 	}
2026 	gyro_speed_plus  = get_unaligned_le16(&buf[19]);
2027 	gyro_speed_minus = get_unaligned_le16(&buf[21]);
2028 	acc_x_plus       = get_unaligned_le16(&buf[23]);
2029 	acc_x_minus      = get_unaligned_le16(&buf[25]);
2030 	acc_y_plus       = get_unaligned_le16(&buf[27]);
2031 	acc_y_minus      = get_unaligned_le16(&buf[29]);
2032 	acc_z_plus       = get_unaligned_le16(&buf[31]);
2033 	acc_z_minus      = get_unaligned_le16(&buf[33]);
2034 
2035 	/* Done parsing the buffer, so let's free it. */
2036 	kfree(buf);
2037 
2038 	/*
2039 	 * Set gyroscope calibration and normalization parameters.
2040 	 * Data values will be normalized to 1/DS4_GYRO_RES_PER_DEG_S degree/s.
2041 	 */
2042 	speed_2x = (gyro_speed_plus + gyro_speed_minus);
2043 	ds4->gyro_calib_data[0].abs_code = ABS_RX;
2044 	ds4->gyro_calib_data[0].bias = 0;
2045 	ds4->gyro_calib_data[0].sens_numer = speed_2x * DS4_GYRO_RES_PER_DEG_S;
2046 	ds4->gyro_calib_data[0].sens_denom = abs(gyro_pitch_plus - gyro_pitch_bias) +
2047 			abs(gyro_pitch_minus - gyro_pitch_bias);
2048 
2049 	ds4->gyro_calib_data[1].abs_code = ABS_RY;
2050 	ds4->gyro_calib_data[1].bias = 0;
2051 	ds4->gyro_calib_data[1].sens_numer = speed_2x * DS4_GYRO_RES_PER_DEG_S;
2052 	ds4->gyro_calib_data[1].sens_denom = abs(gyro_yaw_plus - gyro_yaw_bias) +
2053 			abs(gyro_yaw_minus - gyro_yaw_bias);
2054 
2055 	ds4->gyro_calib_data[2].abs_code = ABS_RZ;
2056 	ds4->gyro_calib_data[2].bias = 0;
2057 	ds4->gyro_calib_data[2].sens_numer = speed_2x * DS4_GYRO_RES_PER_DEG_S;
2058 	ds4->gyro_calib_data[2].sens_denom = abs(gyro_roll_plus - gyro_roll_bias) +
2059 			abs(gyro_roll_minus - gyro_roll_bias);
2060 
2061 	/*
2062 	 * Set accelerometer calibration and normalization parameters.
2063 	 * Data values will be normalized to 1/DS4_ACC_RES_PER_G g.
2064 	 */
2065 	range_2g = acc_x_plus - acc_x_minus;
2066 	ds4->accel_calib_data[0].abs_code = ABS_X;
2067 	ds4->accel_calib_data[0].bias = acc_x_plus - range_2g / 2;
2068 	ds4->accel_calib_data[0].sens_numer = 2 * DS4_ACC_RES_PER_G;
2069 	ds4->accel_calib_data[0].sens_denom = range_2g;
2070 
2071 	range_2g = acc_y_plus - acc_y_minus;
2072 	ds4->accel_calib_data[1].abs_code = ABS_Y;
2073 	ds4->accel_calib_data[1].bias = acc_y_plus - range_2g / 2;
2074 	ds4->accel_calib_data[1].sens_numer = 2 * DS4_ACC_RES_PER_G;
2075 	ds4->accel_calib_data[1].sens_denom = range_2g;
2076 
2077 	range_2g = acc_z_plus - acc_z_minus;
2078 	ds4->accel_calib_data[2].abs_code = ABS_Z;
2079 	ds4->accel_calib_data[2].bias = acc_z_plus - range_2g / 2;
2080 	ds4->accel_calib_data[2].sens_numer = 2 * DS4_ACC_RES_PER_G;
2081 	ds4->accel_calib_data[2].sens_denom = range_2g;
2082 
2083 transfer_failed:
2084 	/*
2085 	 * Sanity check gyro calibration data. This is needed to prevent crashes
2086 	 * during report handling of virtual, clone or broken devices not implementing
2087 	 * calibration data properly.
2088 	 */
2089 	for (i = 0; i < ARRAY_SIZE(ds4->gyro_calib_data); i++) {
2090 		if (ds4->gyro_calib_data[i].sens_denom == 0) {
2091 			ds4->gyro_calib_data[i].abs_code = ABS_RX + i;
2092 			hid_warn(hdev,
2093 				 "Invalid gyro calibration data for axis (%d), disabling calibration.",
2094 				 ds4->gyro_calib_data[i].abs_code);
2095 			ds4->gyro_calib_data[i].bias = 0;
2096 			ds4->gyro_calib_data[i].sens_numer = DS4_GYRO_RANGE;
2097 			ds4->gyro_calib_data[i].sens_denom = S16_MAX;
2098 		}
2099 	}
2100 
2101 	/*
2102 	 * Sanity check accelerometer calibration data. This is needed to prevent crashes
2103 	 * during report handling of virtual, clone or broken devices not implementing calibration
2104 	 * data properly.
2105 	 */
2106 	for (i = 0; i < ARRAY_SIZE(ds4->accel_calib_data); i++) {
2107 		if (ds4->accel_calib_data[i].sens_denom == 0) {
2108 			ds4->accel_calib_data[i].abs_code = ABS_X + i;
2109 			hid_warn(hdev,
2110 				 "Invalid accelerometer calibration data for axis (%d), disabling calibration.",
2111 				 ds4->accel_calib_data[i].abs_code);
2112 			ds4->accel_calib_data[i].bias = 0;
2113 			ds4->accel_calib_data[i].sens_numer = DS4_ACC_RANGE;
2114 			ds4->accel_calib_data[i].sens_denom = S16_MAX;
2115 		}
2116 	}
2117 
2118 	return ret;
2119 }
2120 
2121 static int dualshock4_get_firmware_info(struct dualshock4 *ds4)
2122 {
2123 	u8 *buf;
2124 	int ret;
2125 
2126 	buf = kzalloc(DS4_FEATURE_REPORT_FIRMWARE_INFO_SIZE, GFP_KERNEL);
2127 	if (!buf)
2128 		return -ENOMEM;
2129 
2130 	/* Note USB and BT support the same feature report, but this report
2131 	 * lacks CRC support, so must be disabled in ps_get_report.
2132 	 */
2133 	ret = ps_get_report(ds4->base.hdev, DS4_FEATURE_REPORT_FIRMWARE_INFO, buf,
2134 			    DS4_FEATURE_REPORT_FIRMWARE_INFO_SIZE, false);
2135 	if (ret) {
2136 		hid_err(ds4->base.hdev, "Failed to retrieve DualShock4 firmware info: %d\n", ret);
2137 		goto err_free;
2138 	}
2139 
2140 	ds4->base.hw_version = get_unaligned_le16(&buf[35]);
2141 	ds4->base.fw_version = get_unaligned_le16(&buf[41]);
2142 
2143 err_free:
2144 	kfree(buf);
2145 	return ret;
2146 }
2147 
2148 static int dualshock4_get_mac_address(struct dualshock4 *ds4)
2149 {
2150 	struct hid_device *hdev = ds4->base.hdev;
2151 	u8 *buf;
2152 	int ret = 0;
2153 
2154 	if (hdev->bus == BUS_USB) {
2155 		buf = kzalloc(DS4_FEATURE_REPORT_PAIRING_INFO_SIZE, GFP_KERNEL);
2156 		if (!buf)
2157 			return -ENOMEM;
2158 
2159 		ret = ps_get_report(hdev, DS4_FEATURE_REPORT_PAIRING_INFO, buf,
2160 				    DS4_FEATURE_REPORT_PAIRING_INFO_SIZE, false);
2161 		if (ret) {
2162 			hid_err(hdev, "Failed to retrieve DualShock4 pairing info: %d\n", ret);
2163 			goto err_free;
2164 		}
2165 
2166 		memcpy(ds4->base.mac_address, &buf[1], sizeof(ds4->base.mac_address));
2167 	} else {
2168 		/* Rely on HIDP for Bluetooth */
2169 		if (strlen(hdev->uniq) != 17)
2170 			return -EINVAL;
2171 
2172 		ret = sscanf(hdev->uniq, "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx",
2173 			     &ds4->base.mac_address[5], &ds4->base.mac_address[4],
2174 			     &ds4->base.mac_address[3], &ds4->base.mac_address[2],
2175 			     &ds4->base.mac_address[1], &ds4->base.mac_address[0]);
2176 
2177 		if (ret != sizeof(ds4->base.mac_address))
2178 			return -EINVAL;
2179 
2180 		return 0;
2181 	}
2182 
2183 err_free:
2184 	kfree(buf);
2185 	return ret;
2186 }
2187 
2188 static enum led_brightness dualshock4_led_get_brightness(struct led_classdev *led)
2189 {
2190 	struct hid_device *hdev = to_hid_device(led->dev->parent);
2191 	struct dualshock4 *ds4 = hid_get_drvdata(hdev);
2192 	unsigned int led_index;
2193 
2194 	led_index = led - ds4->lightbar_leds;
2195 	switch (led_index) {
2196 	case 0:
2197 		return ds4->lightbar_red;
2198 	case 1:
2199 		return ds4->lightbar_green;
2200 	case 2:
2201 		return ds4->lightbar_blue;
2202 	case 3:
2203 		return ds4->lightbar_enabled;
2204 	}
2205 
2206 	return -1;
2207 }
2208 
2209 static int dualshock4_led_set_blink(struct led_classdev *led, unsigned long *delay_on,
2210 				    unsigned long *delay_off)
2211 {
2212 	struct hid_device *hdev = to_hid_device(led->dev->parent);
2213 	struct dualshock4 *ds4 = hid_get_drvdata(hdev);
2214 
2215 	scoped_guard(spinlock_irqsave, &ds4->base.lock) {
2216 		if (!*delay_on && !*delay_off) {
2217 			/* Default to 1 Hz (50 centiseconds on, 50 centiseconds off). */
2218 			ds4->lightbar_blink_on = 50;
2219 			ds4->lightbar_blink_off = 50;
2220 		} else {
2221 			/* Blink delays in centiseconds. */
2222 			ds4->lightbar_blink_on = min_t(unsigned long, *delay_on / 10,
2223 						       DS4_LIGHTBAR_MAX_BLINK);
2224 			ds4->lightbar_blink_off = min_t(unsigned long, *delay_off / 10,
2225 							DS4_LIGHTBAR_MAX_BLINK);
2226 		}
2227 
2228 		ds4->update_lightbar_blink = true;
2229 	}
2230 
2231 	dualshock4_schedule_work(ds4);
2232 
2233 	/* Report scaled values back to LED subsystem */
2234 	*delay_on = ds4->lightbar_blink_on * 10;
2235 	*delay_off = ds4->lightbar_blink_off * 10;
2236 
2237 	return 0;
2238 }
2239 
2240 static int dualshock4_led_set_brightness(struct led_classdev *led, enum led_brightness value)
2241 {
2242 	struct hid_device *hdev = to_hid_device(led->dev->parent);
2243 	struct dualshock4 *ds4 = hid_get_drvdata(hdev);
2244 	unsigned int led_index;
2245 
2246 	scoped_guard(spinlock_irqsave, &ds4->base.lock) {
2247 		led_index = led - ds4->lightbar_leds;
2248 		switch (led_index) {
2249 		case 0:
2250 			ds4->lightbar_red = value;
2251 			break;
2252 		case 1:
2253 			ds4->lightbar_green = value;
2254 			break;
2255 		case 2:
2256 			ds4->lightbar_blue = value;
2257 			break;
2258 		case 3:
2259 			ds4->lightbar_enabled = !!value;
2260 
2261 			/* brightness = 0 also cancels blinking in Linux. */
2262 			if (!ds4->lightbar_enabled) {
2263 				ds4->lightbar_blink_off = 0;
2264 				ds4->lightbar_blink_on = 0;
2265 				ds4->update_lightbar_blink = true;
2266 			}
2267 		}
2268 
2269 		ds4->update_lightbar = true;
2270 	}
2271 
2272 	dualshock4_schedule_work(ds4);
2273 
2274 	return 0;
2275 }
2276 
2277 static void dualshock4_init_output_report(struct dualshock4 *ds4,
2278 					  struct dualshock4_output_report *rp, void *buf)
2279 {
2280 	struct hid_device *hdev = ds4->base.hdev;
2281 
2282 	if (hdev->bus == BUS_BLUETOOTH) {
2283 		struct dualshock4_output_report_bt *bt = buf;
2284 
2285 		memset(bt, 0, sizeof(*bt));
2286 		bt->report_id = DS4_OUTPUT_REPORT_BT;
2287 
2288 		rp->data = buf;
2289 		rp->len = sizeof(*bt);
2290 		rp->bt = bt;
2291 		rp->usb = NULL;
2292 		rp->common = &bt->common;
2293 	} else { /* USB */
2294 		struct dualshock4_output_report_usb *usb = buf;
2295 
2296 		memset(usb, 0, sizeof(*usb));
2297 		usb->report_id = DS4_OUTPUT_REPORT_USB;
2298 
2299 		rp->data = buf;
2300 		rp->len = sizeof(*usb);
2301 		rp->bt = NULL;
2302 		rp->usb = usb;
2303 		rp->common = &usb->common;
2304 	}
2305 }
2306 
2307 static void dualshock4_output_worker(struct work_struct *work)
2308 {
2309 	struct dualshock4 *ds4 = container_of(work, struct dualshock4, output_worker);
2310 	struct dualshock4_output_report report;
2311 	struct dualshock4_output_report_common *common;
2312 
2313 	dualshock4_init_output_report(ds4, &report, ds4->output_report_dmabuf);
2314 	common = report.common;
2315 
2316 	scoped_guard(spinlock_irqsave, &ds4->base.lock) {
2317 		/*
2318 		 * Some 3rd party gamepads expect updates to rumble and lightbar
2319 		 * together, and setting one may cancel the other.
2320 		 *
2321 		 * Let's maximise compatibility by always sending rumble and lightbar
2322 		 * updates together, even when only one has been scheduled, resulting
2323 		 * in:
2324 		 *
2325 		 *   ds4->valid_flag0 >= 0x03
2326 		 *
2327 		 * Hopefully this will maximise compatibility with third-party pads.
2328 		 *
2329 		 * Any further update bits, such as 0x04 for lightbar blinking, will
2330 		 * be or'd on top of this like before.
2331 		 */
2332 		if (ds4->update_rumble || ds4->update_lightbar) {
2333 			ds4->update_rumble = true; /* 0x01 */
2334 			ds4->update_lightbar = true; /* 0x02 */
2335 		}
2336 
2337 		if (ds4->update_rumble) {
2338 			/* Select classic rumble style haptics and enable it. */
2339 			common->valid_flag0 |= DS4_OUTPUT_VALID_FLAG0_MOTOR;
2340 			common->motor_left = ds4->motor_left;
2341 			common->motor_right = ds4->motor_right;
2342 			ds4->update_rumble = false;
2343 		}
2344 
2345 		if (ds4->update_lightbar) {
2346 			common->valid_flag0 |= DS4_OUTPUT_VALID_FLAG0_LED;
2347 			/* Compatible behavior with hid-sony, which used a dummy global LED to
2348 			 * allow enabling/disabling the lightbar. The global LED maps to
2349 			 * lightbar_enabled.
2350 			 */
2351 			common->lightbar_red = ds4->lightbar_enabled ? ds4->lightbar_red : 0;
2352 			common->lightbar_green = ds4->lightbar_enabled ? ds4->lightbar_green : 0;
2353 			common->lightbar_blue = ds4->lightbar_enabled ? ds4->lightbar_blue : 0;
2354 			ds4->update_lightbar = false;
2355 		}
2356 
2357 		if (ds4->update_lightbar_blink) {
2358 			common->valid_flag0 |= DS4_OUTPUT_VALID_FLAG0_LED_BLINK;
2359 			common->lightbar_blink_on = ds4->lightbar_blink_on;
2360 			common->lightbar_blink_off = ds4->lightbar_blink_off;
2361 			ds4->update_lightbar_blink = false;
2362 		}
2363 	}
2364 
2365 	/* Bluetooth packets need additional flags as well as a CRC in the last 4 bytes. */
2366 	if (report.bt) {
2367 		u32 crc;
2368 		u8 seed = PS_OUTPUT_CRC32_SEED;
2369 
2370 		/* Hardware control flags need to set to let the device know
2371 		 * there is HID data as well as CRC.
2372 		 */
2373 		report.bt->hw_control = DS4_OUTPUT_HWCTL_HID | DS4_OUTPUT_HWCTL_CRC32;
2374 
2375 		if (ds4->update_bt_poll_interval) {
2376 			report.bt->hw_control |= ds4->bt_poll_interval;
2377 			ds4->update_bt_poll_interval = false;
2378 		}
2379 
2380 		crc = crc32_le(0xFFFFFFFF, &seed, 1);
2381 		crc = ~crc32_le(crc, report.data, report.len - 4);
2382 
2383 		report.bt->crc32 = cpu_to_le32(crc);
2384 	}
2385 
2386 	hid_hw_output_report(ds4->base.hdev, report.data, report.len);
2387 }
2388 
2389 static int dualshock4_parse_report(struct ps_device *ps_dev, struct hid_report *report,
2390 				   u8 *data, int size)
2391 {
2392 	struct hid_device *hdev = ps_dev->hdev;
2393 	struct dualshock4 *ds4 = container_of(ps_dev, struct dualshock4, base);
2394 	struct dualshock4_input_report_common *ds4_report;
2395 	struct dualshock4_touch_report *touch_reports;
2396 	u8 battery_capacity, num_touch_reports, value;
2397 	int battery_status, i, j;
2398 	u16 sensor_timestamp;
2399 	bool is_minimal = false;
2400 
2401 	/*
2402 	 * DualShock4 in USB uses the full HID report for reportID 1, but
2403 	 * Bluetooth uses a minimal HID report for reportID 1 and reports
2404 	 * the full report using reportID 17.
2405 	 */
2406 	if (hdev->bus == BUS_USB && report->id == DS4_INPUT_REPORT_USB &&
2407 	    size == DS4_INPUT_REPORT_USB_SIZE) {
2408 		struct dualshock4_input_report_usb *usb =
2409 			(struct dualshock4_input_report_usb *)data;
2410 
2411 		if (usb->num_touch_reports > ARRAY_SIZE(usb->touch_reports)) {
2412 			hid_err(hdev, "DualShock4 USB input report has invalid num_touch_reports=%d\n",
2413 				usb->num_touch_reports);
2414 			return -EINVAL;
2415 		}
2416 
2417 		ds4_report = &usb->common;
2418 		num_touch_reports = min_t(u8, usb->num_touch_reports,
2419 					  ARRAY_SIZE(usb->touch_reports));
2420 		touch_reports = usb->touch_reports;
2421 	} else if (hdev->bus == BUS_BLUETOOTH && report->id == DS4_INPUT_REPORT_BT &&
2422 		   size == DS4_INPUT_REPORT_BT_SIZE) {
2423 		struct dualshock4_input_report_bt *bt = (struct dualshock4_input_report_bt *)data;
2424 		u32 report_crc = get_unaligned_le32(&bt->crc32);
2425 
2426 		/* Last 4 bytes of input report contains CRC. */
2427 		if (!ps_check_crc32(PS_INPUT_CRC32_SEED, data, size - 4, report_crc)) {
2428 			hid_err(hdev, "DualShock4 input CRC's check failed\n");
2429 			return -EILSEQ;
2430 		}
2431 
2432 		if (bt->num_touch_reports > ARRAY_SIZE(bt->touch_reports)) {
2433 			hid_err(hdev, "DualShock4 BT input report has invalid num_touch_reports=%d\n",
2434 				bt->num_touch_reports);
2435 			return -EINVAL;
2436 		}
2437 
2438 		ds4_report = &bt->common;
2439 		num_touch_reports = min_t(u8, bt->num_touch_reports,
2440 					  ARRAY_SIZE(bt->touch_reports));
2441 		touch_reports = bt->touch_reports;
2442 	} else if (hdev->bus == BUS_BLUETOOTH &&
2443 		   report->id == DS4_INPUT_REPORT_BT_MINIMAL &&
2444 			 size == DS4_INPUT_REPORT_BT_MINIMAL_SIZE) {
2445 		/* Some third-party pads never switch to the full 0x11 report.
2446 		 * The short 0x01 report is 10 bytes long:
2447 		 *   u8 report_id == 0x01
2448 		 *   u8 first_bytes_of_full_report[9]
2449 		 * So let's reuse the full report parser, and stop it after
2450 		 * parsing the buttons.
2451 		 */
2452 		ds4_report = (struct dualshock4_input_report_common *)&data[1];
2453 		is_minimal = true;
2454 	} else {
2455 		hid_err(hdev, "Unhandled reportID=%d\n", report->id);
2456 		return -1;
2457 	}
2458 
2459 	input_report_abs(ds4->gamepad, ABS_X,  ds4_report->x);
2460 	input_report_abs(ds4->gamepad, ABS_Y,  ds4_report->y);
2461 	input_report_abs(ds4->gamepad, ABS_RX, ds4_report->rx);
2462 	input_report_abs(ds4->gamepad, ABS_RY, ds4_report->ry);
2463 	input_report_abs(ds4->gamepad, ABS_Z,  ds4_report->z);
2464 	input_report_abs(ds4->gamepad, ABS_RZ, ds4_report->rz);
2465 
2466 	value = ds4_report->buttons[0] & DS_BUTTONS0_HAT_SWITCH;
2467 	if (value >= ARRAY_SIZE(ps_gamepad_hat_mapping))
2468 		value = 8; /* center */
2469 	input_report_abs(ds4->gamepad, ABS_HAT0X, ps_gamepad_hat_mapping[value].x);
2470 	input_report_abs(ds4->gamepad, ABS_HAT0Y, ps_gamepad_hat_mapping[value].y);
2471 
2472 	input_report_key(ds4->gamepad, BTN_WEST,   ds4_report->buttons[0] & DS_BUTTONS0_SQUARE);
2473 	input_report_key(ds4->gamepad, BTN_SOUTH,  ds4_report->buttons[0] & DS_BUTTONS0_CROSS);
2474 	input_report_key(ds4->gamepad, BTN_EAST,   ds4_report->buttons[0] & DS_BUTTONS0_CIRCLE);
2475 	input_report_key(ds4->gamepad, BTN_NORTH,  ds4_report->buttons[0] & DS_BUTTONS0_TRIANGLE);
2476 	input_report_key(ds4->gamepad, BTN_TL,     ds4_report->buttons[1] & DS_BUTTONS1_L1);
2477 	input_report_key(ds4->gamepad, BTN_TR,     ds4_report->buttons[1] & DS_BUTTONS1_R1);
2478 	input_report_key(ds4->gamepad, BTN_TL2,    ds4_report->buttons[1] & DS_BUTTONS1_L2);
2479 	input_report_key(ds4->gamepad, BTN_TR2,    ds4_report->buttons[1] & DS_BUTTONS1_R2);
2480 	input_report_key(ds4->gamepad, BTN_SELECT, ds4_report->buttons[1] & DS_BUTTONS1_CREATE);
2481 	input_report_key(ds4->gamepad, BTN_START,  ds4_report->buttons[1] & DS_BUTTONS1_OPTIONS);
2482 	input_report_key(ds4->gamepad, BTN_THUMBL, ds4_report->buttons[1] & DS_BUTTONS1_L3);
2483 	input_report_key(ds4->gamepad, BTN_THUMBR, ds4_report->buttons[1] & DS_BUTTONS1_R3);
2484 	input_report_key(ds4->gamepad, BTN_MODE,   ds4_report->buttons[2] & DS_BUTTONS2_PS_HOME);
2485 	input_sync(ds4->gamepad);
2486 
2487 	if (is_minimal)
2488 		return 0;
2489 
2490 	/* Parse and calibrate gyroscope data. */
2491 	for (i = 0; i < ARRAY_SIZE(ds4_report->gyro); i++) {
2492 		int raw_data = (short)le16_to_cpu(ds4_report->gyro[i]);
2493 		int calib_data = mult_frac(ds4->gyro_calib_data[i].sens_numer,
2494 					   raw_data, ds4->gyro_calib_data[i].sens_denom);
2495 
2496 		input_report_abs(ds4->sensors, ds4->gyro_calib_data[i].abs_code, calib_data);
2497 	}
2498 
2499 	/* Parse and calibrate accelerometer data. */
2500 	for (i = 0; i < ARRAY_SIZE(ds4_report->accel); i++) {
2501 		int raw_data = (short)le16_to_cpu(ds4_report->accel[i]);
2502 		int calib_data = mult_frac(ds4->accel_calib_data[i].sens_numer,
2503 					   raw_data - ds4->accel_calib_data[i].bias,
2504 					   ds4->accel_calib_data[i].sens_denom);
2505 
2506 		input_report_abs(ds4->sensors, ds4->accel_calib_data[i].abs_code, calib_data);
2507 	}
2508 
2509 	/* Convert timestamp (in 5.33us unit) to timestamp_us */
2510 	sensor_timestamp = le16_to_cpu(ds4_report->sensor_timestamp);
2511 	if (!ds4->sensor_timestamp_initialized) {
2512 		ds4->sensor_timestamp_us = DIV_ROUND_CLOSEST(sensor_timestamp * 16, 3);
2513 		ds4->sensor_timestamp_initialized = true;
2514 	} else {
2515 		u16 delta;
2516 
2517 		if (ds4->prev_sensor_timestamp > sensor_timestamp)
2518 			delta = (U16_MAX - ds4->prev_sensor_timestamp + sensor_timestamp + 1);
2519 		else
2520 			delta = sensor_timestamp - ds4->prev_sensor_timestamp;
2521 		ds4->sensor_timestamp_us += DIV_ROUND_CLOSEST(delta * 16, 3);
2522 	}
2523 	ds4->prev_sensor_timestamp = sensor_timestamp;
2524 	input_event(ds4->sensors, EV_MSC, MSC_TIMESTAMP, ds4->sensor_timestamp_us);
2525 	input_sync(ds4->sensors);
2526 
2527 	for (i = 0; i < num_touch_reports; i++) {
2528 		struct dualshock4_touch_report *touch_report = &touch_reports[i];
2529 
2530 		for (j = 0; j < ARRAY_SIZE(touch_report->points); j++) {
2531 			struct dualshock4_touch_point *point = &touch_report->points[j];
2532 			bool active = (point->contact & DS4_TOUCH_POINT_INACTIVE) ? false : true;
2533 
2534 			input_mt_slot(ds4->touchpad, j);
2535 			input_mt_report_slot_state(ds4->touchpad, MT_TOOL_FINGER, active);
2536 
2537 			if (active) {
2538 				input_report_abs(ds4->touchpad, ABS_MT_POSITION_X,
2539 						 DS4_TOUCH_POINT_X(point->x_hi, point->x_lo));
2540 				input_report_abs(ds4->touchpad, ABS_MT_POSITION_Y,
2541 						 DS4_TOUCH_POINT_Y(point->y_hi, point->y_lo));
2542 			}
2543 		}
2544 		input_mt_sync_frame(ds4->touchpad);
2545 		input_sync(ds4->touchpad);
2546 	}
2547 	input_report_key(ds4->touchpad, BTN_LEFT, ds4_report->buttons[2] & DS_BUTTONS2_TOUCHPAD);
2548 
2549 	/*
2550 	 * Interpretation of the battery_capacity data depends on the cable state.
2551 	 * When no cable is connected (bit4 is 0):
2552 	 * - 0:10: percentage in units of 10%.
2553 	 * When a cable is plugged in:
2554 	 * - 0-10: percentage in units of 10%.
2555 	 * - 11: battery is full
2556 	 * - 14: not charging due to Voltage or temperature error
2557 	 * - 15: charge error
2558 	 */
2559 	if (ds4_report->status[0] & DS4_STATUS0_CABLE_STATE) {
2560 		u8 battery_data = ds4_report->status[0] & DS4_STATUS0_BATTERY_CAPACITY;
2561 
2562 		if (battery_data < 10) {
2563 			/* Take the mid-point for each battery capacity value,
2564 			 * because on the hardware side 0 = 0-9%, 1=10-19%, etc.
2565 			 * This matches official platform behavior, which does
2566 			 * the same.
2567 			 */
2568 			battery_capacity = battery_data * 10 + 5;
2569 			battery_status = POWER_SUPPLY_STATUS_CHARGING;
2570 		} else if (battery_data == 10) {
2571 			battery_capacity = 100;
2572 			battery_status = POWER_SUPPLY_STATUS_CHARGING;
2573 		} else if (battery_data == DS4_BATTERY_STATUS_FULL) {
2574 			battery_capacity = 100;
2575 			battery_status = POWER_SUPPLY_STATUS_FULL;
2576 		} else { /* 14, 15 and undefined values */
2577 			battery_capacity = 0;
2578 			battery_status = POWER_SUPPLY_STATUS_UNKNOWN;
2579 		}
2580 	} else {
2581 		u8 battery_data = ds4_report->status[0] & DS4_STATUS0_BATTERY_CAPACITY;
2582 
2583 		if (battery_data < 10)
2584 			battery_capacity = battery_data * 10 + 5;
2585 		else /* 10 */
2586 			battery_capacity = 100;
2587 
2588 		battery_status = POWER_SUPPLY_STATUS_DISCHARGING;
2589 	}
2590 
2591 	scoped_guard(spinlock_irqsave, &ps_dev->lock) {
2592 		ps_dev->battery_capacity = battery_capacity;
2593 		ps_dev->battery_status = battery_status;
2594 	}
2595 
2596 	return 0;
2597 }
2598 
2599 static int dualshock4_dongle_parse_report(struct ps_device *ps_dev, struct hid_report *report,
2600 					  u8 *data, int size)
2601 {
2602 	struct dualshock4 *ds4 = container_of(ps_dev, struct dualshock4, base);
2603 	bool connected = false;
2604 
2605 	/* The dongle reports data using the main USB report (0x1) no matter whether a controller
2606 	 * is connected with mostly zeros. The report does contain dongle status, which we use to
2607 	 * determine if a controller is connected and if so we forward to the regular DualShock4
2608 	 * parsing code.
2609 	 */
2610 	if (data[0] == DS4_INPUT_REPORT_USB && size == DS4_INPUT_REPORT_USB_SIZE) {
2611 		struct dualshock4_input_report_common *ds4_report =
2612 			(struct dualshock4_input_report_common *)&data[1];
2613 
2614 		connected = ds4_report->status[1] & DS4_STATUS1_DONGLE_STATE ? false : true;
2615 
2616 		if (ds4->dongle_state == DONGLE_DISCONNECTED && connected) {
2617 			hid_info(ps_dev->hdev, "DualShock 4 USB dongle: controller connected\n");
2618 
2619 			dualshock4_set_default_lightbar_colors(ds4);
2620 
2621 			scoped_guard(spinlock_irqsave, &ps_dev->lock)
2622 				ds4->dongle_state = DONGLE_CALIBRATING;
2623 
2624 			schedule_work(&ds4->dongle_hotplug_worker);
2625 
2626 			/* Don't process the report since we don't have
2627 			 * calibration data, but let hidraw have it anyway.
2628 			 */
2629 			return 0;
2630 		} else if ((ds4->dongle_state == DONGLE_CONNECTED ||
2631 			    ds4->dongle_state == DONGLE_DISABLED) && !connected) {
2632 			hid_info(ps_dev->hdev, "DualShock 4 USB dongle: controller disconnected\n");
2633 
2634 			scoped_guard(spinlock_irqsave, &ps_dev->lock)
2635 				ds4->dongle_state = DONGLE_DISCONNECTED;
2636 
2637 			/* Return 0, so hidraw can get the report. */
2638 			return 0;
2639 		} else if (ds4->dongle_state == DONGLE_CALIBRATING ||
2640 			   ds4->dongle_state == DONGLE_DISABLED ||
2641 			   ds4->dongle_state == DONGLE_DISCONNECTED) {
2642 			/* Return 0, so hidraw can get the report. */
2643 			return 0;
2644 		}
2645 	}
2646 
2647 	if (connected)
2648 		return dualshock4_parse_report(ps_dev, report, data, size);
2649 
2650 	return 0;
2651 }
2652 
2653 static int dualshock4_play_effect(struct input_dev *dev, void *data, struct ff_effect *effect)
2654 {
2655 	struct hid_device *hdev = input_get_drvdata(dev);
2656 	struct dualshock4 *ds4 = hid_get_drvdata(hdev);
2657 
2658 	if (effect->type != FF_RUMBLE)
2659 		return 0;
2660 
2661 	scoped_guard(spinlock_irqsave, &ds4->base.lock) {
2662 		ds4->update_rumble = true;
2663 		ds4->motor_left = effect->u.rumble.strong_magnitude / 256;
2664 		ds4->motor_right = effect->u.rumble.weak_magnitude / 256;
2665 	}
2666 
2667 	dualshock4_schedule_work(ds4);
2668 	return 0;
2669 }
2670 
2671 static void dualshock4_remove(struct ps_device *ps_dev)
2672 {
2673 	struct dualshock4 *ds4 = container_of(ps_dev, struct dualshock4, base);
2674 
2675 	scoped_guard(spinlock_irqsave, &ds4->base.lock)
2676 		ds4->output_worker_initialized = false;
2677 
2678 	cancel_work_sync(&ds4->output_worker);
2679 
2680 	if (ps_dev->hdev->product == USB_DEVICE_ID_SONY_PS4_CONTROLLER_DONGLE)
2681 		cancel_work_sync(&ds4->dongle_hotplug_worker);
2682 }
2683 
2684 static inline void dualshock4_schedule_work(struct dualshock4 *ds4)
2685 {
2686 	/* Using scoped_guard() instead of guard() to make sparse happy */
2687 	scoped_guard(spinlock_irqsave, &ds4->base.lock)
2688 		if (ds4->output_worker_initialized)
2689 			schedule_work(&ds4->output_worker);
2690 }
2691 
2692 static void dualshock4_set_bt_poll_interval(struct dualshock4 *ds4, u8 interval)
2693 {
2694 	ds4->bt_poll_interval = interval;
2695 	ds4->update_bt_poll_interval = true;
2696 	dualshock4_schedule_work(ds4);
2697 }
2698 
2699 /* Set default lightbar color based on player. */
2700 static void dualshock4_set_default_lightbar_colors(struct dualshock4 *ds4)
2701 {
2702 	/* Use same player colors as PlayStation 4.
2703 	 * Array of colors is in RGB.
2704 	 */
2705 	static const int player_colors[4][3] = {
2706 		{ 0x00, 0x00, 0x40 }, /* Blue */
2707 		{ 0x40, 0x00, 0x00 }, /* Red */
2708 		{ 0x00, 0x40, 0x00 }, /* Green */
2709 		{ 0x20, 0x00, 0x20 }  /* Pink */
2710 	};
2711 
2712 	u8 player_id = ds4->base.player_id % ARRAY_SIZE(player_colors);
2713 
2714 	ds4->lightbar_enabled = true;
2715 	ds4->lightbar_red = player_colors[player_id][0];
2716 	ds4->lightbar_green = player_colors[player_id][1];
2717 	ds4->lightbar_blue = player_colors[player_id][2];
2718 
2719 	ds4->update_lightbar = true;
2720 	dualshock4_schedule_work(ds4);
2721 }
2722 
2723 static struct ps_device *dualshock4_create(struct hid_device *hdev)
2724 {
2725 	struct dualshock4 *ds4;
2726 	struct ps_device *ps_dev;
2727 	u8 max_output_report_size;
2728 	int i, ret;
2729 
2730 	/* The DualShock4 has an RGB lightbar, which the original hid-sony driver
2731 	 * exposed as a set of 4 LEDs for the 3 color channels and a global control.
2732 	 * Ideally this should have used the multi-color LED class, which didn't exist
2733 	 * yet. In addition the driver used a naming scheme not compliant with the LED
2734 	 * naming spec by using "<mac_address>:<color>", which contained many colons.
2735 	 * We use a more compliant by using "<device_name>:<color>" name now. Ideally
2736 	 * would have been "<device_name>:<color>:indicator", but that would break
2737 	 * existing applications (e.g. Android). Nothing matches against MAC address.
2738 	 */
2739 	static const struct ps_led_info lightbar_leds_info[] = {
2740 		{ NULL, "red", 255, dualshock4_led_get_brightness,
2741 		  dualshock4_led_set_brightness },
2742 		{ NULL, "green", 255, dualshock4_led_get_brightness,
2743 		  dualshock4_led_set_brightness },
2744 		{ NULL, "blue", 255, dualshock4_led_get_brightness,
2745 		  dualshock4_led_set_brightness },
2746 		{ NULL, "global", 1, dualshock4_led_get_brightness,
2747 		  dualshock4_led_set_brightness, dualshock4_led_set_blink },
2748 	};
2749 
2750 	ds4 = devm_kzalloc(&hdev->dev, sizeof(*ds4), GFP_KERNEL);
2751 	if (!ds4)
2752 		return ERR_PTR(-ENOMEM);
2753 
2754 	/*
2755 	 * Patch version to allow userspace to distinguish between
2756 	 * hid-generic vs hid-playstation axis and button mapping.
2757 	 */
2758 	hdev->version |= HID_PLAYSTATION_VERSION_PATCH;
2759 
2760 	ps_dev = &ds4->base;
2761 	ps_dev->hdev = hdev;
2762 	spin_lock_init(&ps_dev->lock);
2763 	ps_dev->battery_capacity = 100; /* initial value until parse_report. */
2764 	ps_dev->battery_status = POWER_SUPPLY_STATUS_UNKNOWN;
2765 	ps_dev->parse_report = dualshock4_parse_report;
2766 	ps_dev->remove = dualshock4_remove;
2767 	INIT_WORK(&ds4->output_worker, dualshock4_output_worker);
2768 	ds4->output_worker_initialized = true;
2769 	hid_set_drvdata(hdev, ds4);
2770 
2771 	max_output_report_size = sizeof(struct dualshock4_output_report_bt);
2772 	ds4->output_report_dmabuf = devm_kzalloc(&hdev->dev, max_output_report_size, GFP_KERNEL);
2773 	if (!ds4->output_report_dmabuf)
2774 		return ERR_PTR(-ENOMEM);
2775 
2776 	if (hdev->product == USB_DEVICE_ID_SONY_PS4_CONTROLLER_DONGLE) {
2777 		ds4->dongle_state = DONGLE_DISCONNECTED;
2778 		INIT_WORK(&ds4->dongle_hotplug_worker, dualshock4_dongle_calibration_work);
2779 
2780 		/* Override parse report for dongle specific hotplug handling. */
2781 		ps_dev->parse_report = dualshock4_dongle_parse_report;
2782 	}
2783 
2784 	ret = dualshock4_get_mac_address(ds4);
2785 	if (ret) {
2786 		hid_err(hdev, "Failed to get MAC address from DualShock4\n");
2787 		return ERR_PTR(ret);
2788 	}
2789 	snprintf(hdev->uniq, sizeof(hdev->uniq), "%pMR", ds4->base.mac_address);
2790 
2791 	ret = dualshock4_get_firmware_info(ds4);
2792 	if (ret) {
2793 		hid_warn(hdev, "Failed to get firmware info from DualShock4\n");
2794 		hid_warn(hdev, "HW/FW version data in sysfs will be invalid.\n");
2795 	}
2796 
2797 	ret = ps_devices_list_add(ps_dev);
2798 	if (ret)
2799 		return ERR_PTR(ret);
2800 
2801 	ret = dualshock4_get_calibration_data(ds4);
2802 	if (ret) {
2803 		hid_warn(hdev, "Failed to get calibration data from DualShock4\n");
2804 		hid_warn(hdev, "Gyroscope and accelerometer will be inaccurate.\n");
2805 	}
2806 
2807 	ds4->gamepad = ps_gamepad_create(hdev, dualshock4_play_effect);
2808 	if (IS_ERR(ds4->gamepad)) {
2809 		ret = PTR_ERR(ds4->gamepad);
2810 		goto err;
2811 	}
2812 
2813 	/* Use gamepad input device name as primary device name for e.g. LEDs */
2814 	ps_dev->input_dev_name = dev_name(&ds4->gamepad->dev);
2815 
2816 	ds4->sensors = ps_sensors_create(hdev, DS4_ACC_RANGE, DS4_ACC_RES_PER_G,
2817 					 DS4_GYRO_RANGE, DS4_GYRO_RES_PER_DEG_S);
2818 	if (IS_ERR(ds4->sensors)) {
2819 		ret = PTR_ERR(ds4->sensors);
2820 		goto err;
2821 	}
2822 
2823 	ds4->touchpad = ps_touchpad_create(hdev, DS4_TOUCHPAD_WIDTH, DS4_TOUCHPAD_HEIGHT, 2);
2824 	if (IS_ERR(ds4->touchpad)) {
2825 		ret = PTR_ERR(ds4->touchpad);
2826 		goto err;
2827 	}
2828 
2829 	ret = ps_device_register_battery(ps_dev);
2830 	if (ret)
2831 		goto err;
2832 
2833 	for (i = 0; i < ARRAY_SIZE(lightbar_leds_info); i++) {
2834 		const struct ps_led_info *led_info = &lightbar_leds_info[i];
2835 
2836 		ret = ps_led_register(ps_dev, &ds4->lightbar_leds[i], led_info);
2837 		if (ret < 0)
2838 			goto err;
2839 	}
2840 
2841 	dualshock4_set_bt_poll_interval(ds4, DS4_BT_DEFAULT_POLL_INTERVAL_MS);
2842 
2843 	ret = ps_device_set_player_id(ps_dev);
2844 	if (ret) {
2845 		hid_err(hdev, "Failed to assign player id for DualShock4: %d\n", ret);
2846 		goto err;
2847 	}
2848 
2849 	dualshock4_set_default_lightbar_colors(ds4);
2850 
2851 	/*
2852 	 * Reporting hardware and firmware is important as there are frequent updates, which
2853 	 * can change behavior.
2854 	 */
2855 	hid_info(hdev, "Registered DualShock4 controller hw_version=0x%08x fw_version=0x%08x\n",
2856 		 ds4->base.hw_version, ds4->base.fw_version);
2857 	return &ds4->base;
2858 
2859 err:
2860 	ps_devices_list_remove(ps_dev);
2861 	return ERR_PTR(ret);
2862 }
2863 
2864 static int ps_raw_event(struct hid_device *hdev, struct hid_report *report,
2865 			u8 *data, int size)
2866 {
2867 	struct ps_device *dev = hid_get_drvdata(hdev);
2868 
2869 	if (dev && dev->parse_report)
2870 		return dev->parse_report(dev, report, data, size);
2871 
2872 	return 0;
2873 }
2874 
2875 static int ps_probe(struct hid_device *hdev, const struct hid_device_id *id)
2876 {
2877 	struct ps_device *dev;
2878 	int ret;
2879 
2880 	ret = hid_parse(hdev);
2881 	if (ret) {
2882 		hid_err(hdev, "Parse failed\n");
2883 		return ret;
2884 	}
2885 
2886 	ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
2887 	if (ret) {
2888 		hid_err(hdev, "Failed to start HID device\n");
2889 		return ret;
2890 	}
2891 
2892 	ret = hid_hw_open(hdev);
2893 	if (ret) {
2894 		hid_err(hdev, "Failed to open HID device\n");
2895 		goto err_stop;
2896 	}
2897 
2898 	if (id->driver_data == PS_TYPE_PS4_DUALSHOCK4) {
2899 		dev = dualshock4_create(hdev);
2900 		if (IS_ERR(dev)) {
2901 			hid_err(hdev, "Failed to create dualshock4.\n");
2902 			ret = PTR_ERR(dev);
2903 			goto err_close;
2904 		}
2905 	} else if (id->driver_data == PS_TYPE_PS5_DUALSENSE) {
2906 		dev = dualsense_create(hdev);
2907 		if (IS_ERR(dev)) {
2908 			hid_err(hdev, "Failed to create dualsense.\n");
2909 			ret = PTR_ERR(dev);
2910 			goto err_close;
2911 		}
2912 	}
2913 
2914 	return ret;
2915 
2916 err_close:
2917 	hid_hw_close(hdev);
2918 err_stop:
2919 	hid_hw_stop(hdev);
2920 	return ret;
2921 }
2922 
2923 static void ps_remove(struct hid_device *hdev)
2924 {
2925 	struct ps_device *dev = hid_get_drvdata(hdev);
2926 
2927 	ps_devices_list_remove(dev);
2928 	ps_device_release_player_id(dev);
2929 
2930 	if (dev->remove)
2931 		dev->remove(dev);
2932 
2933 	hid_hw_close(hdev);
2934 	hid_hw_stop(hdev);
2935 }
2936 
2937 static const struct hid_device_id ps_devices[] = {
2938 	/* Sony DualShock 4 controllers for PS4 */
2939 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER),
2940 		.driver_data = PS_TYPE_PS4_DUALSHOCK4 },
2941 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER),
2942 		.driver_data = PS_TYPE_PS4_DUALSHOCK4 },
2943 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER_2),
2944 		.driver_data = PS_TYPE_PS4_DUALSHOCK4 },
2945 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER_2),
2946 		.driver_data = PS_TYPE_PS4_DUALSHOCK4 },
2947 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER_DONGLE),
2948 		.driver_data = PS_TYPE_PS4_DUALSHOCK4 },
2949 
2950 	/* Sony DualSense controllers for PS5 */
2951 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER),
2952 		.driver_data = PS_TYPE_PS5_DUALSENSE },
2953 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER),
2954 		.driver_data = PS_TYPE_PS5_DUALSENSE },
2955 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER_2),
2956 		.driver_data = PS_TYPE_PS5_DUALSENSE },
2957 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER_2),
2958 		.driver_data = PS_TYPE_PS5_DUALSENSE },
2959 	{ }
2960 };
2961 MODULE_DEVICE_TABLE(hid, ps_devices);
2962 
2963 static struct hid_driver ps_driver = {
2964 	.name		= "playstation",
2965 	.id_table	= ps_devices,
2966 	.probe		= ps_probe,
2967 	.remove		= ps_remove,
2968 	.raw_event	= ps_raw_event,
2969 	.driver = {
2970 		.dev_groups = ps_device_groups,
2971 	},
2972 };
2973 
2974 static int __init ps_init(void)
2975 {
2976 	return hid_register_driver(&ps_driver);
2977 }
2978 
2979 static void __exit ps_exit(void)
2980 {
2981 	hid_unregister_driver(&ps_driver);
2982 	ida_destroy(&ps_player_id_allocator);
2983 }
2984 
2985 module_init(ps_init);
2986 module_exit(ps_exit);
2987 
2988 MODULE_AUTHOR("Sony Interactive Entertainment");
2989 MODULE_DESCRIPTION("HID Driver for PlayStation peripherals.");
2990 MODULE_LICENSE("GPL");
2991