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