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