Linux kernel mirror (for testing)
git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel
os
linux
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. */
25static DEFINE_MUTEX(ps_devices_lock);
26static LIST_HEAD(ps_devices_list);
27
28static DEFINE_IDA(ps_player_id_allocator);
29
30#define HID_PLAYSTATION_VERSION_PATCH 0x8000
31
32enum PS_TYPE {
33 PS_TYPE_PS4_DUALSHOCK4,
34 PS_TYPE_PS5_DUALSENSE,
35};
36
37/* Base class for playstation devices. */
38struct 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. */
60struct ps_calibration_data {
61 int abs_code;
62 short bias;
63 int sens_numer;
64 int sens_denom;
65};
66
67struct 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
174struct 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
227struct dualsense_touch_point {
228 u8 contact;
229 u8 x_lo;
230 u8 x_hi:4, y_lo:4;
231 u8 y_hi;
232} __packed;
233static_assert(sizeof(struct dualsense_touch_point) == 4);
234
235/* Main DualSense input report excluding any BT/USB specific headers. */
236struct 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. */
258static_assert(sizeof(struct dualsense_input_report) == DS_INPUT_REPORT_USB_SIZE - 1);
259
260/* Common data between DualSense BT/USB main output report. */
261struct 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;
290static_assert(sizeof(struct dualsense_output_report_common) == 47);
291
292struct 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;
300static_assert(sizeof(struct dualsense_output_report_bt) == DS_OUTPUT_REPORT_BT_SIZE);
301
302struct dualsense_output_report_usb {
303 u8 report_id; /* 0x02 */
304 struct dualsense_output_report_common common;
305 u8 reserved[15];
306} __packed;
307static_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 */
314struct 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
394enum dualshock4_dongle_state {
395 DONGLE_DISCONNECTED,
396 DONGLE_CALIBRATING,
397 DONGLE_CONNECTED,
398 DONGLE_DISABLED
399};
400
401struct 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
445struct dualshock4_touch_point {
446 u8 contact;
447 u8 x_lo;
448 u8 x_hi:4, y_lo:4;
449 u8 y_hi;
450} __packed;
451static_assert(sizeof(struct dualshock4_touch_point) == 4);
452
453struct dualshock4_touch_report {
454 u8 timestamp;
455 struct dualshock4_touch_point points[2];
456} __packed;
457static_assert(sizeof(struct dualshock4_touch_report) == 9);
458
459/* Main DualShock4 input report excluding any BT/USB specific headers. */
460struct 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;
476static_assert(sizeof(struct dualshock4_input_report_common) == 32);
477
478struct 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;
485static_assert(sizeof(struct dualshock4_input_report_usb) == DS4_INPUT_REPORT_USB_SIZE);
486
487struct 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;
496static_assert(sizeof(struct dualshock4_input_report_bt) == DS4_INPUT_REPORT_BT_SIZE);
497
498/* Common data between Bluetooth and USB DualShock4 output reports. */
499struct 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
515struct dualshock4_output_report_usb {
516 u8 report_id; /* 0x5 */
517 struct dualshock4_output_report_common common;
518 u8 reserved[21];
519} __packed;
520static_assert(sizeof(struct dualshock4_output_report_usb) == DS4_OUTPUT_REPORT_USB_SIZE);
521
522struct 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;
530static_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 */
537struct 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 */
554static 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
570static 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
575static int dualshock4_get_calibration_data(struct dualshock4 *ds4);
576static inline void dualsense_schedule_work(struct dualsense *ds);
577static inline void dualshock4_schedule_work(struct dualshock4 *ds4);
578static void dualsense_set_lightbar(struct dualsense *ds, u8 red, u8 green, u8 blue);
579static 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 */
586static 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
604static 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
612static 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
623static 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
630static 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
659static 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
666static 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
701static 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. */
734static 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
744static struct input_dev *
745ps_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
783static 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
819static 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. */
856static 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
894static 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
931static 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
959static 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
978static 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
987static DEVICE_ATTR_RO(firmware_version);
988
989static 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
998static DEVICE_ATTR_RO(hardware_version);
999
1000static struct attribute *ps_device_attrs[] = {
1001 &dev_attr_firmware_version.attr,
1002 &dev_attr_hardware_version.attr,
1003 NULL
1004};
1005ATTRIBUTE_GROUPS(ps_device);
1006
1007static 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
1129err_free:
1130 kfree(buf);
1131 return ret;
1132}
1133
1134static 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
1162err_free:
1163 kfree(buf);
1164 return ret;
1165}
1166
1167static 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
1185err_free:
1186 kfree(buf);
1187 return ret;
1188}
1189
1190static 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
1206static 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
1214static 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
1235static 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
1275static 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 */
1287static 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
1306static 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
1420static 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
1621static 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
1639static 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
1649static 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
1674static 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
1686static 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
1709static 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
1869err:
1870 ps_devices_list_remove(ps_dev);
1871 return ERR_PTR(ret);
1872}
1873
1874static 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
1900static 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 goto transfer_failed;
1946 } else {
1947 break;
1948 }
1949 }
1950 } else { /* Bluetooth */
1951 buf = kzalloc(DS4_FEATURE_REPORT_CALIBRATION_BT_SIZE, GFP_KERNEL);
1952 if (!buf) {
1953 ret = -ENOMEM;
1954 goto transfer_failed;
1955 }
1956
1957 ret = ps_get_report(hdev, DS4_FEATURE_REPORT_CALIBRATION_BT, buf,
1958 DS4_FEATURE_REPORT_CALIBRATION_BT_SIZE, true);
1959
1960 if (ret) {
1961 hid_warn(hdev, "Failed to retrieve DualShock4 calibration info: %d\n", ret);
1962 goto transfer_failed;
1963 }
1964 }
1965
1966 /* Transfer succeeded - parse the calibration data received. */
1967 gyro_pitch_bias = get_unaligned_le16(&buf[1]);
1968 gyro_yaw_bias = get_unaligned_le16(&buf[3]);
1969 gyro_roll_bias = get_unaligned_le16(&buf[5]);
1970 if (ds4->base.hdev->bus == BUS_USB) {
1971 gyro_pitch_plus = get_unaligned_le16(&buf[7]);
1972 gyro_pitch_minus = get_unaligned_le16(&buf[9]);
1973 gyro_yaw_plus = get_unaligned_le16(&buf[11]);
1974 gyro_yaw_minus = get_unaligned_le16(&buf[13]);
1975 gyro_roll_plus = get_unaligned_le16(&buf[15]);
1976 gyro_roll_minus = get_unaligned_le16(&buf[17]);
1977 } else {
1978 /* BT + Dongle */
1979 gyro_pitch_plus = get_unaligned_le16(&buf[7]);
1980 gyro_yaw_plus = get_unaligned_le16(&buf[9]);
1981 gyro_roll_plus = get_unaligned_le16(&buf[11]);
1982 gyro_pitch_minus = get_unaligned_le16(&buf[13]);
1983 gyro_yaw_minus = get_unaligned_le16(&buf[15]);
1984 gyro_roll_minus = get_unaligned_le16(&buf[17]);
1985 }
1986 gyro_speed_plus = get_unaligned_le16(&buf[19]);
1987 gyro_speed_minus = get_unaligned_le16(&buf[21]);
1988 acc_x_plus = get_unaligned_le16(&buf[23]);
1989 acc_x_minus = get_unaligned_le16(&buf[25]);
1990 acc_y_plus = get_unaligned_le16(&buf[27]);
1991 acc_y_minus = get_unaligned_le16(&buf[29]);
1992 acc_z_plus = get_unaligned_le16(&buf[31]);
1993 acc_z_minus = get_unaligned_le16(&buf[33]);
1994
1995 /* Done parsing the buffer, so let's free it. */
1996 kfree(buf);
1997
1998 /*
1999 * Set gyroscope calibration and normalization parameters.
2000 * Data values will be normalized to 1/DS4_GYRO_RES_PER_DEG_S degree/s.
2001 */
2002 speed_2x = (gyro_speed_plus + gyro_speed_minus);
2003 ds4->gyro_calib_data[0].abs_code = ABS_RX;
2004 ds4->gyro_calib_data[0].bias = 0;
2005 ds4->gyro_calib_data[0].sens_numer = speed_2x * DS4_GYRO_RES_PER_DEG_S;
2006 ds4->gyro_calib_data[0].sens_denom = abs(gyro_pitch_plus - gyro_pitch_bias) +
2007 abs(gyro_pitch_minus - gyro_pitch_bias);
2008
2009 ds4->gyro_calib_data[1].abs_code = ABS_RY;
2010 ds4->gyro_calib_data[1].bias = 0;
2011 ds4->gyro_calib_data[1].sens_numer = speed_2x * DS4_GYRO_RES_PER_DEG_S;
2012 ds4->gyro_calib_data[1].sens_denom = abs(gyro_yaw_plus - gyro_yaw_bias) +
2013 abs(gyro_yaw_minus - gyro_yaw_bias);
2014
2015 ds4->gyro_calib_data[2].abs_code = ABS_RZ;
2016 ds4->gyro_calib_data[2].bias = 0;
2017 ds4->gyro_calib_data[2].sens_numer = speed_2x * DS4_GYRO_RES_PER_DEG_S;
2018 ds4->gyro_calib_data[2].sens_denom = abs(gyro_roll_plus - gyro_roll_bias) +
2019 abs(gyro_roll_minus - gyro_roll_bias);
2020
2021 /*
2022 * Set accelerometer calibration and normalization parameters.
2023 * Data values will be normalized to 1/DS4_ACC_RES_PER_G g.
2024 */
2025 range_2g = acc_x_plus - acc_x_minus;
2026 ds4->accel_calib_data[0].abs_code = ABS_X;
2027 ds4->accel_calib_data[0].bias = acc_x_plus - range_2g / 2;
2028 ds4->accel_calib_data[0].sens_numer = 2 * DS4_ACC_RES_PER_G;
2029 ds4->accel_calib_data[0].sens_denom = range_2g;
2030
2031 range_2g = acc_y_plus - acc_y_minus;
2032 ds4->accel_calib_data[1].abs_code = ABS_Y;
2033 ds4->accel_calib_data[1].bias = acc_y_plus - range_2g / 2;
2034 ds4->accel_calib_data[1].sens_numer = 2 * DS4_ACC_RES_PER_G;
2035 ds4->accel_calib_data[1].sens_denom = range_2g;
2036
2037 range_2g = acc_z_plus - acc_z_minus;
2038 ds4->accel_calib_data[2].abs_code = ABS_Z;
2039 ds4->accel_calib_data[2].bias = acc_z_plus - range_2g / 2;
2040 ds4->accel_calib_data[2].sens_numer = 2 * DS4_ACC_RES_PER_G;
2041 ds4->accel_calib_data[2].sens_denom = range_2g;
2042
2043transfer_failed:
2044 /*
2045 * Sanity check gyro calibration data. This is needed to prevent crashes
2046 * during report handling of virtual, clone or broken devices not implementing
2047 * calibration data properly.
2048 */
2049 for (i = 0; i < ARRAY_SIZE(ds4->gyro_calib_data); i++) {
2050 if (ds4->gyro_calib_data[i].sens_denom == 0) {
2051 ds4->gyro_calib_data[i].abs_code = ABS_RX + i;
2052 hid_warn(hdev,
2053 "Invalid gyro calibration data for axis (%d), disabling calibration.",
2054 ds4->gyro_calib_data[i].abs_code);
2055 ds4->gyro_calib_data[i].bias = 0;
2056 ds4->gyro_calib_data[i].sens_numer = DS4_GYRO_RANGE;
2057 ds4->gyro_calib_data[i].sens_denom = S16_MAX;
2058 }
2059 }
2060
2061 /*
2062 * Sanity check accelerometer calibration data. This is needed to prevent crashes
2063 * during report handling of virtual, clone or broken devices not implementing calibration
2064 * data properly.
2065 */
2066 for (i = 0; i < ARRAY_SIZE(ds4->accel_calib_data); i++) {
2067 if (ds4->accel_calib_data[i].sens_denom == 0) {
2068 ds4->accel_calib_data[i].abs_code = ABS_X + i;
2069 hid_warn(hdev,
2070 "Invalid accelerometer calibration data for axis (%d), disabling calibration.",
2071 ds4->accel_calib_data[i].abs_code);
2072 ds4->accel_calib_data[i].bias = 0;
2073 ds4->accel_calib_data[i].sens_numer = DS4_ACC_RANGE;
2074 ds4->accel_calib_data[i].sens_denom = S16_MAX;
2075 }
2076 }
2077
2078 return ret;
2079}
2080
2081static int dualshock4_get_firmware_info(struct dualshock4 *ds4)
2082{
2083 u8 *buf;
2084 int ret;
2085
2086 buf = kzalloc(DS4_FEATURE_REPORT_FIRMWARE_INFO_SIZE, GFP_KERNEL);
2087 if (!buf)
2088 return -ENOMEM;
2089
2090 /* Note USB and BT support the same feature report, but this report
2091 * lacks CRC support, so must be disabled in ps_get_report.
2092 */
2093 ret = ps_get_report(ds4->base.hdev, DS4_FEATURE_REPORT_FIRMWARE_INFO, buf,
2094 DS4_FEATURE_REPORT_FIRMWARE_INFO_SIZE, false);
2095 if (ret) {
2096 hid_err(ds4->base.hdev, "Failed to retrieve DualShock4 firmware info: %d\n", ret);
2097 goto err_free;
2098 }
2099
2100 ds4->base.hw_version = get_unaligned_le16(&buf[35]);
2101 ds4->base.fw_version = get_unaligned_le16(&buf[41]);
2102
2103err_free:
2104 kfree(buf);
2105 return ret;
2106}
2107
2108static int dualshock4_get_mac_address(struct dualshock4 *ds4)
2109{
2110 struct hid_device *hdev = ds4->base.hdev;
2111 u8 *buf;
2112 int ret = 0;
2113
2114 if (hdev->bus == BUS_USB) {
2115 buf = kzalloc(DS4_FEATURE_REPORT_PAIRING_INFO_SIZE, GFP_KERNEL);
2116 if (!buf)
2117 return -ENOMEM;
2118
2119 ret = ps_get_report(hdev, DS4_FEATURE_REPORT_PAIRING_INFO, buf,
2120 DS4_FEATURE_REPORT_PAIRING_INFO_SIZE, false);
2121 if (ret) {
2122 hid_err(hdev, "Failed to retrieve DualShock4 pairing info: %d\n", ret);
2123 goto err_free;
2124 }
2125
2126 memcpy(ds4->base.mac_address, &buf[1], sizeof(ds4->base.mac_address));
2127 } else {
2128 /* Rely on HIDP for Bluetooth */
2129 if (strlen(hdev->uniq) != 17)
2130 return -EINVAL;
2131
2132 ret = sscanf(hdev->uniq, "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx",
2133 &ds4->base.mac_address[5], &ds4->base.mac_address[4],
2134 &ds4->base.mac_address[3], &ds4->base.mac_address[2],
2135 &ds4->base.mac_address[1], &ds4->base.mac_address[0]);
2136
2137 if (ret != sizeof(ds4->base.mac_address))
2138 return -EINVAL;
2139
2140 return 0;
2141 }
2142
2143err_free:
2144 kfree(buf);
2145 return ret;
2146}
2147
2148static enum led_brightness dualshock4_led_get_brightness(struct led_classdev *led)
2149{
2150 struct hid_device *hdev = to_hid_device(led->dev->parent);
2151 struct dualshock4 *ds4 = hid_get_drvdata(hdev);
2152 unsigned int led_index;
2153
2154 led_index = led - ds4->lightbar_leds;
2155 switch (led_index) {
2156 case 0:
2157 return ds4->lightbar_red;
2158 case 1:
2159 return ds4->lightbar_green;
2160 case 2:
2161 return ds4->lightbar_blue;
2162 case 3:
2163 return ds4->lightbar_enabled;
2164 }
2165
2166 return -1;
2167}
2168
2169static int dualshock4_led_set_blink(struct led_classdev *led, unsigned long *delay_on,
2170 unsigned long *delay_off)
2171{
2172 struct hid_device *hdev = to_hid_device(led->dev->parent);
2173 struct dualshock4 *ds4 = hid_get_drvdata(hdev);
2174
2175 scoped_guard(spinlock_irqsave, &ds4->base.lock) {
2176 if (!*delay_on && !*delay_off) {
2177 /* Default to 1 Hz (50 centiseconds on, 50 centiseconds off). */
2178 ds4->lightbar_blink_on = 50;
2179 ds4->lightbar_blink_off = 50;
2180 } else {
2181 /* Blink delays in centiseconds. */
2182 ds4->lightbar_blink_on = min_t(unsigned long, *delay_on / 10,
2183 DS4_LIGHTBAR_MAX_BLINK);
2184 ds4->lightbar_blink_off = min_t(unsigned long, *delay_off / 10,
2185 DS4_LIGHTBAR_MAX_BLINK);
2186 }
2187
2188 ds4->update_lightbar_blink = true;
2189 }
2190
2191 dualshock4_schedule_work(ds4);
2192
2193 /* Report scaled values back to LED subsystem */
2194 *delay_on = ds4->lightbar_blink_on * 10;
2195 *delay_off = ds4->lightbar_blink_off * 10;
2196
2197 return 0;
2198}
2199
2200static int dualshock4_led_set_brightness(struct led_classdev *led, enum led_brightness value)
2201{
2202 struct hid_device *hdev = to_hid_device(led->dev->parent);
2203 struct dualshock4 *ds4 = hid_get_drvdata(hdev);
2204 unsigned int led_index;
2205
2206 scoped_guard(spinlock_irqsave, &ds4->base.lock) {
2207 led_index = led - ds4->lightbar_leds;
2208 switch (led_index) {
2209 case 0:
2210 ds4->lightbar_red = value;
2211 break;
2212 case 1:
2213 ds4->lightbar_green = value;
2214 break;
2215 case 2:
2216 ds4->lightbar_blue = value;
2217 break;
2218 case 3:
2219 ds4->lightbar_enabled = !!value;
2220
2221 /* brightness = 0 also cancels blinking in Linux. */
2222 if (!ds4->lightbar_enabled) {
2223 ds4->lightbar_blink_off = 0;
2224 ds4->lightbar_blink_on = 0;
2225 ds4->update_lightbar_blink = true;
2226 }
2227 }
2228
2229 ds4->update_lightbar = true;
2230 }
2231
2232 dualshock4_schedule_work(ds4);
2233
2234 return 0;
2235}
2236
2237static void dualshock4_init_output_report(struct dualshock4 *ds4,
2238 struct dualshock4_output_report *rp, void *buf)
2239{
2240 struct hid_device *hdev = ds4->base.hdev;
2241
2242 if (hdev->bus == BUS_BLUETOOTH) {
2243 struct dualshock4_output_report_bt *bt = buf;
2244
2245 memset(bt, 0, sizeof(*bt));
2246 bt->report_id = DS4_OUTPUT_REPORT_BT;
2247
2248 rp->data = buf;
2249 rp->len = sizeof(*bt);
2250 rp->bt = bt;
2251 rp->usb = NULL;
2252 rp->common = &bt->common;
2253 } else { /* USB */
2254 struct dualshock4_output_report_usb *usb = buf;
2255
2256 memset(usb, 0, sizeof(*usb));
2257 usb->report_id = DS4_OUTPUT_REPORT_USB;
2258
2259 rp->data = buf;
2260 rp->len = sizeof(*usb);
2261 rp->bt = NULL;
2262 rp->usb = usb;
2263 rp->common = &usb->common;
2264 }
2265}
2266
2267static void dualshock4_output_worker(struct work_struct *work)
2268{
2269 struct dualshock4 *ds4 = container_of(work, struct dualshock4, output_worker);
2270 struct dualshock4_output_report report;
2271 struct dualshock4_output_report_common *common;
2272
2273 dualshock4_init_output_report(ds4, &report, ds4->output_report_dmabuf);
2274 common = report.common;
2275
2276 scoped_guard(spinlock_irqsave, &ds4->base.lock) {
2277 /*
2278 * Some 3rd party gamepads expect updates to rumble and lightbar
2279 * together, and setting one may cancel the other.
2280 *
2281 * Let's maximise compatibility by always sending rumble and lightbar
2282 * updates together, even when only one has been scheduled, resulting
2283 * in:
2284 *
2285 * ds4->valid_flag0 >= 0x03
2286 *
2287 * Hopefully this will maximise compatibility with third-party pads.
2288 *
2289 * Any further update bits, such as 0x04 for lightbar blinking, will
2290 * be or'd on top of this like before.
2291 */
2292 if (ds4->update_rumble || ds4->update_lightbar) {
2293 ds4->update_rumble = true; /* 0x01 */
2294 ds4->update_lightbar = true; /* 0x02 */
2295 }
2296
2297 if (ds4->update_rumble) {
2298 /* Select classic rumble style haptics and enable it. */
2299 common->valid_flag0 |= DS4_OUTPUT_VALID_FLAG0_MOTOR;
2300 common->motor_left = ds4->motor_left;
2301 common->motor_right = ds4->motor_right;
2302 ds4->update_rumble = false;
2303 }
2304
2305 if (ds4->update_lightbar) {
2306 common->valid_flag0 |= DS4_OUTPUT_VALID_FLAG0_LED;
2307 /* Compatible behavior with hid-sony, which used a dummy global LED to
2308 * allow enabling/disabling the lightbar. The global LED maps to
2309 * lightbar_enabled.
2310 */
2311 common->lightbar_red = ds4->lightbar_enabled ? ds4->lightbar_red : 0;
2312 common->lightbar_green = ds4->lightbar_enabled ? ds4->lightbar_green : 0;
2313 common->lightbar_blue = ds4->lightbar_enabled ? ds4->lightbar_blue : 0;
2314 ds4->update_lightbar = false;
2315 }
2316
2317 if (ds4->update_lightbar_blink) {
2318 common->valid_flag0 |= DS4_OUTPUT_VALID_FLAG0_LED_BLINK;
2319 common->lightbar_blink_on = ds4->lightbar_blink_on;
2320 common->lightbar_blink_off = ds4->lightbar_blink_off;
2321 ds4->update_lightbar_blink = false;
2322 }
2323 }
2324
2325 /* Bluetooth packets need additional flags as well as a CRC in the last 4 bytes. */
2326 if (report.bt) {
2327 u32 crc;
2328 u8 seed = PS_OUTPUT_CRC32_SEED;
2329
2330 /* Hardware control flags need to set to let the device know
2331 * there is HID data as well as CRC.
2332 */
2333 report.bt->hw_control = DS4_OUTPUT_HWCTL_HID | DS4_OUTPUT_HWCTL_CRC32;
2334
2335 if (ds4->update_bt_poll_interval) {
2336 report.bt->hw_control |= ds4->bt_poll_interval;
2337 ds4->update_bt_poll_interval = false;
2338 }
2339
2340 crc = crc32_le(0xFFFFFFFF, &seed, 1);
2341 crc = ~crc32_le(crc, report.data, report.len - 4);
2342
2343 report.bt->crc32 = cpu_to_le32(crc);
2344 }
2345
2346 hid_hw_output_report(ds4->base.hdev, report.data, report.len);
2347}
2348
2349static int dualshock4_parse_report(struct ps_device *ps_dev, struct hid_report *report,
2350 u8 *data, int size)
2351{
2352 struct hid_device *hdev = ps_dev->hdev;
2353 struct dualshock4 *ds4 = container_of(ps_dev, struct dualshock4, base);
2354 struct dualshock4_input_report_common *ds4_report;
2355 struct dualshock4_touch_report *touch_reports;
2356 u8 battery_capacity, num_touch_reports, value;
2357 int battery_status, i, j;
2358 u16 sensor_timestamp;
2359 bool is_minimal = false;
2360
2361 /*
2362 * DualShock4 in USB uses the full HID report for reportID 1, but
2363 * Bluetooth uses a minimal HID report for reportID 1 and reports
2364 * the full report using reportID 17.
2365 */
2366 if (hdev->bus == BUS_USB && report->id == DS4_INPUT_REPORT_USB &&
2367 size == DS4_INPUT_REPORT_USB_SIZE) {
2368 struct dualshock4_input_report_usb *usb =
2369 (struct dualshock4_input_report_usb *)data;
2370
2371 ds4_report = &usb->common;
2372 num_touch_reports = usb->num_touch_reports;
2373 touch_reports = usb->touch_reports;
2374 } else if (hdev->bus == BUS_BLUETOOTH && report->id == DS4_INPUT_REPORT_BT &&
2375 size == DS4_INPUT_REPORT_BT_SIZE) {
2376 struct dualshock4_input_report_bt *bt = (struct dualshock4_input_report_bt *)data;
2377 u32 report_crc = get_unaligned_le32(&bt->crc32);
2378
2379 /* Last 4 bytes of input report contains CRC. */
2380 if (!ps_check_crc32(PS_INPUT_CRC32_SEED, data, size - 4, report_crc)) {
2381 hid_err(hdev, "DualShock4 input CRC's check failed\n");
2382 return -EILSEQ;
2383 }
2384
2385 ds4_report = &bt->common;
2386 num_touch_reports = bt->num_touch_reports;
2387 touch_reports = bt->touch_reports;
2388 } else if (hdev->bus == BUS_BLUETOOTH &&
2389 report->id == DS4_INPUT_REPORT_BT_MINIMAL &&
2390 size == DS4_INPUT_REPORT_BT_MINIMAL_SIZE) {
2391 /* Some third-party pads never switch to the full 0x11 report.
2392 * The short 0x01 report is 10 bytes long:
2393 * u8 report_id == 0x01
2394 * u8 first_bytes_of_full_report[9]
2395 * So let's reuse the full report parser, and stop it after
2396 * parsing the buttons.
2397 */
2398 ds4_report = (struct dualshock4_input_report_common *)&data[1];
2399 is_minimal = true;
2400 } else {
2401 hid_err(hdev, "Unhandled reportID=%d\n", report->id);
2402 return -1;
2403 }
2404
2405 input_report_abs(ds4->gamepad, ABS_X, ds4_report->x);
2406 input_report_abs(ds4->gamepad, ABS_Y, ds4_report->y);
2407 input_report_abs(ds4->gamepad, ABS_RX, ds4_report->rx);
2408 input_report_abs(ds4->gamepad, ABS_RY, ds4_report->ry);
2409 input_report_abs(ds4->gamepad, ABS_Z, ds4_report->z);
2410 input_report_abs(ds4->gamepad, ABS_RZ, ds4_report->rz);
2411
2412 value = ds4_report->buttons[0] & DS_BUTTONS0_HAT_SWITCH;
2413 if (value >= ARRAY_SIZE(ps_gamepad_hat_mapping))
2414 value = 8; /* center */
2415 input_report_abs(ds4->gamepad, ABS_HAT0X, ps_gamepad_hat_mapping[value].x);
2416 input_report_abs(ds4->gamepad, ABS_HAT0Y, ps_gamepad_hat_mapping[value].y);
2417
2418 input_report_key(ds4->gamepad, BTN_WEST, ds4_report->buttons[0] & DS_BUTTONS0_SQUARE);
2419 input_report_key(ds4->gamepad, BTN_SOUTH, ds4_report->buttons[0] & DS_BUTTONS0_CROSS);
2420 input_report_key(ds4->gamepad, BTN_EAST, ds4_report->buttons[0] & DS_BUTTONS0_CIRCLE);
2421 input_report_key(ds4->gamepad, BTN_NORTH, ds4_report->buttons[0] & DS_BUTTONS0_TRIANGLE);
2422 input_report_key(ds4->gamepad, BTN_TL, ds4_report->buttons[1] & DS_BUTTONS1_L1);
2423 input_report_key(ds4->gamepad, BTN_TR, ds4_report->buttons[1] & DS_BUTTONS1_R1);
2424 input_report_key(ds4->gamepad, BTN_TL2, ds4_report->buttons[1] & DS_BUTTONS1_L2);
2425 input_report_key(ds4->gamepad, BTN_TR2, ds4_report->buttons[1] & DS_BUTTONS1_R2);
2426 input_report_key(ds4->gamepad, BTN_SELECT, ds4_report->buttons[1] & DS_BUTTONS1_CREATE);
2427 input_report_key(ds4->gamepad, BTN_START, ds4_report->buttons[1] & DS_BUTTONS1_OPTIONS);
2428 input_report_key(ds4->gamepad, BTN_THUMBL, ds4_report->buttons[1] & DS_BUTTONS1_L3);
2429 input_report_key(ds4->gamepad, BTN_THUMBR, ds4_report->buttons[1] & DS_BUTTONS1_R3);
2430 input_report_key(ds4->gamepad, BTN_MODE, ds4_report->buttons[2] & DS_BUTTONS2_PS_HOME);
2431 input_sync(ds4->gamepad);
2432
2433 if (is_minimal)
2434 return 0;
2435
2436 /* Parse and calibrate gyroscope data. */
2437 for (i = 0; i < ARRAY_SIZE(ds4_report->gyro); i++) {
2438 int raw_data = (short)le16_to_cpu(ds4_report->gyro[i]);
2439 int calib_data = mult_frac(ds4->gyro_calib_data[i].sens_numer,
2440 raw_data, ds4->gyro_calib_data[i].sens_denom);
2441
2442 input_report_abs(ds4->sensors, ds4->gyro_calib_data[i].abs_code, calib_data);
2443 }
2444
2445 /* Parse and calibrate accelerometer data. */
2446 for (i = 0; i < ARRAY_SIZE(ds4_report->accel); i++) {
2447 int raw_data = (short)le16_to_cpu(ds4_report->accel[i]);
2448 int calib_data = mult_frac(ds4->accel_calib_data[i].sens_numer,
2449 raw_data - ds4->accel_calib_data[i].bias,
2450 ds4->accel_calib_data[i].sens_denom);
2451
2452 input_report_abs(ds4->sensors, ds4->accel_calib_data[i].abs_code, calib_data);
2453 }
2454
2455 /* Convert timestamp (in 5.33us unit) to timestamp_us */
2456 sensor_timestamp = le16_to_cpu(ds4_report->sensor_timestamp);
2457 if (!ds4->sensor_timestamp_initialized) {
2458 ds4->sensor_timestamp_us = DIV_ROUND_CLOSEST(sensor_timestamp * 16, 3);
2459 ds4->sensor_timestamp_initialized = true;
2460 } else {
2461 u16 delta;
2462
2463 if (ds4->prev_sensor_timestamp > sensor_timestamp)
2464 delta = (U16_MAX - ds4->prev_sensor_timestamp + sensor_timestamp + 1);
2465 else
2466 delta = sensor_timestamp - ds4->prev_sensor_timestamp;
2467 ds4->sensor_timestamp_us += DIV_ROUND_CLOSEST(delta * 16, 3);
2468 }
2469 ds4->prev_sensor_timestamp = sensor_timestamp;
2470 input_event(ds4->sensors, EV_MSC, MSC_TIMESTAMP, ds4->sensor_timestamp_us);
2471 input_sync(ds4->sensors);
2472
2473 for (i = 0; i < num_touch_reports; i++) {
2474 struct dualshock4_touch_report *touch_report = &touch_reports[i];
2475
2476 for (j = 0; j < ARRAY_SIZE(touch_report->points); j++) {
2477 struct dualshock4_touch_point *point = &touch_report->points[j];
2478 bool active = (point->contact & DS4_TOUCH_POINT_INACTIVE) ? false : true;
2479
2480 input_mt_slot(ds4->touchpad, j);
2481 input_mt_report_slot_state(ds4->touchpad, MT_TOOL_FINGER, active);
2482
2483 if (active) {
2484 input_report_abs(ds4->touchpad, ABS_MT_POSITION_X,
2485 DS4_TOUCH_POINT_X(point->x_hi, point->x_lo));
2486 input_report_abs(ds4->touchpad, ABS_MT_POSITION_Y,
2487 DS4_TOUCH_POINT_Y(point->y_hi, point->y_lo));
2488 }
2489 }
2490 input_mt_sync_frame(ds4->touchpad);
2491 input_sync(ds4->touchpad);
2492 }
2493 input_report_key(ds4->touchpad, BTN_LEFT, ds4_report->buttons[2] & DS_BUTTONS2_TOUCHPAD);
2494
2495 /*
2496 * Interpretation of the battery_capacity data depends on the cable state.
2497 * When no cable is connected (bit4 is 0):
2498 * - 0:10: percentage in units of 10%.
2499 * When a cable is plugged in:
2500 * - 0-10: percentage in units of 10%.
2501 * - 11: battery is full
2502 * - 14: not charging due to Voltage or temperature error
2503 * - 15: charge error
2504 */
2505 if (ds4_report->status[0] & DS4_STATUS0_CABLE_STATE) {
2506 u8 battery_data = ds4_report->status[0] & DS4_STATUS0_BATTERY_CAPACITY;
2507
2508 if (battery_data < 10) {
2509 /* Take the mid-point for each battery capacity value,
2510 * because on the hardware side 0 = 0-9%, 1=10-19%, etc.
2511 * This matches official platform behavior, which does
2512 * the same.
2513 */
2514 battery_capacity = battery_data * 10 + 5;
2515 battery_status = POWER_SUPPLY_STATUS_CHARGING;
2516 } else if (battery_data == 10) {
2517 battery_capacity = 100;
2518 battery_status = POWER_SUPPLY_STATUS_CHARGING;
2519 } else if (battery_data == DS4_BATTERY_STATUS_FULL) {
2520 battery_capacity = 100;
2521 battery_status = POWER_SUPPLY_STATUS_FULL;
2522 } else { /* 14, 15 and undefined values */
2523 battery_capacity = 0;
2524 battery_status = POWER_SUPPLY_STATUS_UNKNOWN;
2525 }
2526 } else {
2527 u8 battery_data = ds4_report->status[0] & DS4_STATUS0_BATTERY_CAPACITY;
2528
2529 if (battery_data < 10)
2530 battery_capacity = battery_data * 10 + 5;
2531 else /* 10 */
2532 battery_capacity = 100;
2533
2534 battery_status = POWER_SUPPLY_STATUS_DISCHARGING;
2535 }
2536
2537 scoped_guard(spinlock_irqsave, &ps_dev->lock) {
2538 ps_dev->battery_capacity = battery_capacity;
2539 ps_dev->battery_status = battery_status;
2540 }
2541
2542 return 0;
2543}
2544
2545static int dualshock4_dongle_parse_report(struct ps_device *ps_dev, struct hid_report *report,
2546 u8 *data, int size)
2547{
2548 struct dualshock4 *ds4 = container_of(ps_dev, struct dualshock4, base);
2549 bool connected = false;
2550
2551 /* The dongle reports data using the main USB report (0x1) no matter whether a controller
2552 * is connected with mostly zeros. The report does contain dongle status, which we use to
2553 * determine if a controller is connected and if so we forward to the regular DualShock4
2554 * parsing code.
2555 */
2556 if (data[0] == DS4_INPUT_REPORT_USB && size == DS4_INPUT_REPORT_USB_SIZE) {
2557 struct dualshock4_input_report_common *ds4_report =
2558 (struct dualshock4_input_report_common *)&data[1];
2559
2560 connected = ds4_report->status[1] & DS4_STATUS1_DONGLE_STATE ? false : true;
2561
2562 if (ds4->dongle_state == DONGLE_DISCONNECTED && connected) {
2563 hid_info(ps_dev->hdev, "DualShock 4 USB dongle: controller connected\n");
2564
2565 dualshock4_set_default_lightbar_colors(ds4);
2566
2567 scoped_guard(spinlock_irqsave, &ps_dev->lock)
2568 ds4->dongle_state = DONGLE_CALIBRATING;
2569
2570 schedule_work(&ds4->dongle_hotplug_worker);
2571
2572 /* Don't process the report since we don't have
2573 * calibration data, but let hidraw have it anyway.
2574 */
2575 return 0;
2576 } else if ((ds4->dongle_state == DONGLE_CONNECTED ||
2577 ds4->dongle_state == DONGLE_DISABLED) && !connected) {
2578 hid_info(ps_dev->hdev, "DualShock 4 USB dongle: controller disconnected\n");
2579
2580 scoped_guard(spinlock_irqsave, &ps_dev->lock)
2581 ds4->dongle_state = DONGLE_DISCONNECTED;
2582
2583 /* Return 0, so hidraw can get the report. */
2584 return 0;
2585 } else if (ds4->dongle_state == DONGLE_CALIBRATING ||
2586 ds4->dongle_state == DONGLE_DISABLED ||
2587 ds4->dongle_state == DONGLE_DISCONNECTED) {
2588 /* Return 0, so hidraw can get the report. */
2589 return 0;
2590 }
2591 }
2592
2593 if (connected)
2594 return dualshock4_parse_report(ps_dev, report, data, size);
2595
2596 return 0;
2597}
2598
2599static int dualshock4_play_effect(struct input_dev *dev, void *data, struct ff_effect *effect)
2600{
2601 struct hid_device *hdev = input_get_drvdata(dev);
2602 struct dualshock4 *ds4 = hid_get_drvdata(hdev);
2603
2604 if (effect->type != FF_RUMBLE)
2605 return 0;
2606
2607 scoped_guard(spinlock_irqsave, &ds4->base.lock) {
2608 ds4->update_rumble = true;
2609 ds4->motor_left = effect->u.rumble.strong_magnitude / 256;
2610 ds4->motor_right = effect->u.rumble.weak_magnitude / 256;
2611 }
2612
2613 dualshock4_schedule_work(ds4);
2614 return 0;
2615}
2616
2617static void dualshock4_remove(struct ps_device *ps_dev)
2618{
2619 struct dualshock4 *ds4 = container_of(ps_dev, struct dualshock4, base);
2620
2621 scoped_guard(spinlock_irqsave, &ds4->base.lock)
2622 ds4->output_worker_initialized = false;
2623
2624 cancel_work_sync(&ds4->output_worker);
2625
2626 if (ps_dev->hdev->product == USB_DEVICE_ID_SONY_PS4_CONTROLLER_DONGLE)
2627 cancel_work_sync(&ds4->dongle_hotplug_worker);
2628}
2629
2630static inline void dualshock4_schedule_work(struct dualshock4 *ds4)
2631{
2632 /* Using scoped_guard() instead of guard() to make sparse happy */
2633 scoped_guard(spinlock_irqsave, &ds4->base.lock)
2634 if (ds4->output_worker_initialized)
2635 schedule_work(&ds4->output_worker);
2636}
2637
2638static void dualshock4_set_bt_poll_interval(struct dualshock4 *ds4, u8 interval)
2639{
2640 ds4->bt_poll_interval = interval;
2641 ds4->update_bt_poll_interval = true;
2642 dualshock4_schedule_work(ds4);
2643}
2644
2645/* Set default lightbar color based on player. */
2646static void dualshock4_set_default_lightbar_colors(struct dualshock4 *ds4)
2647{
2648 /* Use same player colors as PlayStation 4.
2649 * Array of colors is in RGB.
2650 */
2651 static const int player_colors[4][3] = {
2652 { 0x00, 0x00, 0x40 }, /* Blue */
2653 { 0x40, 0x00, 0x00 }, /* Red */
2654 { 0x00, 0x40, 0x00 }, /* Green */
2655 { 0x20, 0x00, 0x20 } /* Pink */
2656 };
2657
2658 u8 player_id = ds4->base.player_id % ARRAY_SIZE(player_colors);
2659
2660 ds4->lightbar_enabled = true;
2661 ds4->lightbar_red = player_colors[player_id][0];
2662 ds4->lightbar_green = player_colors[player_id][1];
2663 ds4->lightbar_blue = player_colors[player_id][2];
2664
2665 ds4->update_lightbar = true;
2666 dualshock4_schedule_work(ds4);
2667}
2668
2669static struct ps_device *dualshock4_create(struct hid_device *hdev)
2670{
2671 struct dualshock4 *ds4;
2672 struct ps_device *ps_dev;
2673 u8 max_output_report_size;
2674 int i, ret;
2675
2676 /* The DualShock4 has an RGB lightbar, which the original hid-sony driver
2677 * exposed as a set of 4 LEDs for the 3 color channels and a global control.
2678 * Ideally this should have used the multi-color LED class, which didn't exist
2679 * yet. In addition the driver used a naming scheme not compliant with the LED
2680 * naming spec by using "<mac_address>:<color>", which contained many colons.
2681 * We use a more compliant by using "<device_name>:<color>" name now. Ideally
2682 * would have been "<device_name>:<color>:indicator", but that would break
2683 * existing applications (e.g. Android). Nothing matches against MAC address.
2684 */
2685 static const struct ps_led_info lightbar_leds_info[] = {
2686 { NULL, "red", 255, dualshock4_led_get_brightness,
2687 dualshock4_led_set_brightness },
2688 { NULL, "green", 255, dualshock4_led_get_brightness,
2689 dualshock4_led_set_brightness },
2690 { NULL, "blue", 255, dualshock4_led_get_brightness,
2691 dualshock4_led_set_brightness },
2692 { NULL, "global", 1, dualshock4_led_get_brightness,
2693 dualshock4_led_set_brightness, dualshock4_led_set_blink },
2694 };
2695
2696 ds4 = devm_kzalloc(&hdev->dev, sizeof(*ds4), GFP_KERNEL);
2697 if (!ds4)
2698 return ERR_PTR(-ENOMEM);
2699
2700 /*
2701 * Patch version to allow userspace to distinguish between
2702 * hid-generic vs hid-playstation axis and button mapping.
2703 */
2704 hdev->version |= HID_PLAYSTATION_VERSION_PATCH;
2705
2706 ps_dev = &ds4->base;
2707 ps_dev->hdev = hdev;
2708 spin_lock_init(&ps_dev->lock);
2709 ps_dev->battery_capacity = 100; /* initial value until parse_report. */
2710 ps_dev->battery_status = POWER_SUPPLY_STATUS_UNKNOWN;
2711 ps_dev->parse_report = dualshock4_parse_report;
2712 ps_dev->remove = dualshock4_remove;
2713 INIT_WORK(&ds4->output_worker, dualshock4_output_worker);
2714 ds4->output_worker_initialized = true;
2715 hid_set_drvdata(hdev, ds4);
2716
2717 max_output_report_size = sizeof(struct dualshock4_output_report_bt);
2718 ds4->output_report_dmabuf = devm_kzalloc(&hdev->dev, max_output_report_size, GFP_KERNEL);
2719 if (!ds4->output_report_dmabuf)
2720 return ERR_PTR(-ENOMEM);
2721
2722 if (hdev->product == USB_DEVICE_ID_SONY_PS4_CONTROLLER_DONGLE) {
2723 ds4->dongle_state = DONGLE_DISCONNECTED;
2724 INIT_WORK(&ds4->dongle_hotplug_worker, dualshock4_dongle_calibration_work);
2725
2726 /* Override parse report for dongle specific hotplug handling. */
2727 ps_dev->parse_report = dualshock4_dongle_parse_report;
2728 }
2729
2730 ret = dualshock4_get_mac_address(ds4);
2731 if (ret) {
2732 hid_err(hdev, "Failed to get MAC address from DualShock4\n");
2733 return ERR_PTR(ret);
2734 }
2735 snprintf(hdev->uniq, sizeof(hdev->uniq), "%pMR", ds4->base.mac_address);
2736
2737 ret = dualshock4_get_firmware_info(ds4);
2738 if (ret) {
2739 hid_warn(hdev, "Failed to get firmware info from DualShock4\n");
2740 hid_warn(hdev, "HW/FW version data in sysfs will be invalid.\n");
2741 }
2742
2743 ret = ps_devices_list_add(ps_dev);
2744 if (ret)
2745 return ERR_PTR(ret);
2746
2747 ret = dualshock4_get_calibration_data(ds4);
2748 if (ret) {
2749 hid_warn(hdev, "Failed to get calibration data from DualShock4\n");
2750 hid_warn(hdev, "Gyroscope and accelerometer will be inaccurate.\n");
2751 }
2752
2753 ds4->gamepad = ps_gamepad_create(hdev, dualshock4_play_effect);
2754 if (IS_ERR(ds4->gamepad)) {
2755 ret = PTR_ERR(ds4->gamepad);
2756 goto err;
2757 }
2758
2759 /* Use gamepad input device name as primary device name for e.g. LEDs */
2760 ps_dev->input_dev_name = dev_name(&ds4->gamepad->dev);
2761
2762 ds4->sensors = ps_sensors_create(hdev, DS4_ACC_RANGE, DS4_ACC_RES_PER_G,
2763 DS4_GYRO_RANGE, DS4_GYRO_RES_PER_DEG_S);
2764 if (IS_ERR(ds4->sensors)) {
2765 ret = PTR_ERR(ds4->sensors);
2766 goto err;
2767 }
2768
2769 ds4->touchpad = ps_touchpad_create(hdev, DS4_TOUCHPAD_WIDTH, DS4_TOUCHPAD_HEIGHT, 2);
2770 if (IS_ERR(ds4->touchpad)) {
2771 ret = PTR_ERR(ds4->touchpad);
2772 goto err;
2773 }
2774
2775 ret = ps_device_register_battery(ps_dev);
2776 if (ret)
2777 goto err;
2778
2779 for (i = 0; i < ARRAY_SIZE(lightbar_leds_info); i++) {
2780 const struct ps_led_info *led_info = &lightbar_leds_info[i];
2781
2782 ret = ps_led_register(ps_dev, &ds4->lightbar_leds[i], led_info);
2783 if (ret < 0)
2784 goto err;
2785 }
2786
2787 dualshock4_set_bt_poll_interval(ds4, DS4_BT_DEFAULT_POLL_INTERVAL_MS);
2788
2789 ret = ps_device_set_player_id(ps_dev);
2790 if (ret) {
2791 hid_err(hdev, "Failed to assign player id for DualShock4: %d\n", ret);
2792 goto err;
2793 }
2794
2795 dualshock4_set_default_lightbar_colors(ds4);
2796
2797 /*
2798 * Reporting hardware and firmware is important as there are frequent updates, which
2799 * can change behavior.
2800 */
2801 hid_info(hdev, "Registered DualShock4 controller hw_version=0x%08x fw_version=0x%08x\n",
2802 ds4->base.hw_version, ds4->base.fw_version);
2803 return &ds4->base;
2804
2805err:
2806 ps_devices_list_remove(ps_dev);
2807 return ERR_PTR(ret);
2808}
2809
2810static int ps_raw_event(struct hid_device *hdev, struct hid_report *report,
2811 u8 *data, int size)
2812{
2813 struct ps_device *dev = hid_get_drvdata(hdev);
2814
2815 if (dev && dev->parse_report)
2816 return dev->parse_report(dev, report, data, size);
2817
2818 return 0;
2819}
2820
2821static int ps_probe(struct hid_device *hdev, const struct hid_device_id *id)
2822{
2823 struct ps_device *dev;
2824 int ret;
2825
2826 ret = hid_parse(hdev);
2827 if (ret) {
2828 hid_err(hdev, "Parse failed\n");
2829 return ret;
2830 }
2831
2832 ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
2833 if (ret) {
2834 hid_err(hdev, "Failed to start HID device\n");
2835 return ret;
2836 }
2837
2838 ret = hid_hw_open(hdev);
2839 if (ret) {
2840 hid_err(hdev, "Failed to open HID device\n");
2841 goto err_stop;
2842 }
2843
2844 if (id->driver_data == PS_TYPE_PS4_DUALSHOCK4) {
2845 dev = dualshock4_create(hdev);
2846 if (IS_ERR(dev)) {
2847 hid_err(hdev, "Failed to create dualshock4.\n");
2848 ret = PTR_ERR(dev);
2849 goto err_close;
2850 }
2851 } else if (id->driver_data == PS_TYPE_PS5_DUALSENSE) {
2852 dev = dualsense_create(hdev);
2853 if (IS_ERR(dev)) {
2854 hid_err(hdev, "Failed to create dualsense.\n");
2855 ret = PTR_ERR(dev);
2856 goto err_close;
2857 }
2858 }
2859
2860 return ret;
2861
2862err_close:
2863 hid_hw_close(hdev);
2864err_stop:
2865 hid_hw_stop(hdev);
2866 return ret;
2867}
2868
2869static void ps_remove(struct hid_device *hdev)
2870{
2871 struct ps_device *dev = hid_get_drvdata(hdev);
2872
2873 ps_devices_list_remove(dev);
2874 ps_device_release_player_id(dev);
2875
2876 if (dev->remove)
2877 dev->remove(dev);
2878
2879 hid_hw_close(hdev);
2880 hid_hw_stop(hdev);
2881}
2882
2883static const struct hid_device_id ps_devices[] = {
2884 /* Sony DualShock 4 controllers for PS4 */
2885 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER),
2886 .driver_data = PS_TYPE_PS4_DUALSHOCK4 },
2887 { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER),
2888 .driver_data = PS_TYPE_PS4_DUALSHOCK4 },
2889 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER_2),
2890 .driver_data = PS_TYPE_PS4_DUALSHOCK4 },
2891 { HID_USB_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_DONGLE),
2894 .driver_data = PS_TYPE_PS4_DUALSHOCK4 },
2895
2896 /* Sony DualSense controllers for PS5 */
2897 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER),
2898 .driver_data = PS_TYPE_PS5_DUALSENSE },
2899 { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER),
2900 .driver_data = PS_TYPE_PS5_DUALSENSE },
2901 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER_2),
2902 .driver_data = PS_TYPE_PS5_DUALSENSE },
2903 { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER_2),
2904 .driver_data = PS_TYPE_PS5_DUALSENSE },
2905 { }
2906};
2907MODULE_DEVICE_TABLE(hid, ps_devices);
2908
2909static struct hid_driver ps_driver = {
2910 .name = "playstation",
2911 .id_table = ps_devices,
2912 .probe = ps_probe,
2913 .remove = ps_remove,
2914 .raw_event = ps_raw_event,
2915 .driver = {
2916 .dev_groups = ps_device_groups,
2917 },
2918};
2919
2920static int __init ps_init(void)
2921{
2922 return hid_register_driver(&ps_driver);
2923}
2924
2925static void __exit ps_exit(void)
2926{
2927 hid_unregister_driver(&ps_driver);
2928 ida_destroy(&ps_player_id_allocator);
2929}
2930
2931module_init(ps_init);
2932module_exit(ps_exit);
2933
2934MODULE_AUTHOR("Sony Interactive Entertainment");
2935MODULE_DESCRIPTION("HID Driver for PlayStation peripherals.");
2936MODULE_LICENSE("GPL");