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_NESL = 0x09, 320 JOYCON_CTLR_TYPE_NESR = 0x0A, 321 JOYCON_CTLR_TYPE_SNES = 0x0B, 322 JOYCON_CTLR_TYPE_GEN = 0x0D, 323 JOYCON_CTLR_TYPE_N64 = 0x0C, 324 }; 325 326 struct joycon_stick_cal { 327 s32 max; 328 s32 min; 329 s32 center; 330 }; 331 332 struct joycon_imu_cal { 333 s16 offset[3]; 334 s16 scale[3]; 335 }; 336 337 /* 338 * All the controller's button values are stored in a u32. 339 * They can be accessed with bitwise ANDs. 340 */ 341 #define JC_BTN_Y BIT(0) 342 #define JC_BTN_X BIT(1) 343 #define JC_BTN_B BIT(2) 344 #define JC_BTN_A BIT(3) 345 #define JC_BTN_SR_R BIT(4) 346 #define JC_BTN_SL_R BIT(5) 347 #define JC_BTN_R BIT(6) 348 #define JC_BTN_ZR BIT(7) 349 #define JC_BTN_MINUS BIT(8) 350 #define JC_BTN_PLUS BIT(9) 351 #define JC_BTN_RSTICK BIT(10) 352 #define JC_BTN_LSTICK BIT(11) 353 #define JC_BTN_HOME BIT(12) 354 #define JC_BTN_CAP BIT(13) /* capture button */ 355 #define JC_BTN_DOWN BIT(16) 356 #define JC_BTN_UP BIT(17) 357 #define JC_BTN_RIGHT BIT(18) 358 #define JC_BTN_LEFT BIT(19) 359 #define JC_BTN_SR_L BIT(20) 360 #define JC_BTN_SL_L BIT(21) 361 #define JC_BTN_L BIT(22) 362 #define JC_BTN_ZL BIT(23) 363 364 struct joycon_ctlr_button_mapping { 365 u32 code; 366 u32 bit; 367 }; 368 369 /* 370 * D-pad is configured as buttons for the left Joy-Con only! 371 */ 372 static const struct joycon_ctlr_button_mapping left_joycon_button_mappings[] = { 373 { BTN_TL, JC_BTN_L, }, 374 { BTN_TL2, JC_BTN_ZL, }, 375 { BTN_SELECT, JC_BTN_MINUS, }, 376 { BTN_THUMBL, JC_BTN_LSTICK, }, 377 { BTN_DPAD_UP, JC_BTN_UP, }, 378 { BTN_DPAD_DOWN, JC_BTN_DOWN, }, 379 { BTN_DPAD_LEFT, JC_BTN_LEFT, }, 380 { BTN_DPAD_RIGHT, JC_BTN_RIGHT, }, 381 { BTN_Z, JC_BTN_CAP, }, 382 { /* sentinel */ }, 383 }; 384 385 /* 386 * The unused *right*-side triggers become the SL/SR triggers for the *left* 387 * Joy-Con, if and only if we're not using a charging grip. 388 */ 389 static const struct joycon_ctlr_button_mapping left_joycon_s_button_mappings[] = { 390 { BTN_TR, JC_BTN_SL_L, }, 391 { BTN_TR2, JC_BTN_SR_L, }, 392 { /* sentinel */ }, 393 }; 394 395 static const struct joycon_ctlr_button_mapping right_joycon_button_mappings[] = { 396 { BTN_EAST, JC_BTN_A, }, 397 { BTN_SOUTH, JC_BTN_B, }, 398 { BTN_NORTH, JC_BTN_X, }, 399 { BTN_WEST, JC_BTN_Y, }, 400 { BTN_TR, JC_BTN_R, }, 401 { BTN_TR2, JC_BTN_ZR, }, 402 { BTN_START, JC_BTN_PLUS, }, 403 { BTN_THUMBR, JC_BTN_RSTICK, }, 404 { BTN_MODE, JC_BTN_HOME, }, 405 { /* sentinel */ }, 406 }; 407 408 /* 409 * The unused *left*-side triggers become the SL/SR triggers for the *right* 410 * Joy-Con, if and only if we're not using a charging grip. 411 */ 412 static const struct joycon_ctlr_button_mapping right_joycon_s_button_mappings[] = { 413 { BTN_TL, JC_BTN_SL_R, }, 414 { BTN_TL2, JC_BTN_SR_R, }, 415 { /* sentinel */ }, 416 }; 417 418 static const struct joycon_ctlr_button_mapping procon_button_mappings[] = { 419 { BTN_EAST, JC_BTN_A, }, 420 { BTN_SOUTH, JC_BTN_B, }, 421 { BTN_NORTH, JC_BTN_X, }, 422 { BTN_WEST, JC_BTN_Y, }, 423 { BTN_TL, JC_BTN_L, }, 424 { BTN_TR, JC_BTN_R, }, 425 { BTN_TL2, JC_BTN_ZL, }, 426 { BTN_TR2, JC_BTN_ZR, }, 427 { BTN_SELECT, JC_BTN_MINUS, }, 428 { BTN_START, JC_BTN_PLUS, }, 429 { BTN_THUMBL, JC_BTN_LSTICK, }, 430 { BTN_THUMBR, JC_BTN_RSTICK, }, 431 { BTN_MODE, JC_BTN_HOME, }, 432 { BTN_Z, JC_BTN_CAP, }, 433 { /* sentinel */ }, 434 }; 435 436 static const struct joycon_ctlr_button_mapping nescon_button_mappings[] = { 437 { BTN_SOUTH, JC_BTN_A, }, 438 { BTN_EAST, JC_BTN_B, }, 439 { BTN_TL, JC_BTN_L, }, 440 { BTN_TR, JC_BTN_R, }, 441 { BTN_SELECT, JC_BTN_MINUS, }, 442 { BTN_START, JC_BTN_PLUS, }, 443 { /* sentinel */ }, 444 }; 445 446 static const struct joycon_ctlr_button_mapping snescon_button_mappings[] = { 447 { BTN_EAST, JC_BTN_A, }, 448 { BTN_SOUTH, JC_BTN_B, }, 449 { BTN_NORTH, JC_BTN_X, }, 450 { BTN_WEST, JC_BTN_Y, }, 451 { BTN_TL, JC_BTN_L, }, 452 { BTN_TR, JC_BTN_R, }, 453 { BTN_TL2, JC_BTN_ZL, }, 454 { BTN_TR2, JC_BTN_ZR, }, 455 { BTN_SELECT, JC_BTN_MINUS, }, 456 { BTN_START, JC_BTN_PLUS, }, 457 { /* sentinel */ }, 458 }; 459 460 static const struct joycon_ctlr_button_mapping gencon_button_mappings[] = { 461 { BTN_WEST, JC_BTN_A, }, /* A */ 462 { BTN_SOUTH, JC_BTN_B, }, /* B */ 463 { BTN_EAST, JC_BTN_R, }, /* C */ 464 { BTN_TL, JC_BTN_X, }, /* X MD/GEN 6B Only */ 465 { BTN_NORTH, JC_BTN_Y, }, /* Y MD/GEN 6B Only */ 466 { BTN_TR, JC_BTN_L, }, /* Z MD/GEN 6B Only */ 467 { BTN_SELECT, JC_BTN_ZR, }, /* Mode */ 468 { BTN_START, JC_BTN_PLUS, }, 469 { BTN_MODE, JC_BTN_HOME, }, 470 { BTN_Z, JC_BTN_CAP, }, 471 { /* sentinel */ }, 472 }; 473 474 static const struct joycon_ctlr_button_mapping n64con_button_mappings[] = { 475 { BTN_A, JC_BTN_A, }, 476 { BTN_B, JC_BTN_B, }, 477 { BTN_TL2, JC_BTN_ZL, }, /* Z */ 478 { BTN_TL, JC_BTN_L, }, 479 { BTN_TR, JC_BTN_R, }, 480 { BTN_TR2, JC_BTN_LSTICK, }, /* ZR */ 481 { BTN_START, JC_BTN_PLUS, }, 482 { BTN_SELECT, JC_BTN_Y, }, /* C UP */ 483 { BTN_X, JC_BTN_ZR, }, /* C DOWN */ 484 { BTN_Y, JC_BTN_X, }, /* C LEFT */ 485 { BTN_C, JC_BTN_MINUS, }, /* C RIGHT */ 486 { BTN_MODE, JC_BTN_HOME, }, 487 { BTN_Z, JC_BTN_CAP, }, 488 { /* sentinel */ }, 489 }; 490 491 enum joycon_msg_type { 492 JOYCON_MSG_TYPE_NONE, 493 JOYCON_MSG_TYPE_USB, 494 JOYCON_MSG_TYPE_SUBCMD, 495 }; 496 497 struct joycon_rumble_output { 498 u8 output_id; 499 u8 packet_num; 500 u8 rumble_data[8]; 501 } __packed; 502 503 struct joycon_subcmd_request { 504 u8 output_id; /* must be 0x01 for subcommand, 0x10 for rumble only */ 505 u8 packet_num; /* incremented every send */ 506 u8 rumble_data[8]; 507 u8 subcmd_id; 508 u8 data[]; /* length depends on the subcommand */ 509 } __packed; 510 511 struct joycon_subcmd_reply { 512 u8 ack; /* MSB 1 for ACK, 0 for NACK */ 513 u8 id; /* id of requested subcmd */ 514 u8 data[]; /* will be at most 35 bytes */ 515 } __packed; 516 517 struct joycon_imu_data { 518 s16 accel_x; 519 s16 accel_y; 520 s16 accel_z; 521 s16 gyro_x; 522 s16 gyro_y; 523 s16 gyro_z; 524 } __packed; 525 526 struct joycon_input_report { 527 u8 id; 528 u8 timer; 529 u8 bat_con; /* battery and connection info */ 530 u8 button_status[3]; 531 u8 left_stick[3]; 532 u8 right_stick[3]; 533 u8 vibrator_report; 534 535 union { 536 struct joycon_subcmd_reply subcmd_reply; 537 /* IMU input reports contain 3 samples */ 538 u8 imu_raw_bytes[sizeof(struct joycon_imu_data) * 3]; 539 }; 540 } __packed; 541 542 #define JC_MAX_RESP_SIZE (sizeof(struct joycon_input_report) + 35) 543 #define JC_RUMBLE_DATA_SIZE 8 544 #define JC_RUMBLE_QUEUE_SIZE 8 545 546 static const char * const joycon_player_led_names[] = { 547 LED_FUNCTION_PLAYER1, 548 LED_FUNCTION_PLAYER2, 549 LED_FUNCTION_PLAYER3, 550 LED_FUNCTION_PLAYER4, 551 }; 552 #define JC_NUM_LEDS ARRAY_SIZE(joycon_player_led_names) 553 #define JC_NUM_LED_PATTERNS 8 554 /* Taken from https://www.nintendo.com/my/support/qa/detail/33822 */ 555 static const enum led_brightness joycon_player_led_patterns[JC_NUM_LED_PATTERNS][JC_NUM_LEDS] = { 556 { 1, 0, 0, 0 }, 557 { 1, 1, 0, 0 }, 558 { 1, 1, 1, 0 }, 559 { 1, 1, 1, 1 }, 560 { 1, 0, 0, 1 }, 561 { 1, 0, 1, 0 }, 562 { 1, 0, 1, 1 }, 563 { 0, 1, 1, 0 }, 564 }; 565 566 /* Each physical controller is associated with a joycon_ctlr struct */ 567 struct joycon_ctlr { 568 struct hid_device *hdev; 569 struct input_dev *input; 570 u32 player_id; 571 struct led_classdev leds[JC_NUM_LEDS]; /* player leds */ 572 struct led_classdev home_led; 573 enum joycon_ctlr_state ctlr_state; 574 spinlock_t lock; 575 u8 mac_addr[6]; 576 char *mac_addr_str; 577 enum joycon_ctlr_type ctlr_type; 578 579 /* The following members are used for synchronous sends/receives */ 580 enum joycon_msg_type msg_type; 581 u8 subcmd_num; 582 struct mutex output_mutex; 583 u8 input_buf[JC_MAX_RESP_SIZE]; 584 wait_queue_head_t wait; 585 bool received_resp; 586 u8 usb_ack_match; 587 u8 subcmd_ack_match; 588 bool received_input_report; 589 unsigned int last_input_report_msecs; 590 unsigned int last_subcmd_sent_msecs; 591 unsigned int consecutive_valid_report_deltas; 592 593 /* factory calibration data */ 594 struct joycon_stick_cal left_stick_cal_x; 595 struct joycon_stick_cal left_stick_cal_y; 596 struct joycon_stick_cal right_stick_cal_x; 597 struct joycon_stick_cal right_stick_cal_y; 598 599 struct joycon_imu_cal accel_cal; 600 struct joycon_imu_cal gyro_cal; 601 602 /* prevents needlessly recalculating these divisors every sample */ 603 s32 imu_cal_accel_divisor[3]; 604 s32 imu_cal_gyro_divisor[3]; 605 606 /* power supply data */ 607 struct power_supply *battery; 608 struct power_supply_desc battery_desc; 609 u8 battery_capacity; 610 bool battery_charging; 611 bool host_powered; 612 613 /* rumble */ 614 u8 rumble_data[JC_RUMBLE_QUEUE_SIZE][JC_RUMBLE_DATA_SIZE]; 615 int rumble_queue_head; 616 int rumble_queue_tail; 617 struct workqueue_struct *rumble_queue; 618 struct work_struct rumble_worker; 619 unsigned int rumble_msecs; 620 u16 rumble_ll_freq; 621 u16 rumble_lh_freq; 622 u16 rumble_rl_freq; 623 u16 rumble_rh_freq; 624 unsigned short rumble_zero_countdown; 625 626 /* imu */ 627 struct input_dev *imu_input; 628 bool imu_first_packet_received; /* helps in initiating timestamp */ 629 unsigned int imu_timestamp_us; /* timestamp we report to userspace */ 630 unsigned int imu_last_pkt_ms; /* used to calc imu report delta */ 631 /* the following are used to track the average imu report time delta */ 632 unsigned int imu_delta_samples_count; 633 unsigned int imu_delta_samples_sum; 634 unsigned int imu_avg_delta_ms; 635 }; 636 637 /* Helper macros for checking controller type */ 638 #define jc_type_is_joycon(ctlr) \ 639 (ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONL || \ 640 ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONR || \ 641 ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_CHRGGRIP) 642 #define jc_type_is_procon(ctlr) \ 643 (ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_PROCON) 644 #define jc_type_is_chrggrip(ctlr) \ 645 (ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_CHRGGRIP) 646 647 /* Does this controller have inputs associated with left joycon? */ 648 #define jc_type_has_left(ctlr) \ 649 (ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCL || \ 650 ctlr->ctlr_type == JOYCON_CTLR_TYPE_PRO || \ 651 ctlr->ctlr_type == JOYCON_CTLR_TYPE_N64) 652 653 /* Does this controller have inputs associated with right joycon? */ 654 #define jc_type_has_right(ctlr) \ 655 (ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCR || \ 656 ctlr->ctlr_type == JOYCON_CTLR_TYPE_PRO) 657 658 /* 659 * Controller device helpers 660 * 661 * These look at the device ID known to the HID subsystem to identify a device, 662 * but take caution: some NSO devices lie about themselves (NES Joy-Cons and 663 * Sega Genesis controller). See type helpers below. 664 * 665 * These helpers are most useful early during the HID probe or in conjunction 666 * with the capability helpers below. 667 */ 668 static inline bool joycon_device_is_chrggrip(struct joycon_ctlr *ctlr) 669 { 670 return ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_CHRGGRIP; 671 } 672 673 /* 674 * Controller type helpers 675 * 676 * These are slightly different than the device-ID-based helpers above. They are 677 * generally more reliable, since they can distinguish between, e.g., Genesis 678 * versus SNES, or NES Joy-Cons versus regular Switch Joy-Cons. They're most 679 * useful for reporting available inputs. For other kinds of distinctions, see 680 * the capability helpers below. 681 * 682 * They have two major drawbacks: (1) they're not available until after we set 683 * the reporting method and then request the device info; (2) they can't 684 * distinguish all controllers (like the Charging Grip from the Pro controller.) 685 */ 686 static inline bool joycon_type_is_left_joycon(struct joycon_ctlr *ctlr) 687 { 688 return ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCL; 689 } 690 691 static inline bool joycon_type_is_right_joycon(struct joycon_ctlr *ctlr) 692 { 693 return ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCR; 694 } 695 696 static inline bool joycon_type_is_procon(struct joycon_ctlr *ctlr) 697 { 698 return ctlr->ctlr_type == JOYCON_CTLR_TYPE_PRO; 699 } 700 701 static inline bool joycon_type_is_snescon(struct joycon_ctlr *ctlr) 702 { 703 return ctlr->ctlr_type == JOYCON_CTLR_TYPE_SNES; 704 } 705 706 static inline bool joycon_type_is_gencon(struct joycon_ctlr *ctlr) 707 { 708 return ctlr->ctlr_type == JOYCON_CTLR_TYPE_GEN; 709 } 710 711 static inline bool joycon_type_is_n64con(struct joycon_ctlr *ctlr) 712 { 713 return ctlr->ctlr_type == JOYCON_CTLR_TYPE_N64; 714 } 715 716 static inline bool joycon_type_is_left_nescon(struct joycon_ctlr *ctlr) 717 { 718 return ctlr->ctlr_type == JOYCON_CTLR_TYPE_NESL; 719 } 720 721 static inline bool joycon_type_is_right_nescon(struct joycon_ctlr *ctlr) 722 { 723 return ctlr->ctlr_type == JOYCON_CTLR_TYPE_NESR; 724 } 725 726 static inline bool joycon_type_is_any_joycon(struct joycon_ctlr *ctlr) 727 { 728 return joycon_type_is_left_joycon(ctlr) || 729 joycon_type_is_right_joycon(ctlr) || 730 joycon_device_is_chrggrip(ctlr); 731 } 732 733 static inline bool joycon_type_is_any_nescon(struct joycon_ctlr *ctlr) 734 { 735 return joycon_type_is_left_nescon(ctlr) || 736 joycon_type_is_right_nescon(ctlr); 737 } 738 739 /* 740 * Controller capability helpers 741 * 742 * These helpers combine the use of the helpers above to detect certain 743 * capabilities during initialization. They are always accurate but (since they 744 * use type helpers) cannot be used early in the HID probe. 745 */ 746 static inline bool joycon_has_imu(struct joycon_ctlr *ctlr) 747 { 748 return joycon_device_is_chrggrip(ctlr) || 749 joycon_type_is_any_joycon(ctlr) || 750 joycon_type_is_procon(ctlr); 751 } 752 753 static inline bool joycon_has_joysticks(struct joycon_ctlr *ctlr) 754 { 755 return joycon_device_is_chrggrip(ctlr) || 756 joycon_type_is_any_joycon(ctlr) || 757 joycon_type_is_procon(ctlr) || 758 joycon_type_is_n64con(ctlr); 759 } 760 761 static inline bool joycon_has_rumble(struct joycon_ctlr *ctlr) 762 { 763 return joycon_device_is_chrggrip(ctlr) || 764 joycon_type_is_any_joycon(ctlr) || 765 joycon_type_is_procon(ctlr) || 766 joycon_type_is_n64con(ctlr); 767 } 768 769 static inline bool joycon_using_usb(struct joycon_ctlr *ctlr) 770 { 771 return ctlr->hdev->bus == BUS_USB; 772 } 773 774 static int __joycon_hid_send(struct hid_device *hdev, u8 *data, size_t len) 775 { 776 u8 *buf; 777 int ret; 778 779 buf = kmemdup(data, len, GFP_KERNEL); 780 if (!buf) 781 return -ENOMEM; 782 ret = hid_hw_output_report(hdev, buf, len); 783 kfree(buf); 784 if (ret < 0) 785 hid_dbg(hdev, "Failed to send output report ret=%d\n", ret); 786 return ret; 787 } 788 789 static void joycon_wait_for_input_report(struct joycon_ctlr *ctlr) 790 { 791 int ret; 792 793 /* 794 * If we are in the proper reporting mode, wait for an input 795 * report prior to sending the subcommand. This improves 796 * reliability considerably. 797 */ 798 if (ctlr->ctlr_state == JOYCON_CTLR_STATE_READ) { 799 unsigned long flags; 800 801 spin_lock_irqsave(&ctlr->lock, flags); 802 ctlr->received_input_report = false; 803 spin_unlock_irqrestore(&ctlr->lock, flags); 804 ret = wait_event_timeout(ctlr->wait, 805 ctlr->received_input_report, 806 HZ / 4); 807 /* We will still proceed, even with a timeout here */ 808 if (!ret) 809 hid_warn(ctlr->hdev, 810 "timeout waiting for input report\n"); 811 } 812 } 813 814 /* 815 * Sending subcommands and/or rumble data at too high a rate can cause bluetooth 816 * controller disconnections. 817 */ 818 #define JC_INPUT_REPORT_MIN_DELTA 8 819 #define JC_INPUT_REPORT_MAX_DELTA 17 820 #define JC_SUBCMD_TX_OFFSET_MS 4 821 #define JC_SUBCMD_VALID_DELTA_REQ 3 822 #define JC_SUBCMD_RATE_MAX_ATTEMPTS 500 823 #define JC_SUBCMD_RATE_LIMITER_USB_MS 20 824 #define JC_SUBCMD_RATE_LIMITER_BT_MS 60 825 #define JC_SUBCMD_RATE_LIMITER_MS(ctlr) ((ctlr)->hdev->bus == BUS_USB ? JC_SUBCMD_RATE_LIMITER_USB_MS : JC_SUBCMD_RATE_LIMITER_BT_MS) 826 static void joycon_enforce_subcmd_rate(struct joycon_ctlr *ctlr) 827 { 828 unsigned int current_ms; 829 unsigned long subcmd_delta; 830 int consecutive_valid_deltas = 0; 831 int attempts = 0; 832 unsigned long flags; 833 834 if (unlikely(ctlr->ctlr_state != JOYCON_CTLR_STATE_READ)) 835 return; 836 837 do { 838 joycon_wait_for_input_report(ctlr); 839 current_ms = jiffies_to_msecs(jiffies); 840 subcmd_delta = current_ms - ctlr->last_subcmd_sent_msecs; 841 842 spin_lock_irqsave(&ctlr->lock, flags); 843 consecutive_valid_deltas = ctlr->consecutive_valid_report_deltas; 844 spin_unlock_irqrestore(&ctlr->lock, flags); 845 846 attempts++; 847 } while ((consecutive_valid_deltas < JC_SUBCMD_VALID_DELTA_REQ || 848 subcmd_delta < JC_SUBCMD_RATE_LIMITER_MS(ctlr)) && 849 ctlr->ctlr_state == JOYCON_CTLR_STATE_READ && 850 attempts < JC_SUBCMD_RATE_MAX_ATTEMPTS); 851 852 if (attempts >= JC_SUBCMD_RATE_MAX_ATTEMPTS) { 853 hid_warn(ctlr->hdev, "%s: exceeded max attempts", __func__); 854 return; 855 } 856 857 ctlr->last_subcmd_sent_msecs = current_ms; 858 859 /* 860 * Wait a short time after receiving an input report before 861 * transmitting. This should reduce odds of a TX coinciding with an RX. 862 * Minimizing concurrent BT traffic with the controller seems to lower 863 * the rate of disconnections. 864 */ 865 msleep(JC_SUBCMD_TX_OFFSET_MS); 866 } 867 868 static int joycon_hid_send_sync(struct joycon_ctlr *ctlr, u8 *data, size_t len, 869 u32 timeout) 870 { 871 int ret; 872 int tries = 2; 873 874 /* 875 * The controller occasionally seems to drop subcommands. In testing, 876 * doing one retry after a timeout appears to always work. 877 */ 878 while (tries--) { 879 joycon_enforce_subcmd_rate(ctlr); 880 881 ret = __joycon_hid_send(ctlr->hdev, data, len); 882 if (ret < 0) { 883 memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE); 884 return ret; 885 } 886 887 ret = wait_event_timeout(ctlr->wait, ctlr->received_resp, 888 timeout); 889 if (!ret) { 890 hid_dbg(ctlr->hdev, 891 "synchronous send/receive timed out\n"); 892 if (tries) { 893 hid_dbg(ctlr->hdev, 894 "retrying sync send after timeout\n"); 895 } 896 memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE); 897 ret = -ETIMEDOUT; 898 } else { 899 ret = 0; 900 break; 901 } 902 } 903 904 ctlr->received_resp = false; 905 return ret; 906 } 907 908 static int joycon_send_usb(struct joycon_ctlr *ctlr, u8 cmd, u32 timeout) 909 { 910 int ret; 911 u8 buf[2] = {JC_OUTPUT_USB_CMD}; 912 913 buf[1] = cmd; 914 ctlr->usb_ack_match = cmd; 915 ctlr->msg_type = JOYCON_MSG_TYPE_USB; 916 ret = joycon_hid_send_sync(ctlr, buf, sizeof(buf), timeout); 917 if (ret) 918 hid_dbg(ctlr->hdev, "send usb command failed; ret=%d\n", ret); 919 return ret; 920 } 921 922 static int joycon_send_subcmd(struct joycon_ctlr *ctlr, 923 struct joycon_subcmd_request *subcmd, 924 size_t data_len, u32 timeout) 925 { 926 int ret; 927 unsigned long flags; 928 929 spin_lock_irqsave(&ctlr->lock, flags); 930 /* 931 * If the controller has been removed, just return ENODEV so the LED 932 * subsystem doesn't print invalid errors on removal. 933 */ 934 if (ctlr->ctlr_state == JOYCON_CTLR_STATE_REMOVED) { 935 spin_unlock_irqrestore(&ctlr->lock, flags); 936 return -ENODEV; 937 } 938 memcpy(subcmd->rumble_data, ctlr->rumble_data[ctlr->rumble_queue_tail], 939 JC_RUMBLE_DATA_SIZE); 940 spin_unlock_irqrestore(&ctlr->lock, flags); 941 942 subcmd->output_id = JC_OUTPUT_RUMBLE_AND_SUBCMD; 943 subcmd->packet_num = ctlr->subcmd_num; 944 if (++ctlr->subcmd_num > 0xF) 945 ctlr->subcmd_num = 0; 946 ctlr->subcmd_ack_match = subcmd->subcmd_id; 947 ctlr->msg_type = JOYCON_MSG_TYPE_SUBCMD; 948 949 ret = joycon_hid_send_sync(ctlr, (u8 *)subcmd, 950 sizeof(*subcmd) + data_len, timeout); 951 if (ret < 0) 952 hid_dbg(ctlr->hdev, "send subcommand failed; ret=%d\n", ret); 953 else 954 ret = 0; 955 return ret; 956 } 957 958 /* Supply nibbles for flash and on. Ones correspond to active */ 959 static int joycon_set_player_leds(struct joycon_ctlr *ctlr, u8 flash, u8 on) 960 { 961 struct joycon_subcmd_request *req; 962 u8 buffer[sizeof(*req) + 1] = { 0 }; 963 964 req = (struct joycon_subcmd_request *)buffer; 965 req->subcmd_id = JC_SUBCMD_SET_PLAYER_LIGHTS; 966 req->data[0] = (flash << 4) | on; 967 968 hid_dbg(ctlr->hdev, "setting player leds\n"); 969 return joycon_send_subcmd(ctlr, req, 1, HZ/4); 970 } 971 972 static int joycon_set_home_led(struct joycon_ctlr *ctlr, enum led_brightness brightness) 973 { 974 struct joycon_subcmd_request *req; 975 u8 buffer[sizeof(*req) + 5] = { 0 }; 976 u8 *data; 977 978 req = (struct joycon_subcmd_request *)buffer; 979 req->subcmd_id = JC_SUBCMD_SET_HOME_LIGHT; 980 data = req->data; 981 data[0] = 0x01; 982 data[1] = brightness << 4; 983 data[2] = brightness | (brightness << 4); 984 data[3] = 0x11; 985 data[4] = 0x11; 986 987 hid_dbg(ctlr->hdev, "setting home led brightness\n"); 988 return joycon_send_subcmd(ctlr, req, 5, HZ/4); 989 } 990 991 static int joycon_request_spi_flash_read(struct joycon_ctlr *ctlr, 992 u32 start_addr, u8 size, u8 **reply) 993 { 994 struct joycon_subcmd_request *req; 995 struct joycon_input_report *report; 996 u8 buffer[sizeof(*req) + 5] = { 0 }; 997 u8 *data; 998 int ret; 999 1000 if (!reply) 1001 return -EINVAL; 1002 1003 req = (struct joycon_subcmd_request *)buffer; 1004 req->subcmd_id = JC_SUBCMD_SPI_FLASH_READ; 1005 data = req->data; 1006 put_unaligned_le32(start_addr, data); 1007 data[4] = size; 1008 1009 hid_dbg(ctlr->hdev, "requesting SPI flash data\n"); 1010 ret = joycon_send_subcmd(ctlr, req, 5, HZ); 1011 if (ret) { 1012 hid_err(ctlr->hdev, "failed reading SPI flash; ret=%d\n", ret); 1013 } else { 1014 report = (struct joycon_input_report *)ctlr->input_buf; 1015 /* The read data starts at the 6th byte */ 1016 *reply = &report->subcmd_reply.data[5]; 1017 } 1018 return ret; 1019 } 1020 1021 /* 1022 * User calibration's presence is denoted with a magic byte preceding it. 1023 * returns 0 if magic val is present, 1 if not present, < 0 on error 1024 */ 1025 static int joycon_check_for_cal_magic(struct joycon_ctlr *ctlr, u32 flash_addr) 1026 { 1027 int ret; 1028 u8 *reply; 1029 1030 ret = joycon_request_spi_flash_read(ctlr, flash_addr, 1031 JC_CAL_USR_MAGIC_SIZE, &reply); 1032 if (ret) 1033 return ret; 1034 1035 return reply[0] != JC_CAL_USR_MAGIC_0 || reply[1] != JC_CAL_USR_MAGIC_1; 1036 } 1037 1038 static int joycon_read_stick_calibration(struct joycon_ctlr *ctlr, u16 cal_addr, 1039 struct joycon_stick_cal *cal_x, 1040 struct joycon_stick_cal *cal_y, 1041 bool left_stick) 1042 { 1043 s32 x_max_above; 1044 s32 x_min_below; 1045 s32 y_max_above; 1046 s32 y_min_below; 1047 u8 *raw_cal; 1048 int ret; 1049 1050 ret = joycon_request_spi_flash_read(ctlr, cal_addr, 1051 JC_CAL_STICK_DATA_SIZE, &raw_cal); 1052 if (ret) 1053 return ret; 1054 1055 /* stick calibration parsing: note the order differs based on stick */ 1056 if (left_stick) { 1057 x_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 0), 0, 1058 12); 1059 y_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 1), 4, 1060 12); 1061 cal_x->center = hid_field_extract(ctlr->hdev, (raw_cal + 3), 0, 1062 12); 1063 cal_y->center = hid_field_extract(ctlr->hdev, (raw_cal + 4), 4, 1064 12); 1065 x_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 6), 0, 1066 12); 1067 y_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 7), 4, 1068 12); 1069 } else { 1070 cal_x->center = hid_field_extract(ctlr->hdev, (raw_cal + 0), 0, 1071 12); 1072 cal_y->center = hid_field_extract(ctlr->hdev, (raw_cal + 1), 4, 1073 12); 1074 x_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 3), 0, 1075 12); 1076 y_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 4), 4, 1077 12); 1078 x_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 6), 0, 1079 12); 1080 y_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 7), 4, 1081 12); 1082 } 1083 1084 cal_x->max = cal_x->center + x_max_above; 1085 cal_x->min = cal_x->center - x_min_below; 1086 cal_y->max = cal_y->center + y_max_above; 1087 cal_y->min = cal_y->center - y_min_below; 1088 1089 /* check if calibration values are plausible */ 1090 if (cal_x->min >= cal_x->center || cal_x->center >= cal_x->max || 1091 cal_y->min >= cal_y->center || cal_y->center >= cal_y->max) 1092 ret = -EINVAL; 1093 1094 return ret; 1095 } 1096 1097 static const u16 DFLT_STICK_CAL_CEN = 2000; 1098 static const u16 DFLT_STICK_CAL_MAX = 3500; 1099 static const u16 DFLT_STICK_CAL_MIN = 500; 1100 static void joycon_use_default_calibration(struct hid_device *hdev, 1101 struct joycon_stick_cal *cal_x, 1102 struct joycon_stick_cal *cal_y, 1103 const char *stick, int ret) 1104 { 1105 hid_warn(hdev, 1106 "Failed to read %s stick cal, using defaults; e=%d\n", 1107 stick, ret); 1108 1109 cal_x->center = cal_y->center = DFLT_STICK_CAL_CEN; 1110 cal_x->max = cal_y->max = DFLT_STICK_CAL_MAX; 1111 cal_x->min = cal_y->min = DFLT_STICK_CAL_MIN; 1112 } 1113 1114 static int joycon_request_calibration(struct joycon_ctlr *ctlr) 1115 { 1116 u16 left_stick_addr = JC_CAL_FCT_DATA_LEFT_ADDR; 1117 u16 right_stick_addr = JC_CAL_FCT_DATA_RIGHT_ADDR; 1118 int ret; 1119 1120 hid_dbg(ctlr->hdev, "requesting cal data\n"); 1121 1122 /* check if user stick calibrations are present */ 1123 if (!joycon_check_for_cal_magic(ctlr, JC_CAL_USR_LEFT_MAGIC_ADDR)) { 1124 left_stick_addr = JC_CAL_USR_LEFT_DATA_ADDR; 1125 hid_info(ctlr->hdev, "using user cal for left stick\n"); 1126 } else { 1127 hid_info(ctlr->hdev, "using factory cal for left stick\n"); 1128 } 1129 if (!joycon_check_for_cal_magic(ctlr, JC_CAL_USR_RIGHT_MAGIC_ADDR)) { 1130 right_stick_addr = JC_CAL_USR_RIGHT_DATA_ADDR; 1131 hid_info(ctlr->hdev, "using user cal for right stick\n"); 1132 } else { 1133 hid_info(ctlr->hdev, "using factory cal for right stick\n"); 1134 } 1135 1136 /* read the left stick calibration data */ 1137 ret = joycon_read_stick_calibration(ctlr, left_stick_addr, 1138 &ctlr->left_stick_cal_x, 1139 &ctlr->left_stick_cal_y, 1140 true); 1141 1142 if (ret) 1143 joycon_use_default_calibration(ctlr->hdev, 1144 &ctlr->left_stick_cal_x, 1145 &ctlr->left_stick_cal_y, 1146 "left", ret); 1147 1148 /* read the right stick calibration data */ 1149 ret = joycon_read_stick_calibration(ctlr, right_stick_addr, 1150 &ctlr->right_stick_cal_x, 1151 &ctlr->right_stick_cal_y, 1152 false); 1153 1154 if (ret) 1155 joycon_use_default_calibration(ctlr->hdev, 1156 &ctlr->right_stick_cal_x, 1157 &ctlr->right_stick_cal_y, 1158 "right", ret); 1159 1160 hid_dbg(ctlr->hdev, "calibration:\n" 1161 "l_x_c=%d l_x_max=%d l_x_min=%d\n" 1162 "l_y_c=%d l_y_max=%d l_y_min=%d\n" 1163 "r_x_c=%d r_x_max=%d r_x_min=%d\n" 1164 "r_y_c=%d r_y_max=%d r_y_min=%d\n", 1165 ctlr->left_stick_cal_x.center, 1166 ctlr->left_stick_cal_x.max, 1167 ctlr->left_stick_cal_x.min, 1168 ctlr->left_stick_cal_y.center, 1169 ctlr->left_stick_cal_y.max, 1170 ctlr->left_stick_cal_y.min, 1171 ctlr->right_stick_cal_x.center, 1172 ctlr->right_stick_cal_x.max, 1173 ctlr->right_stick_cal_x.min, 1174 ctlr->right_stick_cal_y.center, 1175 ctlr->right_stick_cal_y.max, 1176 ctlr->right_stick_cal_y.min); 1177 1178 return 0; 1179 } 1180 1181 /* 1182 * These divisors are calculated once rather than for each sample. They are only 1183 * dependent on the IMU calibration values. They are used when processing the 1184 * IMU input reports. 1185 */ 1186 static void joycon_calc_imu_cal_divisors(struct joycon_ctlr *ctlr) 1187 { 1188 int i, divz = 0; 1189 1190 for (i = 0; i < 3; i++) { 1191 ctlr->imu_cal_accel_divisor[i] = ctlr->accel_cal.scale[i] - 1192 ctlr->accel_cal.offset[i]; 1193 ctlr->imu_cal_gyro_divisor[i] = ctlr->gyro_cal.scale[i] - 1194 ctlr->gyro_cal.offset[i]; 1195 1196 if (ctlr->imu_cal_accel_divisor[i] == 0) { 1197 ctlr->imu_cal_accel_divisor[i] = 1; 1198 divz++; 1199 } 1200 1201 if (ctlr->imu_cal_gyro_divisor[i] == 0) { 1202 ctlr->imu_cal_gyro_divisor[i] = 1; 1203 divz++; 1204 } 1205 } 1206 1207 if (divz) 1208 hid_warn(ctlr->hdev, "inaccurate IMU divisors (%d)\n", divz); 1209 } 1210 1211 static const s16 DFLT_ACCEL_OFFSET /*= 0*/; 1212 static const s16 DFLT_ACCEL_SCALE = 16384; 1213 static const s16 DFLT_GYRO_OFFSET /*= 0*/; 1214 static const s16 DFLT_GYRO_SCALE = 13371; 1215 static int joycon_request_imu_calibration(struct joycon_ctlr *ctlr) 1216 { 1217 u16 imu_cal_addr = JC_IMU_CAL_FCT_DATA_ADDR; 1218 u8 *raw_cal; 1219 int ret; 1220 int i; 1221 1222 /* check if user calibration exists */ 1223 if (!joycon_check_for_cal_magic(ctlr, JC_IMU_CAL_USR_MAGIC_ADDR)) { 1224 imu_cal_addr = JC_IMU_CAL_USR_DATA_ADDR; 1225 hid_info(ctlr->hdev, "using user cal for IMU\n"); 1226 } else { 1227 hid_info(ctlr->hdev, "using factory cal for IMU\n"); 1228 } 1229 1230 /* request IMU calibration data */ 1231 hid_dbg(ctlr->hdev, "requesting IMU cal data\n"); 1232 ret = joycon_request_spi_flash_read(ctlr, imu_cal_addr, 1233 JC_IMU_CAL_DATA_SIZE, &raw_cal); 1234 if (ret) { 1235 hid_warn(ctlr->hdev, 1236 "Failed to read IMU cal, using defaults; ret=%d\n", 1237 ret); 1238 1239 for (i = 0; i < 3; i++) { 1240 ctlr->accel_cal.offset[i] = DFLT_ACCEL_OFFSET; 1241 ctlr->accel_cal.scale[i] = DFLT_ACCEL_SCALE; 1242 ctlr->gyro_cal.offset[i] = DFLT_GYRO_OFFSET; 1243 ctlr->gyro_cal.scale[i] = DFLT_GYRO_SCALE; 1244 } 1245 joycon_calc_imu_cal_divisors(ctlr); 1246 return ret; 1247 } 1248 1249 /* IMU calibration parsing */ 1250 for (i = 0; i < 3; i++) { 1251 int j = i * 2; 1252 1253 ctlr->accel_cal.offset[i] = get_unaligned_le16(raw_cal + j); 1254 ctlr->accel_cal.scale[i] = get_unaligned_le16(raw_cal + j + 6); 1255 ctlr->gyro_cal.offset[i] = get_unaligned_le16(raw_cal + j + 12); 1256 ctlr->gyro_cal.scale[i] = get_unaligned_le16(raw_cal + j + 18); 1257 } 1258 1259 joycon_calc_imu_cal_divisors(ctlr); 1260 1261 hid_dbg(ctlr->hdev, "IMU calibration:\n" 1262 "a_o[0]=%d a_o[1]=%d a_o[2]=%d\n" 1263 "a_s[0]=%d a_s[1]=%d a_s[2]=%d\n" 1264 "g_o[0]=%d g_o[1]=%d g_o[2]=%d\n" 1265 "g_s[0]=%d g_s[1]=%d g_s[2]=%d\n", 1266 ctlr->accel_cal.offset[0], 1267 ctlr->accel_cal.offset[1], 1268 ctlr->accel_cal.offset[2], 1269 ctlr->accel_cal.scale[0], 1270 ctlr->accel_cal.scale[1], 1271 ctlr->accel_cal.scale[2], 1272 ctlr->gyro_cal.offset[0], 1273 ctlr->gyro_cal.offset[1], 1274 ctlr->gyro_cal.offset[2], 1275 ctlr->gyro_cal.scale[0], 1276 ctlr->gyro_cal.scale[1], 1277 ctlr->gyro_cal.scale[2]); 1278 1279 return 0; 1280 } 1281 1282 static int joycon_set_report_mode(struct joycon_ctlr *ctlr) 1283 { 1284 struct joycon_subcmd_request *req; 1285 u8 buffer[sizeof(*req) + 1] = { 0 }; 1286 1287 req = (struct joycon_subcmd_request *)buffer; 1288 req->subcmd_id = JC_SUBCMD_SET_REPORT_MODE; 1289 req->data[0] = 0x30; /* standard, full report mode */ 1290 1291 hid_dbg(ctlr->hdev, "setting controller report mode\n"); 1292 return joycon_send_subcmd(ctlr, req, 1, HZ); 1293 } 1294 1295 static int joycon_enable_rumble(struct joycon_ctlr *ctlr) 1296 { 1297 struct joycon_subcmd_request *req; 1298 u8 buffer[sizeof(*req) + 1] = { 0 }; 1299 1300 req = (struct joycon_subcmd_request *)buffer; 1301 req->subcmd_id = JC_SUBCMD_ENABLE_VIBRATION; 1302 req->data[0] = 0x01; /* note: 0x00 would disable */ 1303 1304 hid_dbg(ctlr->hdev, "enabling rumble\n"); 1305 return joycon_send_subcmd(ctlr, req, 1, HZ/4); 1306 } 1307 1308 static int joycon_enable_imu(struct joycon_ctlr *ctlr) 1309 { 1310 struct joycon_subcmd_request *req; 1311 u8 buffer[sizeof(*req) + 1] = { 0 }; 1312 1313 req = (struct joycon_subcmd_request *)buffer; 1314 req->subcmd_id = JC_SUBCMD_ENABLE_IMU; 1315 req->data[0] = 0x01; /* note: 0x00 would disable */ 1316 1317 hid_dbg(ctlr->hdev, "enabling IMU\n"); 1318 return joycon_send_subcmd(ctlr, req, 1, HZ); 1319 } 1320 1321 static s32 joycon_map_stick_val(struct joycon_stick_cal *cal, s32 val) 1322 { 1323 s32 center = cal->center; 1324 s32 min = cal->min; 1325 s32 max = cal->max; 1326 s32 new_val; 1327 1328 if (val > center) { 1329 new_val = (val - center) * JC_MAX_STICK_MAG; 1330 new_val /= (max - center); 1331 } else { 1332 new_val = (center - val) * -JC_MAX_STICK_MAG; 1333 new_val /= (center - min); 1334 } 1335 new_val = clamp(new_val, (s32)-JC_MAX_STICK_MAG, (s32)JC_MAX_STICK_MAG); 1336 return new_val; 1337 } 1338 1339 static void joycon_input_report_parse_imu_data(struct joycon_ctlr *ctlr, 1340 struct joycon_input_report *rep, 1341 struct joycon_imu_data *imu_data) 1342 { 1343 u8 *raw = rep->imu_raw_bytes; 1344 int i; 1345 1346 for (i = 0; i < 3; i++) { 1347 struct joycon_imu_data *data = &imu_data[i]; 1348 1349 data->accel_x = get_unaligned_le16(raw + 0); 1350 data->accel_y = get_unaligned_le16(raw + 2); 1351 data->accel_z = get_unaligned_le16(raw + 4); 1352 data->gyro_x = get_unaligned_le16(raw + 6); 1353 data->gyro_y = get_unaligned_le16(raw + 8); 1354 data->gyro_z = get_unaligned_le16(raw + 10); 1355 /* point to next imu sample */ 1356 raw += sizeof(struct joycon_imu_data); 1357 } 1358 } 1359 1360 static void joycon_parse_imu_report(struct joycon_ctlr *ctlr, 1361 struct joycon_input_report *rep) 1362 { 1363 struct joycon_imu_data imu_data[3] = {0}; /* 3 reports per packet */ 1364 struct input_dev *idev = ctlr->imu_input; 1365 unsigned int msecs = jiffies_to_msecs(jiffies); 1366 unsigned int last_msecs = ctlr->imu_last_pkt_ms; 1367 int i; 1368 int value[6]; 1369 1370 joycon_input_report_parse_imu_data(ctlr, rep, imu_data); 1371 1372 /* 1373 * There are complexities surrounding how we determine the timestamps we 1374 * associate with the samples we pass to userspace. The IMU input 1375 * reports do not provide us with a good timestamp. There's a quickly 1376 * incrementing 8-bit counter per input report, but it is not very 1377 * useful for this purpose (it is not entirely clear what rate it 1378 * increments at or if it varies based on packet push rate - more on 1379 * the push rate below...). 1380 * 1381 * The reverse engineering work done on the joy-cons and pro controllers 1382 * by the community seems to indicate the following: 1383 * - The controller samples the IMU every 1.35ms. It then does some of 1384 * its own processing, probably averaging the samples out. 1385 * - Each imu input report contains 3 IMU samples, (usually 5ms apart). 1386 * - In the standard reporting mode (which this driver uses exclusively) 1387 * input reports are pushed from the controller as follows: 1388 * * joy-con (bluetooth): every 15 ms 1389 * * joy-cons (in charging grip via USB): every 15 ms 1390 * * pro controller (USB): every 15 ms 1391 * * pro controller (bluetooth): every 8 ms (this is the wildcard) 1392 * 1393 * Further complicating matters is that some bluetooth stacks are known 1394 * to alter the controller's packet rate by hardcoding the bluetooth 1395 * SSR for the switch controllers (android's stack currently sets the 1396 * SSR to 11ms for both the joy-cons and pro controllers). 1397 * 1398 * In my own testing, I've discovered that my pro controller either 1399 * reports IMU sample batches every 11ms or every 15ms. This rate is 1400 * stable after connecting. It isn't 100% clear what determines this 1401 * rate. Importantly, even when sending every 11ms, none of the samples 1402 * are duplicates. This seems to indicate that the time deltas between 1403 * reported samples can vary based on the input report rate. 1404 * 1405 * The solution employed in this driver is to keep track of the average 1406 * time delta between IMU input reports. In testing, this value has 1407 * proven to be stable, staying at 15ms or 11ms, though other hardware 1408 * configurations and bluetooth stacks could potentially see other rates 1409 * (hopefully this will become more clear as more people use the 1410 * driver). 1411 * 1412 * Keeping track of the average report delta allows us to submit our 1413 * timestamps to userspace based on that. Each report contains 3 1414 * samples, so the IMU sampling rate should be avg_time_delta/3. We can 1415 * also use this average to detect events where we have dropped a 1416 * packet. The userspace timestamp for the samples will be adjusted 1417 * accordingly to prevent unwanted behvaior. 1418 */ 1419 if (!ctlr->imu_first_packet_received) { 1420 ctlr->imu_timestamp_us = 0; 1421 ctlr->imu_delta_samples_count = 0; 1422 ctlr->imu_delta_samples_sum = 0; 1423 ctlr->imu_avg_delta_ms = JC_IMU_DFLT_AVG_DELTA_MS; 1424 ctlr->imu_first_packet_received = true; 1425 } else { 1426 unsigned int delta = msecs - last_msecs; 1427 unsigned int dropped_pkts; 1428 unsigned int dropped_threshold; 1429 1430 /* avg imu report delta housekeeping */ 1431 ctlr->imu_delta_samples_sum += delta; 1432 ctlr->imu_delta_samples_count++; 1433 if (ctlr->imu_delta_samples_count >= 1434 JC_IMU_SAMPLES_PER_DELTA_AVG) { 1435 ctlr->imu_avg_delta_ms = ctlr->imu_delta_samples_sum / 1436 ctlr->imu_delta_samples_count; 1437 ctlr->imu_delta_samples_count = 0; 1438 ctlr->imu_delta_samples_sum = 0; 1439 } 1440 1441 /* don't ever want divide by zero shenanigans */ 1442 if (ctlr->imu_avg_delta_ms == 0) { 1443 ctlr->imu_avg_delta_ms = 1; 1444 hid_warn(ctlr->hdev, "calculated avg imu delta of 0\n"); 1445 } 1446 1447 /* useful for debugging IMU sample rate */ 1448 hid_dbg(ctlr->hdev, 1449 "imu_report: ms=%u last_ms=%u delta=%u avg_delta=%u\n", 1450 msecs, last_msecs, delta, ctlr->imu_avg_delta_ms); 1451 1452 /* check if any packets have been dropped */ 1453 dropped_threshold = ctlr->imu_avg_delta_ms * 3 / 2; 1454 dropped_pkts = (delta - min(delta, dropped_threshold)) / 1455 ctlr->imu_avg_delta_ms; 1456 ctlr->imu_timestamp_us += 1000 * ctlr->imu_avg_delta_ms; 1457 if (dropped_pkts > JC_IMU_DROPPED_PKT_WARNING) { 1458 hid_warn(ctlr->hdev, 1459 "compensating for %u dropped IMU reports\n", 1460 dropped_pkts); 1461 hid_warn(ctlr->hdev, 1462 "delta=%u avg_delta=%u\n", 1463 delta, ctlr->imu_avg_delta_ms); 1464 } 1465 } 1466 ctlr->imu_last_pkt_ms = msecs; 1467 1468 /* Each IMU input report contains three samples */ 1469 for (i = 0; i < 3; i++) { 1470 input_event(idev, EV_MSC, MSC_TIMESTAMP, 1471 ctlr->imu_timestamp_us); 1472 1473 /* 1474 * These calculations (which use the controller's calibration 1475 * settings to improve the final values) are based on those 1476 * found in the community's reverse-engineering repo (linked at 1477 * top of driver). For hid-nintendo, we make sure that the final 1478 * value given to userspace is always in terms of the axis 1479 * resolution we provided. 1480 * 1481 * Currently only the gyro calculations subtract the calibration 1482 * offsets from the raw value itself. In testing, doing the same 1483 * for the accelerometer raw values decreased accuracy. 1484 * 1485 * Note that the gyro values are multiplied by the 1486 * precision-saving scaling factor to prevent large inaccuracies 1487 * due to truncation of the resolution value which would 1488 * otherwise occur. To prevent overflow (without resorting to 64 1489 * bit integer math), the mult_frac macro is used. 1490 */ 1491 value[0] = mult_frac((JC_IMU_PREC_RANGE_SCALE * 1492 (imu_data[i].gyro_x - 1493 ctlr->gyro_cal.offset[0])), 1494 ctlr->gyro_cal.scale[0], 1495 ctlr->imu_cal_gyro_divisor[0]); 1496 value[1] = mult_frac((JC_IMU_PREC_RANGE_SCALE * 1497 (imu_data[i].gyro_y - 1498 ctlr->gyro_cal.offset[1])), 1499 ctlr->gyro_cal.scale[1], 1500 ctlr->imu_cal_gyro_divisor[1]); 1501 value[2] = mult_frac((JC_IMU_PREC_RANGE_SCALE * 1502 (imu_data[i].gyro_z - 1503 ctlr->gyro_cal.offset[2])), 1504 ctlr->gyro_cal.scale[2], 1505 ctlr->imu_cal_gyro_divisor[2]); 1506 1507 value[3] = ((s32)imu_data[i].accel_x * 1508 ctlr->accel_cal.scale[0]) / 1509 ctlr->imu_cal_accel_divisor[0]; 1510 value[4] = ((s32)imu_data[i].accel_y * 1511 ctlr->accel_cal.scale[1]) / 1512 ctlr->imu_cal_accel_divisor[1]; 1513 value[5] = ((s32)imu_data[i].accel_z * 1514 ctlr->accel_cal.scale[2]) / 1515 ctlr->imu_cal_accel_divisor[2]; 1516 1517 hid_dbg(ctlr->hdev, "raw_gyro: g_x=%d g_y=%d g_z=%d\n", 1518 imu_data[i].gyro_x, imu_data[i].gyro_y, 1519 imu_data[i].gyro_z); 1520 hid_dbg(ctlr->hdev, "raw_accel: a_x=%d a_y=%d a_z=%d\n", 1521 imu_data[i].accel_x, imu_data[i].accel_y, 1522 imu_data[i].accel_z); 1523 1524 /* 1525 * The right joy-con has 2 axes negated, Y and Z. This is due to 1526 * the orientation of the IMU in the controller. We negate those 1527 * axes' values in order to be consistent with the left joy-con 1528 * and the pro controller: 1529 * X: positive is pointing toward the triggers 1530 * Y: positive is pointing to the left 1531 * Z: positive is pointing up (out of the buttons/sticks) 1532 * The axes follow the right-hand rule. 1533 */ 1534 if (jc_type_is_joycon(ctlr) && jc_type_has_right(ctlr)) { 1535 int j; 1536 1537 /* negate all but x axis */ 1538 for (j = 1; j < 6; ++j) { 1539 if (j == 3) 1540 continue; 1541 value[j] *= -1; 1542 } 1543 } 1544 1545 input_report_abs(idev, ABS_RX, value[0]); 1546 input_report_abs(idev, ABS_RY, value[1]); 1547 input_report_abs(idev, ABS_RZ, value[2]); 1548 input_report_abs(idev, ABS_X, value[3]); 1549 input_report_abs(idev, ABS_Y, value[4]); 1550 input_report_abs(idev, ABS_Z, value[5]); 1551 input_sync(idev); 1552 /* convert to micros and divide by 3 (3 samples per report). */ 1553 ctlr->imu_timestamp_us += ctlr->imu_avg_delta_ms * 1000 / 3; 1554 } 1555 } 1556 1557 static void joycon_handle_rumble_report(struct joycon_ctlr *ctlr, struct joycon_input_report *rep) 1558 { 1559 unsigned long flags; 1560 unsigned long msecs = jiffies_to_msecs(jiffies); 1561 1562 spin_lock_irqsave(&ctlr->lock, flags); 1563 if (IS_ENABLED(CONFIG_NINTENDO_FF) && rep->vibrator_report && 1564 ctlr->ctlr_state != JOYCON_CTLR_STATE_REMOVED && 1565 (msecs - ctlr->rumble_msecs) >= JC_RUMBLE_PERIOD_MS && 1566 (ctlr->rumble_queue_head != ctlr->rumble_queue_tail || 1567 ctlr->rumble_zero_countdown > 0)) { 1568 /* 1569 * When this value reaches 0, we know we've sent multiple 1570 * packets to the controller instructing it to disable rumble. 1571 * We can safely stop sending periodic rumble packets until the 1572 * next ff effect. 1573 */ 1574 if (ctlr->rumble_zero_countdown > 0) 1575 ctlr->rumble_zero_countdown--; 1576 queue_work(ctlr->rumble_queue, &ctlr->rumble_worker); 1577 } 1578 1579 spin_unlock_irqrestore(&ctlr->lock, flags); 1580 } 1581 1582 static void joycon_parse_battery_status(struct joycon_ctlr *ctlr, struct joycon_input_report *rep) 1583 { 1584 u8 tmp; 1585 unsigned long flags; 1586 1587 spin_lock_irqsave(&ctlr->lock, flags); 1588 1589 tmp = rep->bat_con; 1590 ctlr->host_powered = tmp & BIT(0); 1591 ctlr->battery_charging = tmp & BIT(4); 1592 tmp = tmp >> 5; 1593 1594 switch (tmp) { 1595 case 0: /* empty */ 1596 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL; 1597 break; 1598 case 1: /* low */ 1599 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_LOW; 1600 break; 1601 case 2: /* medium */ 1602 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL; 1603 break; 1604 case 3: /* high */ 1605 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_HIGH; 1606 break; 1607 case 4: /* full */ 1608 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_FULL; 1609 break; 1610 default: 1611 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN; 1612 hid_warn(ctlr->hdev, "Invalid battery status\n"); 1613 break; 1614 } 1615 1616 spin_unlock_irqrestore(&ctlr->lock, flags); 1617 } 1618 1619 static void joycon_report_left_stick(struct joycon_ctlr *ctlr, 1620 struct joycon_input_report *rep) 1621 { 1622 u16 raw_x; 1623 u16 raw_y; 1624 s32 x; 1625 s32 y; 1626 1627 raw_x = hid_field_extract(ctlr->hdev, rep->left_stick, 0, 12); 1628 raw_y = hid_field_extract(ctlr->hdev, rep->left_stick + 1, 4, 12); 1629 1630 x = joycon_map_stick_val(&ctlr->left_stick_cal_x, raw_x); 1631 y = -joycon_map_stick_val(&ctlr->left_stick_cal_y, raw_y); 1632 1633 input_report_abs(ctlr->input, ABS_X, x); 1634 input_report_abs(ctlr->input, ABS_Y, y); 1635 } 1636 1637 static void joycon_report_right_stick(struct joycon_ctlr *ctlr, 1638 struct joycon_input_report *rep) 1639 { 1640 u16 raw_x; 1641 u16 raw_y; 1642 s32 x; 1643 s32 y; 1644 1645 raw_x = hid_field_extract(ctlr->hdev, rep->right_stick, 0, 12); 1646 raw_y = hid_field_extract(ctlr->hdev, rep->right_stick + 1, 4, 12); 1647 1648 x = joycon_map_stick_val(&ctlr->right_stick_cal_x, raw_x); 1649 y = -joycon_map_stick_val(&ctlr->right_stick_cal_y, raw_y); 1650 1651 input_report_abs(ctlr->input, ABS_RX, x); 1652 input_report_abs(ctlr->input, ABS_RY, y); 1653 } 1654 1655 static void joycon_report_dpad(struct joycon_ctlr *ctlr, 1656 struct joycon_input_report *rep) 1657 { 1658 int hatx = 0; 1659 int haty = 0; 1660 u32 btns = hid_field_extract(ctlr->hdev, rep->button_status, 0, 24); 1661 1662 if (btns & JC_BTN_LEFT) 1663 hatx = -1; 1664 else if (btns & JC_BTN_RIGHT) 1665 hatx = 1; 1666 1667 if (btns & JC_BTN_UP) 1668 haty = -1; 1669 else if (btns & JC_BTN_DOWN) 1670 haty = 1; 1671 1672 input_report_abs(ctlr->input, ABS_HAT0X, hatx); 1673 input_report_abs(ctlr->input, ABS_HAT0Y, haty); 1674 } 1675 1676 static void joycon_report_buttons(struct joycon_ctlr *ctlr, 1677 struct joycon_input_report *rep, 1678 const struct joycon_ctlr_button_mapping button_mappings[]) 1679 { 1680 const struct joycon_ctlr_button_mapping *button; 1681 u32 status = hid_field_extract(ctlr->hdev, rep->button_status, 0, 24); 1682 1683 for (button = button_mappings; button->code; button++) 1684 input_report_key(ctlr->input, button->code, status & button->bit); 1685 } 1686 1687 static void joycon_parse_report(struct joycon_ctlr *ctlr, 1688 struct joycon_input_report *rep) 1689 { 1690 unsigned long flags; 1691 unsigned long msecs = jiffies_to_msecs(jiffies); 1692 unsigned long report_delta_ms = msecs - ctlr->last_input_report_msecs; 1693 1694 if (joycon_has_rumble(ctlr)) 1695 joycon_handle_rumble_report(ctlr, rep); 1696 1697 joycon_parse_battery_status(ctlr, rep); 1698 1699 if (joycon_type_is_left_joycon(ctlr)) { 1700 joycon_report_left_stick(ctlr, rep); 1701 joycon_report_buttons(ctlr, rep, left_joycon_button_mappings); 1702 if (!joycon_device_is_chrggrip(ctlr)) 1703 joycon_report_buttons(ctlr, rep, left_joycon_s_button_mappings); 1704 } else if (joycon_type_is_right_joycon(ctlr)) { 1705 joycon_report_right_stick(ctlr, rep); 1706 joycon_report_buttons(ctlr, rep, right_joycon_button_mappings); 1707 if (!joycon_device_is_chrggrip(ctlr)) 1708 joycon_report_buttons(ctlr, rep, right_joycon_s_button_mappings); 1709 } else if (joycon_type_is_procon(ctlr)) { 1710 joycon_report_left_stick(ctlr, rep); 1711 joycon_report_right_stick(ctlr, rep); 1712 joycon_report_dpad(ctlr, rep); 1713 joycon_report_buttons(ctlr, rep, procon_button_mappings); 1714 } else if (joycon_type_is_any_nescon(ctlr)) { 1715 joycon_report_dpad(ctlr, rep); 1716 joycon_report_buttons(ctlr, rep, nescon_button_mappings); 1717 } else if (joycon_type_is_snescon(ctlr)) { 1718 joycon_report_dpad(ctlr, rep); 1719 joycon_report_buttons(ctlr, rep, snescon_button_mappings); 1720 } else if (joycon_type_is_gencon(ctlr)) { 1721 joycon_report_dpad(ctlr, rep); 1722 joycon_report_buttons(ctlr, rep, gencon_button_mappings); 1723 } else if (joycon_type_is_n64con(ctlr)) { 1724 joycon_report_left_stick(ctlr, rep); 1725 joycon_report_dpad(ctlr, rep); 1726 joycon_report_buttons(ctlr, rep, n64con_button_mappings); 1727 } 1728 1729 input_sync(ctlr->input); 1730 1731 spin_lock_irqsave(&ctlr->lock, flags); 1732 ctlr->last_input_report_msecs = msecs; 1733 /* 1734 * Was this input report a reasonable time delta compared to the prior 1735 * report? We use this information to decide when a safe time is to send 1736 * rumble packets or subcommand packets. 1737 */ 1738 if (report_delta_ms >= JC_INPUT_REPORT_MIN_DELTA && 1739 report_delta_ms <= JC_INPUT_REPORT_MAX_DELTA) { 1740 if (ctlr->consecutive_valid_report_deltas < JC_SUBCMD_VALID_DELTA_REQ) 1741 ctlr->consecutive_valid_report_deltas++; 1742 } else { 1743 ctlr->consecutive_valid_report_deltas = 0; 1744 } 1745 /* 1746 * Our consecutive valid report tracking is only relevant for 1747 * bluetooth-connected controllers. For USB devices, we're beholden to 1748 * USB's underlying polling rate anyway. Always set to the consecutive 1749 * delta requirement. 1750 */ 1751 if (ctlr->hdev->bus == BUS_USB) 1752 ctlr->consecutive_valid_report_deltas = JC_SUBCMD_VALID_DELTA_REQ; 1753 1754 spin_unlock_irqrestore(&ctlr->lock, flags); 1755 1756 /* 1757 * Immediately after receiving a report is the most reliable time to 1758 * send a subcommand to the controller. Wake any subcommand senders 1759 * waiting for a report. 1760 */ 1761 if (unlikely(mutex_is_locked(&ctlr->output_mutex))) { 1762 spin_lock_irqsave(&ctlr->lock, flags); 1763 ctlr->received_input_report = true; 1764 spin_unlock_irqrestore(&ctlr->lock, flags); 1765 wake_up(&ctlr->wait); 1766 } 1767 1768 /* parse IMU data if present */ 1769 if ((rep->id == JC_INPUT_IMU_DATA) && joycon_has_imu(ctlr)) 1770 joycon_parse_imu_report(ctlr, rep); 1771 } 1772 1773 static int joycon_send_rumble_data(struct joycon_ctlr *ctlr) 1774 { 1775 int ret; 1776 unsigned long flags; 1777 struct joycon_rumble_output rumble_output = { 0 }; 1778 1779 spin_lock_irqsave(&ctlr->lock, flags); 1780 /* 1781 * If the controller has been removed, just return ENODEV so the LED 1782 * subsystem doesn't print invalid errors on removal. 1783 */ 1784 if (ctlr->ctlr_state == JOYCON_CTLR_STATE_REMOVED) { 1785 spin_unlock_irqrestore(&ctlr->lock, flags); 1786 return -ENODEV; 1787 } 1788 memcpy(rumble_output.rumble_data, 1789 ctlr->rumble_data[ctlr->rumble_queue_tail], 1790 JC_RUMBLE_DATA_SIZE); 1791 spin_unlock_irqrestore(&ctlr->lock, flags); 1792 1793 rumble_output.output_id = JC_OUTPUT_RUMBLE_ONLY; 1794 rumble_output.packet_num = ctlr->subcmd_num; 1795 if (++ctlr->subcmd_num > 0xF) 1796 ctlr->subcmd_num = 0; 1797 1798 joycon_enforce_subcmd_rate(ctlr); 1799 1800 ret = __joycon_hid_send(ctlr->hdev, (u8 *)&rumble_output, 1801 sizeof(rumble_output)); 1802 return ret; 1803 } 1804 1805 static void joycon_rumble_worker(struct work_struct *work) 1806 { 1807 struct joycon_ctlr *ctlr = container_of(work, struct joycon_ctlr, 1808 rumble_worker); 1809 unsigned long flags; 1810 bool again = true; 1811 int ret; 1812 1813 while (again) { 1814 mutex_lock(&ctlr->output_mutex); 1815 ret = joycon_send_rumble_data(ctlr); 1816 mutex_unlock(&ctlr->output_mutex); 1817 1818 /* -ENODEV means the controller was just unplugged */ 1819 spin_lock_irqsave(&ctlr->lock, flags); 1820 if (ret < 0 && ret != -ENODEV && 1821 ctlr->ctlr_state != JOYCON_CTLR_STATE_REMOVED) 1822 hid_warn(ctlr->hdev, "Failed to set rumble; e=%d", ret); 1823 1824 ctlr->rumble_msecs = jiffies_to_msecs(jiffies); 1825 if (ctlr->rumble_queue_tail != ctlr->rumble_queue_head) { 1826 if (++ctlr->rumble_queue_tail >= JC_RUMBLE_QUEUE_SIZE) 1827 ctlr->rumble_queue_tail = 0; 1828 } else { 1829 again = false; 1830 } 1831 spin_unlock_irqrestore(&ctlr->lock, flags); 1832 } 1833 } 1834 1835 #if IS_ENABLED(CONFIG_NINTENDO_FF) 1836 static struct joycon_rumble_freq_data joycon_find_rumble_freq(u16 freq) 1837 { 1838 const size_t length = ARRAY_SIZE(joycon_rumble_frequencies); 1839 const struct joycon_rumble_freq_data *data = joycon_rumble_frequencies; 1840 int i = 0; 1841 1842 if (freq > data[0].freq) { 1843 for (i = 1; i < length - 1; i++) { 1844 if (freq > data[i - 1].freq && freq <= data[i].freq) 1845 break; 1846 } 1847 } 1848 1849 return data[i]; 1850 } 1851 1852 static struct joycon_rumble_amp_data joycon_find_rumble_amp(u16 amp) 1853 { 1854 const size_t length = ARRAY_SIZE(joycon_rumble_amplitudes); 1855 const struct joycon_rumble_amp_data *data = joycon_rumble_amplitudes; 1856 int i = 0; 1857 1858 if (amp > data[0].amp) { 1859 for (i = 1; i < length - 1; i++) { 1860 if (amp > data[i - 1].amp && amp <= data[i].amp) 1861 break; 1862 } 1863 } 1864 1865 return data[i]; 1866 } 1867 1868 static void joycon_encode_rumble(u8 *data, u16 freq_low, u16 freq_high, u16 amp) 1869 { 1870 struct joycon_rumble_freq_data freq_data_low; 1871 struct joycon_rumble_freq_data freq_data_high; 1872 struct joycon_rumble_amp_data amp_data; 1873 1874 freq_data_low = joycon_find_rumble_freq(freq_low); 1875 freq_data_high = joycon_find_rumble_freq(freq_high); 1876 amp_data = joycon_find_rumble_amp(amp); 1877 1878 data[0] = (freq_data_high.high >> 8) & 0xFF; 1879 data[1] = (freq_data_high.high & 0xFF) + amp_data.high; 1880 data[2] = freq_data_low.low + ((amp_data.low >> 8) & 0xFF); 1881 data[3] = amp_data.low & 0xFF; 1882 } 1883 1884 static const u16 JOYCON_MAX_RUMBLE_HIGH_FREQ = 1253; 1885 static const u16 JOYCON_MIN_RUMBLE_HIGH_FREQ = 82; 1886 static const u16 JOYCON_MAX_RUMBLE_LOW_FREQ = 626; 1887 static const u16 JOYCON_MIN_RUMBLE_LOW_FREQ = 41; 1888 1889 static void joycon_clamp_rumble_freqs(struct joycon_ctlr *ctlr) 1890 { 1891 unsigned long flags; 1892 1893 spin_lock_irqsave(&ctlr->lock, flags); 1894 ctlr->rumble_ll_freq = clamp(ctlr->rumble_ll_freq, 1895 JOYCON_MIN_RUMBLE_LOW_FREQ, 1896 JOYCON_MAX_RUMBLE_LOW_FREQ); 1897 ctlr->rumble_lh_freq = clamp(ctlr->rumble_lh_freq, 1898 JOYCON_MIN_RUMBLE_HIGH_FREQ, 1899 JOYCON_MAX_RUMBLE_HIGH_FREQ); 1900 ctlr->rumble_rl_freq = clamp(ctlr->rumble_rl_freq, 1901 JOYCON_MIN_RUMBLE_LOW_FREQ, 1902 JOYCON_MAX_RUMBLE_LOW_FREQ); 1903 ctlr->rumble_rh_freq = clamp(ctlr->rumble_rh_freq, 1904 JOYCON_MIN_RUMBLE_HIGH_FREQ, 1905 JOYCON_MAX_RUMBLE_HIGH_FREQ); 1906 spin_unlock_irqrestore(&ctlr->lock, flags); 1907 } 1908 1909 static int joycon_set_rumble(struct joycon_ctlr *ctlr, u16 amp_r, u16 amp_l, 1910 bool schedule_now) 1911 { 1912 u8 data[JC_RUMBLE_DATA_SIZE]; 1913 u16 amp; 1914 u16 freq_r_low; 1915 u16 freq_r_high; 1916 u16 freq_l_low; 1917 u16 freq_l_high; 1918 unsigned long flags; 1919 int next_rq_head; 1920 1921 spin_lock_irqsave(&ctlr->lock, flags); 1922 freq_r_low = ctlr->rumble_rl_freq; 1923 freq_r_high = ctlr->rumble_rh_freq; 1924 freq_l_low = ctlr->rumble_ll_freq; 1925 freq_l_high = ctlr->rumble_lh_freq; 1926 /* limit number of silent rumble packets to reduce traffic */ 1927 if (amp_l != 0 || amp_r != 0) 1928 ctlr->rumble_zero_countdown = JC_RUMBLE_ZERO_AMP_PKT_CNT; 1929 spin_unlock_irqrestore(&ctlr->lock, flags); 1930 1931 /* right joy-con */ 1932 amp = amp_r * (u32)joycon_max_rumble_amp / 65535; 1933 joycon_encode_rumble(data + 4, freq_r_low, freq_r_high, amp); 1934 1935 /* left joy-con */ 1936 amp = amp_l * (u32)joycon_max_rumble_amp / 65535; 1937 joycon_encode_rumble(data, freq_l_low, freq_l_high, amp); 1938 1939 spin_lock_irqsave(&ctlr->lock, flags); 1940 1941 next_rq_head = ctlr->rumble_queue_head + 1; 1942 if (next_rq_head >= JC_RUMBLE_QUEUE_SIZE) 1943 next_rq_head = 0; 1944 1945 /* Did we overrun the circular buffer? 1946 * If so, be sure we keep the latest intended rumble state. 1947 */ 1948 if (next_rq_head == ctlr->rumble_queue_tail) { 1949 hid_dbg(ctlr->hdev, "rumble queue is full"); 1950 /* overwrite the prior value at the end of the circular buf */ 1951 next_rq_head = ctlr->rumble_queue_head; 1952 } 1953 1954 ctlr->rumble_queue_head = next_rq_head; 1955 memcpy(ctlr->rumble_data[ctlr->rumble_queue_head], data, 1956 JC_RUMBLE_DATA_SIZE); 1957 1958 /* don't wait for the periodic send (reduces latency) */ 1959 if (schedule_now && ctlr->ctlr_state != JOYCON_CTLR_STATE_REMOVED) 1960 queue_work(ctlr->rumble_queue, &ctlr->rumble_worker); 1961 1962 spin_unlock_irqrestore(&ctlr->lock, flags); 1963 1964 return 0; 1965 } 1966 1967 static int joycon_play_effect(struct input_dev *dev, void *data, 1968 struct ff_effect *effect) 1969 { 1970 struct joycon_ctlr *ctlr = input_get_drvdata(dev); 1971 1972 if (effect->type != FF_RUMBLE) 1973 return 0; 1974 1975 return joycon_set_rumble(ctlr, 1976 effect->u.rumble.weak_magnitude, 1977 effect->u.rumble.strong_magnitude, 1978 true); 1979 } 1980 #endif /* IS_ENABLED(CONFIG_NINTENDO_FF) */ 1981 1982 static void joycon_config_left_stick(struct input_dev *idev) 1983 { 1984 input_set_abs_params(idev, 1985 ABS_X, 1986 -JC_MAX_STICK_MAG, 1987 JC_MAX_STICK_MAG, 1988 JC_STICK_FUZZ, 1989 JC_STICK_FLAT); 1990 input_set_abs_params(idev, 1991 ABS_Y, 1992 -JC_MAX_STICK_MAG, 1993 JC_MAX_STICK_MAG, 1994 JC_STICK_FUZZ, 1995 JC_STICK_FLAT); 1996 } 1997 1998 static void joycon_config_right_stick(struct input_dev *idev) 1999 { 2000 input_set_abs_params(idev, 2001 ABS_RX, 2002 -JC_MAX_STICK_MAG, 2003 JC_MAX_STICK_MAG, 2004 JC_STICK_FUZZ, 2005 JC_STICK_FLAT); 2006 input_set_abs_params(idev, 2007 ABS_RY, 2008 -JC_MAX_STICK_MAG, 2009 JC_MAX_STICK_MAG, 2010 JC_STICK_FUZZ, 2011 JC_STICK_FLAT); 2012 } 2013 2014 static void joycon_config_dpad(struct input_dev *idev) 2015 { 2016 input_set_abs_params(idev, 2017 ABS_HAT0X, 2018 -JC_MAX_DPAD_MAG, 2019 JC_MAX_DPAD_MAG, 2020 JC_DPAD_FUZZ, 2021 JC_DPAD_FLAT); 2022 input_set_abs_params(idev, 2023 ABS_HAT0Y, 2024 -JC_MAX_DPAD_MAG, 2025 JC_MAX_DPAD_MAG, 2026 JC_DPAD_FUZZ, 2027 JC_DPAD_FLAT); 2028 } 2029 2030 static void joycon_config_buttons(struct input_dev *idev, 2031 const struct joycon_ctlr_button_mapping button_mappings[]) 2032 { 2033 const struct joycon_ctlr_button_mapping *button; 2034 2035 for (button = button_mappings; button->code; button++) 2036 input_set_capability(idev, EV_KEY, button->code); 2037 } 2038 2039 static void joycon_config_rumble(struct joycon_ctlr *ctlr) 2040 { 2041 #if IS_ENABLED(CONFIG_NINTENDO_FF) 2042 /* set up rumble */ 2043 input_set_capability(ctlr->input, EV_FF, FF_RUMBLE); 2044 input_ff_create_memless(ctlr->input, NULL, joycon_play_effect); 2045 ctlr->rumble_ll_freq = JC_RUMBLE_DFLT_LOW_FREQ; 2046 ctlr->rumble_lh_freq = JC_RUMBLE_DFLT_HIGH_FREQ; 2047 ctlr->rumble_rl_freq = JC_RUMBLE_DFLT_LOW_FREQ; 2048 ctlr->rumble_rh_freq = JC_RUMBLE_DFLT_HIGH_FREQ; 2049 joycon_clamp_rumble_freqs(ctlr); 2050 joycon_set_rumble(ctlr, 0, 0, false); 2051 ctlr->rumble_msecs = jiffies_to_msecs(jiffies); 2052 #endif 2053 } 2054 2055 static int joycon_imu_input_create(struct joycon_ctlr *ctlr) 2056 { 2057 struct hid_device *hdev; 2058 const char *imu_name; 2059 int ret; 2060 2061 hdev = ctlr->hdev; 2062 2063 /* configure the imu input device */ 2064 ctlr->imu_input = devm_input_allocate_device(&hdev->dev); 2065 if (!ctlr->imu_input) 2066 return -ENOMEM; 2067 2068 ctlr->imu_input->id.bustype = hdev->bus; 2069 ctlr->imu_input->id.vendor = hdev->vendor; 2070 ctlr->imu_input->id.product = hdev->product; 2071 ctlr->imu_input->id.version = hdev->version; 2072 ctlr->imu_input->uniq = ctlr->mac_addr_str; 2073 ctlr->imu_input->phys = hdev->phys; 2074 2075 imu_name = devm_kasprintf(&hdev->dev, GFP_KERNEL, "%s (IMU)", ctlr->input->name); 2076 if (!imu_name) 2077 return -ENOMEM; 2078 2079 ctlr->imu_input->name = imu_name; 2080 2081 input_set_drvdata(ctlr->imu_input, ctlr); 2082 2083 /* configure imu axes */ 2084 input_set_abs_params(ctlr->imu_input, ABS_X, 2085 -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG, 2086 JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT); 2087 input_set_abs_params(ctlr->imu_input, ABS_Y, 2088 -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG, 2089 JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT); 2090 input_set_abs_params(ctlr->imu_input, ABS_Z, 2091 -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG, 2092 JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT); 2093 input_abs_set_res(ctlr->imu_input, ABS_X, JC_IMU_ACCEL_RES_PER_G); 2094 input_abs_set_res(ctlr->imu_input, ABS_Y, JC_IMU_ACCEL_RES_PER_G); 2095 input_abs_set_res(ctlr->imu_input, ABS_Z, JC_IMU_ACCEL_RES_PER_G); 2096 2097 input_set_abs_params(ctlr->imu_input, ABS_RX, 2098 -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG, 2099 JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT); 2100 input_set_abs_params(ctlr->imu_input, ABS_RY, 2101 -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG, 2102 JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT); 2103 input_set_abs_params(ctlr->imu_input, ABS_RZ, 2104 -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG, 2105 JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT); 2106 2107 input_abs_set_res(ctlr->imu_input, ABS_RX, JC_IMU_GYRO_RES_PER_DPS); 2108 input_abs_set_res(ctlr->imu_input, ABS_RY, JC_IMU_GYRO_RES_PER_DPS); 2109 input_abs_set_res(ctlr->imu_input, ABS_RZ, JC_IMU_GYRO_RES_PER_DPS); 2110 2111 __set_bit(EV_MSC, ctlr->imu_input->evbit); 2112 __set_bit(MSC_TIMESTAMP, ctlr->imu_input->mscbit); 2113 __set_bit(INPUT_PROP_ACCELEROMETER, ctlr->imu_input->propbit); 2114 2115 ret = input_register_device(ctlr->imu_input); 2116 if (ret) 2117 return ret; 2118 2119 return 0; 2120 } 2121 2122 static int joycon_input_create(struct joycon_ctlr *ctlr) 2123 { 2124 struct hid_device *hdev; 2125 int ret; 2126 2127 hdev = ctlr->hdev; 2128 2129 ctlr->input = devm_input_allocate_device(&hdev->dev); 2130 if (!ctlr->input) 2131 return -ENOMEM; 2132 ctlr->input->id.bustype = hdev->bus; 2133 ctlr->input->id.vendor = hdev->vendor; 2134 ctlr->input->id.product = hdev->product; 2135 ctlr->input->id.version = hdev->version; 2136 ctlr->input->uniq = ctlr->mac_addr_str; 2137 ctlr->input->name = hdev->name; 2138 ctlr->input->phys = hdev->phys; 2139 input_set_drvdata(ctlr->input, ctlr); 2140 2141 ret = input_register_device(ctlr->input); 2142 if (ret) 2143 return ret; 2144 2145 if (joycon_type_is_right_joycon(ctlr)) { 2146 joycon_config_right_stick(ctlr->input); 2147 joycon_config_buttons(ctlr->input, right_joycon_button_mappings); 2148 if (!joycon_device_is_chrggrip(ctlr)) 2149 joycon_config_buttons(ctlr->input, right_joycon_s_button_mappings); 2150 } else if (joycon_type_is_left_joycon(ctlr)) { 2151 joycon_config_left_stick(ctlr->input); 2152 joycon_config_buttons(ctlr->input, left_joycon_button_mappings); 2153 if (!joycon_device_is_chrggrip(ctlr)) 2154 joycon_config_buttons(ctlr->input, left_joycon_s_button_mappings); 2155 } else if (joycon_type_is_procon(ctlr)) { 2156 joycon_config_left_stick(ctlr->input); 2157 joycon_config_right_stick(ctlr->input); 2158 joycon_config_dpad(ctlr->input); 2159 joycon_config_buttons(ctlr->input, procon_button_mappings); 2160 } else if (joycon_type_is_any_nescon(ctlr)) { 2161 joycon_config_dpad(ctlr->input); 2162 joycon_config_buttons(ctlr->input, nescon_button_mappings); 2163 } else if (joycon_type_is_snescon(ctlr)) { 2164 joycon_config_dpad(ctlr->input); 2165 joycon_config_buttons(ctlr->input, snescon_button_mappings); 2166 } else if (joycon_type_is_gencon(ctlr)) { 2167 joycon_config_dpad(ctlr->input); 2168 joycon_config_buttons(ctlr->input, gencon_button_mappings); 2169 } else if (joycon_type_is_n64con(ctlr)) { 2170 joycon_config_dpad(ctlr->input); 2171 joycon_config_left_stick(ctlr->input); 2172 joycon_config_buttons(ctlr->input, n64con_button_mappings); 2173 } 2174 2175 if (joycon_has_imu(ctlr)) { 2176 ret = joycon_imu_input_create(ctlr); 2177 if (ret) 2178 return ret; 2179 } 2180 2181 if (joycon_has_rumble(ctlr)) 2182 joycon_config_rumble(ctlr); 2183 2184 return 0; 2185 } 2186 2187 /* Because the subcommand sets all the leds at once, the brightness argument is ignored */ 2188 static int joycon_player_led_brightness_set(struct led_classdev *led, 2189 enum led_brightness brightness) 2190 { 2191 struct device *dev = led->dev->parent; 2192 struct hid_device *hdev = to_hid_device(dev); 2193 struct joycon_ctlr *ctlr; 2194 int val = 0; 2195 int i; 2196 int ret; 2197 2198 ctlr = hid_get_drvdata(hdev); 2199 if (!ctlr) { 2200 hid_err(hdev, "No controller data\n"); 2201 return -ENODEV; 2202 } 2203 2204 for (i = 0; i < JC_NUM_LEDS; i++) 2205 val |= ctlr->leds[i].brightness << i; 2206 2207 mutex_lock(&ctlr->output_mutex); 2208 ret = joycon_set_player_leds(ctlr, 0, val); 2209 mutex_unlock(&ctlr->output_mutex); 2210 2211 return ret; 2212 } 2213 2214 static int joycon_home_led_brightness_set(struct led_classdev *led, 2215 enum led_brightness brightness) 2216 { 2217 struct device *dev = led->dev->parent; 2218 struct hid_device *hdev = to_hid_device(dev); 2219 struct joycon_ctlr *ctlr; 2220 int ret; 2221 2222 ctlr = hid_get_drvdata(hdev); 2223 if (!ctlr) { 2224 hid_err(hdev, "No controller data\n"); 2225 return -ENODEV; 2226 } 2227 mutex_lock(&ctlr->output_mutex); 2228 ret = joycon_set_home_led(ctlr, brightness); 2229 mutex_unlock(&ctlr->output_mutex); 2230 return ret; 2231 } 2232 2233 static DEFINE_IDA(nintendo_player_id_allocator); 2234 2235 static int joycon_leds_create(struct joycon_ctlr *ctlr) 2236 { 2237 struct hid_device *hdev = ctlr->hdev; 2238 struct device *dev = &hdev->dev; 2239 const char *d_name = dev_name(dev); 2240 struct led_classdev *led; 2241 int led_val = 0; 2242 char *name; 2243 int ret; 2244 int i; 2245 int player_led_pattern; 2246 2247 /* configure the player LEDs */ 2248 ctlr->player_id = U32_MAX; 2249 ret = ida_alloc(&nintendo_player_id_allocator, GFP_KERNEL); 2250 if (ret < 0) { 2251 hid_warn(hdev, "Failed to allocate player ID, skipping; ret=%d\n", ret); 2252 goto home_led; 2253 } 2254 ctlr->player_id = ret; 2255 player_led_pattern = ret % JC_NUM_LED_PATTERNS; 2256 hid_info(ctlr->hdev, "assigned player %d led pattern", player_led_pattern + 1); 2257 2258 for (i = 0; i < JC_NUM_LEDS; i++) { 2259 name = devm_kasprintf(dev, GFP_KERNEL, "%s:%s:%s", 2260 d_name, 2261 "green", 2262 joycon_player_led_names[i]); 2263 if (!name) 2264 return -ENOMEM; 2265 2266 led = &ctlr->leds[i]; 2267 led->name = name; 2268 led->brightness = joycon_player_led_patterns[player_led_pattern][i]; 2269 led->max_brightness = 1; 2270 led->brightness_set_blocking = 2271 joycon_player_led_brightness_set; 2272 led->flags = LED_CORE_SUSPENDRESUME | LED_HW_PLUGGABLE; 2273 2274 led_val |= joycon_player_led_patterns[player_led_pattern][i] << i; 2275 } 2276 mutex_lock(&ctlr->output_mutex); 2277 ret = joycon_set_player_leds(ctlr, 0, led_val); 2278 mutex_unlock(&ctlr->output_mutex); 2279 if (ret) { 2280 hid_warn(hdev, "Failed to set players LEDs, skipping registration; ret=%d\n", ret); 2281 goto home_led; 2282 } 2283 2284 for (i = 0; i < JC_NUM_LEDS; i++) { 2285 led = &ctlr->leds[i]; 2286 ret = devm_led_classdev_register(&hdev->dev, led); 2287 if (ret) { 2288 hid_err(hdev, "Failed to register player %d LED; ret=%d\n", i + 1, ret); 2289 return ret; 2290 } 2291 } 2292 2293 home_led: 2294 /* configure the home LED */ 2295 if (jc_type_has_right(ctlr)) { 2296 name = devm_kasprintf(dev, GFP_KERNEL, "%s:%s:%s", 2297 d_name, 2298 "blue", 2299 LED_FUNCTION_PLAYER5); 2300 if (!name) 2301 return -ENOMEM; 2302 2303 led = &ctlr->home_led; 2304 led->name = name; 2305 led->brightness = 0; 2306 led->max_brightness = 0xF; 2307 led->brightness_set_blocking = joycon_home_led_brightness_set; 2308 led->flags = LED_CORE_SUSPENDRESUME | LED_HW_PLUGGABLE; 2309 2310 /* Set the home LED to 0 as default state */ 2311 mutex_lock(&ctlr->output_mutex); 2312 ret = joycon_set_home_led(ctlr, 0); 2313 mutex_unlock(&ctlr->output_mutex); 2314 if (ret) { 2315 hid_warn(hdev, "Failed to set home LED, skipping registration; ret=%d\n", ret); 2316 return 0; 2317 } 2318 2319 ret = devm_led_classdev_register(&hdev->dev, led); 2320 if (ret) { 2321 hid_err(hdev, "Failed to register home LED; ret=%d\n", ret); 2322 return ret; 2323 } 2324 } 2325 2326 return 0; 2327 } 2328 2329 static int joycon_battery_get_property(struct power_supply *supply, 2330 enum power_supply_property prop, 2331 union power_supply_propval *val) 2332 { 2333 struct joycon_ctlr *ctlr = power_supply_get_drvdata(supply); 2334 unsigned long flags; 2335 int ret = 0; 2336 u8 capacity; 2337 bool charging; 2338 bool powered; 2339 2340 spin_lock_irqsave(&ctlr->lock, flags); 2341 capacity = ctlr->battery_capacity; 2342 charging = ctlr->battery_charging; 2343 powered = ctlr->host_powered; 2344 spin_unlock_irqrestore(&ctlr->lock, flags); 2345 2346 switch (prop) { 2347 case POWER_SUPPLY_PROP_PRESENT: 2348 val->intval = 1; 2349 break; 2350 case POWER_SUPPLY_PROP_SCOPE: 2351 val->intval = POWER_SUPPLY_SCOPE_DEVICE; 2352 break; 2353 case POWER_SUPPLY_PROP_CAPACITY_LEVEL: 2354 val->intval = capacity; 2355 break; 2356 case POWER_SUPPLY_PROP_STATUS: 2357 if (charging) 2358 val->intval = POWER_SUPPLY_STATUS_CHARGING; 2359 else if (capacity == POWER_SUPPLY_CAPACITY_LEVEL_FULL && 2360 powered) 2361 val->intval = POWER_SUPPLY_STATUS_FULL; 2362 else 2363 val->intval = POWER_SUPPLY_STATUS_DISCHARGING; 2364 break; 2365 default: 2366 ret = -EINVAL; 2367 break; 2368 } 2369 return ret; 2370 } 2371 2372 static enum power_supply_property joycon_battery_props[] = { 2373 POWER_SUPPLY_PROP_PRESENT, 2374 POWER_SUPPLY_PROP_CAPACITY_LEVEL, 2375 POWER_SUPPLY_PROP_SCOPE, 2376 POWER_SUPPLY_PROP_STATUS, 2377 }; 2378 2379 static int joycon_power_supply_create(struct joycon_ctlr *ctlr) 2380 { 2381 struct hid_device *hdev = ctlr->hdev; 2382 struct power_supply_config supply_config = { .drv_data = ctlr, }; 2383 const char * const name_fmt = "nintendo_switch_controller_battery_%s"; 2384 int ret = 0; 2385 2386 /* Set initially to unknown before receiving first input report */ 2387 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN; 2388 2389 /* Configure the battery's description */ 2390 ctlr->battery_desc.properties = joycon_battery_props; 2391 ctlr->battery_desc.num_properties = 2392 ARRAY_SIZE(joycon_battery_props); 2393 ctlr->battery_desc.get_property = joycon_battery_get_property; 2394 ctlr->battery_desc.type = POWER_SUPPLY_TYPE_BATTERY; 2395 ctlr->battery_desc.use_for_apm = 0; 2396 ctlr->battery_desc.name = devm_kasprintf(&hdev->dev, GFP_KERNEL, 2397 name_fmt, 2398 dev_name(&hdev->dev)); 2399 if (!ctlr->battery_desc.name) 2400 return -ENOMEM; 2401 2402 ctlr->battery = devm_power_supply_register(&hdev->dev, 2403 &ctlr->battery_desc, 2404 &supply_config); 2405 if (IS_ERR(ctlr->battery)) { 2406 ret = PTR_ERR(ctlr->battery); 2407 hid_err(hdev, "Failed to register battery; ret=%d\n", ret); 2408 return ret; 2409 } 2410 2411 return power_supply_powers(ctlr->battery, &hdev->dev); 2412 } 2413 2414 static int joycon_read_info(struct joycon_ctlr *ctlr) 2415 { 2416 int ret; 2417 int i; 2418 int j; 2419 struct joycon_subcmd_request req = { 0 }; 2420 struct joycon_input_report *report; 2421 2422 req.subcmd_id = JC_SUBCMD_REQ_DEV_INFO; 2423 ret = joycon_send_subcmd(ctlr, &req, 0, HZ); 2424 if (ret) { 2425 hid_err(ctlr->hdev, "Failed to get joycon info; ret=%d\n", ret); 2426 return ret; 2427 } 2428 2429 report = (struct joycon_input_report *)ctlr->input_buf; 2430 2431 for (i = 4, j = 0; j < 6; i++, j++) 2432 ctlr->mac_addr[j] = report->subcmd_reply.data[i]; 2433 2434 ctlr->mac_addr_str = devm_kasprintf(&ctlr->hdev->dev, GFP_KERNEL, 2435 "%02X:%02X:%02X:%02X:%02X:%02X", 2436 ctlr->mac_addr[0], 2437 ctlr->mac_addr[1], 2438 ctlr->mac_addr[2], 2439 ctlr->mac_addr[3], 2440 ctlr->mac_addr[4], 2441 ctlr->mac_addr[5]); 2442 if (!ctlr->mac_addr_str) 2443 return -ENOMEM; 2444 hid_info(ctlr->hdev, "controller MAC = %s\n", ctlr->mac_addr_str); 2445 2446 /* 2447 * Retrieve the type so we can distinguish the controller type 2448 * Unfortantly the hdev->product can't always be used due to a ?bug? 2449 * with the NSO Genesis controller. Over USB, it will report the 2450 * PID as 0x201E, but over bluetooth it will report the PID as 0x2017 2451 * which is the same as the NSO SNES controller. This is different from 2452 * the rest of the controllers which will report the same PID over USB 2453 * and bluetooth. 2454 */ 2455 ctlr->ctlr_type = report->subcmd_reply.data[2]; 2456 hid_dbg(ctlr->hdev, "controller type = 0x%02X\n", ctlr->ctlr_type); 2457 2458 return 0; 2459 } 2460 2461 static int joycon_init(struct hid_device *hdev) 2462 { 2463 struct joycon_ctlr *ctlr = hid_get_drvdata(hdev); 2464 int ret = 0; 2465 2466 mutex_lock(&ctlr->output_mutex); 2467 /* if handshake command fails, assume ble pro controller */ 2468 if (joycon_using_usb(ctlr) && !joycon_send_usb(ctlr, JC_USB_CMD_HANDSHAKE, HZ)) { 2469 hid_dbg(hdev, "detected USB controller\n"); 2470 /* set baudrate for improved latency */ 2471 ret = joycon_send_usb(ctlr, JC_USB_CMD_BAUDRATE_3M, HZ); 2472 if (ret) { 2473 /* 2474 * We can function with the default baudrate. 2475 * Provide a warning, and continue on. 2476 */ 2477 hid_warn(hdev, "Failed to set baudrate (ret=%d), continuing anyway\n", ret); 2478 } 2479 /* handshake */ 2480 ret = joycon_send_usb(ctlr, JC_USB_CMD_HANDSHAKE, HZ); 2481 if (ret) { 2482 hid_err(hdev, "Failed handshake; ret=%d\n", ret); 2483 goto out_unlock; 2484 } 2485 /* 2486 * Set no timeout (to keep controller in USB mode). 2487 * This doesn't send a response, so ignore the timeout. 2488 */ 2489 joycon_send_usb(ctlr, JC_USB_CMD_NO_TIMEOUT, HZ/10); 2490 } else if (jc_type_is_chrggrip(ctlr)) { 2491 hid_err(hdev, "Failed charging grip handshake\n"); 2492 ret = -ETIMEDOUT; 2493 goto out_unlock; 2494 } 2495 2496 /* needed to retrieve the controller type */ 2497 ret = joycon_read_info(ctlr); 2498 if (ret) { 2499 hid_err(hdev, "Failed to retrieve controller info; ret=%d\n", 2500 ret); 2501 goto out_unlock; 2502 } 2503 2504 if (joycon_has_joysticks(ctlr)) { 2505 /* get controller calibration data, and parse it */ 2506 ret = joycon_request_calibration(ctlr); 2507 if (ret) { 2508 /* 2509 * We can function with default calibration, but it may be 2510 * inaccurate. Provide a warning, and continue on. 2511 */ 2512 hid_warn(hdev, "Analog stick positions may be inaccurate\n"); 2513 } 2514 } 2515 2516 if (joycon_has_imu(ctlr)) { 2517 /* get IMU calibration data, and parse it */ 2518 ret = joycon_request_imu_calibration(ctlr); 2519 if (ret) { 2520 /* 2521 * We can function with default calibration, but it may be 2522 * inaccurate. Provide a warning, and continue on. 2523 */ 2524 hid_warn(hdev, "Unable to read IMU calibration data\n"); 2525 } 2526 2527 /* Enable the IMU */ 2528 ret = joycon_enable_imu(ctlr); 2529 if (ret) { 2530 hid_err(hdev, "Failed to enable the IMU; ret=%d\n", ret); 2531 goto out_unlock; 2532 } 2533 } 2534 2535 /* Set the reporting mode to 0x30, which is the full report mode */ 2536 ret = joycon_set_report_mode(ctlr); 2537 if (ret) { 2538 hid_err(hdev, "Failed to set report mode; ret=%d\n", ret); 2539 goto out_unlock; 2540 } 2541 2542 if (joycon_has_rumble(ctlr)) { 2543 /* Enable rumble */ 2544 ret = joycon_enable_rumble(ctlr); 2545 if (ret) { 2546 hid_err(hdev, "Failed to enable rumble; ret=%d\n", ret); 2547 goto out_unlock; 2548 } 2549 } 2550 2551 out_unlock: 2552 mutex_unlock(&ctlr->output_mutex); 2553 return ret; 2554 } 2555 2556 /* Common handler for parsing inputs */ 2557 static int joycon_ctlr_read_handler(struct joycon_ctlr *ctlr, u8 *data, 2558 int size) 2559 { 2560 if (data[0] == JC_INPUT_SUBCMD_REPLY || data[0] == JC_INPUT_IMU_DATA || 2561 data[0] == JC_INPUT_MCU_DATA) { 2562 if (size >= 12) /* make sure it contains the input report */ 2563 joycon_parse_report(ctlr, 2564 (struct joycon_input_report *)data); 2565 } 2566 2567 return 0; 2568 } 2569 2570 static int joycon_ctlr_handle_event(struct joycon_ctlr *ctlr, u8 *data, 2571 int size) 2572 { 2573 int ret = 0; 2574 bool match = false; 2575 struct joycon_input_report *report; 2576 2577 if (unlikely(mutex_is_locked(&ctlr->output_mutex)) && 2578 ctlr->msg_type != JOYCON_MSG_TYPE_NONE) { 2579 switch (ctlr->msg_type) { 2580 case JOYCON_MSG_TYPE_USB: 2581 if (size < 2) 2582 break; 2583 if (data[0] == JC_INPUT_USB_RESPONSE && 2584 data[1] == ctlr->usb_ack_match) 2585 match = true; 2586 break; 2587 case JOYCON_MSG_TYPE_SUBCMD: 2588 if (size < sizeof(struct joycon_input_report) || 2589 data[0] != JC_INPUT_SUBCMD_REPLY) 2590 break; 2591 report = (struct joycon_input_report *)data; 2592 if (report->subcmd_reply.id == ctlr->subcmd_ack_match) 2593 match = true; 2594 break; 2595 default: 2596 break; 2597 } 2598 2599 if (match) { 2600 memcpy(ctlr->input_buf, data, 2601 min(size, (int)JC_MAX_RESP_SIZE)); 2602 ctlr->msg_type = JOYCON_MSG_TYPE_NONE; 2603 ctlr->received_resp = true; 2604 wake_up(&ctlr->wait); 2605 2606 /* This message has been handled */ 2607 return 1; 2608 } 2609 } 2610 2611 if (ctlr->ctlr_state == JOYCON_CTLR_STATE_READ) 2612 ret = joycon_ctlr_read_handler(ctlr, data, size); 2613 2614 return ret; 2615 } 2616 2617 static int nintendo_hid_event(struct hid_device *hdev, 2618 struct hid_report *report, u8 *raw_data, int size) 2619 { 2620 struct joycon_ctlr *ctlr = hid_get_drvdata(hdev); 2621 2622 if (size < 1) 2623 return -EINVAL; 2624 2625 return joycon_ctlr_handle_event(ctlr, raw_data, size); 2626 } 2627 2628 static int nintendo_hid_probe(struct hid_device *hdev, 2629 const struct hid_device_id *id) 2630 { 2631 int ret; 2632 struct joycon_ctlr *ctlr; 2633 2634 hid_dbg(hdev, "probe - start\n"); 2635 2636 ctlr = devm_kzalloc(&hdev->dev, sizeof(*ctlr), GFP_KERNEL); 2637 if (!ctlr) { 2638 ret = -ENOMEM; 2639 goto err; 2640 } 2641 2642 ctlr->hdev = hdev; 2643 ctlr->ctlr_state = JOYCON_CTLR_STATE_INIT; 2644 ctlr->rumble_queue_head = 0; 2645 ctlr->rumble_queue_tail = 0; 2646 hid_set_drvdata(hdev, ctlr); 2647 mutex_init(&ctlr->output_mutex); 2648 init_waitqueue_head(&ctlr->wait); 2649 spin_lock_init(&ctlr->lock); 2650 ctlr->rumble_queue = alloc_workqueue("hid-nintendo-rumble_wq", 2651 WQ_FREEZABLE | WQ_MEM_RECLAIM, 0); 2652 if (!ctlr->rumble_queue) { 2653 ret = -ENOMEM; 2654 goto err; 2655 } 2656 INIT_WORK(&ctlr->rumble_worker, joycon_rumble_worker); 2657 2658 ret = hid_parse(hdev); 2659 if (ret) { 2660 hid_err(hdev, "HID parse failed\n"); 2661 goto err_wq; 2662 } 2663 2664 /* 2665 * Patch the hw version of pro controller/joycons, so applications can 2666 * distinguish between the default HID mappings and the mappings defined 2667 * by the Linux game controller spec. This is important for the SDL2 2668 * library, which has a game controller database, which uses device ids 2669 * in combination with version as a key. 2670 */ 2671 hdev->version |= 0x8000; 2672 2673 ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW); 2674 if (ret) { 2675 hid_err(hdev, "HW start failed\n"); 2676 goto err_wq; 2677 } 2678 2679 ret = hid_hw_open(hdev); 2680 if (ret) { 2681 hid_err(hdev, "cannot start hardware I/O\n"); 2682 goto err_stop; 2683 } 2684 2685 hid_device_io_start(hdev); 2686 2687 ret = joycon_init(hdev); 2688 if (ret) { 2689 hid_err(hdev, "Failed to initialize controller; ret=%d\n", ret); 2690 goto err_close; 2691 } 2692 2693 /* Initialize the leds */ 2694 ret = joycon_leds_create(ctlr); 2695 if (ret) { 2696 hid_err(hdev, "Failed to create leds; ret=%d\n", ret); 2697 goto err_close; 2698 } 2699 2700 /* Initialize the battery power supply */ 2701 ret = joycon_power_supply_create(ctlr); 2702 if (ret) { 2703 hid_err(hdev, "Failed to create power_supply; ret=%d\n", ret); 2704 goto err_ida; 2705 } 2706 2707 ret = joycon_input_create(ctlr); 2708 if (ret) { 2709 hid_err(hdev, "Failed to create input device; ret=%d\n", ret); 2710 goto err_ida; 2711 } 2712 2713 ctlr->ctlr_state = JOYCON_CTLR_STATE_READ; 2714 2715 hid_dbg(hdev, "probe - success\n"); 2716 return 0; 2717 2718 err_ida: 2719 ida_free(&nintendo_player_id_allocator, ctlr->player_id); 2720 err_close: 2721 hid_hw_close(hdev); 2722 err_stop: 2723 hid_hw_stop(hdev); 2724 err_wq: 2725 destroy_workqueue(ctlr->rumble_queue); 2726 err: 2727 hid_err(hdev, "probe - fail = %d\n", ret); 2728 return ret; 2729 } 2730 2731 static void nintendo_hid_remove(struct hid_device *hdev) 2732 { 2733 struct joycon_ctlr *ctlr = hid_get_drvdata(hdev); 2734 unsigned long flags; 2735 2736 hid_dbg(hdev, "remove\n"); 2737 2738 /* Prevent further attempts at sending subcommands. */ 2739 spin_lock_irqsave(&ctlr->lock, flags); 2740 ctlr->ctlr_state = JOYCON_CTLR_STATE_REMOVED; 2741 spin_unlock_irqrestore(&ctlr->lock, flags); 2742 2743 destroy_workqueue(ctlr->rumble_queue); 2744 ida_free(&nintendo_player_id_allocator, ctlr->player_id); 2745 2746 hid_hw_close(hdev); 2747 hid_hw_stop(hdev); 2748 } 2749 2750 #ifdef CONFIG_PM 2751 2752 static int nintendo_hid_resume(struct hid_device *hdev) 2753 { 2754 struct joycon_ctlr *ctlr = hid_get_drvdata(hdev); 2755 int ret; 2756 2757 hid_dbg(hdev, "resume\n"); 2758 if (!joycon_using_usb(ctlr)) { 2759 hid_dbg(hdev, "no-op resume for bt ctlr\n"); 2760 ctlr->ctlr_state = JOYCON_CTLR_STATE_READ; 2761 return 0; 2762 } 2763 2764 ret = joycon_init(hdev); 2765 if (ret) 2766 hid_err(hdev, 2767 "Failed to restore controller after resume: %d\n", 2768 ret); 2769 else 2770 ctlr->ctlr_state = JOYCON_CTLR_STATE_READ; 2771 2772 return ret; 2773 } 2774 2775 static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) 2776 { 2777 struct joycon_ctlr *ctlr = hid_get_drvdata(hdev); 2778 2779 hid_dbg(hdev, "suspend: %d\n", message.event); 2780 /* 2781 * Avoid any blocking loops in suspend/resume transitions. 2782 * 2783 * joycon_enforce_subcmd_rate() can result in repeated retries if for 2784 * whatever reason the controller stops providing input reports. 2785 * 2786 * This has been observed with bluetooth controllers which lose 2787 * connectivity prior to suspend (but not long enough to result in 2788 * complete disconnection). 2789 */ 2790 ctlr->ctlr_state = JOYCON_CTLR_STATE_SUSPENDED; 2791 return 0; 2792 } 2793 2794 #endif 2795 2796 static const struct hid_device_id nintendo_hid_devices[] = { 2797 { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO, 2798 USB_DEVICE_ID_NINTENDO_PROCON) }, 2799 { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO, 2800 USB_DEVICE_ID_NINTENDO_SNESCON) }, 2801 { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO, 2802 USB_DEVICE_ID_NINTENDO_GENCON) }, 2803 { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO, 2804 USB_DEVICE_ID_NINTENDO_N64CON) }, 2805 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO, 2806 USB_DEVICE_ID_NINTENDO_PROCON) }, 2807 { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO, 2808 USB_DEVICE_ID_NINTENDO_CHRGGRIP) }, 2809 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO, 2810 USB_DEVICE_ID_NINTENDO_JOYCONL) }, 2811 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO, 2812 USB_DEVICE_ID_NINTENDO_JOYCONR) }, 2813 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO, 2814 USB_DEVICE_ID_NINTENDO_SNESCON) }, 2815 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO, 2816 USB_DEVICE_ID_NINTENDO_GENCON) }, 2817 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO, 2818 USB_DEVICE_ID_NINTENDO_N64CON) }, 2819 { } 2820 }; 2821 MODULE_DEVICE_TABLE(hid, nintendo_hid_devices); 2822 2823 static struct hid_driver nintendo_hid_driver = { 2824 .name = "nintendo", 2825 .id_table = nintendo_hid_devices, 2826 .probe = nintendo_hid_probe, 2827 .remove = nintendo_hid_remove, 2828 .raw_event = nintendo_hid_event, 2829 2830 #ifdef CONFIG_PM 2831 .resume = nintendo_hid_resume, 2832 .suspend = nintendo_hid_suspend, 2833 #endif 2834 }; 2835 static int __init nintendo_init(void) 2836 { 2837 return hid_register_driver(&nintendo_hid_driver); 2838 } 2839 2840 static void __exit nintendo_exit(void) 2841 { 2842 hid_unregister_driver(&nintendo_hid_driver); 2843 ida_destroy(&nintendo_player_id_allocator); 2844 } 2845 2846 module_init(nintendo_init); 2847 module_exit(nintendo_exit); 2848 2849 MODULE_LICENSE("GPL"); 2850 MODULE_AUTHOR("Ryan McClelland <rymcclel@gmail.com>"); 2851 MODULE_AUTHOR("Emily Strickland <linux@emily.st>"); 2852 MODULE_AUTHOR("Daniel J. Ogorchock <djogorchock@gmail.com>"); 2853 MODULE_DESCRIPTION("Driver for Nintendo Switch Controllers"); 2854