xref: /linux/drivers/hid/hid-nintendo.c (revision 2d7eaeb05ae265bd64270376e6a2c0d80244771f)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * HID driver for Nintendo Switch Joy-Cons and Pro Controllers, as well as
4  * Nintendo Switch 2 Joy-Cons, Pro Controller, and GameCube Controller
5  *
6  * Copyright (c) 2019-2021 Daniel J. Ogorchock <djogorchock@gmail.com>
7  * Portions Copyright (c) 2020 Nadia Holmquist Pedersen <nadia@nhp.sh>
8  * Copyright (c) 2022 Emily Strickland <linux@emily.st>
9  * Copyright (c) 2023 Ryan McClelland <rymcclel@gmail.com>
10  * Copyright (c) 2026 Valve Software
11  *
12  * The following resources/projects were referenced for this driver:
13  *   https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering
14  *   https://gitlab.com/pjranki/joycon-linux-kernel (Peter Rankin)
15  *   https://github.com/FrotBot/SwitchProConLinuxUSB
16  *   https://github.com/MTCKC/ProconXInput
17  *   https://github.com/Davidobot/BetterJoyForCemu
18  *   https://gist.github.com/shinyquagsire23/66f006b46c56216acbaac6c1e2279b64
19  *   https://github.com/ndeadly/switch2_controller_research
20  *   hid-wiimote kernel hid driver
21  *   hid-logitech-hidpp driver
22  *   hid-sony driver
23  *
24  * This driver supports the Nintendo Switch Joy-Cons and Pro Controllers. The
25  * Pro Controllers can either be used over USB or Bluetooth.
26  *
27  * This driver also incorporates support for Nintendo Switch Online controllers
28  * for the NES, SNES, Sega Genesis, and N64.
29  *
30  * The driver will retrieve the factory calibration info from the controllers,
31  * so little to no user calibration should be required.
32  *
33  */
34 
35 #include "hid-ids.h"
36 #include "hid-nintendo.h"
37 #include <linux/unaligned.h>
38 #include <linux/delay.h>
39 #include <linux/device.h>
40 #include <linux/devm-helpers.h>
41 #include <linux/kernel.h>
42 #include <linux/hid.h>
43 #include <linux/idr.h>
44 #include <linux/input.h>
45 #include <linux/jiffies.h>
46 #include <linux/leds.h>
47 #include <linux/module.h>
48 #include <linux/power_supply.h>
49 #include <linux/spinlock.h>
50 #include <linux/usb.h>
51 #include "usbhid/usbhid.h"
52 
53 /*
54  * Reference the url below for the following HID report defines:
55  * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering
56  */
57 
58 /* Output Reports */
59 #define JC_OUTPUT_RUMBLE_AND_SUBCMD	 0x01
60 #define JC_OUTPUT_FW_UPDATE_PKT		 0x03
61 #define JC_OUTPUT_RUMBLE_ONLY		 0x10
62 #define JC_OUTPUT_MCU_DATA		 0x11
63 #define JC_OUTPUT_USB_CMD		 0x80
64 
65 /* Subcommand IDs */
66 #define JC_SUBCMD_STATE			 0x00
67 #define JC_SUBCMD_MANUAL_BT_PAIRING	 0x01
68 #define JC_SUBCMD_REQ_DEV_INFO		 0x02
69 #define JC_SUBCMD_SET_REPORT_MODE	 0x03
70 #define JC_SUBCMD_TRIGGERS_ELAPSED	 0x04
71 #define JC_SUBCMD_GET_PAGE_LIST_STATE	 0x05
72 #define JC_SUBCMD_SET_HCI_STATE		 0x06
73 #define JC_SUBCMD_RESET_PAIRING_INFO	 0x07
74 #define JC_SUBCMD_LOW_POWER_MODE	 0x08
75 #define JC_SUBCMD_SPI_FLASH_READ	 0x10
76 #define JC_SUBCMD_SPI_FLASH_WRITE	 0x11
77 #define JC_SUBCMD_RESET_MCU		 0x20
78 #define JC_SUBCMD_SET_MCU_CONFIG	 0x21
79 #define JC_SUBCMD_SET_MCU_STATE		 0x22
80 #define JC_SUBCMD_SET_PLAYER_LIGHTS	 0x30
81 #define JC_SUBCMD_GET_PLAYER_LIGHTS	 0x31
82 #define JC_SUBCMD_SET_HOME_LIGHT	 0x38
83 #define JC_SUBCMD_ENABLE_IMU		 0x40
84 #define JC_SUBCMD_SET_IMU_SENSITIVITY	 0x41
85 #define JC_SUBCMD_WRITE_IMU_REG		 0x42
86 #define JC_SUBCMD_READ_IMU_REG		 0x43
87 #define JC_SUBCMD_ENABLE_VIBRATION	 0x48
88 #define JC_SUBCMD_GET_REGULATED_VOLTAGE	 0x50
89 
90 /* Input Reports */
91 #define JC_INPUT_BUTTON_EVENT		 0x3F
92 #define JC_INPUT_SUBCMD_REPLY		 0x21
93 #define JC_INPUT_IMU_DATA		 0x30
94 #define JC_INPUT_MCU_DATA		 0x31
95 #define JC_INPUT_USB_RESPONSE		 0x81
96 
97 /* Feature Reports */
98 #define JC_FEATURE_LAST_SUBCMD		 0x02
99 #define JC_FEATURE_OTA_FW_UPGRADE	 0x70
100 #define JC_FEATURE_SETUP_MEM_READ	 0x71
101 #define JC_FEATURE_MEM_READ		 0x72
102 #define JC_FEATURE_ERASE_MEM_SECTOR	 0x73
103 #define JC_FEATURE_MEM_WRITE		 0x74
104 #define JC_FEATURE_LAUNCH		 0x75
105 
106 /* USB Commands */
107 #define JC_USB_CMD_CONN_STATUS		 0x01
108 #define JC_USB_CMD_HANDSHAKE		 0x02
109 #define JC_USB_CMD_BAUDRATE_3M		 0x03
110 #define JC_USB_CMD_NO_TIMEOUT		 0x04
111 #define JC_USB_CMD_EN_TIMEOUT		 0x05
112 #define JC_USB_RESET			 0x06
113 #define JC_USB_PRE_HANDSHAKE		 0x91
114 #define JC_USB_SEND_UART		 0x92
115 
116 /* Magic value denoting presence of user calibration */
117 #define JC_CAL_USR_MAGIC_0		 0xB2
118 #define JC_CAL_USR_MAGIC_1		 0xA1
119 #define JC_CAL_USR_MAGIC_SIZE		 2
120 
121 /* SPI storage addresses of user calibration data */
122 #define JC_CAL_USR_LEFT_MAGIC_ADDR	 0x8010
123 #define JC_CAL_USR_LEFT_DATA_ADDR	 0x8012
124 #define JC_CAL_USR_LEFT_DATA_END	 0x801A
125 #define JC_CAL_USR_RIGHT_MAGIC_ADDR	 0x801B
126 #define JC_CAL_USR_RIGHT_DATA_ADDR	 0x801D
127 #define JC_CAL_STICK_DATA_SIZE \
128 	(JC_CAL_USR_LEFT_DATA_END - JC_CAL_USR_LEFT_DATA_ADDR + 1)
129 
130 /* SPI storage addresses of factory calibration data */
131 #define JC_CAL_FCT_DATA_LEFT_ADDR	 0x603d
132 #define JC_CAL_FCT_DATA_RIGHT_ADDR	 0x6046
133 
134 /* SPI storage addresses of IMU factory calibration data */
135 #define JC_IMU_CAL_FCT_DATA_ADDR	 0x6020
136 #define JC_IMU_CAL_FCT_DATA_END	 0x6037
137 #define JC_IMU_CAL_DATA_SIZE \
138 	(JC_IMU_CAL_FCT_DATA_END - JC_IMU_CAL_FCT_DATA_ADDR + 1)
139 /* SPI storage addresses of IMU user calibration data */
140 #define JC_IMU_CAL_USR_MAGIC_ADDR	 0x8026
141 #define JC_IMU_CAL_USR_DATA_ADDR	 0x8028
142 
143 /* The raw analog joystick values will be mapped in terms of this magnitude */
144 #define JC_MAX_STICK_MAG		 32767
145 #define JC_STICK_FUZZ			 250
146 #define JC_STICK_FLAT			 500
147 
148 /* Hat values for pro controller's d-pad */
149 #define JC_MAX_DPAD_MAG		1
150 #define JC_DPAD_FUZZ		0
151 #define JC_DPAD_FLAT		0
152 
153 /* Under most circumstances IMU reports are pushed every 15ms; use as default */
154 #define JC_IMU_DFLT_AVG_DELTA_MS	15
155 /* How many samples to sum before calculating average IMU report delta */
156 #define JC_IMU_SAMPLES_PER_DELTA_AVG	300
157 /* Controls how many dropped IMU packets at once trigger a warning message */
158 #define JC_IMU_DROPPED_PKT_WARNING	3
159 
160 /*
161  * The controller's accelerometer has a sensor resolution of 16bits and is
162  * configured with a range of +-8000 milliGs. Therefore, the resolution can be
163  * calculated thus: (2^16-1)/(8000 * 2) = 4.096 digits per milliG
164  * Resolution per G (rather than per millliG): 4.096 * 1000 = 4096 digits per G
165  * Alternatively: 1/4096 = .0002441 Gs per digit
166  */
167 #define JC_IMU_MAX_ACCEL_MAG		32767
168 #define JC_IMU_ACCEL_RES_PER_G		4096
169 #define JC_IMU_ACCEL_FUZZ		10
170 #define JC_IMU_ACCEL_FLAT		0
171 
172 /*
173  * The controller's gyroscope has a sensor resolution of 16bits and is
174  * configured with a range of +-2000 degrees/second.
175  * Digits per dps: (2^16 -1)/(2000*2) = 16.38375
176  * dps per digit: 16.38375E-1 = .0610
177  *
178  * STMicro recommends in the datasheet to add 15% to the dps/digit. This allows
179  * the full sensitivity range to be saturated without clipping. This yields more
180  * accurate results, so it's the technique this driver uses.
181  * dps per digit (corrected): .0610 * 1.15 = .0702
182  * digits per dps (corrected): .0702E-1 = 14.247
183  *
184  * Now, 14.247 truncating to 14 loses a lot of precision, so we rescale the
185  * min/max range by 1000.
186  */
187 #define JC_IMU_PREC_RANGE_SCALE	1000
188 /* Note: change mag and res_per_dps if prec_range_scale is ever altered */
189 #define JC_IMU_MAX_GYRO_MAG		32767000 /* (2^16-1)*1000 */
190 #define JC_IMU_GYRO_RES_PER_DPS		14247 /* (14.247*1000) */
191 #define JC_IMU_GYRO_FUZZ		10
192 #define JC_IMU_GYRO_FLAT		0
193 
194 /* frequency/amplitude tables for rumble */
195 struct joycon_rumble_freq_data {
196 	u16 high;
197 	u8 low;
198 	u16 freq; /* Hz*/
199 };
200 
201 struct joycon_rumble_amp_data {
202 	u8 high;
203 	u16 low;
204 	u16 amp;
205 };
206 
207 #if IS_ENABLED(CONFIG_NINTENDO_FF)
208 /*
209  * These tables are from
210  * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/rumble_data_table.md
211  */
212 static const struct joycon_rumble_freq_data joycon_rumble_frequencies[] = {
213 	/* high, low, freq */
214 	{ 0x0000, 0x01,   41 }, { 0x0000, 0x02,   42 }, { 0x0000, 0x03,   43 },
215 	{ 0x0000, 0x04,   44 }, { 0x0000, 0x05,   45 }, { 0x0000, 0x06,   46 },
216 	{ 0x0000, 0x07,   47 }, { 0x0000, 0x08,   48 }, { 0x0000, 0x09,   49 },
217 	{ 0x0000, 0x0A,   50 }, { 0x0000, 0x0B,   51 }, { 0x0000, 0x0C,   52 },
218 	{ 0x0000, 0x0D,   53 }, { 0x0000, 0x0E,   54 }, { 0x0000, 0x0F,   55 },
219 	{ 0x0000, 0x10,   57 }, { 0x0000, 0x11,   58 }, { 0x0000, 0x12,   59 },
220 	{ 0x0000, 0x13,   60 }, { 0x0000, 0x14,   62 }, { 0x0000, 0x15,   63 },
221 	{ 0x0000, 0x16,   64 }, { 0x0000, 0x17,   66 }, { 0x0000, 0x18,   67 },
222 	{ 0x0000, 0x19,   69 }, { 0x0000, 0x1A,   70 }, { 0x0000, 0x1B,   72 },
223 	{ 0x0000, 0x1C,   73 }, { 0x0000, 0x1D,   75 }, { 0x0000, 0x1e,   77 },
224 	{ 0x0000, 0x1f,   78 }, { 0x0000, 0x20,   80 }, { 0x0400, 0x21,   82 },
225 	{ 0x0800, 0x22,   84 }, { 0x0c00, 0x23,   85 }, { 0x1000, 0x24,   87 },
226 	{ 0x1400, 0x25,   89 }, { 0x1800, 0x26,   91 }, { 0x1c00, 0x27,   93 },
227 	{ 0x2000, 0x28,   95 }, { 0x2400, 0x29,   97 }, { 0x2800, 0x2a,   99 },
228 	{ 0x2c00, 0x2b,  102 }, { 0x3000, 0x2c,  104 }, { 0x3400, 0x2d,  106 },
229 	{ 0x3800, 0x2e,  108 }, { 0x3c00, 0x2f,  111 }, { 0x4000, 0x30,  113 },
230 	{ 0x4400, 0x31,  116 }, { 0x4800, 0x32,  118 }, { 0x4c00, 0x33,  121 },
231 	{ 0x5000, 0x34,  123 }, { 0x5400, 0x35,  126 }, { 0x5800, 0x36,  129 },
232 	{ 0x5c00, 0x37,  132 }, { 0x6000, 0x38,  135 }, { 0x6400, 0x39,  137 },
233 	{ 0x6800, 0x3a,  141 }, { 0x6c00, 0x3b,  144 }, { 0x7000, 0x3c,  147 },
234 	{ 0x7400, 0x3d,  150 }, { 0x7800, 0x3e,  153 }, { 0x7c00, 0x3f,  157 },
235 	{ 0x8000, 0x40,  160 }, { 0x8400, 0x41,  164 }, { 0x8800, 0x42,  167 },
236 	{ 0x8c00, 0x43,  171 }, { 0x9000, 0x44,  174 }, { 0x9400, 0x45,  178 },
237 	{ 0x9800, 0x46,  182 }, { 0x9c00, 0x47,  186 }, { 0xa000, 0x48,  190 },
238 	{ 0xa400, 0x49,  194 }, { 0xa800, 0x4a,  199 }, { 0xac00, 0x4b,  203 },
239 	{ 0xb000, 0x4c,  207 }, { 0xb400, 0x4d,  212 }, { 0xb800, 0x4e,  217 },
240 	{ 0xbc00, 0x4f,  221 }, { 0xc000, 0x50,  226 }, { 0xc400, 0x51,  231 },
241 	{ 0xc800, 0x52,  236 }, { 0xcc00, 0x53,  241 }, { 0xd000, 0x54,  247 },
242 	{ 0xd400, 0x55,  252 }, { 0xd800, 0x56,  258 }, { 0xdc00, 0x57,  263 },
243 	{ 0xe000, 0x58,  269 }, { 0xe400, 0x59,  275 }, { 0xe800, 0x5a,  281 },
244 	{ 0xec00, 0x5b,  287 }, { 0xf000, 0x5c,  293 }, { 0xf400, 0x5d,  300 },
245 	{ 0xf800, 0x5e,  306 }, { 0xfc00, 0x5f,  313 }, { 0x0001, 0x60,  320 },
246 	{ 0x0401, 0x61,  327 }, { 0x0801, 0x62,  334 }, { 0x0c01, 0x63,  341 },
247 	{ 0x1001, 0x64,  349 }, { 0x1401, 0x65,  357 }, { 0x1801, 0x66,  364 },
248 	{ 0x1c01, 0x67,  372 }, { 0x2001, 0x68,  381 }, { 0x2401, 0x69,  389 },
249 	{ 0x2801, 0x6a,  397 }, { 0x2c01, 0x6b,  406 }, { 0x3001, 0x6c,  415 },
250 	{ 0x3401, 0x6d,  424 }, { 0x3801, 0x6e,  433 }, { 0x3c01, 0x6f,  443 },
251 	{ 0x4001, 0x70,  453 }, { 0x4401, 0x71,  462 }, { 0x4801, 0x72,  473 },
252 	{ 0x4c01, 0x73,  483 }, { 0x5001, 0x74,  494 }, { 0x5401, 0x75,  504 },
253 	{ 0x5801, 0x76,  515 }, { 0x5c01, 0x77,  527 }, { 0x6001, 0x78,  538 },
254 	{ 0x6401, 0x79,  550 }, { 0x6801, 0x7a,  562 }, { 0x6c01, 0x7b,  574 },
255 	{ 0x7001, 0x7c,  587 }, { 0x7401, 0x7d,  600 }, { 0x7801, 0x7e,  613 },
256 	{ 0x7c01, 0x7f,  626 }, { 0x8001, 0x00,  640 }, { 0x8401, 0x00,  654 },
257 	{ 0x8801, 0x00,  668 }, { 0x8c01, 0x00,  683 }, { 0x9001, 0x00,  698 },
258 	{ 0x9401, 0x00,  713 }, { 0x9801, 0x00,  729 }, { 0x9c01, 0x00,  745 },
259 	{ 0xa001, 0x00,  761 }, { 0xa401, 0x00,  778 }, { 0xa801, 0x00,  795 },
260 	{ 0xac01, 0x00,  812 }, { 0xb001, 0x00,  830 }, { 0xb401, 0x00,  848 },
261 	{ 0xb801, 0x00,  867 }, { 0xbc01, 0x00,  886 }, { 0xc001, 0x00,  905 },
262 	{ 0xc401, 0x00,  925 }, { 0xc801, 0x00,  945 }, { 0xcc01, 0x00,  966 },
263 	{ 0xd001, 0x00,  987 }, { 0xd401, 0x00, 1009 }, { 0xd801, 0x00, 1031 },
264 	{ 0xdc01, 0x00, 1053 }, { 0xe001, 0x00, 1076 }, { 0xe401, 0x00, 1100 },
265 	{ 0xe801, 0x00, 1124 }, { 0xec01, 0x00, 1149 }, { 0xf001, 0x00, 1174 },
266 	{ 0xf401, 0x00, 1199 }, { 0xf801, 0x00, 1226 }, { 0xfc01, 0x00, 1253 }
267 };
268 
269 #define joycon_max_rumble_amp	(1003)
270 static const struct joycon_rumble_amp_data joycon_rumble_amplitudes[] = {
271 	/* high, low, amp */
272 	{ 0x00, 0x0040,    0 },
273 	{ 0x02, 0x8040,   10 }, { 0x04, 0x0041,   12 }, { 0x06, 0x8041,   14 },
274 	{ 0x08, 0x0042,   17 }, { 0x0a, 0x8042,   20 }, { 0x0c, 0x0043,   24 },
275 	{ 0x0e, 0x8043,   28 }, { 0x10, 0x0044,   33 }, { 0x12, 0x8044,   40 },
276 	{ 0x14, 0x0045,   47 }, { 0x16, 0x8045,   56 }, { 0x18, 0x0046,   67 },
277 	{ 0x1a, 0x8046,   80 }, { 0x1c, 0x0047,   95 }, { 0x1e, 0x8047,  112 },
278 	{ 0x20, 0x0048,  117 }, { 0x22, 0x8048,  123 }, { 0x24, 0x0049,  128 },
279 	{ 0x26, 0x8049,  134 }, { 0x28, 0x004a,  140 }, { 0x2a, 0x804a,  146 },
280 	{ 0x2c, 0x004b,  152 }, { 0x2e, 0x804b,  159 }, { 0x30, 0x004c,  166 },
281 	{ 0x32, 0x804c,  173 }, { 0x34, 0x004d,  181 }, { 0x36, 0x804d,  189 },
282 	{ 0x38, 0x004e,  198 }, { 0x3a, 0x804e,  206 }, { 0x3c, 0x004f,  215 },
283 	{ 0x3e, 0x804f,  225 }, { 0x40, 0x0050,  230 }, { 0x42, 0x8050,  235 },
284 	{ 0x44, 0x0051,  240 }, { 0x46, 0x8051,  245 }, { 0x48, 0x0052,  251 },
285 	{ 0x4a, 0x8052,  256 }, { 0x4c, 0x0053,  262 }, { 0x4e, 0x8053,  268 },
286 	{ 0x50, 0x0054,  273 }, { 0x52, 0x8054,  279 }, { 0x54, 0x0055,  286 },
287 	{ 0x56, 0x8055,  292 }, { 0x58, 0x0056,  298 }, { 0x5a, 0x8056,  305 },
288 	{ 0x5c, 0x0057,  311 }, { 0x5e, 0x8057,  318 }, { 0x60, 0x0058,  325 },
289 	{ 0x62, 0x8058,  332 }, { 0x64, 0x0059,  340 }, { 0x66, 0x8059,  347 },
290 	{ 0x68, 0x005a,  355 }, { 0x6a, 0x805a,  362 }, { 0x6c, 0x005b,  370 },
291 	{ 0x6e, 0x805b,  378 }, { 0x70, 0x005c,  387 }, { 0x72, 0x805c,  395 },
292 	{ 0x74, 0x005d,  404 }, { 0x76, 0x805d,  413 }, { 0x78, 0x005e,  422 },
293 	{ 0x7a, 0x805e,  431 }, { 0x7c, 0x005f,  440 }, { 0x7e, 0x805f,  450 },
294 	{ 0x80, 0x0060,  460 }, { 0x82, 0x8060,  470 }, { 0x84, 0x0061,  480 },
295 	{ 0x86, 0x8061,  491 }, { 0x88, 0x0062,  501 }, { 0x8a, 0x8062,  512 },
296 	{ 0x8c, 0x0063,  524 }, { 0x8e, 0x8063,  535 }, { 0x90, 0x0064,  547 },
297 	{ 0x92, 0x8064,  559 }, { 0x94, 0x0065,  571 }, { 0x96, 0x8065,  584 },
298 	{ 0x98, 0x0066,  596 }, { 0x9a, 0x8066,  609 }, { 0x9c, 0x0067,  623 },
299 	{ 0x9e, 0x8067,  636 }, { 0xa0, 0x0068,  650 }, { 0xa2, 0x8068,  665 },
300 	{ 0xa4, 0x0069,  679 }, { 0xa6, 0x8069,  694 }, { 0xa8, 0x006a,  709 },
301 	{ 0xaa, 0x806a,  725 }, { 0xac, 0x006b,  741 }, { 0xae, 0x806b,  757 },
302 	{ 0xb0, 0x006c,  773 }, { 0xb2, 0x806c,  790 }, { 0xb4, 0x006d,  808 },
303 	{ 0xb6, 0x806d,  825 }, { 0xb8, 0x006e,  843 }, { 0xba, 0x806e,  862 },
304 	{ 0xbc, 0x006f,  881 }, { 0xbe, 0x806f,  900 }, { 0xc0, 0x0070,  920 },
305 	{ 0xc2, 0x8070,  940 }, { 0xc4, 0x0071,  960 }, { 0xc6, 0x8071,  981 },
306 	{ 0xc8, 0x0072, joycon_max_rumble_amp }
307 };
308 static const u16 JC_RUMBLE_DFLT_LOW_FREQ = 160;
309 static const u16 JC_RUMBLE_DFLT_HIGH_FREQ = 320;
310 static const unsigned short JC_RUMBLE_ZERO_AMP_PKT_CNT = 5;
311 #endif /* IS_ENABLED(CONFIG_NINTENDO_FF) */
312 static const u16 JC_RUMBLE_PERIOD_MS = 50;
313 
314 /* States for controller state machine */
315 enum joycon_ctlr_state {
316 	JOYCON_CTLR_STATE_INIT,
317 	JOYCON_CTLR_STATE_READ,
318 	JOYCON_CTLR_STATE_REMOVED,
319 	JOYCON_CTLR_STATE_SUSPENDED,
320 };
321 
322 /* Controller type received as part of device info */
323 enum joycon_ctlr_type {
324 	JOYCON_CTLR_TYPE_JCL  = 0x01,
325 	JOYCON_CTLR_TYPE_JCR  = 0x02,
326 	JOYCON_CTLR_TYPE_PRO  = 0x03,
327 	JOYCON_CTLR_TYPE_LIC_PRO = 0x06,
328 	JOYCON_CTLR_TYPE_NESL = 0x09,
329 	JOYCON_CTLR_TYPE_NESR = 0x0A,
330 	JOYCON_CTLR_TYPE_SNES = 0x0B,
331 	JOYCON_CTLR_TYPE_GEN  = 0x0D,
332 	JOYCON_CTLR_TYPE_N64  = 0x0C,
333 };
334 
335 struct joycon_stick_cal {
336 	s32 max;
337 	s32 min;
338 	s32 center;
339 };
340 
341 struct joycon_imu_cal {
342 	s16 offset[3];
343 	s16 scale[3];
344 };
345 
346 /*
347  * All the controller's button values are stored in a u32.
348  * They can be accessed with bitwise ANDs.
349  */
350 #define JC_BTN_Y	 BIT(0)
351 #define JC_BTN_X	 BIT(1)
352 #define JC_BTN_B	 BIT(2)
353 #define JC_BTN_A	 BIT(3)
354 #define JC_BTN_SR_R	 BIT(4)
355 #define JC_BTN_SL_R	 BIT(5)
356 #define JC_BTN_R	 BIT(6)
357 #define JC_BTN_ZR	 BIT(7)
358 #define JC_BTN_MINUS	 BIT(8)
359 #define JC_BTN_PLUS	 BIT(9)
360 #define JC_BTN_RSTICK	 BIT(10)
361 #define JC_BTN_LSTICK	 BIT(11)
362 #define JC_BTN_HOME	 BIT(12)
363 #define JC_BTN_CAP	 BIT(13) /* capture button */
364 #define JC_BTN_DOWN	 BIT(16)
365 #define JC_BTN_UP	 BIT(17)
366 #define JC_BTN_RIGHT	 BIT(18)
367 #define JC_BTN_LEFT	 BIT(19)
368 #define JC_BTN_SR_L	 BIT(20)
369 #define JC_BTN_SL_L	 BIT(21)
370 #define JC_BTN_L	 BIT(22)
371 #define JC_BTN_ZL	 BIT(23)
372 
373 struct joycon_ctlr_button_mapping {
374 	u32 code;
375 	u32 bit;
376 };
377 
378 /*
379  * D-pad is configured as buttons for the left Joy-Con only!
380  */
381 static const struct joycon_ctlr_button_mapping left_joycon_button_mappings[] = {
382 	{ BTN_TL,		JC_BTN_L,	},
383 	{ BTN_TL2,		JC_BTN_ZL,	},
384 	{ BTN_SELECT,		JC_BTN_MINUS,	},
385 	{ BTN_THUMBL,		JC_BTN_LSTICK,	},
386 	{ BTN_DPAD_UP,		JC_BTN_UP,	},
387 	{ BTN_DPAD_DOWN,	JC_BTN_DOWN,	},
388 	{ BTN_DPAD_LEFT,	JC_BTN_LEFT,	},
389 	{ BTN_DPAD_RIGHT,	JC_BTN_RIGHT,	},
390 	{ BTN_Z,		JC_BTN_CAP,	},
391 	{ /* sentinel */ },
392 };
393 
394 /*
395  * The unused *right*-side triggers become the SL/SR triggers for the *left*
396  * Joy-Con, if and only if we're not using a charging grip.
397  */
398 static const struct joycon_ctlr_button_mapping left_joycon_s_button_mappings[] = {
399 	{ BTN_TR,	JC_BTN_SL_L,	},
400 	{ BTN_TR2,	JC_BTN_SR_L,	},
401 	{ /* sentinel */ },
402 };
403 
404 static const struct joycon_ctlr_button_mapping right_joycon_button_mappings[] = {
405 	{ BTN_EAST,	JC_BTN_A,	},
406 	{ BTN_SOUTH,	JC_BTN_B,	},
407 	{ BTN_NORTH,	JC_BTN_X,	},
408 	{ BTN_WEST,	JC_BTN_Y,	},
409 	{ BTN_TR,	JC_BTN_R,	},
410 	{ BTN_TR2,	JC_BTN_ZR,	},
411 	{ BTN_START,	JC_BTN_PLUS,	},
412 	{ BTN_THUMBR,	JC_BTN_RSTICK,	},
413 	{ BTN_MODE,	JC_BTN_HOME,	},
414 	{ /* sentinel */ },
415 };
416 
417 /*
418  * The unused *left*-side triggers become the SL/SR triggers for the *right*
419  * Joy-Con, if and only if we're not using a charging grip.
420  */
421 static const struct joycon_ctlr_button_mapping right_joycon_s_button_mappings[] = {
422 	{ BTN_TL,	JC_BTN_SL_R,	},
423 	{ BTN_TL2,	JC_BTN_SR_R,	},
424 	{ /* sentinel */ },
425 };
426 
427 static const struct joycon_ctlr_button_mapping procon_button_mappings[] = {
428 	{ BTN_EAST,	JC_BTN_A,	},
429 	{ BTN_SOUTH,	JC_BTN_B,	},
430 	{ BTN_NORTH,	JC_BTN_X,	},
431 	{ BTN_WEST,	JC_BTN_Y,	},
432 	{ BTN_TL,	JC_BTN_L,	},
433 	{ BTN_TR,	JC_BTN_R,	},
434 	{ BTN_TL2,	JC_BTN_ZL,	},
435 	{ BTN_TR2,	JC_BTN_ZR,	},
436 	{ BTN_SELECT,	JC_BTN_MINUS,	},
437 	{ BTN_START,	JC_BTN_PLUS,	},
438 	{ BTN_THUMBL,	JC_BTN_LSTICK,	},
439 	{ BTN_THUMBR,	JC_BTN_RSTICK,	},
440 	{ BTN_MODE,	JC_BTN_HOME,	},
441 	{ BTN_Z,	JC_BTN_CAP,	},
442 	{ /* sentinel */ },
443 };
444 
445 /* HORI Licensed Pro Controllers swap X/Y bits in the report */
446 static const struct joycon_ctlr_button_mapping lic_hori_procon_button_mappings[] = {
447 	{ BTN_EAST,	JC_BTN_A,	},
448 	{ BTN_SOUTH,	JC_BTN_B,	},
449 	{ BTN_NORTH,	JC_BTN_Y,	},
450 	{ BTN_WEST,	JC_BTN_X,	},
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 	{ BTN_THUMBL,	JC_BTN_LSTICK,	},
458 	{ BTN_THUMBR,	JC_BTN_RSTICK,	},
459 	{ BTN_MODE,	JC_BTN_HOME,	},
460 	{ BTN_Z,	JC_BTN_CAP,	},
461 	{ /* sentinel */ },
462 };
463 
464 static const struct joycon_ctlr_button_mapping nescon_button_mappings[] = {
465 	{ BTN_SOUTH,	JC_BTN_A,	},
466 	{ BTN_EAST,	JC_BTN_B,	},
467 	{ BTN_TL,	JC_BTN_L,	},
468 	{ BTN_TR,	JC_BTN_R,	},
469 	{ BTN_SELECT,	JC_BTN_MINUS,	},
470 	{ BTN_START,	JC_BTN_PLUS,	},
471 	{ /* sentinel */ },
472 };
473 
474 static const struct joycon_ctlr_button_mapping snescon_button_mappings[] = {
475 	{ BTN_EAST,	JC_BTN_A,	},
476 	{ BTN_SOUTH,	JC_BTN_B,	},
477 	{ BTN_NORTH,	JC_BTN_X,	},
478 	{ BTN_WEST,	JC_BTN_Y,	},
479 	{ BTN_TL,	JC_BTN_L,	},
480 	{ BTN_TR,	JC_BTN_R,	},
481 	{ BTN_TL2,	JC_BTN_ZL,	},
482 	{ BTN_TR2,	JC_BTN_ZR,	},
483 	{ BTN_SELECT,	JC_BTN_MINUS,	},
484 	{ BTN_START,	JC_BTN_PLUS,	},
485 	{ /* sentinel */ },
486 };
487 
488 static const struct joycon_ctlr_button_mapping gencon_button_mappings[] = {
489 	{ BTN_WEST,	JC_BTN_A,	}, /* A */
490 	{ BTN_SOUTH,	JC_BTN_B,	}, /* B */
491 	{ BTN_EAST,	JC_BTN_R,	}, /* C */
492 	{ BTN_TL,	JC_BTN_X,	}, /* X MD/GEN 6B Only */
493 	{ BTN_NORTH,	JC_BTN_Y,	}, /* Y MD/GEN 6B Only */
494 	{ BTN_TR,	JC_BTN_L,	}, /* Z MD/GEN 6B Only */
495 	{ BTN_SELECT,	JC_BTN_ZR,	}, /* Mode */
496 	{ BTN_START,	JC_BTN_PLUS,	},
497 	{ BTN_MODE,	JC_BTN_HOME,	},
498 	{ BTN_Z,	JC_BTN_CAP,	},
499 	{ /* sentinel */ },
500 };
501 
502 static const struct joycon_ctlr_button_mapping n64con_button_mappings[] = {
503 	{ BTN_A,		JC_BTN_A,	},
504 	{ BTN_B,		JC_BTN_B,	},
505 	{ BTN_TL2,		JC_BTN_ZL,	}, /* Z */
506 	{ BTN_TL,		JC_BTN_L,	},
507 	{ BTN_TR,		JC_BTN_R,	},
508 	{ BTN_TR2,		JC_BTN_LSTICK,	}, /* ZR */
509 	{ BTN_START,		JC_BTN_PLUS,	},
510 	{ BTN_SELECT,		JC_BTN_Y,	}, /* C UP */
511 	{ BTN_X,		JC_BTN_ZR,	}, /* C DOWN */
512 	{ BTN_Y,		JC_BTN_X,	}, /* C LEFT */
513 	{ BTN_C,		JC_BTN_MINUS,	}, /* C RIGHT */
514 	{ BTN_MODE,		JC_BTN_HOME,	},
515 	{ BTN_Z,		JC_BTN_CAP,	},
516 	{ /* sentinel */ },
517 };
518 
519 enum joycon_msg_type {
520 	JOYCON_MSG_TYPE_NONE,
521 	JOYCON_MSG_TYPE_USB,
522 	JOYCON_MSG_TYPE_SUBCMD,
523 };
524 
525 struct joycon_rumble_output {
526 	u8 output_id;
527 	u8 packet_num;
528 	u8 rumble_data[8];
529 } __packed;
530 
531 struct joycon_subcmd_request {
532 	u8 output_id; /* must be 0x01 for subcommand, 0x10 for rumble only */
533 	u8 packet_num; /* incremented every send */
534 	u8 rumble_data[8];
535 	u8 subcmd_id;
536 	u8 data[]; /* length depends on the subcommand */
537 } __packed;
538 
539 struct joycon_subcmd_reply {
540 	u8 ack; /* MSB 1 for ACK, 0 for NACK */
541 	u8 id; /* id of requested subcmd */
542 	u8 data[]; /* will be at most 35 bytes */
543 } __packed;
544 
545 struct joycon_imu_data {
546 	s16 accel_x;
547 	s16 accel_y;
548 	s16 accel_z;
549 	s16 gyro_x;
550 	s16 gyro_y;
551 	s16 gyro_z;
552 } __packed;
553 
554 struct joycon_input_report {
555 	u8 id;
556 	u8 timer;
557 	u8 bat_con; /* battery and connection info */
558 	u8 button_status[3];
559 	u8 left_stick[3];
560 	u8 right_stick[3];
561 	u8 vibrator_report;
562 
563 	union {
564 		struct joycon_subcmd_reply subcmd_reply;
565 		/* IMU input reports contain 3 samples */
566 		u8 imu_raw_bytes[sizeof(struct joycon_imu_data) * 3];
567 	};
568 } __packed;
569 
570 #define JC_MAX_RESP_SIZE	(sizeof(struct joycon_input_report) + 35)
571 #define JC_RUMBLE_DATA_SIZE	8
572 #define JC_RUMBLE_QUEUE_SIZE	8
573 
574 static const char * const joycon_player_led_names[] = {
575 	LED_FUNCTION_PLAYER1,
576 	LED_FUNCTION_PLAYER2,
577 	LED_FUNCTION_PLAYER3,
578 	LED_FUNCTION_PLAYER4,
579 };
580 #define JC_NUM_LEDS		ARRAY_SIZE(joycon_player_led_names)
581 #define JC_NUM_LED_PATTERNS 8
582 /* Taken from https://www.nintendo.com/my/support/qa/detail/33822 */
583 static const enum led_brightness joycon_player_led_patterns[JC_NUM_LED_PATTERNS][JC_NUM_LEDS] = {
584 	{ 1, 0, 0, 0 },
585 	{ 1, 1, 0, 0 },
586 	{ 1, 1, 1, 0 },
587 	{ 1, 1, 1, 1 },
588 	{ 1, 0, 0, 1 },
589 	{ 1, 0, 1, 0 },
590 	{ 1, 0, 1, 1 },
591 	{ 0, 1, 1, 0 },
592 };
593 
594 /* Each physical controller is associated with a joycon_ctlr struct */
595 struct joycon_ctlr {
596 	struct hid_device *hdev;
597 	struct input_dev *input;
598 	u32 player_id;
599 	struct led_classdev leds[JC_NUM_LEDS]; /* player leds */
600 	struct led_classdev home_led;
601 	enum joycon_ctlr_state ctlr_state;
602 	spinlock_t lock;
603 	u8 mac_addr[6];
604 	char *mac_addr_str;
605 	enum joycon_ctlr_type ctlr_type;
606 
607 	/* The following members are used for synchronous sends/receives */
608 	enum joycon_msg_type msg_type;
609 	u8 subcmd_num;
610 	struct mutex output_mutex;
611 	u8 input_buf[JC_MAX_RESP_SIZE];
612 	wait_queue_head_t wait;
613 	bool received_resp;
614 	u8 usb_ack_match;
615 	u8 subcmd_ack_match;
616 	bool received_input_report;
617 	unsigned int last_input_report_msecs;
618 	unsigned int last_subcmd_sent_msecs;
619 	unsigned int consecutive_valid_report_deltas;
620 	unsigned int subcmd_rate_exhaustions;
621 	bool subcmd_rate_relaxed;
622 
623 	/* factory calibration data */
624 	struct joycon_stick_cal left_stick_cal_x;
625 	struct joycon_stick_cal left_stick_cal_y;
626 	struct joycon_stick_cal right_stick_cal_x;
627 	struct joycon_stick_cal right_stick_cal_y;
628 
629 	struct joycon_imu_cal accel_cal;
630 	struct joycon_imu_cal gyro_cal;
631 
632 	/* prevents needlessly recalculating these divisors every sample */
633 	s32 imu_cal_accel_divisor[3];
634 	s32 imu_cal_gyro_divisor[3];
635 
636 	/* power supply data */
637 	struct power_supply *battery;
638 	struct power_supply_desc battery_desc;
639 	u8 battery_capacity;
640 	bool battery_charging;
641 	bool host_powered;
642 
643 	/* rumble */
644 	u8 rumble_data[JC_RUMBLE_QUEUE_SIZE][JC_RUMBLE_DATA_SIZE];
645 	int rumble_queue_head;
646 	int rumble_queue_tail;
647 	struct workqueue_struct *rumble_queue;
648 	struct work_struct rumble_worker;
649 	unsigned int rumble_msecs;
650 	u16 rumble_ll_freq;
651 	u16 rumble_lh_freq;
652 	u16 rumble_rl_freq;
653 	u16 rumble_rh_freq;
654 	unsigned short rumble_zero_countdown;
655 
656 	/* imu */
657 	struct input_dev *imu_input;
658 	bool imu_first_packet_received; /* helps in initiating timestamp */
659 	unsigned int imu_timestamp_us; /* timestamp we report to userspace */
660 	unsigned int imu_last_pkt_ms; /* used to calc imu report delta */
661 	/* the following are used to track the average imu report time delta */
662 	unsigned int imu_delta_samples_count;
663 	unsigned int imu_delta_samples_sum;
664 	unsigned int imu_avg_delta_ms;
665 };
666 
667 /* Helper macros for checking controller type */
668 #define jc_type_is_joycon(ctlr) \
669 	(ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONL || \
670 	 ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONR || \
671 	 ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_CHRGGRIP)
672 #define jc_type_is_procon(ctlr) \
673 	(ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_PROCON)
674 #define jc_type_is_chrggrip(ctlr) \
675 	(ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_CHRGGRIP)
676 
677 /* Does this controller have inputs associated with left joycon? */
678 #define jc_type_has_left(ctlr) \
679 	(ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCL || \
680 	 ctlr->ctlr_type == JOYCON_CTLR_TYPE_PRO || \
681 	 ctlr->ctlr_type == JOYCON_CTLR_TYPE_N64)
682 
683 /* Does this controller have inputs associated with right joycon? */
684 #define jc_type_has_right(ctlr) \
685 	(ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCR || \
686 	 ctlr->ctlr_type == JOYCON_CTLR_TYPE_PRO)
687 
688 /*
689  * Controller device helpers
690  *
691  * These look at the device ID known to the HID subsystem to identify a device,
692  * but take caution: some NSO devices lie about themselves (NES Joy-Cons and
693  * Sega Genesis controller). See type helpers below.
694  *
695  * These helpers are most useful early during the HID probe or in conjunction
696  * with the capability helpers below.
697  */
698 static inline bool joycon_device_is_chrggrip(struct joycon_ctlr *ctlr)
699 {
700 	return ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_CHRGGRIP;
701 }
702 
703 /*
704  * Controller type helpers
705  *
706  * These are slightly different than the device-ID-based helpers above. They are
707  * generally more reliable, since they can distinguish between, e.g., Genesis
708  * versus SNES, or NES Joy-Cons versus regular Switch Joy-Cons. They're most
709  * useful for reporting available inputs. For other kinds of distinctions, see
710  * the capability helpers below.
711  *
712  * They have two major drawbacks: (1) they're not available until after we set
713  * the reporting method and then request the device info; (2) they can't
714  * distinguish all controllers (like the Charging Grip from the Pro controller.)
715  */
716 static inline bool joycon_type_is_left_joycon(struct joycon_ctlr *ctlr)
717 {
718 	return ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCL;
719 }
720 
721 static inline bool joycon_type_is_right_joycon(struct joycon_ctlr *ctlr)
722 {
723 	return ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCR;
724 }
725 
726 static inline bool joycon_type_is_procon(struct joycon_ctlr *ctlr)
727 {
728 	return ctlr->ctlr_type == JOYCON_CTLR_TYPE_PRO ||
729 	       ctlr->ctlr_type == JOYCON_CTLR_TYPE_LIC_PRO;
730 }
731 
732 static inline bool joycon_type_is_snescon(struct joycon_ctlr *ctlr)
733 {
734 	return ctlr->ctlr_type == JOYCON_CTLR_TYPE_SNES;
735 }
736 
737 static inline bool joycon_type_is_gencon(struct joycon_ctlr *ctlr)
738 {
739 	return ctlr->ctlr_type == JOYCON_CTLR_TYPE_GEN;
740 }
741 
742 static inline bool joycon_type_is_n64con(struct joycon_ctlr *ctlr)
743 {
744 	return ctlr->ctlr_type == JOYCON_CTLR_TYPE_N64;
745 }
746 
747 static inline bool joycon_type_is_left_nescon(struct joycon_ctlr *ctlr)
748 {
749 	return ctlr->ctlr_type == JOYCON_CTLR_TYPE_NESL;
750 }
751 
752 static inline bool joycon_type_is_right_nescon(struct joycon_ctlr *ctlr)
753 {
754 	return ctlr->ctlr_type == JOYCON_CTLR_TYPE_NESR;
755 }
756 
757 static inline bool joycon_type_is_any_joycon(struct joycon_ctlr *ctlr)
758 {
759 	return joycon_type_is_left_joycon(ctlr) ||
760 	       joycon_type_is_right_joycon(ctlr) ||
761 	       joycon_device_is_chrggrip(ctlr);
762 }
763 
764 static inline bool joycon_type_is_any_nescon(struct joycon_ctlr *ctlr)
765 {
766 	return joycon_type_is_left_nescon(ctlr) ||
767 	       joycon_type_is_right_nescon(ctlr);
768 }
769 
770 /*
771  * Controller capability helpers
772  *
773  * These helpers combine the use of the helpers above to detect certain
774  * capabilities during initialization. They are always accurate but (since they
775  * use type helpers) cannot be used early in the HID probe.
776  */
777 static inline bool joycon_has_imu(struct joycon_ctlr *ctlr)
778 {
779 	return joycon_device_is_chrggrip(ctlr) ||
780 	       joycon_type_is_any_joycon(ctlr) ||
781 	       joycon_type_is_procon(ctlr);
782 }
783 
784 static inline bool joycon_has_joysticks(struct joycon_ctlr *ctlr)
785 {
786 	return joycon_device_is_chrggrip(ctlr) ||
787 	       joycon_type_is_any_joycon(ctlr) ||
788 	       joycon_type_is_procon(ctlr) ||
789 	       joycon_type_is_n64con(ctlr);
790 }
791 
792 static inline bool joycon_has_rumble(struct joycon_ctlr *ctlr)
793 {
794 	return joycon_device_is_chrggrip(ctlr) ||
795 	       joycon_type_is_any_joycon(ctlr) ||
796 	       joycon_type_is_procon(ctlr) ||
797 	       joycon_type_is_n64con(ctlr);
798 }
799 
800 static inline bool joycon_using_usb(struct joycon_ctlr *ctlr)
801 {
802 	return ctlr->hdev->bus == BUS_USB;
803 }
804 
805 static int __joycon_hid_send(struct hid_device *hdev, u8 *data, size_t len)
806 {
807 	u8 *buf;
808 	int ret;
809 
810 	buf = kmemdup(data, len, GFP_KERNEL);
811 	if (!buf)
812 		return -ENOMEM;
813 	ret = hid_hw_output_report(hdev, buf, len);
814 	kfree(buf);
815 	if (ret < 0)
816 		hid_dbg(hdev, "Failed to send output report ret=%d\n", ret);
817 	return ret;
818 }
819 
820 static void joycon_wait_for_input_report(struct joycon_ctlr *ctlr)
821 {
822 	int ret;
823 
824 	/*
825 	 * If we are in the proper reporting mode, wait for an input
826 	 * report prior to sending the subcommand. This improves
827 	 * reliability considerably.
828 	 */
829 	if (ctlr->ctlr_state == JOYCON_CTLR_STATE_READ) {
830 		unsigned long flags;
831 
832 		spin_lock_irqsave(&ctlr->lock, flags);
833 		ctlr->received_input_report = false;
834 		spin_unlock_irqrestore(&ctlr->lock, flags);
835 		ret = wait_event_timeout(ctlr->wait,
836 					 ctlr->received_input_report,
837 					 HZ / 4);
838 		/* We will still proceed, even with a timeout here */
839 		if (!ret)
840 			hid_warn(ctlr->hdev,
841 				 "timeout waiting for input report\n");
842 	}
843 }
844 
845 /*
846  * Sending subcommands and/or rumble data at too high a rate can cause bluetooth
847  * controller disconnections.
848  */
849 #define JC_INPUT_REPORT_MIN_DELTA	8
850 #define JC_INPUT_REPORT_MAX_DELTA	17
851 #define JC_SUBCMD_TX_OFFSET_MS		4
852 #define JC_SUBCMD_VALID_DELTA_REQ	3
853 #define JC_SUBCMD_RATE_MAX_ATTEMPTS	25
854 #define JC_SUBCMD_RATE_MAX_FAILURES	4
855 #define JC_SUBCMD_RATE_LIMITER_USB_MS	20
856 #define JC_SUBCMD_RATE_LIMITER_BT_MS	60
857 #define JC_SUBCMD_RATE_LIMITER_MS(ctlr)	((ctlr)->hdev->bus == BUS_USB ? JC_SUBCMD_RATE_LIMITER_USB_MS : JC_SUBCMD_RATE_LIMITER_BT_MS)
858 static void joycon_enforce_subcmd_rate_strict(struct joycon_ctlr *ctlr)
859 {
860 	unsigned int current_ms;
861 	unsigned long subcmd_delta;
862 	int consecutive_valid_deltas = 0;
863 	int attempts = 0;
864 	unsigned long flags;
865 
866 	if (unlikely(ctlr->ctlr_state != JOYCON_CTLR_STATE_READ))
867 		return;
868 
869 	do {
870 		joycon_wait_for_input_report(ctlr);
871 		current_ms = jiffies_to_msecs(jiffies);
872 		subcmd_delta = current_ms - ctlr->last_subcmd_sent_msecs;
873 
874 		spin_lock_irqsave(&ctlr->lock, flags);
875 		consecutive_valid_deltas = ctlr->consecutive_valid_report_deltas;
876 		spin_unlock_irqrestore(&ctlr->lock, flags);
877 
878 		attempts++;
879 	} while ((consecutive_valid_deltas < JC_SUBCMD_VALID_DELTA_REQ ||
880 		  subcmd_delta < JC_SUBCMD_RATE_LIMITER_MS(ctlr)) &&
881 		 ctlr->ctlr_state == JOYCON_CTLR_STATE_READ &&
882 		 attempts < JC_SUBCMD_RATE_MAX_ATTEMPTS);
883 
884 	if (attempts >= JC_SUBCMD_RATE_MAX_ATTEMPTS) {
885 		hid_warn(ctlr->hdev, "%s: exceeded max attempts", __func__);
886 
887 		if (++ctlr->subcmd_rate_exhaustions == JC_SUBCMD_RATE_MAX_FAILURES) {
888 			ctlr->subcmd_rate_relaxed = true;
889 			hid_info(ctlr->hdev,
890 				 "input report cadence does not fit the %d-%dms window; using the legacy subcommand throttle\n",
891 				 JC_INPUT_REPORT_MIN_DELTA,
892 				 JC_INPUT_REPORT_MAX_DELTA);
893 		}
894 		return;
895 	}
896 
897 	ctlr->last_subcmd_sent_msecs = current_ms;
898 
899 	/*
900 	 * Wait a short time after receiving an input report before
901 	 * transmitting. This should reduce odds of a TX coinciding with an RX.
902 	 * Minimizing concurrent BT traffic with the controller seems to lower
903 	 * the rate of disconnections.
904 	 */
905 	msleep(JC_SUBCMD_TX_OFFSET_MS);
906 }
907 
908 /* The rate limiter as it was before commit d750d1480362, without the report
909  * cadence requirement.
910  */
911 static void joycon_enforce_subcmd_rate_legacy(struct joycon_ctlr *ctlr)
912 {
913 	static const unsigned int max_subcmd_rate_ms = 25;
914 	unsigned int current_ms = jiffies_to_msecs(jiffies);
915 	unsigned int delta_ms = current_ms - ctlr->last_subcmd_sent_msecs;
916 
917 	while (delta_ms < max_subcmd_rate_ms &&
918 	       ctlr->ctlr_state == JOYCON_CTLR_STATE_READ) {
919 		joycon_wait_for_input_report(ctlr);
920 		current_ms = jiffies_to_msecs(jiffies);
921 		delta_ms = current_ms - ctlr->last_subcmd_sent_msecs;
922 	}
923 	ctlr->last_subcmd_sent_msecs = current_ms;
924 }
925 
926 static void joycon_enforce_subcmd_rate(struct joycon_ctlr *ctlr)
927 {
928 	if (ctlr->subcmd_rate_relaxed)
929 		joycon_enforce_subcmd_rate_legacy(ctlr);
930 	else
931 		joycon_enforce_subcmd_rate_strict(ctlr);
932 }
933 
934 static int joycon_hid_send_sync(struct joycon_ctlr *ctlr, u8 *data, size_t len,
935 				u32 timeout)
936 {
937 	int ret;
938 	int tries = 2;
939 
940 	/*
941 	 * The controller occasionally seems to drop subcommands. In testing,
942 	 * doing one retry after a timeout appears to always work.
943 	 */
944 	while (tries--) {
945 		joycon_enforce_subcmd_rate(ctlr);
946 
947 		ret = __joycon_hid_send(ctlr->hdev, data, len);
948 		if (ret < 0) {
949 			memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE);
950 			return ret;
951 		}
952 
953 		ret = wait_event_timeout(ctlr->wait, ctlr->received_resp,
954 					 timeout);
955 		if (!ret) {
956 			hid_dbg(ctlr->hdev,
957 				"synchronous send/receive timed out\n");
958 			if (tries) {
959 				hid_dbg(ctlr->hdev,
960 					"retrying sync send after timeout\n");
961 			}
962 			memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE);
963 			ret = -ETIMEDOUT;
964 		} else {
965 			ret = 0;
966 			break;
967 		}
968 	}
969 
970 	ctlr->received_resp = false;
971 	return ret;
972 }
973 
974 static int joycon_send_usb(struct joycon_ctlr *ctlr, u8 cmd, u32 timeout)
975 {
976 	int ret;
977 	u8 buf[2] = {JC_OUTPUT_USB_CMD};
978 
979 	buf[1] = cmd;
980 	ctlr->usb_ack_match = cmd;
981 	ctlr->msg_type = JOYCON_MSG_TYPE_USB;
982 	ret = joycon_hid_send_sync(ctlr, buf, sizeof(buf), timeout);
983 	if (ret)
984 		hid_dbg(ctlr->hdev, "send usb command failed; ret=%d\n", ret);
985 	return ret;
986 }
987 
988 static int joycon_send_subcmd(struct joycon_ctlr *ctlr,
989 			      struct joycon_subcmd_request *subcmd,
990 			      size_t data_len, u32 timeout)
991 {
992 	int ret;
993 	unsigned long flags;
994 
995 	spin_lock_irqsave(&ctlr->lock, flags);
996 	/*
997 	 * If the controller has been removed, just return ENODEV so the LED
998 	 * subsystem doesn't print invalid errors on removal.
999 	 */
1000 	if (ctlr->ctlr_state == JOYCON_CTLR_STATE_REMOVED) {
1001 		spin_unlock_irqrestore(&ctlr->lock, flags);
1002 		return -ENODEV;
1003 	}
1004 	memcpy(subcmd->rumble_data, ctlr->rumble_data[ctlr->rumble_queue_tail],
1005 	       JC_RUMBLE_DATA_SIZE);
1006 	spin_unlock_irqrestore(&ctlr->lock, flags);
1007 
1008 	subcmd->output_id = JC_OUTPUT_RUMBLE_AND_SUBCMD;
1009 	subcmd->packet_num = ctlr->subcmd_num;
1010 	if (++ctlr->subcmd_num > 0xF)
1011 		ctlr->subcmd_num = 0;
1012 	ctlr->subcmd_ack_match = subcmd->subcmd_id;
1013 	ctlr->msg_type = JOYCON_MSG_TYPE_SUBCMD;
1014 
1015 	ret = joycon_hid_send_sync(ctlr, (u8 *)subcmd,
1016 				   sizeof(*subcmd) + data_len, timeout);
1017 	if (ret < 0)
1018 		hid_dbg(ctlr->hdev, "send subcommand failed; ret=%d\n", ret);
1019 	else
1020 		ret = 0;
1021 	return ret;
1022 }
1023 
1024 /* Supply nibbles for flash and on. Ones correspond to active */
1025 static int joycon_set_player_leds(struct joycon_ctlr *ctlr, u8 flash, u8 on)
1026 {
1027 	struct joycon_subcmd_request *req;
1028 	u8 buffer[sizeof(*req) + 1] = { 0 };
1029 
1030 	req = (struct joycon_subcmd_request *)buffer;
1031 	req->subcmd_id = JC_SUBCMD_SET_PLAYER_LIGHTS;
1032 	req->data[0] = (flash << 4) | on;
1033 
1034 	hid_dbg(ctlr->hdev, "setting player leds\n");
1035 	return joycon_send_subcmd(ctlr, req, 1, HZ/4);
1036 }
1037 
1038 static int joycon_set_home_led(struct joycon_ctlr *ctlr, enum led_brightness brightness)
1039 {
1040 	struct joycon_subcmd_request *req;
1041 	u8 buffer[sizeof(*req) + 5] = { 0 };
1042 	u8 *data;
1043 
1044 	req = (struct joycon_subcmd_request *)buffer;
1045 	req->subcmd_id = JC_SUBCMD_SET_HOME_LIGHT;
1046 	data = req->data;
1047 	data[0] = 0x01;
1048 	data[1] = brightness << 4;
1049 	data[2] = brightness | (brightness << 4);
1050 	data[3] = 0x11;
1051 	data[4] = 0x11;
1052 
1053 	hid_dbg(ctlr->hdev, "setting home led brightness\n");
1054 	return joycon_send_subcmd(ctlr, req, 5, HZ/4);
1055 }
1056 
1057 static int joycon_request_spi_flash_read(struct joycon_ctlr *ctlr,
1058 					 u32 start_addr, u8 size, u8 **reply)
1059 {
1060 	struct joycon_subcmd_request *req;
1061 	struct joycon_input_report *report;
1062 	u8 buffer[sizeof(*req) + 5] = { 0 };
1063 	u8 *data;
1064 	int ret;
1065 
1066 	if (!reply)
1067 		return -EINVAL;
1068 
1069 	req = (struct joycon_subcmd_request *)buffer;
1070 	req->subcmd_id = JC_SUBCMD_SPI_FLASH_READ;
1071 	data = req->data;
1072 	put_unaligned_le32(start_addr, data);
1073 	data[4] = size;
1074 
1075 	hid_dbg(ctlr->hdev, "requesting SPI flash data\n");
1076 	ret = joycon_send_subcmd(ctlr, req, 5, HZ);
1077 	if (ret) {
1078 		hid_err(ctlr->hdev, "failed reading SPI flash; ret=%d\n", ret);
1079 	} else {
1080 		report = (struct joycon_input_report *)ctlr->input_buf;
1081 		/* The read data starts at the 6th byte */
1082 		*reply = &report->subcmd_reply.data[5];
1083 	}
1084 	return ret;
1085 }
1086 
1087 /*
1088  * User calibration's presence is denoted with a magic byte preceding it.
1089  * returns 0 if magic val is present, 1 if not present, < 0 on error
1090  */
1091 static int joycon_check_for_cal_magic(struct joycon_ctlr *ctlr, u32 flash_addr)
1092 {
1093 	int ret;
1094 	u8 *reply;
1095 
1096 	ret = joycon_request_spi_flash_read(ctlr, flash_addr,
1097 					    JC_CAL_USR_MAGIC_SIZE, &reply);
1098 	if (ret)
1099 		return ret;
1100 
1101 	return reply[0] != JC_CAL_USR_MAGIC_0 || reply[1] != JC_CAL_USR_MAGIC_1;
1102 }
1103 
1104 static int joycon_read_stick_calibration(struct joycon_ctlr *ctlr, u16 cal_addr,
1105 					 struct joycon_stick_cal *cal_x,
1106 					 struct joycon_stick_cal *cal_y,
1107 					 bool left_stick)
1108 {
1109 	s32 x_max_above;
1110 	s32 x_min_below;
1111 	s32 y_max_above;
1112 	s32 y_min_below;
1113 	u8 *raw_cal;
1114 	int ret;
1115 
1116 	ret = joycon_request_spi_flash_read(ctlr, cal_addr,
1117 					    JC_CAL_STICK_DATA_SIZE, &raw_cal);
1118 	if (ret)
1119 		return ret;
1120 
1121 	/* stick calibration parsing: note the order differs based on stick */
1122 	if (left_stick) {
1123 		x_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 0), 0,
1124 						12);
1125 		y_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 1), 4,
1126 						12);
1127 		cal_x->center = hid_field_extract(ctlr->hdev, (raw_cal + 3), 0,
1128 						  12);
1129 		cal_y->center = hid_field_extract(ctlr->hdev, (raw_cal + 4), 4,
1130 						  12);
1131 		x_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 6), 0,
1132 						12);
1133 		y_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 7), 4,
1134 						12);
1135 	} else {
1136 		cal_x->center = hid_field_extract(ctlr->hdev, (raw_cal + 0), 0,
1137 						  12);
1138 		cal_y->center = hid_field_extract(ctlr->hdev, (raw_cal + 1), 4,
1139 						  12);
1140 		x_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 3), 0,
1141 						12);
1142 		y_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 4), 4,
1143 						12);
1144 		x_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 6), 0,
1145 						12);
1146 		y_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 7), 4,
1147 						12);
1148 	}
1149 
1150 	cal_x->max = cal_x->center + x_max_above;
1151 	cal_x->min = cal_x->center - x_min_below;
1152 	cal_y->max = cal_y->center + y_max_above;
1153 	cal_y->min = cal_y->center - y_min_below;
1154 
1155 	/* check if calibration values are plausible */
1156 	if (cal_x->min >= cal_x->center || cal_x->center >= cal_x->max ||
1157 	    cal_y->min >= cal_y->center || cal_y->center >= cal_y->max)
1158 		ret = -EINVAL;
1159 
1160 	return ret;
1161 }
1162 
1163 static const u16 DFLT_STICK_CAL_CEN = 2000;
1164 static const u16 DFLT_STICK_CAL_MAX = 3500;
1165 static const u16 DFLT_STICK_CAL_MIN = 500;
1166 static void joycon_use_default_calibration(struct hid_device *hdev,
1167 					   struct joycon_stick_cal *cal_x,
1168 					   struct joycon_stick_cal *cal_y,
1169 					   const char *stick, int ret)
1170 {
1171 	hid_warn(hdev,
1172 		 "Failed to read %s stick cal, using defaults; e=%d\n",
1173 		 stick, ret);
1174 
1175 	cal_x->center = cal_y->center = DFLT_STICK_CAL_CEN;
1176 	cal_x->max = cal_y->max = DFLT_STICK_CAL_MAX;
1177 	cal_x->min = cal_y->min = DFLT_STICK_CAL_MIN;
1178 }
1179 
1180 static int joycon_request_calibration(struct joycon_ctlr *ctlr)
1181 {
1182 	u16 left_stick_addr = JC_CAL_FCT_DATA_LEFT_ADDR;
1183 	u16 right_stick_addr = JC_CAL_FCT_DATA_RIGHT_ADDR;
1184 	int ret;
1185 
1186 	hid_dbg(ctlr->hdev, "requesting cal data\n");
1187 
1188 	/* check if user stick calibrations are present */
1189 	if (!joycon_check_for_cal_magic(ctlr, JC_CAL_USR_LEFT_MAGIC_ADDR)) {
1190 		left_stick_addr = JC_CAL_USR_LEFT_DATA_ADDR;
1191 		hid_info(ctlr->hdev, "using user cal for left stick\n");
1192 	} else {
1193 		hid_info(ctlr->hdev, "using factory cal for left stick\n");
1194 	}
1195 	if (!joycon_check_for_cal_magic(ctlr, JC_CAL_USR_RIGHT_MAGIC_ADDR)) {
1196 		right_stick_addr = JC_CAL_USR_RIGHT_DATA_ADDR;
1197 		hid_info(ctlr->hdev, "using user cal for right stick\n");
1198 	} else {
1199 		hid_info(ctlr->hdev, "using factory cal for right stick\n");
1200 	}
1201 
1202 	/* read the left stick calibration data */
1203 	ret = joycon_read_stick_calibration(ctlr, left_stick_addr,
1204 					    &ctlr->left_stick_cal_x,
1205 					    &ctlr->left_stick_cal_y,
1206 					    true);
1207 
1208 	if (ret)
1209 		joycon_use_default_calibration(ctlr->hdev,
1210 					       &ctlr->left_stick_cal_x,
1211 					       &ctlr->left_stick_cal_y,
1212 					       "left", ret);
1213 
1214 	/* read the right stick calibration data */
1215 	ret = joycon_read_stick_calibration(ctlr, right_stick_addr,
1216 					    &ctlr->right_stick_cal_x,
1217 					    &ctlr->right_stick_cal_y,
1218 					    false);
1219 
1220 	if (ret)
1221 		joycon_use_default_calibration(ctlr->hdev,
1222 					       &ctlr->right_stick_cal_x,
1223 					       &ctlr->right_stick_cal_y,
1224 					       "right", ret);
1225 
1226 	hid_dbg(ctlr->hdev, "calibration:\n"
1227 			    "l_x_c=%d l_x_max=%d l_x_min=%d\n"
1228 			    "l_y_c=%d l_y_max=%d l_y_min=%d\n"
1229 			    "r_x_c=%d r_x_max=%d r_x_min=%d\n"
1230 			    "r_y_c=%d r_y_max=%d r_y_min=%d\n",
1231 			    ctlr->left_stick_cal_x.center,
1232 			    ctlr->left_stick_cal_x.max,
1233 			    ctlr->left_stick_cal_x.min,
1234 			    ctlr->left_stick_cal_y.center,
1235 			    ctlr->left_stick_cal_y.max,
1236 			    ctlr->left_stick_cal_y.min,
1237 			    ctlr->right_stick_cal_x.center,
1238 			    ctlr->right_stick_cal_x.max,
1239 			    ctlr->right_stick_cal_x.min,
1240 			    ctlr->right_stick_cal_y.center,
1241 			    ctlr->right_stick_cal_y.max,
1242 			    ctlr->right_stick_cal_y.min);
1243 
1244 	return 0;
1245 }
1246 
1247 /*
1248  * These divisors are calculated once rather than for each sample. They are only
1249  * dependent on the IMU calibration values. They are used when processing the
1250  * IMU input reports.
1251  */
1252 static void joycon_calc_imu_cal_divisors(struct joycon_ctlr *ctlr)
1253 {
1254 	int i, divz = 0;
1255 
1256 	for (i = 0; i < 3; i++) {
1257 		ctlr->imu_cal_accel_divisor[i] = ctlr->accel_cal.scale[i] -
1258 						ctlr->accel_cal.offset[i];
1259 		ctlr->imu_cal_gyro_divisor[i] = ctlr->gyro_cal.scale[i] -
1260 						ctlr->gyro_cal.offset[i];
1261 
1262 		if (ctlr->imu_cal_accel_divisor[i] == 0) {
1263 			ctlr->imu_cal_accel_divisor[i] = 1;
1264 			divz++;
1265 		}
1266 
1267 		if (ctlr->imu_cal_gyro_divisor[i] == 0) {
1268 			ctlr->imu_cal_gyro_divisor[i] = 1;
1269 			divz++;
1270 		}
1271 	}
1272 
1273 	if (divz)
1274 		hid_warn(ctlr->hdev, "inaccurate IMU divisors (%d)\n", divz);
1275 }
1276 
1277 static const s16 DFLT_ACCEL_OFFSET /*= 0*/;
1278 static const s16 DFLT_ACCEL_SCALE = 16384;
1279 static const s16 DFLT_GYRO_OFFSET /*= 0*/;
1280 static const s16 DFLT_GYRO_SCALE  = 13371;
1281 static int joycon_request_imu_calibration(struct joycon_ctlr *ctlr)
1282 {
1283 	u16 imu_cal_addr = JC_IMU_CAL_FCT_DATA_ADDR;
1284 	u8 *raw_cal;
1285 	int ret;
1286 	int i;
1287 
1288 	/* check if user calibration exists */
1289 	if (!joycon_check_for_cal_magic(ctlr, JC_IMU_CAL_USR_MAGIC_ADDR)) {
1290 		imu_cal_addr = JC_IMU_CAL_USR_DATA_ADDR;
1291 		hid_info(ctlr->hdev, "using user cal for IMU\n");
1292 	} else {
1293 		hid_info(ctlr->hdev, "using factory cal for IMU\n");
1294 	}
1295 
1296 	/* request IMU calibration data */
1297 	hid_dbg(ctlr->hdev, "requesting IMU cal data\n");
1298 	ret = joycon_request_spi_flash_read(ctlr, imu_cal_addr,
1299 					    JC_IMU_CAL_DATA_SIZE, &raw_cal);
1300 	if (ret) {
1301 		hid_warn(ctlr->hdev,
1302 			 "Failed to read IMU cal, using defaults; ret=%d\n",
1303 			 ret);
1304 
1305 		for (i = 0; i < 3; i++) {
1306 			ctlr->accel_cal.offset[i] = DFLT_ACCEL_OFFSET;
1307 			ctlr->accel_cal.scale[i] = DFLT_ACCEL_SCALE;
1308 			ctlr->gyro_cal.offset[i] = DFLT_GYRO_OFFSET;
1309 			ctlr->gyro_cal.scale[i] = DFLT_GYRO_SCALE;
1310 		}
1311 		joycon_calc_imu_cal_divisors(ctlr);
1312 		return ret;
1313 	}
1314 
1315 	/* IMU calibration parsing */
1316 	for (i = 0; i < 3; i++) {
1317 		int j = i * 2;
1318 
1319 		ctlr->accel_cal.offset[i] = get_unaligned_le16(raw_cal + j);
1320 		ctlr->accel_cal.scale[i] = get_unaligned_le16(raw_cal + j + 6);
1321 		ctlr->gyro_cal.offset[i] = get_unaligned_le16(raw_cal + j + 12);
1322 		ctlr->gyro_cal.scale[i] = get_unaligned_le16(raw_cal + j + 18);
1323 	}
1324 
1325 	joycon_calc_imu_cal_divisors(ctlr);
1326 
1327 	hid_dbg(ctlr->hdev, "IMU calibration:\n"
1328 			    "a_o[0]=%d a_o[1]=%d a_o[2]=%d\n"
1329 			    "a_s[0]=%d a_s[1]=%d a_s[2]=%d\n"
1330 			    "g_o[0]=%d g_o[1]=%d g_o[2]=%d\n"
1331 			    "g_s[0]=%d g_s[1]=%d g_s[2]=%d\n",
1332 			    ctlr->accel_cal.offset[0],
1333 			    ctlr->accel_cal.offset[1],
1334 			    ctlr->accel_cal.offset[2],
1335 			    ctlr->accel_cal.scale[0],
1336 			    ctlr->accel_cal.scale[1],
1337 			    ctlr->accel_cal.scale[2],
1338 			    ctlr->gyro_cal.offset[0],
1339 			    ctlr->gyro_cal.offset[1],
1340 			    ctlr->gyro_cal.offset[2],
1341 			    ctlr->gyro_cal.scale[0],
1342 			    ctlr->gyro_cal.scale[1],
1343 			    ctlr->gyro_cal.scale[2]);
1344 
1345 	return 0;
1346 }
1347 
1348 static int joycon_set_report_mode(struct joycon_ctlr *ctlr)
1349 {
1350 	struct joycon_subcmd_request *req;
1351 	u8 buffer[sizeof(*req) + 1] = { 0 };
1352 
1353 	req = (struct joycon_subcmd_request *)buffer;
1354 	req->subcmd_id = JC_SUBCMD_SET_REPORT_MODE;
1355 	req->data[0] = 0x30; /* standard, full report mode */
1356 
1357 	hid_dbg(ctlr->hdev, "setting controller report mode\n");
1358 	return joycon_send_subcmd(ctlr, req, 1, HZ);
1359 }
1360 
1361 static int joycon_enable_rumble(struct joycon_ctlr *ctlr)
1362 {
1363 	struct joycon_subcmd_request *req;
1364 	u8 buffer[sizeof(*req) + 1] = { 0 };
1365 
1366 	req = (struct joycon_subcmd_request *)buffer;
1367 	req->subcmd_id = JC_SUBCMD_ENABLE_VIBRATION;
1368 	req->data[0] = 0x01; /* note: 0x00 would disable */
1369 
1370 	hid_dbg(ctlr->hdev, "enabling rumble\n");
1371 	return joycon_send_subcmd(ctlr, req, 1, HZ/4);
1372 }
1373 
1374 static int joycon_enable_imu(struct joycon_ctlr *ctlr)
1375 {
1376 	struct joycon_subcmd_request *req;
1377 	u8 buffer[sizeof(*req) + 1] = { 0 };
1378 
1379 	req = (struct joycon_subcmd_request *)buffer;
1380 	req->subcmd_id = JC_SUBCMD_ENABLE_IMU;
1381 	req->data[0] = 0x01; /* note: 0x00 would disable */
1382 
1383 	hid_dbg(ctlr->hdev, "enabling IMU\n");
1384 	return joycon_send_subcmd(ctlr, req, 1, HZ);
1385 }
1386 
1387 static s32 joycon_map_stick_val(struct joycon_stick_cal *cal, s32 val)
1388 {
1389 	s32 center = cal->center;
1390 	s32 min = cal->min;
1391 	s32 max = cal->max;
1392 	s32 new_val;
1393 
1394 	if (val > center) {
1395 		new_val = (val - center) * JC_MAX_STICK_MAG;
1396 		new_val /= (max - center);
1397 	} else {
1398 		new_val = (center - val) * -JC_MAX_STICK_MAG;
1399 		new_val /= (center - min);
1400 	}
1401 	new_val = clamp(new_val, (s32)-JC_MAX_STICK_MAG, (s32)JC_MAX_STICK_MAG);
1402 	return new_val;
1403 }
1404 
1405 static void joycon_input_report_parse_imu_data(struct joycon_ctlr *ctlr,
1406 					       struct joycon_input_report *rep,
1407 					       struct joycon_imu_data *imu_data)
1408 {
1409 	u8 *raw = rep->imu_raw_bytes;
1410 	int i;
1411 
1412 	for (i = 0; i < 3; i++) {
1413 		struct joycon_imu_data *data = &imu_data[i];
1414 
1415 		data->accel_x = get_unaligned_le16(raw + 0);
1416 		data->accel_y = get_unaligned_le16(raw + 2);
1417 		data->accel_z = get_unaligned_le16(raw + 4);
1418 		data->gyro_x = get_unaligned_le16(raw + 6);
1419 		data->gyro_y = get_unaligned_le16(raw + 8);
1420 		data->gyro_z = get_unaligned_le16(raw + 10);
1421 		/* point to next imu sample */
1422 		raw += sizeof(struct joycon_imu_data);
1423 	}
1424 }
1425 
1426 static void joycon_parse_imu_report(struct joycon_ctlr *ctlr,
1427 				    struct joycon_input_report *rep)
1428 {
1429 	struct joycon_imu_data imu_data[3] = {0}; /* 3 reports per packet */
1430 	struct input_dev *idev = ctlr->imu_input;
1431 	unsigned int msecs = jiffies_to_msecs(jiffies);
1432 	unsigned int last_msecs = ctlr->imu_last_pkt_ms;
1433 	int i;
1434 	int value[6];
1435 
1436 	joycon_input_report_parse_imu_data(ctlr, rep, imu_data);
1437 
1438 	/*
1439 	 * There are complexities surrounding how we determine the timestamps we
1440 	 * associate with the samples we pass to userspace. The IMU input
1441 	 * reports do not provide us with a good timestamp. There's a quickly
1442 	 * incrementing 8-bit counter per input report, but it is not very
1443 	 * useful for this purpose (it is not entirely clear what rate it
1444 	 * increments at or if it varies based on packet push rate - more on
1445 	 * the push rate below...).
1446 	 *
1447 	 * The reverse engineering work done on the joy-cons and pro controllers
1448 	 * by the community seems to indicate the following:
1449 	 * - The controller samples the IMU every 1.35ms. It then does some of
1450 	 *   its own processing, probably averaging the samples out.
1451 	 * - Each imu input report contains 3 IMU samples, (usually 5ms apart).
1452 	 * - In the standard reporting mode (which this driver uses exclusively)
1453 	 *   input reports are pushed from the controller as follows:
1454 	 *      * joy-con (bluetooth): every 15 ms
1455 	 *      * joy-cons (in charging grip via USB): every 15 ms
1456 	 *      * pro controller (USB): every 15 ms
1457 	 *      * pro controller (bluetooth): every 8 ms (this is the wildcard)
1458 	 *
1459 	 * Further complicating matters is that some bluetooth stacks are known
1460 	 * to alter the controller's packet rate by hardcoding the bluetooth
1461 	 * SSR for the switch controllers (android's stack currently sets the
1462 	 * SSR to 11ms for both the joy-cons and pro controllers).
1463 	 *
1464 	 * In my own testing, I've discovered that my pro controller either
1465 	 * reports IMU sample batches every 11ms or every 15ms. This rate is
1466 	 * stable after connecting. It isn't 100% clear what determines this
1467 	 * rate. Importantly, even when sending every 11ms, none of the samples
1468 	 * are duplicates. This seems to indicate that the time deltas between
1469 	 * reported samples can vary based on the input report rate.
1470 	 *
1471 	 * The solution employed in this driver is to keep track of the average
1472 	 * time delta between IMU input reports. In testing, this value has
1473 	 * proven to be stable, staying at 15ms or 11ms, though other hardware
1474 	 * configurations and bluetooth stacks could potentially see other rates
1475 	 * (hopefully this will become more clear as more people use the
1476 	 * driver).
1477 	 *
1478 	 * Keeping track of the average report delta allows us to submit our
1479 	 * timestamps to userspace based on that. Each report contains 3
1480 	 * samples, so the IMU sampling rate should be avg_time_delta/3. We can
1481 	 * also use this average to detect events where we have dropped a
1482 	 * packet. The userspace timestamp for the samples will be adjusted
1483 	 * accordingly to prevent unwanted behvaior.
1484 	 */
1485 	if (!ctlr->imu_first_packet_received) {
1486 		ctlr->imu_timestamp_us = 0;
1487 		ctlr->imu_delta_samples_count = 0;
1488 		ctlr->imu_delta_samples_sum = 0;
1489 		ctlr->imu_avg_delta_ms = JC_IMU_DFLT_AVG_DELTA_MS;
1490 		ctlr->imu_first_packet_received = true;
1491 	} else {
1492 		unsigned int delta = msecs - last_msecs;
1493 		unsigned int dropped_pkts;
1494 		unsigned int dropped_threshold;
1495 
1496 		/* avg imu report delta housekeeping */
1497 		ctlr->imu_delta_samples_sum += delta;
1498 		ctlr->imu_delta_samples_count++;
1499 		if (ctlr->imu_delta_samples_count >=
1500 		    JC_IMU_SAMPLES_PER_DELTA_AVG) {
1501 			ctlr->imu_avg_delta_ms = ctlr->imu_delta_samples_sum /
1502 						 ctlr->imu_delta_samples_count;
1503 			ctlr->imu_delta_samples_count = 0;
1504 			ctlr->imu_delta_samples_sum = 0;
1505 		}
1506 
1507 		/* don't ever want divide by zero shenanigans */
1508 		if (ctlr->imu_avg_delta_ms == 0) {
1509 			ctlr->imu_avg_delta_ms = 1;
1510 			hid_warn(ctlr->hdev, "calculated avg imu delta of 0\n");
1511 		}
1512 
1513 		/* useful for debugging IMU sample rate */
1514 		hid_dbg(ctlr->hdev,
1515 			"imu_report: ms=%u last_ms=%u delta=%u avg_delta=%u\n",
1516 			msecs, last_msecs, delta, ctlr->imu_avg_delta_ms);
1517 
1518 		/* check if any packets have been dropped */
1519 		dropped_threshold = ctlr->imu_avg_delta_ms * 3 / 2;
1520 		dropped_pkts = (delta - min(delta, dropped_threshold)) /
1521 				ctlr->imu_avg_delta_ms;
1522 		if (dropped_pkts > JC_IMU_DROPPED_PKT_WARNING) {
1523 			hid_warn_ratelimited(ctlr->hdev,
1524 				 "compensating for %u dropped IMU reports\n",
1525 				 dropped_pkts);
1526 			hid_warn_ratelimited(ctlr->hdev,
1527 				 "delta=%u avg_delta=%u\n",
1528 				 delta, ctlr->imu_avg_delta_ms);
1529 		}
1530 	}
1531 	ctlr->imu_last_pkt_ms = msecs;
1532 
1533 	/* Each IMU input report contains three samples */
1534 	for (i = 0; i < 3; i++) {
1535 		input_event(idev, EV_MSC, MSC_TIMESTAMP,
1536 			    ctlr->imu_timestamp_us);
1537 
1538 		/*
1539 		 * These calculations (which use the controller's calibration
1540 		 * settings to improve the final values) are based on those
1541 		 * found in the community's reverse-engineering repo (linked at
1542 		 * top of driver). For hid-nintendo, we make sure that the final
1543 		 * value given to userspace is always in terms of the axis
1544 		 * resolution we provided.
1545 		 *
1546 		 * Currently only the gyro calculations subtract the calibration
1547 		 * offsets from the raw value itself. In testing, doing the same
1548 		 * for the accelerometer raw values decreased accuracy.
1549 		 *
1550 		 * Note that the gyro values are multiplied by the
1551 		 * precision-saving scaling factor to prevent large inaccuracies
1552 		 * due to truncation of the resolution value which would
1553 		 * otherwise occur. To prevent overflow (without resorting to 64
1554 		 * bit integer math), the mult_frac macro is used.
1555 		 */
1556 		value[0] = mult_frac((JC_IMU_PREC_RANGE_SCALE *
1557 				      (imu_data[i].gyro_x -
1558 				       ctlr->gyro_cal.offset[0])),
1559 				     ctlr->gyro_cal.scale[0],
1560 				     ctlr->imu_cal_gyro_divisor[0]);
1561 		value[1] = mult_frac((JC_IMU_PREC_RANGE_SCALE *
1562 				      (imu_data[i].gyro_y -
1563 				       ctlr->gyro_cal.offset[1])),
1564 				     ctlr->gyro_cal.scale[1],
1565 				     ctlr->imu_cal_gyro_divisor[1]);
1566 		value[2] = mult_frac((JC_IMU_PREC_RANGE_SCALE *
1567 				      (imu_data[i].gyro_z -
1568 				       ctlr->gyro_cal.offset[2])),
1569 				     ctlr->gyro_cal.scale[2],
1570 				     ctlr->imu_cal_gyro_divisor[2]);
1571 
1572 		value[3] = ((s32)imu_data[i].accel_x *
1573 			    ctlr->accel_cal.scale[0]) /
1574 			    ctlr->imu_cal_accel_divisor[0];
1575 		value[4] = ((s32)imu_data[i].accel_y *
1576 			    ctlr->accel_cal.scale[1]) /
1577 			    ctlr->imu_cal_accel_divisor[1];
1578 		value[5] = ((s32)imu_data[i].accel_z *
1579 			    ctlr->accel_cal.scale[2]) /
1580 			    ctlr->imu_cal_accel_divisor[2];
1581 
1582 		hid_dbg(ctlr->hdev, "raw_gyro: g_x=%d g_y=%d g_z=%d\n",
1583 			imu_data[i].gyro_x, imu_data[i].gyro_y,
1584 			imu_data[i].gyro_z);
1585 		hid_dbg(ctlr->hdev, "raw_accel: a_x=%d a_y=%d a_z=%d\n",
1586 			imu_data[i].accel_x, imu_data[i].accel_y,
1587 			imu_data[i].accel_z);
1588 
1589 		/*
1590 		 * The right joy-con has 2 axes negated, Y and Z. This is due to
1591 		 * the orientation of the IMU in the controller. We negate those
1592 		 * axes' values in order to be consistent with the left joy-con
1593 		 * and the pro controller:
1594 		 *   X: positive is pointing toward the triggers
1595 		 *   Y: positive is pointing to the left
1596 		 *   Z: positive is pointing up (out of the buttons/sticks)
1597 		 * The axes follow the right-hand rule.
1598 		 */
1599 		if (jc_type_is_joycon(ctlr) && jc_type_has_right(ctlr)) {
1600 			int j;
1601 
1602 			/* negate all but x axis */
1603 			for (j = 1; j < 6; ++j) {
1604 				if (j == 3)
1605 					continue;
1606 				value[j] *= -1;
1607 			}
1608 		}
1609 
1610 		input_report_abs(idev, ABS_RX, value[0]);
1611 		input_report_abs(idev, ABS_RY, value[1]);
1612 		input_report_abs(idev, ABS_RZ, value[2]);
1613 		input_report_abs(idev, ABS_X, value[3]);
1614 		input_report_abs(idev, ABS_Y, value[4]);
1615 		input_report_abs(idev, ABS_Z, value[5]);
1616 		input_sync(idev);
1617 		/* convert to micros and divide by 3 (3 samples per report). */
1618 		ctlr->imu_timestamp_us += ctlr->imu_avg_delta_ms * 1000 / 3;
1619 	}
1620 }
1621 
1622 static void joycon_handle_rumble_report(struct joycon_ctlr *ctlr, struct joycon_input_report *rep)
1623 {
1624 	unsigned long flags;
1625 	unsigned long msecs = jiffies_to_msecs(jiffies);
1626 
1627 	spin_lock_irqsave(&ctlr->lock, flags);
1628 	if (IS_ENABLED(CONFIG_NINTENDO_FF) && rep->vibrator_report &&
1629 	    ctlr->ctlr_state != JOYCON_CTLR_STATE_REMOVED &&
1630 	    (msecs - ctlr->rumble_msecs) >= JC_RUMBLE_PERIOD_MS &&
1631 	    (ctlr->rumble_queue_head != ctlr->rumble_queue_tail ||
1632 	     ctlr->rumble_zero_countdown > 0)) {
1633 		/*
1634 		 * When this value reaches 0, we know we've sent multiple
1635 		 * packets to the controller instructing it to disable rumble.
1636 		 * We can safely stop sending periodic rumble packets until the
1637 		 * next ff effect.
1638 		 */
1639 		if (ctlr->rumble_zero_countdown > 0)
1640 			ctlr->rumble_zero_countdown--;
1641 		queue_work(ctlr->rumble_queue, &ctlr->rumble_worker);
1642 	}
1643 
1644 	spin_unlock_irqrestore(&ctlr->lock, flags);
1645 }
1646 
1647 static void joycon_parse_battery_status(struct joycon_ctlr *ctlr, struct joycon_input_report *rep)
1648 {
1649 	u8 tmp;
1650 	unsigned long flags;
1651 
1652 	spin_lock_irqsave(&ctlr->lock, flags);
1653 
1654 	tmp = rep->bat_con;
1655 	ctlr->host_powered = tmp & BIT(0);
1656 	ctlr->battery_charging = tmp & BIT(4);
1657 	tmp = tmp >> 5;
1658 
1659 	switch (tmp) {
1660 	case 0: /* empty */
1661 		ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
1662 		break;
1663 	case 1: /* low */
1664 		ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
1665 		break;
1666 	case 2: /* medium */
1667 		ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
1668 		break;
1669 	case 3: /* high */
1670 		ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_HIGH;
1671 		break;
1672 	case 4: /* full */
1673 		ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
1674 		break;
1675 	default:
1676 		ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
1677 		hid_warn(ctlr->hdev, "Invalid battery status\n");
1678 		break;
1679 	}
1680 
1681 	spin_unlock_irqrestore(&ctlr->lock, flags);
1682 }
1683 
1684 static void joycon_report_left_stick(struct joycon_ctlr *ctlr,
1685 				     struct joycon_input_report *rep)
1686 {
1687 	u16 raw_x;
1688 	u16 raw_y;
1689 	s32 x;
1690 	s32 y;
1691 
1692 	raw_x = hid_field_extract(ctlr->hdev, rep->left_stick, 0, 12);
1693 	raw_y = hid_field_extract(ctlr->hdev, rep->left_stick + 1, 4, 12);
1694 
1695 	x = joycon_map_stick_val(&ctlr->left_stick_cal_x, raw_x);
1696 	y = -joycon_map_stick_val(&ctlr->left_stick_cal_y, raw_y);
1697 
1698 	input_report_abs(ctlr->input, ABS_X, x);
1699 	input_report_abs(ctlr->input, ABS_Y, y);
1700 }
1701 
1702 static void joycon_report_right_stick(struct joycon_ctlr *ctlr,
1703 				      struct joycon_input_report *rep)
1704 {
1705 	u16 raw_x;
1706 	u16 raw_y;
1707 	s32 x;
1708 	s32 y;
1709 
1710 	raw_x = hid_field_extract(ctlr->hdev, rep->right_stick, 0, 12);
1711 	raw_y = hid_field_extract(ctlr->hdev, rep->right_stick + 1, 4, 12);
1712 
1713 	x = joycon_map_stick_val(&ctlr->right_stick_cal_x, raw_x);
1714 	y = -joycon_map_stick_val(&ctlr->right_stick_cal_y, raw_y);
1715 
1716 	input_report_abs(ctlr->input, ABS_RX, x);
1717 	input_report_abs(ctlr->input, ABS_RY, y);
1718 }
1719 
1720 static void joycon_report_dpad(struct joycon_ctlr *ctlr,
1721 			       struct joycon_input_report *rep)
1722 {
1723 	int hatx = 0;
1724 	int haty = 0;
1725 	u32 btns = hid_field_extract(ctlr->hdev, rep->button_status, 0, 24);
1726 
1727 	if (btns & JC_BTN_LEFT)
1728 		hatx = -1;
1729 	else if (btns & JC_BTN_RIGHT)
1730 		hatx = 1;
1731 
1732 	if (btns & JC_BTN_UP)
1733 		haty = -1;
1734 	else if (btns & JC_BTN_DOWN)
1735 		haty = 1;
1736 
1737 	input_report_abs(ctlr->input, ABS_HAT0X, hatx);
1738 	input_report_abs(ctlr->input, ABS_HAT0Y, haty);
1739 }
1740 
1741 static void joycon_report_buttons(struct joycon_ctlr *ctlr,
1742 				  struct joycon_input_report *rep,
1743 				  const struct joycon_ctlr_button_mapping button_mappings[])
1744 {
1745 	const struct joycon_ctlr_button_mapping *button;
1746 	u32 status = hid_field_extract(ctlr->hdev, rep->button_status, 0, 24);
1747 
1748 	for (button = button_mappings; button->code; button++)
1749 		input_report_key(ctlr->input, button->code, status & button->bit);
1750 }
1751 
1752 static void joycon_parse_report(struct joycon_ctlr *ctlr,
1753 				struct joycon_input_report *rep)
1754 {
1755 	unsigned long flags;
1756 	unsigned long msecs = jiffies_to_msecs(jiffies);
1757 	unsigned long report_delta_ms = msecs - ctlr->last_input_report_msecs;
1758 
1759 	if (joycon_has_rumble(ctlr))
1760 		joycon_handle_rumble_report(ctlr, rep);
1761 
1762 	joycon_parse_battery_status(ctlr, rep);
1763 
1764 	if (joycon_type_is_left_joycon(ctlr)) {
1765 		joycon_report_left_stick(ctlr, rep);
1766 		joycon_report_buttons(ctlr, rep, left_joycon_button_mappings);
1767 		if (!joycon_device_is_chrggrip(ctlr))
1768 			joycon_report_buttons(ctlr, rep, left_joycon_s_button_mappings);
1769 	} else if (joycon_type_is_right_joycon(ctlr)) {
1770 		joycon_report_right_stick(ctlr, rep);
1771 		joycon_report_buttons(ctlr, rep, right_joycon_button_mappings);
1772 		if (!joycon_device_is_chrggrip(ctlr))
1773 			joycon_report_buttons(ctlr, rep, right_joycon_s_button_mappings);
1774 	} else if (joycon_type_is_procon(ctlr)) {
1775 		joycon_report_left_stick(ctlr, rep);
1776 		joycon_report_right_stick(ctlr, rep);
1777 		joycon_report_dpad(ctlr, rep);
1778 		if (ctlr->hdev->vendor == USB_VENDOR_ID_HORI)
1779 			joycon_report_buttons(ctlr, rep, lic_hori_procon_button_mappings);
1780 		else
1781 			joycon_report_buttons(ctlr, rep, procon_button_mappings);
1782 	} else if (joycon_type_is_any_nescon(ctlr)) {
1783 		joycon_report_dpad(ctlr, rep);
1784 		joycon_report_buttons(ctlr, rep, nescon_button_mappings);
1785 	} else if (joycon_type_is_snescon(ctlr)) {
1786 		joycon_report_dpad(ctlr, rep);
1787 		joycon_report_buttons(ctlr, rep, snescon_button_mappings);
1788 	} else if (joycon_type_is_gencon(ctlr)) {
1789 		joycon_report_dpad(ctlr, rep);
1790 		joycon_report_buttons(ctlr, rep, gencon_button_mappings);
1791 	} else if (joycon_type_is_n64con(ctlr)) {
1792 		joycon_report_left_stick(ctlr, rep);
1793 		joycon_report_dpad(ctlr, rep);
1794 		joycon_report_buttons(ctlr, rep, n64con_button_mappings);
1795 	}
1796 
1797 	input_sync(ctlr->input);
1798 
1799 	spin_lock_irqsave(&ctlr->lock, flags);
1800 	ctlr->last_input_report_msecs = msecs;
1801 	/*
1802 	 * Was this input report a reasonable time delta compared to the prior
1803 	 * report? We use this information to decide when a safe time is to send
1804 	 * rumble packets or subcommand packets.
1805 	 */
1806 	if (report_delta_ms >= JC_INPUT_REPORT_MIN_DELTA &&
1807 	    report_delta_ms <= JC_INPUT_REPORT_MAX_DELTA) {
1808 		if (ctlr->consecutive_valid_report_deltas < JC_SUBCMD_VALID_DELTA_REQ)
1809 			ctlr->consecutive_valid_report_deltas++;
1810 	} else {
1811 		ctlr->consecutive_valid_report_deltas = 0;
1812 	}
1813 	/*
1814 	 * Our consecutive valid report tracking is only relevant for
1815 	 * bluetooth-connected controllers. For USB devices, we're beholden to
1816 	 * USB's underlying polling rate anyway. Always set to the consecutive
1817 	 * delta requirement.
1818 	 */
1819 	if (ctlr->hdev->bus == BUS_USB)
1820 		ctlr->consecutive_valid_report_deltas = JC_SUBCMD_VALID_DELTA_REQ;
1821 
1822 	spin_unlock_irqrestore(&ctlr->lock, flags);
1823 
1824 	/*
1825 	 * Immediately after receiving a report is the most reliable time to
1826 	 * send a subcommand to the controller. Wake any subcommand senders
1827 	 * waiting for a report.
1828 	 */
1829 	if (unlikely(mutex_is_locked(&ctlr->output_mutex))) {
1830 		spin_lock_irqsave(&ctlr->lock, flags);
1831 		ctlr->received_input_report = true;
1832 		spin_unlock_irqrestore(&ctlr->lock, flags);
1833 		wake_up(&ctlr->wait);
1834 	}
1835 
1836 	/* parse IMU data if present */
1837 	if ((rep->id == JC_INPUT_IMU_DATA) && joycon_has_imu(ctlr))
1838 		joycon_parse_imu_report(ctlr, rep);
1839 }
1840 
1841 static int joycon_send_rumble_data(struct joycon_ctlr *ctlr)
1842 {
1843 	int ret;
1844 	unsigned long flags;
1845 	struct joycon_rumble_output rumble_output = { 0 };
1846 
1847 	spin_lock_irqsave(&ctlr->lock, flags);
1848 	/*
1849 	 * If the controller has been removed, just return ENODEV so the LED
1850 	 * subsystem doesn't print invalid errors on removal.
1851 	 */
1852 	if (ctlr->ctlr_state == JOYCON_CTLR_STATE_REMOVED) {
1853 		spin_unlock_irqrestore(&ctlr->lock, flags);
1854 		return -ENODEV;
1855 	}
1856 	memcpy(rumble_output.rumble_data,
1857 	       ctlr->rumble_data[ctlr->rumble_queue_tail],
1858 	       JC_RUMBLE_DATA_SIZE);
1859 	spin_unlock_irqrestore(&ctlr->lock, flags);
1860 
1861 	rumble_output.output_id = JC_OUTPUT_RUMBLE_ONLY;
1862 	rumble_output.packet_num = ctlr->subcmd_num;
1863 	if (++ctlr->subcmd_num > 0xF)
1864 		ctlr->subcmd_num = 0;
1865 
1866 	joycon_enforce_subcmd_rate(ctlr);
1867 
1868 	ret = __joycon_hid_send(ctlr->hdev, (u8 *)&rumble_output,
1869 				sizeof(rumble_output));
1870 	return ret;
1871 }
1872 
1873 static void joycon_rumble_worker(struct work_struct *work)
1874 {
1875 	struct joycon_ctlr *ctlr = container_of(work, struct joycon_ctlr,
1876 							rumble_worker);
1877 	unsigned long flags;
1878 	bool again = true;
1879 	int ret;
1880 
1881 	while (again) {
1882 		mutex_lock(&ctlr->output_mutex);
1883 		ret = joycon_send_rumble_data(ctlr);
1884 		mutex_unlock(&ctlr->output_mutex);
1885 
1886 		/* -ENODEV means the controller was just unplugged */
1887 		spin_lock_irqsave(&ctlr->lock, flags);
1888 		if (ret < 0 && ret != -ENODEV &&
1889 		    ctlr->ctlr_state != JOYCON_CTLR_STATE_REMOVED)
1890 			hid_warn(ctlr->hdev, "Failed to set rumble; e=%d", ret);
1891 
1892 		ctlr->rumble_msecs = jiffies_to_msecs(jiffies);
1893 		if (ctlr->rumble_queue_tail != ctlr->rumble_queue_head) {
1894 			if (++ctlr->rumble_queue_tail >= JC_RUMBLE_QUEUE_SIZE)
1895 				ctlr->rumble_queue_tail = 0;
1896 		} else {
1897 			again = false;
1898 		}
1899 		spin_unlock_irqrestore(&ctlr->lock, flags);
1900 	}
1901 }
1902 
1903 #if IS_ENABLED(CONFIG_NINTENDO_FF)
1904 static struct joycon_rumble_freq_data joycon_find_rumble_freq(u16 freq)
1905 {
1906 	const size_t length = ARRAY_SIZE(joycon_rumble_frequencies);
1907 	const struct joycon_rumble_freq_data *data = joycon_rumble_frequencies;
1908 	int i = 0;
1909 
1910 	if (freq > data[0].freq) {
1911 		for (i = 1; i < length - 1; i++) {
1912 			if (freq > data[i - 1].freq && freq <= data[i].freq)
1913 				break;
1914 		}
1915 	}
1916 
1917 	return data[i];
1918 }
1919 
1920 static struct joycon_rumble_amp_data joycon_find_rumble_amp(u16 amp)
1921 {
1922 	const size_t length = ARRAY_SIZE(joycon_rumble_amplitudes);
1923 	const struct joycon_rumble_amp_data *data = joycon_rumble_amplitudes;
1924 	int i = 0;
1925 
1926 	if (amp > data[0].amp) {
1927 		for (i = 1; i < length - 1; i++) {
1928 			if (amp > data[i - 1].amp && amp <= data[i].amp)
1929 				break;
1930 		}
1931 	}
1932 
1933 	return data[i];
1934 }
1935 
1936 static void joycon_encode_rumble(u8 *data, u16 freq_low, u16 freq_high, u16 amp)
1937 {
1938 	struct joycon_rumble_freq_data freq_data_low;
1939 	struct joycon_rumble_freq_data freq_data_high;
1940 	struct joycon_rumble_amp_data amp_data;
1941 
1942 	freq_data_low = joycon_find_rumble_freq(freq_low);
1943 	freq_data_high = joycon_find_rumble_freq(freq_high);
1944 	amp_data = joycon_find_rumble_amp(amp);
1945 
1946 	data[0] = (freq_data_high.high >> 8) & 0xFF;
1947 	data[1] = (freq_data_high.high & 0xFF) + amp_data.high;
1948 	data[2] = freq_data_low.low + ((amp_data.low >> 8) & 0xFF);
1949 	data[3] = amp_data.low & 0xFF;
1950 }
1951 
1952 static const u16 JOYCON_MAX_RUMBLE_HIGH_FREQ	= 1253;
1953 static const u16 JOYCON_MIN_RUMBLE_HIGH_FREQ	= 82;
1954 static const u16 JOYCON_MAX_RUMBLE_LOW_FREQ	= 626;
1955 static const u16 JOYCON_MIN_RUMBLE_LOW_FREQ	= 41;
1956 
1957 static void joycon_clamp_rumble_freqs(struct joycon_ctlr *ctlr)
1958 {
1959 	unsigned long flags;
1960 
1961 	spin_lock_irqsave(&ctlr->lock, flags);
1962 	ctlr->rumble_ll_freq = clamp(ctlr->rumble_ll_freq,
1963 				     JOYCON_MIN_RUMBLE_LOW_FREQ,
1964 				     JOYCON_MAX_RUMBLE_LOW_FREQ);
1965 	ctlr->rumble_lh_freq = clamp(ctlr->rumble_lh_freq,
1966 				     JOYCON_MIN_RUMBLE_HIGH_FREQ,
1967 				     JOYCON_MAX_RUMBLE_HIGH_FREQ);
1968 	ctlr->rumble_rl_freq = clamp(ctlr->rumble_rl_freq,
1969 				     JOYCON_MIN_RUMBLE_LOW_FREQ,
1970 				     JOYCON_MAX_RUMBLE_LOW_FREQ);
1971 	ctlr->rumble_rh_freq = clamp(ctlr->rumble_rh_freq,
1972 				     JOYCON_MIN_RUMBLE_HIGH_FREQ,
1973 				     JOYCON_MAX_RUMBLE_HIGH_FREQ);
1974 	spin_unlock_irqrestore(&ctlr->lock, flags);
1975 }
1976 
1977 static int joycon_set_rumble(struct joycon_ctlr *ctlr, u16 amp_r, u16 amp_l,
1978 			     bool schedule_now)
1979 {
1980 	u8 data[JC_RUMBLE_DATA_SIZE];
1981 	u16 amp;
1982 	u16 freq_r_low;
1983 	u16 freq_r_high;
1984 	u16 freq_l_low;
1985 	u16 freq_l_high;
1986 	unsigned long flags;
1987 	int next_rq_head;
1988 
1989 	spin_lock_irqsave(&ctlr->lock, flags);
1990 	freq_r_low = ctlr->rumble_rl_freq;
1991 	freq_r_high = ctlr->rumble_rh_freq;
1992 	freq_l_low = ctlr->rumble_ll_freq;
1993 	freq_l_high = ctlr->rumble_lh_freq;
1994 	/* limit number of silent rumble packets to reduce traffic */
1995 	if (amp_l != 0 || amp_r != 0)
1996 		ctlr->rumble_zero_countdown = JC_RUMBLE_ZERO_AMP_PKT_CNT;
1997 	spin_unlock_irqrestore(&ctlr->lock, flags);
1998 
1999 	/* right joy-con */
2000 	amp = amp_r * (u32)joycon_max_rumble_amp / 65535;
2001 	joycon_encode_rumble(data + 4, freq_r_low, freq_r_high, amp);
2002 
2003 	/* left joy-con */
2004 	amp = amp_l * (u32)joycon_max_rumble_amp / 65535;
2005 	joycon_encode_rumble(data, freq_l_low, freq_l_high, amp);
2006 
2007 	spin_lock_irqsave(&ctlr->lock, flags);
2008 
2009 	next_rq_head = ctlr->rumble_queue_head + 1;
2010 	if (next_rq_head >= JC_RUMBLE_QUEUE_SIZE)
2011 		next_rq_head = 0;
2012 
2013 	/* Did we overrun the circular buffer?
2014 	 * If so, be sure we keep the latest intended rumble state.
2015 	 */
2016 	if (next_rq_head == ctlr->rumble_queue_tail) {
2017 		hid_dbg(ctlr->hdev, "rumble queue is full");
2018 		/* overwrite the prior value at the end of the circular buf */
2019 		next_rq_head = ctlr->rumble_queue_head;
2020 	}
2021 
2022 	ctlr->rumble_queue_head = next_rq_head;
2023 	memcpy(ctlr->rumble_data[ctlr->rumble_queue_head], data,
2024 	       JC_RUMBLE_DATA_SIZE);
2025 
2026 	/* don't wait for the periodic send (reduces latency) */
2027 	if (schedule_now && ctlr->ctlr_state != JOYCON_CTLR_STATE_REMOVED)
2028 		queue_work(ctlr->rumble_queue, &ctlr->rumble_worker);
2029 
2030 	spin_unlock_irqrestore(&ctlr->lock, flags);
2031 
2032 	return 0;
2033 }
2034 
2035 static int joycon_play_effect(struct input_dev *dev, void *data,
2036 						     struct ff_effect *effect)
2037 {
2038 	struct joycon_ctlr *ctlr = input_get_drvdata(dev);
2039 
2040 	if (effect->type != FF_RUMBLE)
2041 		return 0;
2042 
2043 	return joycon_set_rumble(ctlr,
2044 				 effect->u.rumble.weak_magnitude,
2045 				 effect->u.rumble.strong_magnitude,
2046 				 true);
2047 }
2048 #endif /* IS_ENABLED(CONFIG_NINTENDO_FF) */
2049 
2050 static void joycon_config_left_stick(struct input_dev *idev)
2051 {
2052 	input_set_abs_params(idev,
2053 			     ABS_X,
2054 			     -JC_MAX_STICK_MAG,
2055 			     JC_MAX_STICK_MAG,
2056 			     JC_STICK_FUZZ,
2057 			     JC_STICK_FLAT);
2058 	input_set_abs_params(idev,
2059 			     ABS_Y,
2060 			     -JC_MAX_STICK_MAG,
2061 			     JC_MAX_STICK_MAG,
2062 			     JC_STICK_FUZZ,
2063 			     JC_STICK_FLAT);
2064 }
2065 
2066 static void joycon_config_right_stick(struct input_dev *idev)
2067 {
2068 	input_set_abs_params(idev,
2069 			     ABS_RX,
2070 			     -JC_MAX_STICK_MAG,
2071 			     JC_MAX_STICK_MAG,
2072 			     JC_STICK_FUZZ,
2073 			     JC_STICK_FLAT);
2074 	input_set_abs_params(idev,
2075 			     ABS_RY,
2076 			     -JC_MAX_STICK_MAG,
2077 			     JC_MAX_STICK_MAG,
2078 			     JC_STICK_FUZZ,
2079 			     JC_STICK_FLAT);
2080 }
2081 
2082 static void joycon_config_dpad(struct input_dev *idev)
2083 {
2084 	input_set_abs_params(idev,
2085 			     ABS_HAT0X,
2086 			     -JC_MAX_DPAD_MAG,
2087 			     JC_MAX_DPAD_MAG,
2088 			     JC_DPAD_FUZZ,
2089 			     JC_DPAD_FLAT);
2090 	input_set_abs_params(idev,
2091 			     ABS_HAT0Y,
2092 			     -JC_MAX_DPAD_MAG,
2093 			     JC_MAX_DPAD_MAG,
2094 			     JC_DPAD_FUZZ,
2095 			     JC_DPAD_FLAT);
2096 }
2097 
2098 static void joycon_config_buttons(struct input_dev *idev,
2099 		 const struct joycon_ctlr_button_mapping button_mappings[])
2100 {
2101 	const struct joycon_ctlr_button_mapping *button;
2102 
2103 	for (button = button_mappings; button->code; button++)
2104 		input_set_capability(idev, EV_KEY, button->code);
2105 }
2106 
2107 static void joycon_config_rumble(struct joycon_ctlr *ctlr)
2108 {
2109 #if IS_ENABLED(CONFIG_NINTENDO_FF)
2110 	/* set up rumble */
2111 	input_set_capability(ctlr->input, EV_FF, FF_RUMBLE);
2112 	input_ff_create_memless(ctlr->input, NULL, joycon_play_effect);
2113 	ctlr->rumble_ll_freq = JC_RUMBLE_DFLT_LOW_FREQ;
2114 	ctlr->rumble_lh_freq = JC_RUMBLE_DFLT_HIGH_FREQ;
2115 	ctlr->rumble_rl_freq = JC_RUMBLE_DFLT_LOW_FREQ;
2116 	ctlr->rumble_rh_freq = JC_RUMBLE_DFLT_HIGH_FREQ;
2117 	joycon_clamp_rumble_freqs(ctlr);
2118 	joycon_set_rumble(ctlr, 0, 0, false);
2119 	ctlr->rumble_msecs = jiffies_to_msecs(jiffies);
2120 #endif
2121 }
2122 
2123 static int joycon_imu_input_create(struct joycon_ctlr *ctlr)
2124 {
2125 	struct hid_device *hdev;
2126 	const char *imu_name;
2127 	int ret;
2128 
2129 	hdev = ctlr->hdev;
2130 
2131 	/* configure the imu input device */
2132 	ctlr->imu_input = devm_input_allocate_device(&hdev->dev);
2133 	if (!ctlr->imu_input)
2134 		return -ENOMEM;
2135 
2136 	ctlr->imu_input->id.bustype = hdev->bus;
2137 	ctlr->imu_input->id.vendor = hdev->vendor;
2138 	ctlr->imu_input->id.product = hdev->product;
2139 	ctlr->imu_input->id.version = hdev->version;
2140 	ctlr->imu_input->uniq = ctlr->mac_addr_str;
2141 	ctlr->imu_input->phys = hdev->phys;
2142 
2143 	imu_name = devm_kasprintf(&hdev->dev, GFP_KERNEL, "%s (IMU)", ctlr->input->name);
2144 	if (!imu_name)
2145 		return -ENOMEM;
2146 
2147 	ctlr->imu_input->name = imu_name;
2148 
2149 	input_set_drvdata(ctlr->imu_input, ctlr);
2150 
2151 	/* configure imu axes */
2152 	input_set_abs_params(ctlr->imu_input, ABS_X,
2153 			     -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG,
2154 			     JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT);
2155 	input_set_abs_params(ctlr->imu_input, ABS_Y,
2156 			     -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG,
2157 			     JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT);
2158 	input_set_abs_params(ctlr->imu_input, ABS_Z,
2159 			     -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG,
2160 			     JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT);
2161 	input_abs_set_res(ctlr->imu_input, ABS_X, JC_IMU_ACCEL_RES_PER_G);
2162 	input_abs_set_res(ctlr->imu_input, ABS_Y, JC_IMU_ACCEL_RES_PER_G);
2163 	input_abs_set_res(ctlr->imu_input, ABS_Z, JC_IMU_ACCEL_RES_PER_G);
2164 
2165 	input_set_abs_params(ctlr->imu_input, ABS_RX,
2166 			     -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG,
2167 			     JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT);
2168 	input_set_abs_params(ctlr->imu_input, ABS_RY,
2169 			     -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG,
2170 			     JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT);
2171 	input_set_abs_params(ctlr->imu_input, ABS_RZ,
2172 			     -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG,
2173 			     JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT);
2174 
2175 	input_abs_set_res(ctlr->imu_input, ABS_RX, JC_IMU_GYRO_RES_PER_DPS);
2176 	input_abs_set_res(ctlr->imu_input, ABS_RY, JC_IMU_GYRO_RES_PER_DPS);
2177 	input_abs_set_res(ctlr->imu_input, ABS_RZ, JC_IMU_GYRO_RES_PER_DPS);
2178 
2179 	__set_bit(EV_MSC, ctlr->imu_input->evbit);
2180 	__set_bit(MSC_TIMESTAMP, ctlr->imu_input->mscbit);
2181 	__set_bit(INPUT_PROP_ACCELEROMETER, ctlr->imu_input->propbit);
2182 
2183 	ret = input_register_device(ctlr->imu_input);
2184 	if (ret)
2185 		return ret;
2186 
2187 	return 0;
2188 }
2189 
2190 static int joycon_input_create(struct joycon_ctlr *ctlr)
2191 {
2192 	struct hid_device *hdev;
2193 	int ret;
2194 
2195 	hdev = ctlr->hdev;
2196 
2197 	ctlr->input = devm_input_allocate_device(&hdev->dev);
2198 	if (!ctlr->input)
2199 		return -ENOMEM;
2200 	ctlr->input->id.bustype = hdev->bus;
2201 	ctlr->input->id.vendor = hdev->vendor;
2202 	ctlr->input->id.product = hdev->product;
2203 	ctlr->input->id.version = hdev->version;
2204 	ctlr->input->uniq = ctlr->mac_addr_str;
2205 	ctlr->input->name = hdev->name;
2206 	ctlr->input->phys = hdev->phys;
2207 	input_set_drvdata(ctlr->input, ctlr);
2208 
2209 	if (joycon_type_is_right_joycon(ctlr)) {
2210 		joycon_config_right_stick(ctlr->input);
2211 		joycon_config_buttons(ctlr->input, right_joycon_button_mappings);
2212 		if (!joycon_device_is_chrggrip(ctlr))
2213 			joycon_config_buttons(ctlr->input, right_joycon_s_button_mappings);
2214 	} else if (joycon_type_is_left_joycon(ctlr)) {
2215 		joycon_config_left_stick(ctlr->input);
2216 		joycon_config_buttons(ctlr->input, left_joycon_button_mappings);
2217 		if (!joycon_device_is_chrggrip(ctlr))
2218 			joycon_config_buttons(ctlr->input, left_joycon_s_button_mappings);
2219 	} else if (joycon_type_is_procon(ctlr)) {
2220 		joycon_config_left_stick(ctlr->input);
2221 		joycon_config_right_stick(ctlr->input);
2222 		joycon_config_dpad(ctlr->input);
2223 		if (ctlr->hdev->vendor == USB_VENDOR_ID_HORI)
2224 			joycon_config_buttons(ctlr->input, lic_hori_procon_button_mappings);
2225 		else
2226 			joycon_config_buttons(ctlr->input, procon_button_mappings);
2227 	} else if (joycon_type_is_any_nescon(ctlr)) {
2228 		joycon_config_dpad(ctlr->input);
2229 		joycon_config_buttons(ctlr->input, nescon_button_mappings);
2230 	} else if (joycon_type_is_snescon(ctlr)) {
2231 		joycon_config_dpad(ctlr->input);
2232 		joycon_config_buttons(ctlr->input, snescon_button_mappings);
2233 	} else if (joycon_type_is_gencon(ctlr)) {
2234 		joycon_config_dpad(ctlr->input);
2235 		joycon_config_buttons(ctlr->input, gencon_button_mappings);
2236 	} else if (joycon_type_is_n64con(ctlr)) {
2237 		joycon_config_dpad(ctlr->input);
2238 		joycon_config_left_stick(ctlr->input);
2239 		joycon_config_buttons(ctlr->input, n64con_button_mappings);
2240 	}
2241 
2242 	if (joycon_has_imu(ctlr)) {
2243 		ret = joycon_imu_input_create(ctlr);
2244 		if (ret)
2245 			return ret;
2246 	}
2247 
2248 	if (joycon_has_rumble(ctlr))
2249 		joycon_config_rumble(ctlr);
2250 
2251 	ret = input_register_device(ctlr->input);
2252 	if (ret)
2253 		return ret;
2254 
2255 	return 0;
2256 }
2257 
2258 /* Because the subcommand sets all the leds at once, the brightness argument is ignored */
2259 static int joycon_player_led_brightness_set(struct led_classdev *led,
2260 					    enum led_brightness brightness)
2261 {
2262 	struct device *dev = led->dev->parent;
2263 	struct hid_device *hdev = to_hid_device(dev);
2264 	struct joycon_ctlr *ctlr;
2265 	int val = 0;
2266 	int i;
2267 	int ret;
2268 
2269 	ctlr = hid_get_drvdata(hdev);
2270 	if (!ctlr) {
2271 		hid_err(hdev, "No controller data\n");
2272 		return -ENODEV;
2273 	}
2274 
2275 	for (i = 0; i < JC_NUM_LEDS; i++)
2276 		val |= ctlr->leds[i].brightness << i;
2277 
2278 	mutex_lock(&ctlr->output_mutex);
2279 	ret = joycon_set_player_leds(ctlr, 0, val);
2280 	mutex_unlock(&ctlr->output_mutex);
2281 
2282 	return ret;
2283 }
2284 
2285 static int joycon_home_led_brightness_set(struct led_classdev *led,
2286 					  enum led_brightness brightness)
2287 {
2288 	struct device *dev = led->dev->parent;
2289 	struct hid_device *hdev = to_hid_device(dev);
2290 	struct joycon_ctlr *ctlr;
2291 	int ret;
2292 
2293 	ctlr = hid_get_drvdata(hdev);
2294 	if (!ctlr) {
2295 		hid_err(hdev, "No controller data\n");
2296 		return -ENODEV;
2297 	}
2298 	mutex_lock(&ctlr->output_mutex);
2299 	ret = joycon_set_home_led(ctlr, brightness);
2300 	mutex_unlock(&ctlr->output_mutex);
2301 	return ret;
2302 }
2303 
2304 static DEFINE_IDA(nintendo_player_id_allocator);
2305 
2306 static int joycon_leds_create(struct joycon_ctlr *ctlr)
2307 {
2308 	struct hid_device *hdev = ctlr->hdev;
2309 	struct device *dev = &hdev->dev;
2310 	const char *d_name = dev_name(dev);
2311 	struct led_classdev *led;
2312 	int led_val = 0;
2313 	char *name;
2314 	int ret;
2315 	int i;
2316 	int player_led_pattern;
2317 
2318 	/* configure the player LEDs */
2319 	ctlr->player_id = U32_MAX;
2320 	ret = ida_alloc(&nintendo_player_id_allocator, GFP_KERNEL);
2321 	if (ret < 0) {
2322 		hid_warn(hdev, "Failed to allocate player ID, skipping; ret=%d\n", ret);
2323 		goto home_led;
2324 	}
2325 	ctlr->player_id = ret;
2326 	player_led_pattern = ret % JC_NUM_LED_PATTERNS;
2327 	hid_info(ctlr->hdev, "assigned player %d led pattern", player_led_pattern + 1);
2328 
2329 	for (i = 0; i < JC_NUM_LEDS; i++) {
2330 		name = devm_kasprintf(dev, GFP_KERNEL, "%s:%s:%s",
2331 				      d_name,
2332 				      "green",
2333 				      joycon_player_led_names[i]);
2334 		if (!name)
2335 			return -ENOMEM;
2336 
2337 		led = &ctlr->leds[i];
2338 		led->name = name;
2339 		led->brightness = joycon_player_led_patterns[player_led_pattern][i];
2340 		led->max_brightness = 1;
2341 		led->brightness_set_blocking =
2342 					joycon_player_led_brightness_set;
2343 		led->flags = LED_CORE_SUSPENDRESUME | LED_HW_PLUGGABLE;
2344 
2345 		led_val |= joycon_player_led_patterns[player_led_pattern][i] << i;
2346 	}
2347 	mutex_lock(&ctlr->output_mutex);
2348 	ret = joycon_set_player_leds(ctlr, 0, led_val);
2349 	mutex_unlock(&ctlr->output_mutex);
2350 	if (ret) {
2351 		hid_warn(hdev, "Failed to set players LEDs, skipping registration; ret=%d\n", ret);
2352 		goto home_led;
2353 	}
2354 
2355 	for (i = 0; i < JC_NUM_LEDS; i++) {
2356 		led = &ctlr->leds[i];
2357 		ret = devm_led_classdev_register(&hdev->dev, led);
2358 		if (ret) {
2359 			hid_err(hdev, "Failed to register player %d LED; ret=%d\n", i + 1, ret);
2360 			return ret;
2361 		}
2362 	}
2363 
2364 home_led:
2365 	/* configure the home LED */
2366 	if (jc_type_has_right(ctlr)) {
2367 		name = devm_kasprintf(dev, GFP_KERNEL, "%s:%s:%s",
2368 				      d_name,
2369 				      "blue",
2370 				      LED_FUNCTION_PLAYER5);
2371 		if (!name)
2372 			return -ENOMEM;
2373 
2374 		led = &ctlr->home_led;
2375 		led->name = name;
2376 		led->brightness = 0;
2377 		led->max_brightness = 0xF;
2378 		led->brightness_set_blocking = joycon_home_led_brightness_set;
2379 		led->flags = LED_CORE_SUSPENDRESUME | LED_HW_PLUGGABLE;
2380 
2381 		/* Set the home LED to 0 as default state */
2382 		mutex_lock(&ctlr->output_mutex);
2383 		ret = joycon_set_home_led(ctlr, 0);
2384 		mutex_unlock(&ctlr->output_mutex);
2385 		if (ret) {
2386 			hid_warn(hdev, "Failed to set home LED, skipping registration; ret=%d\n", ret);
2387 			return 0;
2388 		}
2389 
2390 		ret = devm_led_classdev_register(&hdev->dev, led);
2391 		if (ret) {
2392 			hid_err(hdev, "Failed to register home LED; ret=%d\n", ret);
2393 			return ret;
2394 		}
2395 	}
2396 
2397 	return 0;
2398 }
2399 
2400 static int joycon_battery_get_property(struct power_supply *supply,
2401 				       enum power_supply_property prop,
2402 				       union power_supply_propval *val)
2403 {
2404 	struct joycon_ctlr *ctlr = power_supply_get_drvdata(supply);
2405 	unsigned long flags;
2406 	int ret = 0;
2407 	u8 capacity;
2408 	bool charging;
2409 	bool powered;
2410 
2411 	spin_lock_irqsave(&ctlr->lock, flags);
2412 	capacity = ctlr->battery_capacity;
2413 	charging = ctlr->battery_charging;
2414 	powered = ctlr->host_powered;
2415 	spin_unlock_irqrestore(&ctlr->lock, flags);
2416 
2417 	switch (prop) {
2418 	case POWER_SUPPLY_PROP_PRESENT:
2419 		val->intval = 1;
2420 		break;
2421 	case POWER_SUPPLY_PROP_SCOPE:
2422 		val->intval = POWER_SUPPLY_SCOPE_DEVICE;
2423 		break;
2424 	case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
2425 		val->intval = capacity;
2426 		break;
2427 	case POWER_SUPPLY_PROP_STATUS:
2428 		if (charging)
2429 			val->intval = POWER_SUPPLY_STATUS_CHARGING;
2430 		else if (capacity == POWER_SUPPLY_CAPACITY_LEVEL_FULL &&
2431 			 powered)
2432 			val->intval = POWER_SUPPLY_STATUS_FULL;
2433 		else
2434 			val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
2435 		break;
2436 	default:
2437 		ret = -EINVAL;
2438 		break;
2439 	}
2440 	return ret;
2441 }
2442 
2443 static enum power_supply_property joycon_battery_props[] = {
2444 	POWER_SUPPLY_PROP_PRESENT,
2445 	POWER_SUPPLY_PROP_CAPACITY_LEVEL,
2446 	POWER_SUPPLY_PROP_SCOPE,
2447 	POWER_SUPPLY_PROP_STATUS,
2448 };
2449 
2450 static int joycon_power_supply_create(struct joycon_ctlr *ctlr)
2451 {
2452 	struct hid_device *hdev = ctlr->hdev;
2453 	struct power_supply_config supply_config = { .drv_data = ctlr, };
2454 	const char * const name_fmt = "nintendo_switch_controller_battery_%s";
2455 	int ret = 0;
2456 
2457 	/* Set initially to unknown before receiving first input report */
2458 	ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
2459 
2460 	/* Configure the battery's description */
2461 	ctlr->battery_desc.properties = joycon_battery_props;
2462 	ctlr->battery_desc.num_properties =
2463 					ARRAY_SIZE(joycon_battery_props);
2464 	ctlr->battery_desc.get_property = joycon_battery_get_property;
2465 	ctlr->battery_desc.type = POWER_SUPPLY_TYPE_BATTERY;
2466 	ctlr->battery_desc.use_for_apm = 0;
2467 	ctlr->battery_desc.name = devm_kasprintf(&hdev->dev, GFP_KERNEL,
2468 						 name_fmt,
2469 						 dev_name(&hdev->dev));
2470 	if (!ctlr->battery_desc.name)
2471 		return -ENOMEM;
2472 
2473 	ctlr->battery = devm_power_supply_register(&hdev->dev,
2474 						   &ctlr->battery_desc,
2475 						   &supply_config);
2476 	if (IS_ERR(ctlr->battery)) {
2477 		ret = PTR_ERR(ctlr->battery);
2478 		hid_err(hdev, "Failed to register battery; ret=%d\n", ret);
2479 		return ret;
2480 	}
2481 
2482 	return power_supply_powers(ctlr->battery, &hdev->dev);
2483 }
2484 
2485 static int joycon_read_info(struct joycon_ctlr *ctlr)
2486 {
2487 	int ret;
2488 	int i;
2489 	int j;
2490 	struct joycon_subcmd_request req = { 0 };
2491 	struct joycon_input_report *report;
2492 
2493 	req.subcmd_id = JC_SUBCMD_REQ_DEV_INFO;
2494 	ret = joycon_send_subcmd(ctlr, &req, 0, 2 * HZ);
2495 	if (ret) {
2496 		hid_err(ctlr->hdev, "Failed to get joycon info; ret=%d\n", ret);
2497 		return ret;
2498 	}
2499 
2500 	report = (struct joycon_input_report *)ctlr->input_buf;
2501 
2502 	for (i = 4, j = 0; j < 6; i++, j++)
2503 		ctlr->mac_addr[j] = report->subcmd_reply.data[i];
2504 
2505 	ctlr->mac_addr_str = devm_kasprintf(&ctlr->hdev->dev, GFP_KERNEL, "%pMU",
2506 					    ctlr->mac_addr);
2507 	if (!ctlr->mac_addr_str)
2508 		return -ENOMEM;
2509 	hid_info(ctlr->hdev, "controller MAC = %s\n", ctlr->mac_addr_str);
2510 
2511 	/*
2512 	 * Retrieve the type so we can distinguish the controller type
2513 	 * Unfortantly the hdev->product can't always be used due to a ?bug?
2514 	 * with the NSO Genesis controller. Over USB, it will report the
2515 	 * PID as 0x201E, but over bluetooth it will report the PID as 0x2017
2516 	 * which is the same as the NSO SNES controller. This is different from
2517 	 * the rest of the controllers which will report the same PID over USB
2518 	 * and bluetooth.
2519 	 */
2520 	ctlr->ctlr_type = report->subcmd_reply.data[2];
2521 	hid_dbg(ctlr->hdev, "controller type = 0x%02X\n", ctlr->ctlr_type);
2522 
2523 	return 0;
2524 }
2525 
2526 static int joycon_init(struct hid_device *hdev)
2527 {
2528 	struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
2529 	int ret = 0;
2530 
2531 	mutex_lock(&ctlr->output_mutex);
2532 	/* if handshake command fails, assume ble pro controller */
2533 	if (joycon_using_usb(ctlr) && !joycon_send_usb(ctlr, JC_USB_CMD_HANDSHAKE, HZ)) {
2534 		hid_dbg(hdev, "detected USB controller\n");
2535 		/* set baudrate for improved latency */
2536 		ret = joycon_send_usb(ctlr, JC_USB_CMD_BAUDRATE_3M, HZ);
2537 		if (ret) {
2538 			/*
2539 			 * We can function with the default baudrate.
2540 			 * Provide a warning, and continue on.
2541 			 */
2542 			hid_warn(hdev, "Failed to set baudrate (ret=%d), continuing anyway\n", ret);
2543 		}
2544 		/* handshake */
2545 		ret = joycon_send_usb(ctlr, JC_USB_CMD_HANDSHAKE, HZ);
2546 		if (ret) {
2547 			hid_err(hdev, "Failed handshake; ret=%d\n", ret);
2548 			goto out_unlock;
2549 		}
2550 		/*
2551 		 * Set no timeout (to keep controller in USB mode).
2552 		 * This doesn't send a response, so ignore the timeout.
2553 		 */
2554 		joycon_send_usb(ctlr, JC_USB_CMD_NO_TIMEOUT, HZ/10);
2555 	} else if (jc_type_is_chrggrip(ctlr)) {
2556 		hid_err(hdev, "Failed charging grip handshake\n");
2557 		ret = -ETIMEDOUT;
2558 		goto out_unlock;
2559 	}
2560 
2561 	/* needed to retrieve the controller type */
2562 	ret = joycon_read_info(ctlr);
2563 	if (ret) {
2564 		hid_err(hdev, "Failed to retrieve controller info; ret=%d\n",
2565 			ret);
2566 		goto out_unlock;
2567 	}
2568 
2569 	if (joycon_has_joysticks(ctlr)) {
2570 		/* get controller calibration data, and parse it */
2571 		if (ctlr->ctlr_type == JOYCON_CTLR_TYPE_LIC_PRO) {
2572 			/*
2573 			 * Licensed controllers may have incompatible SPI flash
2574 			 * layouts. Use default calibration values.
2575 			 */
2576 			hid_info(hdev, "using default cal for licensed controller\n");
2577 			joycon_use_default_calibration(hdev,
2578 						       &ctlr->left_stick_cal_x,
2579 						       &ctlr->left_stick_cal_y,
2580 						       "left", 0);
2581 			joycon_use_default_calibration(hdev,
2582 						       &ctlr->right_stick_cal_x,
2583 						       &ctlr->right_stick_cal_y,
2584 						       "right", 0);
2585 		} else {
2586 			ret = joycon_request_calibration(ctlr);
2587 			if (ret) {
2588 				/*
2589 				 * We can function with default calibration, but
2590 				 * it may be inaccurate. Provide a warning, and
2591 				 * continue on.
2592 				 */
2593 				hid_warn(hdev, "Analog stick positions may be inaccurate\n");
2594 			}
2595 		}
2596 	}
2597 
2598 	if (joycon_has_imu(ctlr)) {
2599 		/* get IMU calibration data, and parse it */
2600 		ret = joycon_request_imu_calibration(ctlr);
2601 		if (ret) {
2602 			/*
2603 			 * We can function with default calibration, but it may be
2604 			 * inaccurate. Provide a warning, and continue on.
2605 			 */
2606 			hid_warn(hdev, "Unable to read IMU calibration data\n");
2607 		}
2608 
2609 		/* Enable the IMU */
2610 		ret = joycon_enable_imu(ctlr);
2611 		if (ret) {
2612 			if (ctlr->ctlr_type == JOYCON_CTLR_TYPE_LIC_PRO) {
2613 				hid_dbg(hdev, "IMU enable failed for licensed controller, continuing\n");
2614 				ret = 0;
2615 			} else {
2616 				hid_err(hdev, "Failed to enable the IMU; ret=%d\n", ret);
2617 				goto out_unlock;
2618 			}
2619 		}
2620 	}
2621 
2622 	/* Set the reporting mode to 0x30, which is the full report mode */
2623 	ret = joycon_set_report_mode(ctlr);
2624 	if (ret) {
2625 		hid_err(hdev, "Failed to set report mode; ret=%d\n", ret);
2626 		goto out_unlock;
2627 	}
2628 
2629 	if (joycon_has_rumble(ctlr)) {
2630 		/* Enable rumble */
2631 		ret = joycon_enable_rumble(ctlr);
2632 		if (ret) {
2633 			if (ctlr->ctlr_type == JOYCON_CTLR_TYPE_LIC_PRO) {
2634 				hid_dbg(hdev, "rumble enable failed for licensed controller, continuing\n");
2635 				ret = 0;
2636 			} else {
2637 				hid_err(hdev, "Failed to enable rumble; ret=%d\n", ret);
2638 				goto out_unlock;
2639 			}
2640 		}
2641 	}
2642 
2643 out_unlock:
2644 	mutex_unlock(&ctlr->output_mutex);
2645 	return ret;
2646 }
2647 
2648 /* Common handler for parsing inputs */
2649 static int joycon_ctlr_read_handler(struct joycon_ctlr *ctlr, u8 *data,
2650 							      int size)
2651 {
2652 	if (data[0] == JC_INPUT_SUBCMD_REPLY || data[0] == JC_INPUT_IMU_DATA ||
2653 	    data[0] == JC_INPUT_MCU_DATA) {
2654 		/*
2655 		 * The whole struct is cast and parsed below, including the
2656 		 * IMU/subcmd union, not just the 12-byte partial header this
2657 		 * used to check for.
2658 		 */
2659 		if (size >= sizeof(struct joycon_input_report))
2660 			joycon_parse_report(ctlr,
2661 					    (struct joycon_input_report *)data);
2662 	}
2663 
2664 	return 0;
2665 }
2666 
2667 static int joycon_ctlr_handle_event(struct joycon_ctlr *ctlr, u8 *data,
2668 							      int size)
2669 {
2670 	int ret = 0;
2671 	bool match = false;
2672 	struct joycon_input_report *report;
2673 
2674 	if (unlikely(mutex_is_locked(&ctlr->output_mutex)) &&
2675 	    ctlr->msg_type != JOYCON_MSG_TYPE_NONE) {
2676 		switch (ctlr->msg_type) {
2677 		case JOYCON_MSG_TYPE_USB:
2678 			if (size < 2)
2679 				break;
2680 			if (data[0] == JC_INPUT_USB_RESPONSE &&
2681 			    data[1] == ctlr->usb_ack_match)
2682 				match = true;
2683 			break;
2684 		case JOYCON_MSG_TYPE_SUBCMD:
2685 			if (size < sizeof(struct joycon_input_report) ||
2686 			    data[0] != JC_INPUT_SUBCMD_REPLY)
2687 				break;
2688 			report = (struct joycon_input_report *)data;
2689 			if (report->subcmd_reply.id == ctlr->subcmd_ack_match)
2690 				match = true;
2691 			break;
2692 		default:
2693 			break;
2694 		}
2695 
2696 		if (match) {
2697 			memcpy(ctlr->input_buf, data,
2698 			       min(size, (int)JC_MAX_RESP_SIZE));
2699 			ctlr->msg_type = JOYCON_MSG_TYPE_NONE;
2700 			ctlr->received_resp = true;
2701 			wake_up(&ctlr->wait);
2702 
2703 			/* This message has been handled */
2704 			return 1;
2705 		}
2706 	}
2707 
2708 	if (ctlr->ctlr_state == JOYCON_CTLR_STATE_READ)
2709 		ret = joycon_ctlr_read_handler(ctlr, data, size);
2710 
2711 	return ret;
2712 }
2713 
2714 static int joycon_event(struct hid_device *hdev,
2715 			      struct hid_report *report, u8 *raw_data, int size)
2716 {
2717 	struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
2718 
2719 	if (size < 1)
2720 		return -EINVAL;
2721 
2722 	return joycon_ctlr_handle_event(ctlr, raw_data, size);
2723 }
2724 
2725 static int joycon_probe(struct hid_device *hdev,
2726 			    const struct hid_device_id *id)
2727 {
2728 	int ret;
2729 	struct joycon_ctlr *ctlr;
2730 
2731 	hid_dbg(hdev, "probe - start\n");
2732 
2733 	ctlr = devm_kzalloc(&hdev->dev, sizeof(*ctlr), GFP_KERNEL);
2734 	if (!ctlr) {
2735 		ret = -ENOMEM;
2736 		goto err;
2737 	}
2738 
2739 	ctlr->hdev = hdev;
2740 	ctlr->ctlr_state = JOYCON_CTLR_STATE_INIT;
2741 	ctlr->rumble_queue_head = 0;
2742 	ctlr->rumble_queue_tail = 0;
2743 	hid_set_drvdata(hdev, ctlr);
2744 	mutex_init(&ctlr->output_mutex);
2745 	init_waitqueue_head(&ctlr->wait);
2746 	spin_lock_init(&ctlr->lock);
2747 	ctlr->rumble_queue = alloc_workqueue("hid-nintendo-rumble_wq",
2748 					     WQ_FREEZABLE | WQ_MEM_RECLAIM | WQ_PERCPU,
2749 					     0);
2750 	if (!ctlr->rumble_queue) {
2751 		ret = -ENOMEM;
2752 		goto err;
2753 	}
2754 	INIT_WORK(&ctlr->rumble_worker, joycon_rumble_worker);
2755 
2756 	ret = hid_parse(hdev);
2757 	if (ret) {
2758 		hid_err(hdev, "HID parse failed\n");
2759 		goto err_wq;
2760 	}
2761 
2762 	/*
2763 	 * Patch the hw version of pro controller/joycons, so applications can
2764 	 * distinguish between the default HID mappings and the mappings defined
2765 	 * by the Linux game controller spec. This is important for the SDL2
2766 	 * library, which has a game controller database, which uses device ids
2767 	 * in combination with version as a key.
2768 	 */
2769 	hdev->version |= 0x8000;
2770 
2771 	ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
2772 	if (ret) {
2773 		hid_err(hdev, "HW start failed\n");
2774 		goto err_wq;
2775 	}
2776 
2777 	ret = hid_hw_open(hdev);
2778 	if (ret) {
2779 		hid_err(hdev, "cannot start hardware I/O\n");
2780 		goto err_stop;
2781 	}
2782 
2783 	hid_device_io_start(hdev);
2784 
2785 	ret = joycon_init(hdev);
2786 	if (ret) {
2787 		hid_err(hdev, "Failed to initialize controller; ret=%d\n", ret);
2788 		goto err_io_stop;
2789 	}
2790 
2791 	/* Initialize the leds */
2792 	ret = joycon_leds_create(ctlr);
2793 	if (ret) {
2794 		hid_err(hdev, "Failed to create leds; ret=%d\n", ret);
2795 		goto err_io_stop;
2796 	}
2797 
2798 	/* Initialize the battery power supply */
2799 	ret = joycon_power_supply_create(ctlr);
2800 	if (ret) {
2801 		hid_err(hdev, "Failed to create power_supply; ret=%d\n", ret);
2802 		goto err_ida;
2803 	}
2804 
2805 	ret = joycon_input_create(ctlr);
2806 	if (ret) {
2807 		hid_err(hdev, "Failed to create input device; ret=%d\n", ret);
2808 		goto err_ida;
2809 	}
2810 
2811 	ctlr->ctlr_state = JOYCON_CTLR_STATE_READ;
2812 
2813 	hid_dbg(hdev, "probe - success\n");
2814 	return 0;
2815 
2816 err_ida:
2817 	ida_free(&nintendo_player_id_allocator, ctlr->player_id);
2818 err_io_stop:
2819 	hid_device_io_stop(hdev);
2820 	hid_hw_close(hdev);
2821 err_stop:
2822 	hid_hw_stop(hdev);
2823 err_wq:
2824 	destroy_workqueue(ctlr->rumble_queue);
2825 err:
2826 	hid_err(hdev, "probe - fail = %d\n", ret);
2827 	return ret;
2828 }
2829 
2830 static void joycon_remove(struct hid_device *hdev)
2831 {
2832 	struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
2833 	unsigned long flags;
2834 
2835 	hid_dbg(hdev, "remove\n");
2836 
2837 	/* Prevent further attempts at sending subcommands. */
2838 	spin_lock_irqsave(&ctlr->lock, flags);
2839 	ctlr->ctlr_state = JOYCON_CTLR_STATE_REMOVED;
2840 	spin_unlock_irqrestore(&ctlr->lock, flags);
2841 
2842 	destroy_workqueue(ctlr->rumble_queue);
2843 	ida_free(&nintendo_player_id_allocator, ctlr->player_id);
2844 
2845 	hid_hw_close(hdev);
2846 	hid_hw_stop(hdev);
2847 }
2848 
2849 static int joycon_resume(struct hid_device *hdev)
2850 {
2851 	struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
2852 	int ret;
2853 
2854 	hid_dbg(hdev, "resume\n");
2855 	if (!joycon_using_usb(ctlr)) {
2856 		hid_dbg(hdev, "no-op resume for bt ctlr\n");
2857 		ctlr->ctlr_state = JOYCON_CTLR_STATE_READ;
2858 		return 0;
2859 	}
2860 
2861 	ret = joycon_init(hdev);
2862 	if (ret)
2863 		hid_err(hdev,
2864 			"Failed to restore controller after resume: %d\n",
2865 			ret);
2866 	else
2867 		ctlr->ctlr_state = JOYCON_CTLR_STATE_READ;
2868 
2869 	return ret;
2870 }
2871 
2872 static int joycon_suspend(struct hid_device *hdev, pm_message_t message)
2873 {
2874 	struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
2875 
2876 	hid_dbg(hdev, "suspend: %d\n", message.event);
2877 	/*
2878 	 * Avoid any blocking loops in suspend/resume transitions.
2879 	 *
2880 	 * joycon_enforce_subcmd_rate() can result in repeated retries if for
2881 	 * whatever reason the controller stops providing input reports.
2882 	 *
2883 	 * This has been observed with bluetooth controllers which lose
2884 	 * connectivity prior to suspend (but not long enough to result in
2885 	 * complete disconnection).
2886 	 */
2887 	ctlr->ctlr_state = JOYCON_CTLR_STATE_SUSPENDED;
2888 	return 0;
2889 }
2890 
2891 /*
2892  * =============================================================================
2893  * Switch 2 support
2894  * =============================================================================
2895  */
2896 #define NS2_BTNR_B	BIT(0)
2897 #define NS2_BTNR_A	BIT(1)
2898 #define NS2_BTNR_Y	BIT(2)
2899 #define NS2_BTNR_X	BIT(3)
2900 #define NS2_BTNR_R	BIT(4)
2901 #define NS2_BTNR_ZR	BIT(5)
2902 #define NS2_BTNR_PLUS	BIT(6)
2903 #define NS2_BTNR_RS	BIT(7)
2904 
2905 #define NS2_BTNL_DOWN	BIT(0)
2906 #define NS2_BTNL_RIGHT	BIT(1)
2907 #define NS2_BTNL_LEFT	BIT(2)
2908 #define NS2_BTNL_UP	BIT(3)
2909 #define NS2_BTNL_L	BIT(4)
2910 #define NS2_BTNL_ZL	BIT(5)
2911 #define NS2_BTNL_MINUS	BIT(6)
2912 #define NS2_BTNL_LS	BIT(7)
2913 
2914 #define NS2_BTN3_C	BIT(4)
2915 #define NS2_BTN3_SR	BIT(6)
2916 #define NS2_BTN3_SL	BIT(7)
2917 
2918 #define NS2_BTN_U1_Y	BIT(0)
2919 #define NS2_BTN_U1_X	BIT(1)
2920 #define NS2_BTN_U1_B	BIT(2)
2921 #define NS2_BTN_U1_A	BIT(3)
2922 #define NS2_BTN_U1_SR	BIT(4)
2923 #define NS2_BTN_U1_SL	BIT(5)
2924 #define NS2_BTN_U1_R	BIT(6)
2925 #define NS2_BTN_U1_ZR	BIT(7)
2926 
2927 #define NS2_BTN_U2_MINUS	BIT(0)
2928 #define NS2_BTN_U2_PLUS		BIT(1)
2929 #define NS2_BTN_U2_RS		BIT(2)
2930 #define NS2_BTN_U2_LS		BIT(3)
2931 #define NS2_BTN_U2_HOME		BIT(4)
2932 #define NS2_BTN_U2_CAPTURE	BIT(5)
2933 #define NS2_BTN_U2_C		BIT(6)
2934 
2935 #define NS2_BTN_U3_DOWN		BIT(0)
2936 #define NS2_BTN_U3_UP		BIT(1)
2937 #define NS2_BTN_U3_RIGHT	BIT(2)
2938 #define NS2_BTN_U3_LEFT		BIT(3)
2939 #define NS2_BTN_U3_SR		BIT(4)
2940 #define NS2_BTN_U3_SL		BIT(5)
2941 #define NS2_BTN_U3_L		BIT(6)
2942 #define NS2_BTN_U3_ZL		BIT(7)
2943 
2944 #define NS2_BTN_U4_GR		BIT(0)
2945 #define NS2_BTN_U4_GL		BIT(1)
2946 #define NS2_BTN_U4_HEADSET	BIT(5)
2947 
2948 #define NS2_BTN_JCR_HOME	BIT(0)
2949 #define NS2_BTN_JCR_GR		BIT(2)
2950 #define NS2_BTN_JCR_C		NS2_BTN3_C
2951 #define NS2_BTN_JCR_SR		NS2_BTN3_SR
2952 #define NS2_BTN_JCR_SL		NS2_BTN3_SL
2953 
2954 #define NS2_BTN_JCL_CAPTURE	BIT(0)
2955 #define NS2_BTN_JCL_GL		BIT(2)
2956 #define NS2_BTN_JCL_SR		NS2_BTN3_SR
2957 #define NS2_BTN_JCL_SL		NS2_BTN3_SL
2958 
2959 #define NS2_BTN_PRO_HOME	BIT(0)
2960 #define NS2_BTN_PRO_CAPTURE	BIT(1)
2961 #define NS2_BTN_PRO_GR		BIT(2)
2962 #define NS2_BTN_PRO_GL		BIT(3)
2963 #define NS2_BTN_PRO_C		NS2_BTN3_C
2964 
2965 #define NS2_BTN_GC_HOME		BIT(0)
2966 #define NS2_BTN_GC_CAPTURE	BIT(1)
2967 #define NS2_BTN_GC_C		NS2_BTN3_C
2968 
2969 #define NS2_TRIGGER_RANGE	4095
2970 #define NS2_AXIS_MIN		-32768
2971 #define NS2_AXIS_MAX		32767
2972 
2973 #define NS2_MAX_PLAYER_ID	8
2974 
2975 #define NS2_MAX_INIT_RETRIES	4
2976 
2977 #define NS2_FLASH_ADDR_SERIAL			0x13002
2978 #define NS2_FLASH_ADDR_FACTORY_PRIMARY_CALIB	0x130a8
2979 #define NS2_FLASH_ADDR_FACTORY_SECONDARY_CALIB	0x130e8
2980 #define NS2_FLASH_ADDR_FACTORY_TRIGGER_CALIB	0x13140
2981 #define NS2_FLASH_ADDR_USER_PRIMARY_CALIB	0x1fc040
2982 #define NS2_FLASH_ADDR_USER_SECONDARY_CALIB	0x1fc080
2983 
2984 #define NS2_FLASH_SIZE_SERIAL 0x10
2985 #define NS2_FLASH_SIZE_FACTORY_AXIS_CALIB 9
2986 #define NS2_FLASH_SIZE_FACTORY_TRIGGER_CALIB 2
2987 #define NS2_FLASH_SIZE_USER_AXIS_CALIB 11
2988 
2989 #define NS2_USER_CALIB_MAGIC 0xa1b2
2990 
2991 #define NS2_FEATURE_BUTTONS	BIT(0)
2992 #define NS2_FEATURE_ANALOG	BIT(1)
2993 #define NS2_FEATURE_IMU		BIT(2)
2994 #define NS2_FEATURE_MOUSE	BIT(4)
2995 #define NS2_FEATURE_RUMBLE	BIT(5)
2996 #define NS2_FEATURE_MAGNETO	BIT(7)
2997 
2998 enum switch2_subcmd_flash {
2999 	NS2_SUBCMD_FLASH_READ_BLOCK = 0x01,
3000 	NS2_SUBCMD_FLASH_WRITE_BLOCK = 0x02,
3001 	NS2_SUBCMD_FLASH_ERASE_BLOCK = 0x03,
3002 	NS2_SUBCMD_FLASH_READ = 0x04,
3003 	NS2_SUBCMD_FLASH_WRITE = 0x05,
3004 };
3005 
3006 enum switch2_subcmd_init {
3007 	NS2_SUBCMD_INIT_SELECT_REPORT = 0xa,
3008 	NS2_SUBCMD_INIT_USB = 0xd,
3009 };
3010 
3011 enum switch2_subcmd_feature_select {
3012 	NS2_SUBCMD_FEATSEL_GET_INFO = 0x1,
3013 	NS2_SUBCMD_FEATSEL_SET_MASK = 0x2,
3014 	NS2_SUBCMD_FEATSEL_CLEAR_MASK = 0x3,
3015 	NS2_SUBCMD_FEATSEL_ENABLE = 0x4,
3016 	NS2_SUBCMD_FEATSEL_DISABLE = 0x5,
3017 };
3018 
3019 enum switch2_subcmd_grip {
3020 	NS2_SUBCMD_GRIP_GET_INFO = 0x1,
3021 	NS2_SUBCMD_GRIP_ENABLE_BUTTONS = 0x2,
3022 	NS2_SUBCMD_GRIP_GET_INFO_EXT = 0x3,
3023 };
3024 
3025 enum switch2_subcmd_led {
3026 	NS2_SUBCMD_LED_P1 = 0x1,
3027 	NS2_SUBCMD_LED_P2 = 0x2,
3028 	NS2_SUBCMD_LED_P3 = 0x3,
3029 	NS2_SUBCMD_LED_P4 = 0x4,
3030 	NS2_SUBCMD_LED_ALL_ON = 0x5,
3031 	NS2_SUBCMD_LED_ALL_OFF = 0x6,
3032 	NS2_SUBCMD_LED_PATTERN = 0x7,
3033 	NS2_SUBCMD_LED_BLINK = 0x8,
3034 };
3035 
3036 enum switch2_subcmd_fw_info {
3037 	NS2_SUBCMD_FW_INFO_GET = 0x1,
3038 };
3039 
3040 enum switch2_ctlr_type {
3041 	NS2_CTLR_TYPE_JCL = 0x00,
3042 	NS2_CTLR_TYPE_JCR = 0x01,
3043 	NS2_CTLR_TYPE_PRO = 0x02,
3044 	NS2_CTLR_TYPE_GC = 0x03,
3045 };
3046 
3047 enum switch2_report_id {
3048 	NS2_REPORT_UNIFIED = 0x05,
3049 	NS2_REPORT_JCL = 0x07,
3050 	NS2_REPORT_JCR = 0x08,
3051 	NS2_REPORT_PRO = 0x09,
3052 	NS2_REPORT_GC = 0x0a,
3053 };
3054 
3055 enum switch2_init_step {
3056 	NS2_INIT_READ_SERIAL,
3057 	NS2_INIT_GET_FIRMWARE_INFO,
3058 	NS2_INIT_READ_FACTORY_PRIMARY_CALIB,
3059 	NS2_INIT_READ_FACTORY_SECONDARY_CALIB,
3060 	NS2_INIT_READ_FACTORY_TRIGGER_CALIB,
3061 	NS2_INIT_READ_USER_PRIMARY_CALIB,
3062 	NS2_INIT_READ_USER_SECONDARY_CALIB,
3063 	NS2_INIT_SET_FEATURE_MASK,
3064 	NS2_INIT_ENABLE_FEATURES,
3065 	NS2_INIT_ENABLE_RUMBLE,
3066 	NS2_INIT_GRIP_BUTTONS,
3067 	NS2_INIT_REPORT_FORMAT,
3068 	NS2_INIT_INPUT,
3069 	NS2_INIT_SET_PLAYER_LEDS,
3070 	NS2_INIT_FINISH,
3071 	NS2_INIT_DONE,
3072 };
3073 
3074 struct switch2_version_info {
3075 	uint8_t major;
3076 	uint8_t minor;
3077 	uint8_t patch;
3078 	uint8_t ctlr_type;
3079 	__le32 unk;
3080 	int8_t dsp_major;
3081 	int8_t dsp_minor;
3082 	int8_t dsp_patch;
3083 	int8_t dsp_type;
3084 };
3085 
3086 struct switch2_axis_calibration {
3087 	uint16_t neutral;
3088 	uint16_t negative;
3089 	uint16_t positive;
3090 };
3091 
3092 struct switch2_stick_calibration {
3093 	struct switch2_axis_calibration x;
3094 	struct switch2_axis_calibration y;
3095 };
3096 
3097 struct switch2_hd_rumble {
3098 	uint16_t hi_freq : 10;
3099 	uint16_t hi_amp : 10;
3100 	uint16_t lo_freq : 10;
3101 	uint16_t lo_amp : 10;
3102 } __packed;
3103 
3104 struct switch2_erm_rumble {
3105 	uint16_t error;
3106 	uint16_t amplitude;
3107 };
3108 
3109 struct switch2_controller {
3110 	struct hid_device *hdev;
3111 	struct switch2_cfg_intf *cfg;
3112 	struct kref refcount;
3113 
3114 	char name[64];
3115 	char phys[64];
3116 	struct list_head entry;
3117 	struct mutex lock;
3118 
3119 	enum switch2_ctlr_type ctlr_type;
3120 	enum switch2_init_step init_step;
3121 	int init_retries;
3122 	struct input_dev __rcu *input;
3123 	char serial[NS2_FLASH_SIZE_SERIAL + 1];
3124 	struct switch2_version_info version;
3125 
3126 	struct switch2_stick_calibration stick_calib[2];
3127 	uint8_t lt_zero;
3128 	uint8_t rt_zero;
3129 
3130 	uint32_t player_id;
3131 	struct led_classdev *leds;
3132 
3133 #if IS_ENABLED(CONFIG_NINTENDO_FF)
3134 	spinlock_t rumble_lock;
3135 	uint8_t rumble_seq;
3136 	union {
3137 		struct switch2_hd_rumble hd;
3138 		struct switch2_erm_rumble sd;
3139 	} rumble;
3140 	uint64_t last_rumble_work;
3141 	struct delayed_work rumble_work;
3142 	uint8_t *rumble_buffer;
3143 #endif
3144 };
3145 
3146 enum gc_rumble {
3147 	GC_RUMBLE_OFF = 0,
3148 	GC_RUMBLE_ON = 1,
3149 	GC_RUMBLE_STOP = 2,
3150 };
3151 
3152 /*
3153  * The highest rumble level for "HD Rumble" is strong enough to potentially damage the controller,
3154  * and also leaves your hands feeling like melted jelly, so we set a semi-arbitrary scaling factor
3155  * to artificially limit the maximum for safety and comfort. It is currently unknown if the Switch
3156  * 2 itself does something similar, but it's quite likely.
3157  *
3158  * This value must be between 0 and 1024, otherwise the math below will overflow.
3159  */
3160 #define RUMBLE_MAX 450u
3161 
3162 /*
3163  * Semi-arbitrary values used to simulate the "rumble" sensation of an eccentric rotating
3164  * mass type haptic motor on the Switch 2 controllers' linear resonant actuator type haptics.
3165  *
3166  * The units used are unknown, but the values must be between 0 and 1023.
3167  */
3168 #define RUMBLE_HI_FREQ 0x187
3169 #define RUMBLE_LO_FREQ 0x112
3170 
3171 static DEFINE_MUTEX(switch2_controllers_lock);
3172 static LIST_HEAD(switch2_controllers);
3173 
3174 struct switch2_ctlr_button_mapping {
3175 	uint32_t code;
3176 	int byte;
3177 	uint32_t bit;
3178 };
3179 
3180 static const struct switch2_ctlr_button_mapping ns2_left_joycon_button_mappings[] = {
3181 	{ BTN_DPAD_LEFT,	0, NS2_BTNL_LEFT,	},
3182 	{ BTN_DPAD_UP,		0, NS2_BTNL_UP,		},
3183 	{ BTN_DPAD_DOWN,	0, NS2_BTNL_DOWN,	},
3184 	{ BTN_DPAD_RIGHT,	0, NS2_BTNL_RIGHT,	},
3185 	{ BTN_TL,		0, NS2_BTNL_L,		},
3186 	{ BTN_TL2,		0, NS2_BTNL_ZL,		},
3187 	{ BTN_SELECT,		0, NS2_BTNL_MINUS,	},
3188 	{ BTN_THUMBL,		0, NS2_BTNL_LS,		},
3189 	{ KEY_RECORD,		1, NS2_BTN_JCL_CAPTURE,	},
3190 	{ BTN_GRIPR,		1, NS2_BTN_JCL_SL,	},
3191 	{ BTN_GRIPR2,		1, NS2_BTN_JCL_SR,	},
3192 	{ BTN_GRIPL,		1, NS2_BTN_JCL_GL,	},
3193 	{ /* sentinel */ },
3194 };
3195 
3196 static const struct switch2_ctlr_button_mapping ns2_left_joycon_button_unified_mappings[] = {
3197 	{ BTN_DPAD_LEFT,	2, NS2_BTN_U3_LEFT,	},
3198 	{ BTN_DPAD_UP,		2, NS2_BTN_U3_UP,	},
3199 	{ BTN_DPAD_DOWN,	2, NS2_BTN_U3_DOWN,	},
3200 	{ BTN_DPAD_RIGHT,	2, NS2_BTN_U3_RIGHT,	},
3201 	{ BTN_TL,		2, NS2_BTN_U3_L,	},
3202 	{ BTN_TL2,		2, NS2_BTN_U3_ZL,	},
3203 	{ BTN_SELECT,		1, NS2_BTN_U2_MINUS,	},
3204 	{ BTN_THUMBL,		1, NS2_BTN_U2_LS,	},
3205 	{ KEY_RECORD,		1, NS2_BTN_U2_CAPTURE,	},
3206 	{ BTN_GRIPR,		2, NS2_BTN_U3_SL,	},
3207 	{ BTN_GRIPR2,		2, NS2_BTN_U3_SR,	},
3208 	{ BTN_GRIPL,		3, NS2_BTN_U4_GL,	},
3209 	{ /* sentinel */ },
3210 };
3211 
3212 static const struct switch2_ctlr_button_mapping ns2_right_joycon_button_mappings[] = {
3213 	{ BTN_SOUTH,	0, NS2_BTNR_A,		},
3214 	{ BTN_EAST,	0, NS2_BTNR_B,		},
3215 	{ BTN_NORTH,	0, NS2_BTNR_X,		},
3216 	{ BTN_WEST,	0, NS2_BTNR_Y,		},
3217 	{ BTN_TR,	0, NS2_BTNR_R,		},
3218 	{ BTN_TR2,	0, NS2_BTNR_ZR,		},
3219 	{ BTN_START,	0, NS2_BTNR_PLUS,	},
3220 	{ BTN_THUMBR,	0, NS2_BTNR_RS,		},
3221 	{ BTN_C,	1, NS2_BTN_JCR_C,	},
3222 	{ BTN_MODE,	1, NS2_BTN_JCR_HOME,	},
3223 	{ BTN_GRIPL2,	1, NS2_BTN_JCR_SL,	},
3224 	{ BTN_GRIPL,	1, NS2_BTN_JCR_SR,	},
3225 	{ BTN_GRIPR,	1, NS2_BTN_JCR_GR,	},
3226 	{ /* sentinel */ },
3227 };
3228 
3229 static const struct switch2_ctlr_button_mapping ns2_right_joycon_button_unified_mappings[] = {
3230 	{ BTN_SOUTH,	0, NS2_BTN_U1_A,	},
3231 	{ BTN_EAST,	0, NS2_BTN_U1_B,	},
3232 	{ BTN_NORTH,	0, NS2_BTN_U1_X,	},
3233 	{ BTN_WEST,	0, NS2_BTN_U1_Y,	},
3234 	{ BTN_TR,	0, NS2_BTN_U1_R,	},
3235 	{ BTN_TR2,	0, NS2_BTN_U1_ZR	},
3236 	{ BTN_START,	1, NS2_BTN_U2_PLUS,	},
3237 	{ BTN_THUMBR,	1, NS2_BTN_U2_RS,	},
3238 	{ BTN_C,	1, NS2_BTN_U2_C,	},
3239 	{ BTN_MODE,	1, NS2_BTN_U2_HOME,	},
3240 	{ BTN_GRIPL2,	0, NS2_BTN_U1_SL,	},
3241 	{ BTN_GRIPL,	0, NS2_BTN_U1_SR,	},
3242 	{ BTN_GRIPR,	3, NS2_BTN_U4_GR,	},
3243 	{ /* sentinel */ },
3244 };
3245 
3246 static const struct switch2_ctlr_button_mapping ns2_procon_mappings[] = {
3247 	{ BTN_SOUTH,	0, NS2_BTNR_A,		},
3248 	{ BTN_EAST,	0, NS2_BTNR_B,		},
3249 	{ BTN_NORTH,	0, NS2_BTNR_X,		},
3250 	{ BTN_WEST,	0, NS2_BTNR_Y,		},
3251 	{ BTN_TL,	1, NS2_BTNL_L,		},
3252 	{ BTN_TR,	0, NS2_BTNR_R,		},
3253 	{ BTN_TL2,	1, NS2_BTNL_ZL,		},
3254 	{ BTN_TR2,	0, NS2_BTNR_ZR,		},
3255 	{ BTN_SELECT,	1, NS2_BTNL_MINUS,	},
3256 	{ BTN_START,	0, NS2_BTNR_PLUS,	},
3257 	{ BTN_THUMBL,	1, NS2_BTNL_LS,		},
3258 	{ BTN_THUMBR,	0, NS2_BTNR_RS,		},
3259 	{ BTN_MODE,	2, NS2_BTN_PRO_HOME	},
3260 	{ KEY_RECORD,	2, NS2_BTN_PRO_CAPTURE	},
3261 	{ BTN_GRIPR,	2, NS2_BTN_PRO_GR	},
3262 	{ BTN_GRIPL,	2, NS2_BTN_PRO_GL	},
3263 	{ BTN_C,	2, NS2_BTN_PRO_C	},
3264 	{ /* sentinel */ },
3265 };
3266 
3267 static const struct switch2_ctlr_button_mapping ns2_procon_unified_mappings[] = {
3268 	{ BTN_SOUTH,	0, NS2_BTN_U1_A,	},
3269 	{ BTN_EAST,	0, NS2_BTN_U1_B,	},
3270 	{ BTN_NORTH,	0, NS2_BTN_U1_X,	},
3271 	{ BTN_WEST,	0, NS2_BTN_U1_Y,	},
3272 	{ BTN_TL,	2, NS2_BTN_U3_L,	},
3273 	{ BTN_TR,	0, NS2_BTN_U1_R,	},
3274 	{ BTN_TL2,	2, NS2_BTN_U3_ZL,	},
3275 	{ BTN_TR2,	0, NS2_BTN_U1_ZR,	},
3276 	{ BTN_SELECT,	1, NS2_BTN_U2_MINUS,	},
3277 	{ BTN_START,	1, NS2_BTN_U2_PLUS,	},
3278 	{ BTN_THUMBL,	1, NS2_BTN_U2_LS,	},
3279 	{ BTN_THUMBR,	1, NS2_BTN_U2_RS,	},
3280 	{ BTN_MODE,	1, NS2_BTN_U2_HOME	},
3281 	{ KEY_RECORD,	1, NS2_BTN_U2_CAPTURE	},
3282 	{ BTN_GRIPR,	3, NS2_BTN_U4_GR	},
3283 	{ BTN_GRIPL,	3, NS2_BTN_U4_GL	},
3284 	{ BTN_C,	1, NS2_BTN_U2_C		},
3285 	{ /* sentinel */ },
3286 };
3287 
3288 static const struct switch2_ctlr_button_mapping ns2_gccon_mappings[] = {
3289 	{ BTN_SOUTH,	0, NS2_BTNR_A,		},
3290 	{ BTN_EAST,	0, NS2_BTNR_B,		},
3291 	{ BTN_NORTH,	0, NS2_BTNR_X,		},
3292 	{ BTN_WEST,	0, NS2_BTNR_Y,		},
3293 	{ BTN_TL2,	1, NS2_BTNL_L,		},
3294 	{ BTN_TR2,	0, NS2_BTNR_R,		},
3295 	{ BTN_TL,	1, NS2_BTNL_ZL,		},
3296 	{ BTN_TR,	0, NS2_BTNR_ZR,		},
3297 	{ BTN_SELECT,	1, NS2_BTNL_MINUS,	},
3298 	{ BTN_START,	0, NS2_BTNR_PLUS,	},
3299 	{ BTN_MODE,	2, NS2_BTN_GC_HOME	},
3300 	{ KEY_RECORD,	2, NS2_BTN_GC_CAPTURE	},
3301 	{ BTN_C,	2, NS2_BTN_GC_C		},
3302 	{ /* sentinel */ },
3303 };
3304 
3305 static const struct switch2_ctlr_button_mapping ns2_gccon_unified_mappings[] = {
3306 	{ BTN_SOUTH,	0, NS2_BTN_U1_A,	},
3307 	{ BTN_EAST,	0, NS2_BTN_U1_B,	},
3308 	{ BTN_NORTH,	0, NS2_BTN_U1_X,	},
3309 	{ BTN_WEST,	0, NS2_BTN_U1_Y,	},
3310 	{ BTN_TL2,	2, NS2_BTN_U3_L,	},
3311 	{ BTN_TR2,	0, NS2_BTN_U1_R,	},
3312 	{ BTN_TL,	2, NS2_BTN_U3_ZL	},
3313 	{ BTN_TR,	0, NS2_BTN_U1_ZR	},
3314 	{ BTN_SELECT,	1, NS2_BTN_U2_MINUS,	},
3315 	{ BTN_START,	1, NS2_BTN_U2_PLUS,	},
3316 	{ BTN_MODE,	1, NS2_BTN_U2_HOME	},
3317 	{ KEY_RECORD,	1, NS2_BTN_U2_CAPTURE	},
3318 	{ BTN_C,	1, NS2_BTN_U2_C		},
3319 	{ /* sentinel */ },
3320 };
3321 
3322 static const uint8_t switch2_init_cmd_data[] = {
3323 	/*
3324 	 * The last 6 bytes of this packet are the MAC address of
3325 	 * the console, but we don't need that for USB
3326 	 */
3327 	0x01, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
3328 };
3329 
3330 static const uint8_t switch2_one_data[] = { 0x01, 0x00, 0x00, 0x00 };
3331 
3332 static const uint8_t switch2_feature_mask[] = {
3333 	NS2_FEATURE_BUTTONS | NS2_FEATURE_ANALOG | NS2_FEATURE_IMU | NS2_FEATURE_RUMBLE,
3334 	0x00, 0x00, 0x00
3335 };
3336 
3337 static int switch2_init_controller(struct switch2_controller *ns2);
3338 
3339 static void switch2_init_step_done(struct switch2_controller *ns2, enum switch2_init_step step)
3340 {
3341 	if (ns2->init_step != step)
3342 		return;
3343 
3344 	ns2->init_retries = 0;
3345 	ns2->init_step++;
3346 }
3347 
3348 static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type)
3349 {
3350 	return type == NS2_CTLR_TYPE_JCL || type == NS2_CTLR_TYPE_JCR;
3351 }
3352 
3353 static struct switch2_controller *switch2_get_controller(const char *phys)
3354 {
3355 	struct switch2_controller *ns2;
3356 
3357 	guard(mutex)(&switch2_controllers_lock);
3358 	list_for_each_entry(ns2, &switch2_controllers, entry) {
3359 		if (strncmp(ns2->phys, phys, sizeof(ns2->phys)) == 0) {
3360 			if (kref_get_unless_zero(&ns2->refcount))
3361 				return ns2;
3362 		}
3363 	}
3364 	ns2 = kzalloc_obj(*ns2);
3365 	if (!ns2)
3366 		return ERR_PTR(-ENOMEM);
3367 
3368 	kref_init(&ns2->refcount);
3369 	mutex_init(&ns2->lock);
3370 	INIT_LIST_HEAD(&ns2->entry);
3371 	list_add(&ns2->entry, &switch2_controllers);
3372 	strscpy(ns2->phys, phys, sizeof(ns2->phys));
3373 #if IS_ENABLED(CONFIG_NINTENDO_FF)
3374 	spin_lock_init(&ns2->rumble_lock);
3375 #endif
3376 	return ns2;
3377 }
3378 
3379 static void switch2_controller_put(struct switch2_controller *ns2)
3380 {
3381 	struct input_dev *input;
3382 
3383 	mutex_lock(&ns2->lock);
3384 	rcu_read_lock();
3385 	input = rcu_dereference(ns2->input);
3386 	rcu_read_unlock();
3387 
3388 	rcu_assign_pointer(ns2->input, NULL);
3389 	synchronize_rcu();
3390 
3391 	ns2->init_step = 0;
3392 	mutex_unlock(&ns2->lock);
3393 
3394 	if (input)
3395 		input_unregister_device(input);
3396 }
3397 
3398 static void switch2_kref_put(struct kref *refcount)
3399 {
3400 	struct switch2_controller *ns2 = container_of(refcount,
3401 					struct switch2_controller, refcount);
3402 
3403 	guard(mutex)(&switch2_controllers_lock);
3404 	list_del_init(&ns2->entry);
3405 	mutex_destroy(&ns2->lock);
3406 	kfree(ns2);
3407 }
3408 
3409 #if IS_ENABLED(CONFIG_NINTENDO_FF)
3410 static void switch2_encode_rumble(struct switch2_hd_rumble *rumble, uint8_t buffer[5])
3411 {
3412 	buffer[0] = rumble->hi_freq;
3413 	buffer[1] = (rumble->hi_freq >> 8) | (rumble->hi_amp << 2);
3414 	buffer[2] = (rumble->hi_amp >> 6) | (rumble->lo_freq << 4);
3415 	buffer[3] = (rumble->lo_freq >> 4) | (rumble->lo_amp << 6);
3416 	buffer[4] = rumble->lo_amp >> 2;
3417 }
3418 
3419 static int switch2_play_effect(struct input_dev *dev, void *data, struct ff_effect *effect)
3420 {
3421 	struct switch2_controller *ns2 = input_get_drvdata(dev);
3422 	unsigned long flags;
3423 
3424 	if (effect->type != FF_RUMBLE)
3425 		return 0;
3426 
3427 	if (!ns2)
3428 		return -ENODEV;
3429 
3430 	spin_lock_irqsave(&ns2->rumble_lock, flags);
3431 	if (ns2->ctlr_type == NS2_CTLR_TYPE_GC) {
3432 		ns2->rumble.sd.amplitude = max(effect->u.rumble.strong_magnitude,
3433 			(uint16_t) (effect->u.rumble.weak_magnitude >> 1));
3434 	} else {
3435 		ns2->rumble.hd.hi_freq = RUMBLE_HI_FREQ;
3436 		ns2->rumble.hd.lo_freq = RUMBLE_LO_FREQ;
3437 		ns2->rumble.hd.hi_amp = effect->u.rumble.weak_magnitude * RUMBLE_MAX >> 16;
3438 		ns2->rumble.hd.lo_amp = effect->u.rumble.strong_magnitude * RUMBLE_MAX >> 16;
3439 	}
3440 	spin_unlock_irqrestore(&ns2->rumble_lock, flags);
3441 
3442 	schedule_delayed_work(&ns2->rumble_work, 0);
3443 
3444 	return 0;
3445 }
3446 
3447 static void switch2_rumble_work(struct work_struct *work)
3448 {
3449 	struct switch2_controller *ns2 = container_of(to_delayed_work(work),
3450 						      struct switch2_controller, rumble_work);
3451 	unsigned long flags;
3452 	bool active;
3453 	int ret = 0;
3454 
3455 	spin_lock_irqsave(&ns2->rumble_lock, flags);
3456 	ns2->rumble_buffer[0x1] = 0x50 | ns2->rumble_seq;
3457 	if (ns2->ctlr_type == NS2_CTLR_TYPE_GC) {
3458 		ns2->rumble_buffer[0] = 3;
3459 		if (ns2->rumble.sd.amplitude == 0) {
3460 			ns2->rumble_buffer[2] = GC_RUMBLE_STOP;
3461 			ns2->rumble.sd.error = 0;
3462 			active = false;
3463 		} else {
3464 			if (ns2->rumble.sd.error < ns2->rumble.sd.amplitude) {
3465 				ns2->rumble_buffer[2] = GC_RUMBLE_ON;
3466 				ns2->rumble.sd.error += U16_MAX - ns2->rumble.sd.amplitude;
3467 			} else {
3468 				ns2->rumble_buffer[2] = GC_RUMBLE_OFF;
3469 				ns2->rumble.sd.error -= ns2->rumble.sd.amplitude;
3470 			}
3471 			active = true;
3472 		}
3473 	} else {
3474 		ns2->rumble_buffer[0] = 1;
3475 		switch2_encode_rumble(&ns2->rumble.hd, &ns2->rumble_buffer[0x2]);
3476 		active = ns2->rumble.hd.hi_amp || ns2->rumble.hd.lo_amp;
3477 		if (ns2->ctlr_type == NS2_CTLR_TYPE_PRO) {
3478 			/*
3479 			 * The Pro Controller contains separate LRAs on each
3480 			 * side that can be controlled individually.
3481 			 */
3482 			ns2->rumble_buffer[0] = 2;
3483 			ns2->rumble_buffer[0x11] = 0x50 | ns2->rumble_seq;
3484 			switch2_encode_rumble(&ns2->rumble.hd, &ns2->rumble_buffer[0x12]);
3485 		}
3486 	}
3487 	ns2->rumble_seq = (ns2->rumble_seq + 1) & 0xF;
3488 	spin_unlock_irqrestore(&ns2->rumble_lock, flags);
3489 
3490 	if (active) {
3491 		unsigned long interval = msecs_to_jiffies(4);
3492 		uint64_t current_jiffies = get_jiffies_64();
3493 
3494 		if (!ns2->last_rumble_work)
3495 			ns2->last_rumble_work = current_jiffies;
3496 		else
3497 			ns2->last_rumble_work += interval;
3498 
3499 		/* Reschedule a little early to make sure the buffer never underruns */
3500 		interval -= msecs_to_jiffies(2);
3501 		if (ns2->last_rumble_work + interval >= current_jiffies)
3502 			schedule_delayed_work(&ns2->rumble_work,
3503 				ns2->last_rumble_work + interval - current_jiffies);
3504 		else
3505 			schedule_delayed_work(&ns2->rumble_work, 0);
3506 	} else {
3507 		ns2->last_rumble_work = 0;
3508 	}
3509 
3510 	mutex_lock(&ns2->lock);
3511 	if (!ns2->hdev) {
3512 		cancel_delayed_work(&ns2->rumble_work);
3513 	} else {
3514 		ret = hid_hw_output_report(ns2->hdev, ns2->rumble_buffer, 64);
3515 		/*
3516 		 * Don't log on ENODEV, ESHUTDOWN, or EPROTO, which can happen
3517 		 * mid-hotplug. Also cancel any further work on ENODEV or
3518 		 * ESHUTDOWN as they're clear indications that the endpoint
3519 		 * is dead.
3520 		 */
3521 		if (ret == -ENODEV || ret == -ESHUTDOWN)
3522 			cancel_delayed_work(&ns2->rumble_work);
3523 		else if (ret < 0 && ret != -EPROTO)
3524 			hid_warn_ratelimited(ns2->hdev,
3525 				"Failed to send output report ret=%d\n", ret);
3526 	}
3527 	mutex_unlock(&ns2->lock);
3528 }
3529 #endif
3530 
3531 static int switch2_set_leds(struct switch2_controller *ns2)
3532 {
3533 	int i;
3534 	uint8_t message[8] = { 0 };
3535 
3536 	for (i = 0; i < JC_NUM_LEDS; i++)
3537 		message[0] |= (!!ns2->leds[i].brightness) << i;
3538 
3539 	if (!ns2->cfg)
3540 		return -ENOTCONN;
3541 	return ns2->cfg->send_command(NS2_CMD_LED, NS2_SUBCMD_LED_PATTERN,
3542 		&message, sizeof(message),
3543 		ns2->cfg);
3544 }
3545 
3546 static int switch2_player_led_brightness_set(struct led_classdev *led,
3547 					    enum led_brightness brightness)
3548 {
3549 	struct device *dev = led->dev->parent;
3550 	struct input_dev *input = to_input_dev(dev);
3551 	struct switch2_controller *ns2 = input_get_drvdata(input);
3552 
3553 	if (!ns2)
3554 		return -ENODEV;
3555 
3556 	guard(mutex)(&ns2->lock);
3557 	return switch2_set_leds(ns2);
3558 }
3559 
3560 static void switch2_config_buttons(struct input_dev *idev,
3561 	const struct switch2_ctlr_button_mapping button_mappings[])
3562 {
3563 	const struct switch2_ctlr_button_mapping *button;
3564 
3565 	for (button = button_mappings; button->code; button++)
3566 		input_set_capability(idev, EV_KEY, button->code);
3567 }
3568 
3569 static int switch2_input_ref(struct input_dev *input)
3570 {
3571 	struct switch2_controller *ns2 = input_get_drvdata(input);
3572 
3573 	kref_get(&ns2->refcount);
3574 
3575 	return 0;
3576 }
3577 
3578 static void switch2_input_deref(struct input_dev *input)
3579 {
3580 	struct switch2_controller *ns2 = input_get_drvdata(input);
3581 
3582 	kref_put(&ns2->refcount, switch2_kref_put);
3583 }
3584 
3585 static int switch2_init_input(struct switch2_controller *ns2)
3586 {
3587 	struct input_dev *input;
3588 	struct hid_device *hdev = ns2->hdev;
3589 	int player_led_pattern;
3590 	int i;
3591 	int ret;
3592 
3593 	rcu_read_lock();
3594 	input = rcu_dereference(ns2->input);
3595 	rcu_read_unlock();
3596 
3597 	if (input) {
3598 		switch2_init_step_done(ns2, NS2_INIT_INPUT);
3599 		return 0;
3600 	}
3601 
3602 	input = input_allocate_device();
3603 	if (!input)
3604 		return -ENOMEM;
3605 
3606 	input_set_drvdata(input, ns2);
3607 	input->open = switch2_input_ref;
3608 	input->close = switch2_input_deref;
3609 	input->dev.parent = &hdev->dev;
3610 	input->id.bustype = hdev->bus;
3611 	input->id.vendor = hdev->vendor;
3612 	input->id.product = hdev->product;
3613 	input->id.version = hdev->version;
3614 	input->uniq = ns2->serial;
3615 	input->name = ns2->name;
3616 	input->phys = hdev->phys;
3617 
3618 	switch (ns2->ctlr_type) {
3619 	case NS2_CTLR_TYPE_JCL:
3620 		input_set_abs_params(input, ABS_X, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
3621 		input_set_abs_params(input, ABS_Y, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
3622 		switch2_config_buttons(input, ns2_left_joycon_button_mappings);
3623 		break;
3624 	case NS2_CTLR_TYPE_JCR:
3625 		input_set_abs_params(input, ABS_X, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
3626 		input_set_abs_params(input, ABS_Y, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
3627 		switch2_config_buttons(input, ns2_right_joycon_button_mappings);
3628 		break;
3629 	case NS2_CTLR_TYPE_GC:
3630 		input_set_abs_params(input, ABS_X, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
3631 		input_set_abs_params(input, ABS_Y, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
3632 		input_set_abs_params(input, ABS_RX, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
3633 		input_set_abs_params(input, ABS_RY, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
3634 		input_set_abs_params(input, ABS_Z, 0, NS2_TRIGGER_RANGE, 32, 128);
3635 		input_set_abs_params(input, ABS_RZ, 0, NS2_TRIGGER_RANGE, 32, 128);
3636 		input_set_abs_params(input, ABS_HAT0X, -1, 1, 0, 0);
3637 		input_set_abs_params(input, ABS_HAT0Y, -1, 1, 0, 0);
3638 		switch2_config_buttons(input, ns2_gccon_mappings);
3639 		break;
3640 	case NS2_CTLR_TYPE_PRO:
3641 		input_set_abs_params(input, ABS_X, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
3642 		input_set_abs_params(input, ABS_Y, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
3643 		input_set_abs_params(input, ABS_RX, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
3644 		input_set_abs_params(input, ABS_RY, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
3645 		input_set_abs_params(input, ABS_HAT0X, -1, 1, 0, 0);
3646 		input_set_abs_params(input, ABS_HAT0Y, -1, 1, 0, 0);
3647 		switch2_config_buttons(input, ns2_procon_mappings);
3648 		break;
3649 	default:
3650 		input_free_device(input);
3651 		return -EINVAL;
3652 	}
3653 
3654 #if IS_ENABLED(CONFIG_NINTENDO_FF)
3655 	ns2->rumble_buffer = devm_kzalloc(&input->dev, 64, GFP_KERNEL);
3656 	if (!ns2->rumble_buffer) {
3657 		input_free_device(input);
3658 		return -ENOMEM;
3659 	}
3660 	ret = devm_delayed_work_autocancel(&input->dev, &ns2->rumble_work, switch2_rumble_work);
3661 	if (ret < 0) {
3662 		input_free_device(input);
3663 		return ret;
3664 	}
3665 
3666 	input_set_capability(input, EV_FF, FF_RUMBLE);
3667 	ret = input_ff_create_memless(input, NULL, switch2_play_effect);
3668 	if (ret) {
3669 		input_free_device(input);
3670 		return ret;
3671 	}
3672 #endif
3673 
3674 	hid_info(ns2->hdev, "Firmware version %u.%u.%u (type %i)\n", ns2->version.major,
3675 		ns2->version.minor, ns2->version.patch, ns2->version.ctlr_type);
3676 	if (ns2->version.dsp_type >= 0)
3677 		hid_info(ns2->hdev, "DSP version %u.%u.%u\n", ns2->version.dsp_major,
3678 			ns2->version.dsp_minor, ns2->version.dsp_patch);
3679 
3680 	ret = input_register_device(input);
3681 	if (ret < 0) {
3682 		hid_err(ns2->hdev, "Failed to register input; ret=%d\n", ret);
3683 		input_free_device(input);
3684 		return ret;
3685 	}
3686 
3687 	player_led_pattern = ns2->player_id % JC_NUM_LED_PATTERNS;
3688 	hid_dbg(hdev, "assigned player %d led pattern", player_led_pattern + 1);
3689 
3690 	ns2->leds = devm_kcalloc(&input->dev, JC_NUM_LEDS, sizeof(*ns2->leds), GFP_KERNEL);
3691 	if (!ns2->leds) {
3692 		input_unregister_device(input);
3693 		return -ENOMEM;
3694 	}
3695 
3696 	for (i = 0; i < JC_NUM_LEDS; i++) {
3697 		struct led_classdev *led = &ns2->leds[i];
3698 
3699 		led->brightness = joycon_player_led_patterns[player_led_pattern][i];
3700 		led->max_brightness = 1;
3701 		led->brightness_set_blocking = switch2_player_led_brightness_set;
3702 		led->flags = LED_CORE_SUSPENDRESUME | LED_HW_PLUGGABLE | LED_RETAIN_AT_SHUTDOWN;
3703 		char *name = devm_kasprintf(&input->dev, GFP_KERNEL, "%s:%s:%s",
3704 				      dev_name(&input->dev),
3705 				      "green",
3706 				      joycon_player_led_names[i]);
3707 
3708 		if (!name) {
3709 			dev_err(&input->dev, "Failed to allocate name for player %d LED; ret=%d\n",
3710 				i + 1, ret);
3711 			break;
3712 		}
3713 
3714 		led->name = name;
3715 		ret = devm_led_classdev_register(&input->dev, led);
3716 		if (ret < 0) {
3717 			dev_err(&input->dev, "Failed to register player %d LED; ret=%d\n",
3718 				i + 1, ret);
3719 			break;
3720 		}
3721 	}
3722 
3723 	rcu_assign_pointer(ns2->input, input);
3724 	synchronize_rcu();
3725 
3726 	switch2_init_step_done(ns2, NS2_INIT_INPUT);
3727 	return switch2_init_controller(ns2);
3728 }
3729 
3730 static bool switch2_parse_stick_calibration(struct switch2_stick_calibration *calib,
3731 	const uint8_t *data)
3732 {
3733 	static const uint8_t UNCALIBRATED[9] = {
3734 		0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
3735 	};
3736 	if (memcmp(UNCALIBRATED, data, sizeof(UNCALIBRATED)) == 0)
3737 		return false;
3738 
3739 	calib->x.neutral = data[0];
3740 	calib->x.neutral |= (data[1] & 0x0F) << 8;
3741 
3742 	calib->y.neutral = data[1] >> 4;
3743 	calib->y.neutral |= data[2] << 4;
3744 
3745 	calib->x.positive = data[3];
3746 	calib->x.positive |= (data[4] & 0x0F) << 8;
3747 
3748 	calib->y.positive = data[4] >> 4;
3749 	calib->y.positive |= data[5] << 4;
3750 
3751 	calib->x.negative = data[6];
3752 	calib->x.negative |= (data[7] & 0x0F) << 8;
3753 
3754 	calib->y.negative = data[7] >> 4;
3755 	calib->y.negative |= data[8] << 4;
3756 
3757 	return true;
3758 }
3759 
3760 static void switch2_handle_flash_read(struct switch2_controller *ns2, uint8_t size,
3761 	uint32_t address, const uint8_t *data)
3762 {
3763 	bool ok;
3764 
3765 	switch (address) {
3766 	case NS2_FLASH_ADDR_SERIAL:
3767 		if (size != NS2_FLASH_SIZE_SERIAL)
3768 			return;
3769 		memcpy(ns2->serial, data, size);
3770 		switch2_init_step_done(ns2, NS2_INIT_READ_SERIAL);
3771 		break;
3772 	case NS2_FLASH_ADDR_FACTORY_PRIMARY_CALIB:
3773 		if (size != NS2_FLASH_SIZE_FACTORY_AXIS_CALIB)
3774 			return;
3775 		switch2_init_step_done(ns2, NS2_INIT_READ_FACTORY_PRIMARY_CALIB);
3776 		ok = switch2_parse_stick_calibration(&ns2->stick_calib[0], data);
3777 		if (ns2->hdev) {
3778 			if (ok) {
3779 				hid_dbg(ns2->hdev, "Got factory primary stick calibration:\n");
3780 				hid_dbg(ns2->hdev, "Left max: %i, neutral: %i, right max: %i\n",
3781 					ns2->stick_calib[0].x.negative,
3782 					ns2->stick_calib[0].x.neutral,
3783 					ns2->stick_calib[0].x.positive);
3784 				hid_dbg(ns2->hdev, "Down max: %i, neutral: %i, up max: %i\n",
3785 					ns2->stick_calib[0].y.negative,
3786 					ns2->stick_calib[0].y.neutral,
3787 					ns2->stick_calib[0].y.positive);
3788 			} else {
3789 				hid_dbg(ns2->hdev, "Factory primary stick calibration not present\n");
3790 			}
3791 		}
3792 		break;
3793 	case NS2_FLASH_ADDR_FACTORY_SECONDARY_CALIB:
3794 		if (size != NS2_FLASH_SIZE_FACTORY_AXIS_CALIB)
3795 			return;
3796 		switch2_init_step_done(ns2, NS2_INIT_READ_FACTORY_SECONDARY_CALIB);
3797 		ok = switch2_parse_stick_calibration(&ns2->stick_calib[1], data);
3798 		if (ns2->hdev) {
3799 			if (ok) {
3800 				hid_dbg(ns2->hdev, "Got factory secondary stick calibration:\n");
3801 				hid_dbg(ns2->hdev, "Left max: %i, neutral: %i, right max: %i\n",
3802 					ns2->stick_calib[1].x.negative,
3803 					ns2->stick_calib[1].x.neutral,
3804 					ns2->stick_calib[1].x.positive);
3805 				hid_dbg(ns2->hdev, "Down max: %i, neutral: %i, up max: %i\n",
3806 					ns2->stick_calib[1].y.negative,
3807 					ns2->stick_calib[1].y.neutral,
3808 					ns2->stick_calib[1].y.positive);
3809 			} else {
3810 				hid_dbg(ns2->hdev, "Factory secondary stick calibration not present\n");
3811 			}
3812 		}
3813 		break;
3814 	case NS2_FLASH_ADDR_FACTORY_TRIGGER_CALIB:
3815 		if (size != NS2_FLASH_SIZE_FACTORY_TRIGGER_CALIB)
3816 			return;
3817 		switch2_init_step_done(ns2, NS2_INIT_READ_FACTORY_TRIGGER_CALIB);
3818 		if (data[0] != 0xFF && data[1] != 0xFF) {
3819 			ns2->lt_zero = data[0];
3820 			ns2->rt_zero = data[1];
3821 
3822 			if (ns2->hdev) {
3823 				hid_dbg(ns2->hdev, "Got factory trigger calibration:\n");
3824 				hid_dbg(ns2->hdev, "Left zero point: %i\n", ns2->lt_zero);
3825 				hid_dbg(ns2->hdev, "Right zero point: %i\n", ns2->rt_zero);
3826 			}
3827 		} else if (ns2->hdev) {
3828 			hid_dbg(ns2->hdev, "Factory trigger calibration not present\n");
3829 		}
3830 		break;
3831 	case NS2_FLASH_ADDR_USER_PRIMARY_CALIB:
3832 		if (size != NS2_FLASH_SIZE_USER_AXIS_CALIB)
3833 			return;
3834 		switch2_init_step_done(ns2, NS2_INIT_READ_USER_PRIMARY_CALIB);
3835 		if (get_unaligned_le16((__le16 *)data) != NS2_USER_CALIB_MAGIC) {
3836 			if (ns2->hdev)
3837 				hid_dbg(ns2->hdev, "No user primary stick calibration present\n");
3838 			break;
3839 		}
3840 
3841 		ok = switch2_parse_stick_calibration(&ns2->stick_calib[0], &data[2]);
3842 		if (ns2->hdev) {
3843 			if (ok) {
3844 				hid_dbg(ns2->hdev, "Got user primary stick calibration:\n");
3845 				hid_dbg(ns2->hdev, "Left max: %i, neutral: %i, right max: %i\n",
3846 					ns2->stick_calib[0].x.negative,
3847 					ns2->stick_calib[0].x.neutral,
3848 					ns2->stick_calib[0].x.positive);
3849 				hid_dbg(ns2->hdev, "Down max: %i, neutral: %i, up max: %i\n",
3850 					ns2->stick_calib[0].y.negative,
3851 					ns2->stick_calib[0].y.neutral,
3852 					ns2->stick_calib[0].y.positive);
3853 			} else {
3854 				hid_dbg(ns2->hdev, "No user primary stick calibration present\n");
3855 			}
3856 		}
3857 		break;
3858 	case NS2_FLASH_ADDR_USER_SECONDARY_CALIB:
3859 		if (size != NS2_FLASH_SIZE_USER_AXIS_CALIB)
3860 			return;
3861 		switch2_init_step_done(ns2, NS2_INIT_READ_USER_SECONDARY_CALIB);
3862 		if (get_unaligned_le16((__le16 *)data) != NS2_USER_CALIB_MAGIC) {
3863 			if (ns2->hdev)
3864 				hid_dbg(ns2->hdev, "No user secondary stick calibration present\n");
3865 			break;
3866 		}
3867 
3868 		ok = switch2_parse_stick_calibration(&ns2->stick_calib[1], &data[2]);
3869 		if (ns2->hdev) {
3870 			if (ok) {
3871 				hid_dbg(ns2->hdev, "Got user secondary stick calibration:\n");
3872 				hid_dbg(ns2->hdev, "Left max: %i, neutral: %i, right max: %i\n",
3873 					ns2->stick_calib[1].x.negative,
3874 					ns2->stick_calib[1].x.neutral,
3875 					ns2->stick_calib[1].x.positive);
3876 				hid_dbg(ns2->hdev, "Down max: %i, neutral: %i, up max: %i\n",
3877 					ns2->stick_calib[1].y.negative,
3878 					ns2->stick_calib[1].y.neutral,
3879 					ns2->stick_calib[1].y.positive);
3880 			} else {
3881 				hid_dbg(ns2->hdev, "No user secondary stick calibration present\n");
3882 			}
3883 		}
3884 		break;
3885 	}
3886 }
3887 
3888 static void switch2_report_buttons(struct input_dev *input, const uint8_t *bytes,
3889 	const struct switch2_ctlr_button_mapping button_mappings[])
3890 {
3891 	const struct switch2_ctlr_button_mapping *button;
3892 
3893 	for (button = button_mappings; button->code; button++)
3894 		input_report_key(input, button->code, bytes[button->byte] & button->bit);
3895 }
3896 
3897 static void switch2_report_axis(struct input_dev *input, struct switch2_axis_calibration *calib,
3898 	int axis, bool invert, int value)
3899 {
3900 	if (calib && calib->neutral && calib->negative && calib->positive) {
3901 		value -= calib->neutral;
3902 		value *= NS2_AXIS_MAX + 1;
3903 		if (value < 0)
3904 			value /= calib->negative;
3905 		else
3906 			value /= calib->positive;
3907 	} else {
3908 		value = (value - 2048) * 16;
3909 	}
3910 
3911 	if (invert)
3912 		value = -value;
3913 	input_report_abs(input, axis,
3914 		clamp(value, NS2_AXIS_MIN, NS2_AXIS_MAX));
3915 }
3916 
3917 static void switch2_report_stick(struct input_dev *input, struct switch2_stick_calibration *calib,
3918 	int x, bool invert_x, int y, bool invert_y, const uint8_t *data)
3919 {
3920 	switch2_report_axis(input, &calib->x, x, invert_x, data[0] | ((data[1] & 0x0F) << 8));
3921 	switch2_report_axis(input, &calib->y, y, invert_y, (data[1] >> 4) | (data[2] << 4));
3922 }
3923 
3924 static void switch2_report_trigger(struct input_dev *input, uint8_t zero, int abs, uint8_t data)
3925 {
3926 	int value = (NS2_TRIGGER_RANGE + 1) * (data - zero);
3927 
3928 	if (zero != 232)
3929 		value /= (232 - zero);
3930 	input_report_abs(input, abs, clamp(value, 0, NS2_TRIGGER_RANGE));
3931 }
3932 
3933 static int switch2_event(struct hid_device *hdev, struct hid_report *report, uint8_t *raw_data,
3934 	int size)
3935 {
3936 	struct switch2_controller *ns2 = hid_get_drvdata(hdev);
3937 	struct input_dev *input;
3938 
3939 	if (report->type != HID_INPUT_REPORT)
3940 		return 0;
3941 
3942 	if (size < 15)
3943 		return -EINVAL;
3944 
3945 	guard(rcu)();
3946 	input = rcu_dereference(ns2->input);
3947 
3948 	if (!input)
3949 		return 0;
3950 
3951 	switch (report->id) {
3952 	case NS2_REPORT_UNIFIED:
3953 		if (size < 0x3f)
3954 			return -EINVAL;
3955 
3956 		switch (ns2->ctlr_type) {
3957 		case NS2_CTLR_TYPE_JCL:
3958 			switch2_report_stick(input, &ns2->stick_calib[0],
3959 				ABS_X, false, ABS_Y, true, &raw_data[11]);
3960 			switch2_report_buttons(input, &raw_data[5],
3961 				ns2_left_joycon_button_unified_mappings);
3962 			break;
3963 		case NS2_CTLR_TYPE_JCR:
3964 			switch2_report_stick(input, &ns2->stick_calib[0],
3965 				ABS_X, false, ABS_Y, true, &raw_data[14]);
3966 			switch2_report_buttons(input, &raw_data[5],
3967 				ns2_right_joycon_button_unified_mappings);
3968 			break;
3969 		case NS2_CTLR_TYPE_GC:
3970 			input_report_abs(input, ABS_HAT0X,
3971 				!!(raw_data[7] & NS2_BTN_U3_RIGHT) -
3972 				!!(raw_data[7] & NS2_BTN_U3_LEFT));
3973 			input_report_abs(input, ABS_HAT0Y,
3974 				!!(raw_data[7] & NS2_BTN_U3_DOWN) -
3975 				!!(raw_data[7] & NS2_BTN_U3_UP));
3976 			switch2_report_buttons(input, &raw_data[5], ns2_gccon_unified_mappings);
3977 			switch2_report_stick(input, &ns2->stick_calib[0],
3978 				ABS_X, false, ABS_Y, true, &raw_data[11]);
3979 			switch2_report_stick(input, &ns2->stick_calib[1],
3980 				ABS_RX, false, ABS_RY, true, &raw_data[14]);
3981 			switch2_report_trigger(input, ns2->lt_zero, ABS_Z, raw_data[0x3d]);
3982 			switch2_report_trigger(input, ns2->rt_zero, ABS_RZ, raw_data[0x3e]);
3983 			break;
3984 		case NS2_CTLR_TYPE_PRO:
3985 			input_report_abs(input, ABS_HAT0X,
3986 				!!(raw_data[7] & NS2_BTN_U3_RIGHT) -
3987 				!!(raw_data[7] & NS2_BTN_U3_LEFT));
3988 			input_report_abs(input, ABS_HAT0Y,
3989 				!!(raw_data[7] & NS2_BTN_U3_DOWN) -
3990 				!!(raw_data[7] & NS2_BTN_U3_UP));
3991 			switch2_report_buttons(input, &raw_data[5], ns2_procon_unified_mappings);
3992 			switch2_report_stick(input, &ns2->stick_calib[0],
3993 				ABS_X, false, ABS_Y, true, &raw_data[11]);
3994 			switch2_report_stick(input, &ns2->stick_calib[1],
3995 				ABS_RX, false, ABS_RY, true, &raw_data[14]);
3996 			break;
3997 		}
3998 		break;
3999 	case NS2_REPORT_JCL:
4000 		switch2_report_stick(input, &ns2->stick_calib[0], ABS_X, false,
4001 			ABS_Y, true, &raw_data[6]);
4002 		switch2_report_buttons(input, &raw_data[3], ns2_left_joycon_button_mappings);
4003 		break;
4004 	case NS2_REPORT_JCR:
4005 		switch2_report_stick(input, &ns2->stick_calib[0], ABS_X, false,
4006 			ABS_Y, true, &raw_data[6]);
4007 		switch2_report_buttons(input, &raw_data[3], ns2_right_joycon_button_mappings);
4008 		break;
4009 	case NS2_REPORT_GC:
4010 		input_report_abs(input, ABS_HAT0X,
4011 			!!(raw_data[4] & NS2_BTNL_RIGHT) -
4012 			!!(raw_data[4] & NS2_BTNL_LEFT));
4013 		input_report_abs(input, ABS_HAT0Y,
4014 			!!(raw_data[4] & NS2_BTNL_DOWN) -
4015 			!!(raw_data[4] & NS2_BTNL_UP));
4016 		switch2_report_buttons(input, &raw_data[3], ns2_gccon_mappings);
4017 		switch2_report_stick(input, &ns2->stick_calib[0], ABS_X, false,
4018 			ABS_Y, true, &raw_data[6]);
4019 		switch2_report_stick(input, &ns2->stick_calib[1], ABS_RX, false,
4020 			ABS_RY, true, &raw_data[9]);
4021 		switch2_report_trigger(input, ns2->lt_zero, ABS_Z, raw_data[13]);
4022 		switch2_report_trigger(input, ns2->rt_zero, ABS_RZ, raw_data[14]);
4023 		break;
4024 	case NS2_REPORT_PRO:
4025 		input_report_abs(input, ABS_HAT0X,
4026 			!!(raw_data[4] & NS2_BTNL_RIGHT) -
4027 			!!(raw_data[4] & NS2_BTNL_LEFT));
4028 		input_report_abs(input, ABS_HAT0Y,
4029 			!!(raw_data[4] & NS2_BTNL_DOWN) -
4030 			!!(raw_data[4] & NS2_BTNL_UP));
4031 		switch2_report_buttons(input, &raw_data[3], ns2_procon_mappings);
4032 		switch2_report_stick(input, &ns2->stick_calib[0], ABS_X, false,
4033 			ABS_Y, true, &raw_data[6]);
4034 		switch2_report_stick(input, &ns2->stick_calib[1], ABS_RX, false,
4035 			ABS_RY, true, &raw_data[9]);
4036 		break;
4037 	default:
4038 		return -EINVAL;
4039 	}
4040 
4041 	input_sync(input);
4042 	return 0;
4043 }
4044 
4045 static int switch2_features_enable(struct switch2_controller *ns2, int features)
4046 {
4047 	__le32 feature_bits = __cpu_to_le32(features);
4048 
4049 	if (!ns2->cfg)
4050 		return -ENOTCONN;
4051 	return ns2->cfg->send_command(NS2_CMD_FEATSEL, NS2_SUBCMD_FEATSEL_ENABLE,
4052 		&feature_bits, sizeof(feature_bits),
4053 		ns2->cfg);
4054 }
4055 
4056 static int switch2_read_flash(struct switch2_controller *ns2, uint32_t address,
4057 	uint8_t size)
4058 {
4059 	uint8_t message[8] = { size, 0x7e };
4060 
4061 	if (!ns2->cfg)
4062 		return -ENOTCONN;
4063 	put_unaligned_le32(address, &message[4]);
4064 	return ns2->cfg->send_command(NS2_CMD_FLASH, NS2_SUBCMD_FLASH_READ, message,
4065 		sizeof(message), ns2->cfg);
4066 }
4067 
4068 static int switch2_set_player_id(struct switch2_controller *ns2, uint32_t player_id)
4069 {
4070 	int i;
4071 	int player_led_pattern = player_id % JC_NUM_LED_PATTERNS;
4072 
4073 	for (i = 0; i < JC_NUM_LEDS; i++)
4074 		ns2->leds[i].brightness = joycon_player_led_patterns[player_led_pattern][i];
4075 
4076 	return switch2_set_leds(ns2);
4077 }
4078 
4079 static int switch2_set_report_format(struct switch2_controller *ns2, enum switch2_report_id fmt)
4080 {
4081 	__le32 format_id = __cpu_to_le32(fmt);
4082 
4083 	if (!ns2->cfg)
4084 		return -ENOTCONN;
4085 	return ns2->cfg->send_command(NS2_CMD_INIT, NS2_SUBCMD_INIT_SELECT_REPORT,
4086 		&format_id, sizeof(format_id),
4087 		ns2->cfg);
4088 }
4089 
4090 int switch2_init_controller(struct switch2_controller *ns2)
4091 {
4092 	if (ns2->init_step == NS2_INIT_DONE)
4093 		return 0;
4094 
4095 	if (!ns2->cfg)
4096 		return -ENOTCONN;
4097 
4098 	if (ns2->init_retries > NS2_MAX_INIT_RETRIES) {
4099 		if (ns2->init_retries == NS2_MAX_INIT_RETRIES + 1) {
4100 			dev_err(ns2->cfg->dev, "Failed to configure controller\n");
4101 			ns2->init_retries++;
4102 		}
4103 		return -EIO;
4104 	}
4105 
4106 	ns2->init_retries++;
4107 	switch (ns2->init_step) {
4108 	case NS2_INIT_READ_SERIAL:
4109 		return switch2_read_flash(ns2, NS2_FLASH_ADDR_SERIAL,
4110 			NS2_FLASH_SIZE_SERIAL);
4111 	case NS2_INIT_GET_FIRMWARE_INFO:
4112 		return ns2->cfg->send_command(NS2_CMD_FW_INFO, NS2_SUBCMD_FW_INFO_GET,
4113 			NULL, 0, ns2->cfg);
4114 	case NS2_INIT_READ_FACTORY_PRIMARY_CALIB:
4115 		return switch2_read_flash(ns2, NS2_FLASH_ADDR_FACTORY_PRIMARY_CALIB,
4116 			NS2_FLASH_SIZE_FACTORY_AXIS_CALIB);
4117 	case NS2_INIT_READ_FACTORY_SECONDARY_CALIB:
4118 		if (switch2_ctlr_is_joycon(ns2->ctlr_type)) {
4119 			switch2_init_step_done(ns2, ns2->init_step);
4120 			return switch2_init_controller(ns2);
4121 		}
4122 		return switch2_read_flash(ns2, NS2_FLASH_ADDR_FACTORY_SECONDARY_CALIB,
4123 			NS2_FLASH_SIZE_FACTORY_AXIS_CALIB);
4124 	case NS2_INIT_READ_FACTORY_TRIGGER_CALIB:
4125 		if (ns2->ctlr_type != NS2_CTLR_TYPE_GC) {
4126 			switch2_init_step_done(ns2, ns2->init_step);
4127 			return switch2_init_controller(ns2);
4128 		}
4129 		return switch2_read_flash(ns2, NS2_FLASH_ADDR_FACTORY_TRIGGER_CALIB,
4130 			NS2_FLASH_SIZE_FACTORY_TRIGGER_CALIB);
4131 	case NS2_INIT_READ_USER_PRIMARY_CALIB:
4132 		return switch2_read_flash(ns2, NS2_FLASH_ADDR_USER_PRIMARY_CALIB,
4133 			NS2_FLASH_SIZE_USER_AXIS_CALIB);
4134 	case NS2_INIT_READ_USER_SECONDARY_CALIB:
4135 		if (switch2_ctlr_is_joycon(ns2->ctlr_type)) {
4136 			switch2_init_step_done(ns2, ns2->init_step);
4137 			return switch2_init_controller(ns2);
4138 		}
4139 		return switch2_read_flash(ns2, NS2_FLASH_ADDR_USER_SECONDARY_CALIB,
4140 			NS2_FLASH_SIZE_USER_AXIS_CALIB);
4141 	case NS2_INIT_SET_FEATURE_MASK:
4142 		return ns2->cfg->send_command(NS2_CMD_FEATSEL, NS2_SUBCMD_FEATSEL_SET_MASK,
4143 			switch2_feature_mask, sizeof(switch2_feature_mask), ns2->cfg);
4144 	case NS2_INIT_ENABLE_FEATURES:
4145 		return switch2_features_enable(ns2, NS2_FEATURE_BUTTONS |
4146 			NS2_FEATURE_ANALOG | NS2_FEATURE_RUMBLE);
4147 	case NS2_INIT_ENABLE_RUMBLE:
4148 		/*
4149 		 * It is unclear what this packet is supposed to be for, but it
4150 		 * appears to be needed for rumble to work reliably. The reply
4151 		 * data indicates it might be a query of some sort, but we
4152 		 * ignore the reply so long as it doesn't return an error.
4153 		 */
4154 		return ns2->cfg->send_command(0x11, 1, NULL, 0, ns2->cfg);
4155 	case NS2_INIT_GRIP_BUTTONS:
4156 		if (!switch2_ctlr_is_joycon(ns2->ctlr_type)) {
4157 			switch2_init_step_done(ns2, ns2->init_step);
4158 			return switch2_init_controller(ns2);
4159 		}
4160 		return ns2->cfg->send_command(NS2_CMD_GRIP, NS2_SUBCMD_GRIP_ENABLE_BUTTONS,
4161 			switch2_one_data, sizeof(switch2_one_data),
4162 			ns2->cfg);
4163 	case NS2_INIT_REPORT_FORMAT:
4164 		switch (ns2->ctlr_type) {
4165 		case NS2_CTLR_TYPE_JCL:
4166 			return switch2_set_report_format(ns2, NS2_REPORT_JCL);
4167 		case NS2_CTLR_TYPE_JCR:
4168 			return switch2_set_report_format(ns2, NS2_REPORT_JCR);
4169 		case NS2_CTLR_TYPE_PRO:
4170 			return switch2_set_report_format(ns2, NS2_REPORT_PRO);
4171 		case NS2_CTLR_TYPE_GC:
4172 			return switch2_set_report_format(ns2, NS2_REPORT_GC);
4173 		default:
4174 			switch2_init_step_done(ns2, ns2->init_step);
4175 			return switch2_init_controller(ns2);
4176 		}
4177 	case NS2_INIT_INPUT:
4178 		if (ns2->hdev)
4179 			return switch2_init_input(ns2);
4180 		break;
4181 	case NS2_INIT_SET_PLAYER_LEDS:
4182 		return switch2_set_player_id(ns2, ns2->player_id);
4183 	case NS2_INIT_FINISH:
4184 		return ns2->cfg->send_command(NS2_CMD_INIT, NS2_SUBCMD_INIT_USB,
4185 			switch2_init_cmd_data, sizeof(switch2_init_cmd_data), ns2->cfg);
4186 	default:
4187 		WARN_ON_ONCE(1);
4188 		break;
4189 	}
4190 	return 0;
4191 }
4192 
4193 int switch2_receive_command(struct switch2_controller *ns2,
4194 	const uint8_t *message, size_t length)
4195 {
4196 	const struct switch2_cmd_header *header;
4197 	int ret = 0;
4198 
4199 	if (length < 8)
4200 		return -EINVAL;
4201 
4202 	print_hex_dump_debug("got cmd: ", DUMP_PREFIX_OFFSET, 16, 1, message, length, false);
4203 
4204 	mutex_lock(&ns2->lock);
4205 
4206 	header = (const struct switch2_cmd_header *)message;
4207 	if (!(header->flags & NS2_FLAG_OK)) {
4208 		if (ns2->cfg)
4209 			dev_warn(ns2->cfg->dev, "Packet error %02x replying to command %x:%x",
4210 				header->flags, header->command, header->subcommand);
4211 		ret = -EIO;
4212 		goto exit;
4213 	}
4214 	message = &message[8];
4215 	length -= 8;
4216 
4217 	switch (header->command) {
4218 	case NS2_CMD_FLASH:
4219 		if (header->subcommand == NS2_SUBCMD_FLASH_READ) {
4220 			uint8_t read_size;
4221 			uint32_t read_address;
4222 
4223 			if (length < 8) {
4224 				ret = -EINVAL;
4225 				goto exit;
4226 			}
4227 			read_size = message[0];
4228 			read_address = get_unaligned_le32(&message[4]);
4229 			if (length < read_size + 8) {
4230 				ret = -EINVAL;
4231 				goto exit;
4232 			}
4233 			switch2_handle_flash_read(ns2, read_size, read_address, &message[8]);
4234 		}
4235 		break;
4236 	case NS2_CMD_INIT:
4237 		if (header->subcommand == NS2_SUBCMD_INIT_USB)
4238 			switch2_init_step_done(ns2, NS2_INIT_FINISH);
4239 		else if (header->subcommand == NS2_SUBCMD_INIT_SELECT_REPORT)
4240 			switch2_init_step_done(ns2, NS2_INIT_REPORT_FORMAT);
4241 		break;
4242 	case NS2_CMD_GRIP:
4243 		if (header->subcommand == NS2_SUBCMD_GRIP_ENABLE_BUTTONS)
4244 			switch2_init_step_done(ns2, NS2_INIT_GRIP_BUTTONS);
4245 		break;
4246 	case NS2_CMD_LED:
4247 		if (header->subcommand == NS2_SUBCMD_LED_PATTERN)
4248 			switch2_init_step_done(ns2, NS2_INIT_SET_PLAYER_LEDS);
4249 		break;
4250 	case NS2_CMD_FEATSEL:
4251 		if (header->subcommand == NS2_SUBCMD_FEATSEL_SET_MASK)
4252 			switch2_init_step_done(ns2, NS2_INIT_SET_FEATURE_MASK);
4253 		else if (header->subcommand == NS2_SUBCMD_FEATSEL_ENABLE)
4254 			switch2_init_step_done(ns2, NS2_INIT_ENABLE_FEATURES);
4255 		break;
4256 	case NS2_CMD_FW_INFO:
4257 		if (header->subcommand == NS2_SUBCMD_FW_INFO_GET) {
4258 			if (length < sizeof(ns2->version)) {
4259 				ret = -EINVAL;
4260 				goto exit;
4261 			}
4262 			memcpy(&ns2->version, message, sizeof(ns2->version));
4263 			ns2->ctlr_type = ns2->version.ctlr_type;
4264 			switch2_init_step_done(ns2, NS2_INIT_GET_FIRMWARE_INFO);
4265 		}
4266 		break;
4267 	case 0x11:
4268 		if (header->subcommand == 1)
4269 			switch2_init_step_done(ns2, NS2_INIT_ENABLE_RUMBLE);
4270 		break;
4271 	default:
4272 		break;
4273 	}
4274 
4275 exit:
4276 	if (ns2->init_step < NS2_INIT_DONE)
4277 		switch2_init_controller(ns2);
4278 
4279 	mutex_unlock(&ns2->lock);
4280 	return ret;
4281 }
4282 EXPORT_SYMBOL_GPL(switch2_receive_command);
4283 
4284 int switch2_controller_attach_cfg(const char *phys, struct switch2_cfg_intf *cfg)
4285 {
4286 	struct switch2_controller *ns2 = switch2_get_controller(phys);
4287 	int ret = 0;
4288 
4289 	if (IS_ERR(ns2))
4290 		return PTR_ERR(ns2);
4291 
4292 	mutex_lock(&ns2->lock);
4293 	if (ns2->cfg) {
4294 		ret = -EBUSY;
4295 		goto out;
4296 	}
4297 	cfg->parent = ns2;
4298 	ns2->cfg = cfg;
4299 
4300 	if (ns2->hdev)
4301 		ret = switch2_init_controller(ns2);
4302 
4303 	if (ret < 0) {
4304 		if (cfg->shutdown)
4305 			cfg->shutdown(cfg);
4306 		cfg->parent = NULL;
4307 		ns2->cfg = NULL;
4308 	}
4309 
4310 out:
4311 	mutex_unlock(&ns2->lock);
4312 
4313 	if (ret < 0)
4314 		kref_put(&ns2->refcount, switch2_kref_put);
4315 	return ret;
4316 }
4317 EXPORT_SYMBOL_GPL(switch2_controller_attach_cfg);
4318 
4319 void switch2_controller_detach_cfg(struct switch2_controller *ns2)
4320 {
4321 	mutex_lock(&ns2->lock);
4322 	if (!ns2->cfg || WARN_ON(ns2 != ns2->cfg->parent)) {
4323 		mutex_unlock(&ns2->lock);
4324 		return;
4325 	}
4326 	if (ns2->cfg->shutdown)
4327 		ns2->cfg->shutdown(ns2->cfg);
4328 	ns2->cfg->parent = NULL;
4329 	ns2->cfg = NULL;
4330 	mutex_unlock(&ns2->lock);
4331 	switch2_controller_put(ns2);
4332 	kref_put(&ns2->refcount, switch2_kref_put);
4333 }
4334 EXPORT_SYMBOL_GPL(switch2_controller_detach_cfg);
4335 
4336 static int switch2_probe(struct hid_device *hdev, const struct hid_device_id *id)
4337 {
4338 	struct switch2_controller *ns2;
4339 	struct usb_device *udev;
4340 	char phys[64];
4341 	int ret;
4342 
4343 	if (!hid_is_usb(hdev))
4344 		return -ENODEV;
4345 
4346 	udev = hid_to_usb_dev(hdev);
4347 	if (usb_make_path(udev, phys, sizeof(phys)) < 0)
4348 		return -EINVAL;
4349 
4350 	ret = hid_parse(hdev);
4351 	if (ret) {
4352 		hid_err(hdev, "parse failed %d\n", ret);
4353 		return ret;
4354 	}
4355 
4356 	ns2 = switch2_get_controller(phys);
4357 	if (IS_ERR(ns2))
4358 		return PTR_ERR(ns2);
4359 
4360 	mutex_lock(&ns2->lock);
4361 	if (ns2->hdev) {
4362 		mutex_unlock(&ns2->lock);
4363 		hid_err(hdev,
4364 			"Second hdev tried to claim same controller, first=%p vs second=%p\n",
4365 			ns2->hdev, hdev);
4366 		kref_put(&ns2->refcount, switch2_kref_put);
4367 		return -EBUSY;
4368 	}
4369 	ns2->hdev = hdev;
4370 	hid_set_drvdata(hdev, ns2);
4371 
4372 	switch (hdev->product | (hdev->vendor << 16)) {
4373 	default:
4374 		strscpy(ns2->name, hdev->name, sizeof(ns2->name));
4375 		break;
4376 	/* Some controllers have slightly wrong names so we override them */
4377 	case USB_DEVICE_ID_NINTENDO_NS2_JOYCONR | (USB_VENDOR_ID_NINTENDO << 16):
4378 		/* Missing the "2" in the name */
4379 		strscpy(ns2->name, "Nintendo Joy-Con 2 (R)", sizeof(ns2->name));
4380 		break;
4381 	case USB_DEVICE_ID_NINTENDO_NS2_GCCON | (USB_VENDOR_ID_NINTENDO << 16):
4382 		/* Has "Nintendo" in the name twice */
4383 		strscpy(ns2->name, "Nintendo GameCube Controller", sizeof(ns2->name));
4384 		break;
4385 	}
4386 
4387 	ns2->player_id = U32_MAX;
4388 	ret = ida_alloc(&nintendo_player_id_allocator, GFP_KERNEL);
4389 	if (ret < 0)
4390 		hid_warn(hdev, "Failed to allocate player ID, skipping; ret=%d\n", ret);
4391 	else
4392 		ns2->player_id = ret;
4393 
4394 	ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
4395 	if (ret) {
4396 		hid_err(hdev, "hw_start failed %d\n", ret);
4397 		goto err_cleanup;
4398 	}
4399 
4400 	ret = hid_hw_open(hdev);
4401 	if (ret) {
4402 		hid_err(hdev, "hw_open failed %d\n", ret);
4403 		goto err_stop;
4404 	}
4405 
4406 	ret = 0;
4407 	if (ns2->cfg)
4408 		ret = switch2_init_controller(ns2);
4409 
4410 	if (!ret) {
4411 		mutex_unlock(&ns2->lock);
4412 		return 0;
4413 	}
4414 
4415 	hid_hw_close(hdev);
4416 err_stop:
4417 	hid_hw_stop(hdev);
4418 err_cleanup:
4419 	ida_free(&nintendo_player_id_allocator, ns2->player_id);
4420 	ns2->hdev = NULL;
4421 	mutex_unlock(&ns2->lock);
4422 	switch2_controller_put(ns2);
4423 	kref_put(&ns2->refcount, switch2_kref_put);
4424 
4425 	return ret;
4426 }
4427 
4428 static void switch2_remove(struct hid_device *hdev)
4429 {
4430 	struct switch2_controller *ns2 = hid_get_drvdata(hdev);
4431 
4432 	switch2_controller_put(ns2);
4433 	mutex_lock(&ns2->lock);
4434 	ns2->hdev = NULL;
4435 	ida_free(&nintendo_player_id_allocator, ns2->player_id);
4436 	mutex_unlock(&ns2->lock);
4437 	kref_put(&ns2->refcount, switch2_kref_put);
4438 	hid_hw_close(hdev);
4439 	hid_hw_stop(hdev);
4440 }
4441 
4442 static const struct hid_device_id nintendo_hid_devices[] = {
4443 	/* Switch devices */
4444 	{ HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
4445 			 USB_DEVICE_ID_NINTENDO_PROCON) },
4446 	{ HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
4447 			 USB_DEVICE_ID_NINTENDO_SNESCON) },
4448 	{ HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
4449 			 USB_DEVICE_ID_NINTENDO_GENCON) },
4450 	{ HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
4451 			 USB_DEVICE_ID_NINTENDO_N64CON) },
4452 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
4453 			 USB_DEVICE_ID_NINTENDO_PROCON) },
4454 	{ HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
4455 			 USB_DEVICE_ID_NINTENDO_CHRGGRIP) },
4456 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
4457 			 USB_DEVICE_ID_NINTENDO_JOYCONL) },
4458 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
4459 			 USB_DEVICE_ID_NINTENDO_JOYCONR) },
4460 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
4461 			 USB_DEVICE_ID_NINTENDO_SNESCON) },
4462 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
4463 			 USB_DEVICE_ID_NINTENDO_GENCON) },
4464 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
4465 			 USB_DEVICE_ID_NINTENDO_N64CON) },
4466 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_HORI,
4467 			 USB_DEVICE_ID_HORI_WIRELESS_SWITCH_PAD) },
4468 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_PDP,
4469 			 USB_DEVICE_ID_PDP_SWITCH_AFTERGLOW) },
4470 	/* Switch 2 devices */
4471 	{ HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
4472 			 USB_DEVICE_ID_NINTENDO_NS2_JOYCONL) },
4473 	{ HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
4474 			 USB_DEVICE_ID_NINTENDO_NS2_JOYCONR) },
4475 	{ HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
4476 			 USB_DEVICE_ID_NINTENDO_NS2_PROCON) },
4477 	{ HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
4478 			 USB_DEVICE_ID_NINTENDO_NS2_GCCON) },
4479 	{ }
4480 };
4481 MODULE_DEVICE_TABLE(hid, nintendo_hid_devices);
4482 
4483 static bool nintendo_is_switch2(struct hid_device *hdev)
4484 {
4485 	return hdev->vendor == USB_VENDOR_ID_NINTENDO &&
4486 		hdev->product >= USB_DEVICE_ID_NINTENDO_NS2_JOYCONR;
4487 }
4488 
4489 static void nintendo_hid_remove(struct hid_device *hdev)
4490 {
4491 	if (nintendo_is_switch2(hdev))
4492 		switch2_remove(hdev);
4493 	else
4494 		joycon_remove(hdev);
4495 }
4496 
4497 static int nintendo_hid_event(struct hid_device *hdev,
4498 			      struct hid_report *report, u8 *raw_data, int size)
4499 {
4500 	if (nintendo_is_switch2(hdev))
4501 		return switch2_event(hdev, report, raw_data, size);
4502 	else
4503 		return joycon_event(hdev, report, raw_data, size);
4504 }
4505 
4506 static const __u8 *nintendo_hid_report_fixup(struct hid_device *hdev,
4507 			    __u8 *rdesc, unsigned int *rsize)
4508 {
4509 	if (hdev->vendor == USB_VENDOR_ID_NINTENDO &&
4510 		hdev->product == USB_DEVICE_ID_NINTENDO_NS2_JOYCONR &&
4511 		*rsize == 100 && rdesc[24] == NS2_REPORT_JCL)
4512 		/*
4513 		 * The NYXI Hyperion 3 right Joy-Con accidentally reports as the
4514 		 * left one. Since the HID subsystem rejects report IDs that
4515 		 * aren't listed in the descriptor, we need to patch it.
4516 		 */
4517 		rdesc[24] = NS2_REPORT_JCR;
4518 	return rdesc;
4519 }
4520 
4521 static int nintendo_hid_probe(struct hid_device *hdev,
4522 			    const struct hid_device_id *id)
4523 {
4524 	if (nintendo_is_switch2(hdev))
4525 		return switch2_probe(hdev, id);
4526 	else
4527 		return joycon_probe(hdev, id);
4528 }
4529 
4530 static int nintendo_hid_resume(struct hid_device *hdev)
4531 {
4532 	if (nintendo_is_switch2(hdev))
4533 		return 0;
4534 	else
4535 		return joycon_resume(hdev);
4536 }
4537 
4538 static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message)
4539 {
4540 	if (nintendo_is_switch2(hdev))
4541 		return 0;
4542 	else
4543 		return joycon_suspend(hdev, message);
4544 }
4545 
4546 static struct hid_driver nintendo_hid_driver = {
4547 	.name		= "nintendo",
4548 	.id_table	= nintendo_hid_devices,
4549 	.report_fixup	= nintendo_hid_report_fixup,
4550 	.probe		= nintendo_hid_probe,
4551 	.remove		= nintendo_hid_remove,
4552 	.raw_event	= nintendo_hid_event,
4553 	.resume		= pm_ptr(nintendo_hid_resume),
4554 	.suspend	= pm_ptr(nintendo_hid_suspend),
4555 };
4556 static int __init nintendo_init(void)
4557 {
4558 	return hid_register_driver(&nintendo_hid_driver);
4559 }
4560 
4561 static void __exit nintendo_exit(void)
4562 {
4563 	hid_unregister_driver(&nintendo_hid_driver);
4564 	ida_destroy(&nintendo_player_id_allocator);
4565 }
4566 
4567 module_init(nintendo_init);
4568 module_exit(nintendo_exit);
4569 
4570 MODULE_LICENSE("GPL");
4571 MODULE_AUTHOR("Ryan McClelland <rymcclel@gmail.com>");
4572 MODULE_AUTHOR("Emily Strickland <linux@emily.st>");
4573 MODULE_AUTHOR("Daniel J. Ogorchock <djogorchock@gmail.com>");
4574 MODULE_AUTHOR("Vicki Pfau <vi@endrift.com>");
4575 MODULE_DESCRIPTION("Driver for Nintendo Switch Controllers");
4576