• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  *   hid-wiimote kernel hid driver
13  *   hid-logitech-hidpp driver
14  *
15  * This driver supports the Nintendo Switch Joy-Cons and Pro Controllers. The
16  * Pro Controllers can either be used over USB or Bluetooth.
17  *
18  * The driver will retrieve the factory calibration info from the controllers,
19  * so little to no user calibration should be required.
20  *
21  */
22 
23 #include "hid-ids.h"
24 #include <linux/delay.h>
25 #include <linux/device.h>
26 #include <linux/hid.h>
27 #include <linux/input.h>
28 #include <linux/module.h>
29 #include <linux/spinlock.h>
30 
31 /*
32  * Reference the url below for the following HID report defines:
33  * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering
34  */
35 
36 /* Output Reports */
37 static const u8 JC_OUTPUT_RUMBLE_AND_SUBCMD	= 0x01;
38 static const u8 JC_OUTPUT_FW_UPDATE_PKT		= 0x03;
39 static const u8 JC_OUTPUT_RUMBLE_ONLY		= 0x10;
40 static const u8 JC_OUTPUT_MCU_DATA		= 0x11;
41 static const u8 JC_OUTPUT_USB_CMD		= 0x80;
42 
43 /* Subcommand IDs */
44 static const u8 JC_SUBCMD_STATE			/*= 0x00*/;
45 static const u8 JC_SUBCMD_MANUAL_BT_PAIRING	= 0x01;
46 static const u8 JC_SUBCMD_REQ_DEV_INFO		= 0x02;
47 static const u8 JC_SUBCMD_SET_REPORT_MODE	= 0x03;
48 static const u8 JC_SUBCMD_TRIGGERS_ELAPSED	= 0x04;
49 static const u8 JC_SUBCMD_GET_PAGE_LIST_STATE	= 0x05;
50 static const u8 JC_SUBCMD_SET_HCI_STATE		= 0x06;
51 static const u8 JC_SUBCMD_RESET_PAIRING_INFO	= 0x07;
52 static const u8 JC_SUBCMD_LOW_POWER_MODE	= 0x08;
53 static const u8 JC_SUBCMD_SPI_FLASH_READ	= 0x10;
54 static const u8 JC_SUBCMD_SPI_FLASH_WRITE	= 0x11;
55 static const u8 JC_SUBCMD_RESET_MCU		= 0x20;
56 static const u8 JC_SUBCMD_SET_MCU_CONFIG	= 0x21;
57 static const u8 JC_SUBCMD_SET_MCU_STATE		= 0x22;
58 static const u8 JC_SUBCMD_SET_PLAYER_LIGHTS	= 0x30;
59 static const u8 JC_SUBCMD_GET_PLAYER_LIGHTS	= 0x31;
60 static const u8 JC_SUBCMD_SET_HOME_LIGHT	= 0x38;
61 static const u8 JC_SUBCMD_ENABLE_IMU		= 0x40;
62 static const u8 JC_SUBCMD_SET_IMU_SENSITIVITY	= 0x41;
63 static const u8 JC_SUBCMD_WRITE_IMU_REG		= 0x42;
64 static const u8 JC_SUBCMD_READ_IMU_REG		= 0x43;
65 static const u8 JC_SUBCMD_ENABLE_VIBRATION	= 0x48;
66 static const u8 JC_SUBCMD_GET_REGULATED_VOLTAGE	= 0x50;
67 
68 /* Input Reports */
69 static const u8 JC_INPUT_BUTTON_EVENT		= 0x3F;
70 static const u8 JC_INPUT_SUBCMD_REPLY		= 0x21;
71 static const u8 JC_INPUT_IMU_DATA		= 0x30;
72 static const u8 JC_INPUT_MCU_DATA		= 0x31;
73 static const u8 JC_INPUT_USB_RESPONSE		= 0x81;
74 
75 /* Feature Reports */
76 static const u8 JC_FEATURE_LAST_SUBCMD		= 0x02;
77 static const u8 JC_FEATURE_OTA_FW_UPGRADE	= 0x70;
78 static const u8 JC_FEATURE_SETUP_MEM_READ	= 0x71;
79 static const u8 JC_FEATURE_MEM_READ		= 0x72;
80 static const u8 JC_FEATURE_ERASE_MEM_SECTOR	= 0x73;
81 static const u8 JC_FEATURE_MEM_WRITE		= 0x74;
82 static const u8 JC_FEATURE_LAUNCH		= 0x75;
83 
84 /* USB Commands */
85 static const u8 JC_USB_CMD_CONN_STATUS		= 0x01;
86 static const u8 JC_USB_CMD_HANDSHAKE		= 0x02;
87 static const u8 JC_USB_CMD_BAUDRATE_3M		= 0x03;
88 static const u8 JC_USB_CMD_NO_TIMEOUT		= 0x04;
89 static const u8 JC_USB_CMD_EN_TIMEOUT		= 0x05;
90 static const u8 JC_USB_RESET			= 0x06;
91 static const u8 JC_USB_PRE_HANDSHAKE		= 0x91;
92 static const u8 JC_USB_SEND_UART		= 0x92;
93 
94 /* SPI storage addresses of factory calibration data */
95 static const u16 JC_CAL_DATA_START		= 0x603d;
96 static const u16 JC_CAL_DATA_END		= 0x604e;
97 #define JC_CAL_DATA_SIZE	(JC_CAL_DATA_END - JC_CAL_DATA_START + 1)
98 
99 
100 /* The raw analog joystick values will be mapped in terms of this magnitude */
101 static const u16 JC_MAX_STICK_MAG		= 32767;
102 static const u16 JC_STICK_FUZZ			= 250;
103 static const u16 JC_STICK_FLAT			= 500;
104 
105 /* States for controller state machine */
106 enum joycon_ctlr_state {
107 	JOYCON_CTLR_STATE_INIT,
108 	JOYCON_CTLR_STATE_READ,
109 };
110 
111 struct joycon_stick_cal {
112 	s32 max;
113 	s32 min;
114 	s32 center;
115 };
116 
117 /*
118  * All the controller's button values are stored in a u32.
119  * They can be accessed with bitwise ANDs.
120  */
121 static const u32 JC_BTN_Y	= BIT(0);
122 static const u32 JC_BTN_X	= BIT(1);
123 static const u32 JC_BTN_B	= BIT(2);
124 static const u32 JC_BTN_A	= BIT(3);
125 static const u32 JC_BTN_SR_R	= BIT(4);
126 static const u32 JC_BTN_SL_R	= BIT(5);
127 static const u32 JC_BTN_R	= BIT(6);
128 static const u32 JC_BTN_ZR	= BIT(7);
129 static const u32 JC_BTN_MINUS	= BIT(8);
130 static const u32 JC_BTN_PLUS	= BIT(9);
131 static const u32 JC_BTN_RSTICK	= BIT(10);
132 static const u32 JC_BTN_LSTICK	= BIT(11);
133 static const u32 JC_BTN_HOME	= BIT(12);
134 static const u32 JC_BTN_CAP	= BIT(13); /* capture button */
135 static const u32 JC_BTN_DOWN	= BIT(16);
136 static const u32 JC_BTN_UP	= BIT(17);
137 static const u32 JC_BTN_RIGHT	= BIT(18);
138 static const u32 JC_BTN_LEFT	= BIT(19);
139 static const u32 JC_BTN_SR_L	= BIT(20);
140 static const u32 JC_BTN_SL_L	= BIT(21);
141 static const u32 JC_BTN_L	= BIT(22);
142 static const u32 JC_BTN_ZL	= BIT(23);
143 
144 enum joycon_msg_type {
145 	JOYCON_MSG_TYPE_NONE,
146 	JOYCON_MSG_TYPE_USB,
147 	JOYCON_MSG_TYPE_SUBCMD,
148 };
149 
150 struct joycon_subcmd_request {
151 	u8 output_id; /* must be 0x01 for subcommand, 0x10 for rumble only */
152 	u8 packet_num; /* incremented every send */
153 	u8 rumble_data[8];
154 	u8 subcmd_id;
155 	u8 data[0]; /* length depends on the subcommand */
156 } __packed;
157 
158 struct joycon_subcmd_reply {
159 	u8 ack; /* MSB 1 for ACK, 0 for NACK */
160 	u8 id; /* id of requested subcmd */
161 	u8 data[0]; /* will be at most 35 bytes */
162 } __packed;
163 
164 struct joycon_input_report {
165 	u8 id;
166 	u8 timer;
167 	u8 bat_con; /* battery and connection info */
168 	u8 button_status[3];
169 	u8 left_stick[3];
170 	u8 right_stick[3];
171 	u8 vibrator_report;
172 
173 	/*
174 	 * If support for firmware updates, gyroscope data, and/or NFC/IR
175 	 * are added in the future, this can be swapped for a union.
176 	 */
177 	struct joycon_subcmd_reply reply;
178 } __packed;
179 
180 #define JC_MAX_RESP_SIZE	(sizeof(struct joycon_input_report) + 35)
181 
182 /* Each physical controller is associated with a joycon_ctlr struct */
183 struct joycon_ctlr {
184 	struct hid_device *hdev;
185 	struct input_dev *input;
186 	enum joycon_ctlr_state ctlr_state;
187 
188 	/* The following members are used for synchronous sends/receives */
189 	enum joycon_msg_type msg_type;
190 	u8 subcmd_num;
191 	struct mutex output_mutex;
192 	u8 input_buf[JC_MAX_RESP_SIZE];
193 	wait_queue_head_t wait;
194 	bool received_resp;
195 	u8 usb_ack_match;
196 	u8 subcmd_ack_match;
197 
198 	/* factory calibration data */
199 	struct joycon_stick_cal left_stick_cal_x;
200 	struct joycon_stick_cal left_stick_cal_y;
201 	struct joycon_stick_cal right_stick_cal_x;
202 	struct joycon_stick_cal right_stick_cal_y;
203 
204 };
205 
__joycon_hid_send(struct hid_device * hdev,u8 * data,size_t len)206 static int __joycon_hid_send(struct hid_device *hdev, u8 *data, size_t len)
207 {
208 	u8 *buf;
209 	int ret;
210 
211 	buf = kmemdup(data, len, GFP_KERNEL);
212 	if (!buf)
213 		return -ENOMEM;
214 	ret = hid_hw_output_report(hdev, buf, len);
215 	kfree(buf);
216 	if (ret < 0)
217 		hid_dbg(hdev, "Failed to send output report ret=%d\n", ret);
218 	return ret;
219 }
220 
joycon_hid_send_sync(struct joycon_ctlr * ctlr,u8 * data,size_t len)221 static int joycon_hid_send_sync(struct joycon_ctlr *ctlr, u8 *data, size_t len)
222 {
223 	int ret;
224 
225 	ret = __joycon_hid_send(ctlr->hdev, data, len);
226 	if (ret < 0) {
227 		memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE);
228 		return ret;
229 	}
230 
231 	if (!wait_event_timeout(ctlr->wait, ctlr->received_resp, HZ)) {
232 		hid_dbg(ctlr->hdev, "synchronous send/receive timed out\n");
233 		memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE);
234 		return -ETIMEDOUT;
235 	}
236 
237 	ctlr->received_resp = false;
238 	return 0;
239 }
240 
joycon_send_usb(struct joycon_ctlr * ctlr,u8 cmd)241 static int joycon_send_usb(struct joycon_ctlr *ctlr, u8 cmd)
242 {
243 	int ret;
244 	u8 buf[2] = {JC_OUTPUT_USB_CMD};
245 
246 	buf[1] = cmd;
247 	ctlr->usb_ack_match = cmd;
248 	ctlr->msg_type = JOYCON_MSG_TYPE_USB;
249 	ret = joycon_hid_send_sync(ctlr, buf, sizeof(buf));
250 	if (ret)
251 		hid_dbg(ctlr->hdev, "send usb command failed; ret=%d\n", ret);
252 	return ret;
253 }
254 
joycon_send_subcmd(struct joycon_ctlr * ctlr,struct joycon_subcmd_request * subcmd,size_t data_len)255 static int joycon_send_subcmd(struct joycon_ctlr *ctlr,
256 			      struct joycon_subcmd_request *subcmd,
257 			      size_t data_len)
258 {
259 	int ret;
260 
261 	subcmd->output_id = JC_OUTPUT_RUMBLE_AND_SUBCMD;
262 	subcmd->packet_num = ctlr->subcmd_num;
263 	if (++ctlr->subcmd_num > 0xF)
264 		ctlr->subcmd_num = 0;
265 	ctlr->subcmd_ack_match = subcmd->subcmd_id;
266 	ctlr->msg_type = JOYCON_MSG_TYPE_SUBCMD;
267 
268 	ret = joycon_hid_send_sync(ctlr, (u8 *)subcmd,
269 				   sizeof(*subcmd) + data_len);
270 	if (ret < 0)
271 		hid_dbg(ctlr->hdev, "send subcommand failed; ret=%d\n", ret);
272 	else
273 		ret = 0;
274 	return ret;
275 }
276 
277 /* Supply nibbles for flash and on. Ones correspond to active */
joycon_set_player_leds(struct joycon_ctlr * ctlr,u8 flash,u8 on)278 static int joycon_set_player_leds(struct joycon_ctlr *ctlr, u8 flash, u8 on)
279 {
280 	struct joycon_subcmd_request *req;
281 	u8 buffer[sizeof(*req) + 1] = { 0 };
282 
283 	req = (struct joycon_subcmd_request *)buffer;
284 	req->subcmd_id = JC_SUBCMD_SET_PLAYER_LIGHTS;
285 	req->data[0] = (flash << 4) | on;
286 
287 	hid_dbg(ctlr->hdev, "setting player leds\n");
288 	return joycon_send_subcmd(ctlr, req, 1);
289 }
290 
291 static const u16 DFLT_STICK_CAL_CEN = 2000;
292 static const u16 DFLT_STICK_CAL_MAX = 3500;
293 static const u16 DFLT_STICK_CAL_MIN = 500;
joycon_request_calibration(struct joycon_ctlr * ctlr)294 static int joycon_request_calibration(struct joycon_ctlr *ctlr)
295 {
296 	struct joycon_subcmd_request *req;
297 	u8 buffer[sizeof(*req) + 5] = { 0 };
298 	struct joycon_input_report *report;
299 	struct joycon_stick_cal *cal_x;
300 	struct joycon_stick_cal *cal_y;
301 	s32 x_max_above;
302 	s32 x_min_below;
303 	s32 y_max_above;
304 	s32 y_min_below;
305 	u8 *data;
306 	u8 *raw_cal;
307 	int ret;
308 
309 	req = (struct joycon_subcmd_request *)buffer;
310 	req->subcmd_id = JC_SUBCMD_SPI_FLASH_READ;
311 	data = req->data;
312 	data[0] = 0xFF & JC_CAL_DATA_START;
313 	data[1] = 0xFF & (JC_CAL_DATA_START >> 8);
314 	data[2] = 0xFF & (JC_CAL_DATA_START >> 16);
315 	data[3] = 0xFF & (JC_CAL_DATA_START >> 24);
316 	data[4] = JC_CAL_DATA_SIZE;
317 
318 	hid_dbg(ctlr->hdev, "requesting cal data\n");
319 	ret = joycon_send_subcmd(ctlr, req, 5);
320 	if (ret) {
321 		hid_warn(ctlr->hdev,
322 			 "Failed to read stick cal, using defaults; ret=%d\n",
323 			 ret);
324 
325 		ctlr->left_stick_cal_x.center = DFLT_STICK_CAL_CEN;
326 		ctlr->left_stick_cal_x.max = DFLT_STICK_CAL_MAX;
327 		ctlr->left_stick_cal_x.min = DFLT_STICK_CAL_MIN;
328 
329 		ctlr->left_stick_cal_y.center = DFLT_STICK_CAL_CEN;
330 		ctlr->left_stick_cal_y.max = DFLT_STICK_CAL_MAX;
331 		ctlr->left_stick_cal_y.min = DFLT_STICK_CAL_MIN;
332 
333 		ctlr->right_stick_cal_x.center = DFLT_STICK_CAL_CEN;
334 		ctlr->right_stick_cal_x.max = DFLT_STICK_CAL_MAX;
335 		ctlr->right_stick_cal_x.min = DFLT_STICK_CAL_MIN;
336 
337 		ctlr->right_stick_cal_y.center = DFLT_STICK_CAL_CEN;
338 		ctlr->right_stick_cal_y.max = DFLT_STICK_CAL_MAX;
339 		ctlr->right_stick_cal_y.min = DFLT_STICK_CAL_MIN;
340 
341 		return ret;
342 	}
343 
344 	report = (struct joycon_input_report *)ctlr->input_buf;
345 	raw_cal = &report->reply.data[5];
346 
347 	/* left stick calibration parsing */
348 	cal_x = &ctlr->left_stick_cal_x;
349 	cal_y = &ctlr->left_stick_cal_y;
350 
351 	x_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 0), 0, 12);
352 	y_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 1), 4, 12);
353 	cal_x->center = hid_field_extract(ctlr->hdev, (raw_cal + 3), 0, 12);
354 	cal_y->center = hid_field_extract(ctlr->hdev, (raw_cal + 4), 4, 12);
355 	x_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 6), 0, 12);
356 	y_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 7), 4, 12);
357 	cal_x->max = cal_x->center + x_max_above;
358 	cal_x->min = cal_x->center - x_min_below;
359 	cal_y->max = cal_y->center + y_max_above;
360 	cal_y->min = cal_y->center - y_min_below;
361 
362 	/* right stick calibration parsing */
363 	raw_cal += 9;
364 	cal_x = &ctlr->right_stick_cal_x;
365 	cal_y = &ctlr->right_stick_cal_y;
366 
367 	cal_x->center = hid_field_extract(ctlr->hdev, (raw_cal + 0), 0, 12);
368 	cal_y->center = hid_field_extract(ctlr->hdev, (raw_cal + 1), 4, 12);
369 	x_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 3), 0, 12);
370 	y_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 4), 4, 12);
371 	x_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 6), 0, 12);
372 	y_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 7), 4, 12);
373 	cal_x->max = cal_x->center + x_max_above;
374 	cal_x->min = cal_x->center - x_min_below;
375 	cal_y->max = cal_y->center + y_max_above;
376 	cal_y->min = cal_y->center - y_min_below;
377 
378 	hid_dbg(ctlr->hdev, "calibration:\n"
379 			    "l_x_c=%d l_x_max=%d l_x_min=%d\n"
380 			    "l_y_c=%d l_y_max=%d l_y_min=%d\n"
381 			    "r_x_c=%d r_x_max=%d r_x_min=%d\n"
382 			    "r_y_c=%d r_y_max=%d r_y_min=%d\n",
383 			    ctlr->left_stick_cal_x.center,
384 			    ctlr->left_stick_cal_x.max,
385 			    ctlr->left_stick_cal_x.min,
386 			    ctlr->left_stick_cal_y.center,
387 			    ctlr->left_stick_cal_y.max,
388 			    ctlr->left_stick_cal_y.min,
389 			    ctlr->right_stick_cal_x.center,
390 			    ctlr->right_stick_cal_x.max,
391 			    ctlr->right_stick_cal_x.min,
392 			    ctlr->right_stick_cal_y.center,
393 			    ctlr->right_stick_cal_y.max,
394 			    ctlr->right_stick_cal_y.min);
395 
396 	return 0;
397 }
398 
joycon_set_report_mode(struct joycon_ctlr * ctlr)399 static int joycon_set_report_mode(struct joycon_ctlr *ctlr)
400 {
401 	struct joycon_subcmd_request *req;
402 	u8 buffer[sizeof(*req) + 1] = { 0 };
403 
404 	req = (struct joycon_subcmd_request *)buffer;
405 	req->subcmd_id = JC_SUBCMD_SET_REPORT_MODE;
406 	req->data[0] = 0x30; /* standard, full report mode */
407 
408 	hid_dbg(ctlr->hdev, "setting controller report mode\n");
409 	return joycon_send_subcmd(ctlr, req, 1);
410 }
411 
joycon_map_stick_val(struct joycon_stick_cal * cal,s32 val)412 static s32 joycon_map_stick_val(struct joycon_stick_cal *cal, s32 val)
413 {
414 	s32 center = cal->center;
415 	s32 min = cal->min;
416 	s32 max = cal->max;
417 	s32 new_val;
418 
419 	if (val > center) {
420 		new_val = (val - center) * JC_MAX_STICK_MAG;
421 		new_val /= (max - center);
422 	} else {
423 		new_val = (center - val) * -JC_MAX_STICK_MAG;
424 		new_val /= (center - min);
425 	}
426 	new_val = clamp(new_val, (s32)-JC_MAX_STICK_MAG, (s32)JC_MAX_STICK_MAG);
427 	return new_val;
428 }
429 
joycon_parse_report(struct joycon_ctlr * ctlr,struct joycon_input_report * rep)430 static void joycon_parse_report(struct joycon_ctlr *ctlr,
431 				struct joycon_input_report *rep)
432 {
433 	struct input_dev *dev = ctlr->input;
434 	u32 btns;
435 	u32 id = ctlr->hdev->product;
436 
437 	btns = hid_field_extract(ctlr->hdev, rep->button_status, 0, 24);
438 
439 	if (id != USB_DEVICE_ID_NINTENDO_JOYCONR) {
440 		u16 raw_x;
441 		u16 raw_y;
442 		s32 x;
443 		s32 y;
444 
445 		/* get raw stick values */
446 		raw_x = hid_field_extract(ctlr->hdev, rep->left_stick, 0, 12);
447 		raw_y = hid_field_extract(ctlr->hdev,
448 					  rep->left_stick + 1, 4, 12);
449 		/* map the stick values */
450 		x = joycon_map_stick_val(&ctlr->left_stick_cal_x, raw_x);
451 		y = -joycon_map_stick_val(&ctlr->left_stick_cal_y, raw_y);
452 		/* report sticks */
453 		input_report_abs(dev, ABS_X, x);
454 		input_report_abs(dev, ABS_Y, y);
455 
456 		/* report buttons */
457 		input_report_key(dev, BTN_TL, btns & JC_BTN_L);
458 		input_report_key(dev, BTN_TL2, btns & JC_BTN_ZL);
459 		if (id != USB_DEVICE_ID_NINTENDO_PROCON) {
460 			/* Report the S buttons as the non-existent triggers */
461 			input_report_key(dev, BTN_TR, btns & JC_BTN_SL_L);
462 			input_report_key(dev, BTN_TR2, btns & JC_BTN_SR_L);
463 		}
464 		input_report_key(dev, BTN_SELECT, btns & JC_BTN_MINUS);
465 		input_report_key(dev, BTN_THUMBL, btns & JC_BTN_LSTICK);
466 		input_report_key(dev, BTN_Z, btns & JC_BTN_CAP);
467 		input_report_key(dev, BTN_DPAD_DOWN, btns & JC_BTN_DOWN);
468 		input_report_key(dev, BTN_DPAD_UP, btns & JC_BTN_UP);
469 		input_report_key(dev, BTN_DPAD_RIGHT, btns & JC_BTN_RIGHT);
470 		input_report_key(dev, BTN_DPAD_LEFT, btns & JC_BTN_LEFT);
471 	}
472 	if (id != USB_DEVICE_ID_NINTENDO_JOYCONL) {
473 		u16 raw_x;
474 		u16 raw_y;
475 		s32 x;
476 		s32 y;
477 
478 		/* get raw stick values */
479 		raw_x = hid_field_extract(ctlr->hdev, rep->right_stick, 0, 12);
480 		raw_y = hid_field_extract(ctlr->hdev,
481 					  rep->right_stick + 1, 4, 12);
482 		/* map stick values */
483 		x = joycon_map_stick_val(&ctlr->right_stick_cal_x, raw_x);
484 		y = -joycon_map_stick_val(&ctlr->right_stick_cal_y, raw_y);
485 		/* report sticks */
486 		input_report_abs(dev, ABS_RX, x);
487 		input_report_abs(dev, ABS_RY, y);
488 
489 		/* report buttons */
490 		input_report_key(dev, BTN_TR, btns & JC_BTN_R);
491 		input_report_key(dev, BTN_TR2, btns & JC_BTN_ZR);
492 		if (id != USB_DEVICE_ID_NINTENDO_PROCON) {
493 			/* Report the S buttons as the non-existent triggers */
494 			input_report_key(dev, BTN_TL, btns & JC_BTN_SL_R);
495 			input_report_key(dev, BTN_TL2, btns & JC_BTN_SR_R);
496 		}
497 		input_report_key(dev, BTN_START, btns & JC_BTN_PLUS);
498 		input_report_key(dev, BTN_THUMBR, btns & JC_BTN_RSTICK);
499 		input_report_key(dev, BTN_MODE, btns & JC_BTN_HOME);
500 		input_report_key(dev, BTN_WEST, btns & JC_BTN_Y);
501 		input_report_key(dev, BTN_NORTH, btns & JC_BTN_X);
502 		input_report_key(dev, BTN_EAST, btns & JC_BTN_A);
503 		input_report_key(dev, BTN_SOUTH, btns & JC_BTN_B);
504 	}
505 
506 	input_sync(dev);
507 }
508 
509 
510 static const unsigned int joycon_button_inputs_l[] = {
511 	BTN_SELECT, BTN_Z, BTN_THUMBL,
512 	BTN_DPAD_UP, BTN_DPAD_DOWN, BTN_DPAD_LEFT, BTN_DPAD_RIGHT,
513 	BTN_TL, BTN_TL2,
514 	0 /* 0 signals end of array */
515 };
516 
517 static const unsigned int joycon_button_inputs_r[] = {
518 	BTN_START, BTN_MODE, BTN_THUMBR,
519 	BTN_SOUTH, BTN_EAST, BTN_NORTH, BTN_WEST,
520 	BTN_TR, BTN_TR2,
521 	0 /* 0 signals end of array */
522 };
523 
524 static DEFINE_MUTEX(joycon_input_num_mutex);
joycon_input_create(struct joycon_ctlr * ctlr)525 static int joycon_input_create(struct joycon_ctlr *ctlr)
526 {
527 	struct hid_device *hdev;
528 	static int input_num = 1;
529 	const char *name;
530 	int ret;
531 	int i;
532 
533 	hdev = ctlr->hdev;
534 
535 	switch (hdev->product) {
536 	case USB_DEVICE_ID_NINTENDO_PROCON:
537 		name = "Nintendo Switch Pro Controller";
538 		break;
539 	case USB_DEVICE_ID_NINTENDO_JOYCONL:
540 		name = "Nintendo Switch Left Joy-Con";
541 		break;
542 	case USB_DEVICE_ID_NINTENDO_JOYCONR:
543 		name = "Nintendo Switch Right Joy-Con";
544 		break;
545 	default: /* Should be impossible */
546 		hid_err(hdev, "Invalid hid product\n");
547 		return -EINVAL;
548 	}
549 
550 	ctlr->input = devm_input_allocate_device(&hdev->dev);
551 	if (!ctlr->input)
552 		return -ENOMEM;
553 	ctlr->input->id.bustype = hdev->bus;
554 	ctlr->input->id.vendor = hdev->vendor;
555 	ctlr->input->id.product = hdev->product;
556 	ctlr->input->id.version = hdev->version;
557 	ctlr->input->name = name;
558 	input_set_drvdata(ctlr->input, ctlr);
559 
560 
561 	/* set up sticks */
562 	if (hdev->product != USB_DEVICE_ID_NINTENDO_JOYCONR) {
563 		input_set_abs_params(ctlr->input, ABS_X,
564 				     -JC_MAX_STICK_MAG, JC_MAX_STICK_MAG,
565 				     JC_STICK_FUZZ, JC_STICK_FLAT);
566 		input_set_abs_params(ctlr->input, ABS_Y,
567 				     -JC_MAX_STICK_MAG, JC_MAX_STICK_MAG,
568 				     JC_STICK_FUZZ, JC_STICK_FLAT);
569 	}
570 	if (hdev->product != USB_DEVICE_ID_NINTENDO_JOYCONL) {
571 		input_set_abs_params(ctlr->input, ABS_RX,
572 				     -JC_MAX_STICK_MAG, JC_MAX_STICK_MAG,
573 				     JC_STICK_FUZZ, JC_STICK_FLAT);
574 		input_set_abs_params(ctlr->input, ABS_RY,
575 				     -JC_MAX_STICK_MAG, JC_MAX_STICK_MAG,
576 				     JC_STICK_FUZZ, JC_STICK_FLAT);
577 	}
578 
579 	/* set up buttons */
580 	if (hdev->product != USB_DEVICE_ID_NINTENDO_JOYCONR) {
581 		for (i = 0; joycon_button_inputs_l[i] > 0; i++)
582 			input_set_capability(ctlr->input, EV_KEY,
583 					     joycon_button_inputs_l[i]);
584 	}
585 	if (hdev->product != USB_DEVICE_ID_NINTENDO_JOYCONL) {
586 		for (i = 0; joycon_button_inputs_r[i] > 0; i++)
587 			input_set_capability(ctlr->input, EV_KEY,
588 					     joycon_button_inputs_r[i]);
589 	}
590 
591 	ret = input_register_device(ctlr->input);
592 	if (ret)
593 		return ret;
594 
595 	/* Set the default controller player leds based on controller number */
596 	mutex_lock(&joycon_input_num_mutex);
597 	mutex_lock(&ctlr->output_mutex);
598 	ret = joycon_set_player_leds(ctlr, 0, 0xF >> (4 - input_num));
599 	if (ret)
600 		hid_warn(ctlr->hdev, "Failed to set leds; ret=%d\n", ret);
601 	mutex_unlock(&ctlr->output_mutex);
602 	if (++input_num > 4)
603 		input_num = 1;
604 	mutex_unlock(&joycon_input_num_mutex);
605 
606 	return 0;
607 }
608 
609 /* Common handler for parsing inputs */
joycon_ctlr_read_handler(struct joycon_ctlr * ctlr,u8 * data,int size)610 static int joycon_ctlr_read_handler(struct joycon_ctlr *ctlr, u8 *data,
611 							      int size)
612 {
613 	int ret = 0;
614 
615 	if (data[0] == JC_INPUT_SUBCMD_REPLY || data[0] == JC_INPUT_IMU_DATA ||
616 	    data[0] == JC_INPUT_MCU_DATA) {
617 		if (size >= 12) /* make sure it contains the input report */
618 			joycon_parse_report(ctlr,
619 					    (struct joycon_input_report *)data);
620 	}
621 
622 	return ret;
623 }
624 
joycon_ctlr_handle_event(struct joycon_ctlr * ctlr,u8 * data,int size)625 static int joycon_ctlr_handle_event(struct joycon_ctlr *ctlr, u8 *data,
626 							      int size)
627 {
628 	int ret = 0;
629 	bool match = false;
630 	struct joycon_input_report *report;
631 
632 	if (unlikely(mutex_is_locked(&ctlr->output_mutex)) &&
633 	    ctlr->msg_type != JOYCON_MSG_TYPE_NONE) {
634 		switch (ctlr->msg_type) {
635 		case JOYCON_MSG_TYPE_USB:
636 			if (size < 2)
637 				break;
638 			if (data[0] == JC_INPUT_USB_RESPONSE &&
639 			    data[1] == ctlr->usb_ack_match)
640 				match = true;
641 			break;
642 		case JOYCON_MSG_TYPE_SUBCMD:
643 			if (size < sizeof(struct joycon_input_report) ||
644 			    data[0] != JC_INPUT_SUBCMD_REPLY)
645 				break;
646 			report = (struct joycon_input_report *)data;
647 			if (report->reply.id == ctlr->subcmd_ack_match)
648 				match = true;
649 			break;
650 		default:
651 			break;
652 		}
653 
654 		if (match) {
655 			memcpy(ctlr->input_buf, data,
656 			       min(size, (int)JC_MAX_RESP_SIZE));
657 			ctlr->msg_type = JOYCON_MSG_TYPE_NONE;
658 			ctlr->received_resp = true;
659 			wake_up(&ctlr->wait);
660 
661 			/* This message has been handled */
662 			return 1;
663 		}
664 	}
665 
666 	if (ctlr->ctlr_state == JOYCON_CTLR_STATE_READ)
667 		ret = joycon_ctlr_read_handler(ctlr, data, size);
668 
669 	return ret;
670 }
671 
nintendo_hid_event(struct hid_device * hdev,struct hid_report * report,u8 * raw_data,int size)672 static int nintendo_hid_event(struct hid_device *hdev,
673 			      struct hid_report *report, u8 *raw_data, int size)
674 {
675 	struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
676 
677 	if (size < 1)
678 		return -EINVAL;
679 
680 	return joycon_ctlr_handle_event(ctlr, raw_data, size);
681 }
682 
nintendo_hid_probe(struct hid_device * hdev,const struct hid_device_id * id)683 static int nintendo_hid_probe(struct hid_device *hdev,
684 			    const struct hid_device_id *id)
685 {
686 	int ret;
687 	struct joycon_ctlr *ctlr;
688 
689 	hid_dbg(hdev, "probe - start\n");
690 
691 	ctlr = devm_kzalloc(&hdev->dev, sizeof(*ctlr), GFP_KERNEL);
692 	if (!ctlr) {
693 		ret = -ENOMEM;
694 		goto err;
695 	}
696 
697 	ctlr->hdev = hdev;
698 	ctlr->ctlr_state = JOYCON_CTLR_STATE_INIT;
699 	hid_set_drvdata(hdev, ctlr);
700 	mutex_init(&ctlr->output_mutex);
701 	init_waitqueue_head(&ctlr->wait);
702 
703 	ret = hid_parse(hdev);
704 	if (ret) {
705 		hid_err(hdev, "HID parse failed\n");
706 		goto err;
707 	}
708 
709 	ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
710 	if (ret) {
711 		hid_err(hdev, "HW start failed\n");
712 		goto err;
713 	}
714 
715 	ret = hid_hw_open(hdev);
716 	if (ret) {
717 		hid_err(hdev, "cannot start hardware I/O\n");
718 		goto err_stop;
719 	}
720 
721 	hid_device_io_start(hdev);
722 
723 	/* Initialize the controller */
724 	mutex_lock(&ctlr->output_mutex);
725 	/* if handshake command fails, assume ble pro controller */
726 	if (hdev->product == USB_DEVICE_ID_NINTENDO_PROCON &&
727 	    !joycon_send_usb(ctlr, JC_USB_CMD_HANDSHAKE)) {
728 		hid_dbg(hdev, "detected USB controller\n");
729 		/* set baudrate for improved latency */
730 		ret = joycon_send_usb(ctlr, JC_USB_CMD_BAUDRATE_3M);
731 		if (ret) {
732 			hid_err(hdev, "Failed to set baudrate; ret=%d\n", ret);
733 			goto err_mutex;
734 		}
735 		/* handshake */
736 		ret = joycon_send_usb(ctlr, JC_USB_CMD_HANDSHAKE);
737 		if (ret) {
738 			hid_err(hdev, "Failed handshake; ret=%d\n", ret);
739 			goto err_mutex;
740 		}
741 		/*
742 		 * Set no timeout (to keep controller in USB mode).
743 		 * This doesn't send a response, so ignore the timeout.
744 		 */
745 		joycon_send_usb(ctlr, JC_USB_CMD_NO_TIMEOUT);
746 	}
747 
748 	/* get controller calibration data, and parse it */
749 	ret = joycon_request_calibration(ctlr);
750 	if (ret) {
751 		/*
752 		 * We can function with default calibration, but it may be
753 		 * inaccurate. Provide a warning, and continue on.
754 		 */
755 		hid_warn(hdev, "Analog stick positions may be inaccurate\n");
756 	}
757 
758 	/* Set the reporting mode to 0x30, which is the full report mode */
759 	ret = joycon_set_report_mode(ctlr);
760 	if (ret) {
761 		hid_err(hdev, "Failed to set report mode; ret=%d\n", ret);
762 		goto err_mutex;
763 	}
764 
765 	mutex_unlock(&ctlr->output_mutex);
766 
767 	ret = joycon_input_create(ctlr);
768 	if (ret) {
769 		hid_err(hdev, "Failed to create input device; ret=%d\n", ret);
770 		goto err_close;
771 	}
772 
773 	ctlr->ctlr_state = JOYCON_CTLR_STATE_READ;
774 
775 	hid_dbg(hdev, "probe - success\n");
776 	return 0;
777 
778 err_mutex:
779 	mutex_unlock(&ctlr->output_mutex);
780 err_close:
781 	hid_hw_close(hdev);
782 err_stop:
783 	hid_hw_stop(hdev);
784 err:
785 	hid_err(hdev, "probe - fail = %d\n", ret);
786 	return ret;
787 }
788 
nintendo_hid_remove(struct hid_device * hdev)789 static void nintendo_hid_remove(struct hid_device *hdev)
790 {
791 	hid_dbg(hdev, "remove\n");
792 	hid_hw_close(hdev);
793 	hid_hw_stop(hdev);
794 }
795 
796 static const struct hid_device_id nintendo_hid_devices[] = {
797 	{ HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
798 			 USB_DEVICE_ID_NINTENDO_PROCON) },
799 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
800 			 USB_DEVICE_ID_NINTENDO_PROCON) },
801 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
802 			 USB_DEVICE_ID_NINTENDO_JOYCONL) },
803 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
804 			 USB_DEVICE_ID_NINTENDO_JOYCONR) },
805 	{ }
806 };
807 MODULE_DEVICE_TABLE(hid, nintendo_hid_devices);
808 
809 static struct hid_driver nintendo_hid_driver = {
810 	.name		= "nintendo",
811 	.id_table	= nintendo_hid_devices,
812 	.probe		= nintendo_hid_probe,
813 	.remove		= nintendo_hid_remove,
814 	.raw_event	= nintendo_hid_event,
815 };
816 module_hid_driver(nintendo_hid_driver);
817 
818 MODULE_LICENSE("GPL");
819 MODULE_AUTHOR("Daniel J. Ogorchock <djogorchock@gmail.com>");
820 MODULE_DESCRIPTION("Driver for Nintendo Switch Controllers");
821