HID: nintendo: improve rumble performance and stability
[linux-block.git] / drivers / hid / hid-nintendo.c
CommitLineData
2af16c1f
DO
1// SPDX-License-Identifier: GPL-2.0+
2/*
3 * HID driver for Nintendo Switch Joy-Cons and Pro Controllers
4 *
4ff5b108 5 * Copyright (c) 2019-2020 Daniel J. Ogorchock <djogorchock@gmail.com>
2af16c1f
DO
6 *
7 * The following resources/projects were referenced for this driver:
8 * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering
9 * https://gitlab.com/pjranki/joycon-linux-kernel (Peter Rankin)
10 * https://github.com/FrotBot/SwitchProConLinuxUSB
11 * https://github.com/MTCKC/ProconXInput
c4eae84f 12 * https://github.com/Davidobot/BetterJoyForCemu
2af16c1f
DO
13 * hid-wiimote kernel hid driver
14 * hid-logitech-hidpp driver
08ebba5c 15 * hid-sony driver
2af16c1f
DO
16 *
17 * This driver supports the Nintendo Switch Joy-Cons and Pro Controllers. The
18 * Pro Controllers can either be used over USB or Bluetooth.
19 *
20 * The driver will retrieve the factory calibration info from the controllers,
21 * so little to no user calibration should be required.
22 *
23 */
24
25#include "hid-ids.h"
83d640c4 26#include <asm/unaligned.h>
2af16c1f
DO
27#include <linux/delay.h>
28#include <linux/device.h>
4ff5b108 29#include <linux/kernel.h>
2af16c1f
DO
30#include <linux/hid.h>
31#include <linux/input.h>
c4eae84f 32#include <linux/jiffies.h>
c5e62676 33#include <linux/leds.h>
2af16c1f 34#include <linux/module.h>
08ebba5c 35#include <linux/power_supply.h>
2af16c1f
DO
36#include <linux/spinlock.h>
37
38/*
39 * Reference the url below for the following HID report defines:
40 * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering
41 */
42
43/* Output Reports */
44static const u8 JC_OUTPUT_RUMBLE_AND_SUBCMD = 0x01;
45static const u8 JC_OUTPUT_FW_UPDATE_PKT = 0x03;
46static const u8 JC_OUTPUT_RUMBLE_ONLY = 0x10;
47static const u8 JC_OUTPUT_MCU_DATA = 0x11;
48static const u8 JC_OUTPUT_USB_CMD = 0x80;
49
50/* Subcommand IDs */
51static const u8 JC_SUBCMD_STATE /*= 0x00*/;
52static const u8 JC_SUBCMD_MANUAL_BT_PAIRING = 0x01;
53static const u8 JC_SUBCMD_REQ_DEV_INFO = 0x02;
54static const u8 JC_SUBCMD_SET_REPORT_MODE = 0x03;
55static const u8 JC_SUBCMD_TRIGGERS_ELAPSED = 0x04;
56static const u8 JC_SUBCMD_GET_PAGE_LIST_STATE = 0x05;
57static const u8 JC_SUBCMD_SET_HCI_STATE = 0x06;
58static const u8 JC_SUBCMD_RESET_PAIRING_INFO = 0x07;
59static const u8 JC_SUBCMD_LOW_POWER_MODE = 0x08;
60static const u8 JC_SUBCMD_SPI_FLASH_READ = 0x10;
61static const u8 JC_SUBCMD_SPI_FLASH_WRITE = 0x11;
62static const u8 JC_SUBCMD_RESET_MCU = 0x20;
63static const u8 JC_SUBCMD_SET_MCU_CONFIG = 0x21;
64static const u8 JC_SUBCMD_SET_MCU_STATE = 0x22;
65static const u8 JC_SUBCMD_SET_PLAYER_LIGHTS = 0x30;
66static const u8 JC_SUBCMD_GET_PLAYER_LIGHTS = 0x31;
67static const u8 JC_SUBCMD_SET_HOME_LIGHT = 0x38;
68static const u8 JC_SUBCMD_ENABLE_IMU = 0x40;
69static const u8 JC_SUBCMD_SET_IMU_SENSITIVITY = 0x41;
70static const u8 JC_SUBCMD_WRITE_IMU_REG = 0x42;
71static const u8 JC_SUBCMD_READ_IMU_REG = 0x43;
72static const u8 JC_SUBCMD_ENABLE_VIBRATION = 0x48;
73static const u8 JC_SUBCMD_GET_REGULATED_VOLTAGE = 0x50;
74
75/* Input Reports */
76static const u8 JC_INPUT_BUTTON_EVENT = 0x3F;
77static const u8 JC_INPUT_SUBCMD_REPLY = 0x21;
78static const u8 JC_INPUT_IMU_DATA = 0x30;
79static const u8 JC_INPUT_MCU_DATA = 0x31;
80static const u8 JC_INPUT_USB_RESPONSE = 0x81;
81
82/* Feature Reports */
83static const u8 JC_FEATURE_LAST_SUBCMD = 0x02;
84static const u8 JC_FEATURE_OTA_FW_UPGRADE = 0x70;
85static const u8 JC_FEATURE_SETUP_MEM_READ = 0x71;
86static const u8 JC_FEATURE_MEM_READ = 0x72;
87static const u8 JC_FEATURE_ERASE_MEM_SECTOR = 0x73;
88static const u8 JC_FEATURE_MEM_WRITE = 0x74;
89static const u8 JC_FEATURE_LAUNCH = 0x75;
90
91/* USB Commands */
92static const u8 JC_USB_CMD_CONN_STATUS = 0x01;
93static const u8 JC_USB_CMD_HANDSHAKE = 0x02;
94static const u8 JC_USB_CMD_BAUDRATE_3M = 0x03;
95static const u8 JC_USB_CMD_NO_TIMEOUT = 0x04;
96static const u8 JC_USB_CMD_EN_TIMEOUT = 0x05;
97static const u8 JC_USB_RESET = 0x06;
98static const u8 JC_USB_PRE_HANDSHAKE = 0x91;
99static const u8 JC_USB_SEND_UART = 0x92;
100
83d640c4
DO
101/* Magic value denoting presence of user calibration */
102static const u16 JC_CAL_USR_MAGIC_0 = 0xB2;
103static const u16 JC_CAL_USR_MAGIC_1 = 0xA1;
104static const u8 JC_CAL_USR_MAGIC_SIZE = 2;
105
106/* SPI storage addresses of user calibration data */
107static const u16 JC_CAL_USR_LEFT_MAGIC_ADDR = 0x8010;
108static const u16 JC_CAL_USR_LEFT_DATA_ADDR = 0x8012;
109static const u16 JC_CAL_USR_LEFT_DATA_END = 0x801A;
110static const u16 JC_CAL_USR_RIGHT_MAGIC_ADDR = 0x801B;
111static const u16 JC_CAL_USR_RIGHT_DATA_ADDR = 0x801D;
112#define JC_CAL_STICK_DATA_SIZE \
113 (JC_CAL_USR_LEFT_DATA_END - JC_CAL_USR_LEFT_DATA_ADDR + 1)
2af16c1f 114
83d640c4
DO
115/* SPI storage addresses of factory calibration data */
116static const u16 JC_CAL_FCT_DATA_LEFT_ADDR = 0x603d;
117static const u16 JC_CAL_FCT_DATA_RIGHT_ADDR = 0x6046;
2af16c1f 118
4ff5b108
DO
119/* SPI storage addresses of IMU factory calibration data */
120static const u16 JC_IMU_CAL_FCT_DATA_ADDR = 0x6020;
121static const u16 JC_IMU_CAL_FCT_DATA_END = 0x6037;
122#define JC_IMU_CAL_DATA_SIZE \
123 (JC_IMU_CAL_FCT_DATA_END - JC_IMU_CAL_FCT_DATA_ADDR + 1)
124/* SPI storage addresses of IMU user calibration data */
125static const u16 JC_IMU_CAL_USR_MAGIC_ADDR = 0x8026;
126static const u16 JC_IMU_CAL_USR_DATA_ADDR = 0x8028;
127
2af16c1f
DO
128/* The raw analog joystick values will be mapped in terms of this magnitude */
129static const u16 JC_MAX_STICK_MAG = 32767;
130static const u16 JC_STICK_FUZZ = 250;
131static const u16 JC_STICK_FLAT = 500;
132
133/* Hat values for pro controller's d-pad */
134static const u16 JC_MAX_DPAD_MAG = 1;
135static const u16 JC_DPAD_FUZZ /*= 0*/;
136static const u16 JC_DPAD_FLAT /*= 0*/;
137
4ff5b108
DO
138/* Under most circumstances IMU reports are pushed every 15ms; use as default */
139static const u16 JC_IMU_DFLT_AVG_DELTA_MS = 15;
140/* How many samples to sum before calculating average IMU report delta */
141static const u16 JC_IMU_SAMPLES_PER_DELTA_AVG = 300;
142/* Controls how many dropped IMU packets at once trigger a warning message */
143static const u16 JC_IMU_DROPPED_PKT_WARNING = 3;
144
145/*
146 * The controller's accelerometer has a sensor resolution of 16bits and is
147 * configured with a range of +-8000 milliGs. Therefore, the resolution can be
148 * calculated thus: (2^16-1)/(8000 * 2) = 4.096 digits per milliG
149 * Resolution per G (rather than per millliG): 4.096 * 1000 = 4096 digits per G
150 * Alternatively: 1/4096 = .0002441 Gs per digit
151 */
152static const s32 JC_IMU_MAX_ACCEL_MAG = 32767;
153static const u16 JC_IMU_ACCEL_RES_PER_G = 4096;
154static const u16 JC_IMU_ACCEL_FUZZ = 10;
155static const u16 JC_IMU_ACCEL_FLAT /*= 0*/;
156
157/*
158 * The controller's gyroscope has a sensor resolution of 16bits and is
159 * configured with a range of +-2000 degrees/second.
160 * Digits per dps: (2^16 -1)/(2000*2) = 16.38375
161 * dps per digit: 16.38375E-1 = .0610
162 *
163 * STMicro recommends in the datasheet to add 15% to the dps/digit. This allows
164 * the full sensitivity range to be saturated without clipping. This yields more
165 * accurate results, so it's the technique this driver uses.
166 * dps per digit (corrected): .0610 * 1.15 = .0702
167 * digits per dps (corrected): .0702E-1 = 14.247
168 *
169 * Now, 14.247 truncating to 14 loses a lot of precision, so we rescale the
170 * min/max range by 1000.
171 */
172static const s32 JC_IMU_PREC_RANGE_SCALE = 1000;
173/* Note: change mag and res_per_dps if prec_range_scale is ever altered */
174static const s32 JC_IMU_MAX_GYRO_MAG = 32767000; /* (2^16-1)*1000 */
175static const u16 JC_IMU_GYRO_RES_PER_DPS = 14247; /* (14.247*1000) */
176static const u16 JC_IMU_GYRO_FUZZ = 10;
177static const u16 JC_IMU_GYRO_FLAT /*= 0*/;
178
c4eae84f
DO
179/* frequency/amplitude tables for rumble */
180struct joycon_rumble_freq_data {
181 u16 high;
182 u8 low;
183 u16 freq; /* Hz*/
184};
185
186struct joycon_rumble_amp_data {
187 u8 high;
188 u16 low;
189 u16 amp;
190};
191
192/*
193 * These tables are from
194 * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/rumble_data_table.md
195 */
196static const struct joycon_rumble_freq_data joycon_rumble_frequencies[] = {
197 /* high, low, freq */
198 { 0x0000, 0x01, 41 }, { 0x0000, 0x02, 42 }, { 0x0000, 0x03, 43 },
199 { 0x0000, 0x04, 44 }, { 0x0000, 0x05, 45 }, { 0x0000, 0x06, 46 },
200 { 0x0000, 0x07, 47 }, { 0x0000, 0x08, 48 }, { 0x0000, 0x09, 49 },
201 { 0x0000, 0x0A, 50 }, { 0x0000, 0x0B, 51 }, { 0x0000, 0x0C, 52 },
202 { 0x0000, 0x0D, 53 }, { 0x0000, 0x0E, 54 }, { 0x0000, 0x0F, 55 },
203 { 0x0000, 0x10, 57 }, { 0x0000, 0x11, 58 }, { 0x0000, 0x12, 59 },
204 { 0x0000, 0x13, 60 }, { 0x0000, 0x14, 62 }, { 0x0000, 0x15, 63 },
205 { 0x0000, 0x16, 64 }, { 0x0000, 0x17, 66 }, { 0x0000, 0x18, 67 },
206 { 0x0000, 0x19, 69 }, { 0x0000, 0x1A, 70 }, { 0x0000, 0x1B, 72 },
207 { 0x0000, 0x1C, 73 }, { 0x0000, 0x1D, 75 }, { 0x0000, 0x1e, 77 },
208 { 0x0000, 0x1f, 78 }, { 0x0000, 0x20, 80 }, { 0x0400, 0x21, 82 },
209 { 0x0800, 0x22, 84 }, { 0x0c00, 0x23, 85 }, { 0x1000, 0x24, 87 },
210 { 0x1400, 0x25, 89 }, { 0x1800, 0x26, 91 }, { 0x1c00, 0x27, 93 },
211 { 0x2000, 0x28, 95 }, { 0x2400, 0x29, 97 }, { 0x2800, 0x2a, 99 },
212 { 0x2c00, 0x2b, 102 }, { 0x3000, 0x2c, 104 }, { 0x3400, 0x2d, 106 },
213 { 0x3800, 0x2e, 108 }, { 0x3c00, 0x2f, 111 }, { 0x4000, 0x30, 113 },
214 { 0x4400, 0x31, 116 }, { 0x4800, 0x32, 118 }, { 0x4c00, 0x33, 121 },
215 { 0x5000, 0x34, 123 }, { 0x5400, 0x35, 126 }, { 0x5800, 0x36, 129 },
216 { 0x5c00, 0x37, 132 }, { 0x6000, 0x38, 135 }, { 0x6400, 0x39, 137 },
217 { 0x6800, 0x3a, 141 }, { 0x6c00, 0x3b, 144 }, { 0x7000, 0x3c, 147 },
218 { 0x7400, 0x3d, 150 }, { 0x7800, 0x3e, 153 }, { 0x7c00, 0x3f, 157 },
219 { 0x8000, 0x40, 160 }, { 0x8400, 0x41, 164 }, { 0x8800, 0x42, 167 },
220 { 0x8c00, 0x43, 171 }, { 0x9000, 0x44, 174 }, { 0x9400, 0x45, 178 },
221 { 0x9800, 0x46, 182 }, { 0x9c00, 0x47, 186 }, { 0xa000, 0x48, 190 },
222 { 0xa400, 0x49, 194 }, { 0xa800, 0x4a, 199 }, { 0xac00, 0x4b, 203 },
223 { 0xb000, 0x4c, 207 }, { 0xb400, 0x4d, 212 }, { 0xb800, 0x4e, 217 },
224 { 0xbc00, 0x4f, 221 }, { 0xc000, 0x50, 226 }, { 0xc400, 0x51, 231 },
225 { 0xc800, 0x52, 236 }, { 0xcc00, 0x53, 241 }, { 0xd000, 0x54, 247 },
226 { 0xd400, 0x55, 252 }, { 0xd800, 0x56, 258 }, { 0xdc00, 0x57, 263 },
227 { 0xe000, 0x58, 269 }, { 0xe400, 0x59, 275 }, { 0xe800, 0x5a, 281 },
228 { 0xec00, 0x5b, 287 }, { 0xf000, 0x5c, 293 }, { 0xf400, 0x5d, 300 },
229 { 0xf800, 0x5e, 306 }, { 0xfc00, 0x5f, 313 }, { 0x0001, 0x60, 320 },
230 { 0x0401, 0x61, 327 }, { 0x0801, 0x62, 334 }, { 0x0c01, 0x63, 341 },
231 { 0x1001, 0x64, 349 }, { 0x1401, 0x65, 357 }, { 0x1801, 0x66, 364 },
232 { 0x1c01, 0x67, 372 }, { 0x2001, 0x68, 381 }, { 0x2401, 0x69, 389 },
233 { 0x2801, 0x6a, 397 }, { 0x2c01, 0x6b, 406 }, { 0x3001, 0x6c, 415 },
234 { 0x3401, 0x6d, 424 }, { 0x3801, 0x6e, 433 }, { 0x3c01, 0x6f, 443 },
235 { 0x4001, 0x70, 453 }, { 0x4401, 0x71, 462 }, { 0x4801, 0x72, 473 },
236 { 0x4c01, 0x73, 483 }, { 0x5001, 0x74, 494 }, { 0x5401, 0x75, 504 },
237 { 0x5801, 0x76, 515 }, { 0x5c01, 0x77, 527 }, { 0x6001, 0x78, 538 },
238 { 0x6401, 0x79, 550 }, { 0x6801, 0x7a, 562 }, { 0x6c01, 0x7b, 574 },
239 { 0x7001, 0x7c, 587 }, { 0x7401, 0x7d, 600 }, { 0x7801, 0x7e, 613 },
240 { 0x7c01, 0x7f, 626 }, { 0x8001, 0x00, 640 }, { 0x8401, 0x00, 654 },
241 { 0x8801, 0x00, 668 }, { 0x8c01, 0x00, 683 }, { 0x9001, 0x00, 698 },
242 { 0x9401, 0x00, 713 }, { 0x9801, 0x00, 729 }, { 0x9c01, 0x00, 745 },
243 { 0xa001, 0x00, 761 }, { 0xa401, 0x00, 778 }, { 0xa801, 0x00, 795 },
244 { 0xac01, 0x00, 812 }, { 0xb001, 0x00, 830 }, { 0xb401, 0x00, 848 },
245 { 0xb801, 0x00, 867 }, { 0xbc01, 0x00, 886 }, { 0xc001, 0x00, 905 },
246 { 0xc401, 0x00, 925 }, { 0xc801, 0x00, 945 }, { 0xcc01, 0x00, 966 },
247 { 0xd001, 0x00, 987 }, { 0xd401, 0x00, 1009 }, { 0xd801, 0x00, 1031 },
248 { 0xdc01, 0x00, 1053 }, { 0xe001, 0x00, 1076 }, { 0xe401, 0x00, 1100 },
249 { 0xe801, 0x00, 1124 }, { 0xec01, 0x00, 1149 }, { 0xf001, 0x00, 1174 },
250 { 0xf401, 0x00, 1199 }, { 0xf801, 0x00, 1226 }, { 0xfc01, 0x00, 1253 }
251};
252
253#define joycon_max_rumble_amp (1003)
254static const struct joycon_rumble_amp_data joycon_rumble_amplitudes[] = {
255 /* high, low, amp */
256 { 0x00, 0x0040, 0 },
257 { 0x02, 0x8040, 10 }, { 0x04, 0x0041, 12 }, { 0x06, 0x8041, 14 },
258 { 0x08, 0x0042, 17 }, { 0x0a, 0x8042, 20 }, { 0x0c, 0x0043, 24 },
259 { 0x0e, 0x8043, 28 }, { 0x10, 0x0044, 33 }, { 0x12, 0x8044, 40 },
260 { 0x14, 0x0045, 47 }, { 0x16, 0x8045, 56 }, { 0x18, 0x0046, 67 },
261 { 0x1a, 0x8046, 80 }, { 0x1c, 0x0047, 95 }, { 0x1e, 0x8047, 112 },
262 { 0x20, 0x0048, 117 }, { 0x22, 0x8048, 123 }, { 0x24, 0x0049, 128 },
263 { 0x26, 0x8049, 134 }, { 0x28, 0x004a, 140 }, { 0x2a, 0x804a, 146 },
264 { 0x2c, 0x004b, 152 }, { 0x2e, 0x804b, 159 }, { 0x30, 0x004c, 166 },
265 { 0x32, 0x804c, 173 }, { 0x34, 0x004d, 181 }, { 0x36, 0x804d, 189 },
266 { 0x38, 0x004e, 198 }, { 0x3a, 0x804e, 206 }, { 0x3c, 0x004f, 215 },
267 { 0x3e, 0x804f, 225 }, { 0x40, 0x0050, 230 }, { 0x42, 0x8050, 235 },
268 { 0x44, 0x0051, 240 }, { 0x46, 0x8051, 245 }, { 0x48, 0x0052, 251 },
269 { 0x4a, 0x8052, 256 }, { 0x4c, 0x0053, 262 }, { 0x4e, 0x8053, 268 },
270 { 0x50, 0x0054, 273 }, { 0x52, 0x8054, 279 }, { 0x54, 0x0055, 286 },
271 { 0x56, 0x8055, 292 }, { 0x58, 0x0056, 298 }, { 0x5a, 0x8056, 305 },
272 { 0x5c, 0x0057, 311 }, { 0x5e, 0x8057, 318 }, { 0x60, 0x0058, 325 },
273 { 0x62, 0x8058, 332 }, { 0x64, 0x0059, 340 }, { 0x66, 0x8059, 347 },
274 { 0x68, 0x005a, 355 }, { 0x6a, 0x805a, 362 }, { 0x6c, 0x005b, 370 },
275 { 0x6e, 0x805b, 378 }, { 0x70, 0x005c, 387 }, { 0x72, 0x805c, 395 },
276 { 0x74, 0x005d, 404 }, { 0x76, 0x805d, 413 }, { 0x78, 0x005e, 422 },
277 { 0x7a, 0x805e, 431 }, { 0x7c, 0x005f, 440 }, { 0x7e, 0x805f, 450 },
278 { 0x80, 0x0060, 460 }, { 0x82, 0x8060, 470 }, { 0x84, 0x0061, 480 },
279 { 0x86, 0x8061, 491 }, { 0x88, 0x0062, 501 }, { 0x8a, 0x8062, 512 },
280 { 0x8c, 0x0063, 524 }, { 0x8e, 0x8063, 535 }, { 0x90, 0x0064, 547 },
281 { 0x92, 0x8064, 559 }, { 0x94, 0x0065, 571 }, { 0x96, 0x8065, 584 },
282 { 0x98, 0x0066, 596 }, { 0x9a, 0x8066, 609 }, { 0x9c, 0x0067, 623 },
283 { 0x9e, 0x8067, 636 }, { 0xa0, 0x0068, 650 }, { 0xa2, 0x8068, 665 },
284 { 0xa4, 0x0069, 679 }, { 0xa6, 0x8069, 694 }, { 0xa8, 0x006a, 709 },
285 { 0xaa, 0x806a, 725 }, { 0xac, 0x006b, 741 }, { 0xae, 0x806b, 757 },
286 { 0xb0, 0x006c, 773 }, { 0xb2, 0x806c, 790 }, { 0xb4, 0x006d, 808 },
287 { 0xb6, 0x806d, 825 }, { 0xb8, 0x006e, 843 }, { 0xba, 0x806e, 862 },
288 { 0xbc, 0x006f, 881 }, { 0xbe, 0x806f, 900 }, { 0xc0, 0x0070, 920 },
289 { 0xc2, 0x8070, 940 }, { 0xc4, 0x0071, 960 }, { 0xc6, 0x8071, 981 },
290 { 0xc8, 0x0072, joycon_max_rumble_amp }
291};
292
2af16c1f
DO
293/* States for controller state machine */
294enum joycon_ctlr_state {
295 JOYCON_CTLR_STATE_INIT,
296 JOYCON_CTLR_STATE_READ,
012bd52c 297 JOYCON_CTLR_STATE_REMOVED,
2af16c1f
DO
298};
299
294a8287
DO
300/* Controller type received as part of device info */
301enum joycon_ctlr_type {
302 JOYCON_CTLR_TYPE_JCL = 0x01,
303 JOYCON_CTLR_TYPE_JCR = 0x02,
304 JOYCON_CTLR_TYPE_PRO = 0x03,
305};
306
2af16c1f
DO
307struct joycon_stick_cal {
308 s32 max;
309 s32 min;
310 s32 center;
311};
312
4ff5b108
DO
313struct joycon_imu_cal {
314 s16 offset[3];
315 s16 scale[3];
316};
317
2af16c1f
DO
318/*
319 * All the controller's button values are stored in a u32.
320 * They can be accessed with bitwise ANDs.
321 */
322static const u32 JC_BTN_Y = BIT(0);
323static const u32 JC_BTN_X = BIT(1);
324static const u32 JC_BTN_B = BIT(2);
325static const u32 JC_BTN_A = BIT(3);
326static const u32 JC_BTN_SR_R = BIT(4);
327static const u32 JC_BTN_SL_R = BIT(5);
328static const u32 JC_BTN_R = BIT(6);
329static const u32 JC_BTN_ZR = BIT(7);
330static const u32 JC_BTN_MINUS = BIT(8);
331static const u32 JC_BTN_PLUS = BIT(9);
332static const u32 JC_BTN_RSTICK = BIT(10);
333static const u32 JC_BTN_LSTICK = BIT(11);
334static const u32 JC_BTN_HOME = BIT(12);
335static const u32 JC_BTN_CAP = BIT(13); /* capture button */
336static const u32 JC_BTN_DOWN = BIT(16);
337static const u32 JC_BTN_UP = BIT(17);
338static const u32 JC_BTN_RIGHT = BIT(18);
339static const u32 JC_BTN_LEFT = BIT(19);
340static const u32 JC_BTN_SR_L = BIT(20);
341static const u32 JC_BTN_SL_L = BIT(21);
342static const u32 JC_BTN_L = BIT(22);
343static const u32 JC_BTN_ZL = BIT(23);
344
345enum joycon_msg_type {
346 JOYCON_MSG_TYPE_NONE,
347 JOYCON_MSG_TYPE_USB,
348 JOYCON_MSG_TYPE_SUBCMD,
349};
350
4c048f6b
DO
351struct joycon_rumble_output {
352 u8 output_id;
353 u8 packet_num;
354 u8 rumble_data[8];
355} __packed;
356
2af16c1f
DO
357struct joycon_subcmd_request {
358 u8 output_id; /* must be 0x01 for subcommand, 0x10 for rumble only */
359 u8 packet_num; /* incremented every send */
360 u8 rumble_data[8];
361 u8 subcmd_id;
362 u8 data[]; /* length depends on the subcommand */
363} __packed;
364
365struct joycon_subcmd_reply {
366 u8 ack; /* MSB 1 for ACK, 0 for NACK */
367 u8 id; /* id of requested subcmd */
368 u8 data[]; /* will be at most 35 bytes */
369} __packed;
370
4ff5b108
DO
371struct joycon_imu_data {
372 s16 accel_x;
373 s16 accel_y;
374 s16 accel_z;
375 s16 gyro_x;
376 s16 gyro_y;
377 s16 gyro_z;
378} __packed;
379
2af16c1f
DO
380struct joycon_input_report {
381 u8 id;
382 u8 timer;
383 u8 bat_con; /* battery and connection info */
384 u8 button_status[3];
385 u8 left_stick[3];
386 u8 right_stick[3];
387 u8 vibrator_report;
388
4ff5b108
DO
389 union {
390 struct joycon_subcmd_reply subcmd_reply;
391 /* IMU input reports contain 3 samples */
392 u8 imu_raw_bytes[sizeof(struct joycon_imu_data) * 3];
393 };
2af16c1f
DO
394} __packed;
395
396#define JC_MAX_RESP_SIZE (sizeof(struct joycon_input_report) + 35)
c4eae84f
DO
397#define JC_RUMBLE_DATA_SIZE 8
398#define JC_RUMBLE_QUEUE_SIZE 8
399
400static const u16 JC_RUMBLE_DFLT_LOW_FREQ = 160;
401static const u16 JC_RUMBLE_DFLT_HIGH_FREQ = 320;
402static const u16 JC_RUMBLE_PERIOD_MS = 50;
2af16c1f 403
c5e62676
DO
404static const char * const joycon_player_led_names[] = {
405 LED_FUNCTION_PLAYER1,
406 LED_FUNCTION_PLAYER2,
407 LED_FUNCTION_PLAYER3,
408 LED_FUNCTION_PLAYER4,
409};
410#define JC_NUM_LEDS ARRAY_SIZE(joycon_player_led_names)
411
2af16c1f
DO
412/* Each physical controller is associated with a joycon_ctlr struct */
413struct joycon_ctlr {
414 struct hid_device *hdev;
415 struct input_dev *input;
697e5c7a
DO
416 struct led_classdev leds[JC_NUM_LEDS]; /* player leds */
417 struct led_classdev home_led;
2af16c1f 418 enum joycon_ctlr_state ctlr_state;
08ebba5c 419 spinlock_t lock;
14252473
DO
420 u8 mac_addr[6];
421 char *mac_addr_str;
294a8287 422 enum joycon_ctlr_type ctlr_type;
2af16c1f
DO
423
424 /* The following members are used for synchronous sends/receives */
425 enum joycon_msg_type msg_type;
426 u8 subcmd_num;
427 struct mutex output_mutex;
428 u8 input_buf[JC_MAX_RESP_SIZE];
429 wait_queue_head_t wait;
430 bool received_resp;
431 u8 usb_ack_match;
432 u8 subcmd_ack_match;
479da173 433 bool received_input_report;
2af16c1f
DO
434
435 /* factory calibration data */
436 struct joycon_stick_cal left_stick_cal_x;
437 struct joycon_stick_cal left_stick_cal_y;
438 struct joycon_stick_cal right_stick_cal_x;
439 struct joycon_stick_cal right_stick_cal_y;
440
4ff5b108
DO
441 struct joycon_imu_cal accel_cal;
442 struct joycon_imu_cal gyro_cal;
443
444 /* prevents needlessly recalculating these divisors every sample */
445 s32 imu_cal_accel_divisor[3];
446 s32 imu_cal_gyro_divisor[3];
447
08ebba5c
DO
448 /* power supply data */
449 struct power_supply *battery;
450 struct power_supply_desc battery_desc;
451 u8 battery_capacity;
452 bool battery_charging;
453 bool host_powered;
c4eae84f
DO
454
455 /* rumble */
456 u8 rumble_data[JC_RUMBLE_QUEUE_SIZE][JC_RUMBLE_DATA_SIZE];
457 int rumble_queue_head;
458 int rumble_queue_tail;
459 struct workqueue_struct *rumble_queue;
460 struct work_struct rumble_worker;
461 unsigned int rumble_msecs;
462 u16 rumble_ll_freq;
463 u16 rumble_lh_freq;
464 u16 rumble_rl_freq;
465 u16 rumble_rh_freq;
4ff5b108
DO
466
467 /* imu */
468 struct input_dev *imu_input;
469 bool imu_first_packet_received; /* helps in initiating timestamp */
470 unsigned int imu_timestamp_us; /* timestamp we report to userspace */
471 unsigned int imu_last_pkt_ms; /* used to calc imu report delta */
472 /* the following are used to track the average imu report time delta */
473 unsigned int imu_delta_samples_count;
474 unsigned int imu_delta_samples_sum;
475 unsigned int imu_avg_delta_ms;
2af16c1f
DO
476};
477
294a8287
DO
478/* Helper macros for checking controller type */
479#define jc_type_is_joycon(ctlr) \
480 (ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONL || \
481 ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONR || \
482 ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_CHRGGRIP)
483#define jc_type_is_procon(ctlr) \
484 (ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_PROCON)
485#define jc_type_is_chrggrip(ctlr) \
486 (ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_CHRGGRIP)
487
488/* Does this controller have inputs associated with left joycon? */
489#define jc_type_has_left(ctlr) \
490 (ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCL || \
491 ctlr->ctlr_type == JOYCON_CTLR_TYPE_PRO)
492
493/* Does this controller have inputs associated with right joycon? */
494#define jc_type_has_right(ctlr) \
495 (ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCR || \
496 ctlr->ctlr_type == JOYCON_CTLR_TYPE_PRO)
497
2af16c1f
DO
498static int __joycon_hid_send(struct hid_device *hdev, u8 *data, size_t len)
499{
500 u8 *buf;
501 int ret;
502
503 buf = kmemdup(data, len, GFP_KERNEL);
504 if (!buf)
505 return -ENOMEM;
506 ret = hid_hw_output_report(hdev, buf, len);
507 kfree(buf);
508 if (ret < 0)
509 hid_dbg(hdev, "Failed to send output report ret=%d\n", ret);
510 return ret;
511}
512
6b5dca2d
DO
513static int joycon_hid_send_sync(struct joycon_ctlr *ctlr, u8 *data, size_t len,
514 u32 timeout)
2af16c1f
DO
515{
516 int ret;
6b5dca2d 517 int tries = 2;
2af16c1f 518
6b5dca2d
DO
519 /*
520 * The controller occasionally seems to drop subcommands. In testing,
521 * doing one retry after a timeout appears to always work.
522 */
523 while (tries--) {
479da173
DO
524 /*
525 * If we are in the proper reporting mode, wait for an input
526 * report prior to sending the subcommand. This improves
527 * reliability considerably.
528 */
529 if (ctlr->ctlr_state == JOYCON_CTLR_STATE_READ) {
530 unsigned long flags;
531
532 spin_lock_irqsave(&ctlr->lock, flags);
533 ctlr->received_input_report = false;
534 spin_unlock_irqrestore(&ctlr->lock, flags);
535 ret = wait_event_timeout(ctlr->wait,
536 ctlr->received_input_report,
537 HZ / 4);
538 /* We will still proceed, even with a timeout here */
539 if (!ret)
540 hid_warn(ctlr->hdev,
541 "timeout waiting for input report\n");
542 }
543
6b5dca2d
DO
544 ret = __joycon_hid_send(ctlr->hdev, data, len);
545 if (ret < 0) {
546 memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE);
547 return ret;
548 }
2af16c1f 549
6b5dca2d
DO
550 ret = wait_event_timeout(ctlr->wait, ctlr->received_resp,
551 timeout);
552 if (!ret) {
553 hid_dbg(ctlr->hdev,
554 "synchronous send/receive timed out\n");
555 if (tries) {
556 hid_dbg(ctlr->hdev,
557 "retrying sync send after timeout\n");
558 }
559 memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE);
560 ret = -ETIMEDOUT;
561 } else {
562 ret = 0;
563 break;
564 }
2af16c1f
DO
565 }
566
567 ctlr->received_resp = false;
6b5dca2d 568 return ret;
2af16c1f
DO
569}
570
6b5dca2d 571static int joycon_send_usb(struct joycon_ctlr *ctlr, u8 cmd, u32 timeout)
2af16c1f
DO
572{
573 int ret;
574 u8 buf[2] = {JC_OUTPUT_USB_CMD};
575
576 buf[1] = cmd;
577 ctlr->usb_ack_match = cmd;
578 ctlr->msg_type = JOYCON_MSG_TYPE_USB;
6b5dca2d 579 ret = joycon_hid_send_sync(ctlr, buf, sizeof(buf), timeout);
2af16c1f
DO
580 if (ret)
581 hid_dbg(ctlr->hdev, "send usb command failed; ret=%d\n", ret);
582 return ret;
583}
584
585static int joycon_send_subcmd(struct joycon_ctlr *ctlr,
586 struct joycon_subcmd_request *subcmd,
6b5dca2d 587 size_t data_len, u32 timeout)
2af16c1f
DO
588{
589 int ret;
c4eae84f
DO
590 unsigned long flags;
591
592 spin_lock_irqsave(&ctlr->lock, flags);
012bd52c
DO
593 /*
594 * If the controller has been removed, just return ENODEV so the LED
595 * subsystem doesn't print invalid errors on removal.
596 */
597 if (ctlr->ctlr_state == JOYCON_CTLR_STATE_REMOVED) {
598 spin_unlock_irqrestore(&ctlr->lock, flags);
599 return -ENODEV;
600 }
c4eae84f
DO
601 memcpy(subcmd->rumble_data, ctlr->rumble_data[ctlr->rumble_queue_tail],
602 JC_RUMBLE_DATA_SIZE);
603 spin_unlock_irqrestore(&ctlr->lock, flags);
2af16c1f
DO
604
605 subcmd->output_id = JC_OUTPUT_RUMBLE_AND_SUBCMD;
606 subcmd->packet_num = ctlr->subcmd_num;
607 if (++ctlr->subcmd_num > 0xF)
608 ctlr->subcmd_num = 0;
609 ctlr->subcmd_ack_match = subcmd->subcmd_id;
610 ctlr->msg_type = JOYCON_MSG_TYPE_SUBCMD;
611
612 ret = joycon_hid_send_sync(ctlr, (u8 *)subcmd,
6b5dca2d 613 sizeof(*subcmd) + data_len, timeout);
2af16c1f
DO
614 if (ret < 0)
615 hid_dbg(ctlr->hdev, "send subcommand failed; ret=%d\n", ret);
616 else
617 ret = 0;
618 return ret;
619}
620
621/* Supply nibbles for flash and on. Ones correspond to active */
622static int joycon_set_player_leds(struct joycon_ctlr *ctlr, u8 flash, u8 on)
623{
624 struct joycon_subcmd_request *req;
625 u8 buffer[sizeof(*req) + 1] = { 0 };
626
627 req = (struct joycon_subcmd_request *)buffer;
628 req->subcmd_id = JC_SUBCMD_SET_PLAYER_LIGHTS;
629 req->data[0] = (flash << 4) | on;
630
631 hid_dbg(ctlr->hdev, "setting player leds\n");
6b5dca2d 632 return joycon_send_subcmd(ctlr, req, 1, HZ/4);
2af16c1f
DO
633}
634
83d640c4
DO
635static int joycon_request_spi_flash_read(struct joycon_ctlr *ctlr,
636 u32 start_addr, u8 size, u8 **reply)
2af16c1f
DO
637{
638 struct joycon_subcmd_request *req;
2af16c1f 639 struct joycon_input_report *report;
83d640c4
DO
640 u8 buffer[sizeof(*req) + 5] = { 0 };
641 u8 *data;
642 int ret;
643
644 if (!reply)
645 return -EINVAL;
646
647 req = (struct joycon_subcmd_request *)buffer;
648 req->subcmd_id = JC_SUBCMD_SPI_FLASH_READ;
649 data = req->data;
650 put_unaligned_le32(start_addr, data);
651 data[4] = size;
652
653 hid_dbg(ctlr->hdev, "requesting SPI flash data\n");
654 ret = joycon_send_subcmd(ctlr, req, 5, HZ);
655 if (ret) {
656 hid_err(ctlr->hdev, "failed reading SPI flash; ret=%d\n", ret);
657 } else {
658 report = (struct joycon_input_report *)ctlr->input_buf;
659 /* The read data starts at the 6th byte */
4ff5b108 660 *reply = &report->subcmd_reply.data[5];
83d640c4
DO
661 }
662 return ret;
663}
664
665/*
666 * User calibration's presence is denoted with a magic byte preceding it.
667 * returns 0 if magic val is present, 1 if not present, < 0 on error
668 */
669static int joycon_check_for_cal_magic(struct joycon_ctlr *ctlr, u32 flash_addr)
670{
671 int ret;
672 u8 *reply;
673
674 ret = joycon_request_spi_flash_read(ctlr, flash_addr,
675 JC_CAL_USR_MAGIC_SIZE, &reply);
676 if (ret)
677 return ret;
678
679 return reply[0] != JC_CAL_USR_MAGIC_0 || reply[1] != JC_CAL_USR_MAGIC_1;
680}
681
682static int joycon_read_stick_calibration(struct joycon_ctlr *ctlr, u16 cal_addr,
683 struct joycon_stick_cal *cal_x,
684 struct joycon_stick_cal *cal_y,
685 bool left_stick)
686{
2af16c1f
DO
687 s32 x_max_above;
688 s32 x_min_below;
689 s32 y_max_above;
690 s32 y_min_below;
2af16c1f
DO
691 u8 *raw_cal;
692 int ret;
693
83d640c4
DO
694 ret = joycon_request_spi_flash_read(ctlr, cal_addr,
695 JC_CAL_STICK_DATA_SIZE, &raw_cal);
696 if (ret)
697 return ret;
698
699 /* stick calibration parsing: note the order differs based on stick */
700 if (left_stick) {
701 x_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 0), 0,
702 12);
703 y_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 1), 4,
704 12);
705 cal_x->center = hid_field_extract(ctlr->hdev, (raw_cal + 3), 0,
706 12);
707 cal_y->center = hid_field_extract(ctlr->hdev, (raw_cal + 4), 4,
708 12);
709 x_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 6), 0,
710 12);
711 y_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 7), 4,
712 12);
713 } else {
714 cal_x->center = hid_field_extract(ctlr->hdev, (raw_cal + 0), 0,
715 12);
716 cal_y->center = hid_field_extract(ctlr->hdev, (raw_cal + 1), 4,
717 12);
718 x_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 3), 0,
719 12);
720 y_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 4), 4,
721 12);
722 x_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 6), 0,
723 12);
724 y_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 7), 4,
725 12);
726 }
727
728 cal_x->max = cal_x->center + x_max_above;
729 cal_x->min = cal_x->center - x_min_below;
730 cal_y->max = cal_y->center + y_max_above;
731 cal_y->min = cal_y->center - y_min_below;
732
733 return 0;
734}
735
736static const u16 DFLT_STICK_CAL_CEN = 2000;
737static const u16 DFLT_STICK_CAL_MAX = 3500;
738static const u16 DFLT_STICK_CAL_MIN = 500;
739static int joycon_request_calibration(struct joycon_ctlr *ctlr)
740{
741 u16 left_stick_addr = JC_CAL_FCT_DATA_LEFT_ADDR;
742 u16 right_stick_addr = JC_CAL_FCT_DATA_RIGHT_ADDR;
743 int ret;
2af16c1f
DO
744
745 hid_dbg(ctlr->hdev, "requesting cal data\n");
83d640c4
DO
746
747 /* check if user stick calibrations are present */
748 if (!joycon_check_for_cal_magic(ctlr, JC_CAL_USR_LEFT_MAGIC_ADDR)) {
749 left_stick_addr = JC_CAL_USR_LEFT_DATA_ADDR;
750 hid_info(ctlr->hdev, "using user cal for left stick\n");
751 } else {
752 hid_info(ctlr->hdev, "using factory cal for left stick\n");
753 }
754 if (!joycon_check_for_cal_magic(ctlr, JC_CAL_USR_RIGHT_MAGIC_ADDR)) {
755 right_stick_addr = JC_CAL_USR_RIGHT_DATA_ADDR;
756 hid_info(ctlr->hdev, "using user cal for right stick\n");
757 } else {
758 hid_info(ctlr->hdev, "using factory cal for right stick\n");
759 }
760
761 /* read the left stick calibration data */
762 ret = joycon_read_stick_calibration(ctlr, left_stick_addr,
763 &ctlr->left_stick_cal_x,
764 &ctlr->left_stick_cal_y,
765 true);
2af16c1f
DO
766 if (ret) {
767 hid_warn(ctlr->hdev,
83d640c4 768 "Failed to read left stick cal, using dflts; e=%d\n",
2af16c1f
DO
769 ret);
770
771 ctlr->left_stick_cal_x.center = DFLT_STICK_CAL_CEN;
772 ctlr->left_stick_cal_x.max = DFLT_STICK_CAL_MAX;
773 ctlr->left_stick_cal_x.min = DFLT_STICK_CAL_MIN;
774
775 ctlr->left_stick_cal_y.center = DFLT_STICK_CAL_CEN;
776 ctlr->left_stick_cal_y.max = DFLT_STICK_CAL_MAX;
777 ctlr->left_stick_cal_y.min = DFLT_STICK_CAL_MIN;
83d640c4
DO
778 }
779
780 /* read the right stick calibration data */
781 ret = joycon_read_stick_calibration(ctlr, right_stick_addr,
782 &ctlr->right_stick_cal_x,
783 &ctlr->right_stick_cal_y,
784 false);
785 if (ret) {
786 hid_warn(ctlr->hdev,
787 "Failed to read right stick cal, using dflts; e=%d\n",
788 ret);
2af16c1f
DO
789
790 ctlr->right_stick_cal_x.center = DFLT_STICK_CAL_CEN;
791 ctlr->right_stick_cal_x.max = DFLT_STICK_CAL_MAX;
792 ctlr->right_stick_cal_x.min = DFLT_STICK_CAL_MIN;
793
794 ctlr->right_stick_cal_y.center = DFLT_STICK_CAL_CEN;
795 ctlr->right_stick_cal_y.max = DFLT_STICK_CAL_MAX;
796 ctlr->right_stick_cal_y.min = DFLT_STICK_CAL_MIN;
2af16c1f
DO
797 }
798
2af16c1f
DO
799 hid_dbg(ctlr->hdev, "calibration:\n"
800 "l_x_c=%d l_x_max=%d l_x_min=%d\n"
801 "l_y_c=%d l_y_max=%d l_y_min=%d\n"
802 "r_x_c=%d r_x_max=%d r_x_min=%d\n"
803 "r_y_c=%d r_y_max=%d r_y_min=%d\n",
804 ctlr->left_stick_cal_x.center,
805 ctlr->left_stick_cal_x.max,
806 ctlr->left_stick_cal_x.min,
807 ctlr->left_stick_cal_y.center,
808 ctlr->left_stick_cal_y.max,
809 ctlr->left_stick_cal_y.min,
810 ctlr->right_stick_cal_x.center,
811 ctlr->right_stick_cal_x.max,
812 ctlr->right_stick_cal_x.min,
813 ctlr->right_stick_cal_y.center,
814 ctlr->right_stick_cal_y.max,
815 ctlr->right_stick_cal_y.min);
816
817 return 0;
818}
819
4ff5b108
DO
820/*
821 * These divisors are calculated once rather than for each sample. They are only
822 * dependent on the IMU calibration values. They are used when processing the
823 * IMU input reports.
824 */
825static void joycon_calc_imu_cal_divisors(struct joycon_ctlr *ctlr)
826{
827 int i;
828
829 for (i = 0; i < 3; i++) {
830 ctlr->imu_cal_accel_divisor[i] = ctlr->accel_cal.scale[i] -
831 ctlr->accel_cal.offset[i];
832 ctlr->imu_cal_gyro_divisor[i] = ctlr->gyro_cal.scale[i] -
833 ctlr->gyro_cal.offset[i];
834 }
835}
836
837static const s16 DFLT_ACCEL_OFFSET /*= 0*/;
838static const s16 DFLT_ACCEL_SCALE = 16384;
839static const s16 DFLT_GYRO_OFFSET /*= 0*/;
840static const s16 DFLT_GYRO_SCALE = 13371;
841static int joycon_request_imu_calibration(struct joycon_ctlr *ctlr)
842{
843 u16 imu_cal_addr = JC_IMU_CAL_FCT_DATA_ADDR;
844 u8 *raw_cal;
845 int ret;
846 int i;
847
848 /* check if user calibration exists */
849 if (!joycon_check_for_cal_magic(ctlr, JC_IMU_CAL_USR_MAGIC_ADDR)) {
850 imu_cal_addr = JC_IMU_CAL_USR_DATA_ADDR;
851 hid_info(ctlr->hdev, "using user cal for IMU\n");
852 } else {
853 hid_info(ctlr->hdev, "using factory cal for IMU\n");
854 }
855
856 /* request IMU calibration data */
857 hid_dbg(ctlr->hdev, "requesting IMU cal data\n");
858 ret = joycon_request_spi_flash_read(ctlr, imu_cal_addr,
859 JC_IMU_CAL_DATA_SIZE, &raw_cal);
860 if (ret) {
861 hid_warn(ctlr->hdev,
862 "Failed to read IMU cal, using defaults; ret=%d\n",
863 ret);
864
865 for (i = 0; i < 3; i++) {
866 ctlr->accel_cal.offset[i] = DFLT_ACCEL_OFFSET;
867 ctlr->accel_cal.scale[i] = DFLT_ACCEL_SCALE;
868 ctlr->gyro_cal.offset[i] = DFLT_GYRO_OFFSET;
869 ctlr->gyro_cal.scale[i] = DFLT_GYRO_SCALE;
870 }
871 joycon_calc_imu_cal_divisors(ctlr);
872 return ret;
873 }
874
875 /* IMU calibration parsing */
876 for (i = 0; i < 3; i++) {
877 int j = i * 2;
878
879 ctlr->accel_cal.offset[i] = get_unaligned_le16(raw_cal + j);
880 ctlr->accel_cal.scale[i] = get_unaligned_le16(raw_cal + j + 6);
881 ctlr->gyro_cal.offset[i] = get_unaligned_le16(raw_cal + j + 12);
882 ctlr->gyro_cal.scale[i] = get_unaligned_le16(raw_cal + j + 18);
883 }
884
885 joycon_calc_imu_cal_divisors(ctlr);
886
887 hid_dbg(ctlr->hdev, "IMU calibration:\n"
888 "a_o[0]=%d a_o[1]=%d a_o[2]=%d\n"
889 "a_s[0]=%d a_s[1]=%d a_s[2]=%d\n"
890 "g_o[0]=%d g_o[1]=%d g_o[2]=%d\n"
891 "g_s[0]=%d g_s[1]=%d g_s[2]=%d\n",
892 ctlr->accel_cal.offset[0],
893 ctlr->accel_cal.offset[1],
894 ctlr->accel_cal.offset[2],
895 ctlr->accel_cal.scale[0],
896 ctlr->accel_cal.scale[1],
897 ctlr->accel_cal.scale[2],
898 ctlr->gyro_cal.offset[0],
899 ctlr->gyro_cal.offset[1],
900 ctlr->gyro_cal.offset[2],
901 ctlr->gyro_cal.scale[0],
902 ctlr->gyro_cal.scale[1],
903 ctlr->gyro_cal.scale[2]);
904
905 return 0;
906}
907
2af16c1f
DO
908static int joycon_set_report_mode(struct joycon_ctlr *ctlr)
909{
910 struct joycon_subcmd_request *req;
911 u8 buffer[sizeof(*req) + 1] = { 0 };
912
913 req = (struct joycon_subcmd_request *)buffer;
914 req->subcmd_id = JC_SUBCMD_SET_REPORT_MODE;
915 req->data[0] = 0x30; /* standard, full report mode */
916
917 hid_dbg(ctlr->hdev, "setting controller report mode\n");
6b5dca2d 918 return joycon_send_subcmd(ctlr, req, 1, HZ);
2af16c1f
DO
919}
920
c4eae84f
DO
921static int joycon_enable_rumble(struct joycon_ctlr *ctlr)
922{
923 struct joycon_subcmd_request *req;
924 u8 buffer[sizeof(*req) + 1] = { 0 };
925
926 req = (struct joycon_subcmd_request *)buffer;
927 req->subcmd_id = JC_SUBCMD_ENABLE_VIBRATION;
928 req->data[0] = 0x01; /* note: 0x00 would disable */
929
930 hid_dbg(ctlr->hdev, "enabling rumble\n");
6b5dca2d 931 return joycon_send_subcmd(ctlr, req, 1, HZ/4);
c4eae84f
DO
932}
933
4ff5b108
DO
934static int joycon_enable_imu(struct joycon_ctlr *ctlr)
935{
936 struct joycon_subcmd_request *req;
937 u8 buffer[sizeof(*req) + 1] = { 0 };
938
939 req = (struct joycon_subcmd_request *)buffer;
940 req->subcmd_id = JC_SUBCMD_ENABLE_IMU;
941 req->data[0] = 0x01; /* note: 0x00 would disable */
942
943 hid_dbg(ctlr->hdev, "enabling IMU\n");
944 return joycon_send_subcmd(ctlr, req, 1, HZ);
945}
946
2af16c1f
DO
947static s32 joycon_map_stick_val(struct joycon_stick_cal *cal, s32 val)
948{
949 s32 center = cal->center;
950 s32 min = cal->min;
951 s32 max = cal->max;
952 s32 new_val;
953
954 if (val > center) {
955 new_val = (val - center) * JC_MAX_STICK_MAG;
956 new_val /= (max - center);
957 } else {
958 new_val = (center - val) * -JC_MAX_STICK_MAG;
959 new_val /= (center - min);
960 }
961 new_val = clamp(new_val, (s32)-JC_MAX_STICK_MAG, (s32)JC_MAX_STICK_MAG);
962 return new_val;
963}
964
4ff5b108
DO
965static void joycon_input_report_parse_imu_data(struct joycon_ctlr *ctlr,
966 struct joycon_input_report *rep,
967 struct joycon_imu_data *imu_data)
968{
969 u8 *raw = rep->imu_raw_bytes;
970 int i;
971
972 for (i = 0; i < 3; i++) {
973 struct joycon_imu_data *data = &imu_data[i];
974
975 data->accel_x = get_unaligned_le16(raw + 0);
976 data->accel_y = get_unaligned_le16(raw + 2);
977 data->accel_z = get_unaligned_le16(raw + 4);
978 data->gyro_x = get_unaligned_le16(raw + 6);
979 data->gyro_y = get_unaligned_le16(raw + 8);
980 data->gyro_z = get_unaligned_le16(raw + 10);
981 /* point to next imu sample */
982 raw += sizeof(struct joycon_imu_data);
983 }
984}
985
986static void joycon_parse_imu_report(struct joycon_ctlr *ctlr,
987 struct joycon_input_report *rep)
988{
989 struct joycon_imu_data imu_data[3] = {0}; /* 3 reports per packet */
990 struct input_dev *idev = ctlr->imu_input;
991 unsigned int msecs = jiffies_to_msecs(jiffies);
992 unsigned int last_msecs = ctlr->imu_last_pkt_ms;
993 int i;
994 int value[6];
995
996 joycon_input_report_parse_imu_data(ctlr, rep, imu_data);
997
998 /*
999 * There are complexities surrounding how we determine the timestamps we
1000 * associate with the samples we pass to userspace. The IMU input
1001 * reports do not provide us with a good timestamp. There's a quickly
1002 * incrementing 8-bit counter per input report, but it is not very
1003 * useful for this purpose (it is not entirely clear what rate it
1004 * increments at or if it varies based on packet push rate - more on
1005 * the push rate below...).
1006 *
1007 * The reverse engineering work done on the joy-cons and pro controllers
1008 * by the community seems to indicate the following:
1009 * - The controller samples the IMU every 1.35ms. It then does some of
1010 * its own processing, probably averaging the samples out.
1011 * - Each imu input report contains 3 IMU samples, (usually 5ms apart).
1012 * - In the standard reporting mode (which this driver uses exclusively)
1013 * input reports are pushed from the controller as follows:
1014 * * joy-con (bluetooth): every 15 ms
1015 * * joy-cons (in charging grip via USB): every 15 ms
1016 * * pro controller (USB): every 15 ms
1017 * * pro controller (bluetooth): every 8 ms (this is the wildcard)
1018 *
1019 * Further complicating matters is that some bluetooth stacks are known
1020 * to alter the controller's packet rate by hardcoding the bluetooth
1021 * SSR for the switch controllers (android's stack currently sets the
1022 * SSR to 11ms for both the joy-cons and pro controllers).
1023 *
1024 * In my own testing, I've discovered that my pro controller either
1025 * reports IMU sample batches every 11ms or every 15ms. This rate is
1026 * stable after connecting. It isn't 100% clear what determines this
1027 * rate. Importantly, even when sending every 11ms, none of the samples
1028 * are duplicates. This seems to indicate that the time deltas between
1029 * reported samples can vary based on the input report rate.
1030 *
1031 * The solution employed in this driver is to keep track of the average
1032 * time delta between IMU input reports. In testing, this value has
1033 * proven to be stable, staying at 15ms or 11ms, though other hardware
1034 * configurations and bluetooth stacks could potentially see other rates
1035 * (hopefully this will become more clear as more people use the
1036 * driver).
1037 *
1038 * Keeping track of the average report delta allows us to submit our
1039 * timestamps to userspace based on that. Each report contains 3
1040 * samples, so the IMU sampling rate should be avg_time_delta/3. We can
1041 * also use this average to detect events where we have dropped a
1042 * packet. The userspace timestamp for the samples will be adjusted
1043 * accordingly to prevent unwanted behvaior.
1044 */
1045 if (!ctlr->imu_first_packet_received) {
1046 ctlr->imu_timestamp_us = 0;
1047 ctlr->imu_delta_samples_count = 0;
1048 ctlr->imu_delta_samples_sum = 0;
1049 ctlr->imu_avg_delta_ms = JC_IMU_DFLT_AVG_DELTA_MS;
1050 ctlr->imu_first_packet_received = true;
1051 } else {
1052 unsigned int delta = msecs - last_msecs;
1053 unsigned int dropped_pkts;
1054 unsigned int dropped_threshold;
1055
1056 /* avg imu report delta housekeeping */
1057 ctlr->imu_delta_samples_sum += delta;
1058 ctlr->imu_delta_samples_count++;
1059 if (ctlr->imu_delta_samples_count >=
1060 JC_IMU_SAMPLES_PER_DELTA_AVG) {
1061 ctlr->imu_avg_delta_ms = ctlr->imu_delta_samples_sum /
1062 ctlr->imu_delta_samples_count;
1063 /* don't ever want divide by zero shenanigans */
1064 if (ctlr->imu_avg_delta_ms == 0) {
1065 ctlr->imu_avg_delta_ms = 1;
1066 hid_warn(ctlr->hdev,
1067 "calculated avg imu delta of 0\n");
1068 }
1069 ctlr->imu_delta_samples_count = 0;
1070 ctlr->imu_delta_samples_sum = 0;
1071 }
1072
1073 /* useful for debugging IMU sample rate */
1074 hid_dbg(ctlr->hdev,
1075 "imu_report: ms=%u last_ms=%u delta=%u avg_delta=%u\n",
1076 msecs, last_msecs, delta, ctlr->imu_avg_delta_ms);
1077
1078 /* check if any packets have been dropped */
1079 dropped_threshold = ctlr->imu_avg_delta_ms * 3 / 2;
1080 dropped_pkts = (delta - min(delta, dropped_threshold)) /
1081 ctlr->imu_avg_delta_ms;
1082 ctlr->imu_timestamp_us += 1000 * ctlr->imu_avg_delta_ms;
1083 if (dropped_pkts > JC_IMU_DROPPED_PKT_WARNING) {
1084 hid_warn(ctlr->hdev,
1085 "compensating for %u dropped IMU reports\n",
1086 dropped_pkts);
1087 hid_warn(ctlr->hdev,
1088 "delta=%u avg_delta=%u\n",
1089 delta, ctlr->imu_avg_delta_ms);
1090 }
1091 }
1092 ctlr->imu_last_pkt_ms = msecs;
1093
1094 /* Each IMU input report contains three samples */
1095 for (i = 0; i < 3; i++) {
1096 input_event(idev, EV_MSC, MSC_TIMESTAMP,
1097 ctlr->imu_timestamp_us);
1098
1099 /*
1100 * These calculations (which use the controller's calibration
1101 * settings to improve the final values) are based on those
1102 * found in the community's reverse-engineering repo (linked at
1103 * top of driver). For hid-nintendo, we make sure that the final
1104 * value given to userspace is always in terms of the axis
1105 * resolution we provided.
1106 *
1107 * Currently only the gyro calculations subtract the calibration
1108 * offsets from the raw value itself. In testing, doing the same
1109 * for the accelerometer raw values decreased accuracy.
1110 *
1111 * Note that the gyro values are multiplied by the
1112 * precision-saving scaling factor to prevent large inaccuracies
1113 * due to truncation of the resolution value which would
1114 * otherwise occur. To prevent overflow (without resorting to 64
1115 * bit integer math), the mult_frac macro is used.
1116 */
1117 value[0] = mult_frac((JC_IMU_PREC_RANGE_SCALE *
1118 (imu_data[i].gyro_x -
1119 ctlr->gyro_cal.offset[0])),
1120 ctlr->gyro_cal.scale[0],
1121 ctlr->imu_cal_gyro_divisor[0]);
1122 value[1] = mult_frac((JC_IMU_PREC_RANGE_SCALE *
1123 (imu_data[i].gyro_y -
1124 ctlr->gyro_cal.offset[1])),
1125 ctlr->gyro_cal.scale[1],
1126 ctlr->imu_cal_gyro_divisor[1]);
1127 value[2] = mult_frac((JC_IMU_PREC_RANGE_SCALE *
1128 (imu_data[i].gyro_z -
1129 ctlr->gyro_cal.offset[2])),
1130 ctlr->gyro_cal.scale[2],
1131 ctlr->imu_cal_gyro_divisor[2]);
1132
1133 value[3] = ((s32)imu_data[i].accel_x *
1134 ctlr->accel_cal.scale[0]) /
1135 ctlr->imu_cal_accel_divisor[0];
1136 value[4] = ((s32)imu_data[i].accel_y *
1137 ctlr->accel_cal.scale[1]) /
1138 ctlr->imu_cal_accel_divisor[1];
1139 value[5] = ((s32)imu_data[i].accel_z *
1140 ctlr->accel_cal.scale[2]) /
1141 ctlr->imu_cal_accel_divisor[2];
1142
1143 hid_dbg(ctlr->hdev, "raw_gyro: g_x=%d g_y=%d g_z=%d\n",
1144 imu_data[i].gyro_x, imu_data[i].gyro_y,
1145 imu_data[i].gyro_z);
1146 hid_dbg(ctlr->hdev, "raw_accel: a_x=%d a_y=%d a_z=%d\n",
1147 imu_data[i].accel_x, imu_data[i].accel_y,
1148 imu_data[i].accel_z);
1149
1150 /*
1151 * The right joy-con has 2 axes negated, Y and Z. This is due to
1152 * the orientation of the IMU in the controller. We negate those
1153 * axes' values in order to be consistent with the left joy-con
1154 * and the pro controller:
1155 * X: positive is pointing toward the triggers
1156 * Y: positive is pointing to the left
1157 * Z: positive is pointing up (out of the buttons/sticks)
1158 * The axes follow the right-hand rule.
1159 */
1160 if (jc_type_is_joycon(ctlr) && jc_type_has_right(ctlr)) {
1161 int j;
1162
1163 /* negate all but x axis */
1164 for (j = 1; j < 6; ++j) {
1165 if (j == 3)
1166 continue;
1167 value[j] *= -1;
1168 }
1169 }
1170
1171 input_report_abs(idev, ABS_RX, value[0]);
1172 input_report_abs(idev, ABS_RY, value[1]);
1173 input_report_abs(idev, ABS_RZ, value[2]);
1174 input_report_abs(idev, ABS_X, value[3]);
1175 input_report_abs(idev, ABS_Y, value[4]);
1176 input_report_abs(idev, ABS_Z, value[5]);
1177 input_sync(idev);
1178 /* convert to micros and divide by 3 (3 samples per report). */
1179 ctlr->imu_timestamp_us += ctlr->imu_avg_delta_ms * 1000 / 3;
1180 }
1181}
1182
2af16c1f
DO
1183static void joycon_parse_report(struct joycon_ctlr *ctlr,
1184 struct joycon_input_report *rep)
1185{
1186 struct input_dev *dev = ctlr->input;
08ebba5c
DO
1187 unsigned long flags;
1188 u8 tmp;
2af16c1f 1189 u32 btns;
c4eae84f
DO
1190 unsigned long msecs = jiffies_to_msecs(jiffies);
1191
1192 spin_lock_irqsave(&ctlr->lock, flags);
1193 if (IS_ENABLED(CONFIG_NINTENDO_FF) && rep->vibrator_report &&
1194 (msecs - ctlr->rumble_msecs) >= JC_RUMBLE_PERIOD_MS)
1195 queue_work(ctlr->rumble_queue, &ctlr->rumble_worker);
2af16c1f 1196
08ebba5c
DO
1197 /* Parse the battery status */
1198 tmp = rep->bat_con;
08ebba5c
DO
1199 ctlr->host_powered = tmp & BIT(0);
1200 ctlr->battery_charging = tmp & BIT(4);
1201 tmp = tmp >> 5;
1202 switch (tmp) {
1203 case 0: /* empty */
1204 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
1205 break;
1206 case 1: /* low */
1207 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
1208 break;
1209 case 2: /* medium */
1210 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
1211 break;
1212 case 3: /* high */
1213 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_HIGH;
1214 break;
1215 case 4: /* full */
1216 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
1217 break;
1218 default:
1219 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
1220 hid_warn(ctlr->hdev, "Invalid battery status\n");
1221 break;
1222 }
1223 spin_unlock_irqrestore(&ctlr->lock, flags);
1224
1225 /* Parse the buttons and sticks */
2af16c1f
DO
1226 btns = hid_field_extract(ctlr->hdev, rep->button_status, 0, 24);
1227
294a8287 1228 if (jc_type_has_left(ctlr)) {
2af16c1f
DO
1229 u16 raw_x;
1230 u16 raw_y;
1231 s32 x;
1232 s32 y;
1233
1234 /* get raw stick values */
1235 raw_x = hid_field_extract(ctlr->hdev, rep->left_stick, 0, 12);
1236 raw_y = hid_field_extract(ctlr->hdev,
1237 rep->left_stick + 1, 4, 12);
1238 /* map the stick values */
1239 x = joycon_map_stick_val(&ctlr->left_stick_cal_x, raw_x);
1240 y = -joycon_map_stick_val(&ctlr->left_stick_cal_y, raw_y);
1241 /* report sticks */
1242 input_report_abs(dev, ABS_X, x);
1243 input_report_abs(dev, ABS_Y, y);
1244
1245 /* report buttons */
1246 input_report_key(dev, BTN_TL, btns & JC_BTN_L);
1247 input_report_key(dev, BTN_TL2, btns & JC_BTN_ZL);
1248 input_report_key(dev, BTN_SELECT, btns & JC_BTN_MINUS);
1249 input_report_key(dev, BTN_THUMBL, btns & JC_BTN_LSTICK);
1250 input_report_key(dev, BTN_Z, btns & JC_BTN_CAP);
1251
294a8287 1252 if (jc_type_is_joycon(ctlr)) {
2af16c1f
DO
1253 /* Report the S buttons as the non-existent triggers */
1254 input_report_key(dev, BTN_TR, btns & JC_BTN_SL_L);
1255 input_report_key(dev, BTN_TR2, btns & JC_BTN_SR_L);
1256
1257 /* Report d-pad as digital buttons for the joy-cons */
1258 input_report_key(dev, BTN_DPAD_DOWN,
1259 btns & JC_BTN_DOWN);
1260 input_report_key(dev, BTN_DPAD_UP, btns & JC_BTN_UP);
1261 input_report_key(dev, BTN_DPAD_RIGHT,
1262 btns & JC_BTN_RIGHT);
1263 input_report_key(dev, BTN_DPAD_LEFT,
1264 btns & JC_BTN_LEFT);
1265 } else {
1266 int hatx = 0;
1267 int haty = 0;
1268
1269 /* d-pad x */
1270 if (btns & JC_BTN_LEFT)
1271 hatx = -1;
1272 else if (btns & JC_BTN_RIGHT)
1273 hatx = 1;
1274 input_report_abs(dev, ABS_HAT0X, hatx);
1275
1276 /* d-pad y */
1277 if (btns & JC_BTN_UP)
1278 haty = -1;
1279 else if (btns & JC_BTN_DOWN)
1280 haty = 1;
1281 input_report_abs(dev, ABS_HAT0Y, haty);
1282 }
1283 }
294a8287 1284 if (jc_type_has_right(ctlr)) {
2af16c1f
DO
1285 u16 raw_x;
1286 u16 raw_y;
1287 s32 x;
1288 s32 y;
1289
1290 /* get raw stick values */
1291 raw_x = hid_field_extract(ctlr->hdev, rep->right_stick, 0, 12);
1292 raw_y = hid_field_extract(ctlr->hdev,
1293 rep->right_stick + 1, 4, 12);
1294 /* map stick values */
1295 x = joycon_map_stick_val(&ctlr->right_stick_cal_x, raw_x);
1296 y = -joycon_map_stick_val(&ctlr->right_stick_cal_y, raw_y);
1297 /* report sticks */
1298 input_report_abs(dev, ABS_RX, x);
1299 input_report_abs(dev, ABS_RY, y);
1300
1301 /* report buttons */
1302 input_report_key(dev, BTN_TR, btns & JC_BTN_R);
1303 input_report_key(dev, BTN_TR2, btns & JC_BTN_ZR);
294a8287 1304 if (jc_type_is_joycon(ctlr)) {
2af16c1f
DO
1305 /* Report the S buttons as the non-existent triggers */
1306 input_report_key(dev, BTN_TL, btns & JC_BTN_SL_R);
1307 input_report_key(dev, BTN_TL2, btns & JC_BTN_SR_R);
1308 }
1309 input_report_key(dev, BTN_START, btns & JC_BTN_PLUS);
1310 input_report_key(dev, BTN_THUMBR, btns & JC_BTN_RSTICK);
1311 input_report_key(dev, BTN_MODE, btns & JC_BTN_HOME);
1312 input_report_key(dev, BTN_WEST, btns & JC_BTN_Y);
1313 input_report_key(dev, BTN_NORTH, btns & JC_BTN_X);
1314 input_report_key(dev, BTN_EAST, btns & JC_BTN_A);
1315 input_report_key(dev, BTN_SOUTH, btns & JC_BTN_B);
1316 }
1317
1318 input_sync(dev);
479da173
DO
1319
1320 /*
1321 * Immediately after receiving a report is the most reliable time to
1322 * send a subcommand to the controller. Wake any subcommand senders
1323 * waiting for a report.
1324 */
1325 if (unlikely(mutex_is_locked(&ctlr->output_mutex))) {
1326 spin_lock_irqsave(&ctlr->lock, flags);
1327 ctlr->received_input_report = true;
1328 spin_unlock_irqrestore(&ctlr->lock, flags);
1329 wake_up(&ctlr->wait);
1330 }
4ff5b108
DO
1331
1332 /* parse IMU data if present */
1333 if (rep->id == JC_INPUT_IMU_DATA)
1334 joycon_parse_imu_report(ctlr, rep);
2af16c1f
DO
1335}
1336
4c048f6b
DO
1337static int joycon_send_rumble_data(struct joycon_ctlr *ctlr)
1338{
1339 int ret;
1340 unsigned long flags;
1341 struct joycon_rumble_output rumble_output = { 0 };
1342
1343 spin_lock_irqsave(&ctlr->lock, flags);
1344 /*
1345 * If the controller has been removed, just return ENODEV so the LED
1346 * subsystem doesn't print invalid errors on removal.
1347 */
1348 if (ctlr->ctlr_state == JOYCON_CTLR_STATE_REMOVED) {
1349 spin_unlock_irqrestore(&ctlr->lock, flags);
1350 return -ENODEV;
1351 }
1352 memcpy(rumble_output.rumble_data,
1353 ctlr->rumble_data[ctlr->rumble_queue_tail],
1354 JC_RUMBLE_DATA_SIZE);
1355 spin_unlock_irqrestore(&ctlr->lock, flags);
1356
1357 rumble_output.output_id = JC_OUTPUT_RUMBLE_ONLY;
1358 rumble_output.packet_num = ctlr->subcmd_num;
1359 if (++ctlr->subcmd_num > 0xF)
1360 ctlr->subcmd_num = 0;
1361
1362 ret = __joycon_hid_send(ctlr->hdev, (u8 *)&rumble_output,
1363 sizeof(rumble_output));
1364 return ret;
1365}
1366
c4eae84f
DO
1367static void joycon_rumble_worker(struct work_struct *work)
1368{
1369 struct joycon_ctlr *ctlr = container_of(work, struct joycon_ctlr,
1370 rumble_worker);
1371 unsigned long flags;
1372 bool again = true;
1373 int ret;
1374
1375 while (again) {
1376 mutex_lock(&ctlr->output_mutex);
4c048f6b 1377 ret = joycon_send_rumble_data(ctlr);
c4eae84f 1378 mutex_unlock(&ctlr->output_mutex);
c4eae84f 1379
012bd52c 1380 /* -ENODEV means the controller was just unplugged */
c4eae84f 1381 spin_lock_irqsave(&ctlr->lock, flags);
012bd52c
DO
1382 if (ret < 0 && ret != -ENODEV &&
1383 ctlr->ctlr_state != JOYCON_CTLR_STATE_REMOVED)
1384 hid_warn(ctlr->hdev, "Failed to set rumble; e=%d", ret);
1385
c4eae84f
DO
1386 ctlr->rumble_msecs = jiffies_to_msecs(jiffies);
1387 if (ctlr->rumble_queue_tail != ctlr->rumble_queue_head) {
1388 if (++ctlr->rumble_queue_tail >= JC_RUMBLE_QUEUE_SIZE)
1389 ctlr->rumble_queue_tail = 0;
1390 } else {
1391 again = false;
1392 }
1393 spin_unlock_irqrestore(&ctlr->lock, flags);
1394 }
1395}
1396
1397#if IS_ENABLED(CONFIG_NINTENDO_FF)
1398static struct joycon_rumble_freq_data joycon_find_rumble_freq(u16 freq)
1399{
1400 const size_t length = ARRAY_SIZE(joycon_rumble_frequencies);
1401 const struct joycon_rumble_freq_data *data = joycon_rumble_frequencies;
1402 int i = 0;
1403
1404 if (freq > data[0].freq) {
1405 for (i = 1; i < length - 1; i++) {
1406 if (freq > data[i - 1].freq && freq <= data[i].freq)
1407 break;
1408 }
1409 }
1410
1411 return data[i];
1412}
1413
1414static struct joycon_rumble_amp_data joycon_find_rumble_amp(u16 amp)
1415{
1416 const size_t length = ARRAY_SIZE(joycon_rumble_amplitudes);
1417 const struct joycon_rumble_amp_data *data = joycon_rumble_amplitudes;
1418 int i = 0;
1419
1420 if (amp > data[0].amp) {
1421 for (i = 1; i < length - 1; i++) {
1422 if (amp > data[i - 1].amp && amp <= data[i].amp)
1423 break;
1424 }
1425 }
1426
1427 return data[i];
1428}
1429
1430static void joycon_encode_rumble(u8 *data, u16 freq_low, u16 freq_high, u16 amp)
1431{
1432 struct joycon_rumble_freq_data freq_data_low;
1433 struct joycon_rumble_freq_data freq_data_high;
1434 struct joycon_rumble_amp_data amp_data;
1435
1436 freq_data_low = joycon_find_rumble_freq(freq_low);
1437 freq_data_high = joycon_find_rumble_freq(freq_high);
1438 amp_data = joycon_find_rumble_amp(amp);
1439
1440 data[0] = (freq_data_high.high >> 8) & 0xFF;
1441 data[1] = (freq_data_high.high & 0xFF) + amp_data.high;
1442 data[2] = freq_data_low.low + ((amp_data.low >> 8) & 0xFF);
1443 data[3] = amp_data.low & 0xFF;
1444}
1445
1446static const u16 JOYCON_MAX_RUMBLE_HIGH_FREQ = 1253;
1447static const u16 JOYCON_MIN_RUMBLE_HIGH_FREQ = 82;
1448static const u16 JOYCON_MAX_RUMBLE_LOW_FREQ = 626;
1449static const u16 JOYCON_MIN_RUMBLE_LOW_FREQ = 41;
1450
1451static void joycon_clamp_rumble_freqs(struct joycon_ctlr *ctlr)
1452{
1453 unsigned long flags;
1454
1455 spin_lock_irqsave(&ctlr->lock, flags);
1456 ctlr->rumble_ll_freq = clamp(ctlr->rumble_ll_freq,
1457 JOYCON_MIN_RUMBLE_LOW_FREQ,
1458 JOYCON_MAX_RUMBLE_LOW_FREQ);
1459 ctlr->rumble_lh_freq = clamp(ctlr->rumble_lh_freq,
1460 JOYCON_MIN_RUMBLE_HIGH_FREQ,
1461 JOYCON_MAX_RUMBLE_HIGH_FREQ);
1462 ctlr->rumble_rl_freq = clamp(ctlr->rumble_rl_freq,
1463 JOYCON_MIN_RUMBLE_LOW_FREQ,
1464 JOYCON_MAX_RUMBLE_LOW_FREQ);
1465 ctlr->rumble_rh_freq = clamp(ctlr->rumble_rh_freq,
1466 JOYCON_MIN_RUMBLE_HIGH_FREQ,
1467 JOYCON_MAX_RUMBLE_HIGH_FREQ);
1468 spin_unlock_irqrestore(&ctlr->lock, flags);
1469}
1470
1471static int joycon_set_rumble(struct joycon_ctlr *ctlr, u16 amp_r, u16 amp_l,
1472 bool schedule_now)
1473{
1474 u8 data[JC_RUMBLE_DATA_SIZE];
1475 u16 amp;
1476 u16 freq_r_low;
1477 u16 freq_r_high;
1478 u16 freq_l_low;
1479 u16 freq_l_high;
1480 unsigned long flags;
1481
1482 spin_lock_irqsave(&ctlr->lock, flags);
1483 freq_r_low = ctlr->rumble_rl_freq;
1484 freq_r_high = ctlr->rumble_rh_freq;
1485 freq_l_low = ctlr->rumble_ll_freq;
1486 freq_l_high = ctlr->rumble_lh_freq;
1487 spin_unlock_irqrestore(&ctlr->lock, flags);
1488
1489 /* right joy-con */
1490 amp = amp_r * (u32)joycon_max_rumble_amp / 65535;
1491 joycon_encode_rumble(data + 4, freq_r_low, freq_r_high, amp);
1492
1493 /* left joy-con */
1494 amp = amp_l * (u32)joycon_max_rumble_amp / 65535;
1495 joycon_encode_rumble(data, freq_l_low, freq_l_high, amp);
1496
1497 spin_lock_irqsave(&ctlr->lock, flags);
1498 if (++ctlr->rumble_queue_head >= JC_RUMBLE_QUEUE_SIZE)
1499 ctlr->rumble_queue_head = 0;
1500 memcpy(ctlr->rumble_data[ctlr->rumble_queue_head], data,
1501 JC_RUMBLE_DATA_SIZE);
1502 spin_unlock_irqrestore(&ctlr->lock, flags);
1503
1504 /* don't wait for the periodic send (reduces latency) */
1505 if (schedule_now)
1506 queue_work(ctlr->rumble_queue, &ctlr->rumble_worker);
1507
1508 return 0;
1509}
1510
1511static int joycon_play_effect(struct input_dev *dev, void *data,
1512 struct ff_effect *effect)
1513{
1514 struct joycon_ctlr *ctlr = input_get_drvdata(dev);
1515
1516 if (effect->type != FF_RUMBLE)
1517 return 0;
1518
1519 return joycon_set_rumble(ctlr,
1520 effect->u.rumble.weak_magnitude,
1521 effect->u.rumble.strong_magnitude,
1522 true);
1523}
1524#endif /* IS_ENABLED(CONFIG_NINTENDO_FF) */
2af16c1f
DO
1525
1526static const unsigned int joycon_button_inputs_l[] = {
1527 BTN_SELECT, BTN_Z, BTN_THUMBL,
1528 BTN_TL, BTN_TL2,
1529 0 /* 0 signals end of array */
1530};
1531
1532static const unsigned int joycon_button_inputs_r[] = {
1533 BTN_START, BTN_MODE, BTN_THUMBR,
1534 BTN_SOUTH, BTN_EAST, BTN_NORTH, BTN_WEST,
1535 BTN_TR, BTN_TR2,
1536 0 /* 0 signals end of array */
1537};
1538
1539/* We report joy-con d-pad inputs as buttons and pro controller as a hat. */
1540static const unsigned int joycon_dpad_inputs_jc[] = {
1541 BTN_DPAD_UP, BTN_DPAD_DOWN, BTN_DPAD_LEFT, BTN_DPAD_RIGHT,
1542};
1543
2af16c1f
DO
1544static int joycon_input_create(struct joycon_ctlr *ctlr)
1545{
1546 struct hid_device *hdev;
2af16c1f 1547 const char *name;
4ff5b108 1548 const char *imu_name;
2af16c1f
DO
1549 int ret;
1550 int i;
1551
1552 hdev = ctlr->hdev;
1553
1554 switch (hdev->product) {
1555 case USB_DEVICE_ID_NINTENDO_PROCON:
1556 name = "Nintendo Switch Pro Controller";
4ff5b108 1557 imu_name = "Nintendo Switch Pro Controller IMU";
2af16c1f 1558 break;
294a8287 1559 case USB_DEVICE_ID_NINTENDO_CHRGGRIP:
4ff5b108 1560 if (jc_type_has_left(ctlr)) {
294a8287 1561 name = "Nintendo Switch Left Joy-Con (Grip)";
4ff5b108
DO
1562 imu_name = "Nintendo Switch Left Joy-Con IMU (Grip)";
1563 } else {
294a8287 1564 name = "Nintendo Switch Right Joy-Con (Grip)";
4ff5b108
DO
1565 imu_name = "Nintendo Switch Right Joy-Con IMU (Grip)";
1566 }
294a8287 1567 break;
2af16c1f
DO
1568 case USB_DEVICE_ID_NINTENDO_JOYCONL:
1569 name = "Nintendo Switch Left Joy-Con";
4ff5b108 1570 imu_name = "Nintendo Switch Left Joy-Con IMU";
2af16c1f
DO
1571 break;
1572 case USB_DEVICE_ID_NINTENDO_JOYCONR:
1573 name = "Nintendo Switch Right Joy-Con";
4ff5b108 1574 imu_name = "Nintendo Switch Right Joy-Con IMU";
2af16c1f
DO
1575 break;
1576 default: /* Should be impossible */
1577 hid_err(hdev, "Invalid hid product\n");
1578 return -EINVAL;
1579 }
1580
1581 ctlr->input = devm_input_allocate_device(&hdev->dev);
1582 if (!ctlr->input)
1583 return -ENOMEM;
1584 ctlr->input->id.bustype = hdev->bus;
1585 ctlr->input->id.vendor = hdev->vendor;
1586 ctlr->input->id.product = hdev->product;
1587 ctlr->input->id.version = hdev->version;
14252473 1588 ctlr->input->uniq = ctlr->mac_addr_str;
2af16c1f
DO
1589 ctlr->input->name = name;
1590 input_set_drvdata(ctlr->input, ctlr);
1591
2af16c1f 1592 /* set up sticks and buttons */
294a8287 1593 if (jc_type_has_left(ctlr)) {
2af16c1f
DO
1594 input_set_abs_params(ctlr->input, ABS_X,
1595 -JC_MAX_STICK_MAG, JC_MAX_STICK_MAG,
1596 JC_STICK_FUZZ, JC_STICK_FLAT);
1597 input_set_abs_params(ctlr->input, ABS_Y,
1598 -JC_MAX_STICK_MAG, JC_MAX_STICK_MAG,
1599 JC_STICK_FUZZ, JC_STICK_FLAT);
1600
1601 for (i = 0; joycon_button_inputs_l[i] > 0; i++)
1602 input_set_capability(ctlr->input, EV_KEY,
1603 joycon_button_inputs_l[i]);
1604
1605 /* configure d-pad differently for joy-con vs pro controller */
1606 if (hdev->product != USB_DEVICE_ID_NINTENDO_PROCON) {
1607 for (i = 0; joycon_dpad_inputs_jc[i] > 0; i++)
1608 input_set_capability(ctlr->input, EV_KEY,
1609 joycon_dpad_inputs_jc[i]);
1610 } else {
1611 input_set_abs_params(ctlr->input, ABS_HAT0X,
1612 -JC_MAX_DPAD_MAG, JC_MAX_DPAD_MAG,
1613 JC_DPAD_FUZZ, JC_DPAD_FLAT);
1614 input_set_abs_params(ctlr->input, ABS_HAT0Y,
1615 -JC_MAX_DPAD_MAG, JC_MAX_DPAD_MAG,
1616 JC_DPAD_FUZZ, JC_DPAD_FLAT);
1617 }
1618 }
294a8287 1619 if (jc_type_has_right(ctlr)) {
2af16c1f
DO
1620 input_set_abs_params(ctlr->input, ABS_RX,
1621 -JC_MAX_STICK_MAG, JC_MAX_STICK_MAG,
1622 JC_STICK_FUZZ, JC_STICK_FLAT);
1623 input_set_abs_params(ctlr->input, ABS_RY,
1624 -JC_MAX_STICK_MAG, JC_MAX_STICK_MAG,
1625 JC_STICK_FUZZ, JC_STICK_FLAT);
1626
1627 for (i = 0; joycon_button_inputs_r[i] > 0; i++)
1628 input_set_capability(ctlr->input, EV_KEY,
1629 joycon_button_inputs_r[i]);
1630 }
1631
1632 /* Let's report joy-con S triggers separately */
1633 if (hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONL) {
1634 input_set_capability(ctlr->input, EV_KEY, BTN_TR);
1635 input_set_capability(ctlr->input, EV_KEY, BTN_TR2);
1636 } else if (hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONR) {
1637 input_set_capability(ctlr->input, EV_KEY, BTN_TL);
1638 input_set_capability(ctlr->input, EV_KEY, BTN_TL2);
1639 }
1640
c4eae84f
DO
1641#if IS_ENABLED(CONFIG_NINTENDO_FF)
1642 /* set up rumble */
1643 input_set_capability(ctlr->input, EV_FF, FF_RUMBLE);
1644 input_ff_create_memless(ctlr->input, NULL, joycon_play_effect);
1645 ctlr->rumble_ll_freq = JC_RUMBLE_DFLT_LOW_FREQ;
1646 ctlr->rumble_lh_freq = JC_RUMBLE_DFLT_HIGH_FREQ;
1647 ctlr->rumble_rl_freq = JC_RUMBLE_DFLT_LOW_FREQ;
1648 ctlr->rumble_rh_freq = JC_RUMBLE_DFLT_HIGH_FREQ;
1649 joycon_clamp_rumble_freqs(ctlr);
1650 joycon_set_rumble(ctlr, 0, 0, false);
1651 ctlr->rumble_msecs = jiffies_to_msecs(jiffies);
1652#endif
1653
2af16c1f
DO
1654 ret = input_register_device(ctlr->input);
1655 if (ret)
1656 return ret;
1657
4ff5b108
DO
1658 /* configure the imu input device */
1659 ctlr->imu_input = devm_input_allocate_device(&hdev->dev);
1660 if (!ctlr->imu_input)
1661 return -ENOMEM;
1662
1663 ctlr->imu_input->id.bustype = hdev->bus;
1664 ctlr->imu_input->id.vendor = hdev->vendor;
1665 ctlr->imu_input->id.product = hdev->product;
1666 ctlr->imu_input->id.version = hdev->version;
1667 ctlr->imu_input->uniq = ctlr->mac_addr_str;
1668 ctlr->imu_input->name = imu_name;
1669 input_set_drvdata(ctlr->imu_input, ctlr);
1670
1671 /* configure imu axes */
1672 input_set_abs_params(ctlr->imu_input, ABS_X,
1673 -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG,
1674 JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT);
1675 input_set_abs_params(ctlr->imu_input, ABS_Y,
1676 -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG,
1677 JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT);
1678 input_set_abs_params(ctlr->imu_input, ABS_Z,
1679 -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG,
1680 JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT);
1681 input_abs_set_res(ctlr->imu_input, ABS_X, JC_IMU_ACCEL_RES_PER_G);
1682 input_abs_set_res(ctlr->imu_input, ABS_Y, JC_IMU_ACCEL_RES_PER_G);
1683 input_abs_set_res(ctlr->imu_input, ABS_Z, JC_IMU_ACCEL_RES_PER_G);
1684
1685 input_set_abs_params(ctlr->imu_input, ABS_RX,
1686 -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG,
1687 JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT);
1688 input_set_abs_params(ctlr->imu_input, ABS_RY,
1689 -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG,
1690 JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT);
1691 input_set_abs_params(ctlr->imu_input, ABS_RZ,
1692 -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG,
1693 JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT);
1694
1695 input_abs_set_res(ctlr->imu_input, ABS_RX, JC_IMU_GYRO_RES_PER_DPS);
1696 input_abs_set_res(ctlr->imu_input, ABS_RY, JC_IMU_GYRO_RES_PER_DPS);
1697 input_abs_set_res(ctlr->imu_input, ABS_RZ, JC_IMU_GYRO_RES_PER_DPS);
1698
1699 __set_bit(EV_MSC, ctlr->imu_input->evbit);
1700 __set_bit(MSC_TIMESTAMP, ctlr->imu_input->mscbit);
1701 __set_bit(INPUT_PROP_ACCELEROMETER, ctlr->imu_input->propbit);
1702
1703 ret = input_register_device(ctlr->imu_input);
1704 if (ret)
1705 return ret;
1706
c5e62676
DO
1707 return 0;
1708}
1709
1710static int joycon_player_led_brightness_set(struct led_classdev *led,
1711 enum led_brightness brightness)
1712{
1713 struct device *dev = led->dev->parent;
1714 struct hid_device *hdev = to_hid_device(dev);
1715 struct joycon_ctlr *ctlr;
1716 int val = 0;
1717 int i;
1718 int ret;
1719 int num;
1720
1721 ctlr = hid_get_drvdata(hdev);
1722 if (!ctlr) {
1723 hid_err(hdev, "No controller data\n");
1724 return -ENODEV;
1725 }
1726
1727 /* determine which player led this is */
1728 for (num = 0; num < JC_NUM_LEDS; num++) {
1729 if (&ctlr->leds[num] == led)
1730 break;
1731 }
1732 if (num >= JC_NUM_LEDS)
1733 return -EINVAL;
1734
1735 mutex_lock(&ctlr->output_mutex);
1736 for (i = 0; i < JC_NUM_LEDS; i++) {
1737 if (i == num)
1738 val |= brightness << i;
1739 else
1740 val |= ctlr->leds[i].brightness << i;
1741 }
1742 ret = joycon_set_player_leds(ctlr, 0, val);
1743 mutex_unlock(&ctlr->output_mutex);
1744
1745 return ret;
1746}
1747
697e5c7a
DO
1748static int joycon_home_led_brightness_set(struct led_classdev *led,
1749 enum led_brightness brightness)
1750{
1751 struct device *dev = led->dev->parent;
1752 struct hid_device *hdev = to_hid_device(dev);
1753 struct joycon_ctlr *ctlr;
1754 struct joycon_subcmd_request *req;
1755 u8 buffer[sizeof(*req) + 5] = { 0 };
1756 u8 *data;
1757 int ret;
1758
1759 ctlr = hid_get_drvdata(hdev);
1760 if (!ctlr) {
1761 hid_err(hdev, "No controller data\n");
1762 return -ENODEV;
1763 }
1764
1765 req = (struct joycon_subcmd_request *)buffer;
1766 req->subcmd_id = JC_SUBCMD_SET_HOME_LIGHT;
1767 data = req->data;
1768 data[0] = 0x01;
1769 data[1] = brightness << 4;
1770 data[2] = brightness | (brightness << 4);
1771 data[3] = 0x11;
1772 data[4] = 0x11;
1773
1774 hid_dbg(hdev, "setting home led brightness\n");
1775 mutex_lock(&ctlr->output_mutex);
6b5dca2d 1776 ret = joycon_send_subcmd(ctlr, req, 5, HZ/4);
697e5c7a
DO
1777 mutex_unlock(&ctlr->output_mutex);
1778
1779 return ret;
1780}
1781
c5e62676 1782static DEFINE_MUTEX(joycon_input_num_mutex);
697e5c7a 1783static int joycon_leds_create(struct joycon_ctlr *ctlr)
c5e62676
DO
1784{
1785 struct hid_device *hdev = ctlr->hdev;
1786 struct device *dev = &hdev->dev;
1787 const char *d_name = dev_name(dev);
1788 struct led_classdev *led;
1789 char *name;
1790 int ret = 0;
1791 int i;
1792 static int input_num = 1;
1793
2af16c1f
DO
1794 /* Set the default controller player leds based on controller number */
1795 mutex_lock(&joycon_input_num_mutex);
1796 mutex_lock(&ctlr->output_mutex);
1797 ret = joycon_set_player_leds(ctlr, 0, 0xF >> (4 - input_num));
1798 if (ret)
1799 hid_warn(ctlr->hdev, "Failed to set leds; ret=%d\n", ret);
1800 mutex_unlock(&ctlr->output_mutex);
c5e62676
DO
1801
1802 /* configure the player LEDs */
1803 for (i = 0; i < JC_NUM_LEDS; i++) {
1804 name = devm_kasprintf(dev, GFP_KERNEL, "%s:%s:%s",
1805 d_name,
1806 "green",
1807 joycon_player_led_names[i]);
1808 if (!name)
1809 return -ENOMEM;
1810
1811 led = &ctlr->leds[i];
1812 led->name = name;
1813 led->brightness = ((i + 1) <= input_num) ? 1 : 0;
1814 led->max_brightness = 1;
1815 led->brightness_set_blocking =
1816 joycon_player_led_brightness_set;
1817 led->flags = LED_CORE_SUSPENDRESUME | LED_HW_PLUGGABLE;
1818
1819 ret = devm_led_classdev_register(&hdev->dev, led);
1820 if (ret) {
1821 hid_err(hdev, "Failed registering %s LED\n", led->name);
697e5c7a 1822 return ret;
c5e62676
DO
1823 }
1824 }
1825
2af16c1f
DO
1826 if (++input_num > 4)
1827 input_num = 1;
1828 mutex_unlock(&joycon_input_num_mutex);
1829
697e5c7a 1830 /* configure the home LED */
294a8287 1831 if (jc_type_has_right(ctlr)) {
697e5c7a
DO
1832 name = devm_kasprintf(dev, GFP_KERNEL, "%s:%s:%s",
1833 d_name,
1834 "blue",
1835 LED_FUNCTION_PLAYER5);
1836 if (!name)
1837 return -ENOMEM;
1838
1839 led = &ctlr->home_led;
1840 led->name = name;
1841 led->brightness = 0;
1842 led->max_brightness = 0xF;
1843 led->brightness_set_blocking = joycon_home_led_brightness_set;
1844 led->flags = LED_CORE_SUSPENDRESUME | LED_HW_PLUGGABLE;
1845 ret = devm_led_classdev_register(&hdev->dev, led);
1846 if (ret) {
1847 hid_err(hdev, "Failed registering home led\n");
1848 return ret;
1849 }
1850 /* Set the home LED to 0 as default state */
1851 ret = joycon_home_led_brightness_set(led, 0);
1852 if (ret) {
1853 hid_err(hdev, "Failed to set home LED dflt; ret=%d\n",
1854 ret);
1855 return ret;
1856 }
1857 }
1858
2af16c1f
DO
1859 return 0;
1860}
1861
08ebba5c
DO
1862static int joycon_battery_get_property(struct power_supply *supply,
1863 enum power_supply_property prop,
1864 union power_supply_propval *val)
1865{
1866 struct joycon_ctlr *ctlr = power_supply_get_drvdata(supply);
1867 unsigned long flags;
1868 int ret = 0;
1869 u8 capacity;
1870 bool charging;
1871 bool powered;
1872
1873 spin_lock_irqsave(&ctlr->lock, flags);
1874 capacity = ctlr->battery_capacity;
1875 charging = ctlr->battery_charging;
1876 powered = ctlr->host_powered;
1877 spin_unlock_irqrestore(&ctlr->lock, flags);
1878
1879 switch (prop) {
1880 case POWER_SUPPLY_PROP_PRESENT:
1881 val->intval = 1;
1882 break;
1883 case POWER_SUPPLY_PROP_SCOPE:
1884 val->intval = POWER_SUPPLY_SCOPE_DEVICE;
1885 break;
1886 case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
1887 val->intval = capacity;
1888 break;
1889 case POWER_SUPPLY_PROP_STATUS:
1890 if (charging)
1891 val->intval = POWER_SUPPLY_STATUS_CHARGING;
1892 else if (capacity == POWER_SUPPLY_CAPACITY_LEVEL_FULL &&
1893 powered)
1894 val->intval = POWER_SUPPLY_STATUS_FULL;
1895 else
1896 val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
1897 break;
1898 default:
1899 ret = -EINVAL;
1900 break;
1901 }
1902 return ret;
1903}
1904
1905static enum power_supply_property joycon_battery_props[] = {
1906 POWER_SUPPLY_PROP_PRESENT,
1907 POWER_SUPPLY_PROP_CAPACITY_LEVEL,
1908 POWER_SUPPLY_PROP_SCOPE,
1909 POWER_SUPPLY_PROP_STATUS,
1910};
1911
1912static int joycon_power_supply_create(struct joycon_ctlr *ctlr)
1913{
1914 struct hid_device *hdev = ctlr->hdev;
1915 struct power_supply_config supply_config = { .drv_data = ctlr, };
1916 const char * const name_fmt = "nintendo_switch_controller_battery_%s";
1917 int ret = 0;
1918
1919 /* Set initially to unknown before receiving first input report */
1920 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
1921
1922 /* Configure the battery's description */
1923 ctlr->battery_desc.properties = joycon_battery_props;
1924 ctlr->battery_desc.num_properties =
1925 ARRAY_SIZE(joycon_battery_props);
1926 ctlr->battery_desc.get_property = joycon_battery_get_property;
1927 ctlr->battery_desc.type = POWER_SUPPLY_TYPE_BATTERY;
1928 ctlr->battery_desc.use_for_apm = 0;
1929 ctlr->battery_desc.name = devm_kasprintf(&hdev->dev, GFP_KERNEL,
1930 name_fmt,
1931 dev_name(&hdev->dev));
1932 if (!ctlr->battery_desc.name)
1933 return -ENOMEM;
1934
1935 ctlr->battery = devm_power_supply_register(&hdev->dev,
1936 &ctlr->battery_desc,
1937 &supply_config);
1938 if (IS_ERR(ctlr->battery)) {
1939 ret = PTR_ERR(ctlr->battery);
1940 hid_err(hdev, "Failed to register battery; ret=%d\n", ret);
1941 return ret;
1942 }
1943
1944 return power_supply_powers(ctlr->battery, &hdev->dev);
1945}
1946
294a8287 1947static int joycon_read_info(struct joycon_ctlr *ctlr)
14252473
DO
1948{
1949 int ret;
1950 int i;
1951 int j;
1952 struct joycon_subcmd_request req = { 0 };
1953 struct joycon_input_report *report;
1954
1955 req.subcmd_id = JC_SUBCMD_REQ_DEV_INFO;
1956 ret = joycon_send_subcmd(ctlr, &req, 0, HZ);
1957 if (ret) {
1958 hid_err(ctlr->hdev, "Failed to get joycon info; ret=%d\n", ret);
1959 return ret;
1960 }
1961
1962 report = (struct joycon_input_report *)ctlr->input_buf;
1963
1964 for (i = 4, j = 0; j < 6; i++, j++)
4ff5b108 1965 ctlr->mac_addr[j] = report->subcmd_reply.data[i];
14252473
DO
1966
1967 ctlr->mac_addr_str = devm_kasprintf(&ctlr->hdev->dev, GFP_KERNEL,
1968 "%02X:%02X:%02X:%02X:%02X:%02X",
1969 ctlr->mac_addr[0],
1970 ctlr->mac_addr[1],
1971 ctlr->mac_addr[2],
1972 ctlr->mac_addr[3],
1973 ctlr->mac_addr[4],
1974 ctlr->mac_addr[5]);
1975 if (!ctlr->mac_addr_str)
1976 return -ENOMEM;
1977 hid_info(ctlr->hdev, "controller MAC = %s\n", ctlr->mac_addr_str);
1978
294a8287 1979 /* Retrieve the type so we can distinguish for charging grip */
4ff5b108 1980 ctlr->ctlr_type = report->subcmd_reply.data[2];
294a8287 1981
14252473
DO
1982 return 0;
1983}
1984
2af16c1f
DO
1985/* Common handler for parsing inputs */
1986static int joycon_ctlr_read_handler(struct joycon_ctlr *ctlr, u8 *data,
1987 int size)
1988{
1989 if (data[0] == JC_INPUT_SUBCMD_REPLY || data[0] == JC_INPUT_IMU_DATA ||
1990 data[0] == JC_INPUT_MCU_DATA) {
1991 if (size >= 12) /* make sure it contains the input report */
1992 joycon_parse_report(ctlr,
1993 (struct joycon_input_report *)data);
1994 }
1995
1996 return 0;
1997}
1998
1999static int joycon_ctlr_handle_event(struct joycon_ctlr *ctlr, u8 *data,
2000 int size)
2001{
2002 int ret = 0;
2003 bool match = false;
2004 struct joycon_input_report *report;
2005
2006 if (unlikely(mutex_is_locked(&ctlr->output_mutex)) &&
2007 ctlr->msg_type != JOYCON_MSG_TYPE_NONE) {
2008 switch (ctlr->msg_type) {
2009 case JOYCON_MSG_TYPE_USB:
2010 if (size < 2)
2011 break;
2012 if (data[0] == JC_INPUT_USB_RESPONSE &&
2013 data[1] == ctlr->usb_ack_match)
2014 match = true;
2015 break;
2016 case JOYCON_MSG_TYPE_SUBCMD:
2017 if (size < sizeof(struct joycon_input_report) ||
2018 data[0] != JC_INPUT_SUBCMD_REPLY)
2019 break;
2020 report = (struct joycon_input_report *)data;
4ff5b108 2021 if (report->subcmd_reply.id == ctlr->subcmd_ack_match)
2af16c1f
DO
2022 match = true;
2023 break;
2024 default:
2025 break;
2026 }
2027
2028 if (match) {
2029 memcpy(ctlr->input_buf, data,
2030 min(size, (int)JC_MAX_RESP_SIZE));
2031 ctlr->msg_type = JOYCON_MSG_TYPE_NONE;
2032 ctlr->received_resp = true;
2033 wake_up(&ctlr->wait);
2034
2035 /* This message has been handled */
2036 return 1;
2037 }
2038 }
2039
2040 if (ctlr->ctlr_state == JOYCON_CTLR_STATE_READ)
2041 ret = joycon_ctlr_read_handler(ctlr, data, size);
2042
2043 return ret;
2044}
2045
2046static int nintendo_hid_event(struct hid_device *hdev,
2047 struct hid_report *report, u8 *raw_data, int size)
2048{
2049 struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
2050
2051 if (size < 1)
2052 return -EINVAL;
2053
2054 return joycon_ctlr_handle_event(ctlr, raw_data, size);
2055}
2056
2057static int nintendo_hid_probe(struct hid_device *hdev,
2058 const struct hid_device_id *id)
2059{
2060 int ret;
2061 struct joycon_ctlr *ctlr;
2062
2063 hid_dbg(hdev, "probe - start\n");
2064
2065 ctlr = devm_kzalloc(&hdev->dev, sizeof(*ctlr), GFP_KERNEL);
2066 if (!ctlr) {
2067 ret = -ENOMEM;
2068 goto err;
2069 }
2070
2071 ctlr->hdev = hdev;
2072 ctlr->ctlr_state = JOYCON_CTLR_STATE_INIT;
c4eae84f
DO
2073 ctlr->rumble_queue_head = JC_RUMBLE_QUEUE_SIZE - 1;
2074 ctlr->rumble_queue_tail = 0;
2af16c1f
DO
2075 hid_set_drvdata(hdev, ctlr);
2076 mutex_init(&ctlr->output_mutex);
2077 init_waitqueue_head(&ctlr->wait);
08ebba5c 2078 spin_lock_init(&ctlr->lock);
c4eae84f
DO
2079 ctlr->rumble_queue = alloc_workqueue("hid-nintendo-rumble_wq",
2080 WQ_FREEZABLE | WQ_MEM_RECLAIM, 0);
2081 INIT_WORK(&ctlr->rumble_worker, joycon_rumble_worker);
2af16c1f
DO
2082
2083 ret = hid_parse(hdev);
2084 if (ret) {
2085 hid_err(hdev, "HID parse failed\n");
c4eae84f 2086 goto err_wq;
2af16c1f
DO
2087 }
2088
c7d0d636
DO
2089 /*
2090 * Patch the hw version of pro controller/joycons, so applications can
2091 * distinguish between the default HID mappings and the mappings defined
2092 * by the Linux game controller spec. This is important for the SDL2
2093 * library, which has a game controller database, which uses device ids
2094 * in combination with version as a key.
2095 */
2096 hdev->version |= 0x8000;
2097
2af16c1f
DO
2098 ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
2099 if (ret) {
2100 hid_err(hdev, "HW start failed\n");
c4eae84f 2101 goto err_wq;
2af16c1f
DO
2102 }
2103
2104 ret = hid_hw_open(hdev);
2105 if (ret) {
2106 hid_err(hdev, "cannot start hardware I/O\n");
2107 goto err_stop;
2108 }
2109
2110 hid_device_io_start(hdev);
2111
2112 /* Initialize the controller */
2113 mutex_lock(&ctlr->output_mutex);
2114 /* if handshake command fails, assume ble pro controller */
294a8287 2115 if ((jc_type_is_procon(ctlr) || jc_type_is_chrggrip(ctlr)) &&
6b5dca2d 2116 !joycon_send_usb(ctlr, JC_USB_CMD_HANDSHAKE, HZ)) {
2af16c1f
DO
2117 hid_dbg(hdev, "detected USB controller\n");
2118 /* set baudrate for improved latency */
6b5dca2d 2119 ret = joycon_send_usb(ctlr, JC_USB_CMD_BAUDRATE_3M, HZ);
2af16c1f
DO
2120 if (ret) {
2121 hid_err(hdev, "Failed to set baudrate; ret=%d\n", ret);
2122 goto err_mutex;
2123 }
2124 /* handshake */
6b5dca2d 2125 ret = joycon_send_usb(ctlr, JC_USB_CMD_HANDSHAKE, HZ);
2af16c1f
DO
2126 if (ret) {
2127 hid_err(hdev, "Failed handshake; ret=%d\n", ret);
2128 goto err_mutex;
2129 }
2130 /*
2131 * Set no timeout (to keep controller in USB mode).
2132 * This doesn't send a response, so ignore the timeout.
2133 */
6b5dca2d 2134 joycon_send_usb(ctlr, JC_USB_CMD_NO_TIMEOUT, HZ/10);
294a8287
DO
2135 } else if (jc_type_is_chrggrip(ctlr)) {
2136 hid_err(hdev, "Failed charging grip handshake\n");
2137 ret = -ETIMEDOUT;
2138 goto err_mutex;
2af16c1f
DO
2139 }
2140
2141 /* get controller calibration data, and parse it */
2142 ret = joycon_request_calibration(ctlr);
2143 if (ret) {
2144 /*
2145 * We can function with default calibration, but it may be
2146 * inaccurate. Provide a warning, and continue on.
2147 */
2148 hid_warn(hdev, "Analog stick positions may be inaccurate\n");
2149 }
2150
4ff5b108
DO
2151 /* get IMU calibration data, and parse it */
2152 ret = joycon_request_imu_calibration(ctlr);
2153 if (ret) {
2154 /*
2155 * We can function with default calibration, but it may be
2156 * inaccurate. Provide a warning, and continue on.
2157 */
2158 hid_warn(hdev, "Unable to read IMU calibration data\n");
2159 }
2160
2af16c1f
DO
2161 /* Set the reporting mode to 0x30, which is the full report mode */
2162 ret = joycon_set_report_mode(ctlr);
2163 if (ret) {
2164 hid_err(hdev, "Failed to set report mode; ret=%d\n", ret);
2165 goto err_mutex;
2166 }
2167
c4eae84f
DO
2168 /* Enable rumble */
2169 ret = joycon_enable_rumble(ctlr);
2170 if (ret) {
2171 hid_err(hdev, "Failed to enable rumble; ret=%d\n", ret);
2172 goto err_mutex;
2173 }
2174
4ff5b108
DO
2175 /* Enable the IMU */
2176 ret = joycon_enable_imu(ctlr);
2177 if (ret) {
2178 hid_err(hdev, "Failed to enable the IMU; ret=%d\n", ret);
2179 goto err_mutex;
2180 }
2181
294a8287 2182 ret = joycon_read_info(ctlr);
14252473 2183 if (ret) {
294a8287 2184 hid_err(hdev, "Failed to retrieve controller info; ret=%d\n",
14252473
DO
2185 ret);
2186 goto err_mutex;
2187 }
2188
2af16c1f
DO
2189 mutex_unlock(&ctlr->output_mutex);
2190
c5e62676 2191 /* Initialize the leds */
697e5c7a 2192 ret = joycon_leds_create(ctlr);
c5e62676
DO
2193 if (ret) {
2194 hid_err(hdev, "Failed to create leds; ret=%d\n", ret);
2195 goto err_close;
2196 }
2197
08ebba5c
DO
2198 /* Initialize the battery power supply */
2199 ret = joycon_power_supply_create(ctlr);
2200 if (ret) {
2201 hid_err(hdev, "Failed to create power_supply; ret=%d\n", ret);
2202 goto err_close;
2203 }
2204
2af16c1f
DO
2205 ret = joycon_input_create(ctlr);
2206 if (ret) {
2207 hid_err(hdev, "Failed to create input device; ret=%d\n", ret);
2208 goto err_close;
2209 }
2210
2211 ctlr->ctlr_state = JOYCON_CTLR_STATE_READ;
2212
2213 hid_dbg(hdev, "probe - success\n");
2214 return 0;
2215
2216err_mutex:
2217 mutex_unlock(&ctlr->output_mutex);
2218err_close:
2219 hid_hw_close(hdev);
2220err_stop:
2221 hid_hw_stop(hdev);
c4eae84f
DO
2222err_wq:
2223 destroy_workqueue(ctlr->rumble_queue);
2af16c1f
DO
2224err:
2225 hid_err(hdev, "probe - fail = %d\n", ret);
2226 return ret;
2227}
2228
2229static void nintendo_hid_remove(struct hid_device *hdev)
2230{
c4eae84f 2231 struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
012bd52c 2232 unsigned long flags;
c4eae84f 2233
2af16c1f 2234 hid_dbg(hdev, "remove\n");
012bd52c
DO
2235
2236 /* Prevent further attempts at sending subcommands. */
2237 spin_lock_irqsave(&ctlr->lock, flags);
2238 ctlr->ctlr_state = JOYCON_CTLR_STATE_REMOVED;
2239 spin_unlock_irqrestore(&ctlr->lock, flags);
2240
c4eae84f 2241 destroy_workqueue(ctlr->rumble_queue);
012bd52c 2242
2af16c1f
DO
2243 hid_hw_close(hdev);
2244 hid_hw_stop(hdev);
2245}
2246
2247static const struct hid_device_id nintendo_hid_devices[] = {
2248 { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
2249 USB_DEVICE_ID_NINTENDO_PROCON) },
2250 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
2251 USB_DEVICE_ID_NINTENDO_PROCON) },
294a8287
DO
2252 { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
2253 USB_DEVICE_ID_NINTENDO_CHRGGRIP) },
2af16c1f
DO
2254 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
2255 USB_DEVICE_ID_NINTENDO_JOYCONL) },
2256 { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
2257 USB_DEVICE_ID_NINTENDO_JOYCONR) },
2258 { }
2259};
2260MODULE_DEVICE_TABLE(hid, nintendo_hid_devices);
2261
2262static struct hid_driver nintendo_hid_driver = {
2263 .name = "nintendo",
2264 .id_table = nintendo_hid_devices,
2265 .probe = nintendo_hid_probe,
2266 .remove = nintendo_hid_remove,
2267 .raw_event = nintendo_hid_event,
2268};
2269module_hid_driver(nintendo_hid_driver);
2270
2271MODULE_LICENSE("GPL");
2272MODULE_AUTHOR("Daniel J. Ogorchock <djogorchock@gmail.com>");
2273MODULE_DESCRIPTION("Driver for Nintendo Switch Controllers");
4ff5b108 2274