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