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