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