Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-or-later
0002 /*
0003  *  HID driver for Sony DualSense(TM) controller.
0004  *
0005  *  Copyright (c) 2020 Sony Interactive Entertainment
0006  */
0007 
0008 #include <linux/bits.h>
0009 #include <linux/crc32.h>
0010 #include <linux/device.h>
0011 #include <linux/hid.h>
0012 #include <linux/idr.h>
0013 #include <linux/input/mt.h>
0014 #include <linux/leds.h>
0015 #include <linux/led-class-multicolor.h>
0016 #include <linux/module.h>
0017 
0018 #include <asm/unaligned.h>
0019 
0020 #include "hid-ids.h"
0021 
0022 /* List of connected playstation devices. */
0023 static DEFINE_MUTEX(ps_devices_lock);
0024 static LIST_HEAD(ps_devices_list);
0025 
0026 static DEFINE_IDA(ps_player_id_allocator);
0027 
0028 #define HID_PLAYSTATION_VERSION_PATCH 0x8000
0029 
0030 /* Base class for playstation devices. */
0031 struct ps_device {
0032     struct list_head list;
0033     struct hid_device *hdev;
0034     spinlock_t lock;
0035 
0036     uint32_t player_id;
0037 
0038     struct power_supply_desc battery_desc;
0039     struct power_supply *battery;
0040     uint8_t battery_capacity;
0041     int battery_status;
0042 
0043     const char *input_dev_name; /* Name of primary input device. */
0044     uint8_t mac_address[6]; /* Note: stored in little endian order. */
0045     uint32_t hw_version;
0046     uint32_t fw_version;
0047 
0048     int (*parse_report)(struct ps_device *dev, struct hid_report *report, u8 *data, int size);
0049 };
0050 
0051 /* Calibration data for playstation motion sensors. */
0052 struct ps_calibration_data {
0053     int abs_code;
0054     short bias;
0055     int sens_numer;
0056     int sens_denom;
0057 };
0058 
0059 struct ps_led_info {
0060     const char *name;
0061     const char *color;
0062     enum led_brightness (*brightness_get)(struct led_classdev *cdev);
0063     int (*brightness_set)(struct led_classdev *cdev, enum led_brightness);
0064 };
0065 
0066 /* Seed values for DualShock4 / DualSense CRC32 for different report types. */
0067 #define PS_INPUT_CRC32_SEED 0xA1
0068 #define PS_OUTPUT_CRC32_SEED    0xA2
0069 #define PS_FEATURE_CRC32_SEED   0xA3
0070 
0071 #define DS_INPUT_REPORT_USB         0x01
0072 #define DS_INPUT_REPORT_USB_SIZE        64
0073 #define DS_INPUT_REPORT_BT          0x31
0074 #define DS_INPUT_REPORT_BT_SIZE         78
0075 #define DS_OUTPUT_REPORT_USB            0x02
0076 #define DS_OUTPUT_REPORT_USB_SIZE       63
0077 #define DS_OUTPUT_REPORT_BT         0x31
0078 #define DS_OUTPUT_REPORT_BT_SIZE        78
0079 
0080 #define DS_FEATURE_REPORT_CALIBRATION       0x05
0081 #define DS_FEATURE_REPORT_CALIBRATION_SIZE  41
0082 #define DS_FEATURE_REPORT_PAIRING_INFO      0x09
0083 #define DS_FEATURE_REPORT_PAIRING_INFO_SIZE 20
0084 #define DS_FEATURE_REPORT_FIRMWARE_INFO     0x20
0085 #define DS_FEATURE_REPORT_FIRMWARE_INFO_SIZE    64
0086 
0087 /* Button masks for DualSense input report. */
0088 #define DS_BUTTONS0_HAT_SWITCH  GENMASK(3, 0)
0089 #define DS_BUTTONS0_SQUARE  BIT(4)
0090 #define DS_BUTTONS0_CROSS   BIT(5)
0091 #define DS_BUTTONS0_CIRCLE  BIT(6)
0092 #define DS_BUTTONS0_TRIANGLE    BIT(7)
0093 #define DS_BUTTONS1_L1      BIT(0)
0094 #define DS_BUTTONS1_R1      BIT(1)
0095 #define DS_BUTTONS1_L2      BIT(2)
0096 #define DS_BUTTONS1_R2      BIT(3)
0097 #define DS_BUTTONS1_CREATE  BIT(4)
0098 #define DS_BUTTONS1_OPTIONS BIT(5)
0099 #define DS_BUTTONS1_L3      BIT(6)
0100 #define DS_BUTTONS1_R3      BIT(7)
0101 #define DS_BUTTONS2_PS_HOME BIT(0)
0102 #define DS_BUTTONS2_TOUCHPAD    BIT(1)
0103 #define DS_BUTTONS2_MIC_MUTE    BIT(2)
0104 
0105 /* Status field of DualSense input report. */
0106 #define DS_STATUS_BATTERY_CAPACITY  GENMASK(3, 0)
0107 #define DS_STATUS_CHARGING      GENMASK(7, 4)
0108 #define DS_STATUS_CHARGING_SHIFT    4
0109 
0110 /*
0111  * Status of a DualSense touch point contact.
0112  * Contact IDs, with highest bit set are 'inactive'
0113  * and any associated data is then invalid.
0114  */
0115 #define DS_TOUCH_POINT_INACTIVE BIT(7)
0116 
0117  /* Magic value required in tag field of Bluetooth output report. */
0118 #define DS_OUTPUT_TAG 0x10
0119 /* Flags for DualSense output report. */
0120 #define DS_OUTPUT_VALID_FLAG0_COMPATIBLE_VIBRATION BIT(0)
0121 #define DS_OUTPUT_VALID_FLAG0_HAPTICS_SELECT BIT(1)
0122 #define DS_OUTPUT_VALID_FLAG1_MIC_MUTE_LED_CONTROL_ENABLE BIT(0)
0123 #define DS_OUTPUT_VALID_FLAG1_POWER_SAVE_CONTROL_ENABLE BIT(1)
0124 #define DS_OUTPUT_VALID_FLAG1_LIGHTBAR_CONTROL_ENABLE BIT(2)
0125 #define DS_OUTPUT_VALID_FLAG1_RELEASE_LEDS BIT(3)
0126 #define DS_OUTPUT_VALID_FLAG1_PLAYER_INDICATOR_CONTROL_ENABLE BIT(4)
0127 #define DS_OUTPUT_VALID_FLAG2_LIGHTBAR_SETUP_CONTROL_ENABLE BIT(1)
0128 #define DS_OUTPUT_POWER_SAVE_CONTROL_MIC_MUTE BIT(4)
0129 #define DS_OUTPUT_LIGHTBAR_SETUP_LIGHT_OUT BIT(1)
0130 
0131 /* DualSense hardware limits */
0132 #define DS_ACC_RES_PER_G    8192
0133 #define DS_ACC_RANGE        (4*DS_ACC_RES_PER_G)
0134 #define DS_GYRO_RES_PER_DEG_S   1024
0135 #define DS_GYRO_RANGE       (2048*DS_GYRO_RES_PER_DEG_S)
0136 #define DS_TOUCHPAD_WIDTH   1920
0137 #define DS_TOUCHPAD_HEIGHT  1080
0138 
0139 struct dualsense {
0140     struct ps_device base;
0141     struct input_dev *gamepad;
0142     struct input_dev *sensors;
0143     struct input_dev *touchpad;
0144 
0145     /* Calibration data for accelerometer and gyroscope. */
0146     struct ps_calibration_data accel_calib_data[3];
0147     struct ps_calibration_data gyro_calib_data[3];
0148 
0149     /* Timestamp for sensor data */
0150     bool sensor_timestamp_initialized;
0151     uint32_t prev_sensor_timestamp;
0152     uint32_t sensor_timestamp_us;
0153 
0154     /* Compatible rumble state */
0155     bool update_rumble;
0156     uint8_t motor_left;
0157     uint8_t motor_right;
0158 
0159     /* RGB lightbar */
0160     struct led_classdev_mc lightbar;
0161     bool update_lightbar;
0162     uint8_t lightbar_red;
0163     uint8_t lightbar_green;
0164     uint8_t lightbar_blue;
0165 
0166     /* Microphone */
0167     bool update_mic_mute;
0168     bool mic_muted;
0169     bool last_btn_mic_state;
0170 
0171     /* Player leds */
0172     bool update_player_leds;
0173     uint8_t player_leds_state;
0174     struct led_classdev player_leds[5];
0175 
0176     struct work_struct output_worker;
0177     void *output_report_dmabuf;
0178     uint8_t output_seq; /* Sequence number for output report. */
0179 };
0180 
0181 struct dualsense_touch_point {
0182     uint8_t contact;
0183     uint8_t x_lo;
0184     uint8_t x_hi:4, y_lo:4;
0185     uint8_t y_hi;
0186 } __packed;
0187 static_assert(sizeof(struct dualsense_touch_point) == 4);
0188 
0189 /* Main DualSense input report excluding any BT/USB specific headers. */
0190 struct dualsense_input_report {
0191     uint8_t x, y;
0192     uint8_t rx, ry;
0193     uint8_t z, rz;
0194     uint8_t seq_number;
0195     uint8_t buttons[4];
0196     uint8_t reserved[4];
0197 
0198     /* Motion sensors */
0199     __le16 gyro[3]; /* x, y, z */
0200     __le16 accel[3]; /* x, y, z */
0201     __le32 sensor_timestamp;
0202     uint8_t reserved2;
0203 
0204     /* Touchpad */
0205     struct dualsense_touch_point points[2];
0206 
0207     uint8_t reserved3[12];
0208     uint8_t status;
0209     uint8_t reserved4[10];
0210 } __packed;
0211 /* Common input report size shared equals the size of the USB report minus 1 byte for ReportID. */
0212 static_assert(sizeof(struct dualsense_input_report) == DS_INPUT_REPORT_USB_SIZE - 1);
0213 
0214 /* Common data between DualSense BT/USB main output report. */
0215 struct dualsense_output_report_common {
0216     uint8_t valid_flag0;
0217     uint8_t valid_flag1;
0218 
0219     /* For DualShock 4 compatibility mode. */
0220     uint8_t motor_right;
0221     uint8_t motor_left;
0222 
0223     /* Audio controls */
0224     uint8_t reserved[4];
0225     uint8_t mute_button_led;
0226 
0227     uint8_t power_save_control;
0228     uint8_t reserved2[28];
0229 
0230     /* LEDs and lightbar */
0231     uint8_t valid_flag2;
0232     uint8_t reserved3[2];
0233     uint8_t lightbar_setup;
0234     uint8_t led_brightness;
0235     uint8_t player_leds;
0236     uint8_t lightbar_red;
0237     uint8_t lightbar_green;
0238     uint8_t lightbar_blue;
0239 } __packed;
0240 static_assert(sizeof(struct dualsense_output_report_common) == 47);
0241 
0242 struct dualsense_output_report_bt {
0243     uint8_t report_id; /* 0x31 */
0244     uint8_t seq_tag;
0245     uint8_t tag;
0246     struct dualsense_output_report_common common;
0247     uint8_t reserved[24];
0248     __le32 crc32;
0249 } __packed;
0250 static_assert(sizeof(struct dualsense_output_report_bt) == DS_OUTPUT_REPORT_BT_SIZE);
0251 
0252 struct dualsense_output_report_usb {
0253     uint8_t report_id; /* 0x02 */
0254     struct dualsense_output_report_common common;
0255     uint8_t reserved[15];
0256 } __packed;
0257 static_assert(sizeof(struct dualsense_output_report_usb) == DS_OUTPUT_REPORT_USB_SIZE);
0258 
0259 /*
0260  * The DualSense has a main output report used to control most features. It is
0261  * largely the same between Bluetooth and USB except for different headers and CRC.
0262  * This structure hide the differences between the two to simplify sending output reports.
0263  */
0264 struct dualsense_output_report {
0265     uint8_t *data; /* Start of data */
0266     uint8_t len; /* Size of output report */
0267 
0268     /* Points to Bluetooth data payload in case for a Bluetooth report else NULL. */
0269     struct dualsense_output_report_bt *bt;
0270     /* Points to USB data payload in case for a USB report else NULL. */
0271     struct dualsense_output_report_usb *usb;
0272     /* Points to common section of report, so past any headers. */
0273     struct dualsense_output_report_common *common;
0274 };
0275 
0276 /*
0277  * Common gamepad buttons across DualShock 3 / 4 and DualSense.
0278  * Note: for device with a touchpad, touchpad button is not included
0279  *        as it will be part of the touchpad device.
0280  */
0281 static const int ps_gamepad_buttons[] = {
0282     BTN_WEST, /* Square */
0283     BTN_NORTH, /* Triangle */
0284     BTN_EAST, /* Circle */
0285     BTN_SOUTH, /* Cross */
0286     BTN_TL, /* L1 */
0287     BTN_TR, /* R1 */
0288     BTN_TL2, /* L2 */
0289     BTN_TR2, /* R2 */
0290     BTN_SELECT, /* Create (PS5) / Share (PS4) */
0291     BTN_START, /* Option */
0292     BTN_THUMBL, /* L3 */
0293     BTN_THUMBR, /* R3 */
0294     BTN_MODE, /* PS Home */
0295 };
0296 
0297 static const struct {int x; int y; } ps_gamepad_hat_mapping[] = {
0298     {0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1},
0299     {0, 0},
0300 };
0301 
0302 static void dualsense_set_lightbar(struct dualsense *ds, uint8_t red, uint8_t green, uint8_t blue);
0303 
0304 /*
0305  * Add a new ps_device to ps_devices if it doesn't exist.
0306  * Return error on duplicate device, which can happen if the same
0307  * device is connected using both Bluetooth and USB.
0308  */
0309 static int ps_devices_list_add(struct ps_device *dev)
0310 {
0311     struct ps_device *entry;
0312 
0313     mutex_lock(&ps_devices_lock);
0314     list_for_each_entry(entry, &ps_devices_list, list) {
0315         if (!memcmp(entry->mac_address, dev->mac_address, sizeof(dev->mac_address))) {
0316             hid_err(dev->hdev, "Duplicate device found for MAC address %pMR.\n",
0317                     dev->mac_address);
0318             mutex_unlock(&ps_devices_lock);
0319             return -EEXIST;
0320         }
0321     }
0322 
0323     list_add_tail(&dev->list, &ps_devices_list);
0324     mutex_unlock(&ps_devices_lock);
0325     return 0;
0326 }
0327 
0328 static int ps_devices_list_remove(struct ps_device *dev)
0329 {
0330     mutex_lock(&ps_devices_lock);
0331     list_del(&dev->list);
0332     mutex_unlock(&ps_devices_lock);
0333     return 0;
0334 }
0335 
0336 static int ps_device_set_player_id(struct ps_device *dev)
0337 {
0338     int ret = ida_alloc(&ps_player_id_allocator, GFP_KERNEL);
0339 
0340     if (ret < 0)
0341         return ret;
0342 
0343     dev->player_id = ret;
0344     return 0;
0345 }
0346 
0347 static void ps_device_release_player_id(struct ps_device *dev)
0348 {
0349     ida_free(&ps_player_id_allocator, dev->player_id);
0350 
0351     dev->player_id = U32_MAX;
0352 }
0353 
0354 static struct input_dev *ps_allocate_input_dev(struct hid_device *hdev, const char *name_suffix)
0355 {
0356     struct input_dev *input_dev;
0357 
0358     input_dev = devm_input_allocate_device(&hdev->dev);
0359     if (!input_dev)
0360         return ERR_PTR(-ENOMEM);
0361 
0362     input_dev->id.bustype = hdev->bus;
0363     input_dev->id.vendor = hdev->vendor;
0364     input_dev->id.product = hdev->product;
0365     input_dev->id.version = hdev->version;
0366     input_dev->uniq = hdev->uniq;
0367 
0368     if (name_suffix) {
0369         input_dev->name = devm_kasprintf(&hdev->dev, GFP_KERNEL, "%s %s", hdev->name,
0370                 name_suffix);
0371         if (!input_dev->name)
0372             return ERR_PTR(-ENOMEM);
0373     } else {
0374         input_dev->name = hdev->name;
0375     }
0376 
0377     input_set_drvdata(input_dev, hdev);
0378 
0379     return input_dev;
0380 }
0381 
0382 static enum power_supply_property ps_power_supply_props[] = {
0383     POWER_SUPPLY_PROP_STATUS,
0384     POWER_SUPPLY_PROP_PRESENT,
0385     POWER_SUPPLY_PROP_CAPACITY,
0386     POWER_SUPPLY_PROP_SCOPE,
0387 };
0388 
0389 static int ps_battery_get_property(struct power_supply *psy,
0390         enum power_supply_property psp,
0391         union power_supply_propval *val)
0392 {
0393     struct ps_device *dev = power_supply_get_drvdata(psy);
0394     uint8_t battery_capacity;
0395     int battery_status;
0396     unsigned long flags;
0397     int ret = 0;
0398 
0399     spin_lock_irqsave(&dev->lock, flags);
0400     battery_capacity = dev->battery_capacity;
0401     battery_status = dev->battery_status;
0402     spin_unlock_irqrestore(&dev->lock, flags);
0403 
0404     switch (psp) {
0405     case POWER_SUPPLY_PROP_STATUS:
0406         val->intval = battery_status;
0407         break;
0408     case POWER_SUPPLY_PROP_PRESENT:
0409         val->intval = 1;
0410         break;
0411     case POWER_SUPPLY_PROP_CAPACITY:
0412         val->intval = battery_capacity;
0413         break;
0414     case POWER_SUPPLY_PROP_SCOPE:
0415         val->intval = POWER_SUPPLY_SCOPE_DEVICE;
0416         break;
0417     default:
0418         ret = -EINVAL;
0419         break;
0420     }
0421 
0422     return ret;
0423 }
0424 
0425 static int ps_device_register_battery(struct ps_device *dev)
0426 {
0427     struct power_supply *battery;
0428     struct power_supply_config battery_cfg = { .drv_data = dev };
0429     int ret;
0430 
0431     dev->battery_desc.type = POWER_SUPPLY_TYPE_BATTERY;
0432     dev->battery_desc.properties = ps_power_supply_props;
0433     dev->battery_desc.num_properties = ARRAY_SIZE(ps_power_supply_props);
0434     dev->battery_desc.get_property = ps_battery_get_property;
0435     dev->battery_desc.name = devm_kasprintf(&dev->hdev->dev, GFP_KERNEL,
0436             "ps-controller-battery-%pMR", dev->mac_address);
0437     if (!dev->battery_desc.name)
0438         return -ENOMEM;
0439 
0440     battery = devm_power_supply_register(&dev->hdev->dev, &dev->battery_desc, &battery_cfg);
0441     if (IS_ERR(battery)) {
0442         ret = PTR_ERR(battery);
0443         hid_err(dev->hdev, "Unable to register battery device: %d\n", ret);
0444         return ret;
0445     }
0446     dev->battery = battery;
0447 
0448     ret = power_supply_powers(dev->battery, &dev->hdev->dev);
0449     if (ret) {
0450         hid_err(dev->hdev, "Unable to activate battery device: %d\n", ret);
0451         return ret;
0452     }
0453 
0454     return 0;
0455 }
0456 
0457 /* Compute crc32 of HID data and compare against expected CRC. */
0458 static bool ps_check_crc32(uint8_t seed, uint8_t *data, size_t len, uint32_t report_crc)
0459 {
0460     uint32_t crc;
0461 
0462     crc = crc32_le(0xFFFFFFFF, &seed, 1);
0463     crc = ~crc32_le(crc, data, len);
0464 
0465     return crc == report_crc;
0466 }
0467 
0468 static struct input_dev *ps_gamepad_create(struct hid_device *hdev,
0469         int (*play_effect)(struct input_dev *, void *, struct ff_effect *))
0470 {
0471     struct input_dev *gamepad;
0472     unsigned int i;
0473     int ret;
0474 
0475     gamepad = ps_allocate_input_dev(hdev, NULL);
0476     if (IS_ERR(gamepad))
0477         return ERR_CAST(gamepad);
0478 
0479     input_set_abs_params(gamepad, ABS_X, 0, 255, 0, 0);
0480     input_set_abs_params(gamepad, ABS_Y, 0, 255, 0, 0);
0481     input_set_abs_params(gamepad, ABS_Z, 0, 255, 0, 0);
0482     input_set_abs_params(gamepad, ABS_RX, 0, 255, 0, 0);
0483     input_set_abs_params(gamepad, ABS_RY, 0, 255, 0, 0);
0484     input_set_abs_params(gamepad, ABS_RZ, 0, 255, 0, 0);
0485 
0486     input_set_abs_params(gamepad, ABS_HAT0X, -1, 1, 0, 0);
0487     input_set_abs_params(gamepad, ABS_HAT0Y, -1, 1, 0, 0);
0488 
0489     for (i = 0; i < ARRAY_SIZE(ps_gamepad_buttons); i++)
0490         input_set_capability(gamepad, EV_KEY, ps_gamepad_buttons[i]);
0491 
0492 #if IS_ENABLED(CONFIG_PLAYSTATION_FF)
0493     if (play_effect) {
0494         input_set_capability(gamepad, EV_FF, FF_RUMBLE);
0495         input_ff_create_memless(gamepad, NULL, play_effect);
0496     }
0497 #endif
0498 
0499     ret = input_register_device(gamepad);
0500     if (ret)
0501         return ERR_PTR(ret);
0502 
0503     return gamepad;
0504 }
0505 
0506 static int ps_get_report(struct hid_device *hdev, uint8_t report_id, uint8_t *buf, size_t size)
0507 {
0508     int ret;
0509 
0510     ret = hid_hw_raw_request(hdev, report_id, buf, size, HID_FEATURE_REPORT,
0511                  HID_REQ_GET_REPORT);
0512     if (ret < 0) {
0513         hid_err(hdev, "Failed to retrieve feature with reportID %d: %d\n", report_id, ret);
0514         return ret;
0515     }
0516 
0517     if (ret != size) {
0518         hid_err(hdev, "Invalid byte count transferred, expected %zu got %d\n", size, ret);
0519         return -EINVAL;
0520     }
0521 
0522     if (buf[0] != report_id) {
0523         hid_err(hdev, "Invalid reportID received, expected %d got %d\n", report_id, buf[0]);
0524         return -EINVAL;
0525     }
0526 
0527     if (hdev->bus == BUS_BLUETOOTH) {
0528         /* Last 4 bytes contains crc32. */
0529         uint8_t crc_offset = size - 4;
0530         uint32_t report_crc = get_unaligned_le32(&buf[crc_offset]);
0531 
0532         if (!ps_check_crc32(PS_FEATURE_CRC32_SEED, buf, crc_offset, report_crc)) {
0533             hid_err(hdev, "CRC check failed for reportID=%d\n", report_id);
0534             return -EILSEQ;
0535         }
0536     }
0537 
0538     return 0;
0539 }
0540 
0541 static int ps_led_register(struct ps_device *ps_dev, struct led_classdev *led,
0542         const struct ps_led_info *led_info)
0543 {
0544     int ret;
0545 
0546     led->name = devm_kasprintf(&ps_dev->hdev->dev, GFP_KERNEL,
0547             "%s:%s:%s", ps_dev->input_dev_name, led_info->color, led_info->name);
0548 
0549     if (!led->name)
0550         return -ENOMEM;
0551 
0552     led->brightness = 0;
0553     led->max_brightness = 1;
0554     led->flags = LED_CORE_SUSPENDRESUME;
0555     led->brightness_get = led_info->brightness_get;
0556     led->brightness_set_blocking = led_info->brightness_set;
0557 
0558     ret = devm_led_classdev_register(&ps_dev->hdev->dev, led);
0559     if (ret) {
0560         hid_err(ps_dev->hdev, "Failed to register LED %s: %d\n", led_info->name, ret);
0561         return ret;
0562     }
0563 
0564     return 0;
0565 }
0566 
0567 /* Register a DualSense/DualShock4 RGB lightbar represented by a multicolor LED. */
0568 static int ps_lightbar_register(struct ps_device *ps_dev, struct led_classdev_mc *lightbar_mc_dev,
0569     int (*brightness_set)(struct led_classdev *, enum led_brightness))
0570 {
0571     struct hid_device *hdev = ps_dev->hdev;
0572     struct mc_subled *mc_led_info;
0573     struct led_classdev *led_cdev;
0574     int ret;
0575 
0576     mc_led_info = devm_kmalloc_array(&hdev->dev, 3, sizeof(*mc_led_info),
0577                      GFP_KERNEL | __GFP_ZERO);
0578     if (!mc_led_info)
0579         return -ENOMEM;
0580 
0581     mc_led_info[0].color_index = LED_COLOR_ID_RED;
0582     mc_led_info[1].color_index = LED_COLOR_ID_GREEN;
0583     mc_led_info[2].color_index = LED_COLOR_ID_BLUE;
0584 
0585     lightbar_mc_dev->subled_info = mc_led_info;
0586     lightbar_mc_dev->num_colors = 3;
0587 
0588     led_cdev = &lightbar_mc_dev->led_cdev;
0589     led_cdev->name = devm_kasprintf(&hdev->dev, GFP_KERNEL, "%s:rgb:indicator",
0590             ps_dev->input_dev_name);
0591     if (!led_cdev->name)
0592         return -ENOMEM;
0593     led_cdev->brightness = 255;
0594     led_cdev->max_brightness = 255;
0595     led_cdev->brightness_set_blocking = brightness_set;
0596 
0597     ret = devm_led_classdev_multicolor_register(&hdev->dev, lightbar_mc_dev);
0598     if (ret < 0) {
0599         hid_err(hdev, "Cannot register multicolor LED device\n");
0600         return ret;
0601     }
0602 
0603     return 0;
0604 }
0605 
0606 static struct input_dev *ps_sensors_create(struct hid_device *hdev, int accel_range, int accel_res,
0607         int gyro_range, int gyro_res)
0608 {
0609     struct input_dev *sensors;
0610     int ret;
0611 
0612     sensors = ps_allocate_input_dev(hdev, "Motion Sensors");
0613     if (IS_ERR(sensors))
0614         return ERR_CAST(sensors);
0615 
0616     __set_bit(INPUT_PROP_ACCELEROMETER, sensors->propbit);
0617     __set_bit(EV_MSC, sensors->evbit);
0618     __set_bit(MSC_TIMESTAMP, sensors->mscbit);
0619 
0620     /* Accelerometer */
0621     input_set_abs_params(sensors, ABS_X, -accel_range, accel_range, 16, 0);
0622     input_set_abs_params(sensors, ABS_Y, -accel_range, accel_range, 16, 0);
0623     input_set_abs_params(sensors, ABS_Z, -accel_range, accel_range, 16, 0);
0624     input_abs_set_res(sensors, ABS_X, accel_res);
0625     input_abs_set_res(sensors, ABS_Y, accel_res);
0626     input_abs_set_res(sensors, ABS_Z, accel_res);
0627 
0628     /* Gyroscope */
0629     input_set_abs_params(sensors, ABS_RX, -gyro_range, gyro_range, 16, 0);
0630     input_set_abs_params(sensors, ABS_RY, -gyro_range, gyro_range, 16, 0);
0631     input_set_abs_params(sensors, ABS_RZ, -gyro_range, gyro_range, 16, 0);
0632     input_abs_set_res(sensors, ABS_RX, gyro_res);
0633     input_abs_set_res(sensors, ABS_RY, gyro_res);
0634     input_abs_set_res(sensors, ABS_RZ, gyro_res);
0635 
0636     ret = input_register_device(sensors);
0637     if (ret)
0638         return ERR_PTR(ret);
0639 
0640     return sensors;
0641 }
0642 
0643 static struct input_dev *ps_touchpad_create(struct hid_device *hdev, int width, int height,
0644         unsigned int num_contacts)
0645 {
0646     struct input_dev *touchpad;
0647     int ret;
0648 
0649     touchpad = ps_allocate_input_dev(hdev, "Touchpad");
0650     if (IS_ERR(touchpad))
0651         return ERR_CAST(touchpad);
0652 
0653     /* Map button underneath touchpad to BTN_LEFT. */
0654     input_set_capability(touchpad, EV_KEY, BTN_LEFT);
0655     __set_bit(INPUT_PROP_BUTTONPAD, touchpad->propbit);
0656 
0657     input_set_abs_params(touchpad, ABS_MT_POSITION_X, 0, width - 1, 0, 0);
0658     input_set_abs_params(touchpad, ABS_MT_POSITION_Y, 0, height - 1, 0, 0);
0659 
0660     ret = input_mt_init_slots(touchpad, num_contacts, INPUT_MT_POINTER);
0661     if (ret)
0662         return ERR_PTR(ret);
0663 
0664     ret = input_register_device(touchpad);
0665     if (ret)
0666         return ERR_PTR(ret);
0667 
0668     return touchpad;
0669 }
0670 
0671 static ssize_t firmware_version_show(struct device *dev,
0672                 struct device_attribute
0673                 *attr, char *buf)
0674 {
0675     struct hid_device *hdev = to_hid_device(dev);
0676     struct ps_device *ps_dev = hid_get_drvdata(hdev);
0677 
0678     return sysfs_emit(buf, "0x%08x\n", ps_dev->fw_version);
0679 }
0680 
0681 static DEVICE_ATTR_RO(firmware_version);
0682 
0683 static ssize_t hardware_version_show(struct device *dev,
0684                 struct device_attribute
0685                 *attr, char *buf)
0686 {
0687     struct hid_device *hdev = to_hid_device(dev);
0688     struct ps_device *ps_dev = hid_get_drvdata(hdev);
0689 
0690     return sysfs_emit(buf, "0x%08x\n", ps_dev->hw_version);
0691 }
0692 
0693 static DEVICE_ATTR_RO(hardware_version);
0694 
0695 static struct attribute *ps_device_attributes[] = {
0696     &dev_attr_firmware_version.attr,
0697     &dev_attr_hardware_version.attr,
0698     NULL
0699 };
0700 
0701 static const struct attribute_group ps_device_attribute_group = {
0702     .attrs = ps_device_attributes,
0703 };
0704 
0705 static int dualsense_get_calibration_data(struct dualsense *ds)
0706 {
0707     short gyro_pitch_bias, gyro_pitch_plus, gyro_pitch_minus;
0708     short gyro_yaw_bias, gyro_yaw_plus, gyro_yaw_minus;
0709     short gyro_roll_bias, gyro_roll_plus, gyro_roll_minus;
0710     short gyro_speed_plus, gyro_speed_minus;
0711     short acc_x_plus, acc_x_minus;
0712     short acc_y_plus, acc_y_minus;
0713     short acc_z_plus, acc_z_minus;
0714     int speed_2x;
0715     int range_2g;
0716     int ret = 0;
0717     uint8_t *buf;
0718 
0719     buf = kzalloc(DS_FEATURE_REPORT_CALIBRATION_SIZE, GFP_KERNEL);
0720     if (!buf)
0721         return -ENOMEM;
0722 
0723     ret = ps_get_report(ds->base.hdev, DS_FEATURE_REPORT_CALIBRATION, buf,
0724             DS_FEATURE_REPORT_CALIBRATION_SIZE);
0725     if (ret) {
0726         hid_err(ds->base.hdev, "Failed to retrieve DualSense calibration info: %d\n", ret);
0727         goto err_free;
0728     }
0729 
0730     gyro_pitch_bias  = get_unaligned_le16(&buf[1]);
0731     gyro_yaw_bias    = get_unaligned_le16(&buf[3]);
0732     gyro_roll_bias   = get_unaligned_le16(&buf[5]);
0733     gyro_pitch_plus  = get_unaligned_le16(&buf[7]);
0734     gyro_pitch_minus = get_unaligned_le16(&buf[9]);
0735     gyro_yaw_plus    = get_unaligned_le16(&buf[11]);
0736     gyro_yaw_minus   = get_unaligned_le16(&buf[13]);
0737     gyro_roll_plus   = get_unaligned_le16(&buf[15]);
0738     gyro_roll_minus  = get_unaligned_le16(&buf[17]);
0739     gyro_speed_plus  = get_unaligned_le16(&buf[19]);
0740     gyro_speed_minus = get_unaligned_le16(&buf[21]);
0741     acc_x_plus       = get_unaligned_le16(&buf[23]);
0742     acc_x_minus      = get_unaligned_le16(&buf[25]);
0743     acc_y_plus       = get_unaligned_le16(&buf[27]);
0744     acc_y_minus      = get_unaligned_le16(&buf[29]);
0745     acc_z_plus       = get_unaligned_le16(&buf[31]);
0746     acc_z_minus      = get_unaligned_le16(&buf[33]);
0747 
0748     /*
0749      * Set gyroscope calibration and normalization parameters.
0750      * Data values will be normalized to 1/DS_GYRO_RES_PER_DEG_S degree/s.
0751      */
0752     speed_2x = (gyro_speed_plus + gyro_speed_minus);
0753     ds->gyro_calib_data[0].abs_code = ABS_RX;
0754     ds->gyro_calib_data[0].bias = gyro_pitch_bias;
0755     ds->gyro_calib_data[0].sens_numer = speed_2x*DS_GYRO_RES_PER_DEG_S;
0756     ds->gyro_calib_data[0].sens_denom = gyro_pitch_plus - gyro_pitch_minus;
0757 
0758     ds->gyro_calib_data[1].abs_code = ABS_RY;
0759     ds->gyro_calib_data[1].bias = gyro_yaw_bias;
0760     ds->gyro_calib_data[1].sens_numer = speed_2x*DS_GYRO_RES_PER_DEG_S;
0761     ds->gyro_calib_data[1].sens_denom = gyro_yaw_plus - gyro_yaw_minus;
0762 
0763     ds->gyro_calib_data[2].abs_code = ABS_RZ;
0764     ds->gyro_calib_data[2].bias = gyro_roll_bias;
0765     ds->gyro_calib_data[2].sens_numer = speed_2x*DS_GYRO_RES_PER_DEG_S;
0766     ds->gyro_calib_data[2].sens_denom = gyro_roll_plus - gyro_roll_minus;
0767 
0768     /*
0769      * Set accelerometer calibration and normalization parameters.
0770      * Data values will be normalized to 1/DS_ACC_RES_PER_G g.
0771      */
0772     range_2g = acc_x_plus - acc_x_minus;
0773     ds->accel_calib_data[0].abs_code = ABS_X;
0774     ds->accel_calib_data[0].bias = acc_x_plus - range_2g / 2;
0775     ds->accel_calib_data[0].sens_numer = 2*DS_ACC_RES_PER_G;
0776     ds->accel_calib_data[0].sens_denom = range_2g;
0777 
0778     range_2g = acc_y_plus - acc_y_minus;
0779     ds->accel_calib_data[1].abs_code = ABS_Y;
0780     ds->accel_calib_data[1].bias = acc_y_plus - range_2g / 2;
0781     ds->accel_calib_data[1].sens_numer = 2*DS_ACC_RES_PER_G;
0782     ds->accel_calib_data[1].sens_denom = range_2g;
0783 
0784     range_2g = acc_z_plus - acc_z_minus;
0785     ds->accel_calib_data[2].abs_code = ABS_Z;
0786     ds->accel_calib_data[2].bias = acc_z_plus - range_2g / 2;
0787     ds->accel_calib_data[2].sens_numer = 2*DS_ACC_RES_PER_G;
0788     ds->accel_calib_data[2].sens_denom = range_2g;
0789 
0790 err_free:
0791     kfree(buf);
0792     return ret;
0793 }
0794 
0795 static int dualsense_get_firmware_info(struct dualsense *ds)
0796 {
0797     uint8_t *buf;
0798     int ret;
0799 
0800     buf = kzalloc(DS_FEATURE_REPORT_FIRMWARE_INFO_SIZE, GFP_KERNEL);
0801     if (!buf)
0802         return -ENOMEM;
0803 
0804     ret = ps_get_report(ds->base.hdev, DS_FEATURE_REPORT_FIRMWARE_INFO, buf,
0805             DS_FEATURE_REPORT_FIRMWARE_INFO_SIZE);
0806     if (ret) {
0807         hid_err(ds->base.hdev, "Failed to retrieve DualSense firmware info: %d\n", ret);
0808         goto err_free;
0809     }
0810 
0811     ds->base.hw_version = get_unaligned_le32(&buf[24]);
0812     ds->base.fw_version = get_unaligned_le32(&buf[28]);
0813 
0814 err_free:
0815     kfree(buf);
0816     return ret;
0817 }
0818 
0819 static int dualsense_get_mac_address(struct dualsense *ds)
0820 {
0821     uint8_t *buf;
0822     int ret = 0;
0823 
0824     buf = kzalloc(DS_FEATURE_REPORT_PAIRING_INFO_SIZE, GFP_KERNEL);
0825     if (!buf)
0826         return -ENOMEM;
0827 
0828     ret = ps_get_report(ds->base.hdev, DS_FEATURE_REPORT_PAIRING_INFO, buf,
0829             DS_FEATURE_REPORT_PAIRING_INFO_SIZE);
0830     if (ret) {
0831         hid_err(ds->base.hdev, "Failed to retrieve DualSense pairing info: %d\n", ret);
0832         goto err_free;
0833     }
0834 
0835     memcpy(ds->base.mac_address, &buf[1], sizeof(ds->base.mac_address));
0836 
0837 err_free:
0838     kfree(buf);
0839     return ret;
0840 }
0841 
0842 static int dualsense_lightbar_set_brightness(struct led_classdev *cdev,
0843     enum led_brightness brightness)
0844 {
0845     struct led_classdev_mc *mc_cdev = lcdev_to_mccdev(cdev);
0846     struct dualsense *ds = container_of(mc_cdev, struct dualsense, lightbar);
0847     uint8_t red, green, blue;
0848 
0849     led_mc_calc_color_components(mc_cdev, brightness);
0850     red = mc_cdev->subled_info[0].brightness;
0851     green = mc_cdev->subled_info[1].brightness;
0852     blue = mc_cdev->subled_info[2].brightness;
0853 
0854     dualsense_set_lightbar(ds, red, green, blue);
0855     return 0;
0856 }
0857 
0858 static enum led_brightness dualsense_player_led_get_brightness(struct led_classdev *led)
0859 {
0860     struct hid_device *hdev = to_hid_device(led->dev->parent);
0861     struct dualsense *ds = hid_get_drvdata(hdev);
0862 
0863     return !!(ds->player_leds_state & BIT(led - ds->player_leds));
0864 }
0865 
0866 static int dualsense_player_led_set_brightness(struct led_classdev *led, enum led_brightness value)
0867 {
0868     struct hid_device *hdev = to_hid_device(led->dev->parent);
0869     struct dualsense *ds = hid_get_drvdata(hdev);
0870     unsigned long flags;
0871     unsigned int led_index;
0872 
0873     spin_lock_irqsave(&ds->base.lock, flags);
0874 
0875     led_index = led - ds->player_leds;
0876     if (value == LED_OFF)
0877         ds->player_leds_state &= ~BIT(led_index);
0878     else
0879         ds->player_leds_state |= BIT(led_index);
0880 
0881     ds->update_player_leds = true;
0882     spin_unlock_irqrestore(&ds->base.lock, flags);
0883 
0884     schedule_work(&ds->output_worker);
0885 
0886     return 0;
0887 }
0888 
0889 static void dualsense_init_output_report(struct dualsense *ds, struct dualsense_output_report *rp,
0890         void *buf)
0891 {
0892     struct hid_device *hdev = ds->base.hdev;
0893 
0894     if (hdev->bus == BUS_BLUETOOTH) {
0895         struct dualsense_output_report_bt *bt = buf;
0896 
0897         memset(bt, 0, sizeof(*bt));
0898         bt->report_id = DS_OUTPUT_REPORT_BT;
0899         bt->tag = DS_OUTPUT_TAG; /* Tag must be set. Exact meaning is unclear. */
0900 
0901         /*
0902          * Highest 4-bit is a sequence number, which needs to be increased
0903          * every report. Lowest 4-bit is tag and can be zero for now.
0904          */
0905         bt->seq_tag = (ds->output_seq << 4) | 0x0;
0906         if (++ds->output_seq == 16)
0907             ds->output_seq = 0;
0908 
0909         rp->data = buf;
0910         rp->len = sizeof(*bt);
0911         rp->bt = bt;
0912         rp->usb = NULL;
0913         rp->common = &bt->common;
0914     } else { /* USB */
0915         struct dualsense_output_report_usb *usb = buf;
0916 
0917         memset(usb, 0, sizeof(*usb));
0918         usb->report_id = DS_OUTPUT_REPORT_USB;
0919 
0920         rp->data = buf;
0921         rp->len = sizeof(*usb);
0922         rp->bt = NULL;
0923         rp->usb = usb;
0924         rp->common = &usb->common;
0925     }
0926 }
0927 
0928 /*
0929  * Helper function to send DualSense output reports. Applies a CRC at the end of a report
0930  * for Bluetooth reports.
0931  */
0932 static void dualsense_send_output_report(struct dualsense *ds,
0933         struct dualsense_output_report *report)
0934 {
0935     struct hid_device *hdev = ds->base.hdev;
0936 
0937     /* Bluetooth packets need to be signed with a CRC in the last 4 bytes. */
0938     if (report->bt) {
0939         uint32_t crc;
0940         uint8_t seed = PS_OUTPUT_CRC32_SEED;
0941 
0942         crc = crc32_le(0xFFFFFFFF, &seed, 1);
0943         crc = ~crc32_le(crc, report->data, report->len - 4);
0944 
0945         report->bt->crc32 = cpu_to_le32(crc);
0946     }
0947 
0948     hid_hw_output_report(hdev, report->data, report->len);
0949 }
0950 
0951 static void dualsense_output_worker(struct work_struct *work)
0952 {
0953     struct dualsense *ds = container_of(work, struct dualsense, output_worker);
0954     struct dualsense_output_report report;
0955     struct dualsense_output_report_common *common;
0956     unsigned long flags;
0957 
0958     dualsense_init_output_report(ds, &report, ds->output_report_dmabuf);
0959     common = report.common;
0960 
0961     spin_lock_irqsave(&ds->base.lock, flags);
0962 
0963     if (ds->update_rumble) {
0964         /* Select classic rumble style haptics and enable it. */
0965         common->valid_flag0 |= DS_OUTPUT_VALID_FLAG0_HAPTICS_SELECT;
0966         common->valid_flag0 |= DS_OUTPUT_VALID_FLAG0_COMPATIBLE_VIBRATION;
0967         common->motor_left = ds->motor_left;
0968         common->motor_right = ds->motor_right;
0969         ds->update_rumble = false;
0970     }
0971 
0972     if (ds->update_lightbar) {
0973         common->valid_flag1 |= DS_OUTPUT_VALID_FLAG1_LIGHTBAR_CONTROL_ENABLE;
0974         common->lightbar_red = ds->lightbar_red;
0975         common->lightbar_green = ds->lightbar_green;
0976         common->lightbar_blue = ds->lightbar_blue;
0977 
0978         ds->update_lightbar = false;
0979     }
0980 
0981     if (ds->update_player_leds) {
0982         common->valid_flag1 |= DS_OUTPUT_VALID_FLAG1_PLAYER_INDICATOR_CONTROL_ENABLE;
0983         common->player_leds = ds->player_leds_state;
0984 
0985         ds->update_player_leds = false;
0986     }
0987 
0988     if (ds->update_mic_mute) {
0989         common->valid_flag1 |= DS_OUTPUT_VALID_FLAG1_MIC_MUTE_LED_CONTROL_ENABLE;
0990         common->mute_button_led = ds->mic_muted;
0991 
0992         if (ds->mic_muted) {
0993             /* Disable microphone */
0994             common->valid_flag1 |= DS_OUTPUT_VALID_FLAG1_POWER_SAVE_CONTROL_ENABLE;
0995             common->power_save_control |= DS_OUTPUT_POWER_SAVE_CONTROL_MIC_MUTE;
0996         } else {
0997             /* Enable microphone */
0998             common->valid_flag1 |= DS_OUTPUT_VALID_FLAG1_POWER_SAVE_CONTROL_ENABLE;
0999             common->power_save_control &= ~DS_OUTPUT_POWER_SAVE_CONTROL_MIC_MUTE;
1000         }
1001 
1002         ds->update_mic_mute = false;
1003     }
1004 
1005     spin_unlock_irqrestore(&ds->base.lock, flags);
1006 
1007     dualsense_send_output_report(ds, &report);
1008 }
1009 
1010 static int dualsense_parse_report(struct ps_device *ps_dev, struct hid_report *report,
1011         u8 *data, int size)
1012 {
1013     struct hid_device *hdev = ps_dev->hdev;
1014     struct dualsense *ds = container_of(ps_dev, struct dualsense, base);
1015     struct dualsense_input_report *ds_report;
1016     uint8_t battery_data, battery_capacity, charging_status, value;
1017     int battery_status;
1018     uint32_t sensor_timestamp;
1019     bool btn_mic_state;
1020     unsigned long flags;
1021     int i;
1022 
1023     /*
1024      * DualSense in USB uses the full HID report for reportID 1, but
1025      * Bluetooth uses a minimal HID report for reportID 1 and reports
1026      * the full report using reportID 49.
1027      */
1028     if (hdev->bus == BUS_USB && report->id == DS_INPUT_REPORT_USB &&
1029             size == DS_INPUT_REPORT_USB_SIZE) {
1030         ds_report = (struct dualsense_input_report *)&data[1];
1031     } else if (hdev->bus == BUS_BLUETOOTH && report->id == DS_INPUT_REPORT_BT &&
1032             size == DS_INPUT_REPORT_BT_SIZE) {
1033         /* Last 4 bytes of input report contain crc32 */
1034         uint32_t report_crc = get_unaligned_le32(&data[size - 4]);
1035 
1036         if (!ps_check_crc32(PS_INPUT_CRC32_SEED, data, size - 4, report_crc)) {
1037             hid_err(hdev, "DualSense input CRC's check failed\n");
1038             return -EILSEQ;
1039         }
1040 
1041         ds_report = (struct dualsense_input_report *)&data[2];
1042     } else {
1043         hid_err(hdev, "Unhandled reportID=%d\n", report->id);
1044         return -1;
1045     }
1046 
1047     input_report_abs(ds->gamepad, ABS_X,  ds_report->x);
1048     input_report_abs(ds->gamepad, ABS_Y,  ds_report->y);
1049     input_report_abs(ds->gamepad, ABS_RX, ds_report->rx);
1050     input_report_abs(ds->gamepad, ABS_RY, ds_report->ry);
1051     input_report_abs(ds->gamepad, ABS_Z,  ds_report->z);
1052     input_report_abs(ds->gamepad, ABS_RZ, ds_report->rz);
1053 
1054     value = ds_report->buttons[0] & DS_BUTTONS0_HAT_SWITCH;
1055     if (value >= ARRAY_SIZE(ps_gamepad_hat_mapping))
1056         value = 8; /* center */
1057     input_report_abs(ds->gamepad, ABS_HAT0X, ps_gamepad_hat_mapping[value].x);
1058     input_report_abs(ds->gamepad, ABS_HAT0Y, ps_gamepad_hat_mapping[value].y);
1059 
1060     input_report_key(ds->gamepad, BTN_WEST,   ds_report->buttons[0] & DS_BUTTONS0_SQUARE);
1061     input_report_key(ds->gamepad, BTN_SOUTH,  ds_report->buttons[0] & DS_BUTTONS0_CROSS);
1062     input_report_key(ds->gamepad, BTN_EAST,   ds_report->buttons[0] & DS_BUTTONS0_CIRCLE);
1063     input_report_key(ds->gamepad, BTN_NORTH,  ds_report->buttons[0] & DS_BUTTONS0_TRIANGLE);
1064     input_report_key(ds->gamepad, BTN_TL,     ds_report->buttons[1] & DS_BUTTONS1_L1);
1065     input_report_key(ds->gamepad, BTN_TR,     ds_report->buttons[1] & DS_BUTTONS1_R1);
1066     input_report_key(ds->gamepad, BTN_TL2,    ds_report->buttons[1] & DS_BUTTONS1_L2);
1067     input_report_key(ds->gamepad, BTN_TR2,    ds_report->buttons[1] & DS_BUTTONS1_R2);
1068     input_report_key(ds->gamepad, BTN_SELECT, ds_report->buttons[1] & DS_BUTTONS1_CREATE);
1069     input_report_key(ds->gamepad, BTN_START,  ds_report->buttons[1] & DS_BUTTONS1_OPTIONS);
1070     input_report_key(ds->gamepad, BTN_THUMBL, ds_report->buttons[1] & DS_BUTTONS1_L3);
1071     input_report_key(ds->gamepad, BTN_THUMBR, ds_report->buttons[1] & DS_BUTTONS1_R3);
1072     input_report_key(ds->gamepad, BTN_MODE,   ds_report->buttons[2] & DS_BUTTONS2_PS_HOME);
1073     input_sync(ds->gamepad);
1074 
1075     /*
1076      * The DualSense has an internal microphone, which can be muted through a mute button
1077      * on the device. The driver is expected to read the button state and program the device
1078      * to mute/unmute audio at the hardware level.
1079      */
1080     btn_mic_state = !!(ds_report->buttons[2] & DS_BUTTONS2_MIC_MUTE);
1081     if (btn_mic_state && !ds->last_btn_mic_state) {
1082         spin_lock_irqsave(&ps_dev->lock, flags);
1083         ds->update_mic_mute = true;
1084         ds->mic_muted = !ds->mic_muted; /* toggle */
1085         spin_unlock_irqrestore(&ps_dev->lock, flags);
1086 
1087         /* Schedule updating of microphone state at hardware level. */
1088         schedule_work(&ds->output_worker);
1089     }
1090     ds->last_btn_mic_state = btn_mic_state;
1091 
1092     /* Parse and calibrate gyroscope data. */
1093     for (i = 0; i < ARRAY_SIZE(ds_report->gyro); i++) {
1094         int raw_data = (short)le16_to_cpu(ds_report->gyro[i]);
1095         int calib_data = mult_frac(ds->gyro_calib_data[i].sens_numer,
1096                        raw_data - ds->gyro_calib_data[i].bias,
1097                        ds->gyro_calib_data[i].sens_denom);
1098 
1099         input_report_abs(ds->sensors, ds->gyro_calib_data[i].abs_code, calib_data);
1100     }
1101 
1102     /* Parse and calibrate accelerometer data. */
1103     for (i = 0; i < ARRAY_SIZE(ds_report->accel); i++) {
1104         int raw_data = (short)le16_to_cpu(ds_report->accel[i]);
1105         int calib_data = mult_frac(ds->accel_calib_data[i].sens_numer,
1106                        raw_data - ds->accel_calib_data[i].bias,
1107                        ds->accel_calib_data[i].sens_denom);
1108 
1109         input_report_abs(ds->sensors, ds->accel_calib_data[i].abs_code, calib_data);
1110     }
1111 
1112     /* Convert timestamp (in 0.33us unit) to timestamp_us */
1113     sensor_timestamp = le32_to_cpu(ds_report->sensor_timestamp);
1114     if (!ds->sensor_timestamp_initialized) {
1115         ds->sensor_timestamp_us = DIV_ROUND_CLOSEST(sensor_timestamp, 3);
1116         ds->sensor_timestamp_initialized = true;
1117     } else {
1118         uint32_t delta;
1119 
1120         if (ds->prev_sensor_timestamp > sensor_timestamp)
1121             delta = (U32_MAX - ds->prev_sensor_timestamp + sensor_timestamp + 1);
1122         else
1123             delta = sensor_timestamp - ds->prev_sensor_timestamp;
1124         ds->sensor_timestamp_us += DIV_ROUND_CLOSEST(delta, 3);
1125     }
1126     ds->prev_sensor_timestamp = sensor_timestamp;
1127     input_event(ds->sensors, EV_MSC, MSC_TIMESTAMP, ds->sensor_timestamp_us);
1128     input_sync(ds->sensors);
1129 
1130     for (i = 0; i < ARRAY_SIZE(ds_report->points); i++) {
1131         struct dualsense_touch_point *point = &ds_report->points[i];
1132         bool active = (point->contact & DS_TOUCH_POINT_INACTIVE) ? false : true;
1133 
1134         input_mt_slot(ds->touchpad, i);
1135         input_mt_report_slot_state(ds->touchpad, MT_TOOL_FINGER, active);
1136 
1137         if (active) {
1138             int x = (point->x_hi << 8) | point->x_lo;
1139             int y = (point->y_hi << 4) | point->y_lo;
1140 
1141             input_report_abs(ds->touchpad, ABS_MT_POSITION_X, x);
1142             input_report_abs(ds->touchpad, ABS_MT_POSITION_Y, y);
1143         }
1144     }
1145     input_mt_sync_frame(ds->touchpad);
1146     input_report_key(ds->touchpad, BTN_LEFT, ds_report->buttons[2] & DS_BUTTONS2_TOUCHPAD);
1147     input_sync(ds->touchpad);
1148 
1149     battery_data = ds_report->status & DS_STATUS_BATTERY_CAPACITY;
1150     charging_status = (ds_report->status & DS_STATUS_CHARGING) >> DS_STATUS_CHARGING_SHIFT;
1151 
1152     switch (charging_status) {
1153     case 0x0:
1154         /*
1155          * Each unit of battery data corresponds to 10%
1156          * 0 = 0-9%, 1 = 10-19%, .. and 10 = 100%
1157          */
1158         battery_capacity = min(battery_data * 10 + 5, 100);
1159         battery_status = POWER_SUPPLY_STATUS_DISCHARGING;
1160         break;
1161     case 0x1:
1162         battery_capacity = min(battery_data * 10 + 5, 100);
1163         battery_status = POWER_SUPPLY_STATUS_CHARGING;
1164         break;
1165     case 0x2:
1166         battery_capacity = 100;
1167         battery_status = POWER_SUPPLY_STATUS_FULL;
1168         break;
1169     case 0xa: /* voltage or temperature out of range */
1170     case 0xb: /* temperature error */
1171         battery_capacity = 0;
1172         battery_status = POWER_SUPPLY_STATUS_NOT_CHARGING;
1173         break;
1174     case 0xf: /* charging error */
1175     default:
1176         battery_capacity = 0;
1177         battery_status = POWER_SUPPLY_STATUS_UNKNOWN;
1178     }
1179 
1180     spin_lock_irqsave(&ps_dev->lock, flags);
1181     ps_dev->battery_capacity = battery_capacity;
1182     ps_dev->battery_status = battery_status;
1183     spin_unlock_irqrestore(&ps_dev->lock, flags);
1184 
1185     return 0;
1186 }
1187 
1188 static int dualsense_play_effect(struct input_dev *dev, void *data, struct ff_effect *effect)
1189 {
1190     struct hid_device *hdev = input_get_drvdata(dev);
1191     struct dualsense *ds = hid_get_drvdata(hdev);
1192     unsigned long flags;
1193 
1194     if (effect->type != FF_RUMBLE)
1195         return 0;
1196 
1197     spin_lock_irqsave(&ds->base.lock, flags);
1198     ds->update_rumble = true;
1199     ds->motor_left = effect->u.rumble.strong_magnitude / 256;
1200     ds->motor_right = effect->u.rumble.weak_magnitude / 256;
1201     spin_unlock_irqrestore(&ds->base.lock, flags);
1202 
1203     schedule_work(&ds->output_worker);
1204     return 0;
1205 }
1206 
1207 static int dualsense_reset_leds(struct dualsense *ds)
1208 {
1209     struct dualsense_output_report report;
1210     uint8_t *buf;
1211 
1212     buf = kzalloc(sizeof(struct dualsense_output_report_bt), GFP_KERNEL);
1213     if (!buf)
1214         return -ENOMEM;
1215 
1216     dualsense_init_output_report(ds, &report, buf);
1217     /*
1218      * On Bluetooth the DualSense outputs an animation on the lightbar
1219      * during startup and maintains a color afterwards. We need to explicitly
1220      * reconfigure the lightbar before we can do any programming later on.
1221      * In USB the lightbar is not on by default, but redoing the setup there
1222      * doesn't hurt.
1223      */
1224     report.common->valid_flag2 = DS_OUTPUT_VALID_FLAG2_LIGHTBAR_SETUP_CONTROL_ENABLE;
1225     report.common->lightbar_setup = DS_OUTPUT_LIGHTBAR_SETUP_LIGHT_OUT; /* Fade light out. */
1226     dualsense_send_output_report(ds, &report);
1227 
1228     kfree(buf);
1229     return 0;
1230 }
1231 
1232 static void dualsense_set_lightbar(struct dualsense *ds, uint8_t red, uint8_t green, uint8_t blue)
1233 {
1234     unsigned long flags;
1235 
1236     spin_lock_irqsave(&ds->base.lock, flags);
1237     ds->update_lightbar = true;
1238     ds->lightbar_red = red;
1239     ds->lightbar_green = green;
1240     ds->lightbar_blue = blue;
1241     spin_unlock_irqrestore(&ds->base.lock, flags);
1242 
1243     schedule_work(&ds->output_worker);
1244 }
1245 
1246 static void dualsense_set_player_leds(struct dualsense *ds)
1247 {
1248     /*
1249      * The DualSense controller has a row of 5 LEDs used for player ids.
1250      * Behavior on the PlayStation 5 console is to center the player id
1251      * across the LEDs, so e.g. player 1 would be "--x--" with x being 'on'.
1252      * Follow a similar mapping here.
1253      */
1254     static const int player_ids[5] = {
1255         BIT(2),
1256         BIT(3) | BIT(1),
1257         BIT(4) | BIT(2) | BIT(0),
1258         BIT(4) | BIT(3) | BIT(1) | BIT(0),
1259         BIT(4) | BIT(3) | BIT(2) | BIT(1) | BIT(0)
1260     };
1261 
1262     uint8_t player_id = ds->base.player_id % ARRAY_SIZE(player_ids);
1263 
1264     ds->update_player_leds = true;
1265     ds->player_leds_state = player_ids[player_id];
1266     schedule_work(&ds->output_worker);
1267 }
1268 
1269 static struct ps_device *dualsense_create(struct hid_device *hdev)
1270 {
1271     struct dualsense *ds;
1272     struct ps_device *ps_dev;
1273     uint8_t max_output_report_size;
1274     int i, ret;
1275 
1276     static const struct ps_led_info player_leds_info[] = {
1277         { LED_FUNCTION_PLAYER1, "white", dualsense_player_led_get_brightness,
1278                 dualsense_player_led_set_brightness },
1279         { LED_FUNCTION_PLAYER2, "white", dualsense_player_led_get_brightness,
1280                 dualsense_player_led_set_brightness },
1281         { LED_FUNCTION_PLAYER3, "white", dualsense_player_led_get_brightness,
1282                 dualsense_player_led_set_brightness },
1283         { LED_FUNCTION_PLAYER4, "white", dualsense_player_led_get_brightness,
1284                 dualsense_player_led_set_brightness },
1285         { LED_FUNCTION_PLAYER5, "white", dualsense_player_led_get_brightness,
1286                 dualsense_player_led_set_brightness }
1287     };
1288 
1289     ds = devm_kzalloc(&hdev->dev, sizeof(*ds), GFP_KERNEL);
1290     if (!ds)
1291         return ERR_PTR(-ENOMEM);
1292 
1293     /*
1294      * Patch version to allow userspace to distinguish between
1295      * hid-generic vs hid-playstation axis and button mapping.
1296      */
1297     hdev->version |= HID_PLAYSTATION_VERSION_PATCH;
1298 
1299     ps_dev = &ds->base;
1300     ps_dev->hdev = hdev;
1301     spin_lock_init(&ps_dev->lock);
1302     ps_dev->battery_capacity = 100; /* initial value until parse_report. */
1303     ps_dev->battery_status = POWER_SUPPLY_STATUS_UNKNOWN;
1304     ps_dev->parse_report = dualsense_parse_report;
1305     INIT_WORK(&ds->output_worker, dualsense_output_worker);
1306     hid_set_drvdata(hdev, ds);
1307 
1308     max_output_report_size = sizeof(struct dualsense_output_report_bt);
1309     ds->output_report_dmabuf = devm_kzalloc(&hdev->dev, max_output_report_size, GFP_KERNEL);
1310     if (!ds->output_report_dmabuf)
1311         return ERR_PTR(-ENOMEM);
1312 
1313     ret = dualsense_get_mac_address(ds);
1314     if (ret) {
1315         hid_err(hdev, "Failed to get MAC address from DualSense\n");
1316         return ERR_PTR(ret);
1317     }
1318     snprintf(hdev->uniq, sizeof(hdev->uniq), "%pMR", ds->base.mac_address);
1319 
1320     ret = dualsense_get_firmware_info(ds);
1321     if (ret) {
1322         hid_err(hdev, "Failed to get firmware info from DualSense\n");
1323         return ERR_PTR(ret);
1324     }
1325 
1326     ret = ps_devices_list_add(ps_dev);
1327     if (ret)
1328         return ERR_PTR(ret);
1329 
1330     ret = dualsense_get_calibration_data(ds);
1331     if (ret) {
1332         hid_err(hdev, "Failed to get calibration data from DualSense\n");
1333         goto err;
1334     }
1335 
1336     ds->gamepad = ps_gamepad_create(hdev, dualsense_play_effect);
1337     if (IS_ERR(ds->gamepad)) {
1338         ret = PTR_ERR(ds->gamepad);
1339         goto err;
1340     }
1341     /* Use gamepad input device name as primary device name for e.g. LEDs */
1342     ps_dev->input_dev_name = dev_name(&ds->gamepad->dev);
1343 
1344     ds->sensors = ps_sensors_create(hdev, DS_ACC_RANGE, DS_ACC_RES_PER_G,
1345             DS_GYRO_RANGE, DS_GYRO_RES_PER_DEG_S);
1346     if (IS_ERR(ds->sensors)) {
1347         ret = PTR_ERR(ds->sensors);
1348         goto err;
1349     }
1350 
1351     ds->touchpad = ps_touchpad_create(hdev, DS_TOUCHPAD_WIDTH, DS_TOUCHPAD_HEIGHT, 2);
1352     if (IS_ERR(ds->touchpad)) {
1353         ret = PTR_ERR(ds->touchpad);
1354         goto err;
1355     }
1356 
1357     ret = ps_device_register_battery(ps_dev);
1358     if (ret)
1359         goto err;
1360 
1361     /*
1362      * The hardware may have control over the LEDs (e.g. in Bluetooth on startup).
1363      * Reset the LEDs (lightbar, mute, player leds), so we can control them
1364      * from software.
1365      */
1366     ret = dualsense_reset_leds(ds);
1367     if (ret)
1368         goto err;
1369 
1370     ret = ps_lightbar_register(ps_dev, &ds->lightbar, dualsense_lightbar_set_brightness);
1371     if (ret)
1372         goto err;
1373 
1374     /* Set default lightbar color. */
1375     dualsense_set_lightbar(ds, 0, 0, 128); /* blue */
1376 
1377     for (i = 0; i < ARRAY_SIZE(player_leds_info); i++) {
1378         const struct ps_led_info *led_info = &player_leds_info[i];
1379 
1380         ret = ps_led_register(ps_dev, &ds->player_leds[i], led_info);
1381         if (ret < 0)
1382             goto err;
1383     }
1384 
1385     ret = ps_device_set_player_id(ps_dev);
1386     if (ret) {
1387         hid_err(hdev, "Failed to assign player id for DualSense: %d\n", ret);
1388         goto err;
1389     }
1390 
1391     /* Set player LEDs to our player id. */
1392     dualsense_set_player_leds(ds);
1393 
1394     /*
1395      * Reporting hardware and firmware is important as there are frequent updates, which
1396      * can change behavior.
1397      */
1398     hid_info(hdev, "Registered DualSense controller hw_version=0x%08x fw_version=0x%08x\n",
1399             ds->base.hw_version, ds->base.fw_version);
1400 
1401     return &ds->base;
1402 
1403 err:
1404     ps_devices_list_remove(ps_dev);
1405     return ERR_PTR(ret);
1406 }
1407 
1408 static int ps_raw_event(struct hid_device *hdev, struct hid_report *report,
1409         u8 *data, int size)
1410 {
1411     struct ps_device *dev = hid_get_drvdata(hdev);
1412 
1413     if (dev && dev->parse_report)
1414         return dev->parse_report(dev, report, data, size);
1415 
1416     return 0;
1417 }
1418 
1419 static int ps_probe(struct hid_device *hdev, const struct hid_device_id *id)
1420 {
1421     struct ps_device *dev;
1422     int ret;
1423 
1424     ret = hid_parse(hdev);
1425     if (ret) {
1426         hid_err(hdev, "Parse failed\n");
1427         return ret;
1428     }
1429 
1430     ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
1431     if (ret) {
1432         hid_err(hdev, "Failed to start HID device\n");
1433         return ret;
1434     }
1435 
1436     ret = hid_hw_open(hdev);
1437     if (ret) {
1438         hid_err(hdev, "Failed to open HID device\n");
1439         goto err_stop;
1440     }
1441 
1442     if (hdev->product == USB_DEVICE_ID_SONY_PS5_CONTROLLER) {
1443         dev = dualsense_create(hdev);
1444         if (IS_ERR(dev)) {
1445             hid_err(hdev, "Failed to create dualsense.\n");
1446             ret = PTR_ERR(dev);
1447             goto err_close;
1448         }
1449     }
1450 
1451     ret = devm_device_add_group(&hdev->dev, &ps_device_attribute_group);
1452     if (ret) {
1453         hid_err(hdev, "Failed to register sysfs nodes.\n");
1454         goto err_close;
1455     }
1456 
1457     return ret;
1458 
1459 err_close:
1460     hid_hw_close(hdev);
1461 err_stop:
1462     hid_hw_stop(hdev);
1463     return ret;
1464 }
1465 
1466 static void ps_remove(struct hid_device *hdev)
1467 {
1468     struct ps_device *dev = hid_get_drvdata(hdev);
1469 
1470     ps_devices_list_remove(dev);
1471     ps_device_release_player_id(dev);
1472 
1473     hid_hw_close(hdev);
1474     hid_hw_stop(hdev);
1475 }
1476 
1477 static const struct hid_device_id ps_devices[] = {
1478     { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER) },
1479     { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS5_CONTROLLER) },
1480     { }
1481 };
1482 MODULE_DEVICE_TABLE(hid, ps_devices);
1483 
1484 static struct hid_driver ps_driver = {
1485     .name       = "playstation",
1486     .id_table   = ps_devices,
1487     .probe      = ps_probe,
1488     .remove     = ps_remove,
1489     .raw_event  = ps_raw_event,
1490 };
1491 
1492 static int __init ps_init(void)
1493 {
1494     return hid_register_driver(&ps_driver);
1495 }
1496 
1497 static void __exit ps_exit(void)
1498 {
1499     hid_unregister_driver(&ps_driver);
1500     ida_destroy(&ps_player_id_allocator);
1501 }
1502 
1503 module_init(ps_init);
1504 module_exit(ps_exit);
1505 
1506 MODULE_AUTHOR("Sony Interactive Entertainment");
1507 MODULE_DESCRIPTION("HID Driver for PlayStation peripherals.");
1508 MODULE_LICENSE("GPL");