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