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