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