1 // SPDX-License-Identifier: GPL-2.0+ 2 /* 3 * HID driver for Nintendo Switch Joy-Cons and Pro Controllers 4 * 5 * Copyright (c) 2019-2021 Daniel J. Ogorchock <djogorchock@gmail.com> 6 * Portions Copyright (c) 2020 Nadia Holmquist Pedersen <nadia@nhp.sh> 7 * Copyright (c) 2022 Emily Strickland <linux@emily.st> 8 * Copyright (c) 2023 Ryan McClelland <rymcclel@gmail.com> 9 * 10 * The following resources/projects were referenced for this driver: 11 * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering 12 * https://gitlab.com/pjranki/joycon-linux-kernel (Peter Rankin) 13 * https://github.com/FrotBot/SwitchProConLinuxUSB 14 * https://github.com/MTCKC/ProconXInput 15 * https://github.com/Davidobot/BetterJoyForCemu 16 * hid-wiimote kernel hid driver 17 * hid-logitech-hidpp driver 18 * hid-sony driver 19 * 20 * This driver supports the Nintendo Switch Joy-Cons and Pro Controllers. The 21 * Pro Controllers can either be used over USB or Bluetooth. 22 * 23 * This driver also incorporates support for Nintendo Switch Online controllers 24 * for the NES, SNES, Sega Genesis, and N64. 25 * 26 * The driver will retrieve the factory calibration info from the controllers, 27 * so little to no user calibration should be required. 28 * 29 */ 30 31 #include "hid-ids.h" 32 #include <linux/unaligned.h> 33 #include <linux/delay.h> 34 #include <linux/device.h> 35 #include <linux/kernel.h> 36 #include <linux/hid.h> 37 #include <linux/idr.h> 38 #include <linux/input.h> 39 #include <linux/jiffies.h> 40 #include <linux/leds.h> 41 #include <linux/module.h> 42 #include <linux/power_supply.h> 43 #include <linux/spinlock.h> 44 45 /* 46 * Reference the url below for the following HID report defines: 47 * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering 48 */ 49 50 /* Output Reports */ 51 #define JC_OUTPUT_RUMBLE_AND_SUBCMD 0x01 52 #define JC_OUTPUT_FW_UPDATE_PKT 0x03 53 #define JC_OUTPUT_RUMBLE_ONLY 0x10 54 #define JC_OUTPUT_MCU_DATA 0x11 55 #define JC_OUTPUT_USB_CMD 0x80 56 57 /* Subcommand IDs */ 58 #define JC_SUBCMD_STATE 0x00 59 #define JC_SUBCMD_MANUAL_BT_PAIRING 0x01 60 #define JC_SUBCMD_REQ_DEV_INFO 0x02 61 #define JC_SUBCMD_SET_REPORT_MODE 0x03 62 #define JC_SUBCMD_TRIGGERS_ELAPSED 0x04 63 #define JC_SUBCMD_GET_PAGE_LIST_STATE 0x05 64 #define JC_SUBCMD_SET_HCI_STATE 0x06 65 #define JC_SUBCMD_RESET_PAIRING_INFO 0x07 66 #define JC_SUBCMD_LOW_POWER_MODE 0x08 67 #define JC_SUBCMD_SPI_FLASH_READ 0x10 68 #define JC_SUBCMD_SPI_FLASH_WRITE 0x11 69 #define JC_SUBCMD_RESET_MCU 0x20 70 #define JC_SUBCMD_SET_MCU_CONFIG 0x21 71 #define JC_SUBCMD_SET_MCU_STATE 0x22 72 #define JC_SUBCMD_SET_PLAYER_LIGHTS 0x30 73 #define JC_SUBCMD_GET_PLAYER_LIGHTS 0x31 74 #define JC_SUBCMD_SET_HOME_LIGHT 0x38 75 #define JC_SUBCMD_ENABLE_IMU 0x40 76 #define JC_SUBCMD_SET_IMU_SENSITIVITY 0x41 77 #define JC_SUBCMD_WRITE_IMU_REG 0x42 78 #define JC_SUBCMD_READ_IMU_REG 0x43 79 #define JC_SUBCMD_ENABLE_VIBRATION 0x48 80 #define JC_SUBCMD_GET_REGULATED_VOLTAGE 0x50 81 82 /* Input Reports */ 83 #define JC_INPUT_BUTTON_EVENT 0x3F 84 #define JC_INPUT_SUBCMD_REPLY 0x21 85 #define JC_INPUT_IMU_DATA 0x30 86 #define JC_INPUT_MCU_DATA 0x31 87 #define JC_INPUT_USB_RESPONSE 0x81 88 89 /* Feature Reports */ 90 #define JC_FEATURE_LAST_SUBCMD 0x02 91 #define JC_FEATURE_OTA_FW_UPGRADE 0x70 92 #define JC_FEATURE_SETUP_MEM_READ 0x71 93 #define JC_FEATURE_MEM_READ 0x72 94 #define JC_FEATURE_ERASE_MEM_SECTOR 0x73 95 #define JC_FEATURE_MEM_WRITE 0x74 96 #define JC_FEATURE_LAUNCH 0x75 97 98 /* USB Commands */ 99 #define JC_USB_CMD_CONN_STATUS 0x01 100 #define JC_USB_CMD_HANDSHAKE 0x02 101 #define JC_USB_CMD_BAUDRATE_3M 0x03 102 #define JC_USB_CMD_NO_TIMEOUT 0x04 103 #define JC_USB_CMD_EN_TIMEOUT 0x05 104 #define JC_USB_RESET 0x06 105 #define JC_USB_PRE_HANDSHAKE 0x91 106 #define JC_USB_SEND_UART 0x92 107 108 /* Magic value denoting presence of user calibration */ 109 #define JC_CAL_USR_MAGIC_0 0xB2 110 #define JC_CAL_USR_MAGIC_1 0xA1 111 #define JC_CAL_USR_MAGIC_SIZE 2 112 113 /* SPI storage addresses of user calibration data */ 114 #define JC_CAL_USR_LEFT_MAGIC_ADDR 0x8010 115 #define JC_CAL_USR_LEFT_DATA_ADDR 0x8012 116 #define JC_CAL_USR_LEFT_DATA_END 0x801A 117 #define JC_CAL_USR_RIGHT_MAGIC_ADDR 0x801B 118 #define JC_CAL_USR_RIGHT_DATA_ADDR 0x801D 119 #define JC_CAL_STICK_DATA_SIZE \ 120 (JC_CAL_USR_LEFT_DATA_END - JC_CAL_USR_LEFT_DATA_ADDR + 1) 121 122 /* SPI storage addresses of factory calibration data */ 123 #define JC_CAL_FCT_DATA_LEFT_ADDR 0x603d 124 #define JC_CAL_FCT_DATA_RIGHT_ADDR 0x6046 125 126 /* SPI storage addresses of IMU factory calibration data */ 127 #define JC_IMU_CAL_FCT_DATA_ADDR 0x6020 128 #define JC_IMU_CAL_FCT_DATA_END 0x6037 129 #define JC_IMU_CAL_DATA_SIZE \ 130 (JC_IMU_CAL_FCT_DATA_END - JC_IMU_CAL_FCT_DATA_ADDR + 1) 131 /* SPI storage addresses of IMU user calibration data */ 132 #define JC_IMU_CAL_USR_MAGIC_ADDR 0x8026 133 #define JC_IMU_CAL_USR_DATA_ADDR 0x8028 134 135 /* The raw analog joystick values will be mapped in terms of this magnitude */ 136 #define JC_MAX_STICK_MAG 32767 137 #define JC_STICK_FUZZ 250 138 #define JC_STICK_FLAT 500 139 140 /* Hat values for pro controller's d-pad */ 141 #define JC_MAX_DPAD_MAG 1 142 #define JC_DPAD_FUZZ 0 143 #define JC_DPAD_FLAT 0 144 145 /* Under most circumstances IMU reports are pushed every 15ms; use as default */ 146 #define JC_IMU_DFLT_AVG_DELTA_MS 15 147 /* How many samples to sum before calculating average IMU report delta */ 148 #define JC_IMU_SAMPLES_PER_DELTA_AVG 300 149 /* Controls how many dropped IMU packets at once trigger a warning message */ 150 #define JC_IMU_DROPPED_PKT_WARNING 3 151 152 /* 153 * The controller's accelerometer has a sensor resolution of 16bits and is 154 * configured with a range of +-8000 milliGs. Therefore, the resolution can be 155 * calculated thus: (2^16-1)/(8000 * 2) = 4.096 digits per milliG 156 * Resolution per G (rather than per millliG): 4.096 * 1000 = 4096 digits per G 157 * Alternatively: 1/4096 = .0002441 Gs per digit 158 */ 159 #define JC_IMU_MAX_ACCEL_MAG 32767 160 #define JC_IMU_ACCEL_RES_PER_G 4096 161 #define JC_IMU_ACCEL_FUZZ 10 162 #define JC_IMU_ACCEL_FLAT 0 163 164 /* 165 * The controller's gyroscope has a sensor resolution of 16bits and is 166 * configured with a range of +-2000 degrees/second. 167 * Digits per dps: (2^16 -1)/(2000*2) = 16.38375 168 * dps per digit: 16.38375E-1 = .0610 169 * 170 * STMicro recommends in the datasheet to add 15% to the dps/digit. This allows 171 * the full sensitivity range to be saturated without clipping. This yields more 172 * accurate results, so it's the technique this driver uses. 173 * dps per digit (corrected): .0610 * 1.15 = .0702 174 * digits per dps (corrected): .0702E-1 = 14.247 175 * 176 * Now, 14.247 truncating to 14 loses a lot of precision, so we rescale the 177 * min/max range by 1000. 178 */ 179 #define JC_IMU_PREC_RANGE_SCALE 1000 180 /* Note: change mag and res_per_dps if prec_range_scale is ever altered */ 181 #define JC_IMU_MAX_GYRO_MAG 32767000 /* (2^16-1)*1000 */ 182 #define JC_IMU_GYRO_RES_PER_DPS 14247 /* (14.247*1000) */ 183 #define JC_IMU_GYRO_FUZZ 10 184 #define JC_IMU_GYRO_FLAT 0 185 186 /* frequency/amplitude tables for rumble */ 187 struct joycon_rumble_freq_data { 188 u16 high; 189 u8 low; 190 u16 freq; /* Hz*/ 191 }; 192 193 struct joycon_rumble_amp_data { 194 u8 high; 195 u16 low; 196 u16 amp; 197 }; 198 199 #if IS_ENABLED(CONFIG_NINTENDO_FF) 200 /* 201 * These tables are from 202 * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/rumble_data_table.md 203 */ 204 static const struct joycon_rumble_freq_data joycon_rumble_frequencies[] = { 205 /* high, low, freq */ 206 { 0x0000, 0x01, 41 }, { 0x0000, 0x02, 42 }, { 0x0000, 0x03, 43 }, 207 { 0x0000, 0x04, 44 }, { 0x0000, 0x05, 45 }, { 0x0000, 0x06, 46 }, 208 { 0x0000, 0x07, 47 }, { 0x0000, 0x08, 48 }, { 0x0000, 0x09, 49 }, 209 { 0x0000, 0x0A, 50 }, { 0x0000, 0x0B, 51 }, { 0x0000, 0x0C, 52 }, 210 { 0x0000, 0x0D, 53 }, { 0x0000, 0x0E, 54 }, { 0x0000, 0x0F, 55 }, 211 { 0x0000, 0x10, 57 }, { 0x0000, 0x11, 58 }, { 0x0000, 0x12, 59 }, 212 { 0x0000, 0x13, 60 }, { 0x0000, 0x14, 62 }, { 0x0000, 0x15, 63 }, 213 { 0x0000, 0x16, 64 }, { 0x0000, 0x17, 66 }, { 0x0000, 0x18, 67 }, 214 { 0x0000, 0x19, 69 }, { 0x0000, 0x1A, 70 }, { 0x0000, 0x1B, 72 }, 215 { 0x0000, 0x1C, 73 }, { 0x0000, 0x1D, 75 }, { 0x0000, 0x1e, 77 }, 216 { 0x0000, 0x1f, 78 }, { 0x0000, 0x20, 80 }, { 0x0400, 0x21, 82 }, 217 { 0x0800, 0x22, 84 }, { 0x0c00, 0x23, 85 }, { 0x1000, 0x24, 87 }, 218 { 0x1400, 0x25, 89 }, { 0x1800, 0x26, 91 }, { 0x1c00, 0x27, 93 }, 219 { 0x2000, 0x28, 95 }, { 0x2400, 0x29, 97 }, { 0x2800, 0x2a, 99 }, 220 { 0x2c00, 0x2b, 102 }, { 0x3000, 0x2c, 104 }, { 0x3400, 0x2d, 106 }, 221 { 0x3800, 0x2e, 108 }, { 0x3c00, 0x2f, 111 }, { 0x4000, 0x30, 113 }, 222 { 0x4400, 0x31, 116 }, { 0x4800, 0x32, 118 }, { 0x4c00, 0x33, 121 }, 223 { 0x5000, 0x34, 123 }, { 0x5400, 0x35, 126 }, { 0x5800, 0x36, 129 }, 224 { 0x5c00, 0x37, 132 }, { 0x6000, 0x38, 135 }, { 0x6400, 0x39, 137 }, 225 { 0x6800, 0x3a, 141 }, { 0x6c00, 0x3b, 144 }, { 0x7000, 0x3c, 147 }, 226 { 0x7400, 0x3d, 150 }, { 0x7800, 0x3e, 153 }, { 0x7c00, 0x3f, 157 }, 227 { 0x8000, 0x40, 160 }, { 0x8400, 0x41, 164 }, { 0x8800, 0x42, 167 }, 228 { 0x8c00, 0x43, 171 }, { 0x9000, 0x44, 174 }, { 0x9400, 0x45, 178 }, 229 { 0x9800, 0x46, 182 }, { 0x9c00, 0x47, 186 }, { 0xa000, 0x48, 190 }, 230 { 0xa400, 0x49, 194 }, { 0xa800, 0x4a, 199 }, { 0xac00, 0x4b, 203 }, 231 { 0xb000, 0x4c, 207 }, { 0xb400, 0x4d, 212 }, { 0xb800, 0x4e, 217 }, 232 { 0xbc00, 0x4f, 221 }, { 0xc000, 0x50, 226 }, { 0xc400, 0x51, 231 }, 233 { 0xc800, 0x52, 236 }, { 0xcc00, 0x53, 241 }, { 0xd000, 0x54, 247 }, 234 { 0xd400, 0x55, 252 }, { 0xd800, 0x56, 258 }, { 0xdc00, 0x57, 263 }, 235 { 0xe000, 0x58, 269 }, { 0xe400, 0x59, 275 }, { 0xe800, 0x5a, 281 }, 236 { 0xec00, 0x5b, 287 }, { 0xf000, 0x5c, 293 }, { 0xf400, 0x5d, 300 }, 237 { 0xf800, 0x5e, 306 }, { 0xfc00, 0x5f, 313 }, { 0x0001, 0x60, 320 }, 238 { 0x0401, 0x61, 327 }, { 0x0801, 0x62, 334 }, { 0x0c01, 0x63, 341 }, 239 { 0x1001, 0x64, 349 }, { 0x1401, 0x65, 357 }, { 0x1801, 0x66, 364 }, 240 { 0x1c01, 0x67, 372 }, { 0x2001, 0x68, 381 }, { 0x2401, 0x69, 389 }, 241 { 0x2801, 0x6a, 397 }, { 0x2c01, 0x6b, 406 }, { 0x3001, 0x6c, 415 }, 242 { 0x3401, 0x6d, 424 }, { 0x3801, 0x6e, 433 }, { 0x3c01, 0x6f, 443 }, 243 { 0x4001, 0x70, 453 }, { 0x4401, 0x71, 462 }, { 0x4801, 0x72, 473 }, 244 { 0x4c01, 0x73, 483 }, { 0x5001, 0x74, 494 }, { 0x5401, 0x75, 504 }, 245 { 0x5801, 0x76, 515 }, { 0x5c01, 0x77, 527 }, { 0x6001, 0x78, 538 }, 246 { 0x6401, 0x79, 550 }, { 0x6801, 0x7a, 562 }, { 0x6c01, 0x7b, 574 }, 247 { 0x7001, 0x7c, 587 }, { 0x7401, 0x7d, 600 }, { 0x7801, 0x7e, 613 }, 248 { 0x7c01, 0x7f, 626 }, { 0x8001, 0x00, 640 }, { 0x8401, 0x00, 654 }, 249 { 0x8801, 0x00, 668 }, { 0x8c01, 0x00, 683 }, { 0x9001, 0x00, 698 }, 250 { 0x9401, 0x00, 713 }, { 0x9801, 0x00, 729 }, { 0x9c01, 0x00, 745 }, 251 { 0xa001, 0x00, 761 }, { 0xa401, 0x00, 778 }, { 0xa801, 0x00, 795 }, 252 { 0xac01, 0x00, 812 }, { 0xb001, 0x00, 830 }, { 0xb401, 0x00, 848 }, 253 { 0xb801, 0x00, 867 }, { 0xbc01, 0x00, 886 }, { 0xc001, 0x00, 905 }, 254 { 0xc401, 0x00, 925 }, { 0xc801, 0x00, 945 }, { 0xcc01, 0x00, 966 }, 255 { 0xd001, 0x00, 987 }, { 0xd401, 0x00, 1009 }, { 0xd801, 0x00, 1031 }, 256 { 0xdc01, 0x00, 1053 }, { 0xe001, 0x00, 1076 }, { 0xe401, 0x00, 1100 }, 257 { 0xe801, 0x00, 1124 }, { 0xec01, 0x00, 1149 }, { 0xf001, 0x00, 1174 }, 258 { 0xf401, 0x00, 1199 }, { 0xf801, 0x00, 1226 }, { 0xfc01, 0x00, 1253 } 259 }; 260 261 #define joycon_max_rumble_amp (1003) 262 static const struct joycon_rumble_amp_data joycon_rumble_amplitudes[] = { 263 /* high, low, amp */ 264 { 0x00, 0x0040, 0 }, 265 { 0x02, 0x8040, 10 }, { 0x04, 0x0041, 12 }, { 0x06, 0x8041, 14 }, 266 { 0x08, 0x0042, 17 }, { 0x0a, 0x8042, 20 }, { 0x0c, 0x0043, 24 }, 267 { 0x0e, 0x8043, 28 }, { 0x10, 0x0044, 33 }, { 0x12, 0x8044, 40 }, 268 { 0x14, 0x0045, 47 }, { 0x16, 0x8045, 56 }, { 0x18, 0x0046, 67 }, 269 { 0x1a, 0x8046, 80 }, { 0x1c, 0x0047, 95 }, { 0x1e, 0x8047, 112 }, 270 { 0x20, 0x0048, 117 }, { 0x22, 0x8048, 123 }, { 0x24, 0x0049, 128 }, 271 { 0x26, 0x8049, 134 }, { 0x28, 0x004a, 140 }, { 0x2a, 0x804a, 146 }, 272 { 0x2c, 0x004b, 152 }, { 0x2e, 0x804b, 159 }, { 0x30, 0x004c, 166 }, 273 { 0x32, 0x804c, 173 }, { 0x34, 0x004d, 181 }, { 0x36, 0x804d, 189 }, 274 { 0x38, 0x004e, 198 }, { 0x3a, 0x804e, 206 }, { 0x3c, 0x004f, 215 }, 275 { 0x3e, 0x804f, 225 }, { 0x40, 0x0050, 230 }, { 0x42, 0x8050, 235 }, 276 { 0x44, 0x0051, 240 }, { 0x46, 0x8051, 245 }, { 0x48, 0x0052, 251 }, 277 { 0x4a, 0x8052, 256 }, { 0x4c, 0x0053, 262 }, { 0x4e, 0x8053, 268 }, 278 { 0x50, 0x0054, 273 }, { 0x52, 0x8054, 279 }, { 0x54, 0x0055, 286 }, 279 { 0x56, 0x8055, 292 }, { 0x58, 0x0056, 298 }, { 0x5a, 0x8056, 305 }, 280 { 0x5c, 0x0057, 311 }, { 0x5e, 0x8057, 318 }, { 0x60, 0x0058, 325 }, 281 { 0x62, 0x8058, 332 }, { 0x64, 0x0059, 340 }, { 0x66, 0x8059, 347 }, 282 { 0x68, 0x005a, 355 }, { 0x6a, 0x805a, 362 }, { 0x6c, 0x005b, 370 }, 283 { 0x6e, 0x805b, 378 }, { 0x70, 0x005c, 387 }, { 0x72, 0x805c, 395 }, 284 { 0x74, 0x005d, 404 }, { 0x76, 0x805d, 413 }, { 0x78, 0x005e, 422 }, 285 { 0x7a, 0x805e, 431 }, { 0x7c, 0x005f, 440 }, { 0x7e, 0x805f, 450 }, 286 { 0x80, 0x0060, 460 }, { 0x82, 0x8060, 470 }, { 0x84, 0x0061, 480 }, 287 { 0x86, 0x8061, 491 }, { 0x88, 0x0062, 501 }, { 0x8a, 0x8062, 512 }, 288 { 0x8c, 0x0063, 524 }, { 0x8e, 0x8063, 535 }, { 0x90, 0x0064, 547 }, 289 { 0x92, 0x8064, 559 }, { 0x94, 0x0065, 571 }, { 0x96, 0x8065, 584 }, 290 { 0x98, 0x0066, 596 }, { 0x9a, 0x8066, 609 }, { 0x9c, 0x0067, 623 }, 291 { 0x9e, 0x8067, 636 }, { 0xa0, 0x0068, 650 }, { 0xa2, 0x8068, 665 }, 292 { 0xa4, 0x0069, 679 }, { 0xa6, 0x8069, 694 }, { 0xa8, 0x006a, 709 }, 293 { 0xaa, 0x806a, 725 }, { 0xac, 0x006b, 741 }, { 0xae, 0x806b, 757 }, 294 { 0xb0, 0x006c, 773 }, { 0xb2, 0x806c, 790 }, { 0xb4, 0x006d, 808 }, 295 { 0xb6, 0x806d, 825 }, { 0xb8, 0x006e, 843 }, { 0xba, 0x806e, 862 }, 296 { 0xbc, 0x006f, 881 }, { 0xbe, 0x806f, 900 }, { 0xc0, 0x0070, 920 }, 297 { 0xc2, 0x8070, 940 }, { 0xc4, 0x0071, 960 }, { 0xc6, 0x8071, 981 }, 298 { 0xc8, 0x0072, joycon_max_rumble_amp } 299 }; 300 static const u16 JC_RUMBLE_DFLT_LOW_FREQ = 160; 301 static const u16 JC_RUMBLE_DFLT_HIGH_FREQ = 320; 302 static const unsigned short JC_RUMBLE_ZERO_AMP_PKT_CNT = 5; 303 #endif /* IS_ENABLED(CONFIG_NINTENDO_FF) */ 304 static const u16 JC_RUMBLE_PERIOD_MS = 50; 305 306 /* States for controller state machine */ 307 enum joycon_ctlr_state { 308 JOYCON_CTLR_STATE_INIT, 309 JOYCON_CTLR_STATE_READ, 310 JOYCON_CTLR_STATE_REMOVED, 311 JOYCON_CTLR_STATE_SUSPENDED, 312 }; 313 314 /* Controller type received as part of device info */ 315 enum joycon_ctlr_type { 316 JOYCON_CTLR_TYPE_JCL = 0x01, 317 JOYCON_CTLR_TYPE_JCR = 0x02, 318 JOYCON_CTLR_TYPE_PRO = 0x03, 319 JOYCON_CTLR_TYPE_LIC_PRO = 0x06, 320 JOYCON_CTLR_TYPE_NESL = 0x09, 321 JOYCON_CTLR_TYPE_NESR = 0x0A, 322 JOYCON_CTLR_TYPE_SNES = 0x0B, 323 JOYCON_CTLR_TYPE_GEN = 0x0D, 324 JOYCON_CTLR_TYPE_N64 = 0x0C, 325 }; 326 327 struct joycon_stick_cal { 328 s32 max; 329 s32 min; 330 s32 center; 331 }; 332 333 struct joycon_imu_cal { 334 s16 offset[3]; 335 s16 scale[3]; 336 }; 337 338 /* 339 * All the controller's button values are stored in a u32. 340 * They can be accessed with bitwise ANDs. 341 */ 342 #define JC_BTN_Y BIT(0) 343 #define JC_BTN_X BIT(1) 344 #define JC_BTN_B BIT(2) 345 #define JC_BTN_A BIT(3) 346 #define JC_BTN_SR_R BIT(4) 347 #define JC_BTN_SL_R BIT(5) 348 #define JC_BTN_R BIT(6) 349 #define JC_BTN_ZR BIT(7) 350 #define JC_BTN_MINUS BIT(8) 351 #define JC_BTN_PLUS BIT(9) 352 #define JC_BTN_RSTICK BIT(10) 353 #define JC_BTN_LSTICK BIT(11) 354 #define JC_BTN_HOME BIT(12) 355 #define JC_BTN_CAP BIT(13) /* capture button */ 356 #define JC_BTN_DOWN BIT(16) 357 #define JC_BTN_UP BIT(17) 358 #define JC_BTN_RIGHT BIT(18) 359 #define JC_BTN_LEFT BIT(19) 360 #define JC_BTN_SR_L BIT(20) 361 #define JC_BTN_SL_L BIT(21) 362 #define JC_BTN_L BIT(22) 363 #define JC_BTN_ZL BIT(23) 364 365 struct joycon_ctlr_button_mapping { 366 u32 code; 367 u32 bit; 368 }; 369 370 /* 371 * D-pad is configured as buttons for the left Joy-Con only! 372 */ 373 static const struct joycon_ctlr_button_mapping left_joycon_button_mappings[] = { 374 { BTN_TL, JC_BTN_L, }, 375 { BTN_TL2, JC_BTN_ZL, }, 376 { BTN_SELECT, JC_BTN_MINUS, }, 377 { BTN_THUMBL, JC_BTN_LSTICK, }, 378 { BTN_DPAD_UP, JC_BTN_UP, }, 379 { BTN_DPAD_DOWN, JC_BTN_DOWN, }, 380 { BTN_DPAD_LEFT, JC_BTN_LEFT, }, 381 { BTN_DPAD_RIGHT, JC_BTN_RIGHT, }, 382 { BTN_Z, JC_BTN_CAP, }, 383 { /* sentinel */ }, 384 }; 385 386 /* 387 * The unused *right*-side triggers become the SL/SR triggers for the *left* 388 * Joy-Con, if and only if we're not using a charging grip. 389 */ 390 static const struct joycon_ctlr_button_mapping left_joycon_s_button_mappings[] = { 391 { BTN_TR, JC_BTN_SL_L, }, 392 { BTN_TR2, JC_BTN_SR_L, }, 393 { /* sentinel */ }, 394 }; 395 396 static const struct joycon_ctlr_button_mapping right_joycon_button_mappings[] = { 397 { BTN_EAST, JC_BTN_A, }, 398 { BTN_SOUTH, JC_BTN_B, }, 399 { BTN_NORTH, JC_BTN_X, }, 400 { BTN_WEST, JC_BTN_Y, }, 401 { BTN_TR, JC_BTN_R, }, 402 { BTN_TR2, JC_BTN_ZR, }, 403 { BTN_START, JC_BTN_PLUS, }, 404 { BTN_THUMBR, JC_BTN_RSTICK, }, 405 { BTN_MODE, JC_BTN_HOME, }, 406 { /* sentinel */ }, 407 }; 408 409 /* 410 * The unused *left*-side triggers become the SL/SR triggers for the *right* 411 * Joy-Con, if and only if we're not using a charging grip. 412 */ 413 static const struct joycon_ctlr_button_mapping right_joycon_s_button_mappings[] = { 414 { BTN_TL, JC_BTN_SL_R, }, 415 { BTN_TL2, JC_BTN_SR_R, }, 416 { /* sentinel */ }, 417 }; 418 419 static const struct joycon_ctlr_button_mapping procon_button_mappings[] = { 420 { BTN_EAST, JC_BTN_A, }, 421 { BTN_SOUTH, JC_BTN_B, }, 422 { BTN_NORTH, JC_BTN_X, }, 423 { BTN_WEST, JC_BTN_Y, }, 424 { BTN_TL, JC_BTN_L, }, 425 { BTN_TR, JC_BTN_R, }, 426 { BTN_TL2, JC_BTN_ZL, }, 427 { BTN_TR2, JC_BTN_ZR, }, 428 { BTN_SELECT, JC_BTN_MINUS, }, 429 { BTN_START, JC_BTN_PLUS, }, 430 { BTN_THUMBL, JC_BTN_LSTICK, }, 431 { BTN_THUMBR, JC_BTN_RSTICK, }, 432 { BTN_MODE, JC_BTN_HOME, }, 433 { BTN_Z, JC_BTN_CAP, }, 434 { /* sentinel */ }, 435 }; 436 437 /* Licensed Pro Controllers (e.g. HORI) swap X/Y bits in the report */ 438 static const struct joycon_ctlr_button_mapping lic_procon_button_mappings[] = { 439 { BTN_EAST, JC_BTN_A, }, 440 { BTN_SOUTH, JC_BTN_B, }, 441 { BTN_NORTH, JC_BTN_Y, }, 442 { BTN_WEST, JC_BTN_X, }, 443 { BTN_TL, JC_BTN_L, }, 444 { BTN_TR, JC_BTN_R, }, 445 { BTN_TL2, JC_BTN_ZL, }, 446 { BTN_TR2, JC_BTN_ZR, }, 447 { BTN_SELECT, JC_BTN_MINUS, }, 448 { BTN_START, JC_BTN_PLUS, }, 449 { BTN_THUMBL, JC_BTN_LSTICK, }, 450 { BTN_THUMBR, JC_BTN_RSTICK, }, 451 { BTN_MODE, JC_BTN_HOME, }, 452 { BTN_Z, JC_BTN_CAP, }, 453 { /* sentinel */ }, 454 }; 455 456 static const struct joycon_ctlr_button_mapping nescon_button_mappings[] = { 457 { BTN_SOUTH, JC_BTN_A, }, 458 { BTN_EAST, JC_BTN_B, }, 459 { BTN_TL, JC_BTN_L, }, 460 { BTN_TR, JC_BTN_R, }, 461 { BTN_SELECT, JC_BTN_MINUS, }, 462 { BTN_START, JC_BTN_PLUS, }, 463 { /* sentinel */ }, 464 }; 465 466 static const struct joycon_ctlr_button_mapping snescon_button_mappings[] = { 467 { BTN_EAST, JC_BTN_A, }, 468 { BTN_SOUTH, JC_BTN_B, }, 469 { BTN_NORTH, JC_BTN_X, }, 470 { BTN_WEST, JC_BTN_Y, }, 471 { BTN_TL, JC_BTN_L, }, 472 { BTN_TR, JC_BTN_R, }, 473 { BTN_TL2, JC_BTN_ZL, }, 474 { BTN_TR2, JC_BTN_ZR, }, 475 { BTN_SELECT, JC_BTN_MINUS, }, 476 { BTN_START, JC_BTN_PLUS, }, 477 { /* sentinel */ }, 478 }; 479 480 static const struct joycon_ctlr_button_mapping gencon_button_mappings[] = { 481 { BTN_WEST, JC_BTN_A, }, /* A */ 482 { BTN_SOUTH, JC_BTN_B, }, /* B */ 483 { BTN_EAST, JC_BTN_R, }, /* C */ 484 { BTN_TL, JC_BTN_X, }, /* X MD/GEN 6B Only */ 485 { BTN_NORTH, JC_BTN_Y, }, /* Y MD/GEN 6B Only */ 486 { BTN_TR, JC_BTN_L, }, /* Z MD/GEN 6B Only */ 487 { BTN_SELECT, JC_BTN_ZR, }, /* Mode */ 488 { BTN_START, JC_BTN_PLUS, }, 489 { BTN_MODE, JC_BTN_HOME, }, 490 { BTN_Z, JC_BTN_CAP, }, 491 { /* sentinel */ }, 492 }; 493 494 static const struct joycon_ctlr_button_mapping n64con_button_mappings[] = { 495 { BTN_A, JC_BTN_A, }, 496 { BTN_B, JC_BTN_B, }, 497 { BTN_TL2, JC_BTN_ZL, }, /* Z */ 498 { BTN_TL, JC_BTN_L, }, 499 { BTN_TR, JC_BTN_R, }, 500 { BTN_TR2, JC_BTN_LSTICK, }, /* ZR */ 501 { BTN_START, JC_BTN_PLUS, }, 502 { BTN_SELECT, JC_BTN_Y, }, /* C UP */ 503 { BTN_X, JC_BTN_ZR, }, /* C DOWN */ 504 { BTN_Y, JC_BTN_X, }, /* C LEFT */ 505 { BTN_C, JC_BTN_MINUS, }, /* C RIGHT */ 506 { BTN_MODE, JC_BTN_HOME, }, 507 { BTN_Z, JC_BTN_CAP, }, 508 { /* sentinel */ }, 509 }; 510 511 enum joycon_msg_type { 512 JOYCON_MSG_TYPE_NONE, 513 JOYCON_MSG_TYPE_USB, 514 JOYCON_MSG_TYPE_SUBCMD, 515 }; 516 517 struct joycon_rumble_output { 518 u8 output_id; 519 u8 packet_num; 520 u8 rumble_data[8]; 521 } __packed; 522 523 struct joycon_subcmd_request { 524 u8 output_id; /* must be 0x01 for subcommand, 0x10 for rumble only */ 525 u8 packet_num; /* incremented every send */ 526 u8 rumble_data[8]; 527 u8 subcmd_id; 528 u8 data[]; /* length depends on the subcommand */ 529 } __packed; 530 531 struct joycon_subcmd_reply { 532 u8 ack; /* MSB 1 for ACK, 0 for NACK */ 533 u8 id; /* id of requested subcmd */ 534 u8 data[]; /* will be at most 35 bytes */ 535 } __packed; 536 537 struct joycon_imu_data { 538 s16 accel_x; 539 s16 accel_y; 540 s16 accel_z; 541 s16 gyro_x; 542 s16 gyro_y; 543 s16 gyro_z; 544 } __packed; 545 546 struct joycon_input_report { 547 u8 id; 548 u8 timer; 549 u8 bat_con; /* battery and connection info */ 550 u8 button_status[3]; 551 u8 left_stick[3]; 552 u8 right_stick[3]; 553 u8 vibrator_report; 554 555 union { 556 struct joycon_subcmd_reply subcmd_reply; 557 /* IMU input reports contain 3 samples */ 558 u8 imu_raw_bytes[sizeof(struct joycon_imu_data) * 3]; 559 }; 560 } __packed; 561 562 #define JC_MAX_RESP_SIZE (sizeof(struct joycon_input_report) + 35) 563 #define JC_RUMBLE_DATA_SIZE 8 564 #define JC_RUMBLE_QUEUE_SIZE 8 565 566 static const char * const joycon_player_led_names[] = { 567 LED_FUNCTION_PLAYER1, 568 LED_FUNCTION_PLAYER2, 569 LED_FUNCTION_PLAYER3, 570 LED_FUNCTION_PLAYER4, 571 }; 572 #define JC_NUM_LEDS ARRAY_SIZE(joycon_player_led_names) 573 #define JC_NUM_LED_PATTERNS 8 574 /* Taken from https://www.nintendo.com/my/support/qa/detail/33822 */ 575 static const enum led_brightness joycon_player_led_patterns[JC_NUM_LED_PATTERNS][JC_NUM_LEDS] = { 576 { 1, 0, 0, 0 }, 577 { 1, 1, 0, 0 }, 578 { 1, 1, 1, 0 }, 579 { 1, 1, 1, 1 }, 580 { 1, 0, 0, 1 }, 581 { 1, 0, 1, 0 }, 582 { 1, 0, 1, 1 }, 583 { 0, 1, 1, 0 }, 584 }; 585 586 /* Each physical controller is associated with a joycon_ctlr struct */ 587 struct joycon_ctlr { 588 struct hid_device *hdev; 589 struct input_dev *input; 590 u32 player_id; 591 struct led_classdev leds[JC_NUM_LEDS]; /* player leds */ 592 struct led_classdev home_led; 593 enum joycon_ctlr_state ctlr_state; 594 spinlock_t lock; 595 u8 mac_addr[6]; 596 char *mac_addr_str; 597 enum joycon_ctlr_type ctlr_type; 598 599 /* The following members are used for synchronous sends/receives */ 600 enum joycon_msg_type msg_type; 601 u8 subcmd_num; 602 struct mutex output_mutex; 603 u8 input_buf[JC_MAX_RESP_SIZE]; 604 wait_queue_head_t wait; 605 bool received_resp; 606 u8 usb_ack_match; 607 u8 subcmd_ack_match; 608 bool received_input_report; 609 unsigned int last_input_report_msecs; 610 unsigned int last_subcmd_sent_msecs; 611 unsigned int consecutive_valid_report_deltas; 612 unsigned int subcmd_rate_exhaustions; 613 bool subcmd_rate_relaxed; 614 615 /* factory calibration data */ 616 struct joycon_stick_cal left_stick_cal_x; 617 struct joycon_stick_cal left_stick_cal_y; 618 struct joycon_stick_cal right_stick_cal_x; 619 struct joycon_stick_cal right_stick_cal_y; 620 621 struct joycon_imu_cal accel_cal; 622 struct joycon_imu_cal gyro_cal; 623 624 /* prevents needlessly recalculating these divisors every sample */ 625 s32 imu_cal_accel_divisor[3]; 626 s32 imu_cal_gyro_divisor[3]; 627 628 /* power supply data */ 629 struct power_supply *battery; 630 struct power_supply_desc battery_desc; 631 u8 battery_capacity; 632 bool battery_charging; 633 bool host_powered; 634 635 /* rumble */ 636 u8 rumble_data[JC_RUMBLE_QUEUE_SIZE][JC_RUMBLE_DATA_SIZE]; 637 int rumble_queue_head; 638 int rumble_queue_tail; 639 struct workqueue_struct *rumble_queue; 640 struct work_struct rumble_worker; 641 unsigned int rumble_msecs; 642 u16 rumble_ll_freq; 643 u16 rumble_lh_freq; 644 u16 rumble_rl_freq; 645 u16 rumble_rh_freq; 646 unsigned short rumble_zero_countdown; 647 648 /* imu */ 649 struct input_dev *imu_input; 650 bool imu_first_packet_received; /* helps in initiating timestamp */ 651 unsigned int imu_timestamp_us; /* timestamp we report to userspace */ 652 unsigned int imu_last_pkt_ms; /* used to calc imu report delta */ 653 /* the following are used to track the average imu report time delta */ 654 unsigned int imu_delta_samples_count; 655 unsigned int imu_delta_samples_sum; 656 unsigned int imu_avg_delta_ms; 657 }; 658 659 /* Helper macros for checking controller type */ 660 #define jc_type_is_joycon(ctlr) \ 661 (ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONL || \ 662 ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONR || \ 663 ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_CHRGGRIP) 664 #define jc_type_is_procon(ctlr) \ 665 (ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_PROCON) 666 #define jc_type_is_chrggrip(ctlr) \ 667 (ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_CHRGGRIP) 668 669 /* Does this controller have inputs associated with left joycon? */ 670 #define jc_type_has_left(ctlr) \ 671 (ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCL || \ 672 ctlr->ctlr_type == JOYCON_CTLR_TYPE_PRO || \ 673 ctlr->ctlr_type == JOYCON_CTLR_TYPE_N64) 674 675 /* Does this controller have inputs associated with right joycon? */ 676 #define jc_type_has_right(ctlr) \ 677 (ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCR || \ 678 ctlr->ctlr_type == JOYCON_CTLR_TYPE_PRO) 679 680 /* 681 * Controller device helpers 682 * 683 * These look at the device ID known to the HID subsystem to identify a device, 684 * but take caution: some NSO devices lie about themselves (NES Joy-Cons and 685 * Sega Genesis controller). See type helpers below. 686 * 687 * These helpers are most useful early during the HID probe or in conjunction 688 * with the capability helpers below. 689 */ 690 static inline bool joycon_device_is_chrggrip(struct joycon_ctlr *ctlr) 691 { 692 return ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_CHRGGRIP; 693 } 694 695 /* 696 * Controller type helpers 697 * 698 * These are slightly different than the device-ID-based helpers above. They are 699 * generally more reliable, since they can distinguish between, e.g., Genesis 700 * versus SNES, or NES Joy-Cons versus regular Switch Joy-Cons. They're most 701 * useful for reporting available inputs. For other kinds of distinctions, see 702 * the capability helpers below. 703 * 704 * They have two major drawbacks: (1) they're not available until after we set 705 * the reporting method and then request the device info; (2) they can't 706 * distinguish all controllers (like the Charging Grip from the Pro controller.) 707 */ 708 static inline bool joycon_type_is_left_joycon(struct joycon_ctlr *ctlr) 709 { 710 return ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCL; 711 } 712 713 static inline bool joycon_type_is_right_joycon(struct joycon_ctlr *ctlr) 714 { 715 return ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCR; 716 } 717 718 static inline bool joycon_type_is_procon(struct joycon_ctlr *ctlr) 719 { 720 return ctlr->ctlr_type == JOYCON_CTLR_TYPE_PRO || 721 ctlr->ctlr_type == JOYCON_CTLR_TYPE_LIC_PRO; 722 } 723 724 static inline bool joycon_type_is_snescon(struct joycon_ctlr *ctlr) 725 { 726 return ctlr->ctlr_type == JOYCON_CTLR_TYPE_SNES; 727 } 728 729 static inline bool joycon_type_is_gencon(struct joycon_ctlr *ctlr) 730 { 731 return ctlr->ctlr_type == JOYCON_CTLR_TYPE_GEN; 732 } 733 734 static inline bool joycon_type_is_n64con(struct joycon_ctlr *ctlr) 735 { 736 return ctlr->ctlr_type == JOYCON_CTLR_TYPE_N64; 737 } 738 739 static inline bool joycon_type_is_left_nescon(struct joycon_ctlr *ctlr) 740 { 741 return ctlr->ctlr_type == JOYCON_CTLR_TYPE_NESL; 742 } 743 744 static inline bool joycon_type_is_right_nescon(struct joycon_ctlr *ctlr) 745 { 746 return ctlr->ctlr_type == JOYCON_CTLR_TYPE_NESR; 747 } 748 749 static inline bool joycon_type_is_any_joycon(struct joycon_ctlr *ctlr) 750 { 751 return joycon_type_is_left_joycon(ctlr) || 752 joycon_type_is_right_joycon(ctlr) || 753 joycon_device_is_chrggrip(ctlr); 754 } 755 756 static inline bool joycon_type_is_any_nescon(struct joycon_ctlr *ctlr) 757 { 758 return joycon_type_is_left_nescon(ctlr) || 759 joycon_type_is_right_nescon(ctlr); 760 } 761 762 /* 763 * Controller capability helpers 764 * 765 * These helpers combine the use of the helpers above to detect certain 766 * capabilities during initialization. They are always accurate but (since they 767 * use type helpers) cannot be used early in the HID probe. 768 */ 769 static inline bool joycon_has_imu(struct joycon_ctlr *ctlr) 770 { 771 return joycon_device_is_chrggrip(ctlr) || 772 joycon_type_is_any_joycon(ctlr) || 773 joycon_type_is_procon(ctlr); 774 } 775 776 static inline bool joycon_has_joysticks(struct joycon_ctlr *ctlr) 777 { 778 return joycon_device_is_chrggrip(ctlr) || 779 joycon_type_is_any_joycon(ctlr) || 780 joycon_type_is_procon(ctlr) || 781 joycon_type_is_n64con(ctlr); 782 } 783 784 static inline bool joycon_has_rumble(struct joycon_ctlr *ctlr) 785 { 786 return joycon_device_is_chrggrip(ctlr) || 787 joycon_type_is_any_joycon(ctlr) || 788 joycon_type_is_procon(ctlr) || 789 joycon_type_is_n64con(ctlr); 790 } 791 792 static inline bool joycon_using_usb(struct joycon_ctlr *ctlr) 793 { 794 return ctlr->hdev->bus == BUS_USB; 795 } 796 797 static int __joycon_hid_send(struct hid_device *hdev, u8 *data, size_t len) 798 { 799 u8 *buf; 800 int ret; 801 802 buf = kmemdup(data, len, GFP_KERNEL); 803 if (!buf) 804 return -ENOMEM; 805 ret = hid_hw_output_report(hdev, buf, len); 806 kfree(buf); 807 if (ret < 0) 808 hid_dbg(hdev, "Failed to send output report ret=%d\n", ret); 809 return ret; 810 } 811 812 static void joycon_wait_for_input_report(struct joycon_ctlr *ctlr) 813 { 814 int ret; 815 816 /* 817 * If we are in the proper reporting mode, wait for an input 818 * report prior to sending the subcommand. This improves 819 * reliability considerably. 820 */ 821 if (ctlr->ctlr_state == JOYCON_CTLR_STATE_READ) { 822 unsigned long flags; 823 824 spin_lock_irqsave(&ctlr->lock, flags); 825 ctlr->received_input_report = false; 826 spin_unlock_irqrestore(&ctlr->lock, flags); 827 ret = wait_event_timeout(ctlr->wait, 828 ctlr->received_input_report, 829 HZ / 4); 830 /* We will still proceed, even with a timeout here */ 831 if (!ret) 832 hid_warn(ctlr->hdev, 833 "timeout waiting for input report\n"); 834 } 835 } 836 837 /* 838 * Sending subcommands and/or rumble data at too high a rate can cause bluetooth 839 * controller disconnections. 840 */ 841 #define JC_INPUT_REPORT_MIN_DELTA 8 842 #define JC_INPUT_REPORT_MAX_DELTA 17 843 #define JC_SUBCMD_TX_OFFSET_MS 4 844 #define JC_SUBCMD_VALID_DELTA_REQ 3 845 #define JC_SUBCMD_RATE_MAX_ATTEMPTS 25 846 #define JC_SUBCMD_RATE_MAX_FAILURES 4 847 #define JC_SUBCMD_RATE_LIMITER_USB_MS 20 848 #define JC_SUBCMD_RATE_LIMITER_BT_MS 60 849 #define JC_SUBCMD_RATE_LIMITER_MS(ctlr) ((ctlr)->hdev->bus == BUS_USB ? JC_SUBCMD_RATE_LIMITER_USB_MS : JC_SUBCMD_RATE_LIMITER_BT_MS) 850 static void joycon_enforce_subcmd_rate_strict(struct joycon_ctlr *ctlr) 851 { 852 unsigned int current_ms; 853 unsigned long subcmd_delta; 854 int consecutive_valid_deltas = 0; 855 int attempts = 0; 856 unsigned long flags; 857 858 if (unlikely(ctlr->ctlr_state != JOYCON_CTLR_STATE_READ)) 859 return; 860 861 do { 862 joycon_wait_for_input_report(ctlr); 863 current_ms = jiffies_to_msecs(jiffies); 864 subcmd_delta = current_ms - ctlr->last_subcmd_sent_msecs; 865 866 spin_lock_irqsave(&ctlr->lock, flags); 867 consecutive_valid_deltas = ctlr->consecutive_valid_report_deltas; 868 spin_unlock_irqrestore(&ctlr->lock, flags); 869 870 attempts++; 871 } while ((consecutive_valid_deltas < JC_SUBCMD_VALID_DELTA_REQ || 872 subcmd_delta < JC_SUBCMD_RATE_LIMITER_MS(ctlr)) && 873 ctlr->ctlr_state == JOYCON_CTLR_STATE_READ && 874 attempts < JC_SUBCMD_RATE_MAX_ATTEMPTS); 875 876 if (attempts >= JC_SUBCMD_RATE_MAX_ATTEMPTS) { 877 hid_warn(ctlr->hdev, "%s: exceeded max attempts", __func__); 878 879 if (++ctlr->subcmd_rate_exhaustions == JC_SUBCMD_RATE_MAX_FAILURES) { 880 ctlr->subcmd_rate_relaxed = true; 881 hid_info(ctlr->hdev, 882 "input report cadence does not fit the %d-%dms window; using the legacy subcommand throttle\n", 883 JC_INPUT_REPORT_MIN_DELTA, 884 JC_INPUT_REPORT_MAX_DELTA); 885 } 886 return; 887 } 888 889 ctlr->last_subcmd_sent_msecs = current_ms; 890 891 /* 892 * Wait a short time after receiving an input report before 893 * transmitting. This should reduce odds of a TX coinciding with an RX. 894 * Minimizing concurrent BT traffic with the controller seems to lower 895 * the rate of disconnections. 896 */ 897 msleep(JC_SUBCMD_TX_OFFSET_MS); 898 } 899 900 /* The rate limiter as it was before commit d750d1480362, without the report 901 * cadence requirement. 902 */ 903 static void joycon_enforce_subcmd_rate_legacy(struct joycon_ctlr *ctlr) 904 { 905 static const unsigned int max_subcmd_rate_ms = 25; 906 unsigned int current_ms = jiffies_to_msecs(jiffies); 907 unsigned int delta_ms = current_ms - ctlr->last_subcmd_sent_msecs; 908 909 while (delta_ms < max_subcmd_rate_ms && 910 ctlr->ctlr_state == JOYCON_CTLR_STATE_READ) { 911 joycon_wait_for_input_report(ctlr); 912 current_ms = jiffies_to_msecs(jiffies); 913 delta_ms = current_ms - ctlr->last_subcmd_sent_msecs; 914 } 915 ctlr->last_subcmd_sent_msecs = current_ms; 916 } 917 918 static void joycon_enforce_subcmd_rate(struct joycon_ctlr *ctlr) 919 { 920 if (ctlr->subcmd_rate_relaxed) 921 joycon_enforce_subcmd_rate_legacy(ctlr); 922 else 923 joycon_enforce_subcmd_rate_strict(ctlr); 924 } 925 926 static int joycon_hid_send_sync(struct joycon_ctlr *ctlr, u8 *data, size_t len, 927 u32 timeout) 928 { 929 int ret; 930 int tries = 2; 931 932 /* 933 * The controller occasionally seems to drop subcommands. In testing, 934 * doing one retry after a timeout appears to always work. 935 */ 936 while (tries--) { 937 joycon_enforce_subcmd_rate(ctlr); 938 939 ret = __joycon_hid_send(ctlr->hdev, data, len); 940 if (ret < 0) { 941 memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE); 942 return ret; 943 } 944 945 ret = wait_event_timeout(ctlr->wait, ctlr->received_resp, 946 timeout); 947 if (!ret) { 948 hid_dbg(ctlr->hdev, 949 "synchronous send/receive timed out\n"); 950 if (tries) { 951 hid_dbg(ctlr->hdev, 952 "retrying sync send after timeout\n"); 953 } 954 memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE); 955 ret = -ETIMEDOUT; 956 } else { 957 ret = 0; 958 break; 959 } 960 } 961 962 ctlr->received_resp = false; 963 return ret; 964 } 965 966 static int joycon_send_usb(struct joycon_ctlr *ctlr, u8 cmd, u32 timeout) 967 { 968 int ret; 969 u8 buf[2] = {JC_OUTPUT_USB_CMD}; 970 971 buf[1] = cmd; 972 ctlr->usb_ack_match = cmd; 973 ctlr->msg_type = JOYCON_MSG_TYPE_USB; 974 ret = joycon_hid_send_sync(ctlr, buf, sizeof(buf), timeout); 975 if (ret) 976 hid_dbg(ctlr->hdev, "send usb command failed; ret=%d\n", ret); 977 return ret; 978 } 979 980 static int joycon_send_subcmd(struct joycon_ctlr *ctlr, 981 struct joycon_subcmd_request *subcmd, 982 size_t data_len, u32 timeout) 983 { 984 int ret; 985 unsigned long flags; 986 987 spin_lock_irqsave(&ctlr->lock, flags); 988 /* 989 * If the controller has been removed, just return ENODEV so the LED 990 * subsystem doesn't print invalid errors on removal. 991 */ 992 if (ctlr->ctlr_state == JOYCON_CTLR_STATE_REMOVED) { 993 spin_unlock_irqrestore(&ctlr->lock, flags); 994 return -ENODEV; 995 } 996 memcpy(subcmd->rumble_data, ctlr->rumble_data[ctlr->rumble_queue_tail], 997 JC_RUMBLE_DATA_SIZE); 998 spin_unlock_irqrestore(&ctlr->lock, flags); 999 1000 subcmd->output_id = JC_OUTPUT_RUMBLE_AND_SUBCMD; 1001 subcmd->packet_num = ctlr->subcmd_num; 1002 if (++ctlr->subcmd_num > 0xF) 1003 ctlr->subcmd_num = 0; 1004 ctlr->subcmd_ack_match = subcmd->subcmd_id; 1005 ctlr->msg_type = JOYCON_MSG_TYPE_SUBCMD; 1006 1007 ret = joycon_hid_send_sync(ctlr, (u8 *)subcmd, 1008 sizeof(*subcmd) + data_len, timeout); 1009 if (ret < 0) 1010 hid_dbg(ctlr->hdev, "send subcommand failed; ret=%d\n", ret); 1011 else 1012 ret = 0; 1013 return ret; 1014 } 1015 1016 /* Supply nibbles for flash and on. Ones correspond to active */ 1017 static int joycon_set_player_leds(struct joycon_ctlr *ctlr, u8 flash, u8 on) 1018 { 1019 struct joycon_subcmd_request *req; 1020 u8 buffer[sizeof(*req) + 1] = { 0 }; 1021 1022 req = (struct joycon_subcmd_request *)buffer; 1023 req->subcmd_id = JC_SUBCMD_SET_PLAYER_LIGHTS; 1024 req->data[0] = (flash << 4) | on; 1025 1026 hid_dbg(ctlr->hdev, "setting player leds\n"); 1027 return joycon_send_subcmd(ctlr, req, 1, HZ/4); 1028 } 1029 1030 static int joycon_set_home_led(struct joycon_ctlr *ctlr, enum led_brightness brightness) 1031 { 1032 struct joycon_subcmd_request *req; 1033 u8 buffer[sizeof(*req) + 5] = { 0 }; 1034 u8 *data; 1035 1036 req = (struct joycon_subcmd_request *)buffer; 1037 req->subcmd_id = JC_SUBCMD_SET_HOME_LIGHT; 1038 data = req->data; 1039 data[0] = 0x01; 1040 data[1] = brightness << 4; 1041 data[2] = brightness | (brightness << 4); 1042 data[3] = 0x11; 1043 data[4] = 0x11; 1044 1045 hid_dbg(ctlr->hdev, "setting home led brightness\n"); 1046 return joycon_send_subcmd(ctlr, req, 5, HZ/4); 1047 } 1048 1049 static int joycon_request_spi_flash_read(struct joycon_ctlr *ctlr, 1050 u32 start_addr, u8 size, u8 **reply) 1051 { 1052 struct joycon_subcmd_request *req; 1053 struct joycon_input_report *report; 1054 u8 buffer[sizeof(*req) + 5] = { 0 }; 1055 u8 *data; 1056 int ret; 1057 1058 if (!reply) 1059 return -EINVAL; 1060 1061 req = (struct joycon_subcmd_request *)buffer; 1062 req->subcmd_id = JC_SUBCMD_SPI_FLASH_READ; 1063 data = req->data; 1064 put_unaligned_le32(start_addr, data); 1065 data[4] = size; 1066 1067 hid_dbg(ctlr->hdev, "requesting SPI flash data\n"); 1068 ret = joycon_send_subcmd(ctlr, req, 5, HZ); 1069 if (ret) { 1070 hid_err(ctlr->hdev, "failed reading SPI flash; ret=%d\n", ret); 1071 } else { 1072 report = (struct joycon_input_report *)ctlr->input_buf; 1073 /* The read data starts at the 6th byte */ 1074 *reply = &report->subcmd_reply.data[5]; 1075 } 1076 return ret; 1077 } 1078 1079 /* 1080 * User calibration's presence is denoted with a magic byte preceding it. 1081 * returns 0 if magic val is present, 1 if not present, < 0 on error 1082 */ 1083 static int joycon_check_for_cal_magic(struct joycon_ctlr *ctlr, u32 flash_addr) 1084 { 1085 int ret; 1086 u8 *reply; 1087 1088 ret = joycon_request_spi_flash_read(ctlr, flash_addr, 1089 JC_CAL_USR_MAGIC_SIZE, &reply); 1090 if (ret) 1091 return ret; 1092 1093 return reply[0] != JC_CAL_USR_MAGIC_0 || reply[1] != JC_CAL_USR_MAGIC_1; 1094 } 1095 1096 static int joycon_read_stick_calibration(struct joycon_ctlr *ctlr, u16 cal_addr, 1097 struct joycon_stick_cal *cal_x, 1098 struct joycon_stick_cal *cal_y, 1099 bool left_stick) 1100 { 1101 s32 x_max_above; 1102 s32 x_min_below; 1103 s32 y_max_above; 1104 s32 y_min_below; 1105 u8 *raw_cal; 1106 int ret; 1107 1108 ret = joycon_request_spi_flash_read(ctlr, cal_addr, 1109 JC_CAL_STICK_DATA_SIZE, &raw_cal); 1110 if (ret) 1111 return ret; 1112 1113 /* stick calibration parsing: note the order differs based on stick */ 1114 if (left_stick) { 1115 x_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 0), 0, 1116 12); 1117 y_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 1), 4, 1118 12); 1119 cal_x->center = hid_field_extract(ctlr->hdev, (raw_cal + 3), 0, 1120 12); 1121 cal_y->center = hid_field_extract(ctlr->hdev, (raw_cal + 4), 4, 1122 12); 1123 x_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 6), 0, 1124 12); 1125 y_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 7), 4, 1126 12); 1127 } else { 1128 cal_x->center = hid_field_extract(ctlr->hdev, (raw_cal + 0), 0, 1129 12); 1130 cal_y->center = hid_field_extract(ctlr->hdev, (raw_cal + 1), 4, 1131 12); 1132 x_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 3), 0, 1133 12); 1134 y_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 4), 4, 1135 12); 1136 x_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 6), 0, 1137 12); 1138 y_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 7), 4, 1139 12); 1140 } 1141 1142 cal_x->max = cal_x->center + x_max_above; 1143 cal_x->min = cal_x->center - x_min_below; 1144 cal_y->max = cal_y->center + y_max_above; 1145 cal_y->min = cal_y->center - y_min_below; 1146 1147 /* check if calibration values are plausible */ 1148 if (cal_x->min >= cal_x->center || cal_x->center >= cal_x->max || 1149 cal_y->min >= cal_y->center || cal_y->center >= cal_y->max) 1150 ret = -EINVAL; 1151 1152 return ret; 1153 } 1154 1155 static const u16 DFLT_STICK_CAL_CEN = 2000; 1156 static const u16 DFLT_STICK_CAL_MAX = 3500; 1157 static const u16 DFLT_STICK_CAL_MIN = 500; 1158 static void joycon_use_default_calibration(struct hid_device *hdev, 1159 struct joycon_stick_cal *cal_x, 1160 struct joycon_stick_cal *cal_y, 1161 const char *stick, int ret) 1162 { 1163 hid_warn(hdev, 1164 "Failed to read %s stick cal, using defaults; e=%d\n", 1165 stick, ret); 1166 1167 cal_x->center = cal_y->center = DFLT_STICK_CAL_CEN; 1168 cal_x->max = cal_y->max = DFLT_STICK_CAL_MAX; 1169 cal_x->min = cal_y->min = DFLT_STICK_CAL_MIN; 1170 } 1171 1172 static int joycon_request_calibration(struct joycon_ctlr *ctlr) 1173 { 1174 u16 left_stick_addr = JC_CAL_FCT_DATA_LEFT_ADDR; 1175 u16 right_stick_addr = JC_CAL_FCT_DATA_RIGHT_ADDR; 1176 int ret; 1177 1178 hid_dbg(ctlr->hdev, "requesting cal data\n"); 1179 1180 /* check if user stick calibrations are present */ 1181 if (!joycon_check_for_cal_magic(ctlr, JC_CAL_USR_LEFT_MAGIC_ADDR)) { 1182 left_stick_addr = JC_CAL_USR_LEFT_DATA_ADDR; 1183 hid_info(ctlr->hdev, "using user cal for left stick\n"); 1184 } else { 1185 hid_info(ctlr->hdev, "using factory cal for left stick\n"); 1186 } 1187 if (!joycon_check_for_cal_magic(ctlr, JC_CAL_USR_RIGHT_MAGIC_ADDR)) { 1188 right_stick_addr = JC_CAL_USR_RIGHT_DATA_ADDR; 1189 hid_info(ctlr->hdev, "using user cal for right stick\n"); 1190 } else { 1191 hid_info(ctlr->hdev, "using factory cal for right stick\n"); 1192 } 1193 1194 /* read the left stick calibration data */ 1195 ret = joycon_read_stick_calibration(ctlr, left_stick_addr, 1196 &ctlr->left_stick_cal_x, 1197 &ctlr->left_stick_cal_y, 1198 true); 1199 1200 if (ret) 1201 joycon_use_default_calibration(ctlr->hdev, 1202 &ctlr->left_stick_cal_x, 1203 &ctlr->left_stick_cal_y, 1204 "left", ret); 1205 1206 /* read the right stick calibration data */ 1207 ret = joycon_read_stick_calibration(ctlr, right_stick_addr, 1208 &ctlr->right_stick_cal_x, 1209 &ctlr->right_stick_cal_y, 1210 false); 1211 1212 if (ret) 1213 joycon_use_default_calibration(ctlr->hdev, 1214 &ctlr->right_stick_cal_x, 1215 &ctlr->right_stick_cal_y, 1216 "right", ret); 1217 1218 hid_dbg(ctlr->hdev, "calibration:\n" 1219 "l_x_c=%d l_x_max=%d l_x_min=%d\n" 1220 "l_y_c=%d l_y_max=%d l_y_min=%d\n" 1221 "r_x_c=%d r_x_max=%d r_x_min=%d\n" 1222 "r_y_c=%d r_y_max=%d r_y_min=%d\n", 1223 ctlr->left_stick_cal_x.center, 1224 ctlr->left_stick_cal_x.max, 1225 ctlr->left_stick_cal_x.min, 1226 ctlr->left_stick_cal_y.center, 1227 ctlr->left_stick_cal_y.max, 1228 ctlr->left_stick_cal_y.min, 1229 ctlr->right_stick_cal_x.center, 1230 ctlr->right_stick_cal_x.max, 1231 ctlr->right_stick_cal_x.min, 1232 ctlr->right_stick_cal_y.center, 1233 ctlr->right_stick_cal_y.max, 1234 ctlr->right_stick_cal_y.min); 1235 1236 return 0; 1237 } 1238 1239 /* 1240 * These divisors are calculated once rather than for each sample. They are only 1241 * dependent on the IMU calibration values. They are used when processing the 1242 * IMU input reports. 1243 */ 1244 static void joycon_calc_imu_cal_divisors(struct joycon_ctlr *ctlr) 1245 { 1246 int i, divz = 0; 1247 1248 for (i = 0; i < 3; i++) { 1249 ctlr->imu_cal_accel_divisor[i] = ctlr->accel_cal.scale[i] - 1250 ctlr->accel_cal.offset[i]; 1251 ctlr->imu_cal_gyro_divisor[i] = ctlr->gyro_cal.scale[i] - 1252 ctlr->gyro_cal.offset[i]; 1253 1254 if (ctlr->imu_cal_accel_divisor[i] == 0) { 1255 ctlr->imu_cal_accel_divisor[i] = 1; 1256 divz++; 1257 } 1258 1259 if (ctlr->imu_cal_gyro_divisor[i] == 0) { 1260 ctlr->imu_cal_gyro_divisor[i] = 1; 1261 divz++; 1262 } 1263 } 1264 1265 if (divz) 1266 hid_warn(ctlr->hdev, "inaccurate IMU divisors (%d)\n", divz); 1267 } 1268 1269 static const s16 DFLT_ACCEL_OFFSET /*= 0*/; 1270 static const s16 DFLT_ACCEL_SCALE = 16384; 1271 static const s16 DFLT_GYRO_OFFSET /*= 0*/; 1272 static const s16 DFLT_GYRO_SCALE = 13371; 1273 static int joycon_request_imu_calibration(struct joycon_ctlr *ctlr) 1274 { 1275 u16 imu_cal_addr = JC_IMU_CAL_FCT_DATA_ADDR; 1276 u8 *raw_cal; 1277 int ret; 1278 int i; 1279 1280 /* check if user calibration exists */ 1281 if (!joycon_check_for_cal_magic(ctlr, JC_IMU_CAL_USR_MAGIC_ADDR)) { 1282 imu_cal_addr = JC_IMU_CAL_USR_DATA_ADDR; 1283 hid_info(ctlr->hdev, "using user cal for IMU\n"); 1284 } else { 1285 hid_info(ctlr->hdev, "using factory cal for IMU\n"); 1286 } 1287 1288 /* request IMU calibration data */ 1289 hid_dbg(ctlr->hdev, "requesting IMU cal data\n"); 1290 ret = joycon_request_spi_flash_read(ctlr, imu_cal_addr, 1291 JC_IMU_CAL_DATA_SIZE, &raw_cal); 1292 if (ret) { 1293 hid_warn(ctlr->hdev, 1294 "Failed to read IMU cal, using defaults; ret=%d\n", 1295 ret); 1296 1297 for (i = 0; i < 3; i++) { 1298 ctlr->accel_cal.offset[i] = DFLT_ACCEL_OFFSET; 1299 ctlr->accel_cal.scale[i] = DFLT_ACCEL_SCALE; 1300 ctlr->gyro_cal.offset[i] = DFLT_GYRO_OFFSET; 1301 ctlr->gyro_cal.scale[i] = DFLT_GYRO_SCALE; 1302 } 1303 joycon_calc_imu_cal_divisors(ctlr); 1304 return ret; 1305 } 1306 1307 /* IMU calibration parsing */ 1308 for (i = 0; i < 3; i++) { 1309 int j = i * 2; 1310 1311 ctlr->accel_cal.offset[i] = get_unaligned_le16(raw_cal + j); 1312 ctlr->accel_cal.scale[i] = get_unaligned_le16(raw_cal + j + 6); 1313 ctlr->gyro_cal.offset[i] = get_unaligned_le16(raw_cal + j + 12); 1314 ctlr->gyro_cal.scale[i] = get_unaligned_le16(raw_cal + j + 18); 1315 } 1316 1317 joycon_calc_imu_cal_divisors(ctlr); 1318 1319 hid_dbg(ctlr->hdev, "IMU calibration:\n" 1320 "a_o[0]=%d a_o[1]=%d a_o[2]=%d\n" 1321 "a_s[0]=%d a_s[1]=%d a_s[2]=%d\n" 1322 "g_o[0]=%d g_o[1]=%d g_o[2]=%d\n" 1323 "g_s[0]=%d g_s[1]=%d g_s[2]=%d\n", 1324 ctlr->accel_cal.offset[0], 1325 ctlr->accel_cal.offset[1], 1326 ctlr->accel_cal.offset[2], 1327 ctlr->accel_cal.scale[0], 1328 ctlr->accel_cal.scale[1], 1329 ctlr->accel_cal.scale[2], 1330 ctlr->gyro_cal.offset[0], 1331 ctlr->gyro_cal.offset[1], 1332 ctlr->gyro_cal.offset[2], 1333 ctlr->gyro_cal.scale[0], 1334 ctlr->gyro_cal.scale[1], 1335 ctlr->gyro_cal.scale[2]); 1336 1337 return 0; 1338 } 1339 1340 static int joycon_set_report_mode(struct joycon_ctlr *ctlr) 1341 { 1342 struct joycon_subcmd_request *req; 1343 u8 buffer[sizeof(*req) + 1] = { 0 }; 1344 1345 req = (struct joycon_subcmd_request *)buffer; 1346 req->subcmd_id = JC_SUBCMD_SET_REPORT_MODE; 1347 req->data[0] = 0x30; /* standard, full report mode */ 1348 1349 hid_dbg(ctlr->hdev, "setting controller report mode\n"); 1350 return joycon_send_subcmd(ctlr, req, 1, HZ); 1351 } 1352 1353 static int joycon_enable_rumble(struct joycon_ctlr *ctlr) 1354 { 1355 struct joycon_subcmd_request *req; 1356 u8 buffer[sizeof(*req) + 1] = { 0 }; 1357 1358 req = (struct joycon_subcmd_request *)buffer; 1359 req->subcmd_id = JC_SUBCMD_ENABLE_VIBRATION; 1360 req->data[0] = 0x01; /* note: 0x00 would disable */ 1361 1362 hid_dbg(ctlr->hdev, "enabling rumble\n"); 1363 return joycon_send_subcmd(ctlr, req, 1, HZ/4); 1364 } 1365 1366 static int joycon_enable_imu(struct joycon_ctlr *ctlr) 1367 { 1368 struct joycon_subcmd_request *req; 1369 u8 buffer[sizeof(*req) + 1] = { 0 }; 1370 1371 req = (struct joycon_subcmd_request *)buffer; 1372 req->subcmd_id = JC_SUBCMD_ENABLE_IMU; 1373 req->data[0] = 0x01; /* note: 0x00 would disable */ 1374 1375 hid_dbg(ctlr->hdev, "enabling IMU\n"); 1376 return joycon_send_subcmd(ctlr, req, 1, HZ); 1377 } 1378 1379 static s32 joycon_map_stick_val(struct joycon_stick_cal *cal, s32 val) 1380 { 1381 s32 center = cal->center; 1382 s32 min = cal->min; 1383 s32 max = cal->max; 1384 s32 new_val; 1385 1386 if (val > center) { 1387 new_val = (val - center) * JC_MAX_STICK_MAG; 1388 new_val /= (max - center); 1389 } else { 1390 new_val = (center - val) * -JC_MAX_STICK_MAG; 1391 new_val /= (center - min); 1392 } 1393 new_val = clamp(new_val, (s32)-JC_MAX_STICK_MAG, (s32)JC_MAX_STICK_MAG); 1394 return new_val; 1395 } 1396 1397 static void joycon_input_report_parse_imu_data(struct joycon_ctlr *ctlr, 1398 struct joycon_input_report *rep, 1399 struct joycon_imu_data *imu_data) 1400 { 1401 u8 *raw = rep->imu_raw_bytes; 1402 int i; 1403 1404 for (i = 0; i < 3; i++) { 1405 struct joycon_imu_data *data = &imu_data[i]; 1406 1407 data->accel_x = get_unaligned_le16(raw + 0); 1408 data->accel_y = get_unaligned_le16(raw + 2); 1409 data->accel_z = get_unaligned_le16(raw + 4); 1410 data->gyro_x = get_unaligned_le16(raw + 6); 1411 data->gyro_y = get_unaligned_le16(raw + 8); 1412 data->gyro_z = get_unaligned_le16(raw + 10); 1413 /* point to next imu sample */ 1414 raw += sizeof(struct joycon_imu_data); 1415 } 1416 } 1417 1418 static void joycon_parse_imu_report(struct joycon_ctlr *ctlr, 1419 struct joycon_input_report *rep) 1420 { 1421 struct joycon_imu_data imu_data[3] = {0}; /* 3 reports per packet */ 1422 struct input_dev *idev = ctlr->imu_input; 1423 unsigned int msecs = jiffies_to_msecs(jiffies); 1424 unsigned int last_msecs = ctlr->imu_last_pkt_ms; 1425 int i; 1426 int value[6]; 1427 1428 joycon_input_report_parse_imu_data(ctlr, rep, imu_data); 1429 1430 /* 1431 * There are complexities surrounding how we determine the timestamps we 1432 * associate with the samples we pass to userspace. The IMU input 1433 * reports do not provide us with a good timestamp. There's a quickly 1434 * incrementing 8-bit counter per input report, but it is not very 1435 * useful for this purpose (it is not entirely clear what rate it 1436 * increments at or if it varies based on packet push rate - more on 1437 * the push rate below...). 1438 * 1439 * The reverse engineering work done on the joy-cons and pro controllers 1440 * by the community seems to indicate the following: 1441 * - The controller samples the IMU every 1.35ms. It then does some of 1442 * its own processing, probably averaging the samples out. 1443 * - Each imu input report contains 3 IMU samples, (usually 5ms apart). 1444 * - In the standard reporting mode (which this driver uses exclusively) 1445 * input reports are pushed from the controller as follows: 1446 * * joy-con (bluetooth): every 15 ms 1447 * * joy-cons (in charging grip via USB): every 15 ms 1448 * * pro controller (USB): every 15 ms 1449 * * pro controller (bluetooth): every 8 ms (this is the wildcard) 1450 * 1451 * Further complicating matters is that some bluetooth stacks are known 1452 * to alter the controller's packet rate by hardcoding the bluetooth 1453 * SSR for the switch controllers (android's stack currently sets the 1454 * SSR to 11ms for both the joy-cons and pro controllers). 1455 * 1456 * In my own testing, I've discovered that my pro controller either 1457 * reports IMU sample batches every 11ms or every 15ms. This rate is 1458 * stable after connecting. It isn't 100% clear what determines this 1459 * rate. Importantly, even when sending every 11ms, none of the samples 1460 * are duplicates. This seems to indicate that the time deltas between 1461 * reported samples can vary based on the input report rate. 1462 * 1463 * The solution employed in this driver is to keep track of the average 1464 * time delta between IMU input reports. In testing, this value has 1465 * proven to be stable, staying at 15ms or 11ms, though other hardware 1466 * configurations and bluetooth stacks could potentially see other rates 1467 * (hopefully this will become more clear as more people use the 1468 * driver). 1469 * 1470 * Keeping track of the average report delta allows us to submit our 1471 * timestamps to userspace based on that. Each report contains 3 1472 * samples, so the IMU sampling rate should be avg_time_delta/3. We can 1473 * also use this average to detect events where we have dropped a 1474 * packet. The userspace timestamp for the samples will be adjusted 1475 * accordingly to prevent unwanted behvaior. 1476 */ 1477 if (!ctlr->imu_first_packet_received) { 1478 ctlr->imu_timestamp_us = 0; 1479 ctlr->imu_delta_samples_count = 0; 1480 ctlr->imu_delta_samples_sum = 0; 1481 ctlr->imu_avg_delta_ms = JC_IMU_DFLT_AVG_DELTA_MS; 1482 ctlr->imu_first_packet_received = true; 1483 } else { 1484 unsigned int delta = msecs - last_msecs; 1485 unsigned int dropped_pkts; 1486 unsigned int dropped_threshold; 1487 1488 /* avg imu report delta housekeeping */ 1489 ctlr->imu_delta_samples_sum += delta; 1490 ctlr->imu_delta_samples_count++; 1491 if (ctlr->imu_delta_samples_count >= 1492 JC_IMU_SAMPLES_PER_DELTA_AVG) { 1493 ctlr->imu_avg_delta_ms = ctlr->imu_delta_samples_sum / 1494 ctlr->imu_delta_samples_count; 1495 ctlr->imu_delta_samples_count = 0; 1496 ctlr->imu_delta_samples_sum = 0; 1497 } 1498 1499 /* don't ever want divide by zero shenanigans */ 1500 if (ctlr->imu_avg_delta_ms == 0) { 1501 ctlr->imu_avg_delta_ms = 1; 1502 hid_warn(ctlr->hdev, "calculated avg imu delta of 0\n"); 1503 } 1504 1505 /* useful for debugging IMU sample rate */ 1506 hid_dbg(ctlr->hdev, 1507 "imu_report: ms=%u last_ms=%u delta=%u avg_delta=%u\n", 1508 msecs, last_msecs, delta, ctlr->imu_avg_delta_ms); 1509 1510 /* check if any packets have been dropped */ 1511 dropped_threshold = ctlr->imu_avg_delta_ms * 3 / 2; 1512 dropped_pkts = (delta - min(delta, dropped_threshold)) / 1513 ctlr->imu_avg_delta_ms; 1514 if (dropped_pkts > JC_IMU_DROPPED_PKT_WARNING) { 1515 hid_warn_ratelimited(ctlr->hdev, 1516 "compensating for %u dropped IMU reports\n", 1517 dropped_pkts); 1518 hid_warn_ratelimited(ctlr->hdev, 1519 "delta=%u avg_delta=%u\n", 1520 delta, ctlr->imu_avg_delta_ms); 1521 } 1522 } 1523 ctlr->imu_last_pkt_ms = msecs; 1524 1525 /* Each IMU input report contains three samples */ 1526 for (i = 0; i < 3; i++) { 1527 input_event(idev, EV_MSC, MSC_TIMESTAMP, 1528 ctlr->imu_timestamp_us); 1529 1530 /* 1531 * These calculations (which use the controller's calibration 1532 * settings to improve the final values) are based on those 1533 * found in the community's reverse-engineering repo (linked at 1534 * top of driver). For hid-nintendo, we make sure that the final 1535 * value given to userspace is always in terms of the axis 1536 * resolution we provided. 1537 * 1538 * Currently only the gyro calculations subtract the calibration 1539 * offsets from the raw value itself. In testing, doing the same 1540 * for the accelerometer raw values decreased accuracy. 1541 * 1542 * Note that the gyro values are multiplied by the 1543 * precision-saving scaling factor to prevent large inaccuracies 1544 * due to truncation of the resolution value which would 1545 * otherwise occur. To prevent overflow (without resorting to 64 1546 * bit integer math), the mult_frac macro is used. 1547 */ 1548 value[0] = mult_frac((JC_IMU_PREC_RANGE_SCALE * 1549 (imu_data[i].gyro_x - 1550 ctlr->gyro_cal.offset[0])), 1551 ctlr->gyro_cal.scale[0], 1552 ctlr->imu_cal_gyro_divisor[0]); 1553 value[1] = mult_frac((JC_IMU_PREC_RANGE_SCALE * 1554 (imu_data[i].gyro_y - 1555 ctlr->gyro_cal.offset[1])), 1556 ctlr->gyro_cal.scale[1], 1557 ctlr->imu_cal_gyro_divisor[1]); 1558 value[2] = mult_frac((JC_IMU_PREC_RANGE_SCALE * 1559 (imu_data[i].gyro_z - 1560 ctlr->gyro_cal.offset[2])), 1561 ctlr->gyro_cal.scale[2], 1562 ctlr->imu_cal_gyro_divisor[2]); 1563 1564 value[3] = ((s32)imu_data[i].accel_x * 1565 ctlr->accel_cal.scale[0]) / 1566 ctlr->imu_cal_accel_divisor[0]; 1567 value[4] = ((s32)imu_data[i].accel_y * 1568 ctlr->accel_cal.scale[1]) / 1569 ctlr->imu_cal_accel_divisor[1]; 1570 value[5] = ((s32)imu_data[i].accel_z * 1571 ctlr->accel_cal.scale[2]) / 1572 ctlr->imu_cal_accel_divisor[2]; 1573 1574 hid_dbg(ctlr->hdev, "raw_gyro: g_x=%d g_y=%d g_z=%d\n", 1575 imu_data[i].gyro_x, imu_data[i].gyro_y, 1576 imu_data[i].gyro_z); 1577 hid_dbg(ctlr->hdev, "raw_accel: a_x=%d a_y=%d a_z=%d\n", 1578 imu_data[i].accel_x, imu_data[i].accel_y, 1579 imu_data[i].accel_z); 1580 1581 /* 1582 * The right joy-con has 2 axes negated, Y and Z. This is due to 1583 * the orientation of the IMU in the controller. We negate those 1584 * axes' values in order to be consistent with the left joy-con 1585 * and the pro controller: 1586 * X: positive is pointing toward the triggers 1587 * Y: positive is pointing to the left 1588 * Z: positive is pointing up (out of the buttons/sticks) 1589 * The axes follow the right-hand rule. 1590 */ 1591 if (jc_type_is_joycon(ctlr) && jc_type_has_right(ctlr)) { 1592 int j; 1593 1594 /* negate all but x axis */ 1595 for (j = 1; j < 6; ++j) { 1596 if (j == 3) 1597 continue; 1598 value[j] *= -1; 1599 } 1600 } 1601 1602 input_report_abs(idev, ABS_RX, value[0]); 1603 input_report_abs(idev, ABS_RY, value[1]); 1604 input_report_abs(idev, ABS_RZ, value[2]); 1605 input_report_abs(idev, ABS_X, value[3]); 1606 input_report_abs(idev, ABS_Y, value[4]); 1607 input_report_abs(idev, ABS_Z, value[5]); 1608 input_sync(idev); 1609 /* convert to micros and divide by 3 (3 samples per report). */ 1610 ctlr->imu_timestamp_us += ctlr->imu_avg_delta_ms * 1000 / 3; 1611 } 1612 } 1613 1614 static void joycon_handle_rumble_report(struct joycon_ctlr *ctlr, struct joycon_input_report *rep) 1615 { 1616 unsigned long flags; 1617 unsigned long msecs = jiffies_to_msecs(jiffies); 1618 1619 spin_lock_irqsave(&ctlr->lock, flags); 1620 if (IS_ENABLED(CONFIG_NINTENDO_FF) && rep->vibrator_report && 1621 ctlr->ctlr_state != JOYCON_CTLR_STATE_REMOVED && 1622 (msecs - ctlr->rumble_msecs) >= JC_RUMBLE_PERIOD_MS && 1623 (ctlr->rumble_queue_head != ctlr->rumble_queue_tail || 1624 ctlr->rumble_zero_countdown > 0)) { 1625 /* 1626 * When this value reaches 0, we know we've sent multiple 1627 * packets to the controller instructing it to disable rumble. 1628 * We can safely stop sending periodic rumble packets until the 1629 * next ff effect. 1630 */ 1631 if (ctlr->rumble_zero_countdown > 0) 1632 ctlr->rumble_zero_countdown--; 1633 queue_work(ctlr->rumble_queue, &ctlr->rumble_worker); 1634 } 1635 1636 spin_unlock_irqrestore(&ctlr->lock, flags); 1637 } 1638 1639 static void joycon_parse_battery_status(struct joycon_ctlr *ctlr, struct joycon_input_report *rep) 1640 { 1641 u8 tmp; 1642 unsigned long flags; 1643 1644 spin_lock_irqsave(&ctlr->lock, flags); 1645 1646 tmp = rep->bat_con; 1647 ctlr->host_powered = tmp & BIT(0); 1648 ctlr->battery_charging = tmp & BIT(4); 1649 tmp = tmp >> 5; 1650 1651 switch (tmp) { 1652 case 0: /* empty */ 1653 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL; 1654 break; 1655 case 1: /* low */ 1656 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_LOW; 1657 break; 1658 case 2: /* medium */ 1659 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL; 1660 break; 1661 case 3: /* high */ 1662 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_HIGH; 1663 break; 1664 case 4: /* full */ 1665 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_FULL; 1666 break; 1667 default: 1668 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN; 1669 hid_warn(ctlr->hdev, "Invalid battery status\n"); 1670 break; 1671 } 1672 1673 spin_unlock_irqrestore(&ctlr->lock, flags); 1674 } 1675 1676 static void joycon_report_left_stick(struct joycon_ctlr *ctlr, 1677 struct joycon_input_report *rep) 1678 { 1679 u16 raw_x; 1680 u16 raw_y; 1681 s32 x; 1682 s32 y; 1683 1684 raw_x = hid_field_extract(ctlr->hdev, rep->left_stick, 0, 12); 1685 raw_y = hid_field_extract(ctlr->hdev, rep->left_stick + 1, 4, 12); 1686 1687 x = joycon_map_stick_val(&ctlr->left_stick_cal_x, raw_x); 1688 y = -joycon_map_stick_val(&ctlr->left_stick_cal_y, raw_y); 1689 1690 input_report_abs(ctlr->input, ABS_X, x); 1691 input_report_abs(ctlr->input, ABS_Y, y); 1692 } 1693 1694 static void joycon_report_right_stick(struct joycon_ctlr *ctlr, 1695 struct joycon_input_report *rep) 1696 { 1697 u16 raw_x; 1698 u16 raw_y; 1699 s32 x; 1700 s32 y; 1701 1702 raw_x = hid_field_extract(ctlr->hdev, rep->right_stick, 0, 12); 1703 raw_y = hid_field_extract(ctlr->hdev, rep->right_stick + 1, 4, 12); 1704 1705 x = joycon_map_stick_val(&ctlr->right_stick_cal_x, raw_x); 1706 y = -joycon_map_stick_val(&ctlr->right_stick_cal_y, raw_y); 1707 1708 input_report_abs(ctlr->input, ABS_RX, x); 1709 input_report_abs(ctlr->input, ABS_RY, y); 1710 } 1711 1712 static void joycon_report_dpad(struct joycon_ctlr *ctlr, 1713 struct joycon_input_report *rep) 1714 { 1715 int hatx = 0; 1716 int haty = 0; 1717 u32 btns = hid_field_extract(ctlr->hdev, rep->button_status, 0, 24); 1718 1719 if (btns & JC_BTN_LEFT) 1720 hatx = -1; 1721 else if (btns & JC_BTN_RIGHT) 1722 hatx = 1; 1723 1724 if (btns & JC_BTN_UP) 1725 haty = -1; 1726 else if (btns & JC_BTN_DOWN) 1727 haty = 1; 1728 1729 input_report_abs(ctlr->input, ABS_HAT0X, hatx); 1730 input_report_abs(ctlr->input, ABS_HAT0Y, haty); 1731 } 1732 1733 static void joycon_report_buttons(struct joycon_ctlr *ctlr, 1734 struct joycon_input_report *rep, 1735 const struct joycon_ctlr_button_mapping button_mappings[]) 1736 { 1737 const struct joycon_ctlr_button_mapping *button; 1738 u32 status = hid_field_extract(ctlr->hdev, rep->button_status, 0, 24); 1739 1740 for (button = button_mappings; button->code; button++) 1741 input_report_key(ctlr->input, button->code, status & button->bit); 1742 } 1743 1744 static void joycon_parse_report(struct joycon_ctlr *ctlr, 1745 struct joycon_input_report *rep) 1746 { 1747 unsigned long flags; 1748 unsigned long msecs = jiffies_to_msecs(jiffies); 1749 unsigned long report_delta_ms = msecs - ctlr->last_input_report_msecs; 1750 1751 if (joycon_has_rumble(ctlr)) 1752 joycon_handle_rumble_report(ctlr, rep); 1753 1754 joycon_parse_battery_status(ctlr, rep); 1755 1756 if (joycon_type_is_left_joycon(ctlr)) { 1757 joycon_report_left_stick(ctlr, rep); 1758 joycon_report_buttons(ctlr, rep, left_joycon_button_mappings); 1759 if (!joycon_device_is_chrggrip(ctlr)) 1760 joycon_report_buttons(ctlr, rep, left_joycon_s_button_mappings); 1761 } else if (joycon_type_is_right_joycon(ctlr)) { 1762 joycon_report_right_stick(ctlr, rep); 1763 joycon_report_buttons(ctlr, rep, right_joycon_button_mappings); 1764 if (!joycon_device_is_chrggrip(ctlr)) 1765 joycon_report_buttons(ctlr, rep, right_joycon_s_button_mappings); 1766 } else if (joycon_type_is_procon(ctlr)) { 1767 joycon_report_left_stick(ctlr, rep); 1768 joycon_report_right_stick(ctlr, rep); 1769 joycon_report_dpad(ctlr, rep); 1770 if (ctlr->ctlr_type == JOYCON_CTLR_TYPE_LIC_PRO) 1771 joycon_report_buttons(ctlr, rep, lic_procon_button_mappings); 1772 else 1773 joycon_report_buttons(ctlr, rep, procon_button_mappings); 1774 } else if (joycon_type_is_any_nescon(ctlr)) { 1775 joycon_report_dpad(ctlr, rep); 1776 joycon_report_buttons(ctlr, rep, nescon_button_mappings); 1777 } else if (joycon_type_is_snescon(ctlr)) { 1778 joycon_report_dpad(ctlr, rep); 1779 joycon_report_buttons(ctlr, rep, snescon_button_mappings); 1780 } else if (joycon_type_is_gencon(ctlr)) { 1781 joycon_report_dpad(ctlr, rep); 1782 joycon_report_buttons(ctlr, rep, gencon_button_mappings); 1783 } else if (joycon_type_is_n64con(ctlr)) { 1784 joycon_report_left_stick(ctlr, rep); 1785 joycon_report_dpad(ctlr, rep); 1786 joycon_report_buttons(ctlr, rep, n64con_button_mappings); 1787 } 1788 1789 input_sync(ctlr->input); 1790 1791 spin_lock_irqsave(&ctlr->lock, flags); 1792 ctlr->last_input_report_msecs = msecs; 1793 /* 1794 * Was this input report a reasonable time delta compared to the prior 1795 * report? We use this information to decide when a safe time is to send 1796 * rumble packets or subcommand packets. 1797 */ 1798 if (report_delta_ms >= JC_INPUT_REPORT_MIN_DELTA && 1799 report_delta_ms <= JC_INPUT_REPORT_MAX_DELTA) { 1800 if (ctlr->consecutive_valid_report_deltas < JC_SUBCMD_VALID_DELTA_REQ) 1801 ctlr->consecutive_valid_report_deltas++; 1802 } else { 1803 ctlr->consecutive_valid_report_deltas = 0; 1804 } 1805 /* 1806 * Our consecutive valid report tracking is only relevant for 1807 * bluetooth-connected controllers. For USB devices, we're beholden to 1808 * USB's underlying polling rate anyway. Always set to the consecutive 1809 * delta requirement. 1810 */ 1811 if (ctlr->hdev->bus == BUS_USB) 1812 ctlr->consecutive_valid_report_deltas = JC_SUBCMD_VALID_DELTA_REQ; 1813 1814 spin_unlock_irqrestore(&ctlr->lock, flags); 1815 1816 /* 1817 * Immediately after receiving a report is the most reliable time to 1818 * send a subcommand to the controller. Wake any subcommand senders 1819 * waiting for a report. 1820 */ 1821 if (unlikely(mutex_is_locked(&ctlr->output_mutex))) { 1822 spin_lock_irqsave(&ctlr->lock, flags); 1823 ctlr->received_input_report = true; 1824 spin_unlock_irqrestore(&ctlr->lock, flags); 1825 wake_up(&ctlr->wait); 1826 } 1827 1828 /* parse IMU data if present */ 1829 if ((rep->id == JC_INPUT_IMU_DATA) && joycon_has_imu(ctlr)) 1830 joycon_parse_imu_report(ctlr, rep); 1831 } 1832 1833 static int joycon_send_rumble_data(struct joycon_ctlr *ctlr) 1834 { 1835 int ret; 1836 unsigned long flags; 1837 struct joycon_rumble_output rumble_output = { 0 }; 1838 1839 spin_lock_irqsave(&ctlr->lock, flags); 1840 /* 1841 * If the controller has been removed, just return ENODEV so the LED 1842 * subsystem doesn't print invalid errors on removal. 1843 */ 1844 if (ctlr->ctlr_state == JOYCON_CTLR_STATE_REMOVED) { 1845 spin_unlock_irqrestore(&ctlr->lock, flags); 1846 return -ENODEV; 1847 } 1848 memcpy(rumble_output.rumble_data, 1849 ctlr->rumble_data[ctlr->rumble_queue_tail], 1850 JC_RUMBLE_DATA_SIZE); 1851 spin_unlock_irqrestore(&ctlr->lock, flags); 1852 1853 rumble_output.output_id = JC_OUTPUT_RUMBLE_ONLY; 1854 rumble_output.packet_num = ctlr->subcmd_num; 1855 if (++ctlr->subcmd_num > 0xF) 1856 ctlr->subcmd_num = 0; 1857 1858 joycon_enforce_subcmd_rate(ctlr); 1859 1860 ret = __joycon_hid_send(ctlr->hdev, (u8 *)&rumble_output, 1861 sizeof(rumble_output)); 1862 return ret; 1863 } 1864 1865 static void joycon_rumble_worker(struct work_struct *work) 1866 { 1867 struct joycon_ctlr *ctlr = container_of(work, struct joycon_ctlr, 1868 rumble_worker); 1869 unsigned long flags; 1870 bool again = true; 1871 int ret; 1872 1873 while (again) { 1874 mutex_lock(&ctlr->output_mutex); 1875 ret = joycon_send_rumble_data(ctlr); 1876 mutex_unlock(&ctlr->output_mutex); 1877 1878 /* -ENODEV means the controller was just unplugged */ 1879 spin_lock_irqsave(&ctlr->lock, flags); 1880 if (ret < 0 && ret != -ENODEV && 1881 ctlr->ctlr_state != JOYCON_CTLR_STATE_REMOVED) 1882 hid_warn(ctlr->hdev, "Failed to set rumble; e=%d", ret); 1883 1884 ctlr->rumble_msecs = jiffies_to_msecs(jiffies); 1885 if (ctlr->rumble_queue_tail != ctlr->rumble_queue_head) { 1886 if (++ctlr->rumble_queue_tail >= JC_RUMBLE_QUEUE_SIZE) 1887 ctlr->rumble_queue_tail = 0; 1888 } else { 1889 again = false; 1890 } 1891 spin_unlock_irqrestore(&ctlr->lock, flags); 1892 } 1893 } 1894 1895 #if IS_ENABLED(CONFIG_NINTENDO_FF) 1896 static struct joycon_rumble_freq_data joycon_find_rumble_freq(u16 freq) 1897 { 1898 const size_t length = ARRAY_SIZE(joycon_rumble_frequencies); 1899 const struct joycon_rumble_freq_data *data = joycon_rumble_frequencies; 1900 int i = 0; 1901 1902 if (freq > data[0].freq) { 1903 for (i = 1; i < length - 1; i++) { 1904 if (freq > data[i - 1].freq && freq <= data[i].freq) 1905 break; 1906 } 1907 } 1908 1909 return data[i]; 1910 } 1911 1912 static struct joycon_rumble_amp_data joycon_find_rumble_amp(u16 amp) 1913 { 1914 const size_t length = ARRAY_SIZE(joycon_rumble_amplitudes); 1915 const struct joycon_rumble_amp_data *data = joycon_rumble_amplitudes; 1916 int i = 0; 1917 1918 if (amp > data[0].amp) { 1919 for (i = 1; i < length - 1; i++) { 1920 if (amp > data[i - 1].amp && amp <= data[i].amp) 1921 break; 1922 } 1923 } 1924 1925 return data[i]; 1926 } 1927 1928 static void joycon_encode_rumble(u8 *data, u16 freq_low, u16 freq_high, u16 amp) 1929 { 1930 struct joycon_rumble_freq_data freq_data_low; 1931 struct joycon_rumble_freq_data freq_data_high; 1932 struct joycon_rumble_amp_data amp_data; 1933 1934 freq_data_low = joycon_find_rumble_freq(freq_low); 1935 freq_data_high = joycon_find_rumble_freq(freq_high); 1936 amp_data = joycon_find_rumble_amp(amp); 1937 1938 data[0] = (freq_data_high.high >> 8) & 0xFF; 1939 data[1] = (freq_data_high.high & 0xFF) + amp_data.high; 1940 data[2] = freq_data_low.low + ((amp_data.low >> 8) & 0xFF); 1941 data[3] = amp_data.low & 0xFF; 1942 } 1943 1944 static const u16 JOYCON_MAX_RUMBLE_HIGH_FREQ = 1253; 1945 static const u16 JOYCON_MIN_RUMBLE_HIGH_FREQ = 82; 1946 static const u16 JOYCON_MAX_RUMBLE_LOW_FREQ = 626; 1947 static const u16 JOYCON_MIN_RUMBLE_LOW_FREQ = 41; 1948 1949 static void joycon_clamp_rumble_freqs(struct joycon_ctlr *ctlr) 1950 { 1951 unsigned long flags; 1952 1953 spin_lock_irqsave(&ctlr->lock, flags); 1954 ctlr->rumble_ll_freq = clamp(ctlr->rumble_ll_freq, 1955 JOYCON_MIN_RUMBLE_LOW_FREQ, 1956 JOYCON_MAX_RUMBLE_LOW_FREQ); 1957 ctlr->rumble_lh_freq = clamp(ctlr->rumble_lh_freq, 1958 JOYCON_MIN_RUMBLE_HIGH_FREQ, 1959 JOYCON_MAX_RUMBLE_HIGH_FREQ); 1960 ctlr->rumble_rl_freq = clamp(ctlr->rumble_rl_freq, 1961 JOYCON_MIN_RUMBLE_LOW_FREQ, 1962 JOYCON_MAX_RUMBLE_LOW_FREQ); 1963 ctlr->rumble_rh_freq = clamp(ctlr->rumble_rh_freq, 1964 JOYCON_MIN_RUMBLE_HIGH_FREQ, 1965 JOYCON_MAX_RUMBLE_HIGH_FREQ); 1966 spin_unlock_irqrestore(&ctlr->lock, flags); 1967 } 1968 1969 static int joycon_set_rumble(struct joycon_ctlr *ctlr, u16 amp_r, u16 amp_l, 1970 bool schedule_now) 1971 { 1972 u8 data[JC_RUMBLE_DATA_SIZE]; 1973 u16 amp; 1974 u16 freq_r_low; 1975 u16 freq_r_high; 1976 u16 freq_l_low; 1977 u16 freq_l_high; 1978 unsigned long flags; 1979 int next_rq_head; 1980 1981 spin_lock_irqsave(&ctlr->lock, flags); 1982 freq_r_low = ctlr->rumble_rl_freq; 1983 freq_r_high = ctlr->rumble_rh_freq; 1984 freq_l_low = ctlr->rumble_ll_freq; 1985 freq_l_high = ctlr->rumble_lh_freq; 1986 /* limit number of silent rumble packets to reduce traffic */ 1987 if (amp_l != 0 || amp_r != 0) 1988 ctlr->rumble_zero_countdown = JC_RUMBLE_ZERO_AMP_PKT_CNT; 1989 spin_unlock_irqrestore(&ctlr->lock, flags); 1990 1991 /* right joy-con */ 1992 amp = amp_r * (u32)joycon_max_rumble_amp / 65535; 1993 joycon_encode_rumble(data + 4, freq_r_low, freq_r_high, amp); 1994 1995 /* left joy-con */ 1996 amp = amp_l * (u32)joycon_max_rumble_amp / 65535; 1997 joycon_encode_rumble(data, freq_l_low, freq_l_high, amp); 1998 1999 spin_lock_irqsave(&ctlr->lock, flags); 2000 2001 next_rq_head = ctlr->rumble_queue_head + 1; 2002 if (next_rq_head >= JC_RUMBLE_QUEUE_SIZE) 2003 next_rq_head = 0; 2004 2005 /* Did we overrun the circular buffer? 2006 * If so, be sure we keep the latest intended rumble state. 2007 */ 2008 if (next_rq_head == ctlr->rumble_queue_tail) { 2009 hid_dbg(ctlr->hdev, "rumble queue is full"); 2010 /* overwrite the prior value at the end of the circular buf */ 2011 next_rq_head = ctlr->rumble_queue_head; 2012 } 2013 2014 ctlr->rumble_queue_head = next_rq_head; 2015 memcpy(ctlr->rumble_data[ctlr->rumble_queue_head], data, 2016 JC_RUMBLE_DATA_SIZE); 2017 2018 /* don't wait for the periodic send (reduces latency) */ 2019 if (schedule_now && ctlr->ctlr_state != JOYCON_CTLR_STATE_REMOVED) 2020 queue_work(ctlr->rumble_queue, &ctlr->rumble_worker); 2021 2022 spin_unlock_irqrestore(&ctlr->lock, flags); 2023 2024 return 0; 2025 } 2026 2027 static int joycon_play_effect(struct input_dev *dev, void *data, 2028 struct ff_effect *effect) 2029 { 2030 struct joycon_ctlr *ctlr = input_get_drvdata(dev); 2031 2032 if (effect->type != FF_RUMBLE) 2033 return 0; 2034 2035 return joycon_set_rumble(ctlr, 2036 effect->u.rumble.weak_magnitude, 2037 effect->u.rumble.strong_magnitude, 2038 true); 2039 } 2040 #endif /* IS_ENABLED(CONFIG_NINTENDO_FF) */ 2041 2042 static void joycon_config_left_stick(struct input_dev *idev) 2043 { 2044 input_set_abs_params(idev, 2045 ABS_X, 2046 -JC_MAX_STICK_MAG, 2047 JC_MAX_STICK_MAG, 2048 JC_STICK_FUZZ, 2049 JC_STICK_FLAT); 2050 input_set_abs_params(idev, 2051 ABS_Y, 2052 -JC_MAX_STICK_MAG, 2053 JC_MAX_STICK_MAG, 2054 JC_STICK_FUZZ, 2055 JC_STICK_FLAT); 2056 } 2057 2058 static void joycon_config_right_stick(struct input_dev *idev) 2059 { 2060 input_set_abs_params(idev, 2061 ABS_RX, 2062 -JC_MAX_STICK_MAG, 2063 JC_MAX_STICK_MAG, 2064 JC_STICK_FUZZ, 2065 JC_STICK_FLAT); 2066 input_set_abs_params(idev, 2067 ABS_RY, 2068 -JC_MAX_STICK_MAG, 2069 JC_MAX_STICK_MAG, 2070 JC_STICK_FUZZ, 2071 JC_STICK_FLAT); 2072 } 2073 2074 static void joycon_config_dpad(struct input_dev *idev) 2075 { 2076 input_set_abs_params(idev, 2077 ABS_HAT0X, 2078 -JC_MAX_DPAD_MAG, 2079 JC_MAX_DPAD_MAG, 2080 JC_DPAD_FUZZ, 2081 JC_DPAD_FLAT); 2082 input_set_abs_params(idev, 2083 ABS_HAT0Y, 2084 -JC_MAX_DPAD_MAG, 2085 JC_MAX_DPAD_MAG, 2086 JC_DPAD_FUZZ, 2087 JC_DPAD_FLAT); 2088 } 2089 2090 static void joycon_config_buttons(struct input_dev *idev, 2091 const struct joycon_ctlr_button_mapping button_mappings[]) 2092 { 2093 const struct joycon_ctlr_button_mapping *button; 2094 2095 for (button = button_mappings; button->code; button++) 2096 input_set_capability(idev, EV_KEY, button->code); 2097 } 2098 2099 static void joycon_config_rumble(struct joycon_ctlr *ctlr) 2100 { 2101 #if IS_ENABLED(CONFIG_NINTENDO_FF) 2102 /* set up rumble */ 2103 input_set_capability(ctlr->input, EV_FF, FF_RUMBLE); 2104 input_ff_create_memless(ctlr->input, NULL, joycon_play_effect); 2105 ctlr->rumble_ll_freq = JC_RUMBLE_DFLT_LOW_FREQ; 2106 ctlr->rumble_lh_freq = JC_RUMBLE_DFLT_HIGH_FREQ; 2107 ctlr->rumble_rl_freq = JC_RUMBLE_DFLT_LOW_FREQ; 2108 ctlr->rumble_rh_freq = JC_RUMBLE_DFLT_HIGH_FREQ; 2109 joycon_clamp_rumble_freqs(ctlr); 2110 joycon_set_rumble(ctlr, 0, 0, false); 2111 ctlr->rumble_msecs = jiffies_to_msecs(jiffies); 2112 #endif 2113 } 2114 2115 static int joycon_imu_input_create(struct joycon_ctlr *ctlr) 2116 { 2117 struct hid_device *hdev; 2118 const char *imu_name; 2119 int ret; 2120 2121 hdev = ctlr->hdev; 2122 2123 /* configure the imu input device */ 2124 ctlr->imu_input = devm_input_allocate_device(&hdev->dev); 2125 if (!ctlr->imu_input) 2126 return -ENOMEM; 2127 2128 ctlr->imu_input->id.bustype = hdev->bus; 2129 ctlr->imu_input->id.vendor = hdev->vendor; 2130 ctlr->imu_input->id.product = hdev->product; 2131 ctlr->imu_input->id.version = hdev->version; 2132 ctlr->imu_input->uniq = ctlr->mac_addr_str; 2133 ctlr->imu_input->phys = hdev->phys; 2134 2135 imu_name = devm_kasprintf(&hdev->dev, GFP_KERNEL, "%s (IMU)", ctlr->input->name); 2136 if (!imu_name) 2137 return -ENOMEM; 2138 2139 ctlr->imu_input->name = imu_name; 2140 2141 input_set_drvdata(ctlr->imu_input, ctlr); 2142 2143 /* configure imu axes */ 2144 input_set_abs_params(ctlr->imu_input, ABS_X, 2145 -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG, 2146 JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT); 2147 input_set_abs_params(ctlr->imu_input, ABS_Y, 2148 -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG, 2149 JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT); 2150 input_set_abs_params(ctlr->imu_input, ABS_Z, 2151 -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG, 2152 JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT); 2153 input_abs_set_res(ctlr->imu_input, ABS_X, JC_IMU_ACCEL_RES_PER_G); 2154 input_abs_set_res(ctlr->imu_input, ABS_Y, JC_IMU_ACCEL_RES_PER_G); 2155 input_abs_set_res(ctlr->imu_input, ABS_Z, JC_IMU_ACCEL_RES_PER_G); 2156 2157 input_set_abs_params(ctlr->imu_input, ABS_RX, 2158 -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG, 2159 JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT); 2160 input_set_abs_params(ctlr->imu_input, ABS_RY, 2161 -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG, 2162 JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT); 2163 input_set_abs_params(ctlr->imu_input, ABS_RZ, 2164 -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG, 2165 JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT); 2166 2167 input_abs_set_res(ctlr->imu_input, ABS_RX, JC_IMU_GYRO_RES_PER_DPS); 2168 input_abs_set_res(ctlr->imu_input, ABS_RY, JC_IMU_GYRO_RES_PER_DPS); 2169 input_abs_set_res(ctlr->imu_input, ABS_RZ, JC_IMU_GYRO_RES_PER_DPS); 2170 2171 __set_bit(EV_MSC, ctlr->imu_input->evbit); 2172 __set_bit(MSC_TIMESTAMP, ctlr->imu_input->mscbit); 2173 __set_bit(INPUT_PROP_ACCELEROMETER, ctlr->imu_input->propbit); 2174 2175 ret = input_register_device(ctlr->imu_input); 2176 if (ret) 2177 return ret; 2178 2179 return 0; 2180 } 2181 2182 static int joycon_input_create(struct joycon_ctlr *ctlr) 2183 { 2184 struct hid_device *hdev; 2185 int ret; 2186 2187 hdev = ctlr->hdev; 2188 2189 ctlr->input = devm_input_allocate_device(&hdev->dev); 2190 if (!ctlr->input) 2191 return -ENOMEM; 2192 ctlr->input->id.bustype = hdev->bus; 2193 ctlr->input->id.vendor = hdev->vendor; 2194 ctlr->input->id.product = hdev->product; 2195 ctlr->input->id.version = hdev->version; 2196 ctlr->input->uniq = ctlr->mac_addr_str; 2197 ctlr->input->name = hdev->name; 2198 ctlr->input->phys = hdev->phys; 2199 input_set_drvdata(ctlr->input, ctlr); 2200 2201 if (joycon_type_is_right_joycon(ctlr)) { 2202 joycon_config_right_stick(ctlr->input); 2203 joycon_config_buttons(ctlr->input, right_joycon_button_mappings); 2204 if (!joycon_device_is_chrggrip(ctlr)) 2205 joycon_config_buttons(ctlr->input, right_joycon_s_button_mappings); 2206 } else if (joycon_type_is_left_joycon(ctlr)) { 2207 joycon_config_left_stick(ctlr->input); 2208 joycon_config_buttons(ctlr->input, left_joycon_button_mappings); 2209 if (!joycon_device_is_chrggrip(ctlr)) 2210 joycon_config_buttons(ctlr->input, left_joycon_s_button_mappings); 2211 } else if (joycon_type_is_procon(ctlr)) { 2212 joycon_config_left_stick(ctlr->input); 2213 joycon_config_right_stick(ctlr->input); 2214 joycon_config_dpad(ctlr->input); 2215 if (ctlr->ctlr_type == JOYCON_CTLR_TYPE_LIC_PRO) 2216 joycon_config_buttons(ctlr->input, lic_procon_button_mappings); 2217 else 2218 joycon_config_buttons(ctlr->input, procon_button_mappings); 2219 } else if (joycon_type_is_any_nescon(ctlr)) { 2220 joycon_config_dpad(ctlr->input); 2221 joycon_config_buttons(ctlr->input, nescon_button_mappings); 2222 } else if (joycon_type_is_snescon(ctlr)) { 2223 joycon_config_dpad(ctlr->input); 2224 joycon_config_buttons(ctlr->input, snescon_button_mappings); 2225 } else if (joycon_type_is_gencon(ctlr)) { 2226 joycon_config_dpad(ctlr->input); 2227 joycon_config_buttons(ctlr->input, gencon_button_mappings); 2228 } else if (joycon_type_is_n64con(ctlr)) { 2229 joycon_config_dpad(ctlr->input); 2230 joycon_config_left_stick(ctlr->input); 2231 joycon_config_buttons(ctlr->input, n64con_button_mappings); 2232 } 2233 2234 if (joycon_has_imu(ctlr)) { 2235 ret = joycon_imu_input_create(ctlr); 2236 if (ret) 2237 return ret; 2238 } 2239 2240 if (joycon_has_rumble(ctlr)) 2241 joycon_config_rumble(ctlr); 2242 2243 ret = input_register_device(ctlr->input); 2244 if (ret) 2245 return ret; 2246 2247 return 0; 2248 } 2249 2250 /* Because the subcommand sets all the leds at once, the brightness argument is ignored */ 2251 static int joycon_player_led_brightness_set(struct led_classdev *led, 2252 enum led_brightness brightness) 2253 { 2254 struct device *dev = led->dev->parent; 2255 struct hid_device *hdev = to_hid_device(dev); 2256 struct joycon_ctlr *ctlr; 2257 int val = 0; 2258 int i; 2259 int ret; 2260 2261 ctlr = hid_get_drvdata(hdev); 2262 if (!ctlr) { 2263 hid_err(hdev, "No controller data\n"); 2264 return -ENODEV; 2265 } 2266 2267 for (i = 0; i < JC_NUM_LEDS; i++) 2268 val |= ctlr->leds[i].brightness << i; 2269 2270 mutex_lock(&ctlr->output_mutex); 2271 ret = joycon_set_player_leds(ctlr, 0, val); 2272 mutex_unlock(&ctlr->output_mutex); 2273 2274 return ret; 2275 } 2276 2277 static int joycon_home_led_brightness_set(struct led_classdev *led, 2278 enum led_brightness brightness) 2279 { 2280 struct device *dev = led->dev->parent; 2281 struct hid_device *hdev = to_hid_device(dev); 2282 struct joycon_ctlr *ctlr; 2283 int ret; 2284 2285 ctlr = hid_get_drvdata(hdev); 2286 if (!ctlr) { 2287 hid_err(hdev, "No controller data\n"); 2288 return -ENODEV; 2289 } 2290 mutex_lock(&ctlr->output_mutex); 2291 ret = joycon_set_home_led(ctlr, brightness); 2292 mutex_unlock(&ctlr->output_mutex); 2293 return ret; 2294 } 2295 2296 static DEFINE_IDA(nintendo_player_id_allocator); 2297 2298 static int joycon_leds_create(struct joycon_ctlr *ctlr) 2299 { 2300 struct hid_device *hdev = ctlr->hdev; 2301 struct device *dev = &hdev->dev; 2302 const char *d_name = dev_name(dev); 2303 struct led_classdev *led; 2304 int led_val = 0; 2305 char *name; 2306 int ret; 2307 int i; 2308 int player_led_pattern; 2309 2310 /* configure the player LEDs */ 2311 ctlr->player_id = U32_MAX; 2312 ret = ida_alloc(&nintendo_player_id_allocator, GFP_KERNEL); 2313 if (ret < 0) { 2314 hid_warn(hdev, "Failed to allocate player ID, skipping; ret=%d\n", ret); 2315 goto home_led; 2316 } 2317 ctlr->player_id = ret; 2318 player_led_pattern = ret % JC_NUM_LED_PATTERNS; 2319 hid_info(ctlr->hdev, "assigned player %d led pattern", player_led_pattern + 1); 2320 2321 for (i = 0; i < JC_NUM_LEDS; i++) { 2322 name = devm_kasprintf(dev, GFP_KERNEL, "%s:%s:%s", 2323 d_name, 2324 "green", 2325 joycon_player_led_names[i]); 2326 if (!name) 2327 return -ENOMEM; 2328 2329 led = &ctlr->leds[i]; 2330 led->name = name; 2331 led->brightness = joycon_player_led_patterns[player_led_pattern][i]; 2332 led->max_brightness = 1; 2333 led->brightness_set_blocking = 2334 joycon_player_led_brightness_set; 2335 led->flags = LED_CORE_SUSPENDRESUME | LED_HW_PLUGGABLE; 2336 2337 led_val |= joycon_player_led_patterns[player_led_pattern][i] << i; 2338 } 2339 mutex_lock(&ctlr->output_mutex); 2340 ret = joycon_set_player_leds(ctlr, 0, led_val); 2341 mutex_unlock(&ctlr->output_mutex); 2342 if (ret) { 2343 hid_warn(hdev, "Failed to set players LEDs, skipping registration; ret=%d\n", ret); 2344 goto home_led; 2345 } 2346 2347 for (i = 0; i < JC_NUM_LEDS; i++) { 2348 led = &ctlr->leds[i]; 2349 ret = devm_led_classdev_register(&hdev->dev, led); 2350 if (ret) { 2351 hid_err(hdev, "Failed to register player %d LED; ret=%d\n", i + 1, ret); 2352 return ret; 2353 } 2354 } 2355 2356 home_led: 2357 /* configure the home LED */ 2358 if (jc_type_has_right(ctlr)) { 2359 name = devm_kasprintf(dev, GFP_KERNEL, "%s:%s:%s", 2360 d_name, 2361 "blue", 2362 LED_FUNCTION_PLAYER5); 2363 if (!name) 2364 return -ENOMEM; 2365 2366 led = &ctlr->home_led; 2367 led->name = name; 2368 led->brightness = 0; 2369 led->max_brightness = 0xF; 2370 led->brightness_set_blocking = joycon_home_led_brightness_set; 2371 led->flags = LED_CORE_SUSPENDRESUME | LED_HW_PLUGGABLE; 2372 2373 /* Set the home LED to 0 as default state */ 2374 mutex_lock(&ctlr->output_mutex); 2375 ret = joycon_set_home_led(ctlr, 0); 2376 mutex_unlock(&ctlr->output_mutex); 2377 if (ret) { 2378 hid_warn(hdev, "Failed to set home LED, skipping registration; ret=%d\n", ret); 2379 return 0; 2380 } 2381 2382 ret = devm_led_classdev_register(&hdev->dev, led); 2383 if (ret) { 2384 hid_err(hdev, "Failed to register home LED; ret=%d\n", ret); 2385 return ret; 2386 } 2387 } 2388 2389 return 0; 2390 } 2391 2392 static int joycon_battery_get_property(struct power_supply *supply, 2393 enum power_supply_property prop, 2394 union power_supply_propval *val) 2395 { 2396 struct joycon_ctlr *ctlr = power_supply_get_drvdata(supply); 2397 unsigned long flags; 2398 int ret = 0; 2399 u8 capacity; 2400 bool charging; 2401 bool powered; 2402 2403 spin_lock_irqsave(&ctlr->lock, flags); 2404 capacity = ctlr->battery_capacity; 2405 charging = ctlr->battery_charging; 2406 powered = ctlr->host_powered; 2407 spin_unlock_irqrestore(&ctlr->lock, flags); 2408 2409 switch (prop) { 2410 case POWER_SUPPLY_PROP_PRESENT: 2411 val->intval = 1; 2412 break; 2413 case POWER_SUPPLY_PROP_SCOPE: 2414 val->intval = POWER_SUPPLY_SCOPE_DEVICE; 2415 break; 2416 case POWER_SUPPLY_PROP_CAPACITY_LEVEL: 2417 val->intval = capacity; 2418 break; 2419 case POWER_SUPPLY_PROP_STATUS: 2420 if (charging) 2421 val->intval = POWER_SUPPLY_STATUS_CHARGING; 2422 else if (capacity == POWER_SUPPLY_CAPACITY_LEVEL_FULL && 2423 powered) 2424 val->intval = POWER_SUPPLY_STATUS_FULL; 2425 else 2426 val->intval = POWER_SUPPLY_STATUS_DISCHARGING; 2427 break; 2428 default: 2429 ret = -EINVAL; 2430 break; 2431 } 2432 return ret; 2433 } 2434 2435 static enum power_supply_property joycon_battery_props[] = { 2436 POWER_SUPPLY_PROP_PRESENT, 2437 POWER_SUPPLY_PROP_CAPACITY_LEVEL, 2438 POWER_SUPPLY_PROP_SCOPE, 2439 POWER_SUPPLY_PROP_STATUS, 2440 }; 2441 2442 static int joycon_power_supply_create(struct joycon_ctlr *ctlr) 2443 { 2444 struct hid_device *hdev = ctlr->hdev; 2445 struct power_supply_config supply_config = { .drv_data = ctlr, }; 2446 const char * const name_fmt = "nintendo_switch_controller_battery_%s"; 2447 int ret = 0; 2448 2449 /* Set initially to unknown before receiving first input report */ 2450 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN; 2451 2452 /* Configure the battery's description */ 2453 ctlr->battery_desc.properties = joycon_battery_props; 2454 ctlr->battery_desc.num_properties = 2455 ARRAY_SIZE(joycon_battery_props); 2456 ctlr->battery_desc.get_property = joycon_battery_get_property; 2457 ctlr->battery_desc.type = POWER_SUPPLY_TYPE_BATTERY; 2458 ctlr->battery_desc.use_for_apm = 0; 2459 ctlr->battery_desc.name = devm_kasprintf(&hdev->dev, GFP_KERNEL, 2460 name_fmt, 2461 dev_name(&hdev->dev)); 2462 if (!ctlr->battery_desc.name) 2463 return -ENOMEM; 2464 2465 ctlr->battery = devm_power_supply_register(&hdev->dev, 2466 &ctlr->battery_desc, 2467 &supply_config); 2468 if (IS_ERR(ctlr->battery)) { 2469 ret = PTR_ERR(ctlr->battery); 2470 hid_err(hdev, "Failed to register battery; ret=%d\n", ret); 2471 return ret; 2472 } 2473 2474 return power_supply_powers(ctlr->battery, &hdev->dev); 2475 } 2476 2477 static int joycon_read_info(struct joycon_ctlr *ctlr) 2478 { 2479 int ret; 2480 int i; 2481 int j; 2482 struct joycon_subcmd_request req = { 0 }; 2483 struct joycon_input_report *report; 2484 2485 req.subcmd_id = JC_SUBCMD_REQ_DEV_INFO; 2486 ret = joycon_send_subcmd(ctlr, &req, 0, 2 * HZ); 2487 if (ret) { 2488 hid_err(ctlr->hdev, "Failed to get joycon info; ret=%d\n", ret); 2489 return ret; 2490 } 2491 2492 report = (struct joycon_input_report *)ctlr->input_buf; 2493 2494 for (i = 4, j = 0; j < 6; i++, j++) 2495 ctlr->mac_addr[j] = report->subcmd_reply.data[i]; 2496 2497 ctlr->mac_addr_str = devm_kasprintf(&ctlr->hdev->dev, GFP_KERNEL, "%pMU", 2498 ctlr->mac_addr); 2499 if (!ctlr->mac_addr_str) 2500 return -ENOMEM; 2501 hid_info(ctlr->hdev, "controller MAC = %s\n", ctlr->mac_addr_str); 2502 2503 /* 2504 * Retrieve the type so we can distinguish the controller type 2505 * Unfortantly the hdev->product can't always be used due to a ?bug? 2506 * with the NSO Genesis controller. Over USB, it will report the 2507 * PID as 0x201E, but over bluetooth it will report the PID as 0x2017 2508 * which is the same as the NSO SNES controller. This is different from 2509 * the rest of the controllers which will report the same PID over USB 2510 * and bluetooth. 2511 */ 2512 ctlr->ctlr_type = report->subcmd_reply.data[2]; 2513 hid_dbg(ctlr->hdev, "controller type = 0x%02X\n", ctlr->ctlr_type); 2514 2515 return 0; 2516 } 2517 2518 static int joycon_init(struct hid_device *hdev) 2519 { 2520 struct joycon_ctlr *ctlr = hid_get_drvdata(hdev); 2521 int ret = 0; 2522 2523 mutex_lock(&ctlr->output_mutex); 2524 /* if handshake command fails, assume ble pro controller */ 2525 if (joycon_using_usb(ctlr) && !joycon_send_usb(ctlr, JC_USB_CMD_HANDSHAKE, HZ)) { 2526 hid_dbg(hdev, "detected USB controller\n"); 2527 /* set baudrate for improved latency */ 2528 ret = joycon_send_usb(ctlr, JC_USB_CMD_BAUDRATE_3M, HZ); 2529 if (ret) { 2530 /* 2531 * We can function with the default baudrate. 2532 * Provide a warning, and continue on. 2533 */ 2534 hid_warn(hdev, "Failed to set baudrate (ret=%d), continuing anyway\n", ret); 2535 } 2536 /* handshake */ 2537 ret = joycon_send_usb(ctlr, JC_USB_CMD_HANDSHAKE, HZ); 2538 if (ret) { 2539 hid_err(hdev, "Failed handshake; ret=%d\n", ret); 2540 goto out_unlock; 2541 } 2542 /* 2543 * Set no timeout (to keep controller in USB mode). 2544 * This doesn't send a response, so ignore the timeout. 2545 */ 2546 joycon_send_usb(ctlr, JC_USB_CMD_NO_TIMEOUT, HZ/10); 2547 } else if (jc_type_is_chrggrip(ctlr)) { 2548 hid_err(hdev, "Failed charging grip handshake\n"); 2549 ret = -ETIMEDOUT; 2550 goto out_unlock; 2551 } 2552 2553 /* needed to retrieve the controller type */ 2554 ret = joycon_read_info(ctlr); 2555 if (ret) { 2556 hid_err(hdev, "Failed to retrieve controller info; ret=%d\n", 2557 ret); 2558 goto out_unlock; 2559 } 2560 2561 if (joycon_has_joysticks(ctlr)) { 2562 /* get controller calibration data, and parse it */ 2563 if (ctlr->ctlr_type == JOYCON_CTLR_TYPE_LIC_PRO) { 2564 /* 2565 * Licensed controllers may have incompatible SPI flash 2566 * layouts. Use default calibration values. 2567 */ 2568 hid_info(hdev, "using default cal for licensed controller\n"); 2569 joycon_use_default_calibration(hdev, 2570 &ctlr->left_stick_cal_x, 2571 &ctlr->left_stick_cal_y, 2572 "left", 0); 2573 joycon_use_default_calibration(hdev, 2574 &ctlr->right_stick_cal_x, 2575 &ctlr->right_stick_cal_y, 2576 "right", 0); 2577 } else { 2578 ret = joycon_request_calibration(ctlr); 2579 if (ret) { 2580 /* 2581 * We can function with default calibration, but 2582 * it may be inaccurate. Provide a warning, and 2583 * continue on. 2584 */ 2585 hid_warn(hdev, "Analog stick positions may be inaccurate\n"); 2586 } 2587 } 2588 } 2589 2590 if (joycon_has_imu(ctlr)) { 2591 /* get IMU calibration data, and parse it */ 2592 ret = joycon_request_imu_calibration(ctlr); 2593 if (ret) { 2594 /* 2595 * We can function with default calibration, but it may be 2596 * inaccurate. Provide a warning, and continue on. 2597 */ 2598 hid_warn(hdev, "Unable to read IMU calibration data\n"); 2599 } 2600 2601 /* Enable the IMU */ 2602 ret = joycon_enable_imu(ctlr); 2603 if (ret) { 2604 if (ctlr->ctlr_type == JOYCON_CTLR_TYPE_LIC_PRO) { 2605 hid_dbg(hdev, "IMU enable failed for licensed controller, continuing\n"); 2606 ret = 0; 2607 } else { 2608 hid_err(hdev, "Failed to enable the IMU; ret=%d\n", ret); 2609 goto out_unlock; 2610 } 2611 } 2612 } 2613 2614 /* Set the reporting mode to 0x30, which is the full report mode */ 2615 ret = joycon_set_report_mode(ctlr); 2616 if (ret) { 2617 hid_err(hdev, "Failed to set report mode; ret=%d\n", ret); 2618 goto out_unlock; 2619 } 2620 2621 if (joycon_has_rumble(ctlr)) { 2622 /* Enable rumble */ 2623 ret = joycon_enable_rumble(ctlr); 2624 if (ret) { 2625 if (ctlr->ctlr_type == JOYCON_CTLR_TYPE_LIC_PRO) { 2626 hid_dbg(hdev, "rumble enable failed for licensed controller, continuing\n"); 2627 ret = 0; 2628 } else { 2629 hid_err(hdev, "Failed to enable rumble; ret=%d\n", ret); 2630 goto out_unlock; 2631 } 2632 } 2633 } 2634 2635 out_unlock: 2636 mutex_unlock(&ctlr->output_mutex); 2637 return ret; 2638 } 2639 2640 /* Common handler for parsing inputs */ 2641 static int joycon_ctlr_read_handler(struct joycon_ctlr *ctlr, u8 *data, 2642 int size) 2643 { 2644 if (data[0] == JC_INPUT_SUBCMD_REPLY || data[0] == JC_INPUT_IMU_DATA || 2645 data[0] == JC_INPUT_MCU_DATA) { 2646 /* 2647 * The whole struct is cast and parsed below, including the 2648 * IMU/subcmd union, not just the 12-byte partial header this 2649 * used to check for. 2650 */ 2651 if (size >= sizeof(struct joycon_input_report)) 2652 joycon_parse_report(ctlr, 2653 (struct joycon_input_report *)data); 2654 } 2655 2656 return 0; 2657 } 2658 2659 static int joycon_ctlr_handle_event(struct joycon_ctlr *ctlr, u8 *data, 2660 int size) 2661 { 2662 int ret = 0; 2663 bool match = false; 2664 struct joycon_input_report *report; 2665 2666 if (unlikely(mutex_is_locked(&ctlr->output_mutex)) && 2667 ctlr->msg_type != JOYCON_MSG_TYPE_NONE) { 2668 switch (ctlr->msg_type) { 2669 case JOYCON_MSG_TYPE_USB: 2670 if (size < 2) 2671 break; 2672 if (data[0] == JC_INPUT_USB_RESPONSE && 2673 data[1] == ctlr->usb_ack_match) 2674 match = true; 2675 break; 2676 case JOYCON_MSG_TYPE_SUBCMD: 2677 if (size < sizeof(struct joycon_input_report) || 2678 data[0] != JC_INPUT_SUBCMD_REPLY) 2679 break; 2680 report = (struct joycon_input_report *)data; 2681 if (report->subcmd_reply.id == ctlr->subcmd_ack_match) 2682 match = true; 2683 break; 2684 default: 2685 break; 2686 } 2687 2688 if (match) { 2689 memcpy(ctlr->input_buf, data, 2690 min(size, (int)JC_MAX_RESP_SIZE)); 2691 ctlr->msg_type = JOYCON_MSG_TYPE_NONE; 2692 ctlr->received_resp = true; 2693 wake_up(&ctlr->wait); 2694 2695 /* This message has been handled */ 2696 return 1; 2697 } 2698 } 2699 2700 if (ctlr->ctlr_state == JOYCON_CTLR_STATE_READ) 2701 ret = joycon_ctlr_read_handler(ctlr, data, size); 2702 2703 return ret; 2704 } 2705 2706 static int nintendo_hid_event(struct hid_device *hdev, 2707 struct hid_report *report, u8 *raw_data, int size) 2708 { 2709 struct joycon_ctlr *ctlr = hid_get_drvdata(hdev); 2710 2711 if (size < 1) 2712 return -EINVAL; 2713 2714 return joycon_ctlr_handle_event(ctlr, raw_data, size); 2715 } 2716 2717 static int nintendo_hid_probe(struct hid_device *hdev, 2718 const struct hid_device_id *id) 2719 { 2720 int ret; 2721 struct joycon_ctlr *ctlr; 2722 2723 hid_dbg(hdev, "probe - start\n"); 2724 2725 ctlr = devm_kzalloc(&hdev->dev, sizeof(*ctlr), GFP_KERNEL); 2726 if (!ctlr) { 2727 ret = -ENOMEM; 2728 goto err; 2729 } 2730 2731 ctlr->hdev = hdev; 2732 ctlr->ctlr_state = JOYCON_CTLR_STATE_INIT; 2733 ctlr->rumble_queue_head = 0; 2734 ctlr->rumble_queue_tail = 0; 2735 hid_set_drvdata(hdev, ctlr); 2736 mutex_init(&ctlr->output_mutex); 2737 init_waitqueue_head(&ctlr->wait); 2738 spin_lock_init(&ctlr->lock); 2739 ctlr->rumble_queue = alloc_workqueue("hid-nintendo-rumble_wq", 2740 WQ_FREEZABLE | WQ_MEM_RECLAIM | WQ_PERCPU, 2741 0); 2742 if (!ctlr->rumble_queue) { 2743 ret = -ENOMEM; 2744 goto err; 2745 } 2746 INIT_WORK(&ctlr->rumble_worker, joycon_rumble_worker); 2747 2748 ret = hid_parse(hdev); 2749 if (ret) { 2750 hid_err(hdev, "HID parse failed\n"); 2751 goto err_wq; 2752 } 2753 2754 /* 2755 * Patch the hw version of pro controller/joycons, so applications can 2756 * distinguish between the default HID mappings and the mappings defined 2757 * by the Linux game controller spec. This is important for the SDL2 2758 * library, which has a game controller database, which uses device ids 2759 * in combination with version as a key. 2760 */ 2761 hdev->version |= 0x8000; 2762 2763 ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW); 2764 if (ret) { 2765 hid_err(hdev, "HW start failed\n"); 2766 goto err_wq; 2767 } 2768 2769 ret = hid_hw_open(hdev); 2770 if (ret) { 2771 hid_err(hdev, "cannot start hardware I/O\n"); 2772 goto err_stop; 2773 } 2774 2775 hid_device_io_start(hdev); 2776 2777 ret = joycon_init(hdev); 2778 if (ret) { 2779 hid_err(hdev, "Failed to initialize controller; ret=%d\n", ret); 2780 goto err_io_stop; 2781 } 2782 2783 /* Initialize the leds */ 2784 ret = joycon_leds_create(ctlr); 2785 if (ret) { 2786 hid_err(hdev, "Failed to create leds; ret=%d\n", ret); 2787 goto err_io_stop; 2788 } 2789 2790 /* Initialize the battery power supply */ 2791 ret = joycon_power_supply_create(ctlr); 2792 if (ret) { 2793 hid_err(hdev, "Failed to create power_supply; ret=%d\n", ret); 2794 goto err_ida; 2795 } 2796 2797 ret = joycon_input_create(ctlr); 2798 if (ret) { 2799 hid_err(hdev, "Failed to create input device; ret=%d\n", ret); 2800 goto err_ida; 2801 } 2802 2803 ctlr->ctlr_state = JOYCON_CTLR_STATE_READ; 2804 2805 hid_dbg(hdev, "probe - success\n"); 2806 return 0; 2807 2808 err_ida: 2809 ida_free(&nintendo_player_id_allocator, ctlr->player_id); 2810 err_io_stop: 2811 hid_device_io_stop(hdev); 2812 hid_hw_close(hdev); 2813 err_stop: 2814 hid_hw_stop(hdev); 2815 err_wq: 2816 destroy_workqueue(ctlr->rumble_queue); 2817 err: 2818 hid_err(hdev, "probe - fail = %d\n", ret); 2819 return ret; 2820 } 2821 2822 static void nintendo_hid_remove(struct hid_device *hdev) 2823 { 2824 struct joycon_ctlr *ctlr = hid_get_drvdata(hdev); 2825 unsigned long flags; 2826 2827 hid_dbg(hdev, "remove\n"); 2828 2829 /* Prevent further attempts at sending subcommands. */ 2830 spin_lock_irqsave(&ctlr->lock, flags); 2831 ctlr->ctlr_state = JOYCON_CTLR_STATE_REMOVED; 2832 spin_unlock_irqrestore(&ctlr->lock, flags); 2833 2834 destroy_workqueue(ctlr->rumble_queue); 2835 ida_free(&nintendo_player_id_allocator, ctlr->player_id); 2836 2837 hid_hw_close(hdev); 2838 hid_hw_stop(hdev); 2839 } 2840 2841 static int nintendo_hid_resume(struct hid_device *hdev) 2842 { 2843 struct joycon_ctlr *ctlr = hid_get_drvdata(hdev); 2844 int ret; 2845 2846 hid_dbg(hdev, "resume\n"); 2847 if (!joycon_using_usb(ctlr)) { 2848 hid_dbg(hdev, "no-op resume for bt ctlr\n"); 2849 ctlr->ctlr_state = JOYCON_CTLR_STATE_READ; 2850 return 0; 2851 } 2852 2853 ret = joycon_init(hdev); 2854 if (ret) 2855 hid_err(hdev, 2856 "Failed to restore controller after resume: %d\n", 2857 ret); 2858 else 2859 ctlr->ctlr_state = JOYCON_CTLR_STATE_READ; 2860 2861 return ret; 2862 } 2863 2864 static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) 2865 { 2866 struct joycon_ctlr *ctlr = hid_get_drvdata(hdev); 2867 2868 hid_dbg(hdev, "suspend: %d\n", message.event); 2869 /* 2870 * Avoid any blocking loops in suspend/resume transitions. 2871 * 2872 * joycon_enforce_subcmd_rate() can result in repeated retries if for 2873 * whatever reason the controller stops providing input reports. 2874 * 2875 * This has been observed with bluetooth controllers which lose 2876 * connectivity prior to suspend (but not long enough to result in 2877 * complete disconnection). 2878 */ 2879 ctlr->ctlr_state = JOYCON_CTLR_STATE_SUSPENDED; 2880 return 0; 2881 } 2882 2883 static const struct hid_device_id nintendo_hid_devices[] = { 2884 { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO, 2885 USB_DEVICE_ID_NINTENDO_PROCON) }, 2886 { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO, 2887 USB_DEVICE_ID_NINTENDO_SNESCON) }, 2888 { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO, 2889 USB_DEVICE_ID_NINTENDO_GENCON) }, 2890 { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO, 2891 USB_DEVICE_ID_NINTENDO_N64CON) }, 2892 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO, 2893 USB_DEVICE_ID_NINTENDO_PROCON) }, 2894 { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO, 2895 USB_DEVICE_ID_NINTENDO_CHRGGRIP) }, 2896 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO, 2897 USB_DEVICE_ID_NINTENDO_JOYCONL) }, 2898 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO, 2899 USB_DEVICE_ID_NINTENDO_JOYCONR) }, 2900 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO, 2901 USB_DEVICE_ID_NINTENDO_SNESCON) }, 2902 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO, 2903 USB_DEVICE_ID_NINTENDO_GENCON) }, 2904 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO, 2905 USB_DEVICE_ID_NINTENDO_N64CON) }, 2906 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_HORI, 2907 USB_DEVICE_ID_HORI_WIRELESS_SWITCH_PAD) }, 2908 { } 2909 }; 2910 MODULE_DEVICE_TABLE(hid, nintendo_hid_devices); 2911 2912 static struct hid_driver nintendo_hid_driver = { 2913 .name = "nintendo", 2914 .id_table = nintendo_hid_devices, 2915 .probe = nintendo_hid_probe, 2916 .remove = nintendo_hid_remove, 2917 .raw_event = nintendo_hid_event, 2918 .resume = pm_ptr(nintendo_hid_resume), 2919 .suspend = pm_ptr(nintendo_hid_suspend), 2920 }; 2921 static int __init nintendo_init(void) 2922 { 2923 return hid_register_driver(&nintendo_hid_driver); 2924 } 2925 2926 static void __exit nintendo_exit(void) 2927 { 2928 hid_unregister_driver(&nintendo_hid_driver); 2929 ida_destroy(&nintendo_player_id_allocator); 2930 } 2931 2932 module_init(nintendo_init); 2933 module_exit(nintendo_exit); 2934 2935 MODULE_LICENSE("GPL"); 2936 MODULE_AUTHOR("Ryan McClelland <rymcclel@gmail.com>"); 2937 MODULE_AUTHOR("Emily Strickland <linux@emily.st>"); 2938 MODULE_AUTHOR("Daniel J. Ogorchock <djogorchock@gmail.com>"); 2939 MODULE_DESCRIPTION("Driver for Nintendo Switch Controllers"); 2940