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