xref: /openbmc/linux/drivers/hid/hid-playstation.c (revision c4a11bf4)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  HID driver for Sony DualSense(TM) controller.
4  *
5  *  Copyright (c) 2020 Sony Interactive Entertainment
6  */
7 
8 #include <linux/bits.h>
9 #include <linux/crc32.h>
10 #include <linux/device.h>
11 #include <linux/hid.h>
12 #include <linux/idr.h>
13 #include <linux/input/mt.h>
14 #include <linux/leds.h>
15 #include <linux/led-class-multicolor.h>
16 #include <linux/module.h>
17 
18 #include <asm/unaligned.h>
19 
20 #include "hid-ids.h"
21 
22 /* List of connected playstation devices. */
23 static DEFINE_MUTEX(ps_devices_lock);
24 static LIST_HEAD(ps_devices_list);
25 
26 static DEFINE_IDA(ps_player_id_allocator);
27 
28 #define HID_PLAYSTATION_VERSION_PATCH 0x8000
29 
30 /* Base class for playstation devices. */
31 struct ps_device {
32 	struct list_head list;
33 	struct hid_device *hdev;
34 	spinlock_t lock;
35 
36 	uint32_t player_id;
37 
38 	struct power_supply_desc battery_desc;
39 	struct power_supply *battery;
40 	uint8_t battery_capacity;
41 	int battery_status;
42 
43 	const char *input_dev_name; /* Name of primary input device. */
44 	uint8_t mac_address[6]; /* Note: stored in little endian order. */
45 	uint32_t hw_version;
46 	uint32_t fw_version;
47 
48 	int (*parse_report)(struct ps_device *dev, struct hid_report *report, u8 *data, int size);
49 };
50 
51 /* Calibration data for playstation motion sensors. */
52 struct ps_calibration_data {
53 	int abs_code;
54 	short bias;
55 	int sens_numer;
56 	int sens_denom;
57 };
58 
59 struct ps_led_info {
60 	const char *name;
61 	const char *color;
62 	enum led_brightness (*brightness_get)(struct led_classdev *cdev);
63 	int (*brightness_set)(struct led_classdev *cdev, enum led_brightness);
64 };
65 
66 /* Seed values for DualShock4 / DualSense CRC32 for different report types. */
67 #define PS_INPUT_CRC32_SEED	0xA1
68 #define PS_OUTPUT_CRC32_SEED	0xA2
69 #define PS_FEATURE_CRC32_SEED	0xA3
70 
71 #define DS_INPUT_REPORT_USB			0x01
72 #define DS_INPUT_REPORT_USB_SIZE		64
73 #define DS_INPUT_REPORT_BT			0x31
74 #define DS_INPUT_REPORT_BT_SIZE			78
75 #define DS_OUTPUT_REPORT_USB			0x02
76 #define DS_OUTPUT_REPORT_USB_SIZE		63
77 #define DS_OUTPUT_REPORT_BT			0x31
78 #define DS_OUTPUT_REPORT_BT_SIZE		78
79 
80 #define DS_FEATURE_REPORT_CALIBRATION		0x05
81 #define DS_FEATURE_REPORT_CALIBRATION_SIZE	41
82 #define DS_FEATURE_REPORT_PAIRING_INFO		0x09
83 #define DS_FEATURE_REPORT_PAIRING_INFO_SIZE	20
84 #define DS_FEATURE_REPORT_FIRMWARE_INFO		0x20
85 #define DS_FEATURE_REPORT_FIRMWARE_INFO_SIZE	64
86 
87 /* Button masks for DualSense input report. */
88 #define DS_BUTTONS0_HAT_SWITCH	GENMASK(3, 0)
89 #define DS_BUTTONS0_SQUARE	BIT(4)
90 #define DS_BUTTONS0_CROSS	BIT(5)
91 #define DS_BUTTONS0_CIRCLE	BIT(6)
92 #define DS_BUTTONS0_TRIANGLE	BIT(7)
93 #define DS_BUTTONS1_L1		BIT(0)
94 #define DS_BUTTONS1_R1		BIT(1)
95 #define DS_BUTTONS1_L2		BIT(2)
96 #define DS_BUTTONS1_R2		BIT(3)
97 #define DS_BUTTONS1_CREATE	BIT(4)
98 #define DS_BUTTONS1_OPTIONS	BIT(5)
99 #define DS_BUTTONS1_L3		BIT(6)
100 #define DS_BUTTONS1_R3		BIT(7)
101 #define DS_BUTTONS2_PS_HOME	BIT(0)
102 #define DS_BUTTONS2_TOUCHPAD	BIT(1)
103 #define DS_BUTTONS2_MIC_MUTE	BIT(2)
104 
105 /* Status field of DualSense input report. */
106 #define DS_STATUS_BATTERY_CAPACITY	GENMASK(3, 0)
107 #define DS_STATUS_CHARGING		GENMASK(7, 4)
108 #define DS_STATUS_CHARGING_SHIFT	4
109 
110 /*
111  * Status of a DualSense touch point contact.
112  * Contact IDs, with highest bit set are 'inactive'
113  * and any associated data is then invalid.
114  */
115 #define DS_TOUCH_POINT_INACTIVE BIT(7)
116 
117  /* Magic value required in tag field of Bluetooth output report. */
118 #define DS_OUTPUT_TAG 0x10
119 /* Flags for DualSense output report. */
120 #define DS_OUTPUT_VALID_FLAG0_COMPATIBLE_VIBRATION BIT(0)
121 #define DS_OUTPUT_VALID_FLAG0_HAPTICS_SELECT BIT(1)
122 #define DS_OUTPUT_VALID_FLAG1_MIC_MUTE_LED_CONTROL_ENABLE BIT(0)
123 #define DS_OUTPUT_VALID_FLAG1_POWER_SAVE_CONTROL_ENABLE BIT(1)
124 #define DS_OUTPUT_VALID_FLAG1_LIGHTBAR_CONTROL_ENABLE BIT(2)
125 #define DS_OUTPUT_VALID_FLAG1_RELEASE_LEDS BIT(3)
126 #define DS_OUTPUT_VALID_FLAG1_PLAYER_INDICATOR_CONTROL_ENABLE BIT(4)
127 #define DS_OUTPUT_VALID_FLAG2_LIGHTBAR_SETUP_CONTROL_ENABLE BIT(1)
128 #define DS_OUTPUT_POWER_SAVE_CONTROL_MIC_MUTE BIT(4)
129 #define DS_OUTPUT_LIGHTBAR_SETUP_LIGHT_OUT BIT(1)
130 
131 /* DualSense hardware limits */
132 #define DS_ACC_RES_PER_G	8192
133 #define DS_ACC_RANGE		(4*DS_ACC_RES_PER_G)
134 #define DS_GYRO_RES_PER_DEG_S	1024
135 #define DS_GYRO_RANGE		(2048*DS_GYRO_RES_PER_DEG_S)
136 #define DS_TOUCHPAD_WIDTH	1920
137 #define DS_TOUCHPAD_HEIGHT	1080
138 
139 struct dualsense {
140 	struct ps_device base;
141 	struct input_dev *gamepad;
142 	struct input_dev *sensors;
143 	struct input_dev *touchpad;
144 
145 	/* Calibration data for accelerometer and gyroscope. */
146 	struct ps_calibration_data accel_calib_data[3];
147 	struct ps_calibration_data gyro_calib_data[3];
148 
149 	/* Timestamp for sensor data */
150 	bool sensor_timestamp_initialized;
151 	uint32_t prev_sensor_timestamp;
152 	uint32_t sensor_timestamp_us;
153 
154 	/* Compatible rumble state */
155 	bool update_rumble;
156 	uint8_t motor_left;
157 	uint8_t motor_right;
158 
159 	/* RGB lightbar */
160 	struct led_classdev_mc lightbar;
161 	bool update_lightbar;
162 	uint8_t lightbar_red;
163 	uint8_t lightbar_green;
164 	uint8_t lightbar_blue;
165 
166 	/* Microphone */
167 	bool update_mic_mute;
168 	bool mic_muted;
169 	bool last_btn_mic_state;
170 
171 	/* Player leds */
172 	bool update_player_leds;
173 	uint8_t player_leds_state;
174 	struct led_classdev player_leds[5];
175 
176 	struct work_struct output_worker;
177 	void *output_report_dmabuf;
178 	uint8_t output_seq; /* Sequence number for output report. */
179 };
180 
181 struct dualsense_touch_point {
182 	uint8_t contact;
183 	uint8_t x_lo;
184 	uint8_t x_hi:4, y_lo:4;
185 	uint8_t y_hi;
186 } __packed;
187 static_assert(sizeof(struct dualsense_touch_point) == 4);
188 
189 /* Main DualSense input report excluding any BT/USB specific headers. */
190 struct dualsense_input_report {
191 	uint8_t x, y;
192 	uint8_t rx, ry;
193 	uint8_t z, rz;
194 	uint8_t seq_number;
195 	uint8_t buttons[4];
196 	uint8_t reserved[4];
197 
198 	/* Motion sensors */
199 	__le16 gyro[3]; /* x, y, z */
200 	__le16 accel[3]; /* x, y, z */
201 	__le32 sensor_timestamp;
202 	uint8_t reserved2;
203 
204 	/* Touchpad */
205 	struct dualsense_touch_point points[2];
206 
207 	uint8_t reserved3[12];
208 	uint8_t status;
209 	uint8_t reserved4[10];
210 } __packed;
211 /* Common input report size shared equals the size of the USB report minus 1 byte for ReportID. */
212 static_assert(sizeof(struct dualsense_input_report) == DS_INPUT_REPORT_USB_SIZE - 1);
213 
214 /* Common data between DualSense BT/USB main output report. */
215 struct dualsense_output_report_common {
216 	uint8_t valid_flag0;
217 	uint8_t valid_flag1;
218 
219 	/* For DualShock 4 compatibility mode. */
220 	uint8_t motor_right;
221 	uint8_t motor_left;
222 
223 	/* Audio controls */
224 	uint8_t reserved[4];
225 	uint8_t mute_button_led;
226 
227 	uint8_t power_save_control;
228 	uint8_t reserved2[28];
229 
230 	/* LEDs and lightbar */
231 	uint8_t valid_flag2;
232 	uint8_t reserved3[2];
233 	uint8_t lightbar_setup;
234 	uint8_t led_brightness;
235 	uint8_t player_leds;
236 	uint8_t lightbar_red;
237 	uint8_t lightbar_green;
238 	uint8_t lightbar_blue;
239 } __packed;
240 static_assert(sizeof(struct dualsense_output_report_common) == 47);
241 
242 struct dualsense_output_report_bt {
243 	uint8_t report_id; /* 0x31 */
244 	uint8_t seq_tag;
245 	uint8_t tag;
246 	struct dualsense_output_report_common common;
247 	uint8_t reserved[24];
248 	__le32 crc32;
249 } __packed;
250 static_assert(sizeof(struct dualsense_output_report_bt) == DS_OUTPUT_REPORT_BT_SIZE);
251 
252 struct dualsense_output_report_usb {
253 	uint8_t report_id; /* 0x02 */
254 	struct dualsense_output_report_common common;
255 	uint8_t reserved[15];
256 } __packed;
257 static_assert(sizeof(struct dualsense_output_report_usb) == DS_OUTPUT_REPORT_USB_SIZE);
258 
259 /*
260  * The DualSense has a main output report used to control most features. It is
261  * largely the same between Bluetooth and USB except for different headers and CRC.
262  * This structure hide the differences between the two to simplify sending output reports.
263  */
264 struct dualsense_output_report {
265 	uint8_t *data; /* Start of data */
266 	uint8_t len; /* Size of output report */
267 
268 	/* Points to Bluetooth data payload in case for a Bluetooth report else NULL. */
269 	struct dualsense_output_report_bt *bt;
270 	/* Points to USB data payload in case for a USB report else NULL. */
271 	struct dualsense_output_report_usb *usb;
272 	/* Points to common section of report, so past any headers. */
273 	struct dualsense_output_report_common *common;
274 };
275 
276 /*
277  * Common gamepad buttons across DualShock 3 / 4 and DualSense.
278  * Note: for device with a touchpad, touchpad button is not included
279  *        as it will be part of the touchpad device.
280  */
281 static const int ps_gamepad_buttons[] = {
282 	BTN_WEST, /* Square */
283 	BTN_NORTH, /* Triangle */
284 	BTN_EAST, /* Circle */
285 	BTN_SOUTH, /* Cross */
286 	BTN_TL, /* L1 */
287 	BTN_TR, /* R1 */
288 	BTN_TL2, /* L2 */
289 	BTN_TR2, /* R2 */
290 	BTN_SELECT, /* Create (PS5) / Share (PS4) */
291 	BTN_START, /* Option */
292 	BTN_THUMBL, /* L3 */
293 	BTN_THUMBR, /* R3 */
294 	BTN_MODE, /* PS Home */
295 };
296 
297 static const struct {int x; int y; } ps_gamepad_hat_mapping[] = {
298 	{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1},
299 	{0, 0},
300 };
301 
302 static void dualsense_set_lightbar(struct dualsense *ds, uint8_t red, uint8_t green, uint8_t blue);
303 
304 /*
305  * Add a new ps_device to ps_devices if it doesn't exist.
306  * Return error on duplicate device, which can happen if the same
307  * device is connected using both Bluetooth and USB.
308  */
309 static int ps_devices_list_add(struct ps_device *dev)
310 {
311 	struct ps_device *entry;
312 
313 	mutex_lock(&ps_devices_lock);
314 	list_for_each_entry(entry, &ps_devices_list, list) {
315 		if (!memcmp(entry->mac_address, dev->mac_address, sizeof(dev->mac_address))) {
316 			hid_err(dev->hdev, "Duplicate device found for MAC address %pMR.\n",
317 					dev->mac_address);
318 			mutex_unlock(&ps_devices_lock);
319 			return -EEXIST;
320 		}
321 	}
322 
323 	list_add_tail(&dev->list, &ps_devices_list);
324 	mutex_unlock(&ps_devices_lock);
325 	return 0;
326 }
327 
328 static int ps_devices_list_remove(struct ps_device *dev)
329 {
330 	mutex_lock(&ps_devices_lock);
331 	list_del(&dev->list);
332 	mutex_unlock(&ps_devices_lock);
333 	return 0;
334 }
335 
336 static int ps_device_set_player_id(struct ps_device *dev)
337 {
338 	int ret = ida_alloc(&ps_player_id_allocator, GFP_KERNEL);
339 
340 	if (ret < 0)
341 		return ret;
342 
343 	dev->player_id = ret;
344 	return 0;
345 }
346 
347 static void ps_device_release_player_id(struct ps_device *dev)
348 {
349 	ida_free(&ps_player_id_allocator, dev->player_id);
350 
351 	dev->player_id = U32_MAX;
352 }
353 
354 static struct input_dev *ps_allocate_input_dev(struct hid_device *hdev, const char *name_suffix)
355 {
356 	struct input_dev *input_dev;
357 
358 	input_dev = devm_input_allocate_device(&hdev->dev);
359 	if (!input_dev)
360 		return ERR_PTR(-ENOMEM);
361 
362 	input_dev->id.bustype = hdev->bus;
363 	input_dev->id.vendor = hdev->vendor;
364 	input_dev->id.product = hdev->product;
365 	input_dev->id.version = hdev->version;
366 	input_dev->uniq = hdev->uniq;
367 
368 	if (name_suffix) {
369 		input_dev->name = devm_kasprintf(&hdev->dev, GFP_KERNEL, "%s %s", hdev->name,
370 				name_suffix);
371 		if (!input_dev->name)
372 			return ERR_PTR(-ENOMEM);
373 	} else {
374 		input_dev->name = hdev->name;
375 	}
376 
377 	input_set_drvdata(input_dev, hdev);
378 
379 	return input_dev;
380 }
381 
382 static enum power_supply_property ps_power_supply_props[] = {
383 	POWER_SUPPLY_PROP_STATUS,
384 	POWER_SUPPLY_PROP_PRESENT,
385 	POWER_SUPPLY_PROP_CAPACITY,
386 	POWER_SUPPLY_PROP_SCOPE,
387 };
388 
389 static int ps_battery_get_property(struct power_supply *psy,
390 		enum power_supply_property psp,
391 		union power_supply_propval *val)
392 {
393 	struct ps_device *dev = power_supply_get_drvdata(psy);
394 	uint8_t battery_capacity;
395 	int battery_status;
396 	unsigned long flags;
397 	int ret = 0;
398 
399 	spin_lock_irqsave(&dev->lock, flags);
400 	battery_capacity = dev->battery_capacity;
401 	battery_status = dev->battery_status;
402 	spin_unlock_irqrestore(&dev->lock, flags);
403 
404 	switch (psp) {
405 	case POWER_SUPPLY_PROP_STATUS:
406 		val->intval = battery_status;
407 		break;
408 	case POWER_SUPPLY_PROP_PRESENT:
409 		val->intval = 1;
410 		break;
411 	case POWER_SUPPLY_PROP_CAPACITY:
412 		val->intval = battery_capacity;
413 		break;
414 	case POWER_SUPPLY_PROP_SCOPE:
415 		val->intval = POWER_SUPPLY_SCOPE_DEVICE;
416 		break;
417 	default:
418 		ret = -EINVAL;
419 		break;
420 	}
421 
422 	return ret;
423 }
424 
425 static int ps_device_register_battery(struct ps_device *dev)
426 {
427 	struct power_supply *battery;
428 	struct power_supply_config battery_cfg = { .drv_data = dev };
429 	int ret;
430 
431 	dev->battery_desc.type = POWER_SUPPLY_TYPE_BATTERY;
432 	dev->battery_desc.properties = ps_power_supply_props;
433 	dev->battery_desc.num_properties = ARRAY_SIZE(ps_power_supply_props);
434 	dev->battery_desc.get_property = ps_battery_get_property;
435 	dev->battery_desc.name = devm_kasprintf(&dev->hdev->dev, GFP_KERNEL,
436 			"ps-controller-battery-%pMR", dev->mac_address);
437 	if (!dev->battery_desc.name)
438 		return -ENOMEM;
439 
440 	battery = devm_power_supply_register(&dev->hdev->dev, &dev->battery_desc, &battery_cfg);
441 	if (IS_ERR(battery)) {
442 		ret = PTR_ERR(battery);
443 		hid_err(dev->hdev, "Unable to register battery device: %d\n", ret);
444 		return ret;
445 	}
446 	dev->battery = battery;
447 
448 	ret = power_supply_powers(dev->battery, &dev->hdev->dev);
449 	if (ret) {
450 		hid_err(dev->hdev, "Unable to activate battery device: %d\n", ret);
451 		return ret;
452 	}
453 
454 	return 0;
455 }
456 
457 /* Compute crc32 of HID data and compare against expected CRC. */
458 static bool ps_check_crc32(uint8_t seed, uint8_t *data, size_t len, uint32_t report_crc)
459 {
460 	uint32_t crc;
461 
462 	crc = crc32_le(0xFFFFFFFF, &seed, 1);
463 	crc = ~crc32_le(crc, data, len);
464 
465 	return crc == report_crc;
466 }
467 
468 static struct input_dev *ps_gamepad_create(struct hid_device *hdev,
469 		int (*play_effect)(struct input_dev *, void *, struct ff_effect *))
470 {
471 	struct input_dev *gamepad;
472 	unsigned int i;
473 	int ret;
474 
475 	gamepad = ps_allocate_input_dev(hdev, NULL);
476 	if (IS_ERR(gamepad))
477 		return ERR_CAST(gamepad);
478 
479 	input_set_abs_params(gamepad, ABS_X, 0, 255, 0, 0);
480 	input_set_abs_params(gamepad, ABS_Y, 0, 255, 0, 0);
481 	input_set_abs_params(gamepad, ABS_Z, 0, 255, 0, 0);
482 	input_set_abs_params(gamepad, ABS_RX, 0, 255, 0, 0);
483 	input_set_abs_params(gamepad, ABS_RY, 0, 255, 0, 0);
484 	input_set_abs_params(gamepad, ABS_RZ, 0, 255, 0, 0);
485 
486 	input_set_abs_params(gamepad, ABS_HAT0X, -1, 1, 0, 0);
487 	input_set_abs_params(gamepad, ABS_HAT0Y, -1, 1, 0, 0);
488 
489 	for (i = 0; i < ARRAY_SIZE(ps_gamepad_buttons); i++)
490 		input_set_capability(gamepad, EV_KEY, ps_gamepad_buttons[i]);
491 
492 #if IS_ENABLED(CONFIG_PLAYSTATION_FF)
493 	if (play_effect) {
494 		input_set_capability(gamepad, EV_FF, FF_RUMBLE);
495 		input_ff_create_memless(gamepad, NULL, play_effect);
496 	}
497 #endif
498 
499 	ret = input_register_device(gamepad);
500 	if (ret)
501 		return ERR_PTR(ret);
502 
503 	return gamepad;
504 }
505 
506 static int ps_get_report(struct hid_device *hdev, uint8_t report_id, uint8_t *buf, size_t size)
507 {
508 	int ret;
509 
510 	ret = hid_hw_raw_request(hdev, report_id, buf, size, HID_FEATURE_REPORT,
511 				 HID_REQ_GET_REPORT);
512 	if (ret < 0) {
513 		hid_err(hdev, "Failed to retrieve feature with reportID %d: %d\n", report_id, ret);
514 		return ret;
515 	}
516 
517 	if (ret != size) {
518 		hid_err(hdev, "Invalid byte count transferred, expected %zu got %d\n", size, ret);
519 		return -EINVAL;
520 	}
521 
522 	if (buf[0] != report_id) {
523 		hid_err(hdev, "Invalid reportID received, expected %d got %d\n", report_id, buf[0]);
524 		return -EINVAL;
525 	}
526 
527 	if (hdev->bus == BUS_BLUETOOTH) {
528 		/* Last 4 bytes contains crc32. */
529 		uint8_t crc_offset = size - 4;
530 		uint32_t report_crc = get_unaligned_le32(&buf[crc_offset]);
531 
532 		if (!ps_check_crc32(PS_FEATURE_CRC32_SEED, buf, crc_offset, report_crc)) {
533 			hid_err(hdev, "CRC check failed for reportID=%d\n", report_id);
534 			return -EILSEQ;
535 		}
536 	}
537 
538 	return 0;
539 }
540 
541 static int ps_led_register(struct ps_device *ps_dev, struct led_classdev *led,
542 		const struct ps_led_info *led_info)
543 {
544 	int ret;
545 
546 	led->name = devm_kasprintf(&ps_dev->hdev->dev, GFP_KERNEL,
547 			"%s:%s:%s", ps_dev->input_dev_name, led_info->color, led_info->name);
548 
549 	if (!led->name)
550 		return -ENOMEM;
551 
552 	led->brightness = 0;
553 	led->max_brightness = 1;
554 	led->flags = LED_CORE_SUSPENDRESUME;
555 	led->brightness_get = led_info->brightness_get;
556 	led->brightness_set_blocking = led_info->brightness_set;
557 
558 	ret = devm_led_classdev_register(&ps_dev->hdev->dev, led);
559 	if (ret) {
560 		hid_err(ps_dev->hdev, "Failed to register LED %s: %d\n", led_info->name, ret);
561 		return ret;
562 	}
563 
564 	return 0;
565 }
566 
567 /* Register a DualSense/DualShock4 RGB lightbar represented by a multicolor LED. */
568 static int ps_lightbar_register(struct ps_device *ps_dev, struct led_classdev_mc *lightbar_mc_dev,
569 	int (*brightness_set)(struct led_classdev *, enum led_brightness))
570 {
571 	struct hid_device *hdev = ps_dev->hdev;
572 	struct mc_subled *mc_led_info;
573 	struct led_classdev *led_cdev;
574 	int ret;
575 
576 	mc_led_info = devm_kmalloc_array(&hdev->dev, 3, sizeof(*mc_led_info),
577 					 GFP_KERNEL | __GFP_ZERO);
578 	if (!mc_led_info)
579 		return -ENOMEM;
580 
581 	mc_led_info[0].color_index = LED_COLOR_ID_RED;
582 	mc_led_info[1].color_index = LED_COLOR_ID_GREEN;
583 	mc_led_info[2].color_index = LED_COLOR_ID_BLUE;
584 
585 	lightbar_mc_dev->subled_info = mc_led_info;
586 	lightbar_mc_dev->num_colors = 3;
587 
588 	led_cdev = &lightbar_mc_dev->led_cdev;
589 	led_cdev->name = devm_kasprintf(&hdev->dev, GFP_KERNEL, "%s:rgb:indicator",
590 			ps_dev->input_dev_name);
591 	if (!led_cdev->name)
592 		return -ENOMEM;
593 	led_cdev->brightness = 255;
594 	led_cdev->max_brightness = 255;
595 	led_cdev->brightness_set_blocking = brightness_set;
596 
597 	ret = devm_led_classdev_multicolor_register(&hdev->dev, lightbar_mc_dev);
598 	if (ret < 0) {
599 		hid_err(hdev, "Cannot register multicolor LED device\n");
600 		return ret;
601 	}
602 
603 	return 0;
604 }
605 
606 static struct input_dev *ps_sensors_create(struct hid_device *hdev, int accel_range, int accel_res,
607 		int gyro_range, int gyro_res)
608 {
609 	struct input_dev *sensors;
610 	int ret;
611 
612 	sensors = ps_allocate_input_dev(hdev, "Motion Sensors");
613 	if (IS_ERR(sensors))
614 		return ERR_CAST(sensors);
615 
616 	__set_bit(INPUT_PROP_ACCELEROMETER, sensors->propbit);
617 	__set_bit(EV_MSC, sensors->evbit);
618 	__set_bit(MSC_TIMESTAMP, sensors->mscbit);
619 
620 	/* Accelerometer */
621 	input_set_abs_params(sensors, ABS_X, -accel_range, accel_range, 16, 0);
622 	input_set_abs_params(sensors, ABS_Y, -accel_range, accel_range, 16, 0);
623 	input_set_abs_params(sensors, ABS_Z, -accel_range, accel_range, 16, 0);
624 	input_abs_set_res(sensors, ABS_X, accel_res);
625 	input_abs_set_res(sensors, ABS_Y, accel_res);
626 	input_abs_set_res(sensors, ABS_Z, accel_res);
627 
628 	/* Gyroscope */
629 	input_set_abs_params(sensors, ABS_RX, -gyro_range, gyro_range, 16, 0);
630 	input_set_abs_params(sensors, ABS_RY, -gyro_range, gyro_range, 16, 0);
631 	input_set_abs_params(sensors, ABS_RZ, -gyro_range, gyro_range, 16, 0);
632 	input_abs_set_res(sensors, ABS_RX, gyro_res);
633 	input_abs_set_res(sensors, ABS_RY, gyro_res);
634 	input_abs_set_res(sensors, ABS_RZ, gyro_res);
635 
636 	ret = input_register_device(sensors);
637 	if (ret)
638 		return ERR_PTR(ret);
639 
640 	return sensors;
641 }
642 
643 static struct input_dev *ps_touchpad_create(struct hid_device *hdev, int width, int height,
644 		unsigned int num_contacts)
645 {
646 	struct input_dev *touchpad;
647 	int ret;
648 
649 	touchpad = ps_allocate_input_dev(hdev, "Touchpad");
650 	if (IS_ERR(touchpad))
651 		return ERR_CAST(touchpad);
652 
653 	/* Map button underneath touchpad to BTN_LEFT. */
654 	input_set_capability(touchpad, EV_KEY, BTN_LEFT);
655 	__set_bit(INPUT_PROP_BUTTONPAD, touchpad->propbit);
656 
657 	input_set_abs_params(touchpad, ABS_MT_POSITION_X, 0, width - 1, 0, 0);
658 	input_set_abs_params(touchpad, ABS_MT_POSITION_Y, 0, height - 1, 0, 0);
659 
660 	ret = input_mt_init_slots(touchpad, num_contacts, INPUT_MT_POINTER);
661 	if (ret)
662 		return ERR_PTR(ret);
663 
664 	ret = input_register_device(touchpad);
665 	if (ret)
666 		return ERR_PTR(ret);
667 
668 	return touchpad;
669 }
670 
671 static ssize_t firmware_version_show(struct device *dev,
672 				struct device_attribute
673 				*attr, char *buf)
674 {
675 	struct hid_device *hdev = to_hid_device(dev);
676 	struct ps_device *ps_dev = hid_get_drvdata(hdev);
677 
678 	return sysfs_emit(buf, "0x%08x\n", ps_dev->fw_version);
679 }
680 
681 static DEVICE_ATTR_RO(firmware_version);
682 
683 static ssize_t hardware_version_show(struct device *dev,
684 				struct device_attribute
685 				*attr, char *buf)
686 {
687 	struct hid_device *hdev = to_hid_device(dev);
688 	struct ps_device *ps_dev = hid_get_drvdata(hdev);
689 
690 	return sysfs_emit(buf, "0x%08x\n", ps_dev->hw_version);
691 }
692 
693 static DEVICE_ATTR_RO(hardware_version);
694 
695 static struct attribute *ps_device_attributes[] = {
696 	&dev_attr_firmware_version.attr,
697 	&dev_attr_hardware_version.attr,
698 	NULL
699 };
700 
701 static const struct attribute_group ps_device_attribute_group = {
702 	.attrs = ps_device_attributes,
703 };
704 
705 static int dualsense_get_calibration_data(struct dualsense *ds)
706 {
707 	short gyro_pitch_bias, gyro_pitch_plus, gyro_pitch_minus;
708 	short gyro_yaw_bias, gyro_yaw_plus, gyro_yaw_minus;
709 	short gyro_roll_bias, gyro_roll_plus, gyro_roll_minus;
710 	short gyro_speed_plus, gyro_speed_minus;
711 	short acc_x_plus, acc_x_minus;
712 	short acc_y_plus, acc_y_minus;
713 	short acc_z_plus, acc_z_minus;
714 	int speed_2x;
715 	int range_2g;
716 	int ret = 0;
717 	uint8_t *buf;
718 
719 	buf = kzalloc(DS_FEATURE_REPORT_CALIBRATION_SIZE, GFP_KERNEL);
720 	if (!buf)
721 		return -ENOMEM;
722 
723 	ret = ps_get_report(ds->base.hdev, DS_FEATURE_REPORT_CALIBRATION, buf,
724 			DS_FEATURE_REPORT_CALIBRATION_SIZE);
725 	if (ret) {
726 		hid_err(ds->base.hdev, "Failed to retrieve DualSense calibration info: %d\n", ret);
727 		goto err_free;
728 	}
729 
730 	gyro_pitch_bias  = get_unaligned_le16(&buf[1]);
731 	gyro_yaw_bias    = get_unaligned_le16(&buf[3]);
732 	gyro_roll_bias   = get_unaligned_le16(&buf[5]);
733 	gyro_pitch_plus  = get_unaligned_le16(&buf[7]);
734 	gyro_pitch_minus = get_unaligned_le16(&buf[9]);
735 	gyro_yaw_plus    = get_unaligned_le16(&buf[11]);
736 	gyro_yaw_minus   = get_unaligned_le16(&buf[13]);
737 	gyro_roll_plus   = get_unaligned_le16(&buf[15]);
738 	gyro_roll_minus  = get_unaligned_le16(&buf[17]);
739 	gyro_speed_plus  = get_unaligned_le16(&buf[19]);
740 	gyro_speed_minus = get_unaligned_le16(&buf[21]);
741 	acc_x_plus       = get_unaligned_le16(&buf[23]);
742 	acc_x_minus      = get_unaligned_le16(&buf[25]);
743 	acc_y_plus       = get_unaligned_le16(&buf[27]);
744 	acc_y_minus      = get_unaligned_le16(&buf[29]);
745 	acc_z_plus       = get_unaligned_le16(&buf[31]);
746 	acc_z_minus      = get_unaligned_le16(&buf[33]);
747 
748 	/*
749 	 * Set gyroscope calibration and normalization parameters.
750 	 * Data values will be normalized to 1/DS_GYRO_RES_PER_DEG_S degree/s.
751 	 */
752 	speed_2x = (gyro_speed_plus + gyro_speed_minus);
753 	ds->gyro_calib_data[0].abs_code = ABS_RX;
754 	ds->gyro_calib_data[0].bias = gyro_pitch_bias;
755 	ds->gyro_calib_data[0].sens_numer = speed_2x*DS_GYRO_RES_PER_DEG_S;
756 	ds->gyro_calib_data[0].sens_denom = gyro_pitch_plus - gyro_pitch_minus;
757 
758 	ds->gyro_calib_data[1].abs_code = ABS_RY;
759 	ds->gyro_calib_data[1].bias = gyro_yaw_bias;
760 	ds->gyro_calib_data[1].sens_numer = speed_2x*DS_GYRO_RES_PER_DEG_S;
761 	ds->gyro_calib_data[1].sens_denom = gyro_yaw_plus - gyro_yaw_minus;
762 
763 	ds->gyro_calib_data[2].abs_code = ABS_RZ;
764 	ds->gyro_calib_data[2].bias = gyro_roll_bias;
765 	ds->gyro_calib_data[2].sens_numer = speed_2x*DS_GYRO_RES_PER_DEG_S;
766 	ds->gyro_calib_data[2].sens_denom = gyro_roll_plus - gyro_roll_minus;
767 
768 	/*
769 	 * Set accelerometer calibration and normalization parameters.
770 	 * Data values will be normalized to 1/DS_ACC_RES_PER_G g.
771 	 */
772 	range_2g = acc_x_plus - acc_x_minus;
773 	ds->accel_calib_data[0].abs_code = ABS_X;
774 	ds->accel_calib_data[0].bias = acc_x_plus - range_2g / 2;
775 	ds->accel_calib_data[0].sens_numer = 2*DS_ACC_RES_PER_G;
776 	ds->accel_calib_data[0].sens_denom = range_2g;
777 
778 	range_2g = acc_y_plus - acc_y_minus;
779 	ds->accel_calib_data[1].abs_code = ABS_Y;
780 	ds->accel_calib_data[1].bias = acc_y_plus - range_2g / 2;
781 	ds->accel_calib_data[1].sens_numer = 2*DS_ACC_RES_PER_G;
782 	ds->accel_calib_data[1].sens_denom = range_2g;
783 
784 	range_2g = acc_z_plus - acc_z_minus;
785 	ds->accel_calib_data[2].abs_code = ABS_Z;
786 	ds->accel_calib_data[2].bias = acc_z_plus - range_2g / 2;
787 	ds->accel_calib_data[2].sens_numer = 2*DS_ACC_RES_PER_G;
788 	ds->accel_calib_data[2].sens_denom = range_2g;
789 
790 err_free:
791 	kfree(buf);
792 	return ret;
793 }
794 
795 static int dualsense_get_firmware_info(struct dualsense *ds)
796 {
797 	uint8_t *buf;
798 	int ret;
799 
800 	buf = kzalloc(DS_FEATURE_REPORT_FIRMWARE_INFO_SIZE, GFP_KERNEL);
801 	if (!buf)
802 		return -ENOMEM;
803 
804 	ret = ps_get_report(ds->base.hdev, DS_FEATURE_REPORT_FIRMWARE_INFO, buf,
805 			DS_FEATURE_REPORT_FIRMWARE_INFO_SIZE);
806 	if (ret) {
807 		hid_err(ds->base.hdev, "Failed to retrieve DualSense firmware info: %d\n", ret);
808 		goto err_free;
809 	}
810 
811 	ds->base.hw_version = get_unaligned_le32(&buf[24]);
812 	ds->base.fw_version = get_unaligned_le32(&buf[28]);
813 
814 err_free:
815 	kfree(buf);
816 	return ret;
817 }
818 
819 static int dualsense_get_mac_address(struct dualsense *ds)
820 {
821 	uint8_t *buf;
822 	int ret = 0;
823 
824 	buf = kzalloc(DS_FEATURE_REPORT_PAIRING_INFO_SIZE, GFP_KERNEL);
825 	if (!buf)
826 		return -ENOMEM;
827 
828 	ret = ps_get_report(ds->base.hdev, DS_FEATURE_REPORT_PAIRING_INFO, buf,
829 			DS_FEATURE_REPORT_PAIRING_INFO_SIZE);
830 	if (ret) {
831 		hid_err(ds->base.hdev, "Failed to retrieve DualSense pairing info: %d\n", ret);
832 		goto err_free;
833 	}
834 
835 	memcpy(ds->base.mac_address, &buf[1], sizeof(ds->base.mac_address));
836 
837 err_free:
838 	kfree(buf);
839 	return ret;
840 }
841 
842 static int dualsense_lightbar_set_brightness(struct led_classdev *cdev,
843 	enum led_brightness brightness)
844 {
845 	struct led_classdev_mc *mc_cdev = lcdev_to_mccdev(cdev);
846 	struct dualsense *ds = container_of(mc_cdev, struct dualsense, lightbar);
847 	uint8_t red, green, blue;
848 
849 	led_mc_calc_color_components(mc_cdev, brightness);
850 	red = mc_cdev->subled_info[0].brightness;
851 	green = mc_cdev->subled_info[1].brightness;
852 	blue = mc_cdev->subled_info[2].brightness;
853 
854 	dualsense_set_lightbar(ds, red, green, blue);
855 	return 0;
856 }
857 
858 static enum led_brightness dualsense_player_led_get_brightness(struct led_classdev *led)
859 {
860 	struct hid_device *hdev = to_hid_device(led->dev->parent);
861 	struct dualsense *ds = hid_get_drvdata(hdev);
862 
863 	return !!(ds->player_leds_state & BIT(led - ds->player_leds));
864 }
865 
866 static int dualsense_player_led_set_brightness(struct led_classdev *led, enum led_brightness value)
867 {
868 	struct hid_device *hdev = to_hid_device(led->dev->parent);
869 	struct dualsense *ds = hid_get_drvdata(hdev);
870 	unsigned long flags;
871 	unsigned int led_index;
872 
873 	spin_lock_irqsave(&ds->base.lock, flags);
874 
875 	led_index = led - ds->player_leds;
876 	if (value == LED_OFF)
877 		ds->player_leds_state &= ~BIT(led_index);
878 	else
879 		ds->player_leds_state |= BIT(led_index);
880 
881 	ds->update_player_leds = true;
882 	spin_unlock_irqrestore(&ds->base.lock, flags);
883 
884 	schedule_work(&ds->output_worker);
885 
886 	return 0;
887 }
888 
889 static void dualsense_init_output_report(struct dualsense *ds, struct dualsense_output_report *rp,
890 		void *buf)
891 {
892 	struct hid_device *hdev = ds->base.hdev;
893 
894 	if (hdev->bus == BUS_BLUETOOTH) {
895 		struct dualsense_output_report_bt *bt = buf;
896 
897 		memset(bt, 0, sizeof(*bt));
898 		bt->report_id = DS_OUTPUT_REPORT_BT;
899 		bt->tag = DS_OUTPUT_TAG; /* Tag must be set. Exact meaning is unclear. */
900 
901 		/*
902 		 * Highest 4-bit is a sequence number, which needs to be increased
903 		 * every report. Lowest 4-bit is tag and can be zero for now.
904 		 */
905 		bt->seq_tag = (ds->output_seq << 4) | 0x0;
906 		if (++ds->output_seq == 16)
907 			ds->output_seq = 0;
908 
909 		rp->data = buf;
910 		rp->len = sizeof(*bt);
911 		rp->bt = bt;
912 		rp->usb = NULL;
913 		rp->common = &bt->common;
914 	} else { /* USB */
915 		struct dualsense_output_report_usb *usb = buf;
916 
917 		memset(usb, 0, sizeof(*usb));
918 		usb->report_id = DS_OUTPUT_REPORT_USB;
919 
920 		rp->data = buf;
921 		rp->len = sizeof(*usb);
922 		rp->bt = NULL;
923 		rp->usb = usb;
924 		rp->common = &usb->common;
925 	}
926 }
927 
928 /*
929  * Helper function to send DualSense output reports. Applies a CRC at the end of a report
930  * for Bluetooth reports.
931  */
932 static void dualsense_send_output_report(struct dualsense *ds,
933 		struct dualsense_output_report *report)
934 {
935 	struct hid_device *hdev = ds->base.hdev;
936 
937 	/* Bluetooth packets need to be signed with a CRC in the last 4 bytes. */
938 	if (report->bt) {
939 		uint32_t crc;
940 		uint8_t seed = PS_OUTPUT_CRC32_SEED;
941 
942 		crc = crc32_le(0xFFFFFFFF, &seed, 1);
943 		crc = ~crc32_le(crc, report->data, report->len - 4);
944 
945 		report->bt->crc32 = cpu_to_le32(crc);
946 	}
947 
948 	hid_hw_output_report(hdev, report->data, report->len);
949 }
950 
951 static void dualsense_output_worker(struct work_struct *work)
952 {
953 	struct dualsense *ds = container_of(work, struct dualsense, output_worker);
954 	struct dualsense_output_report report;
955 	struct dualsense_output_report_common *common;
956 	unsigned long flags;
957 
958 	dualsense_init_output_report(ds, &report, ds->output_report_dmabuf);
959 	common = report.common;
960 
961 	spin_lock_irqsave(&ds->base.lock, flags);
962 
963 	if (ds->update_rumble) {
964 		/* Select classic rumble style haptics and enable it. */
965 		common->valid_flag0 |= DS_OUTPUT_VALID_FLAG0_HAPTICS_SELECT;
966 		common->valid_flag0 |= DS_OUTPUT_VALID_FLAG0_COMPATIBLE_VIBRATION;
967 		common->motor_left = ds->motor_left;
968 		common->motor_right = ds->motor_right;
969 		ds->update_rumble = false;
970 	}
971 
972 	if (ds->update_lightbar) {
973 		common->valid_flag1 |= DS_OUTPUT_VALID_FLAG1_LIGHTBAR_CONTROL_ENABLE;
974 		common->lightbar_red = ds->lightbar_red;
975 		common->lightbar_green = ds->lightbar_green;
976 		common->lightbar_blue = ds->lightbar_blue;
977 
978 		ds->update_lightbar = false;
979 	}
980 
981 	if (ds->update_player_leds) {
982 		common->valid_flag1 |= DS_OUTPUT_VALID_FLAG1_PLAYER_INDICATOR_CONTROL_ENABLE;
983 		common->player_leds = ds->player_leds_state;
984 
985 		ds->update_player_leds = false;
986 	}
987 
988 	if (ds->update_mic_mute) {
989 		common->valid_flag1 |= DS_OUTPUT_VALID_FLAG1_MIC_MUTE_LED_CONTROL_ENABLE;
990 		common->mute_button_led = ds->mic_muted;
991 
992 		if (ds->mic_muted) {
993 			/* Disable microphone */
994 			common->valid_flag1 |= DS_OUTPUT_VALID_FLAG1_POWER_SAVE_CONTROL_ENABLE;
995 			common->power_save_control |= DS_OUTPUT_POWER_SAVE_CONTROL_MIC_MUTE;
996 		} else {
997 			/* Enable microphone */
998 			common->valid_flag1 |= DS_OUTPUT_VALID_FLAG1_POWER_SAVE_CONTROL_ENABLE;
999 			common->power_save_control &= ~DS_OUTPUT_POWER_SAVE_CONTROL_MIC_MUTE;
1000 		}
1001 
1002 		ds->update_mic_mute = false;
1003 	}
1004 
1005 	spin_unlock_irqrestore(&ds->base.lock, flags);
1006 
1007 	dualsense_send_output_report(ds, &report);
1008 }
1009 
1010 static int dualsense_parse_report(struct ps_device *ps_dev, struct hid_report *report,
1011 		u8 *data, int size)
1012 {
1013 	struct hid_device *hdev = ps_dev->hdev;
1014 	struct dualsense *ds = container_of(ps_dev, struct dualsense, base);
1015 	struct dualsense_input_report *ds_report;
1016 	uint8_t battery_data, battery_capacity, charging_status, value;
1017 	int battery_status;
1018 	uint32_t sensor_timestamp;
1019 	bool btn_mic_state;
1020 	unsigned long flags;
1021 	int i;
1022 
1023 	/*
1024 	 * DualSense in USB uses the full HID report for reportID 1, but
1025 	 * Bluetooth uses a minimal HID report for reportID 1 and reports
1026 	 * the full report using reportID 49.
1027 	 */
1028 	if (hdev->bus == BUS_USB && report->id == DS_INPUT_REPORT_USB &&
1029 			size == DS_INPUT_REPORT_USB_SIZE) {
1030 		ds_report = (struct dualsense_input_report *)&data[1];
1031 	} else if (hdev->bus == BUS_BLUETOOTH && report->id == DS_INPUT_REPORT_BT &&
1032 			size == DS_INPUT_REPORT_BT_SIZE) {
1033 		/* Last 4 bytes of input report contain crc32 */
1034 		uint32_t report_crc = get_unaligned_le32(&data[size - 4]);
1035 
1036 		if (!ps_check_crc32(PS_INPUT_CRC32_SEED, data, size - 4, report_crc)) {
1037 			hid_err(hdev, "DualSense input CRC's check failed\n");
1038 			return -EILSEQ;
1039 		}
1040 
1041 		ds_report = (struct dualsense_input_report *)&data[2];
1042 	} else {
1043 		hid_err(hdev, "Unhandled reportID=%d\n", report->id);
1044 		return -1;
1045 	}
1046 
1047 	input_report_abs(ds->gamepad, ABS_X,  ds_report->x);
1048 	input_report_abs(ds->gamepad, ABS_Y,  ds_report->y);
1049 	input_report_abs(ds->gamepad, ABS_RX, ds_report->rx);
1050 	input_report_abs(ds->gamepad, ABS_RY, ds_report->ry);
1051 	input_report_abs(ds->gamepad, ABS_Z,  ds_report->z);
1052 	input_report_abs(ds->gamepad, ABS_RZ, ds_report->rz);
1053 
1054 	value = ds_report->buttons[0] & DS_BUTTONS0_HAT_SWITCH;
1055 	if (value >= ARRAY_SIZE(ps_gamepad_hat_mapping))
1056 		value = 8; /* center */
1057 	input_report_abs(ds->gamepad, ABS_HAT0X, ps_gamepad_hat_mapping[value].x);
1058 	input_report_abs(ds->gamepad, ABS_HAT0Y, ps_gamepad_hat_mapping[value].y);
1059 
1060 	input_report_key(ds->gamepad, BTN_WEST,   ds_report->buttons[0] & DS_BUTTONS0_SQUARE);
1061 	input_report_key(ds->gamepad, BTN_SOUTH,  ds_report->buttons[0] & DS_BUTTONS0_CROSS);
1062 	input_report_key(ds->gamepad, BTN_EAST,   ds_report->buttons[0] & DS_BUTTONS0_CIRCLE);
1063 	input_report_key(ds->gamepad, BTN_NORTH,  ds_report->buttons[0] & DS_BUTTONS0_TRIANGLE);
1064 	input_report_key(ds->gamepad, BTN_TL,     ds_report->buttons[1] & DS_BUTTONS1_L1);
1065 	input_report_key(ds->gamepad, BTN_TR,     ds_report->buttons[1] & DS_BUTTONS1_R1);
1066 	input_report_key(ds->gamepad, BTN_TL2,    ds_report->buttons[1] & DS_BUTTONS1_L2);
1067 	input_report_key(ds->gamepad, BTN_TR2,    ds_report->buttons[1] & DS_BUTTONS1_R2);
1068 	input_report_key(ds->gamepad, BTN_SELECT, ds_report->buttons[1] & DS_BUTTONS1_CREATE);
1069 	input_report_key(ds->gamepad, BTN_START,  ds_report->buttons[1] & DS_BUTTONS1_OPTIONS);
1070 	input_report_key(ds->gamepad, BTN_THUMBL, ds_report->buttons[1] & DS_BUTTONS1_L3);
1071 	input_report_key(ds->gamepad, BTN_THUMBR, ds_report->buttons[1] & DS_BUTTONS1_R3);
1072 	input_report_key(ds->gamepad, BTN_MODE,   ds_report->buttons[2] & DS_BUTTONS2_PS_HOME);
1073 	input_sync(ds->gamepad);
1074 
1075 	/*
1076 	 * The DualSense has an internal microphone, which can be muted through a mute button
1077 	 * on the device. The driver is expected to read the button state and program the device
1078 	 * to mute/unmute audio at the hardware level.
1079 	 */
1080 	btn_mic_state = !!(ds_report->buttons[2] & DS_BUTTONS2_MIC_MUTE);
1081 	if (btn_mic_state && !ds->last_btn_mic_state) {
1082 		spin_lock_irqsave(&ps_dev->lock, flags);
1083 		ds->update_mic_mute = true;
1084 		ds->mic_muted = !ds->mic_muted; /* toggle */
1085 		spin_unlock_irqrestore(&ps_dev->lock, flags);
1086 
1087 		/* Schedule updating of microphone state at hardware level. */
1088 		schedule_work(&ds->output_worker);
1089 	}
1090 	ds->last_btn_mic_state = btn_mic_state;
1091 
1092 	/* Parse and calibrate gyroscope data. */
1093 	for (i = 0; i < ARRAY_SIZE(ds_report->gyro); i++) {
1094 		int raw_data = (short)le16_to_cpu(ds_report->gyro[i]);
1095 		int calib_data = mult_frac(ds->gyro_calib_data[i].sens_numer,
1096 					   raw_data - ds->gyro_calib_data[i].bias,
1097 					   ds->gyro_calib_data[i].sens_denom);
1098 
1099 		input_report_abs(ds->sensors, ds->gyro_calib_data[i].abs_code, calib_data);
1100 	}
1101 
1102 	/* Parse and calibrate accelerometer data. */
1103 	for (i = 0; i < ARRAY_SIZE(ds_report->accel); i++) {
1104 		int raw_data = (short)le16_to_cpu(ds_report->accel[i]);
1105 		int calib_data = mult_frac(ds->accel_calib_data[i].sens_numer,
1106 					   raw_data - ds->accel_calib_data[i].bias,
1107 					   ds->accel_calib_data[i].sens_denom);
1108 
1109 		input_report_abs(ds->sensors, ds->accel_calib_data[i].abs_code, calib_data);
1110 	}
1111 
1112 	/* Convert timestamp (in 0.33us unit) to timestamp_us */
1113 	sensor_timestamp = le32_to_cpu(ds_report->sensor_timestamp);
1114 	if (!ds->sensor_timestamp_initialized) {
1115 		ds->sensor_timestamp_us = DIV_ROUND_CLOSEST(sensor_timestamp, 3);
1116 		ds->sensor_timestamp_initialized = true;
1117 	} else {
1118 		uint32_t delta;
1119 
1120 		if (ds->prev_sensor_timestamp > sensor_timestamp)
1121 			delta = (U32_MAX - ds->prev_sensor_timestamp + sensor_timestamp + 1);
1122 		else
1123 			delta = sensor_timestamp - ds->prev_sensor_timestamp;
1124 		ds->sensor_timestamp_us += DIV_ROUND_CLOSEST(delta, 3);
1125 	}
1126 	ds->prev_sensor_timestamp = sensor_timestamp;
1127 	input_event(ds->sensors, EV_MSC, MSC_TIMESTAMP, ds->sensor_timestamp_us);
1128 	input_sync(ds->sensors);
1129 
1130 	for (i = 0; i < ARRAY_SIZE(ds_report->points); i++) {
1131 		struct dualsense_touch_point *point = &ds_report->points[i];
1132 		bool active = (point->contact & DS_TOUCH_POINT_INACTIVE) ? false : true;
1133 
1134 		input_mt_slot(ds->touchpad, i);
1135 		input_mt_report_slot_state(ds->touchpad, MT_TOOL_FINGER, active);
1136 
1137 		if (active) {
1138 			int x = (point->x_hi << 8) | point->x_lo;
1139 			int y = (point->y_hi << 4) | point->y_lo;
1140 
1141 			input_report_abs(ds->touchpad, ABS_MT_POSITION_X, x);
1142 			input_report_abs(ds->touchpad, ABS_MT_POSITION_Y, y);
1143 		}
1144 	}
1145 	input_mt_sync_frame(ds->touchpad);
1146 	input_report_key(ds->touchpad, BTN_LEFT, ds_report->buttons[2] & DS_BUTTONS2_TOUCHPAD);
1147 	input_sync(ds->touchpad);
1148 
1149 	battery_data = ds_report->status & DS_STATUS_BATTERY_CAPACITY;
1150 	charging_status = (ds_report->status & DS_STATUS_CHARGING) >> DS_STATUS_CHARGING_SHIFT;
1151 
1152 	switch (charging_status) {
1153 	case 0x0:
1154 		/*
1155 		 * Each unit of battery data corresponds to 10%
1156 		 * 0 = 0-9%, 1 = 10-19%, .. and 10 = 100%
1157 		 */
1158 		battery_capacity = min(battery_data * 10 + 5, 100);
1159 		battery_status = POWER_SUPPLY_STATUS_DISCHARGING;
1160 		break;
1161 	case 0x1:
1162 		battery_capacity = min(battery_data * 10 + 5, 100);
1163 		battery_status = POWER_SUPPLY_STATUS_CHARGING;
1164 		break;
1165 	case 0x2:
1166 		battery_capacity = 100;
1167 		battery_status = POWER_SUPPLY_STATUS_FULL;
1168 		break;
1169 	case 0xa: /* voltage or temperature out of range */
1170 	case 0xb: /* temperature error */
1171 		battery_capacity = 0;
1172 		battery_status = POWER_SUPPLY_STATUS_NOT_CHARGING;
1173 		break;
1174 	case 0xf: /* charging error */
1175 	default:
1176 		battery_capacity = 0;
1177 		battery_status = POWER_SUPPLY_STATUS_UNKNOWN;
1178 	}
1179 
1180 	spin_lock_irqsave(&ps_dev->lock, flags);
1181 	ps_dev->battery_capacity = battery_capacity;
1182 	ps_dev->battery_status = battery_status;
1183 	spin_unlock_irqrestore(&ps_dev->lock, flags);
1184 
1185 	return 0;
1186 }
1187 
1188 static int dualsense_play_effect(struct input_dev *dev, void *data, struct ff_effect *effect)
1189 {
1190 	struct hid_device *hdev = input_get_drvdata(dev);
1191 	struct dualsense *ds = hid_get_drvdata(hdev);
1192 	unsigned long flags;
1193 
1194 	if (effect->type != FF_RUMBLE)
1195 		return 0;
1196 
1197 	spin_lock_irqsave(&ds->base.lock, flags);
1198 	ds->update_rumble = true;
1199 	ds->motor_left = effect->u.rumble.strong_magnitude / 256;
1200 	ds->motor_right = effect->u.rumble.weak_magnitude / 256;
1201 	spin_unlock_irqrestore(&ds->base.lock, flags);
1202 
1203 	schedule_work(&ds->output_worker);
1204 	return 0;
1205 }
1206 
1207 static int dualsense_reset_leds(struct dualsense *ds)
1208 {
1209 	struct dualsense_output_report report;
1210 	uint8_t *buf;
1211 
1212 	buf = kzalloc(sizeof(struct dualsense_output_report_bt), GFP_KERNEL);
1213 	if (!buf)
1214 		return -ENOMEM;
1215 
1216 	dualsense_init_output_report(ds, &report, buf);
1217 	/*
1218 	 * On Bluetooth the DualSense outputs an animation on the lightbar
1219 	 * during startup and maintains a color afterwards. We need to explicitly
1220 	 * reconfigure the lightbar before we can do any programming later on.
1221 	 * In USB the lightbar is not on by default, but redoing the setup there
1222 	 * doesn't hurt.
1223 	 */
1224 	report.common->valid_flag2 = DS_OUTPUT_VALID_FLAG2_LIGHTBAR_SETUP_CONTROL_ENABLE;
1225 	report.common->lightbar_setup = DS_OUTPUT_LIGHTBAR_SETUP_LIGHT_OUT; /* Fade light out. */
1226 	dualsense_send_output_report(ds, &report);
1227 
1228 	kfree(buf);
1229 	return 0;
1230 }
1231 
1232 static void dualsense_set_lightbar(struct dualsense *ds, uint8_t red, uint8_t green, uint8_t blue)
1233 {
1234 	unsigned long flags;
1235 
1236 	spin_lock_irqsave(&ds->base.lock, flags);
1237 	ds->update_lightbar = true;
1238 	ds->lightbar_red = red;
1239 	ds->lightbar_green = green;
1240 	ds->lightbar_blue = blue;
1241 	spin_unlock_irqrestore(&ds->base.lock, flags);
1242 
1243 	schedule_work(&ds->output_worker);
1244 }
1245 
1246 static void dualsense_set_player_leds(struct dualsense *ds)
1247 {
1248 	/*
1249 	 * The DualSense controller has a row of 5 LEDs used for player ids.
1250 	 * Behavior on the PlayStation 5 console is to center the player id
1251 	 * across the LEDs, so e.g. player 1 would be "--x--" with x being 'on'.
1252 	 * Follow a similar mapping here.
1253 	 */
1254 	static const int player_ids[5] = {
1255 		BIT(2),
1256 		BIT(3) | BIT(1),
1257 		BIT(4) | BIT(2) | BIT(0),
1258 		BIT(4) | BIT(3) | BIT(1) | BIT(0),
1259 		BIT(4) | BIT(3) | BIT(2) | BIT(1) | BIT(0)
1260 	};
1261 
1262 	uint8_t player_id = ds->base.player_id % ARRAY_SIZE(player_ids);
1263 
1264 	ds->update_player_leds = true;
1265 	ds->player_leds_state = player_ids[player_id];
1266 	schedule_work(&ds->output_worker);
1267 }
1268 
1269 static struct ps_device *dualsense_create(struct hid_device *hdev)
1270 {
1271 	struct dualsense *ds;
1272 	struct ps_device *ps_dev;
1273 	uint8_t max_output_report_size;
1274 	int i, ret;
1275 
1276 	static const struct ps_led_info player_leds_info[] = {
1277 		{ LED_FUNCTION_PLAYER1, "white", dualsense_player_led_get_brightness,
1278 				dualsense_player_led_set_brightness },
1279 		{ LED_FUNCTION_PLAYER2, "white", dualsense_player_led_get_brightness,
1280 				dualsense_player_led_set_brightness },
1281 		{ LED_FUNCTION_PLAYER3, "white", dualsense_player_led_get_brightness,
1282 				dualsense_player_led_set_brightness },
1283 		{ LED_FUNCTION_PLAYER4, "white", dualsense_player_led_get_brightness,
1284 				dualsense_player_led_set_brightness },
1285 		{ LED_FUNCTION_PLAYER5, "white", dualsense_player_led_get_brightness,
1286 				dualsense_player_led_set_brightness }
1287 	};
1288 
1289 	ds = devm_kzalloc(&hdev->dev, sizeof(*ds), GFP_KERNEL);
1290 	if (!ds)
1291 		return ERR_PTR(-ENOMEM);
1292 
1293 	/*
1294 	 * Patch version to allow userspace to distinguish between
1295 	 * hid-generic vs hid-playstation axis and button mapping.
1296 	 */
1297 	hdev->version |= HID_PLAYSTATION_VERSION_PATCH;
1298 
1299 	ps_dev = &ds->base;
1300 	ps_dev->hdev = hdev;
1301 	spin_lock_init(&ps_dev->lock);
1302 	ps_dev->battery_capacity = 100; /* initial value until parse_report. */
1303 	ps_dev->battery_status = POWER_SUPPLY_STATUS_UNKNOWN;
1304 	ps_dev->parse_report = dualsense_parse_report;
1305 	INIT_WORK(&ds->output_worker, dualsense_output_worker);
1306 	hid_set_drvdata(hdev, ds);
1307 
1308 	max_output_report_size = sizeof(struct dualsense_output_report_bt);
1309 	ds->output_report_dmabuf = devm_kzalloc(&hdev->dev, max_output_report_size, GFP_KERNEL);
1310 	if (!ds->output_report_dmabuf)
1311 		return ERR_PTR(-ENOMEM);
1312 
1313 	ret = dualsense_get_mac_address(ds);
1314 	if (ret) {
1315 		hid_err(hdev, "Failed to get MAC address from DualSense\n");
1316 		return ERR_PTR(ret);
1317 	}
1318 	snprintf(hdev->uniq, sizeof(hdev->uniq), "%pMR", ds->base.mac_address);
1319 
1320 	ret = dualsense_get_firmware_info(ds);
1321 	if (ret) {
1322 		hid_err(hdev, "Failed to get firmware info from DualSense\n");
1323 		return ERR_PTR(ret);
1324 	}
1325 
1326 	ret = ps_devices_list_add(ps_dev);
1327 	if (ret)
1328 		return ERR_PTR(ret);
1329 
1330 	ret = dualsense_get_calibration_data(ds);
1331 	if (ret) {
1332 		hid_err(hdev, "Failed to get calibration data from DualSense\n");
1333 		goto err;
1334 	}
1335 
1336 	ds->gamepad = ps_gamepad_create(hdev, dualsense_play_effect);
1337 	if (IS_ERR(ds->gamepad)) {
1338 		ret = PTR_ERR(ds->gamepad);
1339 		goto err;
1340 	}
1341 	/* Use gamepad input device name as primary device name for e.g. LEDs */
1342 	ps_dev->input_dev_name = dev_name(&ds->gamepad->dev);
1343 
1344 	ds->sensors = ps_sensors_create(hdev, DS_ACC_RANGE, DS_ACC_RES_PER_G,
1345 			DS_GYRO_RANGE, DS_GYRO_RES_PER_DEG_S);
1346 	if (IS_ERR(ds->sensors)) {
1347 		ret = PTR_ERR(ds->sensors);
1348 		goto err;
1349 	}
1350 
1351 	ds->touchpad = ps_touchpad_create(hdev, DS_TOUCHPAD_WIDTH, DS_TOUCHPAD_HEIGHT, 2);
1352 	if (IS_ERR(ds->touchpad)) {
1353 		ret = PTR_ERR(ds->touchpad);
1354 		goto err;
1355 	}
1356 
1357 	ret = ps_device_register_battery(ps_dev);
1358 	if (ret)
1359 		goto err;
1360 
1361 	/*
1362 	 * The hardware may have control over the LEDs (e.g. in Bluetooth on startup).
1363 	 * Reset the LEDs (lightbar, mute, player leds), so we can control them
1364 	 * from software.
1365 	 */
1366 	ret = dualsense_reset_leds(ds);
1367 	if (ret)
1368 		goto err;
1369 
1370 	ret = ps_lightbar_register(ps_dev, &ds->lightbar, dualsense_lightbar_set_brightness);
1371 	if (ret)
1372 		goto err;
1373 
1374 	/* Set default lightbar color. */
1375 	dualsense_set_lightbar(ds, 0, 0, 128); /* blue */
1376 
1377 	for (i = 0; i < ARRAY_SIZE(player_leds_info); i++) {
1378 		const struct ps_led_info *led_info = &player_leds_info[i];
1379 
1380 		ret = ps_led_register(ps_dev, &ds->player_leds[i], led_info);
1381 		if (ret < 0)
1382 			goto err;
1383 	}
1384 
1385 	ret = ps_device_set_player_id(ps_dev);
1386 	if (ret) {
1387 		hid_err(hdev, "Failed to assign player id for DualSense: %d\n", ret);
1388 		goto err;
1389 	}
1390 
1391 	/* Set player LEDs to our player id. */
1392 	dualsense_set_player_leds(ds);
1393 
1394 	/*
1395 	 * Reporting hardware and firmware is important as there are frequent updates, which
1396 	 * can change behavior.
1397 	 */
1398 	hid_info(hdev, "Registered DualSense controller hw_version=0x%08x fw_version=0x%08x\n",
1399 			ds->base.hw_version, ds->base.fw_version);
1400 
1401 	return &ds->base;
1402 
1403 err:
1404 	ps_devices_list_remove(ps_dev);
1405 	return ERR_PTR(ret);
1406 }
1407 
1408 static int ps_raw_event(struct hid_device *hdev, struct hid_report *report,
1409 		u8 *data, int size)
1410 {
1411 	struct ps_device *dev = hid_get_drvdata(hdev);
1412 
1413 	if (dev && dev->parse_report)
1414 		return dev->parse_report(dev, report, data, size);
1415 
1416 	return 0;
1417 }
1418 
1419 static int ps_probe(struct hid_device *hdev, const struct hid_device_id *id)
1420 {
1421 	struct ps_device *dev;
1422 	int ret;
1423 
1424 	ret = hid_parse(hdev);
1425 	if (ret) {
1426 		hid_err(hdev, "Parse failed\n");
1427 		return ret;
1428 	}
1429 
1430 	ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
1431 	if (ret) {
1432 		hid_err(hdev, "Failed to start HID device\n");
1433 		return ret;
1434 	}
1435 
1436 	ret = hid_hw_open(hdev);
1437 	if (ret) {
1438 		hid_err(hdev, "Failed to open HID device\n");
1439 		goto err_stop;
1440 	}
1441 
1442 	if (hdev->product == USB_DEVICE_ID_SONY_PS5_CONTROLLER) {
1443 		dev = dualsense_create(hdev);
1444 		if (IS_ERR(dev)) {
1445 			hid_err(hdev, "Failed to create dualsense.\n");
1446 			ret = PTR_ERR(dev);
1447 			goto err_close;
1448 		}
1449 	}
1450 
1451 	ret = devm_device_add_group(&hdev->dev, &ps_device_attribute_group);
1452 	if (ret) {
1453 		hid_err(hdev, "Failed to register sysfs nodes.\n");
1454 		goto err_close;
1455 	}
1456 
1457 	return ret;
1458 
1459 err_close:
1460 	hid_hw_close(hdev);
1461 err_stop:
1462 	hid_hw_stop(hdev);
1463 	return ret;
1464 }
1465 
1466 static void ps_remove(struct hid_device *hdev)
1467 {
1468 	struct ps_device *dev = hid_get_drvdata(hdev);
1469 
1470 	ps_devices_list_remove(dev);
1471 	ps_device_release_player_id(dev);
1472 
1473 	hid_hw_close(hdev);
1474 	hid_hw_stop(hdev);
1475 }
1476 
1477 static const struct hid_device_id ps_devices[] = {
1478 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER) },
1479 	{ HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER) },
1480 	{ }
1481 };
1482 MODULE_DEVICE_TABLE(hid, ps_devices);
1483 
1484 static struct hid_driver ps_driver = {
1485 	.name		= "playstation",
1486 	.id_table	= ps_devices,
1487 	.probe		= ps_probe,
1488 	.remove		= ps_remove,
1489 	.raw_event	= ps_raw_event,
1490 };
1491 
1492 static int __init ps_init(void)
1493 {
1494 	return hid_register_driver(&ps_driver);
1495 }
1496 
1497 static void __exit ps_exit(void)
1498 {
1499 	hid_unregister_driver(&ps_driver);
1500 	ida_destroy(&ps_player_id_allocator);
1501 }
1502 
1503 module_init(ps_init);
1504 module_exit(ps_exit);
1505 
1506 MODULE_AUTHOR("Sony Interactive Entertainment");
1507 MODULE_DESCRIPTION("HID Driver for PlayStation peripherals.");
1508 MODULE_LICENSE("GPL");
1509