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