Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0+
0002 /*
0003  * HID driver for Nintendo Switch Joy-Cons and Pro Controllers
0004  *
0005  * Copyright (c) 2019-2021 Daniel J. Ogorchock <djogorchock@gmail.com>
0006  *
0007  * The following resources/projects were referenced for this driver:
0008  *   https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering
0009  *   https://gitlab.com/pjranki/joycon-linux-kernel (Peter Rankin)
0010  *   https://github.com/FrotBot/SwitchProConLinuxUSB
0011  *   https://github.com/MTCKC/ProconXInput
0012  *   https://github.com/Davidobot/BetterJoyForCemu
0013  *   hid-wiimote kernel hid driver
0014  *   hid-logitech-hidpp driver
0015  *   hid-sony driver
0016  *
0017  * This driver supports the Nintendo Switch Joy-Cons and Pro Controllers. The
0018  * Pro Controllers can either be used over USB or Bluetooth.
0019  *
0020  * The driver will retrieve the factory calibration info from the controllers,
0021  * so little to no user calibration should be required.
0022  *
0023  */
0024 
0025 #include "hid-ids.h"
0026 #include <asm/unaligned.h>
0027 #include <linux/delay.h>
0028 #include <linux/device.h>
0029 #include <linux/kernel.h>
0030 #include <linux/hid.h>
0031 #include <linux/input.h>
0032 #include <linux/jiffies.h>
0033 #include <linux/leds.h>
0034 #include <linux/module.h>
0035 #include <linux/power_supply.h>
0036 #include <linux/spinlock.h>
0037 
0038 /*
0039  * Reference the url below for the following HID report defines:
0040  * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering
0041  */
0042 
0043 /* Output Reports */
0044 #define JC_OUTPUT_RUMBLE_AND_SUBCMD  0x01
0045 #define JC_OUTPUT_FW_UPDATE_PKT      0x03
0046 #define JC_OUTPUT_RUMBLE_ONLY        0x10
0047 #define JC_OUTPUT_MCU_DATA       0x11
0048 #define JC_OUTPUT_USB_CMD        0x80
0049 
0050 /* Subcommand IDs */
0051 #define JC_SUBCMD_STATE          0x00
0052 #define JC_SUBCMD_MANUAL_BT_PAIRING  0x01
0053 #define JC_SUBCMD_REQ_DEV_INFO       0x02
0054 #define JC_SUBCMD_SET_REPORT_MODE    0x03
0055 #define JC_SUBCMD_TRIGGERS_ELAPSED   0x04
0056 #define JC_SUBCMD_GET_PAGE_LIST_STATE    0x05
0057 #define JC_SUBCMD_SET_HCI_STATE      0x06
0058 #define JC_SUBCMD_RESET_PAIRING_INFO     0x07
0059 #define JC_SUBCMD_LOW_POWER_MODE     0x08
0060 #define JC_SUBCMD_SPI_FLASH_READ     0x10
0061 #define JC_SUBCMD_SPI_FLASH_WRITE    0x11
0062 #define JC_SUBCMD_RESET_MCU      0x20
0063 #define JC_SUBCMD_SET_MCU_CONFIG     0x21
0064 #define JC_SUBCMD_SET_MCU_STATE      0x22
0065 #define JC_SUBCMD_SET_PLAYER_LIGHTS  0x30
0066 #define JC_SUBCMD_GET_PLAYER_LIGHTS  0x31
0067 #define JC_SUBCMD_SET_HOME_LIGHT     0x38
0068 #define JC_SUBCMD_ENABLE_IMU         0x40
0069 #define JC_SUBCMD_SET_IMU_SENSITIVITY    0x41
0070 #define JC_SUBCMD_WRITE_IMU_REG      0x42
0071 #define JC_SUBCMD_READ_IMU_REG       0x43
0072 #define JC_SUBCMD_ENABLE_VIBRATION   0x48
0073 #define JC_SUBCMD_GET_REGULATED_VOLTAGE  0x50
0074 
0075 /* Input Reports */
0076 #define JC_INPUT_BUTTON_EVENT        0x3F
0077 #define JC_INPUT_SUBCMD_REPLY        0x21
0078 #define JC_INPUT_IMU_DATA        0x30
0079 #define JC_INPUT_MCU_DATA        0x31
0080 #define JC_INPUT_USB_RESPONSE        0x81
0081 
0082 /* Feature Reports */
0083 #define JC_FEATURE_LAST_SUBCMD       0x02
0084 #define JC_FEATURE_OTA_FW_UPGRADE    0x70
0085 #define JC_FEATURE_SETUP_MEM_READ    0x71
0086 #define JC_FEATURE_MEM_READ      0x72
0087 #define JC_FEATURE_ERASE_MEM_SECTOR  0x73
0088 #define JC_FEATURE_MEM_WRITE         0x74
0089 #define JC_FEATURE_LAUNCH        0x75
0090 
0091 /* USB Commands */
0092 #define JC_USB_CMD_CONN_STATUS       0x01
0093 #define JC_USB_CMD_HANDSHAKE         0x02
0094 #define JC_USB_CMD_BAUDRATE_3M       0x03
0095 #define JC_USB_CMD_NO_TIMEOUT        0x04
0096 #define JC_USB_CMD_EN_TIMEOUT        0x05
0097 #define JC_USB_RESET             0x06
0098 #define JC_USB_PRE_HANDSHAKE         0x91
0099 #define JC_USB_SEND_UART         0x92
0100 
0101 /* Magic value denoting presence of user calibration */
0102 #define JC_CAL_USR_MAGIC_0       0xB2
0103 #define JC_CAL_USR_MAGIC_1       0xA1
0104 #define JC_CAL_USR_MAGIC_SIZE        2
0105 
0106 /* SPI storage addresses of user calibration data */
0107 #define JC_CAL_USR_LEFT_MAGIC_ADDR   0x8010
0108 #define JC_CAL_USR_LEFT_DATA_ADDR    0x8012
0109 #define JC_CAL_USR_LEFT_DATA_END     0x801A
0110 #define JC_CAL_USR_RIGHT_MAGIC_ADDR  0x801B
0111 #define JC_CAL_USR_RIGHT_DATA_ADDR   0x801D
0112 #define JC_CAL_STICK_DATA_SIZE \
0113     (JC_CAL_USR_LEFT_DATA_END - JC_CAL_USR_LEFT_DATA_ADDR + 1)
0114 
0115 /* SPI storage addresses of factory calibration data */
0116 #define JC_CAL_FCT_DATA_LEFT_ADDR    0x603d
0117 #define JC_CAL_FCT_DATA_RIGHT_ADDR   0x6046
0118 
0119 /* SPI storage addresses of IMU factory calibration data */
0120 #define JC_IMU_CAL_FCT_DATA_ADDR     0x6020
0121 #define JC_IMU_CAL_FCT_DATA_END  0x6037
0122 #define JC_IMU_CAL_DATA_SIZE \
0123     (JC_IMU_CAL_FCT_DATA_END - JC_IMU_CAL_FCT_DATA_ADDR + 1)
0124 /* SPI storage addresses of IMU user calibration data */
0125 #define JC_IMU_CAL_USR_MAGIC_ADDR    0x8026
0126 #define JC_IMU_CAL_USR_DATA_ADDR     0x8028
0127 
0128 /* The raw analog joystick values will be mapped in terms of this magnitude */
0129 #define JC_MAX_STICK_MAG         32767
0130 #define JC_STICK_FUZZ            250
0131 #define JC_STICK_FLAT            500
0132 
0133 /* Hat values for pro controller's d-pad */
0134 #define JC_MAX_DPAD_MAG     1
0135 #define JC_DPAD_FUZZ        0
0136 #define JC_DPAD_FLAT        0
0137 
0138 /* Under most circumstances IMU reports are pushed every 15ms; use as default */
0139 #define JC_IMU_DFLT_AVG_DELTA_MS    15
0140 /* How many samples to sum before calculating average IMU report delta */
0141 #define JC_IMU_SAMPLES_PER_DELTA_AVG    300
0142 /* Controls how many dropped IMU packets at once trigger a warning message */
0143 #define JC_IMU_DROPPED_PKT_WARNING  3
0144 
0145 /*
0146  * The controller's accelerometer has a sensor resolution of 16bits and is
0147  * configured with a range of +-8000 milliGs. Therefore, the resolution can be
0148  * calculated thus: (2^16-1)/(8000 * 2) = 4.096 digits per milliG
0149  * Resolution per G (rather than per millliG): 4.096 * 1000 = 4096 digits per G
0150  * Alternatively: 1/4096 = .0002441 Gs per digit
0151  */
0152 #define JC_IMU_MAX_ACCEL_MAG        32767
0153 #define JC_IMU_ACCEL_RES_PER_G      4096
0154 #define JC_IMU_ACCEL_FUZZ       10
0155 #define JC_IMU_ACCEL_FLAT       0
0156 
0157 /*
0158  * The controller's gyroscope has a sensor resolution of 16bits and is
0159  * configured with a range of +-2000 degrees/second.
0160  * Digits per dps: (2^16 -1)/(2000*2) = 16.38375
0161  * dps per digit: 16.38375E-1 = .0610
0162  *
0163  * STMicro recommends in the datasheet to add 15% to the dps/digit. This allows
0164  * the full sensitivity range to be saturated without clipping. This yields more
0165  * accurate results, so it's the technique this driver uses.
0166  * dps per digit (corrected): .0610 * 1.15 = .0702
0167  * digits per dps (corrected): .0702E-1 = 14.247
0168  *
0169  * Now, 14.247 truncating to 14 loses a lot of precision, so we rescale the
0170  * min/max range by 1000.
0171  */
0172 #define JC_IMU_PREC_RANGE_SCALE 1000
0173 /* Note: change mag and res_per_dps if prec_range_scale is ever altered */
0174 #define JC_IMU_MAX_GYRO_MAG     32767000 /* (2^16-1)*1000 */
0175 #define JC_IMU_GYRO_RES_PER_DPS     14247 /* (14.247*1000) */
0176 #define JC_IMU_GYRO_FUZZ        10
0177 #define JC_IMU_GYRO_FLAT        0
0178 
0179 /* frequency/amplitude tables for rumble */
0180 struct joycon_rumble_freq_data {
0181     u16 high;
0182     u8 low;
0183     u16 freq; /* Hz*/
0184 };
0185 
0186 struct joycon_rumble_amp_data {
0187     u8 high;
0188     u16 low;
0189     u16 amp;
0190 };
0191 
0192 #if IS_ENABLED(CONFIG_NINTENDO_FF)
0193 /*
0194  * These tables are from
0195  * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/rumble_data_table.md
0196  */
0197 static const struct joycon_rumble_freq_data joycon_rumble_frequencies[] = {
0198     /* high, low, freq */
0199     { 0x0000, 0x01,   41 }, { 0x0000, 0x02,   42 }, { 0x0000, 0x03,   43 },
0200     { 0x0000, 0x04,   44 }, { 0x0000, 0x05,   45 }, { 0x0000, 0x06,   46 },
0201     { 0x0000, 0x07,   47 }, { 0x0000, 0x08,   48 }, { 0x0000, 0x09,   49 },
0202     { 0x0000, 0x0A,   50 }, { 0x0000, 0x0B,   51 }, { 0x0000, 0x0C,   52 },
0203     { 0x0000, 0x0D,   53 }, { 0x0000, 0x0E,   54 }, { 0x0000, 0x0F,   55 },
0204     { 0x0000, 0x10,   57 }, { 0x0000, 0x11,   58 }, { 0x0000, 0x12,   59 },
0205     { 0x0000, 0x13,   60 }, { 0x0000, 0x14,   62 }, { 0x0000, 0x15,   63 },
0206     { 0x0000, 0x16,   64 }, { 0x0000, 0x17,   66 }, { 0x0000, 0x18,   67 },
0207     { 0x0000, 0x19,   69 }, { 0x0000, 0x1A,   70 }, { 0x0000, 0x1B,   72 },
0208     { 0x0000, 0x1C,   73 }, { 0x0000, 0x1D,   75 }, { 0x0000, 0x1e,   77 },
0209     { 0x0000, 0x1f,   78 }, { 0x0000, 0x20,   80 }, { 0x0400, 0x21,   82 },
0210     { 0x0800, 0x22,   84 }, { 0x0c00, 0x23,   85 }, { 0x1000, 0x24,   87 },
0211     { 0x1400, 0x25,   89 }, { 0x1800, 0x26,   91 }, { 0x1c00, 0x27,   93 },
0212     { 0x2000, 0x28,   95 }, { 0x2400, 0x29,   97 }, { 0x2800, 0x2a,   99 },
0213     { 0x2c00, 0x2b,  102 }, { 0x3000, 0x2c,  104 }, { 0x3400, 0x2d,  106 },
0214     { 0x3800, 0x2e,  108 }, { 0x3c00, 0x2f,  111 }, { 0x4000, 0x30,  113 },
0215     { 0x4400, 0x31,  116 }, { 0x4800, 0x32,  118 }, { 0x4c00, 0x33,  121 },
0216     { 0x5000, 0x34,  123 }, { 0x5400, 0x35,  126 }, { 0x5800, 0x36,  129 },
0217     { 0x5c00, 0x37,  132 }, { 0x6000, 0x38,  135 }, { 0x6400, 0x39,  137 },
0218     { 0x6800, 0x3a,  141 }, { 0x6c00, 0x3b,  144 }, { 0x7000, 0x3c,  147 },
0219     { 0x7400, 0x3d,  150 }, { 0x7800, 0x3e,  153 }, { 0x7c00, 0x3f,  157 },
0220     { 0x8000, 0x40,  160 }, { 0x8400, 0x41,  164 }, { 0x8800, 0x42,  167 },
0221     { 0x8c00, 0x43,  171 }, { 0x9000, 0x44,  174 }, { 0x9400, 0x45,  178 },
0222     { 0x9800, 0x46,  182 }, { 0x9c00, 0x47,  186 }, { 0xa000, 0x48,  190 },
0223     { 0xa400, 0x49,  194 }, { 0xa800, 0x4a,  199 }, { 0xac00, 0x4b,  203 },
0224     { 0xb000, 0x4c,  207 }, { 0xb400, 0x4d,  212 }, { 0xb800, 0x4e,  217 },
0225     { 0xbc00, 0x4f,  221 }, { 0xc000, 0x50,  226 }, { 0xc400, 0x51,  231 },
0226     { 0xc800, 0x52,  236 }, { 0xcc00, 0x53,  241 }, { 0xd000, 0x54,  247 },
0227     { 0xd400, 0x55,  252 }, { 0xd800, 0x56,  258 }, { 0xdc00, 0x57,  263 },
0228     { 0xe000, 0x58,  269 }, { 0xe400, 0x59,  275 }, { 0xe800, 0x5a,  281 },
0229     { 0xec00, 0x5b,  287 }, { 0xf000, 0x5c,  293 }, { 0xf400, 0x5d,  300 },
0230     { 0xf800, 0x5e,  306 }, { 0xfc00, 0x5f,  313 }, { 0x0001, 0x60,  320 },
0231     { 0x0401, 0x61,  327 }, { 0x0801, 0x62,  334 }, { 0x0c01, 0x63,  341 },
0232     { 0x1001, 0x64,  349 }, { 0x1401, 0x65,  357 }, { 0x1801, 0x66,  364 },
0233     { 0x1c01, 0x67,  372 }, { 0x2001, 0x68,  381 }, { 0x2401, 0x69,  389 },
0234     { 0x2801, 0x6a,  397 }, { 0x2c01, 0x6b,  406 }, { 0x3001, 0x6c,  415 },
0235     { 0x3401, 0x6d,  424 }, { 0x3801, 0x6e,  433 }, { 0x3c01, 0x6f,  443 },
0236     { 0x4001, 0x70,  453 }, { 0x4401, 0x71,  462 }, { 0x4801, 0x72,  473 },
0237     { 0x4c01, 0x73,  483 }, { 0x5001, 0x74,  494 }, { 0x5401, 0x75,  504 },
0238     { 0x5801, 0x76,  515 }, { 0x5c01, 0x77,  527 }, { 0x6001, 0x78,  538 },
0239     { 0x6401, 0x79,  550 }, { 0x6801, 0x7a,  562 }, { 0x6c01, 0x7b,  574 },
0240     { 0x7001, 0x7c,  587 }, { 0x7401, 0x7d,  600 }, { 0x7801, 0x7e,  613 },
0241     { 0x7c01, 0x7f,  626 }, { 0x8001, 0x00,  640 }, { 0x8401, 0x00,  654 },
0242     { 0x8801, 0x00,  668 }, { 0x8c01, 0x00,  683 }, { 0x9001, 0x00,  698 },
0243     { 0x9401, 0x00,  713 }, { 0x9801, 0x00,  729 }, { 0x9c01, 0x00,  745 },
0244     { 0xa001, 0x00,  761 }, { 0xa401, 0x00,  778 }, { 0xa801, 0x00,  795 },
0245     { 0xac01, 0x00,  812 }, { 0xb001, 0x00,  830 }, { 0xb401, 0x00,  848 },
0246     { 0xb801, 0x00,  867 }, { 0xbc01, 0x00,  886 }, { 0xc001, 0x00,  905 },
0247     { 0xc401, 0x00,  925 }, { 0xc801, 0x00,  945 }, { 0xcc01, 0x00,  966 },
0248     { 0xd001, 0x00,  987 }, { 0xd401, 0x00, 1009 }, { 0xd801, 0x00, 1031 },
0249     { 0xdc01, 0x00, 1053 }, { 0xe001, 0x00, 1076 }, { 0xe401, 0x00, 1100 },
0250     { 0xe801, 0x00, 1124 }, { 0xec01, 0x00, 1149 }, { 0xf001, 0x00, 1174 },
0251     { 0xf401, 0x00, 1199 }, { 0xf801, 0x00, 1226 }, { 0xfc01, 0x00, 1253 }
0252 };
0253 
0254 #define joycon_max_rumble_amp   (1003)
0255 static const struct joycon_rumble_amp_data joycon_rumble_amplitudes[] = {
0256     /* high, low, amp */
0257     { 0x00, 0x0040,    0 },
0258     { 0x02, 0x8040,   10 }, { 0x04, 0x0041,   12 }, { 0x06, 0x8041,   14 },
0259     { 0x08, 0x0042,   17 }, { 0x0a, 0x8042,   20 }, { 0x0c, 0x0043,   24 },
0260     { 0x0e, 0x8043,   28 }, { 0x10, 0x0044,   33 }, { 0x12, 0x8044,   40 },
0261     { 0x14, 0x0045,   47 }, { 0x16, 0x8045,   56 }, { 0x18, 0x0046,   67 },
0262     { 0x1a, 0x8046,   80 }, { 0x1c, 0x0047,   95 }, { 0x1e, 0x8047,  112 },
0263     { 0x20, 0x0048,  117 }, { 0x22, 0x8048,  123 }, { 0x24, 0x0049,  128 },
0264     { 0x26, 0x8049,  134 }, { 0x28, 0x004a,  140 }, { 0x2a, 0x804a,  146 },
0265     { 0x2c, 0x004b,  152 }, { 0x2e, 0x804b,  159 }, { 0x30, 0x004c,  166 },
0266     { 0x32, 0x804c,  173 }, { 0x34, 0x004d,  181 }, { 0x36, 0x804d,  189 },
0267     { 0x38, 0x004e,  198 }, { 0x3a, 0x804e,  206 }, { 0x3c, 0x004f,  215 },
0268     { 0x3e, 0x804f,  225 }, { 0x40, 0x0050,  230 }, { 0x42, 0x8050,  235 },
0269     { 0x44, 0x0051,  240 }, { 0x46, 0x8051,  245 }, { 0x48, 0x0052,  251 },
0270     { 0x4a, 0x8052,  256 }, { 0x4c, 0x0053,  262 }, { 0x4e, 0x8053,  268 },
0271     { 0x50, 0x0054,  273 }, { 0x52, 0x8054,  279 }, { 0x54, 0x0055,  286 },
0272     { 0x56, 0x8055,  292 }, { 0x58, 0x0056,  298 }, { 0x5a, 0x8056,  305 },
0273     { 0x5c, 0x0057,  311 }, { 0x5e, 0x8057,  318 }, { 0x60, 0x0058,  325 },
0274     { 0x62, 0x8058,  332 }, { 0x64, 0x0059,  340 }, { 0x66, 0x8059,  347 },
0275     { 0x68, 0x005a,  355 }, { 0x6a, 0x805a,  362 }, { 0x6c, 0x005b,  370 },
0276     { 0x6e, 0x805b,  378 }, { 0x70, 0x005c,  387 }, { 0x72, 0x805c,  395 },
0277     { 0x74, 0x005d,  404 }, { 0x76, 0x805d,  413 }, { 0x78, 0x005e,  422 },
0278     { 0x7a, 0x805e,  431 }, { 0x7c, 0x005f,  440 }, { 0x7e, 0x805f,  450 },
0279     { 0x80, 0x0060,  460 }, { 0x82, 0x8060,  470 }, { 0x84, 0x0061,  480 },
0280     { 0x86, 0x8061,  491 }, { 0x88, 0x0062,  501 }, { 0x8a, 0x8062,  512 },
0281     { 0x8c, 0x0063,  524 }, { 0x8e, 0x8063,  535 }, { 0x90, 0x0064,  547 },
0282     { 0x92, 0x8064,  559 }, { 0x94, 0x0065,  571 }, { 0x96, 0x8065,  584 },
0283     { 0x98, 0x0066,  596 }, { 0x9a, 0x8066,  609 }, { 0x9c, 0x0067,  623 },
0284     { 0x9e, 0x8067,  636 }, { 0xa0, 0x0068,  650 }, { 0xa2, 0x8068,  665 },
0285     { 0xa4, 0x0069,  679 }, { 0xa6, 0x8069,  694 }, { 0xa8, 0x006a,  709 },
0286     { 0xaa, 0x806a,  725 }, { 0xac, 0x006b,  741 }, { 0xae, 0x806b,  757 },
0287     { 0xb0, 0x006c,  773 }, { 0xb2, 0x806c,  790 }, { 0xb4, 0x006d,  808 },
0288     { 0xb6, 0x806d,  825 }, { 0xb8, 0x006e,  843 }, { 0xba, 0x806e,  862 },
0289     { 0xbc, 0x006f,  881 }, { 0xbe, 0x806f,  900 }, { 0xc0, 0x0070,  920 },
0290     { 0xc2, 0x8070,  940 }, { 0xc4, 0x0071,  960 }, { 0xc6, 0x8071,  981 },
0291     { 0xc8, 0x0072, joycon_max_rumble_amp }
0292 };
0293 static const u16 JC_RUMBLE_DFLT_LOW_FREQ = 160;
0294 static const u16 JC_RUMBLE_DFLT_HIGH_FREQ = 320;
0295 static const unsigned short JC_RUMBLE_ZERO_AMP_PKT_CNT = 5;
0296 #endif /* IS_ENABLED(CONFIG_NINTENDO_FF) */
0297 static const u16 JC_RUMBLE_PERIOD_MS = 50;
0298 
0299 /* States for controller state machine */
0300 enum joycon_ctlr_state {
0301     JOYCON_CTLR_STATE_INIT,
0302     JOYCON_CTLR_STATE_READ,
0303     JOYCON_CTLR_STATE_REMOVED,
0304 };
0305 
0306 /* Controller type received as part of device info */
0307 enum joycon_ctlr_type {
0308     JOYCON_CTLR_TYPE_JCL = 0x01,
0309     JOYCON_CTLR_TYPE_JCR = 0x02,
0310     JOYCON_CTLR_TYPE_PRO = 0x03,
0311 };
0312 
0313 struct joycon_stick_cal {
0314     s32 max;
0315     s32 min;
0316     s32 center;
0317 };
0318 
0319 struct joycon_imu_cal {
0320     s16 offset[3];
0321     s16 scale[3];
0322 };
0323 
0324 /*
0325  * All the controller's button values are stored in a u32.
0326  * They can be accessed with bitwise ANDs.
0327  */
0328 static const u32 JC_BTN_Y   = BIT(0);
0329 static const u32 JC_BTN_X   = BIT(1);
0330 static const u32 JC_BTN_B   = BIT(2);
0331 static const u32 JC_BTN_A   = BIT(3);
0332 static const u32 JC_BTN_SR_R    = BIT(4);
0333 static const u32 JC_BTN_SL_R    = BIT(5);
0334 static const u32 JC_BTN_R   = BIT(6);
0335 static const u32 JC_BTN_ZR  = BIT(7);
0336 static const u32 JC_BTN_MINUS   = BIT(8);
0337 static const u32 JC_BTN_PLUS    = BIT(9);
0338 static const u32 JC_BTN_RSTICK  = BIT(10);
0339 static const u32 JC_BTN_LSTICK  = BIT(11);
0340 static const u32 JC_BTN_HOME    = BIT(12);
0341 static const u32 JC_BTN_CAP = BIT(13); /* capture button */
0342 static const u32 JC_BTN_DOWN    = BIT(16);
0343 static const u32 JC_BTN_UP  = BIT(17);
0344 static const u32 JC_BTN_RIGHT   = BIT(18);
0345 static const u32 JC_BTN_LEFT    = BIT(19);
0346 static const u32 JC_BTN_SR_L    = BIT(20);
0347 static const u32 JC_BTN_SL_L    = BIT(21);
0348 static const u32 JC_BTN_L   = BIT(22);
0349 static const u32 JC_BTN_ZL  = BIT(23);
0350 
0351 enum joycon_msg_type {
0352     JOYCON_MSG_TYPE_NONE,
0353     JOYCON_MSG_TYPE_USB,
0354     JOYCON_MSG_TYPE_SUBCMD,
0355 };
0356 
0357 struct joycon_rumble_output {
0358     u8 output_id;
0359     u8 packet_num;
0360     u8 rumble_data[8];
0361 } __packed;
0362 
0363 struct joycon_subcmd_request {
0364     u8 output_id; /* must be 0x01 for subcommand, 0x10 for rumble only */
0365     u8 packet_num; /* incremented every send */
0366     u8 rumble_data[8];
0367     u8 subcmd_id;
0368     u8 data[]; /* length depends on the subcommand */
0369 } __packed;
0370 
0371 struct joycon_subcmd_reply {
0372     u8 ack; /* MSB 1 for ACK, 0 for NACK */
0373     u8 id; /* id of requested subcmd */
0374     u8 data[]; /* will be at most 35 bytes */
0375 } __packed;
0376 
0377 struct joycon_imu_data {
0378     s16 accel_x;
0379     s16 accel_y;
0380     s16 accel_z;
0381     s16 gyro_x;
0382     s16 gyro_y;
0383     s16 gyro_z;
0384 } __packed;
0385 
0386 struct joycon_input_report {
0387     u8 id;
0388     u8 timer;
0389     u8 bat_con; /* battery and connection info */
0390     u8 button_status[3];
0391     u8 left_stick[3];
0392     u8 right_stick[3];
0393     u8 vibrator_report;
0394 
0395     union {
0396         struct joycon_subcmd_reply subcmd_reply;
0397         /* IMU input reports contain 3 samples */
0398         u8 imu_raw_bytes[sizeof(struct joycon_imu_data) * 3];
0399     };
0400 } __packed;
0401 
0402 #define JC_MAX_RESP_SIZE    (sizeof(struct joycon_input_report) + 35)
0403 #define JC_RUMBLE_DATA_SIZE 8
0404 #define JC_RUMBLE_QUEUE_SIZE    8
0405 
0406 static const char * const joycon_player_led_names[] = {
0407     LED_FUNCTION_PLAYER1,
0408     LED_FUNCTION_PLAYER2,
0409     LED_FUNCTION_PLAYER3,
0410     LED_FUNCTION_PLAYER4,
0411 };
0412 #define JC_NUM_LEDS     ARRAY_SIZE(joycon_player_led_names)
0413 
0414 /* Each physical controller is associated with a joycon_ctlr struct */
0415 struct joycon_ctlr {
0416     struct hid_device *hdev;
0417     struct input_dev *input;
0418     struct led_classdev leds[JC_NUM_LEDS]; /* player leds */
0419     struct led_classdev home_led;
0420     enum joycon_ctlr_state ctlr_state;
0421     spinlock_t lock;
0422     u8 mac_addr[6];
0423     char *mac_addr_str;
0424     enum joycon_ctlr_type ctlr_type;
0425 
0426     /* The following members are used for synchronous sends/receives */
0427     enum joycon_msg_type msg_type;
0428     u8 subcmd_num;
0429     struct mutex output_mutex;
0430     u8 input_buf[JC_MAX_RESP_SIZE];
0431     wait_queue_head_t wait;
0432     bool received_resp;
0433     u8 usb_ack_match;
0434     u8 subcmd_ack_match;
0435     bool received_input_report;
0436     unsigned int last_subcmd_sent_msecs;
0437 
0438     /* factory calibration data */
0439     struct joycon_stick_cal left_stick_cal_x;
0440     struct joycon_stick_cal left_stick_cal_y;
0441     struct joycon_stick_cal right_stick_cal_x;
0442     struct joycon_stick_cal right_stick_cal_y;
0443 
0444     struct joycon_imu_cal accel_cal;
0445     struct joycon_imu_cal gyro_cal;
0446 
0447     /* prevents needlessly recalculating these divisors every sample */
0448     s32 imu_cal_accel_divisor[3];
0449     s32 imu_cal_gyro_divisor[3];
0450 
0451     /* power supply data */
0452     struct power_supply *battery;
0453     struct power_supply_desc battery_desc;
0454     u8 battery_capacity;
0455     bool battery_charging;
0456     bool host_powered;
0457 
0458     /* rumble */
0459     u8 rumble_data[JC_RUMBLE_QUEUE_SIZE][JC_RUMBLE_DATA_SIZE];
0460     int rumble_queue_head;
0461     int rumble_queue_tail;
0462     struct workqueue_struct *rumble_queue;
0463     struct work_struct rumble_worker;
0464     unsigned int rumble_msecs;
0465     u16 rumble_ll_freq;
0466     u16 rumble_lh_freq;
0467     u16 rumble_rl_freq;
0468     u16 rumble_rh_freq;
0469     unsigned short rumble_zero_countdown;
0470 
0471     /* imu */
0472     struct input_dev *imu_input;
0473     bool imu_first_packet_received; /* helps in initiating timestamp */
0474     unsigned int imu_timestamp_us; /* timestamp we report to userspace */
0475     unsigned int imu_last_pkt_ms; /* used to calc imu report delta */
0476     /* the following are used to track the average imu report time delta */
0477     unsigned int imu_delta_samples_count;
0478     unsigned int imu_delta_samples_sum;
0479     unsigned int imu_avg_delta_ms;
0480 };
0481 
0482 /* Helper macros for checking controller type */
0483 #define jc_type_is_joycon(ctlr) \
0484     (ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONL || \
0485      ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONR || \
0486      ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_CHRGGRIP)
0487 #define jc_type_is_procon(ctlr) \
0488     (ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_PROCON)
0489 #define jc_type_is_chrggrip(ctlr) \
0490     (ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_CHRGGRIP)
0491 
0492 /* Does this controller have inputs associated with left joycon? */
0493 #define jc_type_has_left(ctlr) \
0494     (ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCL || \
0495      ctlr->ctlr_type == JOYCON_CTLR_TYPE_PRO)
0496 
0497 /* Does this controller have inputs associated with right joycon? */
0498 #define jc_type_has_right(ctlr) \
0499     (ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCR || \
0500      ctlr->ctlr_type == JOYCON_CTLR_TYPE_PRO)
0501 
0502 static int __joycon_hid_send(struct hid_device *hdev, u8 *data, size_t len)
0503 {
0504     u8 *buf;
0505     int ret;
0506 
0507     buf = kmemdup(data, len, GFP_KERNEL);
0508     if (!buf)
0509         return -ENOMEM;
0510     ret = hid_hw_output_report(hdev, buf, len);
0511     kfree(buf);
0512     if (ret < 0)
0513         hid_dbg(hdev, "Failed to send output report ret=%d\n", ret);
0514     return ret;
0515 }
0516 
0517 static void joycon_wait_for_input_report(struct joycon_ctlr *ctlr)
0518 {
0519     int ret;
0520 
0521     /*
0522      * If we are in the proper reporting mode, wait for an input
0523      * report prior to sending the subcommand. This improves
0524      * reliability considerably.
0525      */
0526     if (ctlr->ctlr_state == JOYCON_CTLR_STATE_READ) {
0527         unsigned long flags;
0528 
0529         spin_lock_irqsave(&ctlr->lock, flags);
0530         ctlr->received_input_report = false;
0531         spin_unlock_irqrestore(&ctlr->lock, flags);
0532         ret = wait_event_timeout(ctlr->wait,
0533                      ctlr->received_input_report,
0534                      HZ / 4);
0535         /* We will still proceed, even with a timeout here */
0536         if (!ret)
0537             hid_warn(ctlr->hdev,
0538                  "timeout waiting for input report\n");
0539     }
0540 }
0541 
0542 /*
0543  * Sending subcommands and/or rumble data at too high a rate can cause bluetooth
0544  * controller disconnections.
0545  */
0546 static void joycon_enforce_subcmd_rate(struct joycon_ctlr *ctlr)
0547 {
0548     static const unsigned int max_subcmd_rate_ms = 25;
0549     unsigned int current_ms = jiffies_to_msecs(jiffies);
0550     unsigned int delta_ms = current_ms - ctlr->last_subcmd_sent_msecs;
0551 
0552     while (delta_ms < max_subcmd_rate_ms &&
0553            ctlr->ctlr_state == JOYCON_CTLR_STATE_READ) {
0554         joycon_wait_for_input_report(ctlr);
0555         current_ms = jiffies_to_msecs(jiffies);
0556         delta_ms = current_ms - ctlr->last_subcmd_sent_msecs;
0557     }
0558     ctlr->last_subcmd_sent_msecs = current_ms;
0559 }
0560 
0561 static int joycon_hid_send_sync(struct joycon_ctlr *ctlr, u8 *data, size_t len,
0562                 u32 timeout)
0563 {
0564     int ret;
0565     int tries = 2;
0566 
0567     /*
0568      * The controller occasionally seems to drop subcommands. In testing,
0569      * doing one retry after a timeout appears to always work.
0570      */
0571     while (tries--) {
0572         joycon_enforce_subcmd_rate(ctlr);
0573 
0574         ret = __joycon_hid_send(ctlr->hdev, data, len);
0575         if (ret < 0) {
0576             memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE);
0577             return ret;
0578         }
0579 
0580         ret = wait_event_timeout(ctlr->wait, ctlr->received_resp,
0581                      timeout);
0582         if (!ret) {
0583             hid_dbg(ctlr->hdev,
0584                 "synchronous send/receive timed out\n");
0585             if (tries) {
0586                 hid_dbg(ctlr->hdev,
0587                     "retrying sync send after timeout\n");
0588             }
0589             memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE);
0590             ret = -ETIMEDOUT;
0591         } else {
0592             ret = 0;
0593             break;
0594         }
0595     }
0596 
0597     ctlr->received_resp = false;
0598     return ret;
0599 }
0600 
0601 static int joycon_send_usb(struct joycon_ctlr *ctlr, u8 cmd, u32 timeout)
0602 {
0603     int ret;
0604     u8 buf[2] = {JC_OUTPUT_USB_CMD};
0605 
0606     buf[1] = cmd;
0607     ctlr->usb_ack_match = cmd;
0608     ctlr->msg_type = JOYCON_MSG_TYPE_USB;
0609     ret = joycon_hid_send_sync(ctlr, buf, sizeof(buf), timeout);
0610     if (ret)
0611         hid_dbg(ctlr->hdev, "send usb command failed; ret=%d\n", ret);
0612     return ret;
0613 }
0614 
0615 static int joycon_send_subcmd(struct joycon_ctlr *ctlr,
0616                   struct joycon_subcmd_request *subcmd,
0617                   size_t data_len, u32 timeout)
0618 {
0619     int ret;
0620     unsigned long flags;
0621 
0622     spin_lock_irqsave(&ctlr->lock, flags);
0623     /*
0624      * If the controller has been removed, just return ENODEV so the LED
0625      * subsystem doesn't print invalid errors on removal.
0626      */
0627     if (ctlr->ctlr_state == JOYCON_CTLR_STATE_REMOVED) {
0628         spin_unlock_irqrestore(&ctlr->lock, flags);
0629         return -ENODEV;
0630     }
0631     memcpy(subcmd->rumble_data, ctlr->rumble_data[ctlr->rumble_queue_tail],
0632            JC_RUMBLE_DATA_SIZE);
0633     spin_unlock_irqrestore(&ctlr->lock, flags);
0634 
0635     subcmd->output_id = JC_OUTPUT_RUMBLE_AND_SUBCMD;
0636     subcmd->packet_num = ctlr->subcmd_num;
0637     if (++ctlr->subcmd_num > 0xF)
0638         ctlr->subcmd_num = 0;
0639     ctlr->subcmd_ack_match = subcmd->subcmd_id;
0640     ctlr->msg_type = JOYCON_MSG_TYPE_SUBCMD;
0641 
0642     ret = joycon_hid_send_sync(ctlr, (u8 *)subcmd,
0643                    sizeof(*subcmd) + data_len, timeout);
0644     if (ret < 0)
0645         hid_dbg(ctlr->hdev, "send subcommand failed; ret=%d\n", ret);
0646     else
0647         ret = 0;
0648     return ret;
0649 }
0650 
0651 /* Supply nibbles for flash and on. Ones correspond to active */
0652 static int joycon_set_player_leds(struct joycon_ctlr *ctlr, u8 flash, u8 on)
0653 {
0654     struct joycon_subcmd_request *req;
0655     u8 buffer[sizeof(*req) + 1] = { 0 };
0656 
0657     req = (struct joycon_subcmd_request *)buffer;
0658     req->subcmd_id = JC_SUBCMD_SET_PLAYER_LIGHTS;
0659     req->data[0] = (flash << 4) | on;
0660 
0661     hid_dbg(ctlr->hdev, "setting player leds\n");
0662     return joycon_send_subcmd(ctlr, req, 1, HZ/4);
0663 }
0664 
0665 static int joycon_request_spi_flash_read(struct joycon_ctlr *ctlr,
0666                      u32 start_addr, u8 size, u8 **reply)
0667 {
0668     struct joycon_subcmd_request *req;
0669     struct joycon_input_report *report;
0670     u8 buffer[sizeof(*req) + 5] = { 0 };
0671     u8 *data;
0672     int ret;
0673 
0674     if (!reply)
0675         return -EINVAL;
0676 
0677     req = (struct joycon_subcmd_request *)buffer;
0678     req->subcmd_id = JC_SUBCMD_SPI_FLASH_READ;
0679     data = req->data;
0680     put_unaligned_le32(start_addr, data);
0681     data[4] = size;
0682 
0683     hid_dbg(ctlr->hdev, "requesting SPI flash data\n");
0684     ret = joycon_send_subcmd(ctlr, req, 5, HZ);
0685     if (ret) {
0686         hid_err(ctlr->hdev, "failed reading SPI flash; ret=%d\n", ret);
0687     } else {
0688         report = (struct joycon_input_report *)ctlr->input_buf;
0689         /* The read data starts at the 6th byte */
0690         *reply = &report->subcmd_reply.data[5];
0691     }
0692     return ret;
0693 }
0694 
0695 /*
0696  * User calibration's presence is denoted with a magic byte preceding it.
0697  * returns 0 if magic val is present, 1 if not present, < 0 on error
0698  */
0699 static int joycon_check_for_cal_magic(struct joycon_ctlr *ctlr, u32 flash_addr)
0700 {
0701     int ret;
0702     u8 *reply;
0703 
0704     ret = joycon_request_spi_flash_read(ctlr, flash_addr,
0705                         JC_CAL_USR_MAGIC_SIZE, &reply);
0706     if (ret)
0707         return ret;
0708 
0709     return reply[0] != JC_CAL_USR_MAGIC_0 || reply[1] != JC_CAL_USR_MAGIC_1;
0710 }
0711 
0712 static int joycon_read_stick_calibration(struct joycon_ctlr *ctlr, u16 cal_addr,
0713                      struct joycon_stick_cal *cal_x,
0714                      struct joycon_stick_cal *cal_y,
0715                      bool left_stick)
0716 {
0717     s32 x_max_above;
0718     s32 x_min_below;
0719     s32 y_max_above;
0720     s32 y_min_below;
0721     u8 *raw_cal;
0722     int ret;
0723 
0724     ret = joycon_request_spi_flash_read(ctlr, cal_addr,
0725                         JC_CAL_STICK_DATA_SIZE, &raw_cal);
0726     if (ret)
0727         return ret;
0728 
0729     /* stick calibration parsing: note the order differs based on stick */
0730     if (left_stick) {
0731         x_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 0), 0,
0732                         12);
0733         y_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 1), 4,
0734                         12);
0735         cal_x->center = hid_field_extract(ctlr->hdev, (raw_cal + 3), 0,
0736                           12);
0737         cal_y->center = hid_field_extract(ctlr->hdev, (raw_cal + 4), 4,
0738                           12);
0739         x_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 6), 0,
0740                         12);
0741         y_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 7), 4,
0742                         12);
0743     } else {
0744         cal_x->center = hid_field_extract(ctlr->hdev, (raw_cal + 0), 0,
0745                           12);
0746         cal_y->center = hid_field_extract(ctlr->hdev, (raw_cal + 1), 4,
0747                           12);
0748         x_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 3), 0,
0749                         12);
0750         y_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 4), 4,
0751                         12);
0752         x_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 6), 0,
0753                         12);
0754         y_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 7), 4,
0755                         12);
0756     }
0757 
0758     cal_x->max = cal_x->center + x_max_above;
0759     cal_x->min = cal_x->center - x_min_below;
0760     cal_y->max = cal_y->center + y_max_above;
0761     cal_y->min = cal_y->center - y_min_below;
0762 
0763     return 0;
0764 }
0765 
0766 static const u16 DFLT_STICK_CAL_CEN = 2000;
0767 static const u16 DFLT_STICK_CAL_MAX = 3500;
0768 static const u16 DFLT_STICK_CAL_MIN = 500;
0769 static int joycon_request_calibration(struct joycon_ctlr *ctlr)
0770 {
0771     u16 left_stick_addr = JC_CAL_FCT_DATA_LEFT_ADDR;
0772     u16 right_stick_addr = JC_CAL_FCT_DATA_RIGHT_ADDR;
0773     int ret;
0774 
0775     hid_dbg(ctlr->hdev, "requesting cal data\n");
0776 
0777     /* check if user stick calibrations are present */
0778     if (!joycon_check_for_cal_magic(ctlr, JC_CAL_USR_LEFT_MAGIC_ADDR)) {
0779         left_stick_addr = JC_CAL_USR_LEFT_DATA_ADDR;
0780         hid_info(ctlr->hdev, "using user cal for left stick\n");
0781     } else {
0782         hid_info(ctlr->hdev, "using factory cal for left stick\n");
0783     }
0784     if (!joycon_check_for_cal_magic(ctlr, JC_CAL_USR_RIGHT_MAGIC_ADDR)) {
0785         right_stick_addr = JC_CAL_USR_RIGHT_DATA_ADDR;
0786         hid_info(ctlr->hdev, "using user cal for right stick\n");
0787     } else {
0788         hid_info(ctlr->hdev, "using factory cal for right stick\n");
0789     }
0790 
0791     /* read the left stick calibration data */
0792     ret = joycon_read_stick_calibration(ctlr, left_stick_addr,
0793                         &ctlr->left_stick_cal_x,
0794                         &ctlr->left_stick_cal_y,
0795                         true);
0796     if (ret) {
0797         hid_warn(ctlr->hdev,
0798              "Failed to read left stick cal, using dflts; e=%d\n",
0799              ret);
0800 
0801         ctlr->left_stick_cal_x.center = DFLT_STICK_CAL_CEN;
0802         ctlr->left_stick_cal_x.max = DFLT_STICK_CAL_MAX;
0803         ctlr->left_stick_cal_x.min = DFLT_STICK_CAL_MIN;
0804 
0805         ctlr->left_stick_cal_y.center = DFLT_STICK_CAL_CEN;
0806         ctlr->left_stick_cal_y.max = DFLT_STICK_CAL_MAX;
0807         ctlr->left_stick_cal_y.min = DFLT_STICK_CAL_MIN;
0808     }
0809 
0810     /* read the right stick calibration data */
0811     ret = joycon_read_stick_calibration(ctlr, right_stick_addr,
0812                         &ctlr->right_stick_cal_x,
0813                         &ctlr->right_stick_cal_y,
0814                         false);
0815     if (ret) {
0816         hid_warn(ctlr->hdev,
0817              "Failed to read right stick cal, using dflts; e=%d\n",
0818              ret);
0819 
0820         ctlr->right_stick_cal_x.center = DFLT_STICK_CAL_CEN;
0821         ctlr->right_stick_cal_x.max = DFLT_STICK_CAL_MAX;
0822         ctlr->right_stick_cal_x.min = DFLT_STICK_CAL_MIN;
0823 
0824         ctlr->right_stick_cal_y.center = DFLT_STICK_CAL_CEN;
0825         ctlr->right_stick_cal_y.max = DFLT_STICK_CAL_MAX;
0826         ctlr->right_stick_cal_y.min = DFLT_STICK_CAL_MIN;
0827     }
0828 
0829     hid_dbg(ctlr->hdev, "calibration:\n"
0830                 "l_x_c=%d l_x_max=%d l_x_min=%d\n"
0831                 "l_y_c=%d l_y_max=%d l_y_min=%d\n"
0832                 "r_x_c=%d r_x_max=%d r_x_min=%d\n"
0833                 "r_y_c=%d r_y_max=%d r_y_min=%d\n",
0834                 ctlr->left_stick_cal_x.center,
0835                 ctlr->left_stick_cal_x.max,
0836                 ctlr->left_stick_cal_x.min,
0837                 ctlr->left_stick_cal_y.center,
0838                 ctlr->left_stick_cal_y.max,
0839                 ctlr->left_stick_cal_y.min,
0840                 ctlr->right_stick_cal_x.center,
0841                 ctlr->right_stick_cal_x.max,
0842                 ctlr->right_stick_cal_x.min,
0843                 ctlr->right_stick_cal_y.center,
0844                 ctlr->right_stick_cal_y.max,
0845                 ctlr->right_stick_cal_y.min);
0846 
0847     return 0;
0848 }
0849 
0850 /*
0851  * These divisors are calculated once rather than for each sample. They are only
0852  * dependent on the IMU calibration values. They are used when processing the
0853  * IMU input reports.
0854  */
0855 static void joycon_calc_imu_cal_divisors(struct joycon_ctlr *ctlr)
0856 {
0857     int i;
0858 
0859     for (i = 0; i < 3; i++) {
0860         ctlr->imu_cal_accel_divisor[i] = ctlr->accel_cal.scale[i] -
0861                         ctlr->accel_cal.offset[i];
0862         ctlr->imu_cal_gyro_divisor[i] = ctlr->gyro_cal.scale[i] -
0863                         ctlr->gyro_cal.offset[i];
0864     }
0865 }
0866 
0867 static const s16 DFLT_ACCEL_OFFSET /*= 0*/;
0868 static const s16 DFLT_ACCEL_SCALE = 16384;
0869 static const s16 DFLT_GYRO_OFFSET /*= 0*/;
0870 static const s16 DFLT_GYRO_SCALE  = 13371;
0871 static int joycon_request_imu_calibration(struct joycon_ctlr *ctlr)
0872 {
0873     u16 imu_cal_addr = JC_IMU_CAL_FCT_DATA_ADDR;
0874     u8 *raw_cal;
0875     int ret;
0876     int i;
0877 
0878     /* check if user calibration exists */
0879     if (!joycon_check_for_cal_magic(ctlr, JC_IMU_CAL_USR_MAGIC_ADDR)) {
0880         imu_cal_addr = JC_IMU_CAL_USR_DATA_ADDR;
0881         hid_info(ctlr->hdev, "using user cal for IMU\n");
0882     } else {
0883         hid_info(ctlr->hdev, "using factory cal for IMU\n");
0884     }
0885 
0886     /* request IMU calibration data */
0887     hid_dbg(ctlr->hdev, "requesting IMU cal data\n");
0888     ret = joycon_request_spi_flash_read(ctlr, imu_cal_addr,
0889                         JC_IMU_CAL_DATA_SIZE, &raw_cal);
0890     if (ret) {
0891         hid_warn(ctlr->hdev,
0892              "Failed to read IMU cal, using defaults; ret=%d\n",
0893              ret);
0894 
0895         for (i = 0; i < 3; i++) {
0896             ctlr->accel_cal.offset[i] = DFLT_ACCEL_OFFSET;
0897             ctlr->accel_cal.scale[i] = DFLT_ACCEL_SCALE;
0898             ctlr->gyro_cal.offset[i] = DFLT_GYRO_OFFSET;
0899             ctlr->gyro_cal.scale[i] = DFLT_GYRO_SCALE;
0900         }
0901         joycon_calc_imu_cal_divisors(ctlr);
0902         return ret;
0903     }
0904 
0905     /* IMU calibration parsing */
0906     for (i = 0; i < 3; i++) {
0907         int j = i * 2;
0908 
0909         ctlr->accel_cal.offset[i] = get_unaligned_le16(raw_cal + j);
0910         ctlr->accel_cal.scale[i] = get_unaligned_le16(raw_cal + j + 6);
0911         ctlr->gyro_cal.offset[i] = get_unaligned_le16(raw_cal + j + 12);
0912         ctlr->gyro_cal.scale[i] = get_unaligned_le16(raw_cal + j + 18);
0913     }
0914 
0915     joycon_calc_imu_cal_divisors(ctlr);
0916 
0917     hid_dbg(ctlr->hdev, "IMU calibration:\n"
0918                 "a_o[0]=%d a_o[1]=%d a_o[2]=%d\n"
0919                 "a_s[0]=%d a_s[1]=%d a_s[2]=%d\n"
0920                 "g_o[0]=%d g_o[1]=%d g_o[2]=%d\n"
0921                 "g_s[0]=%d g_s[1]=%d g_s[2]=%d\n",
0922                 ctlr->accel_cal.offset[0],
0923                 ctlr->accel_cal.offset[1],
0924                 ctlr->accel_cal.offset[2],
0925                 ctlr->accel_cal.scale[0],
0926                 ctlr->accel_cal.scale[1],
0927                 ctlr->accel_cal.scale[2],
0928                 ctlr->gyro_cal.offset[0],
0929                 ctlr->gyro_cal.offset[1],
0930                 ctlr->gyro_cal.offset[2],
0931                 ctlr->gyro_cal.scale[0],
0932                 ctlr->gyro_cal.scale[1],
0933                 ctlr->gyro_cal.scale[2]);
0934 
0935     return 0;
0936 }
0937 
0938 static int joycon_set_report_mode(struct joycon_ctlr *ctlr)
0939 {
0940     struct joycon_subcmd_request *req;
0941     u8 buffer[sizeof(*req) + 1] = { 0 };
0942 
0943     req = (struct joycon_subcmd_request *)buffer;
0944     req->subcmd_id = JC_SUBCMD_SET_REPORT_MODE;
0945     req->data[0] = 0x30; /* standard, full report mode */
0946 
0947     hid_dbg(ctlr->hdev, "setting controller report mode\n");
0948     return joycon_send_subcmd(ctlr, req, 1, HZ);
0949 }
0950 
0951 static int joycon_enable_rumble(struct joycon_ctlr *ctlr)
0952 {
0953     struct joycon_subcmd_request *req;
0954     u8 buffer[sizeof(*req) + 1] = { 0 };
0955 
0956     req = (struct joycon_subcmd_request *)buffer;
0957     req->subcmd_id = JC_SUBCMD_ENABLE_VIBRATION;
0958     req->data[0] = 0x01; /* note: 0x00 would disable */
0959 
0960     hid_dbg(ctlr->hdev, "enabling rumble\n");
0961     return joycon_send_subcmd(ctlr, req, 1, HZ/4);
0962 }
0963 
0964 static int joycon_enable_imu(struct joycon_ctlr *ctlr)
0965 {
0966     struct joycon_subcmd_request *req;
0967     u8 buffer[sizeof(*req) + 1] = { 0 };
0968 
0969     req = (struct joycon_subcmd_request *)buffer;
0970     req->subcmd_id = JC_SUBCMD_ENABLE_IMU;
0971     req->data[0] = 0x01; /* note: 0x00 would disable */
0972 
0973     hid_dbg(ctlr->hdev, "enabling IMU\n");
0974     return joycon_send_subcmd(ctlr, req, 1, HZ);
0975 }
0976 
0977 static s32 joycon_map_stick_val(struct joycon_stick_cal *cal, s32 val)
0978 {
0979     s32 center = cal->center;
0980     s32 min = cal->min;
0981     s32 max = cal->max;
0982     s32 new_val;
0983 
0984     if (val > center) {
0985         new_val = (val - center) * JC_MAX_STICK_MAG;
0986         new_val /= (max - center);
0987     } else {
0988         new_val = (center - val) * -JC_MAX_STICK_MAG;
0989         new_val /= (center - min);
0990     }
0991     new_val = clamp(new_val, (s32)-JC_MAX_STICK_MAG, (s32)JC_MAX_STICK_MAG);
0992     return new_val;
0993 }
0994 
0995 static void joycon_input_report_parse_imu_data(struct joycon_ctlr *ctlr,
0996                            struct joycon_input_report *rep,
0997                            struct joycon_imu_data *imu_data)
0998 {
0999     u8 *raw = rep->imu_raw_bytes;
1000     int i;
1001 
1002     for (i = 0; i < 3; i++) {
1003         struct joycon_imu_data *data = &imu_data[i];
1004 
1005         data->accel_x = get_unaligned_le16(raw + 0);
1006         data->accel_y = get_unaligned_le16(raw + 2);
1007         data->accel_z = get_unaligned_le16(raw + 4);
1008         data->gyro_x = get_unaligned_le16(raw + 6);
1009         data->gyro_y = get_unaligned_le16(raw + 8);
1010         data->gyro_z = get_unaligned_le16(raw + 10);
1011         /* point to next imu sample */
1012         raw += sizeof(struct joycon_imu_data);
1013     }
1014 }
1015 
1016 static void joycon_parse_imu_report(struct joycon_ctlr *ctlr,
1017                     struct joycon_input_report *rep)
1018 {
1019     struct joycon_imu_data imu_data[3] = {0}; /* 3 reports per packet */
1020     struct input_dev *idev = ctlr->imu_input;
1021     unsigned int msecs = jiffies_to_msecs(jiffies);
1022     unsigned int last_msecs = ctlr->imu_last_pkt_ms;
1023     int i;
1024     int value[6];
1025 
1026     joycon_input_report_parse_imu_data(ctlr, rep, imu_data);
1027 
1028     /*
1029      * There are complexities surrounding how we determine the timestamps we
1030      * associate with the samples we pass to userspace. The IMU input
1031      * reports do not provide us with a good timestamp. There's a quickly
1032      * incrementing 8-bit counter per input report, but it is not very
1033      * useful for this purpose (it is not entirely clear what rate it
1034      * increments at or if it varies based on packet push rate - more on
1035      * the push rate below...).
1036      *
1037      * The reverse engineering work done on the joy-cons and pro controllers
1038      * by the community seems to indicate the following:
1039      * - The controller samples the IMU every 1.35ms. It then does some of
1040      *   its own processing, probably averaging the samples out.
1041      * - Each imu input report contains 3 IMU samples, (usually 5ms apart).
1042      * - In the standard reporting mode (which this driver uses exclusively)
1043      *   input reports are pushed from the controller as follows:
1044      *      * joy-con (bluetooth): every 15 ms
1045      *      * joy-cons (in charging grip via USB): every 15 ms
1046      *      * pro controller (USB): every 15 ms
1047      *      * pro controller (bluetooth): every 8 ms (this is the wildcard)
1048      *
1049      * Further complicating matters is that some bluetooth stacks are known
1050      * to alter the controller's packet rate by hardcoding the bluetooth
1051      * SSR for the switch controllers (android's stack currently sets the
1052      * SSR to 11ms for both the joy-cons and pro controllers).
1053      *
1054      * In my own testing, I've discovered that my pro controller either
1055      * reports IMU sample batches every 11ms or every 15ms. This rate is
1056      * stable after connecting. It isn't 100% clear what determines this
1057      * rate. Importantly, even when sending every 11ms, none of the samples
1058      * are duplicates. This seems to indicate that the time deltas between
1059      * reported samples can vary based on the input report rate.
1060      *
1061      * The solution employed in this driver is to keep track of the average
1062      * time delta between IMU input reports. In testing, this value has
1063      * proven to be stable, staying at 15ms or 11ms, though other hardware
1064      * configurations and bluetooth stacks could potentially see other rates
1065      * (hopefully this will become more clear as more people use the
1066      * driver).
1067      *
1068      * Keeping track of the average report delta allows us to submit our
1069      * timestamps to userspace based on that. Each report contains 3
1070      * samples, so the IMU sampling rate should be avg_time_delta/3. We can
1071      * also use this average to detect events where we have dropped a
1072      * packet. The userspace timestamp for the samples will be adjusted
1073      * accordingly to prevent unwanted behvaior.
1074      */
1075     if (!ctlr->imu_first_packet_received) {
1076         ctlr->imu_timestamp_us = 0;
1077         ctlr->imu_delta_samples_count = 0;
1078         ctlr->imu_delta_samples_sum = 0;
1079         ctlr->imu_avg_delta_ms = JC_IMU_DFLT_AVG_DELTA_MS;
1080         ctlr->imu_first_packet_received = true;
1081     } else {
1082         unsigned int delta = msecs - last_msecs;
1083         unsigned int dropped_pkts;
1084         unsigned int dropped_threshold;
1085 
1086         /* avg imu report delta housekeeping */
1087         ctlr->imu_delta_samples_sum += delta;
1088         ctlr->imu_delta_samples_count++;
1089         if (ctlr->imu_delta_samples_count >=
1090             JC_IMU_SAMPLES_PER_DELTA_AVG) {
1091             ctlr->imu_avg_delta_ms = ctlr->imu_delta_samples_sum /
1092                          ctlr->imu_delta_samples_count;
1093             /* don't ever want divide by zero shenanigans */
1094             if (ctlr->imu_avg_delta_ms == 0) {
1095                 ctlr->imu_avg_delta_ms = 1;
1096                 hid_warn(ctlr->hdev,
1097                      "calculated avg imu delta of 0\n");
1098             }
1099             ctlr->imu_delta_samples_count = 0;
1100             ctlr->imu_delta_samples_sum = 0;
1101         }
1102 
1103         /* useful for debugging IMU sample rate */
1104         hid_dbg(ctlr->hdev,
1105             "imu_report: ms=%u last_ms=%u delta=%u avg_delta=%u\n",
1106             msecs, last_msecs, delta, ctlr->imu_avg_delta_ms);
1107 
1108         /* check if any packets have been dropped */
1109         dropped_threshold = ctlr->imu_avg_delta_ms * 3 / 2;
1110         dropped_pkts = (delta - min(delta, dropped_threshold)) /
1111                 ctlr->imu_avg_delta_ms;
1112         ctlr->imu_timestamp_us += 1000 * ctlr->imu_avg_delta_ms;
1113         if (dropped_pkts > JC_IMU_DROPPED_PKT_WARNING) {
1114             hid_warn(ctlr->hdev,
1115                  "compensating for %u dropped IMU reports\n",
1116                  dropped_pkts);
1117             hid_warn(ctlr->hdev,
1118                  "delta=%u avg_delta=%u\n",
1119                  delta, ctlr->imu_avg_delta_ms);
1120         }
1121     }
1122     ctlr->imu_last_pkt_ms = msecs;
1123 
1124     /* Each IMU input report contains three samples */
1125     for (i = 0; i < 3; i++) {
1126         input_event(idev, EV_MSC, MSC_TIMESTAMP,
1127                 ctlr->imu_timestamp_us);
1128 
1129         /*
1130          * These calculations (which use the controller's calibration
1131          * settings to improve the final values) are based on those
1132          * found in the community's reverse-engineering repo (linked at
1133          * top of driver). For hid-nintendo, we make sure that the final
1134          * value given to userspace is always in terms of the axis
1135          * resolution we provided.
1136          *
1137          * Currently only the gyro calculations subtract the calibration
1138          * offsets from the raw value itself. In testing, doing the same
1139          * for the accelerometer raw values decreased accuracy.
1140          *
1141          * Note that the gyro values are multiplied by the
1142          * precision-saving scaling factor to prevent large inaccuracies
1143          * due to truncation of the resolution value which would
1144          * otherwise occur. To prevent overflow (without resorting to 64
1145          * bit integer math), the mult_frac macro is used.
1146          */
1147         value[0] = mult_frac((JC_IMU_PREC_RANGE_SCALE *
1148                       (imu_data[i].gyro_x -
1149                        ctlr->gyro_cal.offset[0])),
1150                      ctlr->gyro_cal.scale[0],
1151                      ctlr->imu_cal_gyro_divisor[0]);
1152         value[1] = mult_frac((JC_IMU_PREC_RANGE_SCALE *
1153                       (imu_data[i].gyro_y -
1154                        ctlr->gyro_cal.offset[1])),
1155                      ctlr->gyro_cal.scale[1],
1156                      ctlr->imu_cal_gyro_divisor[1]);
1157         value[2] = mult_frac((JC_IMU_PREC_RANGE_SCALE *
1158                       (imu_data[i].gyro_z -
1159                        ctlr->gyro_cal.offset[2])),
1160                      ctlr->gyro_cal.scale[2],
1161                      ctlr->imu_cal_gyro_divisor[2]);
1162 
1163         value[3] = ((s32)imu_data[i].accel_x *
1164                 ctlr->accel_cal.scale[0]) /
1165                 ctlr->imu_cal_accel_divisor[0];
1166         value[4] = ((s32)imu_data[i].accel_y *
1167                 ctlr->accel_cal.scale[1]) /
1168                 ctlr->imu_cal_accel_divisor[1];
1169         value[5] = ((s32)imu_data[i].accel_z *
1170                 ctlr->accel_cal.scale[2]) /
1171                 ctlr->imu_cal_accel_divisor[2];
1172 
1173         hid_dbg(ctlr->hdev, "raw_gyro: g_x=%d g_y=%d g_z=%d\n",
1174             imu_data[i].gyro_x, imu_data[i].gyro_y,
1175             imu_data[i].gyro_z);
1176         hid_dbg(ctlr->hdev, "raw_accel: a_x=%d a_y=%d a_z=%d\n",
1177             imu_data[i].accel_x, imu_data[i].accel_y,
1178             imu_data[i].accel_z);
1179 
1180         /*
1181          * The right joy-con has 2 axes negated, Y and Z. This is due to
1182          * the orientation of the IMU in the controller. We negate those
1183          * axes' values in order to be consistent with the left joy-con
1184          * and the pro controller:
1185          *   X: positive is pointing toward the triggers
1186          *   Y: positive is pointing to the left
1187          *   Z: positive is pointing up (out of the buttons/sticks)
1188          * The axes follow the right-hand rule.
1189          */
1190         if (jc_type_is_joycon(ctlr) && jc_type_has_right(ctlr)) {
1191             int j;
1192 
1193             /* negate all but x axis */
1194             for (j = 1; j < 6; ++j) {
1195                 if (j == 3)
1196                     continue;
1197                 value[j] *= -1;
1198             }
1199         }
1200 
1201         input_report_abs(idev, ABS_RX, value[0]);
1202         input_report_abs(idev, ABS_RY, value[1]);
1203         input_report_abs(idev, ABS_RZ, value[2]);
1204         input_report_abs(idev, ABS_X, value[3]);
1205         input_report_abs(idev, ABS_Y, value[4]);
1206         input_report_abs(idev, ABS_Z, value[5]);
1207         input_sync(idev);
1208         /* convert to micros and divide by 3 (3 samples per report). */
1209         ctlr->imu_timestamp_us += ctlr->imu_avg_delta_ms * 1000 / 3;
1210     }
1211 }
1212 
1213 static void joycon_parse_report(struct joycon_ctlr *ctlr,
1214                 struct joycon_input_report *rep)
1215 {
1216     struct input_dev *dev = ctlr->input;
1217     unsigned long flags;
1218     u8 tmp;
1219     u32 btns;
1220     unsigned long msecs = jiffies_to_msecs(jiffies);
1221 
1222     spin_lock_irqsave(&ctlr->lock, flags);
1223     if (IS_ENABLED(CONFIG_NINTENDO_FF) && rep->vibrator_report &&
1224         ctlr->ctlr_state != JOYCON_CTLR_STATE_REMOVED &&
1225         (msecs - ctlr->rumble_msecs) >= JC_RUMBLE_PERIOD_MS &&
1226         (ctlr->rumble_queue_head != ctlr->rumble_queue_tail ||
1227          ctlr->rumble_zero_countdown > 0)) {
1228         /*
1229          * When this value reaches 0, we know we've sent multiple
1230          * packets to the controller instructing it to disable rumble.
1231          * We can safely stop sending periodic rumble packets until the
1232          * next ff effect.
1233          */
1234         if (ctlr->rumble_zero_countdown > 0)
1235             ctlr->rumble_zero_countdown--;
1236         queue_work(ctlr->rumble_queue, &ctlr->rumble_worker);
1237     }
1238 
1239     /* Parse the battery status */
1240     tmp = rep->bat_con;
1241     ctlr->host_powered = tmp & BIT(0);
1242     ctlr->battery_charging = tmp & BIT(4);
1243     tmp = tmp >> 5;
1244     switch (tmp) {
1245     case 0: /* empty */
1246         ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
1247         break;
1248     case 1: /* low */
1249         ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
1250         break;
1251     case 2: /* medium */
1252         ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
1253         break;
1254     case 3: /* high */
1255         ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_HIGH;
1256         break;
1257     case 4: /* full */
1258         ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
1259         break;
1260     default:
1261         ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
1262         hid_warn(ctlr->hdev, "Invalid battery status\n");
1263         break;
1264     }
1265     spin_unlock_irqrestore(&ctlr->lock, flags);
1266 
1267     /* Parse the buttons and sticks */
1268     btns = hid_field_extract(ctlr->hdev, rep->button_status, 0, 24);
1269 
1270     if (jc_type_has_left(ctlr)) {
1271         u16 raw_x;
1272         u16 raw_y;
1273         s32 x;
1274         s32 y;
1275 
1276         /* get raw stick values */
1277         raw_x = hid_field_extract(ctlr->hdev, rep->left_stick, 0, 12);
1278         raw_y = hid_field_extract(ctlr->hdev,
1279                       rep->left_stick + 1, 4, 12);
1280         /* map the stick values */
1281         x = joycon_map_stick_val(&ctlr->left_stick_cal_x, raw_x);
1282         y = -joycon_map_stick_val(&ctlr->left_stick_cal_y, raw_y);
1283         /* report sticks */
1284         input_report_abs(dev, ABS_X, x);
1285         input_report_abs(dev, ABS_Y, y);
1286 
1287         /* report buttons */
1288         input_report_key(dev, BTN_TL, btns & JC_BTN_L);
1289         input_report_key(dev, BTN_TL2, btns & JC_BTN_ZL);
1290         input_report_key(dev, BTN_SELECT, btns & JC_BTN_MINUS);
1291         input_report_key(dev, BTN_THUMBL, btns & JC_BTN_LSTICK);
1292         input_report_key(dev, BTN_Z, btns & JC_BTN_CAP);
1293 
1294         if (jc_type_is_joycon(ctlr)) {
1295             /* Report the S buttons as the non-existent triggers */
1296             input_report_key(dev, BTN_TR, btns & JC_BTN_SL_L);
1297             input_report_key(dev, BTN_TR2, btns & JC_BTN_SR_L);
1298 
1299             /* Report d-pad as digital buttons for the joy-cons */
1300             input_report_key(dev, BTN_DPAD_DOWN,
1301                      btns & JC_BTN_DOWN);
1302             input_report_key(dev, BTN_DPAD_UP, btns & JC_BTN_UP);
1303             input_report_key(dev, BTN_DPAD_RIGHT,
1304                      btns & JC_BTN_RIGHT);
1305             input_report_key(dev, BTN_DPAD_LEFT,
1306                      btns & JC_BTN_LEFT);
1307         } else {
1308             int hatx = 0;
1309             int haty = 0;
1310 
1311             /* d-pad x */
1312             if (btns & JC_BTN_LEFT)
1313                 hatx = -1;
1314             else if (btns & JC_BTN_RIGHT)
1315                 hatx = 1;
1316             input_report_abs(dev, ABS_HAT0X, hatx);
1317 
1318             /* d-pad y */
1319             if (btns & JC_BTN_UP)
1320                 haty = -1;
1321             else if (btns & JC_BTN_DOWN)
1322                 haty = 1;
1323             input_report_abs(dev, ABS_HAT0Y, haty);
1324         }
1325     }
1326     if (jc_type_has_right(ctlr)) {
1327         u16 raw_x;
1328         u16 raw_y;
1329         s32 x;
1330         s32 y;
1331 
1332         /* get raw stick values */
1333         raw_x = hid_field_extract(ctlr->hdev, rep->right_stick, 0, 12);
1334         raw_y = hid_field_extract(ctlr->hdev,
1335                       rep->right_stick + 1, 4, 12);
1336         /* map stick values */
1337         x = joycon_map_stick_val(&ctlr->right_stick_cal_x, raw_x);
1338         y = -joycon_map_stick_val(&ctlr->right_stick_cal_y, raw_y);
1339         /* report sticks */
1340         input_report_abs(dev, ABS_RX, x);
1341         input_report_abs(dev, ABS_RY, y);
1342 
1343         /* report buttons */
1344         input_report_key(dev, BTN_TR, btns & JC_BTN_R);
1345         input_report_key(dev, BTN_TR2, btns & JC_BTN_ZR);
1346         if (jc_type_is_joycon(ctlr)) {
1347             /* Report the S buttons as the non-existent triggers */
1348             input_report_key(dev, BTN_TL, btns & JC_BTN_SL_R);
1349             input_report_key(dev, BTN_TL2, btns & JC_BTN_SR_R);
1350         }
1351         input_report_key(dev, BTN_START, btns & JC_BTN_PLUS);
1352         input_report_key(dev, BTN_THUMBR, btns & JC_BTN_RSTICK);
1353         input_report_key(dev, BTN_MODE, btns & JC_BTN_HOME);
1354         input_report_key(dev, BTN_WEST, btns & JC_BTN_Y);
1355         input_report_key(dev, BTN_NORTH, btns & JC_BTN_X);
1356         input_report_key(dev, BTN_EAST, btns & JC_BTN_A);
1357         input_report_key(dev, BTN_SOUTH, btns & JC_BTN_B);
1358     }
1359 
1360     input_sync(dev);
1361 
1362     /*
1363      * Immediately after receiving a report is the most reliable time to
1364      * send a subcommand to the controller. Wake any subcommand senders
1365      * waiting for a report.
1366      */
1367     if (unlikely(mutex_is_locked(&ctlr->output_mutex))) {
1368         spin_lock_irqsave(&ctlr->lock, flags);
1369         ctlr->received_input_report = true;
1370         spin_unlock_irqrestore(&ctlr->lock, flags);
1371         wake_up(&ctlr->wait);
1372     }
1373 
1374     /* parse IMU data if present */
1375     if (rep->id == JC_INPUT_IMU_DATA)
1376         joycon_parse_imu_report(ctlr, rep);
1377 }
1378 
1379 static int joycon_send_rumble_data(struct joycon_ctlr *ctlr)
1380 {
1381     int ret;
1382     unsigned long flags;
1383     struct joycon_rumble_output rumble_output = { 0 };
1384 
1385     spin_lock_irqsave(&ctlr->lock, flags);
1386     /*
1387      * If the controller has been removed, just return ENODEV so the LED
1388      * subsystem doesn't print invalid errors on removal.
1389      */
1390     if (ctlr->ctlr_state == JOYCON_CTLR_STATE_REMOVED) {
1391         spin_unlock_irqrestore(&ctlr->lock, flags);
1392         return -ENODEV;
1393     }
1394     memcpy(rumble_output.rumble_data,
1395            ctlr->rumble_data[ctlr->rumble_queue_tail],
1396            JC_RUMBLE_DATA_SIZE);
1397     spin_unlock_irqrestore(&ctlr->lock, flags);
1398 
1399     rumble_output.output_id = JC_OUTPUT_RUMBLE_ONLY;
1400     rumble_output.packet_num = ctlr->subcmd_num;
1401     if (++ctlr->subcmd_num > 0xF)
1402         ctlr->subcmd_num = 0;
1403 
1404     joycon_enforce_subcmd_rate(ctlr);
1405 
1406     ret = __joycon_hid_send(ctlr->hdev, (u8 *)&rumble_output,
1407                 sizeof(rumble_output));
1408     return ret;
1409 }
1410 
1411 static void joycon_rumble_worker(struct work_struct *work)
1412 {
1413     struct joycon_ctlr *ctlr = container_of(work, struct joycon_ctlr,
1414                             rumble_worker);
1415     unsigned long flags;
1416     bool again = true;
1417     int ret;
1418 
1419     while (again) {
1420         mutex_lock(&ctlr->output_mutex);
1421         ret = joycon_send_rumble_data(ctlr);
1422         mutex_unlock(&ctlr->output_mutex);
1423 
1424         /* -ENODEV means the controller was just unplugged */
1425         spin_lock_irqsave(&ctlr->lock, flags);
1426         if (ret < 0 && ret != -ENODEV &&
1427             ctlr->ctlr_state != JOYCON_CTLR_STATE_REMOVED)
1428             hid_warn(ctlr->hdev, "Failed to set rumble; e=%d", ret);
1429 
1430         ctlr->rumble_msecs = jiffies_to_msecs(jiffies);
1431         if (ctlr->rumble_queue_tail != ctlr->rumble_queue_head) {
1432             if (++ctlr->rumble_queue_tail >= JC_RUMBLE_QUEUE_SIZE)
1433                 ctlr->rumble_queue_tail = 0;
1434         } else {
1435             again = false;
1436         }
1437         spin_unlock_irqrestore(&ctlr->lock, flags);
1438     }
1439 }
1440 
1441 #if IS_ENABLED(CONFIG_NINTENDO_FF)
1442 static struct joycon_rumble_freq_data joycon_find_rumble_freq(u16 freq)
1443 {
1444     const size_t length = ARRAY_SIZE(joycon_rumble_frequencies);
1445     const struct joycon_rumble_freq_data *data = joycon_rumble_frequencies;
1446     int i = 0;
1447 
1448     if (freq > data[0].freq) {
1449         for (i = 1; i < length - 1; i++) {
1450             if (freq > data[i - 1].freq && freq <= data[i].freq)
1451                 break;
1452         }
1453     }
1454 
1455     return data[i];
1456 }
1457 
1458 static struct joycon_rumble_amp_data joycon_find_rumble_amp(u16 amp)
1459 {
1460     const size_t length = ARRAY_SIZE(joycon_rumble_amplitudes);
1461     const struct joycon_rumble_amp_data *data = joycon_rumble_amplitudes;
1462     int i = 0;
1463 
1464     if (amp > data[0].amp) {
1465         for (i = 1; i < length - 1; i++) {
1466             if (amp > data[i - 1].amp && amp <= data[i].amp)
1467                 break;
1468         }
1469     }
1470 
1471     return data[i];
1472 }
1473 
1474 static void joycon_encode_rumble(u8 *data, u16 freq_low, u16 freq_high, u16 amp)
1475 {
1476     struct joycon_rumble_freq_data freq_data_low;
1477     struct joycon_rumble_freq_data freq_data_high;
1478     struct joycon_rumble_amp_data amp_data;
1479 
1480     freq_data_low = joycon_find_rumble_freq(freq_low);
1481     freq_data_high = joycon_find_rumble_freq(freq_high);
1482     amp_data = joycon_find_rumble_amp(amp);
1483 
1484     data[0] = (freq_data_high.high >> 8) & 0xFF;
1485     data[1] = (freq_data_high.high & 0xFF) + amp_data.high;
1486     data[2] = freq_data_low.low + ((amp_data.low >> 8) & 0xFF);
1487     data[3] = amp_data.low & 0xFF;
1488 }
1489 
1490 static const u16 JOYCON_MAX_RUMBLE_HIGH_FREQ    = 1253;
1491 static const u16 JOYCON_MIN_RUMBLE_HIGH_FREQ    = 82;
1492 static const u16 JOYCON_MAX_RUMBLE_LOW_FREQ = 626;
1493 static const u16 JOYCON_MIN_RUMBLE_LOW_FREQ = 41;
1494 
1495 static void joycon_clamp_rumble_freqs(struct joycon_ctlr *ctlr)
1496 {
1497     unsigned long flags;
1498 
1499     spin_lock_irqsave(&ctlr->lock, flags);
1500     ctlr->rumble_ll_freq = clamp(ctlr->rumble_ll_freq,
1501                      JOYCON_MIN_RUMBLE_LOW_FREQ,
1502                      JOYCON_MAX_RUMBLE_LOW_FREQ);
1503     ctlr->rumble_lh_freq = clamp(ctlr->rumble_lh_freq,
1504                      JOYCON_MIN_RUMBLE_HIGH_FREQ,
1505                      JOYCON_MAX_RUMBLE_HIGH_FREQ);
1506     ctlr->rumble_rl_freq = clamp(ctlr->rumble_rl_freq,
1507                      JOYCON_MIN_RUMBLE_LOW_FREQ,
1508                      JOYCON_MAX_RUMBLE_LOW_FREQ);
1509     ctlr->rumble_rh_freq = clamp(ctlr->rumble_rh_freq,
1510                      JOYCON_MIN_RUMBLE_HIGH_FREQ,
1511                      JOYCON_MAX_RUMBLE_HIGH_FREQ);
1512     spin_unlock_irqrestore(&ctlr->lock, flags);
1513 }
1514 
1515 static int joycon_set_rumble(struct joycon_ctlr *ctlr, u16 amp_r, u16 amp_l,
1516                  bool schedule_now)
1517 {
1518     u8 data[JC_RUMBLE_DATA_SIZE];
1519     u16 amp;
1520     u16 freq_r_low;
1521     u16 freq_r_high;
1522     u16 freq_l_low;
1523     u16 freq_l_high;
1524     unsigned long flags;
1525 
1526     spin_lock_irqsave(&ctlr->lock, flags);
1527     freq_r_low = ctlr->rumble_rl_freq;
1528     freq_r_high = ctlr->rumble_rh_freq;
1529     freq_l_low = ctlr->rumble_ll_freq;
1530     freq_l_high = ctlr->rumble_lh_freq;
1531     /* limit number of silent rumble packets to reduce traffic */
1532     if (amp_l != 0 || amp_r != 0)
1533         ctlr->rumble_zero_countdown = JC_RUMBLE_ZERO_AMP_PKT_CNT;
1534     spin_unlock_irqrestore(&ctlr->lock, flags);
1535 
1536     /* right joy-con */
1537     amp = amp_r * (u32)joycon_max_rumble_amp / 65535;
1538     joycon_encode_rumble(data + 4, freq_r_low, freq_r_high, amp);
1539 
1540     /* left joy-con */
1541     amp = amp_l * (u32)joycon_max_rumble_amp / 65535;
1542     joycon_encode_rumble(data, freq_l_low, freq_l_high, amp);
1543 
1544     spin_lock_irqsave(&ctlr->lock, flags);
1545     if (++ctlr->rumble_queue_head >= JC_RUMBLE_QUEUE_SIZE)
1546         ctlr->rumble_queue_head = 0;
1547     memcpy(ctlr->rumble_data[ctlr->rumble_queue_head], data,
1548            JC_RUMBLE_DATA_SIZE);
1549 
1550     /* don't wait for the periodic send (reduces latency) */
1551     if (schedule_now && ctlr->ctlr_state != JOYCON_CTLR_STATE_REMOVED)
1552         queue_work(ctlr->rumble_queue, &ctlr->rumble_worker);
1553 
1554     spin_unlock_irqrestore(&ctlr->lock, flags);
1555 
1556     return 0;
1557 }
1558 
1559 static int joycon_play_effect(struct input_dev *dev, void *data,
1560                              struct ff_effect *effect)
1561 {
1562     struct joycon_ctlr *ctlr = input_get_drvdata(dev);
1563 
1564     if (effect->type != FF_RUMBLE)
1565         return 0;
1566 
1567     return joycon_set_rumble(ctlr,
1568                  effect->u.rumble.weak_magnitude,
1569                  effect->u.rumble.strong_magnitude,
1570                  true);
1571 }
1572 #endif /* IS_ENABLED(CONFIG_NINTENDO_FF) */
1573 
1574 static const unsigned int joycon_button_inputs_l[] = {
1575     BTN_SELECT, BTN_Z, BTN_THUMBL,
1576     BTN_TL, BTN_TL2,
1577     0 /* 0 signals end of array */
1578 };
1579 
1580 static const unsigned int joycon_button_inputs_r[] = {
1581     BTN_START, BTN_MODE, BTN_THUMBR,
1582     BTN_SOUTH, BTN_EAST, BTN_NORTH, BTN_WEST,
1583     BTN_TR, BTN_TR2,
1584     0 /* 0 signals end of array */
1585 };
1586 
1587 /* We report joy-con d-pad inputs as buttons and pro controller as a hat. */
1588 static const unsigned int joycon_dpad_inputs_jc[] = {
1589     BTN_DPAD_UP, BTN_DPAD_DOWN, BTN_DPAD_LEFT, BTN_DPAD_RIGHT,
1590     0 /* 0 signals end of array */
1591 };
1592 
1593 static int joycon_input_create(struct joycon_ctlr *ctlr)
1594 {
1595     struct hid_device *hdev;
1596     const char *name;
1597     const char *imu_name;
1598     int ret;
1599     int i;
1600 
1601     hdev = ctlr->hdev;
1602 
1603     switch (hdev->product) {
1604     case USB_DEVICE_ID_NINTENDO_PROCON:
1605         name = "Nintendo Switch Pro Controller";
1606         imu_name = "Nintendo Switch Pro Controller IMU";
1607         break;
1608     case USB_DEVICE_ID_NINTENDO_CHRGGRIP:
1609         if (jc_type_has_left(ctlr)) {
1610             name = "Nintendo Switch Left Joy-Con (Grip)";
1611             imu_name = "Nintendo Switch Left Joy-Con IMU (Grip)";
1612         } else {
1613             name = "Nintendo Switch Right Joy-Con (Grip)";
1614             imu_name = "Nintendo Switch Right Joy-Con IMU (Grip)";
1615         }
1616         break;
1617     case USB_DEVICE_ID_NINTENDO_JOYCONL:
1618         name = "Nintendo Switch Left Joy-Con";
1619         imu_name = "Nintendo Switch Left Joy-Con IMU";
1620         break;
1621     case USB_DEVICE_ID_NINTENDO_JOYCONR:
1622         name = "Nintendo Switch Right Joy-Con";
1623         imu_name = "Nintendo Switch Right Joy-Con IMU";
1624         break;
1625     default: /* Should be impossible */
1626         hid_err(hdev, "Invalid hid product\n");
1627         return -EINVAL;
1628     }
1629 
1630     ctlr->input = devm_input_allocate_device(&hdev->dev);
1631     if (!ctlr->input)
1632         return -ENOMEM;
1633     ctlr->input->id.bustype = hdev->bus;
1634     ctlr->input->id.vendor = hdev->vendor;
1635     ctlr->input->id.product = hdev->product;
1636     ctlr->input->id.version = hdev->version;
1637     ctlr->input->uniq = ctlr->mac_addr_str;
1638     ctlr->input->name = name;
1639     ctlr->input->phys = hdev->phys;
1640     input_set_drvdata(ctlr->input, ctlr);
1641 
1642     /* set up sticks and buttons */
1643     if (jc_type_has_left(ctlr)) {
1644         input_set_abs_params(ctlr->input, ABS_X,
1645                      -JC_MAX_STICK_MAG, JC_MAX_STICK_MAG,
1646                      JC_STICK_FUZZ, JC_STICK_FLAT);
1647         input_set_abs_params(ctlr->input, ABS_Y,
1648                      -JC_MAX_STICK_MAG, JC_MAX_STICK_MAG,
1649                      JC_STICK_FUZZ, JC_STICK_FLAT);
1650 
1651         for (i = 0; joycon_button_inputs_l[i] > 0; i++)
1652             input_set_capability(ctlr->input, EV_KEY,
1653                          joycon_button_inputs_l[i]);
1654 
1655         /* configure d-pad differently for joy-con vs pro controller */
1656         if (hdev->product != USB_DEVICE_ID_NINTENDO_PROCON) {
1657             for (i = 0; joycon_dpad_inputs_jc[i] > 0; i++)
1658                 input_set_capability(ctlr->input, EV_KEY,
1659                              joycon_dpad_inputs_jc[i]);
1660         } else {
1661             input_set_abs_params(ctlr->input, ABS_HAT0X,
1662                          -JC_MAX_DPAD_MAG, JC_MAX_DPAD_MAG,
1663                          JC_DPAD_FUZZ, JC_DPAD_FLAT);
1664             input_set_abs_params(ctlr->input, ABS_HAT0Y,
1665                          -JC_MAX_DPAD_MAG, JC_MAX_DPAD_MAG,
1666                          JC_DPAD_FUZZ, JC_DPAD_FLAT);
1667         }
1668     }
1669     if (jc_type_has_right(ctlr)) {
1670         input_set_abs_params(ctlr->input, ABS_RX,
1671                      -JC_MAX_STICK_MAG, JC_MAX_STICK_MAG,
1672                      JC_STICK_FUZZ, JC_STICK_FLAT);
1673         input_set_abs_params(ctlr->input, ABS_RY,
1674                      -JC_MAX_STICK_MAG, JC_MAX_STICK_MAG,
1675                      JC_STICK_FUZZ, JC_STICK_FLAT);
1676 
1677         for (i = 0; joycon_button_inputs_r[i] > 0; i++)
1678             input_set_capability(ctlr->input, EV_KEY,
1679                          joycon_button_inputs_r[i]);
1680     }
1681 
1682     /* Let's report joy-con S triggers separately */
1683     if (hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONL) {
1684         input_set_capability(ctlr->input, EV_KEY, BTN_TR);
1685         input_set_capability(ctlr->input, EV_KEY, BTN_TR2);
1686     } else if (hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONR) {
1687         input_set_capability(ctlr->input, EV_KEY, BTN_TL);
1688         input_set_capability(ctlr->input, EV_KEY, BTN_TL2);
1689     }
1690 
1691 #if IS_ENABLED(CONFIG_NINTENDO_FF)
1692     /* set up rumble */
1693     input_set_capability(ctlr->input, EV_FF, FF_RUMBLE);
1694     input_ff_create_memless(ctlr->input, NULL, joycon_play_effect);
1695     ctlr->rumble_ll_freq = JC_RUMBLE_DFLT_LOW_FREQ;
1696     ctlr->rumble_lh_freq = JC_RUMBLE_DFLT_HIGH_FREQ;
1697     ctlr->rumble_rl_freq = JC_RUMBLE_DFLT_LOW_FREQ;
1698     ctlr->rumble_rh_freq = JC_RUMBLE_DFLT_HIGH_FREQ;
1699     joycon_clamp_rumble_freqs(ctlr);
1700     joycon_set_rumble(ctlr, 0, 0, false);
1701     ctlr->rumble_msecs = jiffies_to_msecs(jiffies);
1702 #endif
1703 
1704     ret = input_register_device(ctlr->input);
1705     if (ret)
1706         return ret;
1707 
1708     /* configure the imu input device */
1709     ctlr->imu_input = devm_input_allocate_device(&hdev->dev);
1710     if (!ctlr->imu_input)
1711         return -ENOMEM;
1712 
1713     ctlr->imu_input->id.bustype = hdev->bus;
1714     ctlr->imu_input->id.vendor = hdev->vendor;
1715     ctlr->imu_input->id.product = hdev->product;
1716     ctlr->imu_input->id.version = hdev->version;
1717     ctlr->imu_input->uniq = ctlr->mac_addr_str;
1718     ctlr->imu_input->name = imu_name;
1719     ctlr->imu_input->phys = hdev->phys;
1720     input_set_drvdata(ctlr->imu_input, ctlr);
1721 
1722     /* configure imu axes */
1723     input_set_abs_params(ctlr->imu_input, ABS_X,
1724                  -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG,
1725                  JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT);
1726     input_set_abs_params(ctlr->imu_input, ABS_Y,
1727                  -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG,
1728                  JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT);
1729     input_set_abs_params(ctlr->imu_input, ABS_Z,
1730                  -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG,
1731                  JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT);
1732     input_abs_set_res(ctlr->imu_input, ABS_X, JC_IMU_ACCEL_RES_PER_G);
1733     input_abs_set_res(ctlr->imu_input, ABS_Y, JC_IMU_ACCEL_RES_PER_G);
1734     input_abs_set_res(ctlr->imu_input, ABS_Z, JC_IMU_ACCEL_RES_PER_G);
1735 
1736     input_set_abs_params(ctlr->imu_input, ABS_RX,
1737                  -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG,
1738                  JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT);
1739     input_set_abs_params(ctlr->imu_input, ABS_RY,
1740                  -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG,
1741                  JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT);
1742     input_set_abs_params(ctlr->imu_input, ABS_RZ,
1743                  -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG,
1744                  JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT);
1745 
1746     input_abs_set_res(ctlr->imu_input, ABS_RX, JC_IMU_GYRO_RES_PER_DPS);
1747     input_abs_set_res(ctlr->imu_input, ABS_RY, JC_IMU_GYRO_RES_PER_DPS);
1748     input_abs_set_res(ctlr->imu_input, ABS_RZ, JC_IMU_GYRO_RES_PER_DPS);
1749 
1750     __set_bit(EV_MSC, ctlr->imu_input->evbit);
1751     __set_bit(MSC_TIMESTAMP, ctlr->imu_input->mscbit);
1752     __set_bit(INPUT_PROP_ACCELEROMETER, ctlr->imu_input->propbit);
1753 
1754     ret = input_register_device(ctlr->imu_input);
1755     if (ret)
1756         return ret;
1757 
1758     return 0;
1759 }
1760 
1761 static int joycon_player_led_brightness_set(struct led_classdev *led,
1762                         enum led_brightness brightness)
1763 {
1764     struct device *dev = led->dev->parent;
1765     struct hid_device *hdev = to_hid_device(dev);
1766     struct joycon_ctlr *ctlr;
1767     int val = 0;
1768     int i;
1769     int ret;
1770     int num;
1771 
1772     ctlr = hid_get_drvdata(hdev);
1773     if (!ctlr) {
1774         hid_err(hdev, "No controller data\n");
1775         return -ENODEV;
1776     }
1777 
1778     /* determine which player led this is */
1779     for (num = 0; num < JC_NUM_LEDS; num++) {
1780         if (&ctlr->leds[num] == led)
1781             break;
1782     }
1783     if (num >= JC_NUM_LEDS)
1784         return -EINVAL;
1785 
1786     mutex_lock(&ctlr->output_mutex);
1787     for (i = 0; i < JC_NUM_LEDS; i++) {
1788         if (i == num)
1789             val |= brightness << i;
1790         else
1791             val |= ctlr->leds[i].brightness << i;
1792     }
1793     ret = joycon_set_player_leds(ctlr, 0, val);
1794     mutex_unlock(&ctlr->output_mutex);
1795 
1796     return ret;
1797 }
1798 
1799 static int joycon_home_led_brightness_set(struct led_classdev *led,
1800                       enum led_brightness brightness)
1801 {
1802     struct device *dev = led->dev->parent;
1803     struct hid_device *hdev = to_hid_device(dev);
1804     struct joycon_ctlr *ctlr;
1805     struct joycon_subcmd_request *req;
1806     u8 buffer[sizeof(*req) + 5] = { 0 };
1807     u8 *data;
1808     int ret;
1809 
1810     ctlr = hid_get_drvdata(hdev);
1811     if (!ctlr) {
1812         hid_err(hdev, "No controller data\n");
1813         return -ENODEV;
1814     }
1815 
1816     req = (struct joycon_subcmd_request *)buffer;
1817     req->subcmd_id = JC_SUBCMD_SET_HOME_LIGHT;
1818     data = req->data;
1819     data[0] = 0x01;
1820     data[1] = brightness << 4;
1821     data[2] = brightness | (brightness << 4);
1822     data[3] = 0x11;
1823     data[4] = 0x11;
1824 
1825     hid_dbg(hdev, "setting home led brightness\n");
1826     mutex_lock(&ctlr->output_mutex);
1827     ret = joycon_send_subcmd(ctlr, req, 5, HZ/4);
1828     mutex_unlock(&ctlr->output_mutex);
1829 
1830     return ret;
1831 }
1832 
1833 static DEFINE_MUTEX(joycon_input_num_mutex);
1834 static int joycon_leds_create(struct joycon_ctlr *ctlr)
1835 {
1836     struct hid_device *hdev = ctlr->hdev;
1837     struct device *dev = &hdev->dev;
1838     const char *d_name = dev_name(dev);
1839     struct led_classdev *led;
1840     char *name;
1841     int ret = 0;
1842     int i;
1843     static int input_num = 1;
1844 
1845     /* Set the default controller player leds based on controller number */
1846     mutex_lock(&joycon_input_num_mutex);
1847     mutex_lock(&ctlr->output_mutex);
1848     ret = joycon_set_player_leds(ctlr, 0, 0xF >> (4 - input_num));
1849     if (ret)
1850         hid_warn(ctlr->hdev, "Failed to set leds; ret=%d\n", ret);
1851     mutex_unlock(&ctlr->output_mutex);
1852 
1853     /* configure the player LEDs */
1854     for (i = 0; i < JC_NUM_LEDS; i++) {
1855         name = devm_kasprintf(dev, GFP_KERNEL, "%s:%s:%s",
1856                       d_name,
1857                       "green",
1858                       joycon_player_led_names[i]);
1859         if (!name) {
1860             mutex_unlock(&joycon_input_num_mutex);
1861             return -ENOMEM;
1862         }
1863 
1864         led = &ctlr->leds[i];
1865         led->name = name;
1866         led->brightness = ((i + 1) <= input_num) ? 1 : 0;
1867         led->max_brightness = 1;
1868         led->brightness_set_blocking =
1869                     joycon_player_led_brightness_set;
1870         led->flags = LED_CORE_SUSPENDRESUME | LED_HW_PLUGGABLE;
1871 
1872         ret = devm_led_classdev_register(&hdev->dev, led);
1873         if (ret) {
1874             hid_err(hdev, "Failed registering %s LED\n", led->name);
1875             mutex_unlock(&joycon_input_num_mutex);
1876             return ret;
1877         }
1878     }
1879 
1880     if (++input_num > 4)
1881         input_num = 1;
1882     mutex_unlock(&joycon_input_num_mutex);
1883 
1884     /* configure the home LED */
1885     if (jc_type_has_right(ctlr)) {
1886         name = devm_kasprintf(dev, GFP_KERNEL, "%s:%s:%s",
1887                       d_name,
1888                       "blue",
1889                       LED_FUNCTION_PLAYER5);
1890         if (!name)
1891             return -ENOMEM;
1892 
1893         led = &ctlr->home_led;
1894         led->name = name;
1895         led->brightness = 0;
1896         led->max_brightness = 0xF;
1897         led->brightness_set_blocking = joycon_home_led_brightness_set;
1898         led->flags = LED_CORE_SUSPENDRESUME | LED_HW_PLUGGABLE;
1899         ret = devm_led_classdev_register(&hdev->dev, led);
1900         if (ret) {
1901             hid_err(hdev, "Failed registering home led\n");
1902             return ret;
1903         }
1904         /* Set the home LED to 0 as default state */
1905         ret = joycon_home_led_brightness_set(led, 0);
1906         if (ret) {
1907             hid_err(hdev, "Failed to set home LED dflt; ret=%d\n",
1908                                     ret);
1909             return ret;
1910         }
1911     }
1912 
1913     return 0;
1914 }
1915 
1916 static int joycon_battery_get_property(struct power_supply *supply,
1917                        enum power_supply_property prop,
1918                        union power_supply_propval *val)
1919 {
1920     struct joycon_ctlr *ctlr = power_supply_get_drvdata(supply);
1921     unsigned long flags;
1922     int ret = 0;
1923     u8 capacity;
1924     bool charging;
1925     bool powered;
1926 
1927     spin_lock_irqsave(&ctlr->lock, flags);
1928     capacity = ctlr->battery_capacity;
1929     charging = ctlr->battery_charging;
1930     powered = ctlr->host_powered;
1931     spin_unlock_irqrestore(&ctlr->lock, flags);
1932 
1933     switch (prop) {
1934     case POWER_SUPPLY_PROP_PRESENT:
1935         val->intval = 1;
1936         break;
1937     case POWER_SUPPLY_PROP_SCOPE:
1938         val->intval = POWER_SUPPLY_SCOPE_DEVICE;
1939         break;
1940     case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
1941         val->intval = capacity;
1942         break;
1943     case POWER_SUPPLY_PROP_STATUS:
1944         if (charging)
1945             val->intval = POWER_SUPPLY_STATUS_CHARGING;
1946         else if (capacity == POWER_SUPPLY_CAPACITY_LEVEL_FULL &&
1947              powered)
1948             val->intval = POWER_SUPPLY_STATUS_FULL;
1949         else
1950             val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
1951         break;
1952     default:
1953         ret = -EINVAL;
1954         break;
1955     }
1956     return ret;
1957 }
1958 
1959 static enum power_supply_property joycon_battery_props[] = {
1960     POWER_SUPPLY_PROP_PRESENT,
1961     POWER_SUPPLY_PROP_CAPACITY_LEVEL,
1962     POWER_SUPPLY_PROP_SCOPE,
1963     POWER_SUPPLY_PROP_STATUS,
1964 };
1965 
1966 static int joycon_power_supply_create(struct joycon_ctlr *ctlr)
1967 {
1968     struct hid_device *hdev = ctlr->hdev;
1969     struct power_supply_config supply_config = { .drv_data = ctlr, };
1970     const char * const name_fmt = "nintendo_switch_controller_battery_%s";
1971     int ret = 0;
1972 
1973     /* Set initially to unknown before receiving first input report */
1974     ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
1975 
1976     /* Configure the battery's description */
1977     ctlr->battery_desc.properties = joycon_battery_props;
1978     ctlr->battery_desc.num_properties =
1979                     ARRAY_SIZE(joycon_battery_props);
1980     ctlr->battery_desc.get_property = joycon_battery_get_property;
1981     ctlr->battery_desc.type = POWER_SUPPLY_TYPE_BATTERY;
1982     ctlr->battery_desc.use_for_apm = 0;
1983     ctlr->battery_desc.name = devm_kasprintf(&hdev->dev, GFP_KERNEL,
1984                          name_fmt,
1985                          dev_name(&hdev->dev));
1986     if (!ctlr->battery_desc.name)
1987         return -ENOMEM;
1988 
1989     ctlr->battery = devm_power_supply_register(&hdev->dev,
1990                            &ctlr->battery_desc,
1991                            &supply_config);
1992     if (IS_ERR(ctlr->battery)) {
1993         ret = PTR_ERR(ctlr->battery);
1994         hid_err(hdev, "Failed to register battery; ret=%d\n", ret);
1995         return ret;
1996     }
1997 
1998     return power_supply_powers(ctlr->battery, &hdev->dev);
1999 }
2000 
2001 static int joycon_read_info(struct joycon_ctlr *ctlr)
2002 {
2003     int ret;
2004     int i;
2005     int j;
2006     struct joycon_subcmd_request req = { 0 };
2007     struct joycon_input_report *report;
2008 
2009     req.subcmd_id = JC_SUBCMD_REQ_DEV_INFO;
2010     ret = joycon_send_subcmd(ctlr, &req, 0, HZ);
2011     if (ret) {
2012         hid_err(ctlr->hdev, "Failed to get joycon info; ret=%d\n", ret);
2013         return ret;
2014     }
2015 
2016     report = (struct joycon_input_report *)ctlr->input_buf;
2017 
2018     for (i = 4, j = 0; j < 6; i++, j++)
2019         ctlr->mac_addr[j] = report->subcmd_reply.data[i];
2020 
2021     ctlr->mac_addr_str = devm_kasprintf(&ctlr->hdev->dev, GFP_KERNEL,
2022                         "%02X:%02X:%02X:%02X:%02X:%02X",
2023                         ctlr->mac_addr[0],
2024                         ctlr->mac_addr[1],
2025                         ctlr->mac_addr[2],
2026                         ctlr->mac_addr[3],
2027                         ctlr->mac_addr[4],
2028                         ctlr->mac_addr[5]);
2029     if (!ctlr->mac_addr_str)
2030         return -ENOMEM;
2031     hid_info(ctlr->hdev, "controller MAC = %s\n", ctlr->mac_addr_str);
2032 
2033     /* Retrieve the type so we can distinguish for charging grip */
2034     ctlr->ctlr_type = report->subcmd_reply.data[2];
2035 
2036     return 0;
2037 }
2038 
2039 /* Common handler for parsing inputs */
2040 static int joycon_ctlr_read_handler(struct joycon_ctlr *ctlr, u8 *data,
2041                                   int size)
2042 {
2043     if (data[0] == JC_INPUT_SUBCMD_REPLY || data[0] == JC_INPUT_IMU_DATA ||
2044         data[0] == JC_INPUT_MCU_DATA) {
2045         if (size >= 12) /* make sure it contains the input report */
2046             joycon_parse_report(ctlr,
2047                         (struct joycon_input_report *)data);
2048     }
2049 
2050     return 0;
2051 }
2052 
2053 static int joycon_ctlr_handle_event(struct joycon_ctlr *ctlr, u8 *data,
2054                                   int size)
2055 {
2056     int ret = 0;
2057     bool match = false;
2058     struct joycon_input_report *report;
2059 
2060     if (unlikely(mutex_is_locked(&ctlr->output_mutex)) &&
2061         ctlr->msg_type != JOYCON_MSG_TYPE_NONE) {
2062         switch (ctlr->msg_type) {
2063         case JOYCON_MSG_TYPE_USB:
2064             if (size < 2)
2065                 break;
2066             if (data[0] == JC_INPUT_USB_RESPONSE &&
2067                 data[1] == ctlr->usb_ack_match)
2068                 match = true;
2069             break;
2070         case JOYCON_MSG_TYPE_SUBCMD:
2071             if (size < sizeof(struct joycon_input_report) ||
2072                 data[0] != JC_INPUT_SUBCMD_REPLY)
2073                 break;
2074             report = (struct joycon_input_report *)data;
2075             if (report->subcmd_reply.id == ctlr->subcmd_ack_match)
2076                 match = true;
2077             break;
2078         default:
2079             break;
2080         }
2081 
2082         if (match) {
2083             memcpy(ctlr->input_buf, data,
2084                    min(size, (int)JC_MAX_RESP_SIZE));
2085             ctlr->msg_type = JOYCON_MSG_TYPE_NONE;
2086             ctlr->received_resp = true;
2087             wake_up(&ctlr->wait);
2088 
2089             /* This message has been handled */
2090             return 1;
2091         }
2092     }
2093 
2094     if (ctlr->ctlr_state == JOYCON_CTLR_STATE_READ)
2095         ret = joycon_ctlr_read_handler(ctlr, data, size);
2096 
2097     return ret;
2098 }
2099 
2100 static int nintendo_hid_event(struct hid_device *hdev,
2101                   struct hid_report *report, u8 *raw_data, int size)
2102 {
2103     struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
2104 
2105     if (size < 1)
2106         return -EINVAL;
2107 
2108     return joycon_ctlr_handle_event(ctlr, raw_data, size);
2109 }
2110 
2111 static int nintendo_hid_probe(struct hid_device *hdev,
2112                 const struct hid_device_id *id)
2113 {
2114     int ret;
2115     struct joycon_ctlr *ctlr;
2116 
2117     hid_dbg(hdev, "probe - start\n");
2118 
2119     ctlr = devm_kzalloc(&hdev->dev, sizeof(*ctlr), GFP_KERNEL);
2120     if (!ctlr) {
2121         ret = -ENOMEM;
2122         goto err;
2123     }
2124 
2125     ctlr->hdev = hdev;
2126     ctlr->ctlr_state = JOYCON_CTLR_STATE_INIT;
2127     ctlr->rumble_queue_head = JC_RUMBLE_QUEUE_SIZE - 1;
2128     ctlr->rumble_queue_tail = 0;
2129     hid_set_drvdata(hdev, ctlr);
2130     mutex_init(&ctlr->output_mutex);
2131     init_waitqueue_head(&ctlr->wait);
2132     spin_lock_init(&ctlr->lock);
2133     ctlr->rumble_queue = alloc_workqueue("hid-nintendo-rumble_wq",
2134                          WQ_FREEZABLE | WQ_MEM_RECLAIM, 0);
2135     if (!ctlr->rumble_queue) {
2136         ret = -ENOMEM;
2137         goto err;
2138     }
2139     INIT_WORK(&ctlr->rumble_worker, joycon_rumble_worker);
2140 
2141     ret = hid_parse(hdev);
2142     if (ret) {
2143         hid_err(hdev, "HID parse failed\n");
2144         goto err_wq;
2145     }
2146 
2147     /*
2148      * Patch the hw version of pro controller/joycons, so applications can
2149      * distinguish between the default HID mappings and the mappings defined
2150      * by the Linux game controller spec. This is important for the SDL2
2151      * library, which has a game controller database, which uses device ids
2152      * in combination with version as a key.
2153      */
2154     hdev->version |= 0x8000;
2155 
2156     ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
2157     if (ret) {
2158         hid_err(hdev, "HW start failed\n");
2159         goto err_wq;
2160     }
2161 
2162     ret = hid_hw_open(hdev);
2163     if (ret) {
2164         hid_err(hdev, "cannot start hardware I/O\n");
2165         goto err_stop;
2166     }
2167 
2168     hid_device_io_start(hdev);
2169 
2170     /* Initialize the controller */
2171     mutex_lock(&ctlr->output_mutex);
2172     /* if handshake command fails, assume ble pro controller */
2173     if ((jc_type_is_procon(ctlr) || jc_type_is_chrggrip(ctlr)) &&
2174         !joycon_send_usb(ctlr, JC_USB_CMD_HANDSHAKE, HZ)) {
2175         hid_dbg(hdev, "detected USB controller\n");
2176         /* set baudrate for improved latency */
2177         ret = joycon_send_usb(ctlr, JC_USB_CMD_BAUDRATE_3M, HZ);
2178         if (ret) {
2179             hid_err(hdev, "Failed to set baudrate; ret=%d\n", ret);
2180             goto err_mutex;
2181         }
2182         /* handshake */
2183         ret = joycon_send_usb(ctlr, JC_USB_CMD_HANDSHAKE, HZ);
2184         if (ret) {
2185             hid_err(hdev, "Failed handshake; ret=%d\n", ret);
2186             goto err_mutex;
2187         }
2188         /*
2189          * Set no timeout (to keep controller in USB mode).
2190          * This doesn't send a response, so ignore the timeout.
2191          */
2192         joycon_send_usb(ctlr, JC_USB_CMD_NO_TIMEOUT, HZ/10);
2193     } else if (jc_type_is_chrggrip(ctlr)) {
2194         hid_err(hdev, "Failed charging grip handshake\n");
2195         ret = -ETIMEDOUT;
2196         goto err_mutex;
2197     }
2198 
2199     /* get controller calibration data, and parse it */
2200     ret = joycon_request_calibration(ctlr);
2201     if (ret) {
2202         /*
2203          * We can function with default calibration, but it may be
2204          * inaccurate. Provide a warning, and continue on.
2205          */
2206         hid_warn(hdev, "Analog stick positions may be inaccurate\n");
2207     }
2208 
2209     /* get IMU calibration data, and parse it */
2210     ret = joycon_request_imu_calibration(ctlr);
2211     if (ret) {
2212         /*
2213          * We can function with default calibration, but it may be
2214          * inaccurate. Provide a warning, and continue on.
2215          */
2216         hid_warn(hdev, "Unable to read IMU calibration data\n");
2217     }
2218 
2219     /* Set the reporting mode to 0x30, which is the full report mode */
2220     ret = joycon_set_report_mode(ctlr);
2221     if (ret) {
2222         hid_err(hdev, "Failed to set report mode; ret=%d\n", ret);
2223         goto err_mutex;
2224     }
2225 
2226     /* Enable rumble */
2227     ret = joycon_enable_rumble(ctlr);
2228     if (ret) {
2229         hid_err(hdev, "Failed to enable rumble; ret=%d\n", ret);
2230         goto err_mutex;
2231     }
2232 
2233     /* Enable the IMU */
2234     ret = joycon_enable_imu(ctlr);
2235     if (ret) {
2236         hid_err(hdev, "Failed to enable the IMU; ret=%d\n", ret);
2237         goto err_mutex;
2238     }
2239 
2240     ret = joycon_read_info(ctlr);
2241     if (ret) {
2242         hid_err(hdev, "Failed to retrieve controller info; ret=%d\n",
2243             ret);
2244         goto err_mutex;
2245     }
2246 
2247     mutex_unlock(&ctlr->output_mutex);
2248 
2249     /* Initialize the leds */
2250     ret = joycon_leds_create(ctlr);
2251     if (ret) {
2252         hid_err(hdev, "Failed to create leds; ret=%d\n", ret);
2253         goto err_close;
2254     }
2255 
2256     /* Initialize the battery power supply */
2257     ret = joycon_power_supply_create(ctlr);
2258     if (ret) {
2259         hid_err(hdev, "Failed to create power_supply; ret=%d\n", ret);
2260         goto err_close;
2261     }
2262 
2263     ret = joycon_input_create(ctlr);
2264     if (ret) {
2265         hid_err(hdev, "Failed to create input device; ret=%d\n", ret);
2266         goto err_close;
2267     }
2268 
2269     ctlr->ctlr_state = JOYCON_CTLR_STATE_READ;
2270 
2271     hid_dbg(hdev, "probe - success\n");
2272     return 0;
2273 
2274 err_mutex:
2275     mutex_unlock(&ctlr->output_mutex);
2276 err_close:
2277     hid_hw_close(hdev);
2278 err_stop:
2279     hid_hw_stop(hdev);
2280 err_wq:
2281     destroy_workqueue(ctlr->rumble_queue);
2282 err:
2283     hid_err(hdev, "probe - fail = %d\n", ret);
2284     return ret;
2285 }
2286 
2287 static void nintendo_hid_remove(struct hid_device *hdev)
2288 {
2289     struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
2290     unsigned long flags;
2291 
2292     hid_dbg(hdev, "remove\n");
2293 
2294     /* Prevent further attempts at sending subcommands. */
2295     spin_lock_irqsave(&ctlr->lock, flags);
2296     ctlr->ctlr_state = JOYCON_CTLR_STATE_REMOVED;
2297     spin_unlock_irqrestore(&ctlr->lock, flags);
2298 
2299     destroy_workqueue(ctlr->rumble_queue);
2300 
2301     hid_hw_close(hdev);
2302     hid_hw_stop(hdev);
2303 }
2304 
2305 static const struct hid_device_id nintendo_hid_devices[] = {
2306     { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
2307              USB_DEVICE_ID_NINTENDO_PROCON) },
2308     { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
2309              USB_DEVICE_ID_NINTENDO_PROCON) },
2310     { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
2311              USB_DEVICE_ID_NINTENDO_CHRGGRIP) },
2312     { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
2313              USB_DEVICE_ID_NINTENDO_JOYCONL) },
2314     { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
2315              USB_DEVICE_ID_NINTENDO_JOYCONR) },
2316     { }
2317 };
2318 MODULE_DEVICE_TABLE(hid, nintendo_hid_devices);
2319 
2320 static struct hid_driver nintendo_hid_driver = {
2321     .name       = "nintendo",
2322     .id_table   = nintendo_hid_devices,
2323     .probe      = nintendo_hid_probe,
2324     .remove     = nintendo_hid_remove,
2325     .raw_event  = nintendo_hid_event,
2326 };
2327 module_hid_driver(nintendo_hid_driver);
2328 
2329 MODULE_LICENSE("GPL");
2330 MODULE_AUTHOR("Daniel J. Ogorchock <djogorchock@gmail.com>");
2331 MODULE_DESCRIPTION("Driver for Nintendo Switch Controllers");
2332