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 /* Set initial resting state for joysticks to 128 (center) */
757 input_set_abs_params(gamepad, ABS_X, 0, 255, 0, 0);
758 gamepad->absinfo[ABS_X].value = 128;
759 input_set_abs_params(gamepad, ABS_Y, 0, 255, 0, 0);
760 gamepad->absinfo[ABS_Y].value = 128;
761 input_set_abs_params(gamepad, ABS_Z, 0, 255, 0, 0);
762 input_set_abs_params(gamepad, ABS_RX, 0, 255, 0, 0);
763 gamepad->absinfo[ABS_RX].value = 128;
764 input_set_abs_params(gamepad, ABS_RY, 0, 255, 0, 0);
765 gamepad->absinfo[ABS_RY].value = 128;
766 input_set_abs_params(gamepad, ABS_RZ, 0, 255, 0, 0);
767
768 input_set_abs_params(gamepad, ABS_HAT0X, -1, 1, 0, 0);
769 input_set_abs_params(gamepad, ABS_HAT0Y, -1, 1, 0, 0);
770
771 for (i = 0; i < ARRAY_SIZE(ps_gamepad_buttons); i++)
772 input_set_capability(gamepad, EV_KEY, ps_gamepad_buttons[i]);
773
774#if IS_ENABLED(CONFIG_PLAYSTATION_FF)
775 if (play_effect) {
776 input_set_capability(gamepad, EV_FF, FF_RUMBLE);
777 ret = input_ff_create_memless(gamepad, NULL, play_effect);
778 if (ret)
779 return ERR_PTR(ret);
780 }
781#endif
782
783 ret = input_register_device(gamepad);
784 if (ret)
785 return ERR_PTR(ret);
786
787 return gamepad;
788}
789
790static int ps_get_report(struct hid_device *hdev, u8 report_id, u8 *buf,
791 size_t size, bool check_crc)
792{
793 int ret;
794
795 ret = hid_hw_raw_request(hdev, report_id, buf, size, HID_FEATURE_REPORT,
796 HID_REQ_GET_REPORT);
797 if (ret < 0) {
798 hid_err(hdev, "Failed to retrieve feature with reportID %d: %d\n", report_id, ret);
799 return ret;
800 }
801
802 if (ret != size) {
803 hid_err(hdev, "Invalid byte count transferred, expected %zu got %d\n", size, ret);
804 return -EINVAL;
805 }
806
807 if (buf[0] != report_id) {
808 hid_err(hdev, "Invalid reportID received, expected %d got %d\n", report_id, buf[0]);
809 return -EINVAL;
810 }
811
812 if (hdev->bus == BUS_BLUETOOTH && check_crc) {
813 /* Last 4 bytes contains crc32. */
814 u8 crc_offset = size - 4;
815 u32 report_crc = get_unaligned_le32(&buf[crc_offset]);
816
817 if (!ps_check_crc32(PS_FEATURE_CRC32_SEED, buf, crc_offset, report_crc)) {
818 hid_err(hdev, "CRC check failed for reportID=%d\n", report_id);
819 return -EILSEQ;
820 }
821 }
822
823 return 0;
824}
825
826static int ps_led_register(struct ps_device *ps_dev, struct led_classdev *led,
827 const struct ps_led_info *led_info)
828{
829 int ret;
830
831 if (led_info->name) {
832 led->name = devm_kasprintf(&ps_dev->hdev->dev, GFP_KERNEL, "%s:%s:%s",
833 ps_dev->input_dev_name, led_info->color,
834 led_info->name);
835 } else {
836 /* Backwards compatible mode for hid-sony, but not compliant
837 * with LED class spec.
838 */
839 led->name = devm_kasprintf(&ps_dev->hdev->dev, GFP_KERNEL, "%s:%s",
840 ps_dev->input_dev_name, led_info->color);
841 }
842
843 if (!led->name)
844 return -ENOMEM;
845
846 led->brightness = 0;
847 led->max_brightness = led_info->max_brightness;
848 led->flags = LED_CORE_SUSPENDRESUME;
849 led->brightness_get = led_info->brightness_get;
850 led->brightness_set_blocking = led_info->brightness_set;
851 led->blink_set = led_info->blink_set;
852
853 ret = devm_led_classdev_register(&ps_dev->hdev->dev, led);
854 if (ret) {
855 hid_err(ps_dev->hdev, "Failed to register LED %s: %d\n", led_info->name, ret);
856 return ret;
857 }
858
859 return 0;
860}
861
862/* Register a DualSense/DualShock4 RGB lightbar represented by a multicolor LED. */
863static int ps_lightbar_register(struct ps_device *ps_dev, struct led_classdev_mc *lightbar_mc_dev,
864 int (*brightness_set)(struct led_classdev *, enum led_brightness))
865{
866 struct hid_device *hdev = ps_dev->hdev;
867 struct mc_subled *mc_led_info;
868 struct led_classdev *led_cdev;
869 int ret;
870
871 mc_led_info = devm_kmalloc_array(&hdev->dev, 3, sizeof(*mc_led_info),
872 GFP_KERNEL | __GFP_ZERO);
873 if (!mc_led_info)
874 return -ENOMEM;
875
876 mc_led_info[0].color_index = LED_COLOR_ID_RED;
877 mc_led_info[1].color_index = LED_COLOR_ID_GREEN;
878 mc_led_info[2].color_index = LED_COLOR_ID_BLUE;
879
880 lightbar_mc_dev->subled_info = mc_led_info;
881 lightbar_mc_dev->num_colors = 3;
882
883 led_cdev = &lightbar_mc_dev->led_cdev;
884 led_cdev->name = devm_kasprintf(&hdev->dev, GFP_KERNEL, "%s:rgb:indicator",
885 ps_dev->input_dev_name);
886 if (!led_cdev->name)
887 return -ENOMEM;
888 led_cdev->brightness = 255;
889 led_cdev->max_brightness = 255;
890 led_cdev->brightness_set_blocking = brightness_set;
891
892 ret = devm_led_classdev_multicolor_register(&hdev->dev, lightbar_mc_dev);
893 if (ret < 0) {
894 hid_err(hdev, "Cannot register multicolor LED device\n");
895 return ret;
896 }
897
898 return 0;
899}
900
901static struct input_dev *ps_sensors_create(struct hid_device *hdev, int accel_range,
902 int accel_res, int gyro_range, int gyro_res)
903{
904 struct input_dev *sensors;
905 int ret;
906
907 sensors = ps_allocate_input_dev(hdev, "Motion Sensors");
908 if (IS_ERR(sensors))
909 return ERR_CAST(sensors);
910
911 __set_bit(INPUT_PROP_ACCELEROMETER, sensors->propbit);
912 __set_bit(EV_MSC, sensors->evbit);
913 __set_bit(MSC_TIMESTAMP, sensors->mscbit);
914
915 /* Accelerometer */
916 input_set_abs_params(sensors, ABS_X, -accel_range, accel_range, 16, 0);
917 input_set_abs_params(sensors, ABS_Y, -accel_range, accel_range, 16, 0);
918 input_set_abs_params(sensors, ABS_Z, -accel_range, accel_range, 16, 0);
919 input_abs_set_res(sensors, ABS_X, accel_res);
920 input_abs_set_res(sensors, ABS_Y, accel_res);
921 input_abs_set_res(sensors, ABS_Z, accel_res);
922
923 /* Gyroscope */
924 input_set_abs_params(sensors, ABS_RX, -gyro_range, gyro_range, 16, 0);
925 input_set_abs_params(sensors, ABS_RY, -gyro_range, gyro_range, 16, 0);
926 input_set_abs_params(sensors, ABS_RZ, -gyro_range, gyro_range, 16, 0);
927 input_abs_set_res(sensors, ABS_RX, gyro_res);
928 input_abs_set_res(sensors, ABS_RY, gyro_res);
929 input_abs_set_res(sensors, ABS_RZ, gyro_res);
930
931 ret = input_register_device(sensors);
932 if (ret)
933 return ERR_PTR(ret);
934
935 return sensors;
936}
937
938static struct input_dev *ps_touchpad_create(struct hid_device *hdev, int width,
939 int height, unsigned int num_contacts)
940{
941 struct input_dev *touchpad;
942 int ret;
943
944 touchpad = ps_allocate_input_dev(hdev, "Touchpad");
945 if (IS_ERR(touchpad))
946 return ERR_CAST(touchpad);
947
948 /* Map button underneath touchpad to BTN_LEFT. */
949 input_set_capability(touchpad, EV_KEY, BTN_LEFT);
950 __set_bit(INPUT_PROP_BUTTONPAD, touchpad->propbit);
951
952 input_set_abs_params(touchpad, ABS_MT_POSITION_X, 0, width - 1, 0, 0);
953 input_set_abs_params(touchpad, ABS_MT_POSITION_Y, 0, height - 1, 0, 0);
954
955 ret = input_mt_init_slots(touchpad, num_contacts, INPUT_MT_POINTER);
956 if (ret)
957 return ERR_PTR(ret);
958
959 ret = input_register_device(touchpad);
960 if (ret)
961 return ERR_PTR(ret);
962
963 return touchpad;
964}
965
966static struct input_dev *ps_headset_jack_create(struct hid_device *hdev)
967{
968 struct input_dev *jack;
969 int ret;
970
971 jack = ps_allocate_input_dev(hdev, "Headset Jack");
972 if (IS_ERR(jack))
973 return ERR_CAST(jack);
974
975 input_set_capability(jack, EV_SW, SW_HEADPHONE_INSERT);
976 input_set_capability(jack, EV_SW, SW_MICROPHONE_INSERT);
977
978 ret = input_register_device(jack);
979 if (ret)
980 return ERR_PTR(ret);
981
982 return jack;
983}
984
985static ssize_t firmware_version_show(struct device *dev,
986 struct device_attribute *attr, char *buf)
987{
988 struct hid_device *hdev = to_hid_device(dev);
989 struct ps_device *ps_dev = hid_get_drvdata(hdev);
990
991 return sysfs_emit(buf, "0x%08x\n", ps_dev->fw_version);
992}
993
994static DEVICE_ATTR_RO(firmware_version);
995
996static ssize_t hardware_version_show(struct device *dev,
997 struct device_attribute *attr, char *buf)
998{
999 struct hid_device *hdev = to_hid_device(dev);
1000 struct ps_device *ps_dev = hid_get_drvdata(hdev);
1001
1002 return sysfs_emit(buf, "0x%08x\n", ps_dev->hw_version);
1003}
1004
1005static DEVICE_ATTR_RO(hardware_version);
1006
1007static struct attribute *ps_device_attrs[] = {
1008 &dev_attr_firmware_version.attr,
1009 &dev_attr_hardware_version.attr,
1010 NULL
1011};
1012ATTRIBUTE_GROUPS(ps_device);
1013
1014static int dualsense_get_calibration_data(struct dualsense *ds)
1015{
1016 struct hid_device *hdev = ds->base.hdev;
1017 short gyro_pitch_bias, gyro_pitch_plus, gyro_pitch_minus;
1018 short gyro_yaw_bias, gyro_yaw_plus, gyro_yaw_minus;
1019 short gyro_roll_bias, gyro_roll_plus, gyro_roll_minus;
1020 short gyro_speed_plus, gyro_speed_minus;
1021 short acc_x_plus, acc_x_minus;
1022 short acc_y_plus, acc_y_minus;
1023 short acc_z_plus, acc_z_minus;
1024 int speed_2x;
1025 int range_2g;
1026 int ret = 0;
1027 int i;
1028 u8 *buf;
1029
1030 buf = kzalloc(DS_FEATURE_REPORT_CALIBRATION_SIZE, GFP_KERNEL);
1031 if (!buf)
1032 return -ENOMEM;
1033
1034 ret = ps_get_report(ds->base.hdev, DS_FEATURE_REPORT_CALIBRATION, buf,
1035 DS_FEATURE_REPORT_CALIBRATION_SIZE, true);
1036 if (ret) {
1037 hid_err(ds->base.hdev, "Failed to retrieve DualSense calibration info: %d\n", ret);
1038 goto err_free;
1039 }
1040
1041 gyro_pitch_bias = get_unaligned_le16(&buf[1]);
1042 gyro_yaw_bias = get_unaligned_le16(&buf[3]);
1043 gyro_roll_bias = get_unaligned_le16(&buf[5]);
1044 gyro_pitch_plus = get_unaligned_le16(&buf[7]);
1045 gyro_pitch_minus = get_unaligned_le16(&buf[9]);
1046 gyro_yaw_plus = get_unaligned_le16(&buf[11]);
1047 gyro_yaw_minus = get_unaligned_le16(&buf[13]);
1048 gyro_roll_plus = get_unaligned_le16(&buf[15]);
1049 gyro_roll_minus = get_unaligned_le16(&buf[17]);
1050 gyro_speed_plus = get_unaligned_le16(&buf[19]);
1051 gyro_speed_minus = get_unaligned_le16(&buf[21]);
1052 acc_x_plus = get_unaligned_le16(&buf[23]);
1053 acc_x_minus = get_unaligned_le16(&buf[25]);
1054 acc_y_plus = get_unaligned_le16(&buf[27]);
1055 acc_y_minus = get_unaligned_le16(&buf[29]);
1056 acc_z_plus = get_unaligned_le16(&buf[31]);
1057 acc_z_minus = get_unaligned_le16(&buf[33]);
1058
1059 /*
1060 * Set gyroscope calibration and normalization parameters.
1061 * Data values will be normalized to 1/DS_GYRO_RES_PER_DEG_S degree/s.
1062 */
1063 speed_2x = (gyro_speed_plus + gyro_speed_minus);
1064 ds->gyro_calib_data[0].abs_code = ABS_RX;
1065 ds->gyro_calib_data[0].bias = 0;
1066 ds->gyro_calib_data[0].sens_numer = speed_2x * DS_GYRO_RES_PER_DEG_S;
1067 ds->gyro_calib_data[0].sens_denom = abs(gyro_pitch_plus - gyro_pitch_bias) +
1068 abs(gyro_pitch_minus - gyro_pitch_bias);
1069
1070 ds->gyro_calib_data[1].abs_code = ABS_RY;
1071 ds->gyro_calib_data[1].bias = 0;
1072 ds->gyro_calib_data[1].sens_numer = speed_2x * DS_GYRO_RES_PER_DEG_S;
1073 ds->gyro_calib_data[1].sens_denom = abs(gyro_yaw_plus - gyro_yaw_bias) +
1074 abs(gyro_yaw_minus - gyro_yaw_bias);
1075
1076 ds->gyro_calib_data[2].abs_code = ABS_RZ;
1077 ds->gyro_calib_data[2].bias = 0;
1078 ds->gyro_calib_data[2].sens_numer = speed_2x * DS_GYRO_RES_PER_DEG_S;
1079 ds->gyro_calib_data[2].sens_denom = abs(gyro_roll_plus - gyro_roll_bias) +
1080 abs(gyro_roll_minus - gyro_roll_bias);
1081
1082 /*
1083 * Sanity check gyro calibration data. This is needed to prevent crashes
1084 * during report handling of virtual, clone or broken devices not implementing
1085 * calibration data properly.
1086 */
1087 for (i = 0; i < ARRAY_SIZE(ds->gyro_calib_data); i++) {
1088 if (ds->gyro_calib_data[i].sens_denom == 0) {
1089 hid_warn(hdev,
1090 "Invalid gyro calibration data for axis (%d), disabling calibration.",
1091 ds->gyro_calib_data[i].abs_code);
1092 ds->gyro_calib_data[i].bias = 0;
1093 ds->gyro_calib_data[i].sens_numer = DS_GYRO_RANGE;
1094 ds->gyro_calib_data[i].sens_denom = S16_MAX;
1095 }
1096 }
1097
1098 /*
1099 * Set accelerometer calibration and normalization parameters.
1100 * Data values will be normalized to 1/DS_ACC_RES_PER_G g.
1101 */
1102 range_2g = acc_x_plus - acc_x_minus;
1103 ds->accel_calib_data[0].abs_code = ABS_X;
1104 ds->accel_calib_data[0].bias = acc_x_plus - range_2g / 2;
1105 ds->accel_calib_data[0].sens_numer = 2 * DS_ACC_RES_PER_G;
1106 ds->accel_calib_data[0].sens_denom = range_2g;
1107
1108 range_2g = acc_y_plus - acc_y_minus;
1109 ds->accel_calib_data[1].abs_code = ABS_Y;
1110 ds->accel_calib_data[1].bias = acc_y_plus - range_2g / 2;
1111 ds->accel_calib_data[1].sens_numer = 2 * DS_ACC_RES_PER_G;
1112 ds->accel_calib_data[1].sens_denom = range_2g;
1113
1114 range_2g = acc_z_plus - acc_z_minus;
1115 ds->accel_calib_data[2].abs_code = ABS_Z;
1116 ds->accel_calib_data[2].bias = acc_z_plus - range_2g / 2;
1117 ds->accel_calib_data[2].sens_numer = 2 * DS_ACC_RES_PER_G;
1118 ds->accel_calib_data[2].sens_denom = range_2g;
1119
1120 /*
1121 * Sanity check accelerometer calibration data. This is needed to prevent crashes
1122 * during report handling of virtual, clone or broken devices not implementing calibration
1123 * data properly.
1124 */
1125 for (i = 0; i < ARRAY_SIZE(ds->accel_calib_data); i++) {
1126 if (ds->accel_calib_data[i].sens_denom == 0) {
1127 hid_warn(hdev,
1128 "Invalid accelerometer calibration data for axis (%d), disabling calibration.",
1129 ds->accel_calib_data[i].abs_code);
1130 ds->accel_calib_data[i].bias = 0;
1131 ds->accel_calib_data[i].sens_numer = DS_ACC_RANGE;
1132 ds->accel_calib_data[i].sens_denom = S16_MAX;
1133 }
1134 }
1135
1136err_free:
1137 kfree(buf);
1138 return ret;
1139}
1140
1141static int dualsense_get_firmware_info(struct dualsense *ds)
1142{
1143 u8 *buf;
1144 int ret;
1145
1146 buf = kzalloc(DS_FEATURE_REPORT_FIRMWARE_INFO_SIZE, GFP_KERNEL);
1147 if (!buf)
1148 return -ENOMEM;
1149
1150 ret = ps_get_report(ds->base.hdev, DS_FEATURE_REPORT_FIRMWARE_INFO, buf,
1151 DS_FEATURE_REPORT_FIRMWARE_INFO_SIZE, true);
1152 if (ret) {
1153 hid_err(ds->base.hdev, "Failed to retrieve DualSense firmware info: %d\n", ret);
1154 goto err_free;
1155 }
1156
1157 ds->base.hw_version = get_unaligned_le32(&buf[24]);
1158 ds->base.fw_version = get_unaligned_le32(&buf[28]);
1159
1160 /* Update version is some kind of feature version. It is distinct from
1161 * the firmware version as there can be many different variations of a
1162 * controller over time with the same physical shell, but with different
1163 * PCBs and other internal changes. The update version (internal name) is
1164 * used as a means to detect what features are available and change behavior.
1165 * Note: the version is different between DualSense and DualSense Edge.
1166 */
1167 ds->update_version = get_unaligned_le16(&buf[44]);
1168
1169err_free:
1170 kfree(buf);
1171 return ret;
1172}
1173
1174static int dualsense_get_mac_address(struct dualsense *ds)
1175{
1176 u8 *buf;
1177 int ret = 0;
1178
1179 buf = kzalloc(DS_FEATURE_REPORT_PAIRING_INFO_SIZE, GFP_KERNEL);
1180 if (!buf)
1181 return -ENOMEM;
1182
1183 ret = ps_get_report(ds->base.hdev, DS_FEATURE_REPORT_PAIRING_INFO, buf,
1184 DS_FEATURE_REPORT_PAIRING_INFO_SIZE, true);
1185 if (ret) {
1186 hid_err(ds->base.hdev, "Failed to retrieve DualSense pairing info: %d\n", ret);
1187 goto err_free;
1188 }
1189
1190 memcpy(ds->base.mac_address, &buf[1], sizeof(ds->base.mac_address));
1191
1192err_free:
1193 kfree(buf);
1194 return ret;
1195}
1196
1197static int dualsense_lightbar_set_brightness(struct led_classdev *cdev,
1198 enum led_brightness brightness)
1199{
1200 struct led_classdev_mc *mc_cdev = lcdev_to_mccdev(cdev);
1201 struct dualsense *ds = container_of(mc_cdev, struct dualsense, lightbar);
1202 u8 red, green, blue;
1203
1204 led_mc_calc_color_components(mc_cdev, brightness);
1205 red = mc_cdev->subled_info[0].brightness;
1206 green = mc_cdev->subled_info[1].brightness;
1207 blue = mc_cdev->subled_info[2].brightness;
1208
1209 dualsense_set_lightbar(ds, red, green, blue);
1210 return 0;
1211}
1212
1213static enum led_brightness dualsense_player_led_get_brightness(struct led_classdev *led)
1214{
1215 struct hid_device *hdev = to_hid_device(led->dev->parent);
1216 struct dualsense *ds = hid_get_drvdata(hdev);
1217
1218 return !!(ds->player_leds_state & BIT(led - ds->player_leds));
1219}
1220
1221static int dualsense_player_led_set_brightness(struct led_classdev *led, enum led_brightness value)
1222{
1223 struct hid_device *hdev = to_hid_device(led->dev->parent);
1224 struct dualsense *ds = hid_get_drvdata(hdev);
1225 unsigned int led_index;
1226
1227 scoped_guard(spinlock_irqsave, &ds->base.lock) {
1228 led_index = led - ds->player_leds;
1229 if (value == LED_OFF)
1230 ds->player_leds_state &= ~BIT(led_index);
1231 else
1232 ds->player_leds_state |= BIT(led_index);
1233
1234 ds->update_player_leds = true;
1235 }
1236
1237 dualsense_schedule_work(ds);
1238
1239 return 0;
1240}
1241
1242static void dualsense_init_output_report(struct dualsense *ds,
1243 struct dualsense_output_report *rp, void *buf)
1244{
1245 struct hid_device *hdev = ds->base.hdev;
1246
1247 if (hdev->bus == BUS_BLUETOOTH) {
1248 struct dualsense_output_report_bt *bt = buf;
1249
1250 memset(bt, 0, sizeof(*bt));
1251 bt->report_id = DS_OUTPUT_REPORT_BT;
1252 bt->tag = DS_OUTPUT_TAG; /* Tag must be set. Exact meaning is unclear. */
1253
1254 /*
1255 * Highest 4-bit is a sequence number, which needs to be increased
1256 * every report. Lowest 4-bit is tag and can be zero for now.
1257 */
1258 bt->seq_tag = FIELD_PREP(DS_OUTPUT_SEQ_NO, ds->output_seq) |
1259 FIELD_PREP(DS_OUTPUT_SEQ_TAG, 0x0);
1260 if (++ds->output_seq == 16)
1261 ds->output_seq = 0;
1262
1263 rp->data = buf;
1264 rp->len = sizeof(*bt);
1265 rp->bt = bt;
1266 rp->usb = NULL;
1267 rp->common = &bt->common;
1268 } else { /* USB */
1269 struct dualsense_output_report_usb *usb = buf;
1270
1271 memset(usb, 0, sizeof(*usb));
1272 usb->report_id = DS_OUTPUT_REPORT_USB;
1273
1274 rp->data = buf;
1275 rp->len = sizeof(*usb);
1276 rp->bt = NULL;
1277 rp->usb = usb;
1278 rp->common = &usb->common;
1279 }
1280}
1281
1282static inline void dualsense_schedule_work(struct dualsense *ds)
1283{
1284 /* Using scoped_guard() instead of guard() to make sparse happy */
1285 scoped_guard(spinlock_irqsave, &ds->base.lock)
1286 if (ds->output_worker_initialized)
1287 schedule_work(&ds->output_worker);
1288}
1289
1290/*
1291 * Helper function to send DualSense output reports. Applies a CRC at the end of a report
1292 * for Bluetooth reports.
1293 */
1294static void dualsense_send_output_report(struct dualsense *ds,
1295 struct dualsense_output_report *report)
1296{
1297 struct hid_device *hdev = ds->base.hdev;
1298
1299 /* Bluetooth packets need to be signed with a CRC in the last 4 bytes. */
1300 if (report->bt) {
1301 u32 crc;
1302 u8 seed = PS_OUTPUT_CRC32_SEED;
1303
1304 crc = crc32_le(0xFFFFFFFF, &seed, 1);
1305 crc = ~crc32_le(crc, report->data, report->len - 4);
1306
1307 report->bt->crc32 = cpu_to_le32(crc);
1308 }
1309
1310 hid_hw_output_report(hdev, report->data, report->len);
1311}
1312
1313static void dualsense_output_worker(struct work_struct *work)
1314{
1315 struct dualsense *ds = container_of(work, struct dualsense, output_worker);
1316 struct dualsense_output_report report;
1317 struct dualsense_output_report_common *common;
1318
1319 dualsense_init_output_report(ds, &report, ds->output_report_dmabuf);
1320 common = report.common;
1321
1322 scoped_guard(spinlock_irqsave, &ds->base.lock) {
1323 if (ds->update_rumble) {
1324 /* Select classic rumble style haptics and enable it. */
1325 common->valid_flag0 |= DS_OUTPUT_VALID_FLAG0_HAPTICS_SELECT;
1326 if (ds->use_vibration_v2)
1327 common->valid_flag2 |= DS_OUTPUT_VALID_FLAG2_COMPATIBLE_VIBRATION2;
1328 else
1329 common->valid_flag0 |= DS_OUTPUT_VALID_FLAG0_COMPATIBLE_VIBRATION;
1330 common->motor_left = ds->motor_left;
1331 common->motor_right = ds->motor_right;
1332 ds->update_rumble = false;
1333 }
1334
1335 if (ds->update_lightbar) {
1336 common->valid_flag1 |= DS_OUTPUT_VALID_FLAG1_LIGHTBAR_CONTROL_ENABLE;
1337 common->lightbar_red = ds->lightbar_red;
1338 common->lightbar_green = ds->lightbar_green;
1339 common->lightbar_blue = ds->lightbar_blue;
1340
1341 ds->update_lightbar = false;
1342 }
1343
1344 if (ds->update_player_leds) {
1345 common->valid_flag1 |=
1346 DS_OUTPUT_VALID_FLAG1_PLAYER_INDICATOR_CONTROL_ENABLE;
1347 common->player_leds = ds->player_leds_state;
1348
1349 ds->update_player_leds = false;
1350 }
1351
1352 if (ds->plugged_state != ds->prev_plugged_state) {
1353 u8 val = ds->plugged_state & DS_STATUS1_HP_DETECT;
1354
1355 if (val != (ds->prev_plugged_state & DS_STATUS1_HP_DETECT)) {
1356 common->valid_flag0 = DS_OUTPUT_VALID_FLAG0_AUDIO_CONTROL_ENABLE;
1357 /*
1358 * _--------> Output path setup in audio_flag0
1359 * / _------> Headphone (HP) Left channel sink
1360 * | / _----> Headphone (HP) Right channel sink
1361 * | | / _--> Internal Speaker (SP) sink
1362 * | | | /
1363 * | | | | L/R - Left/Right channel source
1364 * 0 L-R X X - Unrouted (muted) channel source
1365 * 1 L-L X
1366 * 2 L-L R
1367 * 3 X-X R
1368 */
1369 if (val) {
1370 /* Mute SP and route L+R channels to HP */
1371 common->audio_control = 0;
1372 } else {
1373 /* Mute HP and route R channel to SP */
1374 common->audio_control =
1375 FIELD_PREP(DS_OUTPUT_AUDIO_FLAGS_OUTPUT_PATH_SEL,
1376 0x3);
1377 /*
1378 * Set SP hardware volume to 100%.
1379 * Note the accepted range seems to be [0x3d..0x64]
1380 */
1381 common->valid_flag0 |=
1382 DS_OUTPUT_VALID_FLAG0_SPEAKER_VOLUME_ENABLE;
1383 common->speaker_volume = 0x64;
1384 /* Set SP preamp gain to +6dB */
1385 common->valid_flag1 =
1386 DS_OUTPUT_VALID_FLAG1_AUDIO_CONTROL2_ENABLE;
1387 common->audio_control2 =
1388 FIELD_PREP(DS_OUTPUT_AUDIO_FLAGS2_SP_PREAMP_GAIN,
1389 0x2);
1390 }
1391
1392 input_report_switch(ds->jack, SW_HEADPHONE_INSERT, val);
1393 }
1394
1395 val = ds->plugged_state & DS_STATUS1_MIC_DETECT;
1396 if (val != (ds->prev_plugged_state & DS_STATUS1_MIC_DETECT))
1397 input_report_switch(ds->jack, SW_MICROPHONE_INSERT, val);
1398
1399 input_sync(ds->jack);
1400 ds->prev_plugged_state = ds->plugged_state;
1401 }
1402
1403 if (ds->update_mic_mute) {
1404 common->valid_flag1 |= DS_OUTPUT_VALID_FLAG1_MIC_MUTE_LED_CONTROL_ENABLE;
1405 common->mute_button_led = ds->mic_muted;
1406
1407 if (ds->mic_muted) {
1408 /* Disable microphone */
1409 common->valid_flag1 |=
1410 DS_OUTPUT_VALID_FLAG1_POWER_SAVE_CONTROL_ENABLE;
1411 common->power_save_control |= DS_OUTPUT_POWER_SAVE_CONTROL_MIC_MUTE;
1412 } else {
1413 /* Enable microphone */
1414 common->valid_flag1 |=
1415 DS_OUTPUT_VALID_FLAG1_POWER_SAVE_CONTROL_ENABLE;
1416 common->power_save_control &=
1417 ~DS_OUTPUT_POWER_SAVE_CONTROL_MIC_MUTE;
1418 }
1419
1420 ds->update_mic_mute = false;
1421 }
1422 }
1423
1424 dualsense_send_output_report(ds, &report);
1425}
1426
1427static int dualsense_parse_report(struct ps_device *ps_dev, struct hid_report *report,
1428 u8 *data, int size)
1429{
1430 struct hid_device *hdev = ps_dev->hdev;
1431 struct dualsense *ds = container_of(ps_dev, struct dualsense, base);
1432 struct dualsense_input_report *ds_report;
1433 u8 battery_data, battery_capacity, charging_status, value;
1434 int battery_status;
1435 u32 sensor_timestamp;
1436 bool btn_mic_state;
1437 int i;
1438
1439 /*
1440 * DualSense in USB uses the full HID report for reportID 1, but
1441 * Bluetooth uses a minimal HID report for reportID 1 and reports
1442 * the full report using reportID 49.
1443 */
1444 if (hdev->bus == BUS_USB && report->id == DS_INPUT_REPORT_USB &&
1445 size == DS_INPUT_REPORT_USB_SIZE) {
1446 ds_report = (struct dualsense_input_report *)&data[1];
1447 } else if (hdev->bus == BUS_BLUETOOTH && report->id == DS_INPUT_REPORT_BT &&
1448 size == DS_INPUT_REPORT_BT_SIZE) {
1449 /* Last 4 bytes of input report contain crc32 */
1450 u32 report_crc = get_unaligned_le32(&data[size - 4]);
1451
1452 if (!ps_check_crc32(PS_INPUT_CRC32_SEED, data, size - 4, report_crc)) {
1453 hid_err(hdev, "DualSense input CRC's check failed\n");
1454 return -EILSEQ;
1455 }
1456
1457 ds_report = (struct dualsense_input_report *)&data[2];
1458 } else {
1459 hid_err(hdev, "Unhandled reportID=%d\n", report->id);
1460 return -1;
1461 }
1462
1463 input_report_abs(ds->gamepad, ABS_X, ds_report->x);
1464 input_report_abs(ds->gamepad, ABS_Y, ds_report->y);
1465 input_report_abs(ds->gamepad, ABS_RX, ds_report->rx);
1466 input_report_abs(ds->gamepad, ABS_RY, ds_report->ry);
1467 input_report_abs(ds->gamepad, ABS_Z, ds_report->z);
1468 input_report_abs(ds->gamepad, ABS_RZ, ds_report->rz);
1469
1470 value = ds_report->buttons[0] & DS_BUTTONS0_HAT_SWITCH;
1471 if (value >= ARRAY_SIZE(ps_gamepad_hat_mapping))
1472 value = 8; /* center */
1473 input_report_abs(ds->gamepad, ABS_HAT0X, ps_gamepad_hat_mapping[value].x);
1474 input_report_abs(ds->gamepad, ABS_HAT0Y, ps_gamepad_hat_mapping[value].y);
1475
1476 input_report_key(ds->gamepad, BTN_WEST, ds_report->buttons[0] & DS_BUTTONS0_SQUARE);
1477 input_report_key(ds->gamepad, BTN_SOUTH, ds_report->buttons[0] & DS_BUTTONS0_CROSS);
1478 input_report_key(ds->gamepad, BTN_EAST, ds_report->buttons[0] & DS_BUTTONS0_CIRCLE);
1479 input_report_key(ds->gamepad, BTN_NORTH, ds_report->buttons[0] & DS_BUTTONS0_TRIANGLE);
1480 input_report_key(ds->gamepad, BTN_TL, ds_report->buttons[1] & DS_BUTTONS1_L1);
1481 input_report_key(ds->gamepad, BTN_TR, ds_report->buttons[1] & DS_BUTTONS1_R1);
1482 input_report_key(ds->gamepad, BTN_TL2, ds_report->buttons[1] & DS_BUTTONS1_L2);
1483 input_report_key(ds->gamepad, BTN_TR2, ds_report->buttons[1] & DS_BUTTONS1_R2);
1484 input_report_key(ds->gamepad, BTN_SELECT, ds_report->buttons[1] & DS_BUTTONS1_CREATE);
1485 input_report_key(ds->gamepad, BTN_START, ds_report->buttons[1] & DS_BUTTONS1_OPTIONS);
1486 input_report_key(ds->gamepad, BTN_THUMBL, ds_report->buttons[1] & DS_BUTTONS1_L3);
1487 input_report_key(ds->gamepad, BTN_THUMBR, ds_report->buttons[1] & DS_BUTTONS1_R3);
1488 input_report_key(ds->gamepad, BTN_MODE, ds_report->buttons[2] & DS_BUTTONS2_PS_HOME);
1489 input_sync(ds->gamepad);
1490
1491 /*
1492 * The DualSense has an internal microphone, which can be muted through a mute button
1493 * on the device. The driver is expected to read the button state and program the device
1494 * to mute/unmute audio at the hardware level.
1495 */
1496 btn_mic_state = !!(ds_report->buttons[2] & DS_BUTTONS2_MIC_MUTE);
1497 if (btn_mic_state && !ds->last_btn_mic_state) {
1498 scoped_guard(spinlock_irqsave, &ps_dev->lock) {
1499 ds->update_mic_mute = true;
1500 ds->mic_muted = !ds->mic_muted; /* toggle */
1501 }
1502
1503 /* Schedule updating of microphone state at hardware level. */
1504 dualsense_schedule_work(ds);
1505 }
1506 ds->last_btn_mic_state = btn_mic_state;
1507
1508 /*
1509 * Parse HP/MIC plugged state data for USB use case, since Bluetooth
1510 * audio is currently not supported.
1511 */
1512 if (hdev->bus == BUS_USB) {
1513 value = ds_report->status[1] & DS_STATUS1_JACK_DETECT;
1514
1515 if (!ds->prev_plugged_state_valid) {
1516 /* Initial handling of the plugged state report */
1517 scoped_guard(spinlock_irqsave, &ps_dev->lock) {
1518 ds->plugged_state = (~value) & DS_STATUS1_JACK_DETECT;
1519 ds->prev_plugged_state_valid = true;
1520 }
1521 }
1522
1523 if (value != ds->plugged_state) {
1524 scoped_guard(spinlock_irqsave, &ps_dev->lock) {
1525 ds->prev_plugged_state = ds->plugged_state;
1526 ds->plugged_state = value;
1527 }
1528
1529 /* Schedule audio routing towards active endpoint. */
1530 dualsense_schedule_work(ds);
1531 }
1532 }
1533
1534 /* Parse and calibrate gyroscope data. */
1535 for (i = 0; i < ARRAY_SIZE(ds_report->gyro); i++) {
1536 int raw_data = (short)le16_to_cpu(ds_report->gyro[i]);
1537 int calib_data = mult_frac(ds->gyro_calib_data[i].sens_numer,
1538 raw_data, ds->gyro_calib_data[i].sens_denom);
1539
1540 input_report_abs(ds->sensors, ds->gyro_calib_data[i].abs_code, calib_data);
1541 }
1542
1543 /* Parse and calibrate accelerometer data. */
1544 for (i = 0; i < ARRAY_SIZE(ds_report->accel); i++) {
1545 int raw_data = (short)le16_to_cpu(ds_report->accel[i]);
1546 int calib_data = mult_frac(ds->accel_calib_data[i].sens_numer,
1547 raw_data - ds->accel_calib_data[i].bias,
1548 ds->accel_calib_data[i].sens_denom);
1549
1550 input_report_abs(ds->sensors, ds->accel_calib_data[i].abs_code, calib_data);
1551 }
1552
1553 /* Convert timestamp (in 0.33us unit) to timestamp_us */
1554 sensor_timestamp = le32_to_cpu(ds_report->sensor_timestamp);
1555 if (!ds->sensor_timestamp_initialized) {
1556 ds->sensor_timestamp_us = DIV_ROUND_CLOSEST(sensor_timestamp, 3);
1557 ds->sensor_timestamp_initialized = true;
1558 } else {
1559 u32 delta;
1560
1561 if (ds->prev_sensor_timestamp > sensor_timestamp)
1562 delta = (U32_MAX - ds->prev_sensor_timestamp + sensor_timestamp + 1);
1563 else
1564 delta = sensor_timestamp - ds->prev_sensor_timestamp;
1565 ds->sensor_timestamp_us += DIV_ROUND_CLOSEST(delta, 3);
1566 }
1567 ds->prev_sensor_timestamp = sensor_timestamp;
1568 input_event(ds->sensors, EV_MSC, MSC_TIMESTAMP, ds->sensor_timestamp_us);
1569 input_sync(ds->sensors);
1570
1571 for (i = 0; i < ARRAY_SIZE(ds_report->points); i++) {
1572 struct dualsense_touch_point *point = &ds_report->points[i];
1573 bool active = (point->contact & DS_TOUCH_POINT_INACTIVE) ? false : true;
1574
1575 input_mt_slot(ds->touchpad, i);
1576 input_mt_report_slot_state(ds->touchpad, MT_TOOL_FINGER, active);
1577
1578 if (active) {
1579 input_report_abs(ds->touchpad, ABS_MT_POSITION_X,
1580 DS_TOUCH_POINT_X(point->x_hi, point->x_lo));
1581 input_report_abs(ds->touchpad, ABS_MT_POSITION_Y,
1582 DS_TOUCH_POINT_Y(point->y_hi, point->y_lo));
1583 }
1584 }
1585 input_mt_sync_frame(ds->touchpad);
1586 input_report_key(ds->touchpad, BTN_LEFT, ds_report->buttons[2] & DS_BUTTONS2_TOUCHPAD);
1587 input_sync(ds->touchpad);
1588
1589 battery_data = FIELD_GET(DS_STATUS0_BATTERY_CAPACITY, ds_report->status[0]);
1590 charging_status = FIELD_GET(DS_STATUS0_CHARGING, ds_report->status[0]);
1591
1592 switch (charging_status) {
1593 case 0x0:
1594 /*
1595 * Each unit of battery data corresponds to 10%
1596 * 0 = 0-9%, 1 = 10-19%, .. and 10 = 100%
1597 */
1598 battery_capacity = min(battery_data * 10 + 5, 100);
1599 battery_status = POWER_SUPPLY_STATUS_DISCHARGING;
1600 break;
1601 case 0x1:
1602 battery_capacity = min(battery_data * 10 + 5, 100);
1603 battery_status = POWER_SUPPLY_STATUS_CHARGING;
1604 break;
1605 case 0x2:
1606 battery_capacity = 100;
1607 battery_status = POWER_SUPPLY_STATUS_FULL;
1608 break;
1609 case 0xa: /* voltage or temperature out of range */
1610 case 0xb: /* temperature error */
1611 battery_capacity = 0;
1612 battery_status = POWER_SUPPLY_STATUS_NOT_CHARGING;
1613 break;
1614 case 0xf: /* charging error */
1615 default:
1616 battery_capacity = 0;
1617 battery_status = POWER_SUPPLY_STATUS_UNKNOWN;
1618 }
1619
1620 scoped_guard(spinlock_irqsave, &ps_dev->lock) {
1621 ps_dev->battery_capacity = battery_capacity;
1622 ps_dev->battery_status = battery_status;
1623 }
1624
1625 return 0;
1626}
1627
1628static int dualsense_play_effect(struct input_dev *dev, void *data, struct ff_effect *effect)
1629{
1630 struct hid_device *hdev = input_get_drvdata(dev);
1631 struct dualsense *ds = hid_get_drvdata(hdev);
1632
1633 if (effect->type != FF_RUMBLE)
1634 return 0;
1635
1636 scoped_guard(spinlock_irqsave, &ds->base.lock) {
1637 ds->update_rumble = true;
1638 ds->motor_left = effect->u.rumble.strong_magnitude / 256;
1639 ds->motor_right = effect->u.rumble.weak_magnitude / 256;
1640 }
1641
1642 dualsense_schedule_work(ds);
1643 return 0;
1644}
1645
1646static void dualsense_remove(struct ps_device *ps_dev)
1647{
1648 struct dualsense *ds = container_of(ps_dev, struct dualsense, base);
1649
1650 scoped_guard(spinlock_irqsave, &ds->base.lock)
1651 ds->output_worker_initialized = false;
1652
1653 cancel_work_sync(&ds->output_worker);
1654}
1655
1656static int dualsense_reset_leds(struct dualsense *ds)
1657{
1658 struct dualsense_output_report report;
1659 struct dualsense_output_report_bt *buf;
1660
1661 buf = kzalloc_obj(*buf);
1662 if (!buf)
1663 return -ENOMEM;
1664
1665 dualsense_init_output_report(ds, &report, buf);
1666 /*
1667 * On Bluetooth the DualSense outputs an animation on the lightbar
1668 * during startup and maintains a color afterwards. We need to explicitly
1669 * reconfigure the lightbar before we can do any programming later on.
1670 * In USB the lightbar is not on by default, but redoing the setup there
1671 * doesn't hurt.
1672 */
1673 report.common->valid_flag2 = DS_OUTPUT_VALID_FLAG2_LIGHTBAR_SETUP_CONTROL_ENABLE;
1674 report.common->lightbar_setup = DS_OUTPUT_LIGHTBAR_SETUP_LIGHT_OUT; /* Fade light out. */
1675 dualsense_send_output_report(ds, &report);
1676
1677 kfree(buf);
1678 return 0;
1679}
1680
1681static void dualsense_set_lightbar(struct dualsense *ds, u8 red, u8 green, u8 blue)
1682{
1683 scoped_guard(spinlock_irqsave, &ds->base.lock) {
1684 ds->update_lightbar = true;
1685 ds->lightbar_red = red;
1686 ds->lightbar_green = green;
1687 ds->lightbar_blue = blue;
1688 }
1689
1690 dualsense_schedule_work(ds);
1691}
1692
1693static void dualsense_set_player_leds(struct dualsense *ds)
1694{
1695 /*
1696 * The DualSense controller has a row of 5 LEDs used for player ids.
1697 * Behavior on the PlayStation 5 console is to center the player id
1698 * across the LEDs, so e.g. player 1 would be "--x--" with x being 'on'.
1699 * Follow a similar mapping here.
1700 */
1701 static const int player_ids[5] = {
1702 BIT(2),
1703 BIT(3) | BIT(1),
1704 BIT(4) | BIT(2) | BIT(0),
1705 BIT(4) | BIT(3) | BIT(1) | BIT(0),
1706 BIT(4) | BIT(3) | BIT(2) | BIT(1) | BIT(0)
1707 };
1708
1709 u8 player_id = ds->base.player_id % ARRAY_SIZE(player_ids);
1710
1711 ds->update_player_leds = true;
1712 ds->player_leds_state = player_ids[player_id];
1713 dualsense_schedule_work(ds);
1714}
1715
1716static struct ps_device *dualsense_create(struct hid_device *hdev)
1717{
1718 struct dualsense *ds;
1719 struct ps_device *ps_dev;
1720 u8 max_output_report_size;
1721 int i, ret;
1722
1723 static const struct ps_led_info player_leds_info[] = {
1724 { LED_FUNCTION_PLAYER1, "white", 1, dualsense_player_led_get_brightness,
1725 dualsense_player_led_set_brightness },
1726 { LED_FUNCTION_PLAYER2, "white", 1, dualsense_player_led_get_brightness,
1727 dualsense_player_led_set_brightness },
1728 { LED_FUNCTION_PLAYER3, "white", 1, dualsense_player_led_get_brightness,
1729 dualsense_player_led_set_brightness },
1730 { LED_FUNCTION_PLAYER4, "white", 1, dualsense_player_led_get_brightness,
1731 dualsense_player_led_set_brightness },
1732 { LED_FUNCTION_PLAYER5, "white", 1, dualsense_player_led_get_brightness,
1733 dualsense_player_led_set_brightness }
1734 };
1735
1736 ds = devm_kzalloc(&hdev->dev, sizeof(*ds), GFP_KERNEL);
1737 if (!ds)
1738 return ERR_PTR(-ENOMEM);
1739
1740 /*
1741 * Patch version to allow userspace to distinguish between
1742 * hid-generic vs hid-playstation axis and button mapping.
1743 */
1744 hdev->version |= HID_PLAYSTATION_VERSION_PATCH;
1745
1746 ps_dev = &ds->base;
1747 ps_dev->hdev = hdev;
1748 spin_lock_init(&ps_dev->lock);
1749 ps_dev->battery_capacity = 100; /* initial value until parse_report. */
1750 ps_dev->battery_status = POWER_SUPPLY_STATUS_UNKNOWN;
1751 ps_dev->parse_report = dualsense_parse_report;
1752 ps_dev->remove = dualsense_remove;
1753 INIT_WORK(&ds->output_worker, dualsense_output_worker);
1754 ds->output_worker_initialized = true;
1755 hid_set_drvdata(hdev, ds);
1756
1757 max_output_report_size = sizeof(struct dualsense_output_report_bt);
1758 ds->output_report_dmabuf = devm_kzalloc(&hdev->dev, max_output_report_size, GFP_KERNEL);
1759 if (!ds->output_report_dmabuf)
1760 return ERR_PTR(-ENOMEM);
1761
1762 ret = dualsense_get_mac_address(ds);
1763 if (ret) {
1764 hid_err(hdev, "Failed to get MAC address from DualSense\n");
1765 return ERR_PTR(ret);
1766 }
1767 snprintf(hdev->uniq, sizeof(hdev->uniq), "%pMR", ds->base.mac_address);
1768
1769 ret = dualsense_get_firmware_info(ds);
1770 if (ret) {
1771 hid_err(hdev, "Failed to get firmware info from DualSense\n");
1772 return ERR_PTR(ret);
1773 }
1774
1775 /* Original DualSense firmware simulated classic controller rumble through
1776 * its new haptics hardware. It felt different from classic rumble users
1777 * were used to. Since then new firmwares were introduced to change behavior
1778 * and make this new 'v2' behavior default on PlayStation and other platforms.
1779 * The original DualSense requires a new enough firmware as bundled with PS5
1780 * software released in 2021. DualSense edge supports it out of the box.
1781 * Both devices also support the old mode, but it is not really used.
1782 */
1783 if (hdev->product == USB_DEVICE_ID_SONY_PS5_CONTROLLER) {
1784 /* Feature version 2.21 introduced new vibration method. */
1785 ds->use_vibration_v2 = ds->update_version >= DS_FEATURE_VERSION(2, 21);
1786 } else if (hdev->product == USB_DEVICE_ID_SONY_PS5_CONTROLLER_2) {
1787 ds->use_vibration_v2 = true;
1788 }
1789
1790 ret = ps_devices_list_add(ps_dev);
1791 if (ret)
1792 return ERR_PTR(ret);
1793
1794 ret = dualsense_get_calibration_data(ds);
1795 if (ret) {
1796 hid_err(hdev, "Failed to get calibration data from DualSense\n");
1797 goto err;
1798 }
1799
1800 ds->gamepad = ps_gamepad_create(hdev, dualsense_play_effect);
1801 if (IS_ERR(ds->gamepad)) {
1802 ret = PTR_ERR(ds->gamepad);
1803 goto err;
1804 }
1805 /* Use gamepad input device name as primary device name for e.g. LEDs */
1806 ps_dev->input_dev_name = dev_name(&ds->gamepad->dev);
1807
1808 ds->sensors = ps_sensors_create(hdev, DS_ACC_RANGE, DS_ACC_RES_PER_G,
1809 DS_GYRO_RANGE, DS_GYRO_RES_PER_DEG_S);
1810 if (IS_ERR(ds->sensors)) {
1811 ret = PTR_ERR(ds->sensors);
1812 goto err;
1813 }
1814
1815 ds->touchpad = ps_touchpad_create(hdev, DS_TOUCHPAD_WIDTH, DS_TOUCHPAD_HEIGHT, 2);
1816 if (IS_ERR(ds->touchpad)) {
1817 ret = PTR_ERR(ds->touchpad);
1818 goto err;
1819 }
1820
1821 /* Bluetooth audio is currently not supported. */
1822 if (hdev->bus == BUS_USB) {
1823 ds->jack = ps_headset_jack_create(hdev);
1824 if (IS_ERR(ds->jack)) {
1825 ret = PTR_ERR(ds->jack);
1826 goto err;
1827 }
1828 }
1829
1830 ret = ps_device_register_battery(ps_dev);
1831 if (ret)
1832 goto err;
1833
1834 /*
1835 * The hardware may have control over the LEDs (e.g. in Bluetooth on startup).
1836 * Reset the LEDs (lightbar, mute, player leds), so we can control them
1837 * from software.
1838 */
1839 ret = dualsense_reset_leds(ds);
1840 if (ret)
1841 goto err;
1842
1843 ret = ps_lightbar_register(ps_dev, &ds->lightbar, dualsense_lightbar_set_brightness);
1844 if (ret)
1845 goto err;
1846
1847 /* Set default lightbar color. */
1848 dualsense_set_lightbar(ds, 0, 0, 128); /* blue */
1849
1850 for (i = 0; i < ARRAY_SIZE(player_leds_info); i++) {
1851 const struct ps_led_info *led_info = &player_leds_info[i];
1852
1853 ret = ps_led_register(ps_dev, &ds->player_leds[i], led_info);
1854 if (ret < 0)
1855 goto err;
1856 }
1857
1858 ret = ps_device_set_player_id(ps_dev);
1859 if (ret) {
1860 hid_err(hdev, "Failed to assign player id for DualSense: %d\n", ret);
1861 goto err;
1862 }
1863
1864 /* Set player LEDs to our player id. */
1865 dualsense_set_player_leds(ds);
1866
1867 /*
1868 * Reporting hardware and firmware is important as there are frequent updates, which
1869 * can change behavior.
1870 */
1871 hid_info(hdev, "Registered DualSense controller hw_version=0x%08x fw_version=0x%08x\n",
1872 ds->base.hw_version, ds->base.fw_version);
1873
1874 return &ds->base;
1875
1876err:
1877 ps_devices_list_remove(ps_dev);
1878 return ERR_PTR(ret);
1879}
1880
1881static void dualshock4_dongle_calibration_work(struct work_struct *work)
1882{
1883 struct dualshock4 *ds4 = container_of(work, struct dualshock4, dongle_hotplug_worker);
1884 enum dualshock4_dongle_state dongle_state;
1885 int ret;
1886
1887 ret = dualshock4_get_calibration_data(ds4);
1888 if (ret < 0) {
1889 /* This call is very unlikely to fail for the dongle. When it
1890 * fails we are probably in a very bad state, so mark the
1891 * dongle as disabled. We will re-enable the dongle if a new
1892 * DS4 hotplug is detect from sony_raw_event as any issues
1893 * are likely resolved then (the dongle is quite stupid).
1894 */
1895 hid_err(ds4->base.hdev,
1896 "DualShock 4 USB dongle: calibration failed, disabling device\n");
1897 dongle_state = DONGLE_DISABLED;
1898 } else {
1899 hid_info(ds4->base.hdev, "DualShock 4 USB dongle: calibration completed\n");
1900 dongle_state = DONGLE_CONNECTED;
1901 }
1902
1903 scoped_guard(spinlock_irqsave, &ds4->base.lock)
1904 ds4->dongle_state = dongle_state;
1905}
1906
1907static int dualshock4_get_calibration_data(struct dualshock4 *ds4)
1908{
1909 struct hid_device *hdev = ds4->base.hdev;
1910 short gyro_pitch_bias, gyro_pitch_plus, gyro_pitch_minus;
1911 short gyro_yaw_bias, gyro_yaw_plus, gyro_yaw_minus;
1912 short gyro_roll_bias, gyro_roll_plus, gyro_roll_minus;
1913 short gyro_speed_plus, gyro_speed_minus;
1914 short acc_x_plus, acc_x_minus;
1915 short acc_y_plus, acc_y_minus;
1916 short acc_z_plus, acc_z_minus;
1917 int speed_2x;
1918 int range_2g;
1919 int ret = 0;
1920 int i;
1921 u8 *buf;
1922
1923 if (ds4->base.hdev->bus == BUS_USB) {
1924 int retries;
1925
1926 buf = kzalloc(DS4_FEATURE_REPORT_CALIBRATION_SIZE, GFP_KERNEL);
1927 if (!buf) {
1928 ret = -ENOMEM;
1929 goto transfer_failed;
1930 }
1931
1932 /* We should normally receive the feature report data we asked
1933 * for, but hidraw applications such as Steam can issue feature
1934 * reports as well. In particular for Dongle reconnects, Steam
1935 * and this function are competing resulting in often receiving
1936 * data for a different HID report, so retry a few times.
1937 */
1938 for (retries = 0; retries < 3; retries++) {
1939 ret = ps_get_report(hdev, DS4_FEATURE_REPORT_CALIBRATION, buf,
1940 DS4_FEATURE_REPORT_CALIBRATION_SIZE, true);
1941 if (ret) {
1942 if (retries < 2) {
1943 hid_warn(hdev,
1944 "Retrying DualShock 4 get calibration report (0x02) request\n");
1945 continue;
1946 }
1947
1948 hid_warn(hdev,
1949 "Failed to retrieve DualShock4 calibration info: %d\n",
1950 ret);
1951 ret = -EILSEQ;
1952 kfree(buf);
1953 goto transfer_failed;
1954 } else {
1955 break;
1956 }
1957 }
1958 } else { /* Bluetooth */
1959 buf = kzalloc(DS4_FEATURE_REPORT_CALIBRATION_BT_SIZE, GFP_KERNEL);
1960 if (!buf) {
1961 ret = -ENOMEM;
1962 goto transfer_failed;
1963 }
1964
1965 ret = ps_get_report(hdev, DS4_FEATURE_REPORT_CALIBRATION_BT, buf,
1966 DS4_FEATURE_REPORT_CALIBRATION_BT_SIZE, true);
1967
1968 if (ret) {
1969 hid_warn(hdev, "Failed to retrieve DualShock4 calibration info: %d\n", ret);
1970 kfree(buf);
1971 goto transfer_failed;
1972 }
1973 }
1974
1975 /* Transfer succeeded - parse the calibration data received. */
1976 gyro_pitch_bias = get_unaligned_le16(&buf[1]);
1977 gyro_yaw_bias = get_unaligned_le16(&buf[3]);
1978 gyro_roll_bias = get_unaligned_le16(&buf[5]);
1979 if (ds4->base.hdev->bus == BUS_USB) {
1980 gyro_pitch_plus = get_unaligned_le16(&buf[7]);
1981 gyro_pitch_minus = get_unaligned_le16(&buf[9]);
1982 gyro_yaw_plus = get_unaligned_le16(&buf[11]);
1983 gyro_yaw_minus = get_unaligned_le16(&buf[13]);
1984 gyro_roll_plus = get_unaligned_le16(&buf[15]);
1985 gyro_roll_minus = get_unaligned_le16(&buf[17]);
1986 } else {
1987 /* BT + Dongle */
1988 gyro_pitch_plus = get_unaligned_le16(&buf[7]);
1989 gyro_yaw_plus = get_unaligned_le16(&buf[9]);
1990 gyro_roll_plus = get_unaligned_le16(&buf[11]);
1991 gyro_pitch_minus = get_unaligned_le16(&buf[13]);
1992 gyro_yaw_minus = get_unaligned_le16(&buf[15]);
1993 gyro_roll_minus = get_unaligned_le16(&buf[17]);
1994 }
1995 gyro_speed_plus = get_unaligned_le16(&buf[19]);
1996 gyro_speed_minus = get_unaligned_le16(&buf[21]);
1997 acc_x_plus = get_unaligned_le16(&buf[23]);
1998 acc_x_minus = get_unaligned_le16(&buf[25]);
1999 acc_y_plus = get_unaligned_le16(&buf[27]);
2000 acc_y_minus = get_unaligned_le16(&buf[29]);
2001 acc_z_plus = get_unaligned_le16(&buf[31]);
2002 acc_z_minus = get_unaligned_le16(&buf[33]);
2003
2004 /* Done parsing the buffer, so let's free it. */
2005 kfree(buf);
2006
2007 /*
2008 * Set gyroscope calibration and normalization parameters.
2009 * Data values will be normalized to 1/DS4_GYRO_RES_PER_DEG_S degree/s.
2010 */
2011 speed_2x = (gyro_speed_plus + gyro_speed_minus);
2012 ds4->gyro_calib_data[0].abs_code = ABS_RX;
2013 ds4->gyro_calib_data[0].bias = 0;
2014 ds4->gyro_calib_data[0].sens_numer = speed_2x * DS4_GYRO_RES_PER_DEG_S;
2015 ds4->gyro_calib_data[0].sens_denom = abs(gyro_pitch_plus - gyro_pitch_bias) +
2016 abs(gyro_pitch_minus - gyro_pitch_bias);
2017
2018 ds4->gyro_calib_data[1].abs_code = ABS_RY;
2019 ds4->gyro_calib_data[1].bias = 0;
2020 ds4->gyro_calib_data[1].sens_numer = speed_2x * DS4_GYRO_RES_PER_DEG_S;
2021 ds4->gyro_calib_data[1].sens_denom = abs(gyro_yaw_plus - gyro_yaw_bias) +
2022 abs(gyro_yaw_minus - gyro_yaw_bias);
2023
2024 ds4->gyro_calib_data[2].abs_code = ABS_RZ;
2025 ds4->gyro_calib_data[2].bias = 0;
2026 ds4->gyro_calib_data[2].sens_numer = speed_2x * DS4_GYRO_RES_PER_DEG_S;
2027 ds4->gyro_calib_data[2].sens_denom = abs(gyro_roll_plus - gyro_roll_bias) +
2028 abs(gyro_roll_minus - gyro_roll_bias);
2029
2030 /*
2031 * Set accelerometer calibration and normalization parameters.
2032 * Data values will be normalized to 1/DS4_ACC_RES_PER_G g.
2033 */
2034 range_2g = acc_x_plus - acc_x_minus;
2035 ds4->accel_calib_data[0].abs_code = ABS_X;
2036 ds4->accel_calib_data[0].bias = acc_x_plus - range_2g / 2;
2037 ds4->accel_calib_data[0].sens_numer = 2 * DS4_ACC_RES_PER_G;
2038 ds4->accel_calib_data[0].sens_denom = range_2g;
2039
2040 range_2g = acc_y_plus - acc_y_minus;
2041 ds4->accel_calib_data[1].abs_code = ABS_Y;
2042 ds4->accel_calib_data[1].bias = acc_y_plus - range_2g / 2;
2043 ds4->accel_calib_data[1].sens_numer = 2 * DS4_ACC_RES_PER_G;
2044 ds4->accel_calib_data[1].sens_denom = range_2g;
2045
2046 range_2g = acc_z_plus - acc_z_minus;
2047 ds4->accel_calib_data[2].abs_code = ABS_Z;
2048 ds4->accel_calib_data[2].bias = acc_z_plus - range_2g / 2;
2049 ds4->accel_calib_data[2].sens_numer = 2 * DS4_ACC_RES_PER_G;
2050 ds4->accel_calib_data[2].sens_denom = range_2g;
2051
2052transfer_failed:
2053 /*
2054 * Sanity check gyro calibration data. This is needed to prevent crashes
2055 * during report handling of virtual, clone or broken devices not implementing
2056 * calibration data properly.
2057 */
2058 for (i = 0; i < ARRAY_SIZE(ds4->gyro_calib_data); i++) {
2059 if (ds4->gyro_calib_data[i].sens_denom == 0) {
2060 ds4->gyro_calib_data[i].abs_code = ABS_RX + i;
2061 hid_warn(hdev,
2062 "Invalid gyro calibration data for axis (%d), disabling calibration.",
2063 ds4->gyro_calib_data[i].abs_code);
2064 ds4->gyro_calib_data[i].bias = 0;
2065 ds4->gyro_calib_data[i].sens_numer = DS4_GYRO_RANGE;
2066 ds4->gyro_calib_data[i].sens_denom = S16_MAX;
2067 }
2068 }
2069
2070 /*
2071 * Sanity check accelerometer calibration data. This is needed to prevent crashes
2072 * during report handling of virtual, clone or broken devices not implementing calibration
2073 * data properly.
2074 */
2075 for (i = 0; i < ARRAY_SIZE(ds4->accel_calib_data); i++) {
2076 if (ds4->accel_calib_data[i].sens_denom == 0) {
2077 ds4->accel_calib_data[i].abs_code = ABS_X + i;
2078 hid_warn(hdev,
2079 "Invalid accelerometer calibration data for axis (%d), disabling calibration.",
2080 ds4->accel_calib_data[i].abs_code);
2081 ds4->accel_calib_data[i].bias = 0;
2082 ds4->accel_calib_data[i].sens_numer = DS4_ACC_RANGE;
2083 ds4->accel_calib_data[i].sens_denom = S16_MAX;
2084 }
2085 }
2086
2087 return ret;
2088}
2089
2090static int dualshock4_get_firmware_info(struct dualshock4 *ds4)
2091{
2092 u8 *buf;
2093 int ret;
2094
2095 buf = kzalloc(DS4_FEATURE_REPORT_FIRMWARE_INFO_SIZE, GFP_KERNEL);
2096 if (!buf)
2097 return -ENOMEM;
2098
2099 /* Note USB and BT support the same feature report, but this report
2100 * lacks CRC support, so must be disabled in ps_get_report.
2101 */
2102 ret = ps_get_report(ds4->base.hdev, DS4_FEATURE_REPORT_FIRMWARE_INFO, buf,
2103 DS4_FEATURE_REPORT_FIRMWARE_INFO_SIZE, false);
2104 if (ret) {
2105 hid_err(ds4->base.hdev, "Failed to retrieve DualShock4 firmware info: %d\n", ret);
2106 goto err_free;
2107 }
2108
2109 ds4->base.hw_version = get_unaligned_le16(&buf[35]);
2110 ds4->base.fw_version = get_unaligned_le16(&buf[41]);
2111
2112err_free:
2113 kfree(buf);
2114 return ret;
2115}
2116
2117static int dualshock4_get_mac_address(struct dualshock4 *ds4)
2118{
2119 struct hid_device *hdev = ds4->base.hdev;
2120 u8 *buf;
2121 int ret = 0;
2122
2123 if (hdev->bus == BUS_USB) {
2124 buf = kzalloc(DS4_FEATURE_REPORT_PAIRING_INFO_SIZE, GFP_KERNEL);
2125 if (!buf)
2126 return -ENOMEM;
2127
2128 ret = ps_get_report(hdev, DS4_FEATURE_REPORT_PAIRING_INFO, buf,
2129 DS4_FEATURE_REPORT_PAIRING_INFO_SIZE, false);
2130 if (ret) {
2131 hid_err(hdev, "Failed to retrieve DualShock4 pairing info: %d\n", ret);
2132 goto err_free;
2133 }
2134
2135 memcpy(ds4->base.mac_address, &buf[1], sizeof(ds4->base.mac_address));
2136 } else {
2137 /* Rely on HIDP for Bluetooth */
2138 if (strlen(hdev->uniq) != 17)
2139 return -EINVAL;
2140
2141 ret = sscanf(hdev->uniq, "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx",
2142 &ds4->base.mac_address[5], &ds4->base.mac_address[4],
2143 &ds4->base.mac_address[3], &ds4->base.mac_address[2],
2144 &ds4->base.mac_address[1], &ds4->base.mac_address[0]);
2145
2146 if (ret != sizeof(ds4->base.mac_address))
2147 return -EINVAL;
2148
2149 return 0;
2150 }
2151
2152err_free:
2153 kfree(buf);
2154 return ret;
2155}
2156
2157static enum led_brightness dualshock4_led_get_brightness(struct led_classdev *led)
2158{
2159 struct hid_device *hdev = to_hid_device(led->dev->parent);
2160 struct dualshock4 *ds4 = hid_get_drvdata(hdev);
2161 unsigned int led_index;
2162
2163 led_index = led - ds4->lightbar_leds;
2164 switch (led_index) {
2165 case 0:
2166 return ds4->lightbar_red;
2167 case 1:
2168 return ds4->lightbar_green;
2169 case 2:
2170 return ds4->lightbar_blue;
2171 case 3:
2172 return ds4->lightbar_enabled;
2173 }
2174
2175 return -1;
2176}
2177
2178static int dualshock4_led_set_blink(struct led_classdev *led, unsigned long *delay_on,
2179 unsigned long *delay_off)
2180{
2181 struct hid_device *hdev = to_hid_device(led->dev->parent);
2182 struct dualshock4 *ds4 = hid_get_drvdata(hdev);
2183
2184 scoped_guard(spinlock_irqsave, &ds4->base.lock) {
2185 if (!*delay_on && !*delay_off) {
2186 /* Default to 1 Hz (50 centiseconds on, 50 centiseconds off). */
2187 ds4->lightbar_blink_on = 50;
2188 ds4->lightbar_blink_off = 50;
2189 } else {
2190 /* Blink delays in centiseconds. */
2191 ds4->lightbar_blink_on = min_t(unsigned long, *delay_on / 10,
2192 DS4_LIGHTBAR_MAX_BLINK);
2193 ds4->lightbar_blink_off = min_t(unsigned long, *delay_off / 10,
2194 DS4_LIGHTBAR_MAX_BLINK);
2195 }
2196
2197 ds4->update_lightbar_blink = true;
2198 }
2199
2200 dualshock4_schedule_work(ds4);
2201
2202 /* Report scaled values back to LED subsystem */
2203 *delay_on = ds4->lightbar_blink_on * 10;
2204 *delay_off = ds4->lightbar_blink_off * 10;
2205
2206 return 0;
2207}
2208
2209static int dualshock4_led_set_brightness(struct led_classdev *led, enum led_brightness value)
2210{
2211 struct hid_device *hdev = to_hid_device(led->dev->parent);
2212 struct dualshock4 *ds4 = hid_get_drvdata(hdev);
2213 unsigned int led_index;
2214
2215 scoped_guard(spinlock_irqsave, &ds4->base.lock) {
2216 led_index = led - ds4->lightbar_leds;
2217 switch (led_index) {
2218 case 0:
2219 ds4->lightbar_red = value;
2220 break;
2221 case 1:
2222 ds4->lightbar_green = value;
2223 break;
2224 case 2:
2225 ds4->lightbar_blue = value;
2226 break;
2227 case 3:
2228 ds4->lightbar_enabled = !!value;
2229
2230 /* brightness = 0 also cancels blinking in Linux. */
2231 if (!ds4->lightbar_enabled) {
2232 ds4->lightbar_blink_off = 0;
2233 ds4->lightbar_blink_on = 0;
2234 ds4->update_lightbar_blink = true;
2235 }
2236 }
2237
2238 ds4->update_lightbar = true;
2239 }
2240
2241 dualshock4_schedule_work(ds4);
2242
2243 return 0;
2244}
2245
2246static void dualshock4_init_output_report(struct dualshock4 *ds4,
2247 struct dualshock4_output_report *rp, void *buf)
2248{
2249 struct hid_device *hdev = ds4->base.hdev;
2250
2251 if (hdev->bus == BUS_BLUETOOTH) {
2252 struct dualshock4_output_report_bt *bt = buf;
2253
2254 memset(bt, 0, sizeof(*bt));
2255 bt->report_id = DS4_OUTPUT_REPORT_BT;
2256
2257 rp->data = buf;
2258 rp->len = sizeof(*bt);
2259 rp->bt = bt;
2260 rp->usb = NULL;
2261 rp->common = &bt->common;
2262 } else { /* USB */
2263 struct dualshock4_output_report_usb *usb = buf;
2264
2265 memset(usb, 0, sizeof(*usb));
2266 usb->report_id = DS4_OUTPUT_REPORT_USB;
2267
2268 rp->data = buf;
2269 rp->len = sizeof(*usb);
2270 rp->bt = NULL;
2271 rp->usb = usb;
2272 rp->common = &usb->common;
2273 }
2274}
2275
2276static void dualshock4_output_worker(struct work_struct *work)
2277{
2278 struct dualshock4 *ds4 = container_of(work, struct dualshock4, output_worker);
2279 struct dualshock4_output_report report;
2280 struct dualshock4_output_report_common *common;
2281
2282 dualshock4_init_output_report(ds4, &report, ds4->output_report_dmabuf);
2283 common = report.common;
2284
2285 scoped_guard(spinlock_irqsave, &ds4->base.lock) {
2286 /*
2287 * Some 3rd party gamepads expect updates to rumble and lightbar
2288 * together, and setting one may cancel the other.
2289 *
2290 * Let's maximise compatibility by always sending rumble and lightbar
2291 * updates together, even when only one has been scheduled, resulting
2292 * in:
2293 *
2294 * ds4->valid_flag0 >= 0x03
2295 *
2296 * Hopefully this will maximise compatibility with third-party pads.
2297 *
2298 * Any further update bits, such as 0x04 for lightbar blinking, will
2299 * be or'd on top of this like before.
2300 */
2301 if (ds4->update_rumble || ds4->update_lightbar) {
2302 ds4->update_rumble = true; /* 0x01 */
2303 ds4->update_lightbar = true; /* 0x02 */
2304 }
2305
2306 if (ds4->update_rumble) {
2307 /* Select classic rumble style haptics and enable it. */
2308 common->valid_flag0 |= DS4_OUTPUT_VALID_FLAG0_MOTOR;
2309 common->motor_left = ds4->motor_left;
2310 common->motor_right = ds4->motor_right;
2311 ds4->update_rumble = false;
2312 }
2313
2314 if (ds4->update_lightbar) {
2315 common->valid_flag0 |= DS4_OUTPUT_VALID_FLAG0_LED;
2316 /* Compatible behavior with hid-sony, which used a dummy global LED to
2317 * allow enabling/disabling the lightbar. The global LED maps to
2318 * lightbar_enabled.
2319 */
2320 common->lightbar_red = ds4->lightbar_enabled ? ds4->lightbar_red : 0;
2321 common->lightbar_green = ds4->lightbar_enabled ? ds4->lightbar_green : 0;
2322 common->lightbar_blue = ds4->lightbar_enabled ? ds4->lightbar_blue : 0;
2323 ds4->update_lightbar = false;
2324 }
2325
2326 if (ds4->update_lightbar_blink) {
2327 common->valid_flag0 |= DS4_OUTPUT_VALID_FLAG0_LED_BLINK;
2328 common->lightbar_blink_on = ds4->lightbar_blink_on;
2329 common->lightbar_blink_off = ds4->lightbar_blink_off;
2330 ds4->update_lightbar_blink = false;
2331 }
2332 }
2333
2334 /* Bluetooth packets need additional flags as well as a CRC in the last 4 bytes. */
2335 if (report.bt) {
2336 u32 crc;
2337 u8 seed = PS_OUTPUT_CRC32_SEED;
2338
2339 /* Hardware control flags need to set to let the device know
2340 * there is HID data as well as CRC.
2341 */
2342 report.bt->hw_control = DS4_OUTPUT_HWCTL_HID | DS4_OUTPUT_HWCTL_CRC32;
2343
2344 if (ds4->update_bt_poll_interval) {
2345 report.bt->hw_control |= ds4->bt_poll_interval;
2346 ds4->update_bt_poll_interval = false;
2347 }
2348
2349 crc = crc32_le(0xFFFFFFFF, &seed, 1);
2350 crc = ~crc32_le(crc, report.data, report.len - 4);
2351
2352 report.bt->crc32 = cpu_to_le32(crc);
2353 }
2354
2355 hid_hw_output_report(ds4->base.hdev, report.data, report.len);
2356}
2357
2358static int dualshock4_parse_report(struct ps_device *ps_dev, struct hid_report *report,
2359 u8 *data, int size)
2360{
2361 struct hid_device *hdev = ps_dev->hdev;
2362 struct dualshock4 *ds4 = container_of(ps_dev, struct dualshock4, base);
2363 struct dualshock4_input_report_common *ds4_report;
2364 struct dualshock4_touch_report *touch_reports;
2365 u8 battery_capacity, num_touch_reports, value;
2366 int battery_status, i, j;
2367 u16 sensor_timestamp;
2368 bool is_minimal = false;
2369
2370 /*
2371 * DualShock4 in USB uses the full HID report for reportID 1, but
2372 * Bluetooth uses a minimal HID report for reportID 1 and reports
2373 * the full report using reportID 17.
2374 */
2375 if (hdev->bus == BUS_USB && report->id == DS4_INPUT_REPORT_USB &&
2376 size == DS4_INPUT_REPORT_USB_SIZE) {
2377 struct dualshock4_input_report_usb *usb =
2378 (struct dualshock4_input_report_usb *)data;
2379
2380 if (usb->num_touch_reports > ARRAY_SIZE(usb->touch_reports)) {
2381 hid_err(hdev, "DualShock4 USB input report has invalid num_touch_reports=%d\n",
2382 usb->num_touch_reports);
2383 return -EINVAL;
2384 }
2385
2386 ds4_report = &usb->common;
2387 num_touch_reports = usb->num_touch_reports;
2388 touch_reports = usb->touch_reports;
2389 } else if (hdev->bus == BUS_BLUETOOTH && report->id == DS4_INPUT_REPORT_BT &&
2390 size == DS4_INPUT_REPORT_BT_SIZE) {
2391 struct dualshock4_input_report_bt *bt = (struct dualshock4_input_report_bt *)data;
2392 u32 report_crc = get_unaligned_le32(&bt->crc32);
2393
2394 /* Last 4 bytes of input report contains CRC. */
2395 if (!ps_check_crc32(PS_INPUT_CRC32_SEED, data, size - 4, report_crc)) {
2396 hid_err(hdev, "DualShock4 input CRC's check failed\n");
2397 return -EILSEQ;
2398 }
2399
2400 if (bt->num_touch_reports > ARRAY_SIZE(bt->touch_reports)) {
2401 hid_err(hdev, "DualShock4 BT input report has invalid num_touch_reports=%d\n",
2402 bt->num_touch_reports);
2403 return -EINVAL;
2404 }
2405
2406 ds4_report = &bt->common;
2407 num_touch_reports = bt->num_touch_reports;
2408 touch_reports = bt->touch_reports;
2409 } else if (hdev->bus == BUS_BLUETOOTH &&
2410 report->id == DS4_INPUT_REPORT_BT_MINIMAL &&
2411 size == DS4_INPUT_REPORT_BT_MINIMAL_SIZE) {
2412 /* Some third-party pads never switch to the full 0x11 report.
2413 * The short 0x01 report is 10 bytes long:
2414 * u8 report_id == 0x01
2415 * u8 first_bytes_of_full_report[9]
2416 * So let's reuse the full report parser, and stop it after
2417 * parsing the buttons.
2418 */
2419 ds4_report = (struct dualshock4_input_report_common *)&data[1];
2420 is_minimal = true;
2421 } else {
2422 hid_err(hdev, "Unhandled reportID=%d\n", report->id);
2423 return -1;
2424 }
2425
2426 input_report_abs(ds4->gamepad, ABS_X, ds4_report->x);
2427 input_report_abs(ds4->gamepad, ABS_Y, ds4_report->y);
2428 input_report_abs(ds4->gamepad, ABS_RX, ds4_report->rx);
2429 input_report_abs(ds4->gamepad, ABS_RY, ds4_report->ry);
2430 input_report_abs(ds4->gamepad, ABS_Z, ds4_report->z);
2431 input_report_abs(ds4->gamepad, ABS_RZ, ds4_report->rz);
2432
2433 value = ds4_report->buttons[0] & DS_BUTTONS0_HAT_SWITCH;
2434 if (value >= ARRAY_SIZE(ps_gamepad_hat_mapping))
2435 value = 8; /* center */
2436 input_report_abs(ds4->gamepad, ABS_HAT0X, ps_gamepad_hat_mapping[value].x);
2437 input_report_abs(ds4->gamepad, ABS_HAT0Y, ps_gamepad_hat_mapping[value].y);
2438
2439 input_report_key(ds4->gamepad, BTN_WEST, ds4_report->buttons[0] & DS_BUTTONS0_SQUARE);
2440 input_report_key(ds4->gamepad, BTN_SOUTH, ds4_report->buttons[0] & DS_BUTTONS0_CROSS);
2441 input_report_key(ds4->gamepad, BTN_EAST, ds4_report->buttons[0] & DS_BUTTONS0_CIRCLE);
2442 input_report_key(ds4->gamepad, BTN_NORTH, ds4_report->buttons[0] & DS_BUTTONS0_TRIANGLE);
2443 input_report_key(ds4->gamepad, BTN_TL, ds4_report->buttons[1] & DS_BUTTONS1_L1);
2444 input_report_key(ds4->gamepad, BTN_TR, ds4_report->buttons[1] & DS_BUTTONS1_R1);
2445 input_report_key(ds4->gamepad, BTN_TL2, ds4_report->buttons[1] & DS_BUTTONS1_L2);
2446 input_report_key(ds4->gamepad, BTN_TR2, ds4_report->buttons[1] & DS_BUTTONS1_R2);
2447 input_report_key(ds4->gamepad, BTN_SELECT, ds4_report->buttons[1] & DS_BUTTONS1_CREATE);
2448 input_report_key(ds4->gamepad, BTN_START, ds4_report->buttons[1] & DS_BUTTONS1_OPTIONS);
2449 input_report_key(ds4->gamepad, BTN_THUMBL, ds4_report->buttons[1] & DS_BUTTONS1_L3);
2450 input_report_key(ds4->gamepad, BTN_THUMBR, ds4_report->buttons[1] & DS_BUTTONS1_R3);
2451 input_report_key(ds4->gamepad, BTN_MODE, ds4_report->buttons[2] & DS_BUTTONS2_PS_HOME);
2452 input_sync(ds4->gamepad);
2453
2454 if (is_minimal)
2455 return 0;
2456
2457 /* Parse and calibrate gyroscope data. */
2458 for (i = 0; i < ARRAY_SIZE(ds4_report->gyro); i++) {
2459 int raw_data = (short)le16_to_cpu(ds4_report->gyro[i]);
2460 int calib_data = mult_frac(ds4->gyro_calib_data[i].sens_numer,
2461 raw_data, ds4->gyro_calib_data[i].sens_denom);
2462
2463 input_report_abs(ds4->sensors, ds4->gyro_calib_data[i].abs_code, calib_data);
2464 }
2465
2466 /* Parse and calibrate accelerometer data. */
2467 for (i = 0; i < ARRAY_SIZE(ds4_report->accel); i++) {
2468 int raw_data = (short)le16_to_cpu(ds4_report->accel[i]);
2469 int calib_data = mult_frac(ds4->accel_calib_data[i].sens_numer,
2470 raw_data - ds4->accel_calib_data[i].bias,
2471 ds4->accel_calib_data[i].sens_denom);
2472
2473 input_report_abs(ds4->sensors, ds4->accel_calib_data[i].abs_code, calib_data);
2474 }
2475
2476 /* Convert timestamp (in 5.33us unit) to timestamp_us */
2477 sensor_timestamp = le16_to_cpu(ds4_report->sensor_timestamp);
2478 if (!ds4->sensor_timestamp_initialized) {
2479 ds4->sensor_timestamp_us = DIV_ROUND_CLOSEST(sensor_timestamp * 16, 3);
2480 ds4->sensor_timestamp_initialized = true;
2481 } else {
2482 u16 delta;
2483
2484 if (ds4->prev_sensor_timestamp > sensor_timestamp)
2485 delta = (U16_MAX - ds4->prev_sensor_timestamp + sensor_timestamp + 1);
2486 else
2487 delta = sensor_timestamp - ds4->prev_sensor_timestamp;
2488 ds4->sensor_timestamp_us += DIV_ROUND_CLOSEST(delta * 16, 3);
2489 }
2490 ds4->prev_sensor_timestamp = sensor_timestamp;
2491 input_event(ds4->sensors, EV_MSC, MSC_TIMESTAMP, ds4->sensor_timestamp_us);
2492 input_sync(ds4->sensors);
2493
2494 for (i = 0; i < num_touch_reports; i++) {
2495 struct dualshock4_touch_report *touch_report = &touch_reports[i];
2496
2497 for (j = 0; j < ARRAY_SIZE(touch_report->points); j++) {
2498 struct dualshock4_touch_point *point = &touch_report->points[j];
2499 bool active = (point->contact & DS4_TOUCH_POINT_INACTIVE) ? false : true;
2500
2501 input_mt_slot(ds4->touchpad, j);
2502 input_mt_report_slot_state(ds4->touchpad, MT_TOOL_FINGER, active);
2503
2504 if (active) {
2505 input_report_abs(ds4->touchpad, ABS_MT_POSITION_X,
2506 DS4_TOUCH_POINT_X(point->x_hi, point->x_lo));
2507 input_report_abs(ds4->touchpad, ABS_MT_POSITION_Y,
2508 DS4_TOUCH_POINT_Y(point->y_hi, point->y_lo));
2509 }
2510 }
2511 input_mt_sync_frame(ds4->touchpad);
2512 input_sync(ds4->touchpad);
2513 }
2514 input_report_key(ds4->touchpad, BTN_LEFT, ds4_report->buttons[2] & DS_BUTTONS2_TOUCHPAD);
2515
2516 /*
2517 * Interpretation of the battery_capacity data depends on the cable state.
2518 * When no cable is connected (bit4 is 0):
2519 * - 0:10: percentage in units of 10%.
2520 * When a cable is plugged in:
2521 * - 0-10: percentage in units of 10%.
2522 * - 11: battery is full
2523 * - 14: not charging due to Voltage or temperature error
2524 * - 15: charge error
2525 */
2526 if (ds4_report->status[0] & DS4_STATUS0_CABLE_STATE) {
2527 u8 battery_data = ds4_report->status[0] & DS4_STATUS0_BATTERY_CAPACITY;
2528
2529 if (battery_data < 10) {
2530 /* Take the mid-point for each battery capacity value,
2531 * because on the hardware side 0 = 0-9%, 1=10-19%, etc.
2532 * This matches official platform behavior, which does
2533 * the same.
2534 */
2535 battery_capacity = battery_data * 10 + 5;
2536 battery_status = POWER_SUPPLY_STATUS_CHARGING;
2537 } else if (battery_data == 10) {
2538 battery_capacity = 100;
2539 battery_status = POWER_SUPPLY_STATUS_CHARGING;
2540 } else if (battery_data == DS4_BATTERY_STATUS_FULL) {
2541 battery_capacity = 100;
2542 battery_status = POWER_SUPPLY_STATUS_FULL;
2543 } else { /* 14, 15 and undefined values */
2544 battery_capacity = 0;
2545 battery_status = POWER_SUPPLY_STATUS_UNKNOWN;
2546 }
2547 } else {
2548 u8 battery_data = ds4_report->status[0] & DS4_STATUS0_BATTERY_CAPACITY;
2549
2550 if (battery_data < 10)
2551 battery_capacity = battery_data * 10 + 5;
2552 else /* 10 */
2553 battery_capacity = 100;
2554
2555 battery_status = POWER_SUPPLY_STATUS_DISCHARGING;
2556 }
2557
2558 scoped_guard(spinlock_irqsave, &ps_dev->lock) {
2559 ps_dev->battery_capacity = battery_capacity;
2560 ps_dev->battery_status = battery_status;
2561 }
2562
2563 return 0;
2564}
2565
2566static int dualshock4_dongle_parse_report(struct ps_device *ps_dev, struct hid_report *report,
2567 u8 *data, int size)
2568{
2569 struct dualshock4 *ds4 = container_of(ps_dev, struct dualshock4, base);
2570 bool connected = false;
2571
2572 /* The dongle reports data using the main USB report (0x1) no matter whether a controller
2573 * is connected with mostly zeros. The report does contain dongle status, which we use to
2574 * determine if a controller is connected and if so we forward to the regular DualShock4
2575 * parsing code.
2576 */
2577 if (data[0] == DS4_INPUT_REPORT_USB && size == DS4_INPUT_REPORT_USB_SIZE) {
2578 struct dualshock4_input_report_common *ds4_report =
2579 (struct dualshock4_input_report_common *)&data[1];
2580
2581 connected = ds4_report->status[1] & DS4_STATUS1_DONGLE_STATE ? false : true;
2582
2583 if (ds4->dongle_state == DONGLE_DISCONNECTED && connected) {
2584 hid_info(ps_dev->hdev, "DualShock 4 USB dongle: controller connected\n");
2585
2586 dualshock4_set_default_lightbar_colors(ds4);
2587
2588 scoped_guard(spinlock_irqsave, &ps_dev->lock)
2589 ds4->dongle_state = DONGLE_CALIBRATING;
2590
2591 schedule_work(&ds4->dongle_hotplug_worker);
2592
2593 /* Don't process the report since we don't have
2594 * calibration data, but let hidraw have it anyway.
2595 */
2596 return 0;
2597 } else if ((ds4->dongle_state == DONGLE_CONNECTED ||
2598 ds4->dongle_state == DONGLE_DISABLED) && !connected) {
2599 hid_info(ps_dev->hdev, "DualShock 4 USB dongle: controller disconnected\n");
2600
2601 scoped_guard(spinlock_irqsave, &ps_dev->lock)
2602 ds4->dongle_state = DONGLE_DISCONNECTED;
2603
2604 /* Return 0, so hidraw can get the report. */
2605 return 0;
2606 } else if (ds4->dongle_state == DONGLE_CALIBRATING ||
2607 ds4->dongle_state == DONGLE_DISABLED ||
2608 ds4->dongle_state == DONGLE_DISCONNECTED) {
2609 /* Return 0, so hidraw can get the report. */
2610 return 0;
2611 }
2612 }
2613
2614 if (connected)
2615 return dualshock4_parse_report(ps_dev, report, data, size);
2616
2617 return 0;
2618}
2619
2620static int dualshock4_play_effect(struct input_dev *dev, void *data, struct ff_effect *effect)
2621{
2622 struct hid_device *hdev = input_get_drvdata(dev);
2623 struct dualshock4 *ds4 = hid_get_drvdata(hdev);
2624
2625 if (effect->type != FF_RUMBLE)
2626 return 0;
2627
2628 scoped_guard(spinlock_irqsave, &ds4->base.lock) {
2629 ds4->update_rumble = true;
2630 ds4->motor_left = effect->u.rumble.strong_magnitude / 256;
2631 ds4->motor_right = effect->u.rumble.weak_magnitude / 256;
2632 }
2633
2634 dualshock4_schedule_work(ds4);
2635 return 0;
2636}
2637
2638static void dualshock4_remove(struct ps_device *ps_dev)
2639{
2640 struct dualshock4 *ds4 = container_of(ps_dev, struct dualshock4, base);
2641
2642 scoped_guard(spinlock_irqsave, &ds4->base.lock)
2643 ds4->output_worker_initialized = false;
2644
2645 cancel_work_sync(&ds4->output_worker);
2646
2647 if (ps_dev->hdev->product == USB_DEVICE_ID_SONY_PS4_CONTROLLER_DONGLE)
2648 cancel_work_sync(&ds4->dongle_hotplug_worker);
2649}
2650
2651static inline void dualshock4_schedule_work(struct dualshock4 *ds4)
2652{
2653 /* Using scoped_guard() instead of guard() to make sparse happy */
2654 scoped_guard(spinlock_irqsave, &ds4->base.lock)
2655 if (ds4->output_worker_initialized)
2656 schedule_work(&ds4->output_worker);
2657}
2658
2659static void dualshock4_set_bt_poll_interval(struct dualshock4 *ds4, u8 interval)
2660{
2661 ds4->bt_poll_interval = interval;
2662 ds4->update_bt_poll_interval = true;
2663 dualshock4_schedule_work(ds4);
2664}
2665
2666/* Set default lightbar color based on player. */
2667static void dualshock4_set_default_lightbar_colors(struct dualshock4 *ds4)
2668{
2669 /* Use same player colors as PlayStation 4.
2670 * Array of colors is in RGB.
2671 */
2672 static const int player_colors[4][3] = {
2673 { 0x00, 0x00, 0x40 }, /* Blue */
2674 { 0x40, 0x00, 0x00 }, /* Red */
2675 { 0x00, 0x40, 0x00 }, /* Green */
2676 { 0x20, 0x00, 0x20 } /* Pink */
2677 };
2678
2679 u8 player_id = ds4->base.player_id % ARRAY_SIZE(player_colors);
2680
2681 ds4->lightbar_enabled = true;
2682 ds4->lightbar_red = player_colors[player_id][0];
2683 ds4->lightbar_green = player_colors[player_id][1];
2684 ds4->lightbar_blue = player_colors[player_id][2];
2685
2686 ds4->update_lightbar = true;
2687 dualshock4_schedule_work(ds4);
2688}
2689
2690static struct ps_device *dualshock4_create(struct hid_device *hdev)
2691{
2692 struct dualshock4 *ds4;
2693 struct ps_device *ps_dev;
2694 u8 max_output_report_size;
2695 int i, ret;
2696
2697 /* The DualShock4 has an RGB lightbar, which the original hid-sony driver
2698 * exposed as a set of 4 LEDs for the 3 color channels and a global control.
2699 * Ideally this should have used the multi-color LED class, which didn't exist
2700 * yet. In addition the driver used a naming scheme not compliant with the LED
2701 * naming spec by using "<mac_address>:<color>", which contained many colons.
2702 * We use a more compliant by using "<device_name>:<color>" name now. Ideally
2703 * would have been "<device_name>:<color>:indicator", but that would break
2704 * existing applications (e.g. Android). Nothing matches against MAC address.
2705 */
2706 static const struct ps_led_info lightbar_leds_info[] = {
2707 { NULL, "red", 255, dualshock4_led_get_brightness,
2708 dualshock4_led_set_brightness },
2709 { NULL, "green", 255, dualshock4_led_get_brightness,
2710 dualshock4_led_set_brightness },
2711 { NULL, "blue", 255, dualshock4_led_get_brightness,
2712 dualshock4_led_set_brightness },
2713 { NULL, "global", 1, dualshock4_led_get_brightness,
2714 dualshock4_led_set_brightness, dualshock4_led_set_blink },
2715 };
2716
2717 ds4 = devm_kzalloc(&hdev->dev, sizeof(*ds4), GFP_KERNEL);
2718 if (!ds4)
2719 return ERR_PTR(-ENOMEM);
2720
2721 /*
2722 * Patch version to allow userspace to distinguish between
2723 * hid-generic vs hid-playstation axis and button mapping.
2724 */
2725 hdev->version |= HID_PLAYSTATION_VERSION_PATCH;
2726
2727 ps_dev = &ds4->base;
2728 ps_dev->hdev = hdev;
2729 spin_lock_init(&ps_dev->lock);
2730 ps_dev->battery_capacity = 100; /* initial value until parse_report. */
2731 ps_dev->battery_status = POWER_SUPPLY_STATUS_UNKNOWN;
2732 ps_dev->parse_report = dualshock4_parse_report;
2733 ps_dev->remove = dualshock4_remove;
2734 INIT_WORK(&ds4->output_worker, dualshock4_output_worker);
2735 ds4->output_worker_initialized = true;
2736 hid_set_drvdata(hdev, ds4);
2737
2738 max_output_report_size = sizeof(struct dualshock4_output_report_bt);
2739 ds4->output_report_dmabuf = devm_kzalloc(&hdev->dev, max_output_report_size, GFP_KERNEL);
2740 if (!ds4->output_report_dmabuf)
2741 return ERR_PTR(-ENOMEM);
2742
2743 if (hdev->product == USB_DEVICE_ID_SONY_PS4_CONTROLLER_DONGLE) {
2744 ds4->dongle_state = DONGLE_DISCONNECTED;
2745 INIT_WORK(&ds4->dongle_hotplug_worker, dualshock4_dongle_calibration_work);
2746
2747 /* Override parse report for dongle specific hotplug handling. */
2748 ps_dev->parse_report = dualshock4_dongle_parse_report;
2749 }
2750
2751 ret = dualshock4_get_mac_address(ds4);
2752 if (ret) {
2753 hid_err(hdev, "Failed to get MAC address from DualShock4\n");
2754 return ERR_PTR(ret);
2755 }
2756 snprintf(hdev->uniq, sizeof(hdev->uniq), "%pMR", ds4->base.mac_address);
2757
2758 ret = dualshock4_get_firmware_info(ds4);
2759 if (ret) {
2760 hid_warn(hdev, "Failed to get firmware info from DualShock4\n");
2761 hid_warn(hdev, "HW/FW version data in sysfs will be invalid.\n");
2762 }
2763
2764 ret = ps_devices_list_add(ps_dev);
2765 if (ret)
2766 return ERR_PTR(ret);
2767
2768 ret = dualshock4_get_calibration_data(ds4);
2769 if (ret) {
2770 hid_warn(hdev, "Failed to get calibration data from DualShock4\n");
2771 hid_warn(hdev, "Gyroscope and accelerometer will be inaccurate.\n");
2772 }
2773
2774 ds4->gamepad = ps_gamepad_create(hdev, dualshock4_play_effect);
2775 if (IS_ERR(ds4->gamepad)) {
2776 ret = PTR_ERR(ds4->gamepad);
2777 goto err;
2778 }
2779
2780 /* Use gamepad input device name as primary device name for e.g. LEDs */
2781 ps_dev->input_dev_name = dev_name(&ds4->gamepad->dev);
2782
2783 ds4->sensors = ps_sensors_create(hdev, DS4_ACC_RANGE, DS4_ACC_RES_PER_G,
2784 DS4_GYRO_RANGE, DS4_GYRO_RES_PER_DEG_S);
2785 if (IS_ERR(ds4->sensors)) {
2786 ret = PTR_ERR(ds4->sensors);
2787 goto err;
2788 }
2789
2790 ds4->touchpad = ps_touchpad_create(hdev, DS4_TOUCHPAD_WIDTH, DS4_TOUCHPAD_HEIGHT, 2);
2791 if (IS_ERR(ds4->touchpad)) {
2792 ret = PTR_ERR(ds4->touchpad);
2793 goto err;
2794 }
2795
2796 ret = ps_device_register_battery(ps_dev);
2797 if (ret)
2798 goto err;
2799
2800 for (i = 0; i < ARRAY_SIZE(lightbar_leds_info); i++) {
2801 const struct ps_led_info *led_info = &lightbar_leds_info[i];
2802
2803 ret = ps_led_register(ps_dev, &ds4->lightbar_leds[i], led_info);
2804 if (ret < 0)
2805 goto err;
2806 }
2807
2808 dualshock4_set_bt_poll_interval(ds4, DS4_BT_DEFAULT_POLL_INTERVAL_MS);
2809
2810 ret = ps_device_set_player_id(ps_dev);
2811 if (ret) {
2812 hid_err(hdev, "Failed to assign player id for DualShock4: %d\n", ret);
2813 goto err;
2814 }
2815
2816 dualshock4_set_default_lightbar_colors(ds4);
2817
2818 /*
2819 * Reporting hardware and firmware is important as there are frequent updates, which
2820 * can change behavior.
2821 */
2822 hid_info(hdev, "Registered DualShock4 controller hw_version=0x%08x fw_version=0x%08x\n",
2823 ds4->base.hw_version, ds4->base.fw_version);
2824 return &ds4->base;
2825
2826err:
2827 ps_devices_list_remove(ps_dev);
2828 return ERR_PTR(ret);
2829}
2830
2831static int ps_raw_event(struct hid_device *hdev, struct hid_report *report,
2832 u8 *data, int size)
2833{
2834 struct ps_device *dev = hid_get_drvdata(hdev);
2835
2836 if (dev && dev->parse_report)
2837 return dev->parse_report(dev, report, data, size);
2838
2839 return 0;
2840}
2841
2842static int ps_probe(struct hid_device *hdev, const struct hid_device_id *id)
2843{
2844 struct ps_device *dev;
2845 int ret;
2846
2847 ret = hid_parse(hdev);
2848 if (ret) {
2849 hid_err(hdev, "Parse failed\n");
2850 return ret;
2851 }
2852
2853 ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
2854 if (ret) {
2855 hid_err(hdev, "Failed to start HID device\n");
2856 return ret;
2857 }
2858
2859 ret = hid_hw_open(hdev);
2860 if (ret) {
2861 hid_err(hdev, "Failed to open HID device\n");
2862 goto err_stop;
2863 }
2864
2865 if (id->driver_data == PS_TYPE_PS4_DUALSHOCK4) {
2866 dev = dualshock4_create(hdev);
2867 if (IS_ERR(dev)) {
2868 hid_err(hdev, "Failed to create dualshock4.\n");
2869 ret = PTR_ERR(dev);
2870 goto err_close;
2871 }
2872 } else if (id->driver_data == PS_TYPE_PS5_DUALSENSE) {
2873 dev = dualsense_create(hdev);
2874 if (IS_ERR(dev)) {
2875 hid_err(hdev, "Failed to create dualsense.\n");
2876 ret = PTR_ERR(dev);
2877 goto err_close;
2878 }
2879 }
2880
2881 return ret;
2882
2883err_close:
2884 hid_hw_close(hdev);
2885err_stop:
2886 hid_hw_stop(hdev);
2887 return ret;
2888}
2889
2890static void ps_remove(struct hid_device *hdev)
2891{
2892 struct ps_device *dev = hid_get_drvdata(hdev);
2893
2894 ps_devices_list_remove(dev);
2895 ps_device_release_player_id(dev);
2896
2897 if (dev->remove)
2898 dev->remove(dev);
2899
2900 hid_hw_close(hdev);
2901 hid_hw_stop(hdev);
2902}
2903
2904static const struct hid_device_id ps_devices[] = {
2905 /* Sony DualShock 4 controllers for PS4 */
2906 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER),
2907 .driver_data = PS_TYPE_PS4_DUALSHOCK4 },
2908 { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER),
2909 .driver_data = PS_TYPE_PS4_DUALSHOCK4 },
2910 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER_2),
2911 .driver_data = PS_TYPE_PS4_DUALSHOCK4 },
2912 { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER_2),
2913 .driver_data = PS_TYPE_PS4_DUALSHOCK4 },
2914 { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER_DONGLE),
2915 .driver_data = PS_TYPE_PS4_DUALSHOCK4 },
2916
2917 /* Sony DualSense controllers for PS5 */
2918 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER),
2919 .driver_data = PS_TYPE_PS5_DUALSENSE },
2920 { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER),
2921 .driver_data = PS_TYPE_PS5_DUALSENSE },
2922 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER_2),
2923 .driver_data = PS_TYPE_PS5_DUALSENSE },
2924 { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER_2),
2925 .driver_data = PS_TYPE_PS5_DUALSENSE },
2926 { }
2927};
2928MODULE_DEVICE_TABLE(hid, ps_devices);
2929
2930static struct hid_driver ps_driver = {
2931 .name = "playstation",
2932 .id_table = ps_devices,
2933 .probe = ps_probe,
2934 .remove = ps_remove,
2935 .raw_event = ps_raw_event,
2936 .driver = {
2937 .dev_groups = ps_device_groups,
2938 },
2939};
2940
2941static int __init ps_init(void)
2942{
2943 return hid_register_driver(&ps_driver);
2944}
2945
2946static void __exit ps_exit(void)
2947{
2948 hid_unregister_driver(&ps_driver);
2949 ida_destroy(&ps_player_id_allocator);
2950}
2951
2952module_init(ps_init);
2953module_exit(ps_exit);
2954
2955MODULE_AUTHOR("Sony Interactive Entertainment");
2956MODULE_DESCRIPTION("HID Driver for PlayStation peripherals.");
2957MODULE_LICENSE("GPL");