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 */
ps_devices_list_add(struct ps_device * dev)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
ps_devices_list_remove(struct ps_device * dev)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
ps_device_set_player_id(struct ps_device * dev)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
ps_device_release_player_id(struct ps_device * dev)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
ps_allocate_input_dev(struct hid_device * hdev,const char * name_suffix)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
ps_battery_get_property(struct power_supply * psy,enum power_supply_property psp,union power_supply_propval * val)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
ps_device_register_battery(struct ps_device * dev)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. */
ps_check_crc32(uint8_t seed,uint8_t * data,size_t len,uint32_t report_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
ps_gamepad_create(struct hid_device * hdev,int (* play_effect)(struct input_dev *,void *,struct ff_effect *))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
ps_get_report(struct hid_device * hdev,uint8_t report_id,uint8_t * buf,size_t size)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
ps_led_register(struct ps_device * ps_dev,struct led_classdev * led,const struct ps_led_info * led_info)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. */
ps_lightbar_register(struct ps_device * ps_dev,struct led_classdev_mc * lightbar_mc_dev,int (* brightness_set)(struct led_classdev *,enum led_brightness))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
ps_sensors_create(struct hid_device * hdev,int accel_range,int accel_res,int gyro_range,int gyro_res)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
ps_touchpad_create(struct hid_device * hdev,int width,int height,unsigned int num_contacts)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
firmware_version_show(struct device * dev,struct device_attribute * attr,char * buf)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
hardware_version_show(struct device * dev,struct device_attribute * attr,char * buf)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
dualsense_get_calibration_data(struct dualsense * ds)713 static int dualsense_get_calibration_data(struct dualsense *ds)
714 {
715 struct hid_device *hdev = ds->base.hdev;
716 short gyro_pitch_bias, gyro_pitch_plus, gyro_pitch_minus;
717 short gyro_yaw_bias, gyro_yaw_plus, gyro_yaw_minus;
718 short gyro_roll_bias, gyro_roll_plus, gyro_roll_minus;
719 short gyro_speed_plus, gyro_speed_minus;
720 short acc_x_plus, acc_x_minus;
721 short acc_y_plus, acc_y_minus;
722 short acc_z_plus, acc_z_minus;
723 int speed_2x;
724 int range_2g;
725 int ret = 0;
726 int i;
727 uint8_t *buf;
728
729 buf = kzalloc(DS_FEATURE_REPORT_CALIBRATION_SIZE, GFP_KERNEL);
730 if (!buf)
731 return -ENOMEM;
732
733 ret = ps_get_report(ds->base.hdev, DS_FEATURE_REPORT_CALIBRATION, buf,
734 DS_FEATURE_REPORT_CALIBRATION_SIZE);
735 if (ret) {
736 hid_err(ds->base.hdev, "Failed to retrieve DualSense calibration info: %d\n", ret);
737 goto err_free;
738 }
739
740 gyro_pitch_bias = get_unaligned_le16(&buf[1]);
741 gyro_yaw_bias = get_unaligned_le16(&buf[3]);
742 gyro_roll_bias = get_unaligned_le16(&buf[5]);
743 gyro_pitch_plus = get_unaligned_le16(&buf[7]);
744 gyro_pitch_minus = get_unaligned_le16(&buf[9]);
745 gyro_yaw_plus = get_unaligned_le16(&buf[11]);
746 gyro_yaw_minus = get_unaligned_le16(&buf[13]);
747 gyro_roll_plus = get_unaligned_le16(&buf[15]);
748 gyro_roll_minus = get_unaligned_le16(&buf[17]);
749 gyro_speed_plus = get_unaligned_le16(&buf[19]);
750 gyro_speed_minus = get_unaligned_le16(&buf[21]);
751 acc_x_plus = get_unaligned_le16(&buf[23]);
752 acc_x_minus = get_unaligned_le16(&buf[25]);
753 acc_y_plus = get_unaligned_le16(&buf[27]);
754 acc_y_minus = get_unaligned_le16(&buf[29]);
755 acc_z_plus = get_unaligned_le16(&buf[31]);
756 acc_z_minus = get_unaligned_le16(&buf[33]);
757
758 /*
759 * Set gyroscope calibration and normalization parameters.
760 * Data values will be normalized to 1/DS_GYRO_RES_PER_DEG_S degree/s.
761 */
762 speed_2x = (gyro_speed_plus + gyro_speed_minus);
763 ds->gyro_calib_data[0].abs_code = ABS_RX;
764 ds->gyro_calib_data[0].bias = gyro_pitch_bias;
765 ds->gyro_calib_data[0].sens_numer = speed_2x*DS_GYRO_RES_PER_DEG_S;
766 ds->gyro_calib_data[0].sens_denom = gyro_pitch_plus - gyro_pitch_minus;
767
768 ds->gyro_calib_data[1].abs_code = ABS_RY;
769 ds->gyro_calib_data[1].bias = gyro_yaw_bias;
770 ds->gyro_calib_data[1].sens_numer = speed_2x*DS_GYRO_RES_PER_DEG_S;
771 ds->gyro_calib_data[1].sens_denom = gyro_yaw_plus - gyro_yaw_minus;
772
773 ds->gyro_calib_data[2].abs_code = ABS_RZ;
774 ds->gyro_calib_data[2].bias = gyro_roll_bias;
775 ds->gyro_calib_data[2].sens_numer = speed_2x*DS_GYRO_RES_PER_DEG_S;
776 ds->gyro_calib_data[2].sens_denom = gyro_roll_plus - gyro_roll_minus;
777
778 /*
779 * Sanity check gyro calibration data. This is needed to prevent crashes
780 * during report handling of virtual, clone or broken devices not implementing
781 * calibration data properly.
782 */
783 for (i = 0; i < ARRAY_SIZE(ds->gyro_calib_data); i++) {
784 if (ds->gyro_calib_data[i].sens_denom == 0) {
785 hid_warn(hdev, "Invalid gyro calibration data for axis (%d), disabling calibration.",
786 ds->gyro_calib_data[i].abs_code);
787 ds->gyro_calib_data[i].bias = 0;
788 ds->gyro_calib_data[i].sens_numer = DS_GYRO_RANGE;
789 ds->gyro_calib_data[i].sens_denom = S16_MAX;
790 }
791 }
792
793 /*
794 * Set accelerometer calibration and normalization parameters.
795 * Data values will be normalized to 1/DS_ACC_RES_PER_G g.
796 */
797 range_2g = acc_x_plus - acc_x_minus;
798 ds->accel_calib_data[0].abs_code = ABS_X;
799 ds->accel_calib_data[0].bias = acc_x_plus - range_2g / 2;
800 ds->accel_calib_data[0].sens_numer = 2*DS_ACC_RES_PER_G;
801 ds->accel_calib_data[0].sens_denom = range_2g;
802
803 range_2g = acc_y_plus - acc_y_minus;
804 ds->accel_calib_data[1].abs_code = ABS_Y;
805 ds->accel_calib_data[1].bias = acc_y_plus - range_2g / 2;
806 ds->accel_calib_data[1].sens_numer = 2*DS_ACC_RES_PER_G;
807 ds->accel_calib_data[1].sens_denom = range_2g;
808
809 range_2g = acc_z_plus - acc_z_minus;
810 ds->accel_calib_data[2].abs_code = ABS_Z;
811 ds->accel_calib_data[2].bias = acc_z_plus - range_2g / 2;
812 ds->accel_calib_data[2].sens_numer = 2*DS_ACC_RES_PER_G;
813 ds->accel_calib_data[2].sens_denom = range_2g;
814
815 /*
816 * Sanity check accelerometer calibration data. This is needed to prevent crashes
817 * during report handling of virtual, clone or broken devices not implementing calibration
818 * data properly.
819 */
820 for (i = 0; i < ARRAY_SIZE(ds->accel_calib_data); i++) {
821 if (ds->accel_calib_data[i].sens_denom == 0) {
822 hid_warn(hdev, "Invalid accelerometer calibration data for axis (%d), disabling calibration.",
823 ds->accel_calib_data[i].abs_code);
824 ds->accel_calib_data[i].bias = 0;
825 ds->accel_calib_data[i].sens_numer = DS_ACC_RANGE;
826 ds->accel_calib_data[i].sens_denom = S16_MAX;
827 }
828 }
829
830 err_free:
831 kfree(buf);
832 return ret;
833 }
834
835
dualsense_get_firmware_info(struct dualsense * ds)836 static int dualsense_get_firmware_info(struct dualsense *ds)
837 {
838 uint8_t *buf;
839 int ret;
840
841 buf = kzalloc(DS_FEATURE_REPORT_FIRMWARE_INFO_SIZE, GFP_KERNEL);
842 if (!buf)
843 return -ENOMEM;
844
845 ret = ps_get_report(ds->base.hdev, DS_FEATURE_REPORT_FIRMWARE_INFO, buf,
846 DS_FEATURE_REPORT_FIRMWARE_INFO_SIZE);
847 if (ret) {
848 hid_err(ds->base.hdev, "Failed to retrieve DualSense firmware info: %d\n", ret);
849 goto err_free;
850 }
851
852 ds->base.hw_version = get_unaligned_le32(&buf[24]);
853 ds->base.fw_version = get_unaligned_le32(&buf[28]);
854
855 /* Update version is some kind of feature version. It is distinct from
856 * the firmware version as there can be many different variations of a
857 * controller over time with the same physical shell, but with different
858 * PCBs and other internal changes. The update version (internal name) is
859 * used as a means to detect what features are available and change behavior.
860 * Note: the version is different between DualSense and DualSense Edge.
861 */
862 ds->update_version = get_unaligned_le16(&buf[44]);
863
864 err_free:
865 kfree(buf);
866 return ret;
867 }
868
dualsense_get_mac_address(struct dualsense * ds)869 static int dualsense_get_mac_address(struct dualsense *ds)
870 {
871 uint8_t *buf;
872 int ret = 0;
873
874 buf = kzalloc(DS_FEATURE_REPORT_PAIRING_INFO_SIZE, GFP_KERNEL);
875 if (!buf)
876 return -ENOMEM;
877
878 ret = ps_get_report(ds->base.hdev, DS_FEATURE_REPORT_PAIRING_INFO, buf,
879 DS_FEATURE_REPORT_PAIRING_INFO_SIZE);
880 if (ret) {
881 hid_err(ds->base.hdev, "Failed to retrieve DualSense pairing info: %d\n", ret);
882 goto err_free;
883 }
884
885 memcpy(ds->base.mac_address, &buf[1], sizeof(ds->base.mac_address));
886
887 err_free:
888 kfree(buf);
889 return ret;
890 }
891
dualsense_lightbar_set_brightness(struct led_classdev * cdev,enum led_brightness brightness)892 static int dualsense_lightbar_set_brightness(struct led_classdev *cdev,
893 enum led_brightness brightness)
894 {
895 struct led_classdev_mc *mc_cdev = lcdev_to_mccdev(cdev);
896 struct dualsense *ds = container_of(mc_cdev, struct dualsense, lightbar);
897 uint8_t red, green, blue;
898
899 led_mc_calc_color_components(mc_cdev, brightness);
900 red = mc_cdev->subled_info[0].brightness;
901 green = mc_cdev->subled_info[1].brightness;
902 blue = mc_cdev->subled_info[2].brightness;
903
904 dualsense_set_lightbar(ds, red, green, blue);
905 return 0;
906 }
907
dualsense_player_led_get_brightness(struct led_classdev * led)908 static enum led_brightness dualsense_player_led_get_brightness(struct led_classdev *led)
909 {
910 struct hid_device *hdev = to_hid_device(led->dev->parent);
911 struct dualsense *ds = hid_get_drvdata(hdev);
912
913 return !!(ds->player_leds_state & BIT(led - ds->player_leds));
914 }
915
dualsense_player_led_set_brightness(struct led_classdev * led,enum led_brightness value)916 static int dualsense_player_led_set_brightness(struct led_classdev *led, enum led_brightness value)
917 {
918 struct hid_device *hdev = to_hid_device(led->dev->parent);
919 struct dualsense *ds = hid_get_drvdata(hdev);
920 unsigned long flags;
921 unsigned int led_index;
922
923 spin_lock_irqsave(&ds->base.lock, flags);
924
925 led_index = led - ds->player_leds;
926 if (value == LED_OFF)
927 ds->player_leds_state &= ~BIT(led_index);
928 else
929 ds->player_leds_state |= BIT(led_index);
930
931 ds->update_player_leds = true;
932 spin_unlock_irqrestore(&ds->base.lock, flags);
933
934 dualsense_schedule_work(ds);
935
936 return 0;
937 }
938
dualsense_init_output_report(struct dualsense * ds,struct dualsense_output_report * rp,void * buf)939 static void dualsense_init_output_report(struct dualsense *ds, struct dualsense_output_report *rp,
940 void *buf)
941 {
942 struct hid_device *hdev = ds->base.hdev;
943
944 if (hdev->bus == BUS_BLUETOOTH) {
945 struct dualsense_output_report_bt *bt = buf;
946
947 memset(bt, 0, sizeof(*bt));
948 bt->report_id = DS_OUTPUT_REPORT_BT;
949 bt->tag = DS_OUTPUT_TAG; /* Tag must be set. Exact meaning is unclear. */
950
951 /*
952 * Highest 4-bit is a sequence number, which needs to be increased
953 * every report. Lowest 4-bit is tag and can be zero for now.
954 */
955 bt->seq_tag = (ds->output_seq << 4) | 0x0;
956 if (++ds->output_seq == 16)
957 ds->output_seq = 0;
958
959 rp->data = buf;
960 rp->len = sizeof(*bt);
961 rp->bt = bt;
962 rp->usb = NULL;
963 rp->common = &bt->common;
964 } else { /* USB */
965 struct dualsense_output_report_usb *usb = buf;
966
967 memset(usb, 0, sizeof(*usb));
968 usb->report_id = DS_OUTPUT_REPORT_USB;
969
970 rp->data = buf;
971 rp->len = sizeof(*usb);
972 rp->bt = NULL;
973 rp->usb = usb;
974 rp->common = &usb->common;
975 }
976 }
977
dualsense_schedule_work(struct dualsense * ds)978 static inline void dualsense_schedule_work(struct dualsense *ds)
979 {
980 unsigned long flags;
981
982 spin_lock_irqsave(&ds->base.lock, flags);
983 if (ds->output_worker_initialized)
984 schedule_work(&ds->output_worker);
985 spin_unlock_irqrestore(&ds->base.lock, flags);
986 }
987
988 /*
989 * Helper function to send DualSense output reports. Applies a CRC at the end of a report
990 * for Bluetooth reports.
991 */
dualsense_send_output_report(struct dualsense * ds,struct dualsense_output_report * report)992 static void dualsense_send_output_report(struct dualsense *ds,
993 struct dualsense_output_report *report)
994 {
995 struct hid_device *hdev = ds->base.hdev;
996
997 /* Bluetooth packets need to be signed with a CRC in the last 4 bytes. */
998 if (report->bt) {
999 uint32_t crc;
1000 uint8_t seed = PS_OUTPUT_CRC32_SEED;
1001
1002 crc = crc32_le(0xFFFFFFFF, &seed, 1);
1003 crc = ~crc32_le(crc, report->data, report->len - 4);
1004
1005 report->bt->crc32 = cpu_to_le32(crc);
1006 }
1007
1008 hid_hw_output_report(hdev, report->data, report->len);
1009 }
1010
dualsense_output_worker(struct work_struct * work)1011 static void dualsense_output_worker(struct work_struct *work)
1012 {
1013 struct dualsense *ds = container_of(work, struct dualsense, output_worker);
1014 struct dualsense_output_report report;
1015 struct dualsense_output_report_common *common;
1016 unsigned long flags;
1017
1018 dualsense_init_output_report(ds, &report, ds->output_report_dmabuf);
1019 common = report.common;
1020
1021 spin_lock_irqsave(&ds->base.lock, flags);
1022
1023 if (ds->update_rumble) {
1024 /* Select classic rumble style haptics and enable it. */
1025 common->valid_flag0 |= DS_OUTPUT_VALID_FLAG0_HAPTICS_SELECT;
1026 if (ds->use_vibration_v2)
1027 common->valid_flag2 |= DS_OUTPUT_VALID_FLAG2_COMPATIBLE_VIBRATION2;
1028 else
1029 common->valid_flag0 |= DS_OUTPUT_VALID_FLAG0_COMPATIBLE_VIBRATION;
1030 common->motor_left = ds->motor_left;
1031 common->motor_right = ds->motor_right;
1032 ds->update_rumble = false;
1033 }
1034
1035 if (ds->update_lightbar) {
1036 common->valid_flag1 |= DS_OUTPUT_VALID_FLAG1_LIGHTBAR_CONTROL_ENABLE;
1037 common->lightbar_red = ds->lightbar_red;
1038 common->lightbar_green = ds->lightbar_green;
1039 common->lightbar_blue = ds->lightbar_blue;
1040
1041 ds->update_lightbar = false;
1042 }
1043
1044 if (ds->update_player_leds) {
1045 common->valid_flag1 |= DS_OUTPUT_VALID_FLAG1_PLAYER_INDICATOR_CONTROL_ENABLE;
1046 common->player_leds = ds->player_leds_state;
1047
1048 ds->update_player_leds = false;
1049 }
1050
1051 if (ds->update_mic_mute) {
1052 common->valid_flag1 |= DS_OUTPUT_VALID_FLAG1_MIC_MUTE_LED_CONTROL_ENABLE;
1053 common->mute_button_led = ds->mic_muted;
1054
1055 if (ds->mic_muted) {
1056 /* Disable microphone */
1057 common->valid_flag1 |= DS_OUTPUT_VALID_FLAG1_POWER_SAVE_CONTROL_ENABLE;
1058 common->power_save_control |= DS_OUTPUT_POWER_SAVE_CONTROL_MIC_MUTE;
1059 } else {
1060 /* Enable microphone */
1061 common->valid_flag1 |= DS_OUTPUT_VALID_FLAG1_POWER_SAVE_CONTROL_ENABLE;
1062 common->power_save_control &= ~DS_OUTPUT_POWER_SAVE_CONTROL_MIC_MUTE;
1063 }
1064
1065 ds->update_mic_mute = false;
1066 }
1067
1068 spin_unlock_irqrestore(&ds->base.lock, flags);
1069
1070 dualsense_send_output_report(ds, &report);
1071 }
1072
dualsense_parse_report(struct ps_device * ps_dev,struct hid_report * report,u8 * data,int size)1073 static int dualsense_parse_report(struct ps_device *ps_dev, struct hid_report *report,
1074 u8 *data, int size)
1075 {
1076 struct hid_device *hdev = ps_dev->hdev;
1077 struct dualsense *ds = container_of(ps_dev, struct dualsense, base);
1078 struct dualsense_input_report *ds_report;
1079 uint8_t battery_data, battery_capacity, charging_status, value;
1080 int battery_status;
1081 uint32_t sensor_timestamp;
1082 bool btn_mic_state;
1083 unsigned long flags;
1084 int i;
1085
1086 /*
1087 * DualSense in USB uses the full HID report for reportID 1, but
1088 * Bluetooth uses a minimal HID report for reportID 1 and reports
1089 * the full report using reportID 49.
1090 */
1091 if (hdev->bus == BUS_USB && report->id == DS_INPUT_REPORT_USB &&
1092 size == DS_INPUT_REPORT_USB_SIZE) {
1093 ds_report = (struct dualsense_input_report *)&data[1];
1094 } else if (hdev->bus == BUS_BLUETOOTH && report->id == DS_INPUT_REPORT_BT &&
1095 size == DS_INPUT_REPORT_BT_SIZE) {
1096 /* Last 4 bytes of input report contain crc32 */
1097 uint32_t report_crc = get_unaligned_le32(&data[size - 4]);
1098
1099 if (!ps_check_crc32(PS_INPUT_CRC32_SEED, data, size - 4, report_crc)) {
1100 hid_err(hdev, "DualSense input CRC's check failed\n");
1101 return -EILSEQ;
1102 }
1103
1104 ds_report = (struct dualsense_input_report *)&data[2];
1105 } else {
1106 hid_err(hdev, "Unhandled reportID=%d\n", report->id);
1107 return -1;
1108 }
1109
1110 input_report_abs(ds->gamepad, ABS_X, ds_report->x);
1111 input_report_abs(ds->gamepad, ABS_Y, ds_report->y);
1112 input_report_abs(ds->gamepad, ABS_RX, ds_report->rx);
1113 input_report_abs(ds->gamepad, ABS_RY, ds_report->ry);
1114 input_report_abs(ds->gamepad, ABS_Z, ds_report->z);
1115 input_report_abs(ds->gamepad, ABS_RZ, ds_report->rz);
1116
1117 value = ds_report->buttons[0] & DS_BUTTONS0_HAT_SWITCH;
1118 if (value >= ARRAY_SIZE(ps_gamepad_hat_mapping))
1119 value = 8; /* center */
1120 input_report_abs(ds->gamepad, ABS_HAT0X, ps_gamepad_hat_mapping[value].x);
1121 input_report_abs(ds->gamepad, ABS_HAT0Y, ps_gamepad_hat_mapping[value].y);
1122
1123 input_report_key(ds->gamepad, BTN_WEST, ds_report->buttons[0] & DS_BUTTONS0_SQUARE);
1124 input_report_key(ds->gamepad, BTN_SOUTH, ds_report->buttons[0] & DS_BUTTONS0_CROSS);
1125 input_report_key(ds->gamepad, BTN_EAST, ds_report->buttons[0] & DS_BUTTONS0_CIRCLE);
1126 input_report_key(ds->gamepad, BTN_NORTH, ds_report->buttons[0] & DS_BUTTONS0_TRIANGLE);
1127 input_report_key(ds->gamepad, BTN_TL, ds_report->buttons[1] & DS_BUTTONS1_L1);
1128 input_report_key(ds->gamepad, BTN_TR, ds_report->buttons[1] & DS_BUTTONS1_R1);
1129 input_report_key(ds->gamepad, BTN_TL2, ds_report->buttons[1] & DS_BUTTONS1_L2);
1130 input_report_key(ds->gamepad, BTN_TR2, ds_report->buttons[1] & DS_BUTTONS1_R2);
1131 input_report_key(ds->gamepad, BTN_SELECT, ds_report->buttons[1] & DS_BUTTONS1_CREATE);
1132 input_report_key(ds->gamepad, BTN_START, ds_report->buttons[1] & DS_BUTTONS1_OPTIONS);
1133 input_report_key(ds->gamepad, BTN_THUMBL, ds_report->buttons[1] & DS_BUTTONS1_L3);
1134 input_report_key(ds->gamepad, BTN_THUMBR, ds_report->buttons[1] & DS_BUTTONS1_R3);
1135 input_report_key(ds->gamepad, BTN_MODE, ds_report->buttons[2] & DS_BUTTONS2_PS_HOME);
1136 input_sync(ds->gamepad);
1137
1138 /*
1139 * The DualSense has an internal microphone, which can be muted through a mute button
1140 * on the device. The driver is expected to read the button state and program the device
1141 * to mute/unmute audio at the hardware level.
1142 */
1143 btn_mic_state = !!(ds_report->buttons[2] & DS_BUTTONS2_MIC_MUTE);
1144 if (btn_mic_state && !ds->last_btn_mic_state) {
1145 spin_lock_irqsave(&ps_dev->lock, flags);
1146 ds->update_mic_mute = true;
1147 ds->mic_muted = !ds->mic_muted; /* toggle */
1148 spin_unlock_irqrestore(&ps_dev->lock, flags);
1149
1150 /* Schedule updating of microphone state at hardware level. */
1151 dualsense_schedule_work(ds);
1152 }
1153 ds->last_btn_mic_state = btn_mic_state;
1154
1155 /* Parse and calibrate gyroscope data. */
1156 for (i = 0; i < ARRAY_SIZE(ds_report->gyro); i++) {
1157 int raw_data = (short)le16_to_cpu(ds_report->gyro[i]);
1158 int calib_data = mult_frac(ds->gyro_calib_data[i].sens_numer,
1159 raw_data - ds->gyro_calib_data[i].bias,
1160 ds->gyro_calib_data[i].sens_denom);
1161
1162 input_report_abs(ds->sensors, ds->gyro_calib_data[i].abs_code, calib_data);
1163 }
1164
1165 /* Parse and calibrate accelerometer data. */
1166 for (i = 0; i < ARRAY_SIZE(ds_report->accel); i++) {
1167 int raw_data = (short)le16_to_cpu(ds_report->accel[i]);
1168 int calib_data = mult_frac(ds->accel_calib_data[i].sens_numer,
1169 raw_data - ds->accel_calib_data[i].bias,
1170 ds->accel_calib_data[i].sens_denom);
1171
1172 input_report_abs(ds->sensors, ds->accel_calib_data[i].abs_code, calib_data);
1173 }
1174
1175 /* Convert timestamp (in 0.33us unit) to timestamp_us */
1176 sensor_timestamp = le32_to_cpu(ds_report->sensor_timestamp);
1177 if (!ds->sensor_timestamp_initialized) {
1178 ds->sensor_timestamp_us = DIV_ROUND_CLOSEST(sensor_timestamp, 3);
1179 ds->sensor_timestamp_initialized = true;
1180 } else {
1181 uint32_t delta;
1182
1183 if (ds->prev_sensor_timestamp > sensor_timestamp)
1184 delta = (U32_MAX - ds->prev_sensor_timestamp + sensor_timestamp + 1);
1185 else
1186 delta = sensor_timestamp - ds->prev_sensor_timestamp;
1187 ds->sensor_timestamp_us += DIV_ROUND_CLOSEST(delta, 3);
1188 }
1189 ds->prev_sensor_timestamp = sensor_timestamp;
1190 input_event(ds->sensors, EV_MSC, MSC_TIMESTAMP, ds->sensor_timestamp_us);
1191 input_sync(ds->sensors);
1192
1193 for (i = 0; i < ARRAY_SIZE(ds_report->points); i++) {
1194 struct dualsense_touch_point *point = &ds_report->points[i];
1195 bool active = (point->contact & DS_TOUCH_POINT_INACTIVE) ? false : true;
1196
1197 input_mt_slot(ds->touchpad, i);
1198 input_mt_report_slot_state(ds->touchpad, MT_TOOL_FINGER, active);
1199
1200 if (active) {
1201 int x = (point->x_hi << 8) | point->x_lo;
1202 int y = (point->y_hi << 4) | point->y_lo;
1203
1204 input_report_abs(ds->touchpad, ABS_MT_POSITION_X, x);
1205 input_report_abs(ds->touchpad, ABS_MT_POSITION_Y, y);
1206 }
1207 }
1208 input_mt_sync_frame(ds->touchpad);
1209 input_report_key(ds->touchpad, BTN_LEFT, ds_report->buttons[2] & DS_BUTTONS2_TOUCHPAD);
1210 input_sync(ds->touchpad);
1211
1212 battery_data = ds_report->status & DS_STATUS_BATTERY_CAPACITY;
1213 charging_status = (ds_report->status & DS_STATUS_CHARGING) >> DS_STATUS_CHARGING_SHIFT;
1214
1215 switch (charging_status) {
1216 case 0x0:
1217 /*
1218 * Each unit of battery data corresponds to 10%
1219 * 0 = 0-9%, 1 = 10-19%, .. and 10 = 100%
1220 */
1221 battery_capacity = min(battery_data * 10 + 5, 100);
1222 battery_status = POWER_SUPPLY_STATUS_DISCHARGING;
1223 break;
1224 case 0x1:
1225 battery_capacity = min(battery_data * 10 + 5, 100);
1226 battery_status = POWER_SUPPLY_STATUS_CHARGING;
1227 break;
1228 case 0x2:
1229 battery_capacity = 100;
1230 battery_status = POWER_SUPPLY_STATUS_FULL;
1231 break;
1232 case 0xa: /* voltage or temperature out of range */
1233 case 0xb: /* temperature error */
1234 battery_capacity = 0;
1235 battery_status = POWER_SUPPLY_STATUS_NOT_CHARGING;
1236 break;
1237 case 0xf: /* charging error */
1238 default:
1239 battery_capacity = 0;
1240 battery_status = POWER_SUPPLY_STATUS_UNKNOWN;
1241 }
1242
1243 spin_lock_irqsave(&ps_dev->lock, flags);
1244 ps_dev->battery_capacity = battery_capacity;
1245 ps_dev->battery_status = battery_status;
1246 spin_unlock_irqrestore(&ps_dev->lock, flags);
1247
1248 return 0;
1249 }
1250
dualsense_play_effect(struct input_dev * dev,void * data,struct ff_effect * effect)1251 static int dualsense_play_effect(struct input_dev *dev, void *data, struct ff_effect *effect)
1252 {
1253 struct hid_device *hdev = input_get_drvdata(dev);
1254 struct dualsense *ds = hid_get_drvdata(hdev);
1255 unsigned long flags;
1256
1257 if (effect->type != FF_RUMBLE)
1258 return 0;
1259
1260 spin_lock_irqsave(&ds->base.lock, flags);
1261 ds->update_rumble = true;
1262 ds->motor_left = effect->u.rumble.strong_magnitude / 256;
1263 ds->motor_right = effect->u.rumble.weak_magnitude / 256;
1264 spin_unlock_irqrestore(&ds->base.lock, flags);
1265
1266 dualsense_schedule_work(ds);
1267 return 0;
1268 }
1269
dualsense_remove(struct ps_device * ps_dev)1270 static void dualsense_remove(struct ps_device *ps_dev)
1271 {
1272 struct dualsense *ds = container_of(ps_dev, struct dualsense, base);
1273 unsigned long flags;
1274
1275 spin_lock_irqsave(&ds->base.lock, flags);
1276 ds->output_worker_initialized = false;
1277 spin_unlock_irqrestore(&ds->base.lock, flags);
1278
1279 cancel_work_sync(&ds->output_worker);
1280 }
1281
dualsense_reset_leds(struct dualsense * ds)1282 static int dualsense_reset_leds(struct dualsense *ds)
1283 {
1284 struct dualsense_output_report report;
1285 uint8_t *buf;
1286
1287 buf = kzalloc(sizeof(struct dualsense_output_report_bt), GFP_KERNEL);
1288 if (!buf)
1289 return -ENOMEM;
1290
1291 dualsense_init_output_report(ds, &report, buf);
1292 /*
1293 * On Bluetooth the DualSense outputs an animation on the lightbar
1294 * during startup and maintains a color afterwards. We need to explicitly
1295 * reconfigure the lightbar before we can do any programming later on.
1296 * In USB the lightbar is not on by default, but redoing the setup there
1297 * doesn't hurt.
1298 */
1299 report.common->valid_flag2 = DS_OUTPUT_VALID_FLAG2_LIGHTBAR_SETUP_CONTROL_ENABLE;
1300 report.common->lightbar_setup = DS_OUTPUT_LIGHTBAR_SETUP_LIGHT_OUT; /* Fade light out. */
1301 dualsense_send_output_report(ds, &report);
1302
1303 kfree(buf);
1304 return 0;
1305 }
1306
dualsense_set_lightbar(struct dualsense * ds,uint8_t red,uint8_t green,uint8_t blue)1307 static void dualsense_set_lightbar(struct dualsense *ds, uint8_t red, uint8_t green, uint8_t blue)
1308 {
1309 unsigned long flags;
1310
1311 spin_lock_irqsave(&ds->base.lock, flags);
1312 ds->update_lightbar = true;
1313 ds->lightbar_red = red;
1314 ds->lightbar_green = green;
1315 ds->lightbar_blue = blue;
1316 spin_unlock_irqrestore(&ds->base.lock, flags);
1317
1318 dualsense_schedule_work(ds);
1319 }
1320
dualsense_set_player_leds(struct dualsense * ds)1321 static void dualsense_set_player_leds(struct dualsense *ds)
1322 {
1323 /*
1324 * The DualSense controller has a row of 5 LEDs used for player ids.
1325 * Behavior on the PlayStation 5 console is to center the player id
1326 * across the LEDs, so e.g. player 1 would be "--x--" with x being 'on'.
1327 * Follow a similar mapping here.
1328 */
1329 static const int player_ids[5] = {
1330 BIT(2),
1331 BIT(3) | BIT(1),
1332 BIT(4) | BIT(2) | BIT(0),
1333 BIT(4) | BIT(3) | BIT(1) | BIT(0),
1334 BIT(4) | BIT(3) | BIT(2) | BIT(1) | BIT(0)
1335 };
1336
1337 uint8_t player_id = ds->base.player_id % ARRAY_SIZE(player_ids);
1338
1339 ds->update_player_leds = true;
1340 ds->player_leds_state = player_ids[player_id];
1341 dualsense_schedule_work(ds);
1342 }
1343
dualsense_create(struct hid_device * hdev)1344 static struct ps_device *dualsense_create(struct hid_device *hdev)
1345 {
1346 struct dualsense *ds;
1347 struct ps_device *ps_dev;
1348 uint8_t max_output_report_size;
1349 int i, ret;
1350
1351 static const struct ps_led_info player_leds_info[] = {
1352 { LED_FUNCTION_PLAYER1, "white", dualsense_player_led_get_brightness,
1353 dualsense_player_led_set_brightness },
1354 { LED_FUNCTION_PLAYER2, "white", dualsense_player_led_get_brightness,
1355 dualsense_player_led_set_brightness },
1356 { LED_FUNCTION_PLAYER3, "white", dualsense_player_led_get_brightness,
1357 dualsense_player_led_set_brightness },
1358 { LED_FUNCTION_PLAYER4, "white", dualsense_player_led_get_brightness,
1359 dualsense_player_led_set_brightness },
1360 { LED_FUNCTION_PLAYER5, "white", dualsense_player_led_get_brightness,
1361 dualsense_player_led_set_brightness }
1362 };
1363
1364 ds = devm_kzalloc(&hdev->dev, sizeof(*ds), GFP_KERNEL);
1365 if (!ds)
1366 return ERR_PTR(-ENOMEM);
1367
1368 /*
1369 * Patch version to allow userspace to distinguish between
1370 * hid-generic vs hid-playstation axis and button mapping.
1371 */
1372 hdev->version |= HID_PLAYSTATION_VERSION_PATCH;
1373
1374 ps_dev = &ds->base;
1375 ps_dev->hdev = hdev;
1376 spin_lock_init(&ps_dev->lock);
1377 ps_dev->battery_capacity = 100; /* initial value until parse_report. */
1378 ps_dev->battery_status = POWER_SUPPLY_STATUS_UNKNOWN;
1379 ps_dev->parse_report = dualsense_parse_report;
1380 ps_dev->remove = dualsense_remove;
1381 INIT_WORK(&ds->output_worker, dualsense_output_worker);
1382 ds->output_worker_initialized = true;
1383 hid_set_drvdata(hdev, ds);
1384
1385 max_output_report_size = sizeof(struct dualsense_output_report_bt);
1386 ds->output_report_dmabuf = devm_kzalloc(&hdev->dev, max_output_report_size, GFP_KERNEL);
1387 if (!ds->output_report_dmabuf)
1388 return ERR_PTR(-ENOMEM);
1389
1390 ret = dualsense_get_mac_address(ds);
1391 if (ret) {
1392 hid_err(hdev, "Failed to get MAC address from DualSense\n");
1393 return ERR_PTR(ret);
1394 }
1395 snprintf(hdev->uniq, sizeof(hdev->uniq), "%pMR", ds->base.mac_address);
1396
1397 ret = dualsense_get_firmware_info(ds);
1398 if (ret) {
1399 hid_err(hdev, "Failed to get firmware info from DualSense\n");
1400 return ERR_PTR(ret);
1401 }
1402
1403 /* Original DualSense firmware simulated classic controller rumble through
1404 * its new haptics hardware. It felt different from classic rumble users
1405 * were used to. Since then new firmwares were introduced to change behavior
1406 * and make this new 'v2' behavior default on PlayStation and other platforms.
1407 * The original DualSense requires a new enough firmware as bundled with PS5
1408 * software released in 2021. DualSense edge supports it out of the box.
1409 * Both devices also support the old mode, but it is not really used.
1410 */
1411 if (hdev->product == USB_DEVICE_ID_SONY_PS5_CONTROLLER) {
1412 /* Feature version 2.21 introduced new vibration method. */
1413 ds->use_vibration_v2 = ds->update_version >= DS_FEATURE_VERSION(2, 21);
1414 } else if (hdev->product == USB_DEVICE_ID_SONY_PS5_CONTROLLER_2) {
1415 ds->use_vibration_v2 = true;
1416 }
1417
1418 ret = ps_devices_list_add(ps_dev);
1419 if (ret)
1420 return ERR_PTR(ret);
1421
1422 ret = dualsense_get_calibration_data(ds);
1423 if (ret) {
1424 hid_err(hdev, "Failed to get calibration data from DualSense\n");
1425 goto err;
1426 }
1427
1428 ds->gamepad = ps_gamepad_create(hdev, dualsense_play_effect);
1429 if (IS_ERR(ds->gamepad)) {
1430 ret = PTR_ERR(ds->gamepad);
1431 goto err;
1432 }
1433 /* Use gamepad input device name as primary device name for e.g. LEDs */
1434 ps_dev->input_dev_name = dev_name(&ds->gamepad->dev);
1435
1436 ds->sensors = ps_sensors_create(hdev, DS_ACC_RANGE, DS_ACC_RES_PER_G,
1437 DS_GYRO_RANGE, DS_GYRO_RES_PER_DEG_S);
1438 if (IS_ERR(ds->sensors)) {
1439 ret = PTR_ERR(ds->sensors);
1440 goto err;
1441 }
1442
1443 ds->touchpad = ps_touchpad_create(hdev, DS_TOUCHPAD_WIDTH, DS_TOUCHPAD_HEIGHT, 2);
1444 if (IS_ERR(ds->touchpad)) {
1445 ret = PTR_ERR(ds->touchpad);
1446 goto err;
1447 }
1448
1449 ret = ps_device_register_battery(ps_dev);
1450 if (ret)
1451 goto err;
1452
1453 /*
1454 * The hardware may have control over the LEDs (e.g. in Bluetooth on startup).
1455 * Reset the LEDs (lightbar, mute, player leds), so we can control them
1456 * from software.
1457 */
1458 ret = dualsense_reset_leds(ds);
1459 if (ret)
1460 goto err;
1461
1462 ret = ps_lightbar_register(ps_dev, &ds->lightbar, dualsense_lightbar_set_brightness);
1463 if (ret)
1464 goto err;
1465
1466 /* Set default lightbar color. */
1467 dualsense_set_lightbar(ds, 0, 0, 128); /* blue */
1468
1469 for (i = 0; i < ARRAY_SIZE(player_leds_info); i++) {
1470 const struct ps_led_info *led_info = &player_leds_info[i];
1471
1472 ret = ps_led_register(ps_dev, &ds->player_leds[i], led_info);
1473 if (ret < 0)
1474 goto err;
1475 }
1476
1477 ret = ps_device_set_player_id(ps_dev);
1478 if (ret) {
1479 hid_err(hdev, "Failed to assign player id for DualSense: %d\n", ret);
1480 goto err;
1481 }
1482
1483 /* Set player LEDs to our player id. */
1484 dualsense_set_player_leds(ds);
1485
1486 /*
1487 * Reporting hardware and firmware is important as there are frequent updates, which
1488 * can change behavior.
1489 */
1490 hid_info(hdev, "Registered DualSense controller hw_version=0x%08x fw_version=0x%08x\n",
1491 ds->base.hw_version, ds->base.fw_version);
1492
1493 return &ds->base;
1494
1495 err:
1496 ps_devices_list_remove(ps_dev);
1497 return ERR_PTR(ret);
1498 }
1499
ps_raw_event(struct hid_device * hdev,struct hid_report * report,u8 * data,int size)1500 static int ps_raw_event(struct hid_device *hdev, struct hid_report *report,
1501 u8 *data, int size)
1502 {
1503 struct ps_device *dev = hid_get_drvdata(hdev);
1504
1505 if (dev && dev->parse_report)
1506 return dev->parse_report(dev, report, data, size);
1507
1508 return 0;
1509 }
1510
ps_probe(struct hid_device * hdev,const struct hid_device_id * id)1511 static int ps_probe(struct hid_device *hdev, const struct hid_device_id *id)
1512 {
1513 struct ps_device *dev;
1514 int ret;
1515
1516 ret = hid_parse(hdev);
1517 if (ret) {
1518 hid_err(hdev, "Parse failed\n");
1519 return ret;
1520 }
1521
1522 ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
1523 if (ret) {
1524 hid_err(hdev, "Failed to start HID device\n");
1525 return ret;
1526 }
1527
1528 ret = hid_hw_open(hdev);
1529 if (ret) {
1530 hid_err(hdev, "Failed to open HID device\n");
1531 goto err_stop;
1532 }
1533
1534 if (hdev->product == USB_DEVICE_ID_SONY_PS5_CONTROLLER ||
1535 hdev->product == USB_DEVICE_ID_SONY_PS5_CONTROLLER_2) {
1536 dev = dualsense_create(hdev);
1537 if (IS_ERR(dev)) {
1538 hid_err(hdev, "Failed to create dualsense.\n");
1539 ret = PTR_ERR(dev);
1540 goto err_close;
1541 }
1542 }
1543
1544 return ret;
1545
1546 err_close:
1547 hid_hw_close(hdev);
1548 err_stop:
1549 hid_hw_stop(hdev);
1550 return ret;
1551 }
1552
ps_remove(struct hid_device * hdev)1553 static void ps_remove(struct hid_device *hdev)
1554 {
1555 struct ps_device *dev = hid_get_drvdata(hdev);
1556
1557 ps_devices_list_remove(dev);
1558 ps_device_release_player_id(dev);
1559
1560 if (dev->remove)
1561 dev->remove(dev);
1562
1563 hid_hw_close(hdev);
1564 hid_hw_stop(hdev);
1565 }
1566
1567 static const struct hid_device_id ps_devices[] = {
1568 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER) },
1569 { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER) },
1570 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER_2) },
1571 { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER_2) },
1572 { }
1573 };
1574 MODULE_DEVICE_TABLE(hid, ps_devices);
1575
1576 static struct hid_driver ps_driver = {
1577 .name = "playstation",
1578 .id_table = ps_devices,
1579 .probe = ps_probe,
1580 .remove = ps_remove,
1581 .raw_event = ps_raw_event,
1582 .driver = {
1583 .dev_groups = ps_device_groups,
1584 },
1585 };
1586
ps_init(void)1587 static int __init ps_init(void)
1588 {
1589 return hid_register_driver(&ps_driver);
1590 }
1591
ps_exit(void)1592 static void __exit ps_exit(void)
1593 {
1594 hid_unregister_driver(&ps_driver);
1595 ida_destroy(&ps_player_id_allocator);
1596 }
1597
1598 module_init(ps_init);
1599 module_exit(ps_exit);
1600
1601 MODULE_AUTHOR("Sony Interactive Entertainment");
1602 MODULE_DESCRIPTION("HID Driver for PlayStation peripherals.");
1603 MODULE_LICENSE("GPL");
1604