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