HID: nintendo: patch hw version for userspace HID mappings
[platform/kernel/linux-starfive.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 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 <linux/delay.h>
27 #include <linux/device.h>
28 #include <linux/hid.h>
29 #include <linux/input.h>
30 #include <linux/jiffies.h>
31 #include <linux/leds.h>
32 #include <linux/module.h>
33 #include <linux/power_supply.h>
34 #include <linux/spinlock.h>
35
36 /*
37  * Reference the url below for the following HID report defines:
38  * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering
39  */
40
41 /* Output Reports */
42 static const u8 JC_OUTPUT_RUMBLE_AND_SUBCMD     = 0x01;
43 static const u8 JC_OUTPUT_FW_UPDATE_PKT         = 0x03;
44 static const u8 JC_OUTPUT_RUMBLE_ONLY           = 0x10;
45 static const u8 JC_OUTPUT_MCU_DATA              = 0x11;
46 static const u8 JC_OUTPUT_USB_CMD               = 0x80;
47
48 /* Subcommand IDs */
49 static const u8 JC_SUBCMD_STATE                 /*= 0x00*/;
50 static const u8 JC_SUBCMD_MANUAL_BT_PAIRING     = 0x01;
51 static const u8 JC_SUBCMD_REQ_DEV_INFO          = 0x02;
52 static const u8 JC_SUBCMD_SET_REPORT_MODE       = 0x03;
53 static const u8 JC_SUBCMD_TRIGGERS_ELAPSED      = 0x04;
54 static const u8 JC_SUBCMD_GET_PAGE_LIST_STATE   = 0x05;
55 static const u8 JC_SUBCMD_SET_HCI_STATE         = 0x06;
56 static const u8 JC_SUBCMD_RESET_PAIRING_INFO    = 0x07;
57 static const u8 JC_SUBCMD_LOW_POWER_MODE        = 0x08;
58 static const u8 JC_SUBCMD_SPI_FLASH_READ        = 0x10;
59 static const u8 JC_SUBCMD_SPI_FLASH_WRITE       = 0x11;
60 static const u8 JC_SUBCMD_RESET_MCU             = 0x20;
61 static const u8 JC_SUBCMD_SET_MCU_CONFIG        = 0x21;
62 static const u8 JC_SUBCMD_SET_MCU_STATE         = 0x22;
63 static const u8 JC_SUBCMD_SET_PLAYER_LIGHTS     = 0x30;
64 static const u8 JC_SUBCMD_GET_PLAYER_LIGHTS     = 0x31;
65 static const u8 JC_SUBCMD_SET_HOME_LIGHT        = 0x38;
66 static const u8 JC_SUBCMD_ENABLE_IMU            = 0x40;
67 static const u8 JC_SUBCMD_SET_IMU_SENSITIVITY   = 0x41;
68 static const u8 JC_SUBCMD_WRITE_IMU_REG         = 0x42;
69 static const u8 JC_SUBCMD_READ_IMU_REG          = 0x43;
70 static const u8 JC_SUBCMD_ENABLE_VIBRATION      = 0x48;
71 static const u8 JC_SUBCMD_GET_REGULATED_VOLTAGE = 0x50;
72
73 /* Input Reports */
74 static const u8 JC_INPUT_BUTTON_EVENT           = 0x3F;
75 static const u8 JC_INPUT_SUBCMD_REPLY           = 0x21;
76 static const u8 JC_INPUT_IMU_DATA               = 0x30;
77 static const u8 JC_INPUT_MCU_DATA               = 0x31;
78 static const u8 JC_INPUT_USB_RESPONSE           = 0x81;
79
80 /* Feature Reports */
81 static const u8 JC_FEATURE_LAST_SUBCMD          = 0x02;
82 static const u8 JC_FEATURE_OTA_FW_UPGRADE       = 0x70;
83 static const u8 JC_FEATURE_SETUP_MEM_READ       = 0x71;
84 static const u8 JC_FEATURE_MEM_READ             = 0x72;
85 static const u8 JC_FEATURE_ERASE_MEM_SECTOR     = 0x73;
86 static const u8 JC_FEATURE_MEM_WRITE            = 0x74;
87 static const u8 JC_FEATURE_LAUNCH               = 0x75;
88
89 /* USB Commands */
90 static const u8 JC_USB_CMD_CONN_STATUS          = 0x01;
91 static const u8 JC_USB_CMD_HANDSHAKE            = 0x02;
92 static const u8 JC_USB_CMD_BAUDRATE_3M          = 0x03;
93 static const u8 JC_USB_CMD_NO_TIMEOUT           = 0x04;
94 static const u8 JC_USB_CMD_EN_TIMEOUT           = 0x05;
95 static const u8 JC_USB_RESET                    = 0x06;
96 static const u8 JC_USB_PRE_HANDSHAKE            = 0x91;
97 static const u8 JC_USB_SEND_UART                = 0x92;
98
99 /* SPI storage addresses of factory calibration data */
100 static const u16 JC_CAL_DATA_START              = 0x603d;
101 static const u16 JC_CAL_DATA_END                = 0x604e;
102 #define JC_CAL_DATA_SIZE        (JC_CAL_DATA_END - JC_CAL_DATA_START + 1)
103
104
105 /* The raw analog joystick values will be mapped in terms of this magnitude */
106 static const u16 JC_MAX_STICK_MAG               = 32767;
107 static const u16 JC_STICK_FUZZ                  = 250;
108 static const u16 JC_STICK_FLAT                  = 500;
109
110 /* Hat values for pro controller's d-pad */
111 static const u16 JC_MAX_DPAD_MAG                = 1;
112 static const u16 JC_DPAD_FUZZ                   /*= 0*/;
113 static const u16 JC_DPAD_FLAT                   /*= 0*/;
114
115 /* frequency/amplitude tables for rumble */
116 struct joycon_rumble_freq_data {
117         u16 high;
118         u8 low;
119         u16 freq; /* Hz*/
120 };
121
122 struct joycon_rumble_amp_data {
123         u8 high;
124         u16 low;
125         u16 amp;
126 };
127
128 /*
129  * These tables are from
130  * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/rumble_data_table.md
131  */
132 static const struct joycon_rumble_freq_data joycon_rumble_frequencies[] = {
133         /* high, low, freq */
134         { 0x0000, 0x01,   41 }, { 0x0000, 0x02,   42 }, { 0x0000, 0x03,   43 },
135         { 0x0000, 0x04,   44 }, { 0x0000, 0x05,   45 }, { 0x0000, 0x06,   46 },
136         { 0x0000, 0x07,   47 }, { 0x0000, 0x08,   48 }, { 0x0000, 0x09,   49 },
137         { 0x0000, 0x0A,   50 }, { 0x0000, 0x0B,   51 }, { 0x0000, 0x0C,   52 },
138         { 0x0000, 0x0D,   53 }, { 0x0000, 0x0E,   54 }, { 0x0000, 0x0F,   55 },
139         { 0x0000, 0x10,   57 }, { 0x0000, 0x11,   58 }, { 0x0000, 0x12,   59 },
140         { 0x0000, 0x13,   60 }, { 0x0000, 0x14,   62 }, { 0x0000, 0x15,   63 },
141         { 0x0000, 0x16,   64 }, { 0x0000, 0x17,   66 }, { 0x0000, 0x18,   67 },
142         { 0x0000, 0x19,   69 }, { 0x0000, 0x1A,   70 }, { 0x0000, 0x1B,   72 },
143         { 0x0000, 0x1C,   73 }, { 0x0000, 0x1D,   75 }, { 0x0000, 0x1e,   77 },
144         { 0x0000, 0x1f,   78 }, { 0x0000, 0x20,   80 }, { 0x0400, 0x21,   82 },
145         { 0x0800, 0x22,   84 }, { 0x0c00, 0x23,   85 }, { 0x1000, 0x24,   87 },
146         { 0x1400, 0x25,   89 }, { 0x1800, 0x26,   91 }, { 0x1c00, 0x27,   93 },
147         { 0x2000, 0x28,   95 }, { 0x2400, 0x29,   97 }, { 0x2800, 0x2a,   99 },
148         { 0x2c00, 0x2b,  102 }, { 0x3000, 0x2c,  104 }, { 0x3400, 0x2d,  106 },
149         { 0x3800, 0x2e,  108 }, { 0x3c00, 0x2f,  111 }, { 0x4000, 0x30,  113 },
150         { 0x4400, 0x31,  116 }, { 0x4800, 0x32,  118 }, { 0x4c00, 0x33,  121 },
151         { 0x5000, 0x34,  123 }, { 0x5400, 0x35,  126 }, { 0x5800, 0x36,  129 },
152         { 0x5c00, 0x37,  132 }, { 0x6000, 0x38,  135 }, { 0x6400, 0x39,  137 },
153         { 0x6800, 0x3a,  141 }, { 0x6c00, 0x3b,  144 }, { 0x7000, 0x3c,  147 },
154         { 0x7400, 0x3d,  150 }, { 0x7800, 0x3e,  153 }, { 0x7c00, 0x3f,  157 },
155         { 0x8000, 0x40,  160 }, { 0x8400, 0x41,  164 }, { 0x8800, 0x42,  167 },
156         { 0x8c00, 0x43,  171 }, { 0x9000, 0x44,  174 }, { 0x9400, 0x45,  178 },
157         { 0x9800, 0x46,  182 }, { 0x9c00, 0x47,  186 }, { 0xa000, 0x48,  190 },
158         { 0xa400, 0x49,  194 }, { 0xa800, 0x4a,  199 }, { 0xac00, 0x4b,  203 },
159         { 0xb000, 0x4c,  207 }, { 0xb400, 0x4d,  212 }, { 0xb800, 0x4e,  217 },
160         { 0xbc00, 0x4f,  221 }, { 0xc000, 0x50,  226 }, { 0xc400, 0x51,  231 },
161         { 0xc800, 0x52,  236 }, { 0xcc00, 0x53,  241 }, { 0xd000, 0x54,  247 },
162         { 0xd400, 0x55,  252 }, { 0xd800, 0x56,  258 }, { 0xdc00, 0x57,  263 },
163         { 0xe000, 0x58,  269 }, { 0xe400, 0x59,  275 }, { 0xe800, 0x5a,  281 },
164         { 0xec00, 0x5b,  287 }, { 0xf000, 0x5c,  293 }, { 0xf400, 0x5d,  300 },
165         { 0xf800, 0x5e,  306 }, { 0xfc00, 0x5f,  313 }, { 0x0001, 0x60,  320 },
166         { 0x0401, 0x61,  327 }, { 0x0801, 0x62,  334 }, { 0x0c01, 0x63,  341 },
167         { 0x1001, 0x64,  349 }, { 0x1401, 0x65,  357 }, { 0x1801, 0x66,  364 },
168         { 0x1c01, 0x67,  372 }, { 0x2001, 0x68,  381 }, { 0x2401, 0x69,  389 },
169         { 0x2801, 0x6a,  397 }, { 0x2c01, 0x6b,  406 }, { 0x3001, 0x6c,  415 },
170         { 0x3401, 0x6d,  424 }, { 0x3801, 0x6e,  433 }, { 0x3c01, 0x6f,  443 },
171         { 0x4001, 0x70,  453 }, { 0x4401, 0x71,  462 }, { 0x4801, 0x72,  473 },
172         { 0x4c01, 0x73,  483 }, { 0x5001, 0x74,  494 }, { 0x5401, 0x75,  504 },
173         { 0x5801, 0x76,  515 }, { 0x5c01, 0x77,  527 }, { 0x6001, 0x78,  538 },
174         { 0x6401, 0x79,  550 }, { 0x6801, 0x7a,  562 }, { 0x6c01, 0x7b,  574 },
175         { 0x7001, 0x7c,  587 }, { 0x7401, 0x7d,  600 }, { 0x7801, 0x7e,  613 },
176         { 0x7c01, 0x7f,  626 }, { 0x8001, 0x00,  640 }, { 0x8401, 0x00,  654 },
177         { 0x8801, 0x00,  668 }, { 0x8c01, 0x00,  683 }, { 0x9001, 0x00,  698 },
178         { 0x9401, 0x00,  713 }, { 0x9801, 0x00,  729 }, { 0x9c01, 0x00,  745 },
179         { 0xa001, 0x00,  761 }, { 0xa401, 0x00,  778 }, { 0xa801, 0x00,  795 },
180         { 0xac01, 0x00,  812 }, { 0xb001, 0x00,  830 }, { 0xb401, 0x00,  848 },
181         { 0xb801, 0x00,  867 }, { 0xbc01, 0x00,  886 }, { 0xc001, 0x00,  905 },
182         { 0xc401, 0x00,  925 }, { 0xc801, 0x00,  945 }, { 0xcc01, 0x00,  966 },
183         { 0xd001, 0x00,  987 }, { 0xd401, 0x00, 1009 }, { 0xd801, 0x00, 1031 },
184         { 0xdc01, 0x00, 1053 }, { 0xe001, 0x00, 1076 }, { 0xe401, 0x00, 1100 },
185         { 0xe801, 0x00, 1124 }, { 0xec01, 0x00, 1149 }, { 0xf001, 0x00, 1174 },
186         { 0xf401, 0x00, 1199 }, { 0xf801, 0x00, 1226 }, { 0xfc01, 0x00, 1253 }
187 };
188
189 #define joycon_max_rumble_amp   (1003)
190 static const struct joycon_rumble_amp_data joycon_rumble_amplitudes[] = {
191         /* high, low, amp */
192         { 0x00, 0x0040,    0 },
193         { 0x02, 0x8040,   10 }, { 0x04, 0x0041,   12 }, { 0x06, 0x8041,   14 },
194         { 0x08, 0x0042,   17 }, { 0x0a, 0x8042,   20 }, { 0x0c, 0x0043,   24 },
195         { 0x0e, 0x8043,   28 }, { 0x10, 0x0044,   33 }, { 0x12, 0x8044,   40 },
196         { 0x14, 0x0045,   47 }, { 0x16, 0x8045,   56 }, { 0x18, 0x0046,   67 },
197         { 0x1a, 0x8046,   80 }, { 0x1c, 0x0047,   95 }, { 0x1e, 0x8047,  112 },
198         { 0x20, 0x0048,  117 }, { 0x22, 0x8048,  123 }, { 0x24, 0x0049,  128 },
199         { 0x26, 0x8049,  134 }, { 0x28, 0x004a,  140 }, { 0x2a, 0x804a,  146 },
200         { 0x2c, 0x004b,  152 }, { 0x2e, 0x804b,  159 }, { 0x30, 0x004c,  166 },
201         { 0x32, 0x804c,  173 }, { 0x34, 0x004d,  181 }, { 0x36, 0x804d,  189 },
202         { 0x38, 0x004e,  198 }, { 0x3a, 0x804e,  206 }, { 0x3c, 0x004f,  215 },
203         { 0x3e, 0x804f,  225 }, { 0x40, 0x0050,  230 }, { 0x42, 0x8050,  235 },
204         { 0x44, 0x0051,  240 }, { 0x46, 0x8051,  245 }, { 0x48, 0x0052,  251 },
205         { 0x4a, 0x8052,  256 }, { 0x4c, 0x0053,  262 }, { 0x4e, 0x8053,  268 },
206         { 0x50, 0x0054,  273 }, { 0x52, 0x8054,  279 }, { 0x54, 0x0055,  286 },
207         { 0x56, 0x8055,  292 }, { 0x58, 0x0056,  298 }, { 0x5a, 0x8056,  305 },
208         { 0x5c, 0x0057,  311 }, { 0x5e, 0x8057,  318 }, { 0x60, 0x0058,  325 },
209         { 0x62, 0x8058,  332 }, { 0x64, 0x0059,  340 }, { 0x66, 0x8059,  347 },
210         { 0x68, 0x005a,  355 }, { 0x6a, 0x805a,  362 }, { 0x6c, 0x005b,  370 },
211         { 0x6e, 0x805b,  378 }, { 0x70, 0x005c,  387 }, { 0x72, 0x805c,  395 },
212         { 0x74, 0x005d,  404 }, { 0x76, 0x805d,  413 }, { 0x78, 0x005e,  422 },
213         { 0x7a, 0x805e,  431 }, { 0x7c, 0x005f,  440 }, { 0x7e, 0x805f,  450 },
214         { 0x80, 0x0060,  460 }, { 0x82, 0x8060,  470 }, { 0x84, 0x0061,  480 },
215         { 0x86, 0x8061,  491 }, { 0x88, 0x0062,  501 }, { 0x8a, 0x8062,  512 },
216         { 0x8c, 0x0063,  524 }, { 0x8e, 0x8063,  535 }, { 0x90, 0x0064,  547 },
217         { 0x92, 0x8064,  559 }, { 0x94, 0x0065,  571 }, { 0x96, 0x8065,  584 },
218         { 0x98, 0x0066,  596 }, { 0x9a, 0x8066,  609 }, { 0x9c, 0x0067,  623 },
219         { 0x9e, 0x8067,  636 }, { 0xa0, 0x0068,  650 }, { 0xa2, 0x8068,  665 },
220         { 0xa4, 0x0069,  679 }, { 0xa6, 0x8069,  694 }, { 0xa8, 0x006a,  709 },
221         { 0xaa, 0x806a,  725 }, { 0xac, 0x006b,  741 }, { 0xae, 0x806b,  757 },
222         { 0xb0, 0x006c,  773 }, { 0xb2, 0x806c,  790 }, { 0xb4, 0x006d,  808 },
223         { 0xb6, 0x806d,  825 }, { 0xb8, 0x006e,  843 }, { 0xba, 0x806e,  862 },
224         { 0xbc, 0x006f,  881 }, { 0xbe, 0x806f,  900 }, { 0xc0, 0x0070,  920 },
225         { 0xc2, 0x8070,  940 }, { 0xc4, 0x0071,  960 }, { 0xc6, 0x8071,  981 },
226         { 0xc8, 0x0072, joycon_max_rumble_amp }
227 };
228
229 /* States for controller state machine */
230 enum joycon_ctlr_state {
231         JOYCON_CTLR_STATE_INIT,
232         JOYCON_CTLR_STATE_READ,
233 };
234
235 struct joycon_stick_cal {
236         s32 max;
237         s32 min;
238         s32 center;
239 };
240
241 /*
242  * All the controller's button values are stored in a u32.
243  * They can be accessed with bitwise ANDs.
244  */
245 static const u32 JC_BTN_Y       = BIT(0);
246 static const u32 JC_BTN_X       = BIT(1);
247 static const u32 JC_BTN_B       = BIT(2);
248 static const u32 JC_BTN_A       = BIT(3);
249 static const u32 JC_BTN_SR_R    = BIT(4);
250 static const u32 JC_BTN_SL_R    = BIT(5);
251 static const u32 JC_BTN_R       = BIT(6);
252 static const u32 JC_BTN_ZR      = BIT(7);
253 static const u32 JC_BTN_MINUS   = BIT(8);
254 static const u32 JC_BTN_PLUS    = BIT(9);
255 static const u32 JC_BTN_RSTICK  = BIT(10);
256 static const u32 JC_BTN_LSTICK  = BIT(11);
257 static const u32 JC_BTN_HOME    = BIT(12);
258 static const u32 JC_BTN_CAP     = BIT(13); /* capture button */
259 static const u32 JC_BTN_DOWN    = BIT(16);
260 static const u32 JC_BTN_UP      = BIT(17);
261 static const u32 JC_BTN_RIGHT   = BIT(18);
262 static const u32 JC_BTN_LEFT    = BIT(19);
263 static const u32 JC_BTN_SR_L    = BIT(20);
264 static const u32 JC_BTN_SL_L    = BIT(21);
265 static const u32 JC_BTN_L       = BIT(22);
266 static const u32 JC_BTN_ZL      = BIT(23);
267
268 enum joycon_msg_type {
269         JOYCON_MSG_TYPE_NONE,
270         JOYCON_MSG_TYPE_USB,
271         JOYCON_MSG_TYPE_SUBCMD,
272 };
273
274 struct joycon_subcmd_request {
275         u8 output_id; /* must be 0x01 for subcommand, 0x10 for rumble only */
276         u8 packet_num; /* incremented every send */
277         u8 rumble_data[8];
278         u8 subcmd_id;
279         u8 data[]; /* length depends on the subcommand */
280 } __packed;
281
282 struct joycon_subcmd_reply {
283         u8 ack; /* MSB 1 for ACK, 0 for NACK */
284         u8 id; /* id of requested subcmd */
285         u8 data[]; /* will be at most 35 bytes */
286 } __packed;
287
288 struct joycon_input_report {
289         u8 id;
290         u8 timer;
291         u8 bat_con; /* battery and connection info */
292         u8 button_status[3];
293         u8 left_stick[3];
294         u8 right_stick[3];
295         u8 vibrator_report;
296
297         /*
298          * If support for firmware updates, gyroscope data, and/or NFC/IR
299          * are added in the future, this can be swapped for a union.
300          */
301         struct joycon_subcmd_reply reply;
302 } __packed;
303
304 #define JC_MAX_RESP_SIZE        (sizeof(struct joycon_input_report) + 35)
305 #define JC_RUMBLE_DATA_SIZE     8
306 #define JC_RUMBLE_QUEUE_SIZE    8
307
308 static const u16 JC_RUMBLE_DFLT_LOW_FREQ = 160;
309 static const u16 JC_RUMBLE_DFLT_HIGH_FREQ = 320;
310 static const u16 JC_RUMBLE_PERIOD_MS = 50;
311
312 static const char * const joycon_player_led_names[] = {
313         LED_FUNCTION_PLAYER1,
314         LED_FUNCTION_PLAYER2,
315         LED_FUNCTION_PLAYER3,
316         LED_FUNCTION_PLAYER4,
317 };
318 #define JC_NUM_LEDS             ARRAY_SIZE(joycon_player_led_names)
319
320 /* Each physical controller is associated with a joycon_ctlr struct */
321 struct joycon_ctlr {
322         struct hid_device *hdev;
323         struct input_dev *input;
324         struct led_classdev leds[JC_NUM_LEDS]; /* player leds */
325         struct led_classdev home_led;
326         enum joycon_ctlr_state ctlr_state;
327         spinlock_t lock;
328
329         /* The following members are used for synchronous sends/receives */
330         enum joycon_msg_type msg_type;
331         u8 subcmd_num;
332         struct mutex output_mutex;
333         u8 input_buf[JC_MAX_RESP_SIZE];
334         wait_queue_head_t wait;
335         bool received_resp;
336         u8 usb_ack_match;
337         u8 subcmd_ack_match;
338         bool received_input_report;
339
340         /* factory calibration data */
341         struct joycon_stick_cal left_stick_cal_x;
342         struct joycon_stick_cal left_stick_cal_y;
343         struct joycon_stick_cal right_stick_cal_x;
344         struct joycon_stick_cal right_stick_cal_y;
345
346         /* power supply data */
347         struct power_supply *battery;
348         struct power_supply_desc battery_desc;
349         u8 battery_capacity;
350         bool battery_charging;
351         bool host_powered;
352
353         /* rumble */
354         u8 rumble_data[JC_RUMBLE_QUEUE_SIZE][JC_RUMBLE_DATA_SIZE];
355         int rumble_queue_head;
356         int rumble_queue_tail;
357         struct workqueue_struct *rumble_queue;
358         struct work_struct rumble_worker;
359         unsigned int rumble_msecs;
360         u16 rumble_ll_freq;
361         u16 rumble_lh_freq;
362         u16 rumble_rl_freq;
363         u16 rumble_rh_freq;
364 };
365
366 static int __joycon_hid_send(struct hid_device *hdev, u8 *data, size_t len)
367 {
368         u8 *buf;
369         int ret;
370
371         buf = kmemdup(data, len, GFP_KERNEL);
372         if (!buf)
373                 return -ENOMEM;
374         ret = hid_hw_output_report(hdev, buf, len);
375         kfree(buf);
376         if (ret < 0)
377                 hid_dbg(hdev, "Failed to send output report ret=%d\n", ret);
378         return ret;
379 }
380
381 static int joycon_hid_send_sync(struct joycon_ctlr *ctlr, u8 *data, size_t len,
382                                 u32 timeout)
383 {
384         int ret;
385         int tries = 2;
386
387         /*
388          * The controller occasionally seems to drop subcommands. In testing,
389          * doing one retry after a timeout appears to always work.
390          */
391         while (tries--) {
392                 /*
393                  * If we are in the proper reporting mode, wait for an input
394                  * report prior to sending the subcommand. This improves
395                  * reliability considerably.
396                  */
397                 if (ctlr->ctlr_state == JOYCON_CTLR_STATE_READ) {
398                         unsigned long flags;
399
400                         spin_lock_irqsave(&ctlr->lock, flags);
401                         ctlr->received_input_report = false;
402                         spin_unlock_irqrestore(&ctlr->lock, flags);
403                         ret = wait_event_timeout(ctlr->wait,
404                                                  ctlr->received_input_report,
405                                                  HZ / 4);
406                         /* We will still proceed, even with a timeout here */
407                         if (!ret)
408                                 hid_warn(ctlr->hdev,
409                                          "timeout waiting for input report\n");
410                 }
411
412                 ret = __joycon_hid_send(ctlr->hdev, data, len);
413                 if (ret < 0) {
414                         memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE);
415                         return ret;
416                 }
417
418                 ret = wait_event_timeout(ctlr->wait, ctlr->received_resp,
419                                          timeout);
420                 if (!ret) {
421                         hid_dbg(ctlr->hdev,
422                                 "synchronous send/receive timed out\n");
423                         if (tries) {
424                                 hid_dbg(ctlr->hdev,
425                                         "retrying sync send after timeout\n");
426                         }
427                         memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE);
428                         ret = -ETIMEDOUT;
429                 } else {
430                         ret = 0;
431                         break;
432                 }
433         }
434
435         ctlr->received_resp = false;
436         return ret;
437 }
438
439 static int joycon_send_usb(struct joycon_ctlr *ctlr, u8 cmd, u32 timeout)
440 {
441         int ret;
442         u8 buf[2] = {JC_OUTPUT_USB_CMD};
443
444         buf[1] = cmd;
445         ctlr->usb_ack_match = cmd;
446         ctlr->msg_type = JOYCON_MSG_TYPE_USB;
447         ret = joycon_hid_send_sync(ctlr, buf, sizeof(buf), timeout);
448         if (ret)
449                 hid_dbg(ctlr->hdev, "send usb command failed; ret=%d\n", ret);
450         return ret;
451 }
452
453 static int joycon_send_subcmd(struct joycon_ctlr *ctlr,
454                               struct joycon_subcmd_request *subcmd,
455                               size_t data_len, u32 timeout)
456 {
457         int ret;
458         unsigned long flags;
459
460         spin_lock_irqsave(&ctlr->lock, flags);
461         memcpy(subcmd->rumble_data, ctlr->rumble_data[ctlr->rumble_queue_tail],
462                JC_RUMBLE_DATA_SIZE);
463         spin_unlock_irqrestore(&ctlr->lock, flags);
464
465         subcmd->output_id = JC_OUTPUT_RUMBLE_AND_SUBCMD;
466         subcmd->packet_num = ctlr->subcmd_num;
467         if (++ctlr->subcmd_num > 0xF)
468                 ctlr->subcmd_num = 0;
469         ctlr->subcmd_ack_match = subcmd->subcmd_id;
470         ctlr->msg_type = JOYCON_MSG_TYPE_SUBCMD;
471
472         ret = joycon_hid_send_sync(ctlr, (u8 *)subcmd,
473                                    sizeof(*subcmd) + data_len, timeout);
474         if (ret < 0)
475                 hid_dbg(ctlr->hdev, "send subcommand failed; ret=%d\n", ret);
476         else
477                 ret = 0;
478         return ret;
479 }
480
481 /* Supply nibbles for flash and on. Ones correspond to active */
482 static int joycon_set_player_leds(struct joycon_ctlr *ctlr, u8 flash, u8 on)
483 {
484         struct joycon_subcmd_request *req;
485         u8 buffer[sizeof(*req) + 1] = { 0 };
486
487         req = (struct joycon_subcmd_request *)buffer;
488         req->subcmd_id = JC_SUBCMD_SET_PLAYER_LIGHTS;
489         req->data[0] = (flash << 4) | on;
490
491         hid_dbg(ctlr->hdev, "setting player leds\n");
492         return joycon_send_subcmd(ctlr, req, 1, HZ/4);
493 }
494
495 static const u16 DFLT_STICK_CAL_CEN = 2000;
496 static const u16 DFLT_STICK_CAL_MAX = 3500;
497 static const u16 DFLT_STICK_CAL_MIN = 500;
498 static int joycon_request_calibration(struct joycon_ctlr *ctlr)
499 {
500         struct joycon_subcmd_request *req;
501         u8 buffer[sizeof(*req) + 5] = { 0 };
502         struct joycon_input_report *report;
503         struct joycon_stick_cal *cal_x;
504         struct joycon_stick_cal *cal_y;
505         s32 x_max_above;
506         s32 x_min_below;
507         s32 y_max_above;
508         s32 y_min_below;
509         u8 *data;
510         u8 *raw_cal;
511         int ret;
512
513         req = (struct joycon_subcmd_request *)buffer;
514         req->subcmd_id = JC_SUBCMD_SPI_FLASH_READ;
515         data = req->data;
516         data[0] = 0xFF & JC_CAL_DATA_START;
517         data[1] = 0xFF & (JC_CAL_DATA_START >> 8);
518         data[2] = 0xFF & (JC_CAL_DATA_START >> 16);
519         data[3] = 0xFF & (JC_CAL_DATA_START >> 24);
520         data[4] = JC_CAL_DATA_SIZE;
521
522         hid_dbg(ctlr->hdev, "requesting cal data\n");
523         ret = joycon_send_subcmd(ctlr, req, 5, HZ);
524         if (ret) {
525                 hid_warn(ctlr->hdev,
526                          "Failed to read stick cal, using defaults; ret=%d\n",
527                          ret);
528
529                 ctlr->left_stick_cal_x.center = DFLT_STICK_CAL_CEN;
530                 ctlr->left_stick_cal_x.max = DFLT_STICK_CAL_MAX;
531                 ctlr->left_stick_cal_x.min = DFLT_STICK_CAL_MIN;
532
533                 ctlr->left_stick_cal_y.center = DFLT_STICK_CAL_CEN;
534                 ctlr->left_stick_cal_y.max = DFLT_STICK_CAL_MAX;
535                 ctlr->left_stick_cal_y.min = DFLT_STICK_CAL_MIN;
536
537                 ctlr->right_stick_cal_x.center = DFLT_STICK_CAL_CEN;
538                 ctlr->right_stick_cal_x.max = DFLT_STICK_CAL_MAX;
539                 ctlr->right_stick_cal_x.min = DFLT_STICK_CAL_MIN;
540
541                 ctlr->right_stick_cal_y.center = DFLT_STICK_CAL_CEN;
542                 ctlr->right_stick_cal_y.max = DFLT_STICK_CAL_MAX;
543                 ctlr->right_stick_cal_y.min = DFLT_STICK_CAL_MIN;
544
545                 return ret;
546         }
547
548         report = (struct joycon_input_report *)ctlr->input_buf;
549         raw_cal = &report->reply.data[5];
550
551         /* left stick calibration parsing */
552         cal_x = &ctlr->left_stick_cal_x;
553         cal_y = &ctlr->left_stick_cal_y;
554
555         x_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 0), 0, 12);
556         y_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 1), 4, 12);
557         cal_x->center = hid_field_extract(ctlr->hdev, (raw_cal + 3), 0, 12);
558         cal_y->center = hid_field_extract(ctlr->hdev, (raw_cal + 4), 4, 12);
559         x_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 6), 0, 12);
560         y_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 7), 4, 12);
561         cal_x->max = cal_x->center + x_max_above;
562         cal_x->min = cal_x->center - x_min_below;
563         cal_y->max = cal_y->center + y_max_above;
564         cal_y->min = cal_y->center - y_min_below;
565
566         /* right stick calibration parsing */
567         raw_cal += 9;
568         cal_x = &ctlr->right_stick_cal_x;
569         cal_y = &ctlr->right_stick_cal_y;
570
571         cal_x->center = hid_field_extract(ctlr->hdev, (raw_cal + 0), 0, 12);
572         cal_y->center = hid_field_extract(ctlr->hdev, (raw_cal + 1), 4, 12);
573         x_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 3), 0, 12);
574         y_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 4), 4, 12);
575         x_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 6), 0, 12);
576         y_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 7), 4, 12);
577         cal_x->max = cal_x->center + x_max_above;
578         cal_x->min = cal_x->center - x_min_below;
579         cal_y->max = cal_y->center + y_max_above;
580         cal_y->min = cal_y->center - y_min_below;
581
582         hid_dbg(ctlr->hdev, "calibration:\n"
583                             "l_x_c=%d l_x_max=%d l_x_min=%d\n"
584                             "l_y_c=%d l_y_max=%d l_y_min=%d\n"
585                             "r_x_c=%d r_x_max=%d r_x_min=%d\n"
586                             "r_y_c=%d r_y_max=%d r_y_min=%d\n",
587                             ctlr->left_stick_cal_x.center,
588                             ctlr->left_stick_cal_x.max,
589                             ctlr->left_stick_cal_x.min,
590                             ctlr->left_stick_cal_y.center,
591                             ctlr->left_stick_cal_y.max,
592                             ctlr->left_stick_cal_y.min,
593                             ctlr->right_stick_cal_x.center,
594                             ctlr->right_stick_cal_x.max,
595                             ctlr->right_stick_cal_x.min,
596                             ctlr->right_stick_cal_y.center,
597                             ctlr->right_stick_cal_y.max,
598                             ctlr->right_stick_cal_y.min);
599
600         return 0;
601 }
602
603 static int joycon_set_report_mode(struct joycon_ctlr *ctlr)
604 {
605         struct joycon_subcmd_request *req;
606         u8 buffer[sizeof(*req) + 1] = { 0 };
607
608         req = (struct joycon_subcmd_request *)buffer;
609         req->subcmd_id = JC_SUBCMD_SET_REPORT_MODE;
610         req->data[0] = 0x30; /* standard, full report mode */
611
612         hid_dbg(ctlr->hdev, "setting controller report mode\n");
613         return joycon_send_subcmd(ctlr, req, 1, HZ);
614 }
615
616 static int joycon_enable_rumble(struct joycon_ctlr *ctlr)
617 {
618         struct joycon_subcmd_request *req;
619         u8 buffer[sizeof(*req) + 1] = { 0 };
620
621         req = (struct joycon_subcmd_request *)buffer;
622         req->subcmd_id = JC_SUBCMD_ENABLE_VIBRATION;
623         req->data[0] = 0x01; /* note: 0x00 would disable */
624
625         hid_dbg(ctlr->hdev, "enabling rumble\n");
626         return joycon_send_subcmd(ctlr, req, 1, HZ/4);
627 }
628
629 static s32 joycon_map_stick_val(struct joycon_stick_cal *cal, s32 val)
630 {
631         s32 center = cal->center;
632         s32 min = cal->min;
633         s32 max = cal->max;
634         s32 new_val;
635
636         if (val > center) {
637                 new_val = (val - center) * JC_MAX_STICK_MAG;
638                 new_val /= (max - center);
639         } else {
640                 new_val = (center - val) * -JC_MAX_STICK_MAG;
641                 new_val /= (center - min);
642         }
643         new_val = clamp(new_val, (s32)-JC_MAX_STICK_MAG, (s32)JC_MAX_STICK_MAG);
644         return new_val;
645 }
646
647 static void joycon_parse_report(struct joycon_ctlr *ctlr,
648                                 struct joycon_input_report *rep)
649 {
650         struct input_dev *dev = ctlr->input;
651         unsigned long flags;
652         u8 tmp;
653         u32 btns;
654         u32 id = ctlr->hdev->product;
655         unsigned long msecs = jiffies_to_msecs(jiffies);
656
657         spin_lock_irqsave(&ctlr->lock, flags);
658         if (IS_ENABLED(CONFIG_NINTENDO_FF) && rep->vibrator_report &&
659             (msecs - ctlr->rumble_msecs) >= JC_RUMBLE_PERIOD_MS)
660                 queue_work(ctlr->rumble_queue, &ctlr->rumble_worker);
661
662         /* Parse the battery status */
663         tmp = rep->bat_con;
664         ctlr->host_powered = tmp & BIT(0);
665         ctlr->battery_charging = tmp & BIT(4);
666         tmp = tmp >> 5;
667         switch (tmp) {
668         case 0: /* empty */
669                 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
670                 break;
671         case 1: /* low */
672                 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
673                 break;
674         case 2: /* medium */
675                 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
676                 break;
677         case 3: /* high */
678                 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_HIGH;
679                 break;
680         case 4: /* full */
681                 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
682                 break;
683         default:
684                 ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
685                 hid_warn(ctlr->hdev, "Invalid battery status\n");
686                 break;
687         }
688         spin_unlock_irqrestore(&ctlr->lock, flags);
689
690         /* Parse the buttons and sticks */
691         btns = hid_field_extract(ctlr->hdev, rep->button_status, 0, 24);
692
693         if (id != USB_DEVICE_ID_NINTENDO_JOYCONR) {
694                 u16 raw_x;
695                 u16 raw_y;
696                 s32 x;
697                 s32 y;
698
699                 /* get raw stick values */
700                 raw_x = hid_field_extract(ctlr->hdev, rep->left_stick, 0, 12);
701                 raw_y = hid_field_extract(ctlr->hdev,
702                                           rep->left_stick + 1, 4, 12);
703                 /* map the stick values */
704                 x = joycon_map_stick_val(&ctlr->left_stick_cal_x, raw_x);
705                 y = -joycon_map_stick_val(&ctlr->left_stick_cal_y, raw_y);
706                 /* report sticks */
707                 input_report_abs(dev, ABS_X, x);
708                 input_report_abs(dev, ABS_Y, y);
709
710                 /* report buttons */
711                 input_report_key(dev, BTN_TL, btns & JC_BTN_L);
712                 input_report_key(dev, BTN_TL2, btns & JC_BTN_ZL);
713                 input_report_key(dev, BTN_SELECT, btns & JC_BTN_MINUS);
714                 input_report_key(dev, BTN_THUMBL, btns & JC_BTN_LSTICK);
715                 input_report_key(dev, BTN_Z, btns & JC_BTN_CAP);
716
717                 if (id != USB_DEVICE_ID_NINTENDO_PROCON) {
718                         /* Report the S buttons as the non-existent triggers */
719                         input_report_key(dev, BTN_TR, btns & JC_BTN_SL_L);
720                         input_report_key(dev, BTN_TR2, btns & JC_BTN_SR_L);
721
722                         /* Report d-pad as digital buttons for the joy-cons */
723                         input_report_key(dev, BTN_DPAD_DOWN,
724                                          btns & JC_BTN_DOWN);
725                         input_report_key(dev, BTN_DPAD_UP, btns & JC_BTN_UP);
726                         input_report_key(dev, BTN_DPAD_RIGHT,
727                                          btns & JC_BTN_RIGHT);
728                         input_report_key(dev, BTN_DPAD_LEFT,
729                                          btns & JC_BTN_LEFT);
730                 } else {
731                         int hatx = 0;
732                         int haty = 0;
733
734                         /* d-pad x */
735                         if (btns & JC_BTN_LEFT)
736                                 hatx = -1;
737                         else if (btns & JC_BTN_RIGHT)
738                                 hatx = 1;
739                         input_report_abs(dev, ABS_HAT0X, hatx);
740
741                         /* d-pad y */
742                         if (btns & JC_BTN_UP)
743                                 haty = -1;
744                         else if (btns & JC_BTN_DOWN)
745                                 haty = 1;
746                         input_report_abs(dev, ABS_HAT0Y, haty);
747                 }
748         }
749         if (id != USB_DEVICE_ID_NINTENDO_JOYCONL) {
750                 u16 raw_x;
751                 u16 raw_y;
752                 s32 x;
753                 s32 y;
754
755                 /* get raw stick values */
756                 raw_x = hid_field_extract(ctlr->hdev, rep->right_stick, 0, 12);
757                 raw_y = hid_field_extract(ctlr->hdev,
758                                           rep->right_stick + 1, 4, 12);
759                 /* map stick values */
760                 x = joycon_map_stick_val(&ctlr->right_stick_cal_x, raw_x);
761                 y = -joycon_map_stick_val(&ctlr->right_stick_cal_y, raw_y);
762                 /* report sticks */
763                 input_report_abs(dev, ABS_RX, x);
764                 input_report_abs(dev, ABS_RY, y);
765
766                 /* report buttons */
767                 input_report_key(dev, BTN_TR, btns & JC_BTN_R);
768                 input_report_key(dev, BTN_TR2, btns & JC_BTN_ZR);
769                 if (id != USB_DEVICE_ID_NINTENDO_PROCON) {
770                         /* Report the S buttons as the non-existent triggers */
771                         input_report_key(dev, BTN_TL, btns & JC_BTN_SL_R);
772                         input_report_key(dev, BTN_TL2, btns & JC_BTN_SR_R);
773                 }
774                 input_report_key(dev, BTN_START, btns & JC_BTN_PLUS);
775                 input_report_key(dev, BTN_THUMBR, btns & JC_BTN_RSTICK);
776                 input_report_key(dev, BTN_MODE, btns & JC_BTN_HOME);
777                 input_report_key(dev, BTN_WEST, btns & JC_BTN_Y);
778                 input_report_key(dev, BTN_NORTH, btns & JC_BTN_X);
779                 input_report_key(dev, BTN_EAST, btns & JC_BTN_A);
780                 input_report_key(dev, BTN_SOUTH, btns & JC_BTN_B);
781         }
782
783         input_sync(dev);
784
785         /*
786          * Immediately after receiving a report is the most reliable time to
787          * send a subcommand to the controller. Wake any subcommand senders
788          * waiting for a report.
789          */
790         if (unlikely(mutex_is_locked(&ctlr->output_mutex))) {
791                 spin_lock_irqsave(&ctlr->lock, flags);
792                 ctlr->received_input_report = true;
793                 spin_unlock_irqrestore(&ctlr->lock, flags);
794                 wake_up(&ctlr->wait);
795         }
796 }
797
798 static void joycon_rumble_worker(struct work_struct *work)
799 {
800         struct joycon_ctlr *ctlr = container_of(work, struct joycon_ctlr,
801                                                         rumble_worker);
802         unsigned long flags;
803         bool again = true;
804         int ret;
805
806         while (again) {
807                 mutex_lock(&ctlr->output_mutex);
808                 ret = joycon_enable_rumble(ctlr);
809                 mutex_unlock(&ctlr->output_mutex);
810                 if (ret < 0)
811                         hid_warn(ctlr->hdev, "Failed to set rumble; e=%d", ret);
812
813                 spin_lock_irqsave(&ctlr->lock, flags);
814                 ctlr->rumble_msecs = jiffies_to_msecs(jiffies);
815                 if (ctlr->rumble_queue_tail != ctlr->rumble_queue_head) {
816                         if (++ctlr->rumble_queue_tail >= JC_RUMBLE_QUEUE_SIZE)
817                                 ctlr->rumble_queue_tail = 0;
818                 } else {
819                         again = false;
820                 }
821                 spin_unlock_irqrestore(&ctlr->lock, flags);
822         }
823 }
824
825 #if IS_ENABLED(CONFIG_NINTENDO_FF)
826 static struct joycon_rumble_freq_data joycon_find_rumble_freq(u16 freq)
827 {
828         const size_t length = ARRAY_SIZE(joycon_rumble_frequencies);
829         const struct joycon_rumble_freq_data *data = joycon_rumble_frequencies;
830         int i = 0;
831
832         if (freq > data[0].freq) {
833                 for (i = 1; i < length - 1; i++) {
834                         if (freq > data[i - 1].freq && freq <= data[i].freq)
835                                 break;
836                 }
837         }
838
839         return data[i];
840 }
841
842 static struct joycon_rumble_amp_data joycon_find_rumble_amp(u16 amp)
843 {
844         const size_t length = ARRAY_SIZE(joycon_rumble_amplitudes);
845         const struct joycon_rumble_amp_data *data = joycon_rumble_amplitudes;
846         int i = 0;
847
848         if (amp > data[0].amp) {
849                 for (i = 1; i < length - 1; i++) {
850                         if (amp > data[i - 1].amp && amp <= data[i].amp)
851                                 break;
852                 }
853         }
854
855         return data[i];
856 }
857
858 static void joycon_encode_rumble(u8 *data, u16 freq_low, u16 freq_high, u16 amp)
859 {
860         struct joycon_rumble_freq_data freq_data_low;
861         struct joycon_rumble_freq_data freq_data_high;
862         struct joycon_rumble_amp_data amp_data;
863
864         freq_data_low = joycon_find_rumble_freq(freq_low);
865         freq_data_high = joycon_find_rumble_freq(freq_high);
866         amp_data = joycon_find_rumble_amp(amp);
867
868         data[0] = (freq_data_high.high >> 8) & 0xFF;
869         data[1] = (freq_data_high.high & 0xFF) + amp_data.high;
870         data[2] = freq_data_low.low + ((amp_data.low >> 8) & 0xFF);
871         data[3] = amp_data.low & 0xFF;
872 }
873
874 static const u16 JOYCON_MAX_RUMBLE_HIGH_FREQ    = 1253;
875 static const u16 JOYCON_MIN_RUMBLE_HIGH_FREQ    = 82;
876 static const u16 JOYCON_MAX_RUMBLE_LOW_FREQ     = 626;
877 static const u16 JOYCON_MIN_RUMBLE_LOW_FREQ     = 41;
878
879 static void joycon_clamp_rumble_freqs(struct joycon_ctlr *ctlr)
880 {
881         unsigned long flags;
882
883         spin_lock_irqsave(&ctlr->lock, flags);
884         ctlr->rumble_ll_freq = clamp(ctlr->rumble_ll_freq,
885                                      JOYCON_MIN_RUMBLE_LOW_FREQ,
886                                      JOYCON_MAX_RUMBLE_LOW_FREQ);
887         ctlr->rumble_lh_freq = clamp(ctlr->rumble_lh_freq,
888                                      JOYCON_MIN_RUMBLE_HIGH_FREQ,
889                                      JOYCON_MAX_RUMBLE_HIGH_FREQ);
890         ctlr->rumble_rl_freq = clamp(ctlr->rumble_rl_freq,
891                                      JOYCON_MIN_RUMBLE_LOW_FREQ,
892                                      JOYCON_MAX_RUMBLE_LOW_FREQ);
893         ctlr->rumble_rh_freq = clamp(ctlr->rumble_rh_freq,
894                                      JOYCON_MIN_RUMBLE_HIGH_FREQ,
895                                      JOYCON_MAX_RUMBLE_HIGH_FREQ);
896         spin_unlock_irqrestore(&ctlr->lock, flags);
897 }
898
899 static int joycon_set_rumble(struct joycon_ctlr *ctlr, u16 amp_r, u16 amp_l,
900                              bool schedule_now)
901 {
902         u8 data[JC_RUMBLE_DATA_SIZE];
903         u16 amp;
904         u16 freq_r_low;
905         u16 freq_r_high;
906         u16 freq_l_low;
907         u16 freq_l_high;
908         unsigned long flags;
909
910         spin_lock_irqsave(&ctlr->lock, flags);
911         freq_r_low = ctlr->rumble_rl_freq;
912         freq_r_high = ctlr->rumble_rh_freq;
913         freq_l_low = ctlr->rumble_ll_freq;
914         freq_l_high = ctlr->rumble_lh_freq;
915         spin_unlock_irqrestore(&ctlr->lock, flags);
916
917         /* right joy-con */
918         amp = amp_r * (u32)joycon_max_rumble_amp / 65535;
919         joycon_encode_rumble(data + 4, freq_r_low, freq_r_high, amp);
920
921         /* left joy-con */
922         amp = amp_l * (u32)joycon_max_rumble_amp / 65535;
923         joycon_encode_rumble(data, freq_l_low, freq_l_high, amp);
924
925         spin_lock_irqsave(&ctlr->lock, flags);
926         if (++ctlr->rumble_queue_head >= JC_RUMBLE_QUEUE_SIZE)
927                 ctlr->rumble_queue_head = 0;
928         memcpy(ctlr->rumble_data[ctlr->rumble_queue_head], data,
929                JC_RUMBLE_DATA_SIZE);
930         spin_unlock_irqrestore(&ctlr->lock, flags);
931
932         /* don't wait for the periodic send (reduces latency) */
933         if (schedule_now)
934                 queue_work(ctlr->rumble_queue, &ctlr->rumble_worker);
935
936         return 0;
937 }
938
939 static int joycon_play_effect(struct input_dev *dev, void *data,
940                                                      struct ff_effect *effect)
941 {
942         struct joycon_ctlr *ctlr = input_get_drvdata(dev);
943
944         if (effect->type != FF_RUMBLE)
945                 return 0;
946
947         return joycon_set_rumble(ctlr,
948                                  effect->u.rumble.weak_magnitude,
949                                  effect->u.rumble.strong_magnitude,
950                                  true);
951 }
952 #endif /* IS_ENABLED(CONFIG_NINTENDO_FF) */
953
954 static const unsigned int joycon_button_inputs_l[] = {
955         BTN_SELECT, BTN_Z, BTN_THUMBL,
956         BTN_TL, BTN_TL2,
957         0 /* 0 signals end of array */
958 };
959
960 static const unsigned int joycon_button_inputs_r[] = {
961         BTN_START, BTN_MODE, BTN_THUMBR,
962         BTN_SOUTH, BTN_EAST, BTN_NORTH, BTN_WEST,
963         BTN_TR, BTN_TR2,
964         0 /* 0 signals end of array */
965 };
966
967 /* We report joy-con d-pad inputs as buttons and pro controller as a hat. */
968 static const unsigned int joycon_dpad_inputs_jc[] = {
969         BTN_DPAD_UP, BTN_DPAD_DOWN, BTN_DPAD_LEFT, BTN_DPAD_RIGHT,
970 };
971
972 static int joycon_input_create(struct joycon_ctlr *ctlr)
973 {
974         struct hid_device *hdev;
975         const char *name;
976         int ret;
977         int i;
978
979         hdev = ctlr->hdev;
980
981         switch (hdev->product) {
982         case USB_DEVICE_ID_NINTENDO_PROCON:
983                 name = "Nintendo Switch Pro Controller";
984                 break;
985         case USB_DEVICE_ID_NINTENDO_JOYCONL:
986                 name = "Nintendo Switch Left Joy-Con";
987                 break;
988         case USB_DEVICE_ID_NINTENDO_JOYCONR:
989                 name = "Nintendo Switch Right Joy-Con";
990                 break;
991         default: /* Should be impossible */
992                 hid_err(hdev, "Invalid hid product\n");
993                 return -EINVAL;
994         }
995
996         ctlr->input = devm_input_allocate_device(&hdev->dev);
997         if (!ctlr->input)
998                 return -ENOMEM;
999         ctlr->input->id.bustype = hdev->bus;
1000         ctlr->input->id.vendor = hdev->vendor;
1001         ctlr->input->id.product = hdev->product;
1002         ctlr->input->id.version = hdev->version;
1003         ctlr->input->name = name;
1004         input_set_drvdata(ctlr->input, ctlr);
1005
1006
1007         /* set up sticks and buttons */
1008         if (hdev->product != USB_DEVICE_ID_NINTENDO_JOYCONR) {
1009                 input_set_abs_params(ctlr->input, ABS_X,
1010                                      -JC_MAX_STICK_MAG, JC_MAX_STICK_MAG,
1011                                      JC_STICK_FUZZ, JC_STICK_FLAT);
1012                 input_set_abs_params(ctlr->input, ABS_Y,
1013                                      -JC_MAX_STICK_MAG, JC_MAX_STICK_MAG,
1014                                      JC_STICK_FUZZ, JC_STICK_FLAT);
1015
1016                 for (i = 0; joycon_button_inputs_l[i] > 0; i++)
1017                         input_set_capability(ctlr->input, EV_KEY,
1018                                              joycon_button_inputs_l[i]);
1019
1020                 /* configure d-pad differently for joy-con vs pro controller */
1021                 if (hdev->product != USB_DEVICE_ID_NINTENDO_PROCON) {
1022                         for (i = 0; joycon_dpad_inputs_jc[i] > 0; i++)
1023                                 input_set_capability(ctlr->input, EV_KEY,
1024                                                      joycon_dpad_inputs_jc[i]);
1025                 } else {
1026                         input_set_abs_params(ctlr->input, ABS_HAT0X,
1027                                              -JC_MAX_DPAD_MAG, JC_MAX_DPAD_MAG,
1028                                              JC_DPAD_FUZZ, JC_DPAD_FLAT);
1029                         input_set_abs_params(ctlr->input, ABS_HAT0Y,
1030                                              -JC_MAX_DPAD_MAG, JC_MAX_DPAD_MAG,
1031                                              JC_DPAD_FUZZ, JC_DPAD_FLAT);
1032                 }
1033         }
1034         if (hdev->product != USB_DEVICE_ID_NINTENDO_JOYCONL) {
1035                 input_set_abs_params(ctlr->input, ABS_RX,
1036                                      -JC_MAX_STICK_MAG, JC_MAX_STICK_MAG,
1037                                      JC_STICK_FUZZ, JC_STICK_FLAT);
1038                 input_set_abs_params(ctlr->input, ABS_RY,
1039                                      -JC_MAX_STICK_MAG, JC_MAX_STICK_MAG,
1040                                      JC_STICK_FUZZ, JC_STICK_FLAT);
1041
1042                 for (i = 0; joycon_button_inputs_r[i] > 0; i++)
1043                         input_set_capability(ctlr->input, EV_KEY,
1044                                              joycon_button_inputs_r[i]);
1045         }
1046
1047         /* Let's report joy-con S triggers separately */
1048         if (hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONL) {
1049                 input_set_capability(ctlr->input, EV_KEY, BTN_TR);
1050                 input_set_capability(ctlr->input, EV_KEY, BTN_TR2);
1051         } else if (hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONR) {
1052                 input_set_capability(ctlr->input, EV_KEY, BTN_TL);
1053                 input_set_capability(ctlr->input, EV_KEY, BTN_TL2);
1054         }
1055
1056 #if IS_ENABLED(CONFIG_NINTENDO_FF)
1057         /* set up rumble */
1058         input_set_capability(ctlr->input, EV_FF, FF_RUMBLE);
1059         input_ff_create_memless(ctlr->input, NULL, joycon_play_effect);
1060         ctlr->rumble_ll_freq = JC_RUMBLE_DFLT_LOW_FREQ;
1061         ctlr->rumble_lh_freq = JC_RUMBLE_DFLT_HIGH_FREQ;
1062         ctlr->rumble_rl_freq = JC_RUMBLE_DFLT_LOW_FREQ;
1063         ctlr->rumble_rh_freq = JC_RUMBLE_DFLT_HIGH_FREQ;
1064         joycon_clamp_rumble_freqs(ctlr);
1065         joycon_set_rumble(ctlr, 0, 0, false);
1066         ctlr->rumble_msecs = jiffies_to_msecs(jiffies);
1067 #endif
1068
1069         ret = input_register_device(ctlr->input);
1070         if (ret)
1071                 return ret;
1072
1073         return 0;
1074 }
1075
1076 static int joycon_player_led_brightness_set(struct led_classdev *led,
1077                                             enum led_brightness brightness)
1078 {
1079         struct device *dev = led->dev->parent;
1080         struct hid_device *hdev = to_hid_device(dev);
1081         struct joycon_ctlr *ctlr;
1082         int val = 0;
1083         int i;
1084         int ret;
1085         int num;
1086
1087         ctlr = hid_get_drvdata(hdev);
1088         if (!ctlr) {
1089                 hid_err(hdev, "No controller data\n");
1090                 return -ENODEV;
1091         }
1092
1093         /* determine which player led this is */
1094         for (num = 0; num < JC_NUM_LEDS; num++) {
1095                 if (&ctlr->leds[num] == led)
1096                         break;
1097         }
1098         if (num >= JC_NUM_LEDS)
1099                 return -EINVAL;
1100
1101         mutex_lock(&ctlr->output_mutex);
1102         for (i = 0; i < JC_NUM_LEDS; i++) {
1103                 if (i == num)
1104                         val |= brightness << i;
1105                 else
1106                         val |= ctlr->leds[i].brightness << i;
1107         }
1108         ret = joycon_set_player_leds(ctlr, 0, val);
1109         mutex_unlock(&ctlr->output_mutex);
1110
1111         return ret;
1112 }
1113
1114 static int joycon_home_led_brightness_set(struct led_classdev *led,
1115                                           enum led_brightness brightness)
1116 {
1117         struct device *dev = led->dev->parent;
1118         struct hid_device *hdev = to_hid_device(dev);
1119         struct joycon_ctlr *ctlr;
1120         struct joycon_subcmd_request *req;
1121         u8 buffer[sizeof(*req) + 5] = { 0 };
1122         u8 *data;
1123         int ret;
1124
1125         ctlr = hid_get_drvdata(hdev);
1126         if (!ctlr) {
1127                 hid_err(hdev, "No controller data\n");
1128                 return -ENODEV;
1129         }
1130
1131         req = (struct joycon_subcmd_request *)buffer;
1132         req->subcmd_id = JC_SUBCMD_SET_HOME_LIGHT;
1133         data = req->data;
1134         data[0] = 0x01;
1135         data[1] = brightness << 4;
1136         data[2] = brightness | (brightness << 4);
1137         data[3] = 0x11;
1138         data[4] = 0x11;
1139
1140         hid_dbg(hdev, "setting home led brightness\n");
1141         mutex_lock(&ctlr->output_mutex);
1142         ret = joycon_send_subcmd(ctlr, req, 5, HZ/4);
1143         mutex_unlock(&ctlr->output_mutex);
1144
1145         return ret;
1146 }
1147
1148 static DEFINE_MUTEX(joycon_input_num_mutex);
1149 static int joycon_leds_create(struct joycon_ctlr *ctlr)
1150 {
1151         struct hid_device *hdev = ctlr->hdev;
1152         struct device *dev = &hdev->dev;
1153         const char *d_name = dev_name(dev);
1154         struct led_classdev *led;
1155         char *name;
1156         int ret = 0;
1157         int i;
1158         static int input_num = 1;
1159
1160         /* Set the default controller player leds based on controller number */
1161         mutex_lock(&joycon_input_num_mutex);
1162         mutex_lock(&ctlr->output_mutex);
1163         ret = joycon_set_player_leds(ctlr, 0, 0xF >> (4 - input_num));
1164         if (ret)
1165                 hid_warn(ctlr->hdev, "Failed to set leds; ret=%d\n", ret);
1166         mutex_unlock(&ctlr->output_mutex);
1167
1168         /* configure the player LEDs */
1169         for (i = 0; i < JC_NUM_LEDS; i++) {
1170                 name = devm_kasprintf(dev, GFP_KERNEL, "%s:%s:%s",
1171                                       d_name,
1172                                       "green",
1173                                       joycon_player_led_names[i]);
1174                 if (!name)
1175                         return -ENOMEM;
1176
1177                 led = &ctlr->leds[i];
1178                 led->name = name;
1179                 led->brightness = ((i + 1) <= input_num) ? 1 : 0;
1180                 led->max_brightness = 1;
1181                 led->brightness_set_blocking =
1182                                         joycon_player_led_brightness_set;
1183                 led->flags = LED_CORE_SUSPENDRESUME | LED_HW_PLUGGABLE;
1184
1185                 ret = devm_led_classdev_register(&hdev->dev, led);
1186                 if (ret) {
1187                         hid_err(hdev, "Failed registering %s LED\n", led->name);
1188                         return ret;
1189                 }
1190         }
1191
1192         if (++input_num > 4)
1193                 input_num = 1;
1194         mutex_unlock(&joycon_input_num_mutex);
1195
1196         /* configure the home LED */
1197         if (ctlr->hdev->product != USB_DEVICE_ID_NINTENDO_JOYCONL) {
1198                 name = devm_kasprintf(dev, GFP_KERNEL, "%s:%s:%s",
1199                                       d_name,
1200                                       "blue",
1201                                       LED_FUNCTION_PLAYER5);
1202                 if (!name)
1203                         return -ENOMEM;
1204
1205                 led = &ctlr->home_led;
1206                 led->name = name;
1207                 led->brightness = 0;
1208                 led->max_brightness = 0xF;
1209                 led->brightness_set_blocking = joycon_home_led_brightness_set;
1210                 led->flags = LED_CORE_SUSPENDRESUME | LED_HW_PLUGGABLE;
1211                 ret = devm_led_classdev_register(&hdev->dev, led);
1212                 if (ret) {
1213                         hid_err(hdev, "Failed registering home led\n");
1214                         return ret;
1215                 }
1216                 /* Set the home LED to 0 as default state */
1217                 ret = joycon_home_led_brightness_set(led, 0);
1218                 if (ret) {
1219                         hid_err(hdev, "Failed to set home LED dflt; ret=%d\n",
1220                                                                         ret);
1221                         return ret;
1222                 }
1223         }
1224
1225         return 0;
1226 }
1227
1228 static int joycon_battery_get_property(struct power_supply *supply,
1229                                        enum power_supply_property prop,
1230                                        union power_supply_propval *val)
1231 {
1232         struct joycon_ctlr *ctlr = power_supply_get_drvdata(supply);
1233         unsigned long flags;
1234         int ret = 0;
1235         u8 capacity;
1236         bool charging;
1237         bool powered;
1238
1239         spin_lock_irqsave(&ctlr->lock, flags);
1240         capacity = ctlr->battery_capacity;
1241         charging = ctlr->battery_charging;
1242         powered = ctlr->host_powered;
1243         spin_unlock_irqrestore(&ctlr->lock, flags);
1244
1245         switch (prop) {
1246         case POWER_SUPPLY_PROP_PRESENT:
1247                 val->intval = 1;
1248                 break;
1249         case POWER_SUPPLY_PROP_SCOPE:
1250                 val->intval = POWER_SUPPLY_SCOPE_DEVICE;
1251                 break;
1252         case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
1253                 val->intval = capacity;
1254                 break;
1255         case POWER_SUPPLY_PROP_STATUS:
1256                 if (charging)
1257                         val->intval = POWER_SUPPLY_STATUS_CHARGING;
1258                 else if (capacity == POWER_SUPPLY_CAPACITY_LEVEL_FULL &&
1259                          powered)
1260                         val->intval = POWER_SUPPLY_STATUS_FULL;
1261                 else
1262                         val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
1263                 break;
1264         default:
1265                 ret = -EINVAL;
1266                 break;
1267         }
1268         return ret;
1269 }
1270
1271 static enum power_supply_property joycon_battery_props[] = {
1272         POWER_SUPPLY_PROP_PRESENT,
1273         POWER_SUPPLY_PROP_CAPACITY_LEVEL,
1274         POWER_SUPPLY_PROP_SCOPE,
1275         POWER_SUPPLY_PROP_STATUS,
1276 };
1277
1278 static int joycon_power_supply_create(struct joycon_ctlr *ctlr)
1279 {
1280         struct hid_device *hdev = ctlr->hdev;
1281         struct power_supply_config supply_config = { .drv_data = ctlr, };
1282         const char * const name_fmt = "nintendo_switch_controller_battery_%s";
1283         int ret = 0;
1284
1285         /* Set initially to unknown before receiving first input report */
1286         ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
1287
1288         /* Configure the battery's description */
1289         ctlr->battery_desc.properties = joycon_battery_props;
1290         ctlr->battery_desc.num_properties =
1291                                         ARRAY_SIZE(joycon_battery_props);
1292         ctlr->battery_desc.get_property = joycon_battery_get_property;
1293         ctlr->battery_desc.type = POWER_SUPPLY_TYPE_BATTERY;
1294         ctlr->battery_desc.use_for_apm = 0;
1295         ctlr->battery_desc.name = devm_kasprintf(&hdev->dev, GFP_KERNEL,
1296                                                  name_fmt,
1297                                                  dev_name(&hdev->dev));
1298         if (!ctlr->battery_desc.name)
1299                 return -ENOMEM;
1300
1301         ctlr->battery = devm_power_supply_register(&hdev->dev,
1302                                                    &ctlr->battery_desc,
1303                                                    &supply_config);
1304         if (IS_ERR(ctlr->battery)) {
1305                 ret = PTR_ERR(ctlr->battery);
1306                 hid_err(hdev, "Failed to register battery; ret=%d\n", ret);
1307                 return ret;
1308         }
1309
1310         return power_supply_powers(ctlr->battery, &hdev->dev);
1311 }
1312
1313 /* Common handler for parsing inputs */
1314 static int joycon_ctlr_read_handler(struct joycon_ctlr *ctlr, u8 *data,
1315                                                               int size)
1316 {
1317         if (data[0] == JC_INPUT_SUBCMD_REPLY || data[0] == JC_INPUT_IMU_DATA ||
1318             data[0] == JC_INPUT_MCU_DATA) {
1319                 if (size >= 12) /* make sure it contains the input report */
1320                         joycon_parse_report(ctlr,
1321                                             (struct joycon_input_report *)data);
1322         }
1323
1324         return 0;
1325 }
1326
1327 static int joycon_ctlr_handle_event(struct joycon_ctlr *ctlr, u8 *data,
1328                                                               int size)
1329 {
1330         int ret = 0;
1331         bool match = false;
1332         struct joycon_input_report *report;
1333
1334         if (unlikely(mutex_is_locked(&ctlr->output_mutex)) &&
1335             ctlr->msg_type != JOYCON_MSG_TYPE_NONE) {
1336                 switch (ctlr->msg_type) {
1337                 case JOYCON_MSG_TYPE_USB:
1338                         if (size < 2)
1339                                 break;
1340                         if (data[0] == JC_INPUT_USB_RESPONSE &&
1341                             data[1] == ctlr->usb_ack_match)
1342                                 match = true;
1343                         break;
1344                 case JOYCON_MSG_TYPE_SUBCMD:
1345                         if (size < sizeof(struct joycon_input_report) ||
1346                             data[0] != JC_INPUT_SUBCMD_REPLY)
1347                                 break;
1348                         report = (struct joycon_input_report *)data;
1349                         if (report->reply.id == ctlr->subcmd_ack_match)
1350                                 match = true;
1351                         break;
1352                 default:
1353                         break;
1354                 }
1355
1356                 if (match) {
1357                         memcpy(ctlr->input_buf, data,
1358                                min(size, (int)JC_MAX_RESP_SIZE));
1359                         ctlr->msg_type = JOYCON_MSG_TYPE_NONE;
1360                         ctlr->received_resp = true;
1361                         wake_up(&ctlr->wait);
1362
1363                         /* This message has been handled */
1364                         return 1;
1365                 }
1366         }
1367
1368         if (ctlr->ctlr_state == JOYCON_CTLR_STATE_READ)
1369                 ret = joycon_ctlr_read_handler(ctlr, data, size);
1370
1371         return ret;
1372 }
1373
1374 static int nintendo_hid_event(struct hid_device *hdev,
1375                               struct hid_report *report, u8 *raw_data, int size)
1376 {
1377         struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
1378
1379         if (size < 1)
1380                 return -EINVAL;
1381
1382         return joycon_ctlr_handle_event(ctlr, raw_data, size);
1383 }
1384
1385 static int nintendo_hid_probe(struct hid_device *hdev,
1386                             const struct hid_device_id *id)
1387 {
1388         int ret;
1389         struct joycon_ctlr *ctlr;
1390
1391         hid_dbg(hdev, "probe - start\n");
1392
1393         ctlr = devm_kzalloc(&hdev->dev, sizeof(*ctlr), GFP_KERNEL);
1394         if (!ctlr) {
1395                 ret = -ENOMEM;
1396                 goto err;
1397         }
1398
1399         ctlr->hdev = hdev;
1400         ctlr->ctlr_state = JOYCON_CTLR_STATE_INIT;
1401         ctlr->rumble_queue_head = JC_RUMBLE_QUEUE_SIZE - 1;
1402         ctlr->rumble_queue_tail = 0;
1403         hid_set_drvdata(hdev, ctlr);
1404         mutex_init(&ctlr->output_mutex);
1405         init_waitqueue_head(&ctlr->wait);
1406         spin_lock_init(&ctlr->lock);
1407         ctlr->rumble_queue = alloc_workqueue("hid-nintendo-rumble_wq",
1408                                              WQ_FREEZABLE | WQ_MEM_RECLAIM, 0);
1409         INIT_WORK(&ctlr->rumble_worker, joycon_rumble_worker);
1410
1411         ret = hid_parse(hdev);
1412         if (ret) {
1413                 hid_err(hdev, "HID parse failed\n");
1414                 goto err_wq;
1415         }
1416
1417         /*
1418          * Patch the hw version of pro controller/joycons, so applications can
1419          * distinguish between the default HID mappings and the mappings defined
1420          * by the Linux game controller spec. This is important for the SDL2
1421          * library, which has a game controller database, which uses device ids
1422          * in combination with version as a key.
1423          */
1424         hdev->version |= 0x8000;
1425
1426         ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
1427         if (ret) {
1428                 hid_err(hdev, "HW start failed\n");
1429                 goto err_wq;
1430         }
1431
1432         ret = hid_hw_open(hdev);
1433         if (ret) {
1434                 hid_err(hdev, "cannot start hardware I/O\n");
1435                 goto err_stop;
1436         }
1437
1438         hid_device_io_start(hdev);
1439
1440         /* Initialize the controller */
1441         mutex_lock(&ctlr->output_mutex);
1442         /* if handshake command fails, assume ble pro controller */
1443         if (hdev->product == USB_DEVICE_ID_NINTENDO_PROCON &&
1444             !joycon_send_usb(ctlr, JC_USB_CMD_HANDSHAKE, HZ)) {
1445                 hid_dbg(hdev, "detected USB controller\n");
1446                 /* set baudrate for improved latency */
1447                 ret = joycon_send_usb(ctlr, JC_USB_CMD_BAUDRATE_3M, HZ);
1448                 if (ret) {
1449                         hid_err(hdev, "Failed to set baudrate; ret=%d\n", ret);
1450                         goto err_mutex;
1451                 }
1452                 /* handshake */
1453                 ret = joycon_send_usb(ctlr, JC_USB_CMD_HANDSHAKE, HZ);
1454                 if (ret) {
1455                         hid_err(hdev, "Failed handshake; ret=%d\n", ret);
1456                         goto err_mutex;
1457                 }
1458                 /*
1459                  * Set no timeout (to keep controller in USB mode).
1460                  * This doesn't send a response, so ignore the timeout.
1461                  */
1462                 joycon_send_usb(ctlr, JC_USB_CMD_NO_TIMEOUT, HZ/10);
1463         }
1464
1465         /* get controller calibration data, and parse it */
1466         ret = joycon_request_calibration(ctlr);
1467         if (ret) {
1468                 /*
1469                  * We can function with default calibration, but it may be
1470                  * inaccurate. Provide a warning, and continue on.
1471                  */
1472                 hid_warn(hdev, "Analog stick positions may be inaccurate\n");
1473         }
1474
1475         /* Set the reporting mode to 0x30, which is the full report mode */
1476         ret = joycon_set_report_mode(ctlr);
1477         if (ret) {
1478                 hid_err(hdev, "Failed to set report mode; ret=%d\n", ret);
1479                 goto err_mutex;
1480         }
1481
1482         /* Enable rumble */
1483         ret = joycon_enable_rumble(ctlr);
1484         if (ret) {
1485                 hid_err(hdev, "Failed to enable rumble; ret=%d\n", ret);
1486                 goto err_mutex;
1487         }
1488
1489         mutex_unlock(&ctlr->output_mutex);
1490
1491         /* Initialize the leds */
1492         ret = joycon_leds_create(ctlr);
1493         if (ret) {
1494                 hid_err(hdev, "Failed to create leds; ret=%d\n", ret);
1495                 goto err_close;
1496         }
1497
1498         /* Initialize the battery power supply */
1499         ret = joycon_power_supply_create(ctlr);
1500         if (ret) {
1501                 hid_err(hdev, "Failed to create power_supply; ret=%d\n", ret);
1502                 goto err_close;
1503         }
1504
1505         ret = joycon_input_create(ctlr);
1506         if (ret) {
1507                 hid_err(hdev, "Failed to create input device; ret=%d\n", ret);
1508                 goto err_close;
1509         }
1510
1511         ctlr->ctlr_state = JOYCON_CTLR_STATE_READ;
1512
1513         hid_dbg(hdev, "probe - success\n");
1514         return 0;
1515
1516 err_mutex:
1517         mutex_unlock(&ctlr->output_mutex);
1518 err_close:
1519         hid_hw_close(hdev);
1520 err_stop:
1521         hid_hw_stop(hdev);
1522 err_wq:
1523         destroy_workqueue(ctlr->rumble_queue);
1524 err:
1525         hid_err(hdev, "probe - fail = %d\n", ret);
1526         return ret;
1527 }
1528
1529 static void nintendo_hid_remove(struct hid_device *hdev)
1530 {
1531         struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
1532
1533         hid_dbg(hdev, "remove\n");
1534         destroy_workqueue(ctlr->rumble_queue);
1535         hid_hw_close(hdev);
1536         hid_hw_stop(hdev);
1537 }
1538
1539 static const struct hid_device_id nintendo_hid_devices[] = {
1540         { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
1541                          USB_DEVICE_ID_NINTENDO_PROCON) },
1542         { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
1543                          USB_DEVICE_ID_NINTENDO_PROCON) },
1544         { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
1545                          USB_DEVICE_ID_NINTENDO_JOYCONL) },
1546         { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
1547                          USB_DEVICE_ID_NINTENDO_JOYCONR) },
1548         { }
1549 };
1550 MODULE_DEVICE_TABLE(hid, nintendo_hid_devices);
1551
1552 static struct hid_driver nintendo_hid_driver = {
1553         .name           = "nintendo",
1554         .id_table       = nintendo_hid_devices,
1555         .probe          = nintendo_hid_probe,
1556         .remove         = nintendo_hid_remove,
1557         .raw_event      = nintendo_hid_event,
1558 };
1559 module_hid_driver(nintendo_hid_driver);
1560
1561 MODULE_LICENSE("GPL");
1562 MODULE_AUTHOR("Daniel J. Ogorchock <djogorchock@gmail.com>");
1563 MODULE_DESCRIPTION("Driver for Nintendo Switch Controllers");