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

source code of linux/drivers/hid/hid-playstation.c