Skip to contentSkip to conversation

HID: nintendo

PATCH Superseded Daniel J. Ogorchock 2 participants 12 messages Nov 6, 2019 – Dec 17, 2019 1 message not in the archive

Subsystems (2)

v9 of 16 Superseded Latest is v16 →

lore
Share & tools
lore

Daniel J. Ogorchock

author maintainer
#0 lore raw

v9 cover HID: nintendo

This is a pretty minor change. Importantly it resolves a couple compiler errors when building the driver with a version of gcc prior to 8. It seems that gcc 8 and above are more relaxed about using const integers to initialize other const values and in case statement matching.

It also sets the input device's uniq value to the controller's MAC address. This will be useful once gyro/accelerometer support is added in the future (likely as a second input device). Since the joy-cons can also be used via uart on the nintendo switch's serial rails, this is also a useful mechanism for associating one joy-con between two drivers (hid-nintendo and any serdev joy-con driver written to run on the nintendo switch itself).

Version 9 changes:
- Fixed compiler errors on gcc versions older than 8.2
- Set input device's uniq value to the controller's MAC address

Version 8 changes:
- Corrected the handshaking protocol with USB pro controllers. A handshake now occurs both prior and after the baudrate set. This doesn't appear to have a noticeable difference, but it more accurately follows documentation found online.
- Fixed potential race condition which could lead to a slightly longer delay sending subcommands in rare circumstances.
- Moved the rumble worker to its own workqueue, since it can block. This prevents it from having a negative impact on the default kernel workqueue. It also prevents dropped subcommands due to something else blocking the kernel workqueue. The benefit is most obvious when using multiple controllers at once, since the controller subcommand timings are very picky.
- Added a patch to set the most significant bit of the hid hw version. Roderick had mentioned needing to probably do this awhile ago, but I had forgotten about it until now. This is the same thing hid-sony does. It allows SDL2 to have different mappings for the hid-nintendo driver vs the default hid mappings.

Version 7 changes:
- Changed name to hid-nintendo to fit modern naming conventions
- Removed joycon_ctlr_destroy(), since it wasn't needed an could potentially invalidate a mutex while it could be in use on other threads
- Implemented minor code improvements suggested by Silvan
- The driver now waits to send subcommands until after receiving an input report. This significantly reduces dropped subcommands.
- Reduced the number of error messages when disconnecting a controller.

Version 6 changes:
- Improved subcommand sending reliabilty
- Decreased rumble period to 50ms
- Added rumble queue to avoid missing ff_effects if sent too quickly
- Code cleanup and minor refactoring
- Added default analog stick calibration

Version 5 changes:
- Removed sysfs interface to control motor frequencies.
- Improved rumble reliability by using subcommands to set it.
- Changed mapping of the SL/SR triggers on the joy-cons to map to whichever triggers they lack (e.g. a left joycon's sl/sr map to TR and TR2). This allows userspace to distinguish between the normal and S triggers.
- Minor refactors

Version 4 changes:
- Added support for the Home button LED for the pro controller and right joy-con
- Changed name from hid-switchcon to hid-joycon
- Added rumble support
- Removed ctlr->type and use hdev->product instead
- Use POWER_SUPPLY_CAPACITY_LEVEL enum instead of manually translating to capacity percentages
- Misc. minor refactors based on v3 feedback

Version 3 changes:
- Added led_classdev support for the 4 player LEDs
- Added power_supply support for the controller's battery
- Made the controller number mutex static
- Minor refactoring/style fixes based on Roderick's feedback from v2

Version 2 changes:
- Switched to using a synchronous method for configuring the controller.
- Removed any pairing/orientation logic in the driver. Every controller now corresponds to its own input device.
- Store controller button data as a single u32.
- Style corrections

Daniel J. Ogorchock (10):
HID: nintendo: add nintendo switch controller driver
HID: nintendo: add player led support
HID: nintendo: add power supply support
HID: nintendo: add home led support
HID: nintendo: add rumble support
HID: nintendo: improve subcommand reliability
HID: nintendo: send subcommands after receiving input report
HID: nintendo: reduce device removal subcommand errors
HID: nintendo: patch hw version for userspace HID mappings
HID: nintendo: set controller uniq to MAC

 MAINTAINERS                |    6 +
 drivers/hid/Kconfig        |   24 +
 drivers/hid/Makefile       |    1 +
 drivers/hid/hid-ids.h      |    3 +
 drivers/hid/hid-nintendo.c | 1558 ++++++++++++++++++++++++++++++++++++
 5 files changed, 1592 insertions(+)
 create mode 100644 drivers/hid/hid-nintendo.c
Signature · 1 line
2.23.0
author maintainer
#1 lore raw

PATCH v9 1/10 HID: nintendo: add nintendo switch controller driver

The hid-nintendo driver supports the Nintendo Switch Pro Controllers and the Joy-Cons. The Pro Controllers can be used over USB or Bluetooth.

The Joy-Cons each create their own, independent input devices, so it is up to userspace to combine them if desired.

---
 MAINTAINERS                |   6 +
 drivers/hid/Kconfig        |  11 +
 drivers/hid/Makefile       |   1 +
 drivers/hid/hid-ids.h      |   3 +
 drivers/hid/hid-nintendo.c | 806 +++++++++++++++++++++++++++++++++++++
 5 files changed, 827 insertions(+)
 create mode 100644 drivers/hid/hid-nintendo.c
MAINTAINERS +6 -0
index 1d235c674be8..9e9846cdd524 100644
@@ -11393,6 +11393,12 @@ S:	Maintained
 F:	Documentation/scsi/NinjaSCSI.txt
 F:	drivers/scsi/nsp32*
 
+NINTENDO HID DRIVER
+M:	Daniel J. Ogorchock <[email protected]>
+L:	[email protected]
+S:	Maintained
+F:	drivers/hid/hid-nintendo*
+
 NIOS2 ARCHITECTURE
 M:	Ley Foon Tan <[email protected]>
 L:	[email protected] (moderated for non-subscribers)
drivers/hid/Kconfig +11 -0
index 3872e03d9a59..47ec750c2baf 100644
@@ -692,6 +692,17 @@ config HID_MULTITOUCH
 	  To compile this driver as a module, choose M here: the
 	  module will be called hid-multitouch.
 
+config HID_NINTENDO
+	tristate "Nintendo Joy-Con and Pro Controller support"
+	depends on HID
+	help
+	Adds support for the Nintendo Switch Joy-Cons and Pro Controller.
+	All controllers support bluetooth, and the Pro Controller also supports
+	its USB mode.
+
+	To compile this driver as a module, choose M here: the
+	module will be called hid-nintendo.
+
 config HID_NTI
 	tristate "NTI keyboard adapters"
 	---help---
drivers/hid/Makefile +1 -0
index cc5d827c9164..398d5e91fa4b 100644
@@ -72,6 +72,7 @@ obj-$(CONFIG_HID_MAYFLASH)	+= hid-mf.o
 obj-$(CONFIG_HID_MICROSOFT)	+= hid-microsoft.o
 obj-$(CONFIG_HID_MONTEREY)	+= hid-monterey.o
 obj-$(CONFIG_HID_MULTITOUCH)	+= hid-multitouch.o
+obj-$(CONFIG_HID_NINTENDO)	+= hid-nintendo.o
 obj-$(CONFIG_HID_NTI)			+= hid-nti.o
 obj-$(CONFIG_HID_NTRIG)		+= hid-ntrig.o
 obj-$(CONFIG_HID_ORTEK)		+= hid-ortek.o
drivers/hid/hid-ids.h +3 -0
index e4d51ce20a6a..4a916c00b749 100644
@@ -864,6 +864,9 @@
 #define USB_VENDOR_ID_NINTENDO		0x057e
 #define USB_DEVICE_ID_NINTENDO_WIIMOTE	0x0306
 #define USB_DEVICE_ID_NINTENDO_WIIMOTE2	0x0330
+#define USB_DEVICE_ID_NINTENDO_JOYCONL	0x2006
+#define USB_DEVICE_ID_NINTENDO_JOYCONR	0x2007
+#define USB_DEVICE_ID_NINTENDO_PROCON	0x2009
 
 #define USB_VENDOR_ID_NOVATEK		0x0603
 #define USB_DEVICE_ID_NOVATEK_PCT	0x0600
drivers/hid/hid-nintendo.c new file +806 -0

806 lines not on this page · raw message

Signature · 1 line
2.23.0
author maintainer
#2 lore raw

PATCH v9 2/10 HID: nintendo: add player led support

In reply to Daniel J. Ogorchock

This patch adds led_classdev functionality to the switch controller driver. It adds support for the 4 player LEDs. The Home Button LED still needs to be supported on the pro controllers and right joy-con.

---
 drivers/hid/Kconfig        |  2 +
 drivers/hid/hid-nintendo.c | 95 +++++++++++++++++++++++++++++++++++++-
 2 files changed, 95 insertions(+), 2 deletions(-)
drivers/hid/Kconfig +2 -0
index 47ec750c2baf..41f7da50896f 100644
@@ -695,6 +695,8 @@ config HID_MULTITOUCH
 config HID_NINTENDO
 	tristate "Nintendo Joy-Con and Pro Controller support"
 	depends on HID
+	depends on NEW_LEDS
+	depends on LEDS_CLASS
 	help
 	Adds support for the Nintendo Switch Joy-Cons and Pro Controller.
 	All controllers support bluetooth, and the Pro Controller also supports
drivers/hid/hid-nintendo.c +93 -2

139 lines not on this page · raw message

Signature · 1 line
2.23.0
author maintainer
#3 lore raw

PATCH v9 3/10 HID: nintendo: add power supply support

In reply to Daniel J. Ogorchock

This patch adds power_supply functionality to the switch controller driver for its battery.

---
 drivers/hid/Kconfig        |   1 +
 drivers/hid/hid-nintendo.c | 133 +++++++++++++++++++++++++++++++++++++
 2 files changed, 134 insertions(+)
drivers/hid/Kconfig +1 -0
index 41f7da50896f..a6e0f399bcab 100644
@@ -697,6 +697,7 @@ config HID_NINTENDO
 	depends on HID
 	depends on NEW_LEDS
 	depends on LEDS_CLASS
+	select POWER_SUPPLY
 	help
 	Adds support for the Nintendo Switch Joy-Cons and Pro Controller.
 	All controllers support bluetooth, and the Pro Controller also supports
drivers/hid/hid-nintendo.c +133 -0

184 lines not on this page · raw message

Signature · 1 line
2.23.0
author maintainer
#4 lore raw

PATCH v9 4/10 HID: nintendo: add home led support

In reply to Daniel J. Ogorchock

This patch adds the ability to set the intensity level of the home button's LED.

---
 drivers/hid/hid-nintendo.c | 69 +++++++++++++++++++++++++++++++++++---
 1 file changed, 65 insertions(+), 4 deletions(-)
drivers/hid/hid-nintendo.c +65 -4
index 0caa9e1860ad..18be44214041 100644
@@ -187,7 +187,8 @@ struct joycon_input_report {
 struct joycon_ctlr {
 	struct hid_device *hdev;
 	struct input_dev *input;
-	struct led_classdev leds[JC_NUM_LEDS];
+	struct led_classdev leds[JC_NUM_LEDS]; /* player leds */
+	struct led_classdev home_led;
 	enum joycon_ctlr_state ctlr_state;
 	spinlock_t lock;
 
@@ -659,6 +660,40 @@ static int joycon_player_led_brightness_set(struct led_classdev *led,
 	return ret;
 }
 
+static int joycon_home_led_brightness_set(struct led_classdev *led,
+					  enum led_brightness brightness)
+{
+	struct device *dev = led->dev->parent;
+	struct hid_device *hdev = to_hid_device(dev);
+	struct joycon_ctlr *ctlr;
+	struct joycon_subcmd_request *req;
+	u8 buffer[sizeof(*req) + 5] = { 0 };
+	u8 *data;
+	int ret;
+
+	ctlr = hid_get_drvdata(hdev);
+	if (!ctlr) {
+		hid_err(hdev, "No controller data\n");
+		return -ENODEV;
+	}
+
+	req = (struct joycon_subcmd_request *)buffer;
+	req->subcmd_id = JC_SUBCMD_SET_HOME_LIGHT;
+	data = req->data;
+	data[0] = 0x01;
+	data[1] = brightness << 4;
+	data[2] = brightness | (brightness << 4);
+	data[3] = 0x11;
+	data[4] = 0x11;
+
+	hid_dbg(hdev, "setting home led brightness\n");
+	mutex_lock(&ctlr->output_mutex);
+	ret = joycon_send_subcmd(ctlr, req, 5);
+	mutex_unlock(&ctlr->output_mutex);
+
+	return ret;
+}
+
 static const char * const joycon_player_led_names[] = {
 	"player1",
 	"player2",
@@ -667,7 +702,7 @@ static const char * const joycon_player_led_names[] = {
 };
 
 static DEFINE_MUTEX(joycon_input_num_mutex);
-static int joycon_player_leds_create(struct joycon_ctlr *ctlr)
+static int joycon_leds_create(struct joycon_ctlr *ctlr)
 {
 	struct hid_device *hdev = ctlr->hdev;
 	struct device *dev = &hdev->dev;
@@ -704,7 +739,7 @@ static int joycon_player_leds_create(struct joycon_ctlr *ctlr)
 		ret = devm_led_classdev_register(&hdev->dev, led);
 		if (ret) {
 			hid_err(hdev, "Failed registering %s LED\n", led->name);
-			break;
+			return ret;
 		}
 	}
 
@@ -712,6 +747,32 @@ static int joycon_player_leds_create(struct joycon_ctlr *ctlr)
 		input_num = 1;
 	mutex_unlock(&joycon_input_num_mutex);
 
+	/* configure the home LED */
+	if (ctlr->hdev->product != USB_DEVICE_ID_NINTENDO_JOYCONL) {
+		name = devm_kasprintf(dev, GFP_KERNEL, "%s:%s", d_name, "home");
+		if (!name)
+			return ret;
+
+		led = &ctlr->home_led;
+		led->name = name;
+		led->brightness = 0;
+		led->max_brightness = 0xF;
+		led->brightness_set_blocking = joycon_home_led_brightness_set;
+		led->flags = LED_CORE_SUSPENDRESUME | LED_HW_PLUGGABLE;
+		ret = devm_led_classdev_register(&hdev->dev, led);
+		if (ret) {
+			hid_err(hdev, "Failed registering home led\n");
+			return ret;
+		}
+		/* Set the home LED to 0 as default state */
+		ret = joycon_home_led_brightness_set(led, 0);
+		if (ret) {
+			hid_err(hdev, "Failed to set home LED dflt; ret=%d\n",
+									ret);
+			return ret;
+		}
+	}
+
 	return 0;
 }
 
@@ -965,7 +1026,7 @@ static int nintendo_hid_probe(struct hid_device *hdev,
 	}
 
 	/* Initialize the leds */
-	ret = joycon_player_leds_create(ctlr);
+	ret = joycon_leds_create(ctlr);
 	if (ret) {
 		hid_err(hdev, "Failed to create leds; ret=%d\n", ret);
 		goto err_close;
Signature · 1 line
2.23.0
author maintainer
#5 lore raw

PATCH v9 5/10 HID: nintendo: add rumble support

In reply to Daniel J. Ogorchock

This patch adds support for controller rumble.

The ff_effect weak magnitude is associated with the pro controller's right motor (or with a right joy-con). The strong magnitude is associated with the pro's left motor (or a left joy-con).

The rumble data is sent periodically (currently configured for every 50 milliseconds). If the controller receives no rumble data for too long a time period, it will stop vibrating. The data is also sent every time joycon_set_rumble is called to avoid latency of up to 50ms.

Because the rumble subcommands are sent in a deferred workqueue (they can't be sent in the play_effect function due to the hid send sleeping), the effects are queued. This ensures that no rumble effect is missed due to them arriving in too quick of succession.

---
 drivers/hid/Kconfig        |  10 ++
 drivers/hid/hid-nintendo.c | 347 ++++++++++++++++++++++++++++++++++++-
 2 files changed, 354 insertions(+), 3 deletions(-)
drivers/hid/Kconfig +10 -0
index a6e0f399bcab..fea15e4e085f 100644
@@ -706,6 +706,16 @@ config HID_NINTENDO
 	To compile this driver as a module, choose M here: the
 	module will be called hid-nintendo.
 
+config NINTENDO_FF
+	bool "Nintendo Switch controller force feedback support"
+	depends on HID_NINTENDO
+	select INPUT_FF_MEMLESS
+	help
+	Say Y here if you have a Nintendo Switch controller and want to enable
+	force feedback support for it. This works for both joy-cons and the pro
+	controller. For the pro controller, both rumble motors can be controlled
+	individually.
+
 config HID_NTI
 	tristate "NTI keyboard adapters"
 	---help---
drivers/hid/hid-nintendo.c +344 -3

447 lines not on this page · raw message

Signature · 1 line
2.23.0
author maintainer
#6 lore raw

PATCH v9 6/10 HID: nintendo: improve subcommand reliability

In reply to Daniel J. Ogorchock

The controller occasionally doesn't respond to subcommands. It appears that it's dropping them. To improve reliability, this patch attempts one retry in the case of a synchronous send timeout. In testing, this has resolved all timeout failures (most common for LED setting and rumble setting subcommands).

The 1 second timeout is excessively long for rumble and LED subcommands, so the timeout has been made a param for joycon_hid_send_sync. Most subcommands continue to use the 1s timeout, since they can result in long response times. Rumble and LED setting subcommands have been reduced to 250ms, since response times for them are much quicker (and this significantly reduces the observable impact in the case of a retry being required).

---
 drivers/hid/hid-nintendo.c | 56 +++++++++++++++++++++++++-------------
 1 file changed, 37 insertions(+), 19 deletions(-)
drivers/hid/hid-nintendo.c +37 -19
index ec632a4b9785..8bd49f3a67ab 100644
@@ -365,24 +365,42 @@ static int __joycon_hid_send(struct hid_device *hdev, u8 *data, size_t len)
 	return ret;
 }
 
-static int joycon_hid_send_sync(struct joycon_ctlr *ctlr, u8 *data, size_t len)
+static int joycon_hid_send_sync(struct joycon_ctlr *ctlr, u8 *data, size_t len,
+				u32 timeout)
 {
 	int ret;
+	int tries = 2;
 
-	ret = __joycon_hid_send(ctlr->hdev, data, len);
-	if (ret < 0) {
-		memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE);
-		return ret;
-	}
+	/*
+	 * The controller occasionally seems to drop subcommands. In testing,
+	 * doing one retry after a timeout appears to always work.
+	 */
+	while (tries--) {
+		ret = __joycon_hid_send(ctlr->hdev, data, len);
+		if (ret < 0) {
+			memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE);
+			return ret;
+		}
 
-	if (!wait_event_timeout(ctlr->wait, ctlr->received_resp, HZ)) {
-		hid_dbg(ctlr->hdev, "synchronous send/receive timed out\n");
-		memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE);
-		return -ETIMEDOUT;
+		ret = wait_event_timeout(ctlr->wait, ctlr->received_resp,
+					 timeout);
+		if (!ret) {
+			hid_dbg(ctlr->hdev,
+				"synchronous send/receive timed out\n");
+			if (tries) {
+				hid_dbg(ctlr->hdev,
+					"retrying sync send after timeout\n");
+			}
+			memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE);
+			ret = -ETIMEDOUT;
+		} else {
+			ret = 0;
+			break;
+		}
 	}
 
 	ctlr->received_resp = false;
-	return 0;
+	return ret;
 }
 
 static int joycon_send_usb(struct joycon_ctlr *ctlr, u8 cmd)
@@ -393,7 +411,7 @@ static int joycon_send_usb(struct joycon_ctlr *ctlr, u8 cmd)
 	buf[1] = cmd;
 	ctlr->usb_ack_match = cmd;
 	ctlr->msg_type = JOYCON_MSG_TYPE_USB;
-	ret = joycon_hid_send_sync(ctlr, buf, sizeof(buf));
+	ret = joycon_hid_send_sync(ctlr, buf, sizeof(buf), HZ);
 	if (ret)
 		hid_dbg(ctlr->hdev, "send usb command failed; ret=%d\n", ret);
 	return ret;
@@ -401,7 +419,7 @@ static int joycon_send_usb(struct joycon_ctlr *ctlr, u8 cmd)
 
 static int joycon_send_subcmd(struct joycon_ctlr *ctlr,
 			      struct joycon_subcmd_request *subcmd,
-			      size_t data_len)
+			      size_t data_len, u32 timeout)
 {
 	int ret;
 	unsigned long flags;
@@ -419,7 +437,7 @@ static int joycon_send_subcmd(struct joycon_ctlr *ctlr,
 	ctlr->msg_type = JOYCON_MSG_TYPE_SUBCMD;
 
 	ret = joycon_hid_send_sync(ctlr, (u8 *)subcmd,
-				   sizeof(*subcmd) + data_len);
+				   sizeof(*subcmd) + data_len, timeout);
 	if (ret < 0)
 		hid_dbg(ctlr->hdev, "send subcommand failed; ret=%d\n", ret);
 	else
@@ -438,7 +456,7 @@ static int joycon_set_player_leds(struct joycon_ctlr *ctlr, u8 flash, u8 on)
 	req->data[0] = (flash << 4) | on;
 
 	hid_dbg(ctlr->hdev, "setting player leds\n");
-	return joycon_send_subcmd(ctlr, req, 1);
+	return joycon_send_subcmd(ctlr, req, 1, HZ/4);
 }
 
 static const u16 DFLT_STICK_CAL_CEN = 2000;
@@ -469,7 +487,7 @@ static int joycon_request_calibration(struct joycon_ctlr *ctlr)
 	data[4] = JC_CAL_DATA_SIZE;
 
 	hid_dbg(ctlr->hdev, "requesting cal data\n");
-	ret = joycon_send_subcmd(ctlr, req, 5);
+	ret = joycon_send_subcmd(ctlr, req, 5, HZ);
 	if (ret) {
 		hid_warn(ctlr->hdev,
 			 "Failed to read stick cal, using defaults; ret=%d\n",
@@ -559,7 +577,7 @@ static int joycon_set_report_mode(struct joycon_ctlr *ctlr)
 	req->data[0] = 0x30; /* standard, full report mode */
 
 	hid_dbg(ctlr->hdev, "setting controller report mode\n");
-	return joycon_send_subcmd(ctlr, req, 1);
+	return joycon_send_subcmd(ctlr, req, 1, HZ);
 }
 
 static int joycon_enable_rumble(struct joycon_ctlr *ctlr, bool enable)
@@ -572,7 +590,7 @@ static int joycon_enable_rumble(struct joycon_ctlr *ctlr, bool enable)
 	req->data[0] = enable ? 0x01 : 0x00;
 
 	hid_dbg(ctlr->hdev, "%s rumble\n", enable ? "enabling" : "disabling");
-	return joycon_send_subcmd(ctlr, req, 1);
+	return joycon_send_subcmd(ctlr, req, 1, HZ/4);
 }
 
 static s32 joycon_map_stick_val(struct joycon_stick_cal *cal, s32 val)
@@ -1014,7 +1032,7 @@ static int joycon_home_led_brightness_set(struct led_classdev *led,
 
 	hid_dbg(hdev, "setting home led brightness\n");
 	mutex_lock(&ctlr->output_mutex);
-	ret = joycon_send_subcmd(ctlr, req, 5);
+	ret = joycon_send_subcmd(ctlr, req, 5, HZ/4);
 	mutex_unlock(&ctlr->output_mutex);
 
 	return ret;
Signature · 1 line
2.23.0
author maintainer
#7 lore raw

PATCH v9 7/10 HID: nintendo: send subcommands after receiving input report

In reply to Daniel J. Ogorchock

Waiting to send subcommands until right after receiving an input report drastically improves subcommand reliability. If the driver has finished initial controller configuration, it now waits until receiving an input report for all subcommands.

---
 drivers/hid/hid-nintendo.c | 33 +++++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)
drivers/hid/hid-nintendo.c +33 -0
index 8bd49f3a67ab..14ffd188ef78 100644
@@ -323,6 +323,7 @@ struct joycon_ctlr {
 	bool received_resp;
 	u8 usb_ack_match;
 	u8 subcmd_ack_match;
+	bool received_input_report;
 
 	/* factory calibration data */
 	struct joycon_stick_cal left_stick_cal_x;
@@ -376,6 +377,26 @@ static int joycon_hid_send_sync(struct joycon_ctlr *ctlr, u8 *data, size_t len,
 	 * doing one retry after a timeout appears to always work.
 	 */
 	while (tries--) {
+		/*
+		 * If we are in the proper reporting mode, wait for an input
+		 * report prior to sending the subcommand. This improves
+		 * reliability considerably.
+		 */
+		if (ctlr->ctlr_state == JOYCON_CTLR_STATE_READ) {
+			unsigned long flags;
+
+			spin_lock_irqsave(&ctlr->lock, flags);
+			ctlr->received_input_report = false;
+			spin_unlock_irqrestore(&ctlr->lock, flags);
+			ret = wait_event_timeout(ctlr->wait,
+						 ctlr->received_input_report,
+						 HZ / 4);
+			/* We will still proceed, even with a timeout here */
+			if (!ret)
+				hid_warn(ctlr->hdev,
+					 "timeout waiting for input report\n");
+		}
+
 		ret = __joycon_hid_send(ctlr->hdev, data, len);
 		if (ret < 0) {
 			memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE);
@@ -726,6 +747,18 @@ static void joycon_parse_report(struct joycon_ctlr *ctlr,
 	}
 
 	input_sync(dev);
+
+	/*
+	 * Immediately after receiving a report is the most reliable time to
+	 * send a subcommand to the controller. Wake any subcommand senders
+	 * waiting for a report.
+	 */
+	if (unlikely(mutex_is_locked(&ctlr->output_mutex))) {
+		spin_lock_irqsave(&ctlr->lock, flags);
+		ctlr->received_input_report = true;
+		spin_unlock_irqrestore(&ctlr->lock, flags);
+		wake_up(&ctlr->wait);
+	}
 }
 
 static void joycon_rumble_worker(struct work_struct *work)
Signature · 1 line
2.23.0
author maintainer
#8 lore raw

PATCH v9 8/10 HID: nintendo: reduce device removal subcommand errors

In reply to Daniel J. Ogorchock

This patch fixes meaningless error output from trying to send subcommands immediately after controller removal. It now disables subcommands as soon as possible on removal.

---
 drivers/hid/hid-nintendo.c | 27 ++++++++++++++++++++++++---
 1 file changed, 24 insertions(+), 3 deletions(-)
drivers/hid/hid-nintendo.c +24 -3
index 14ffd188ef78..074fd59decbe 100644
@@ -324,6 +324,7 @@ struct joycon_ctlr {
 	u8 usb_ack_match;
 	u8 subcmd_ack_match;
 	bool received_input_report;
+	bool ctlr_removed;
 
 	/* factory calibration data */
 	struct joycon_stick_cal left_stick_cal_x;
@@ -391,10 +392,12 @@ static int joycon_hid_send_sync(struct joycon_ctlr *ctlr, u8 *data, size_t len,
 			ret = wait_event_timeout(ctlr->wait,
 						 ctlr->received_input_report,
 						 HZ / 4);
+			spin_lock_irqsave(&ctlr->lock, flags);
 			/* We will still proceed, even with a timeout here */
-			if (!ret)
+			if (!ret && !ctlr->ctlr_removed)
 				hid_warn(ctlr->hdev,
 					 "timeout waiting for input report\n");
+			spin_unlock_irqrestore(&ctlr->lock, flags);
 		}
 
 		ret = __joycon_hid_send(ctlr->hdev, data, len);
@@ -446,6 +449,14 @@ static int joycon_send_subcmd(struct joycon_ctlr *ctlr,
 	unsigned long flags;
 
 	spin_lock_irqsave(&ctlr->lock, flags);
+	/*
+	 * If the controller has been removed, just return ENODEV so the LED
+	 * subsystem doesn't print invalid errors on removal.
+	 */
+	if (ctlr->ctlr_removed) {
+		spin_unlock_irqrestore(&ctlr->lock, flags);
+		return -ENODEV;
+	}
 	memcpy(subcmd->rumble_data, ctlr->rumble_data[ctlr->rumble_queue_tail],
 	       JC_RUMBLE_DATA_SIZE);
 	spin_unlock_irqrestore(&ctlr->lock, flags);
@@ -773,10 +784,12 @@ static void joycon_rumble_worker(struct work_struct *work)
 		mutex_lock(&ctlr->output_mutex);
 		ret = joycon_enable_rumble(ctlr, true);
 		mutex_unlock(&ctlr->output_mutex);
-		if (ret < 0)
-			hid_warn(ctlr->hdev, "Failed to set rumble; e=%d", ret);
 
+		/* -ENODEV means the controller was just unplugged */
 		spin_lock_irqsave(&ctlr->lock, flags);
+		if (ret < 0 && ret != -ENODEV && !ctlr->ctlr_removed)
+			hid_warn(ctlr->hdev, "Failed to set rumble; e=%d", ret);
+
 		ctlr->rumble_msecs = jiffies_to_msecs(jiffies);
 		if (ctlr->rumble_queue_tail != ctlr->rumble_queue_head) {
 			if (++ctlr->rumble_queue_tail >= JC_RUMBLE_QUEUE_SIZE)
@@ -1449,9 +1462,17 @@ static int nintendo_hid_probe(struct hid_device *hdev,
 static void nintendo_hid_remove(struct hid_device *hdev)
 {
 	struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
+	unsigned long flags;
 
 	hid_dbg(hdev, "remove\n");
+
+	/* Prevent further attempts at sending subcommands. */
+	spin_lock_irqsave(&ctlr->lock, flags);
+	ctlr->ctlr_removed = true;
+	spin_unlock_irqrestore(&ctlr->lock, flags);
+
 	destroy_workqueue(ctlr->rumble_queue);
+
 	hid_hw_close(hdev);
 	hid_hw_stop(hdev);
 }
Signature · 1 line
2.23.0
author maintainer
#9 lore raw

PATCH v9 9/10 HID: nintendo: patch hw version for userspace HID mappings

In reply to Daniel J. Ogorchock

This patch sets the most significant bit of the hid hw version to allow userspace to distinguish between this driver's input mappings vs. the default hid mappings. This prevents breaking userspace applications that use SDL2 for gamepad input, allowing them to distinguish the mappings based on the version.

---
 drivers/hid/hid-nintendo.c | 9 +++++++++
 1 file changed, 9 insertions(+)
drivers/hid/hid-nintendo.c +9 -0
index 074fd59decbe..24c4ec4e453a 100644
@@ -1356,6 +1356,15 @@ static int nintendo_hid_probe(struct hid_device *hdev,
 		goto err_wq;
 	}
 
+	/*
+	 * Patch the hw version of pro controller/joycons, so applications can
+	 * distinguish between the default HID mappings and the mappings defined
+	 * by the Linux game controller spec. This is important for the SDL2
+	 * library, which has a game controller database, which uses device ids
+	 * in combination with version as a key.
+	 */
+	hdev->version |= 0x8000;
+
 	ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
 	if (ret) {
 		hid_err(hdev, "HW start failed\n");
Signature · 1 line
2.23.0
author maintainer
#10 lore raw

PATCH v9 10/10 HID: nintendo: set controller uniq to MAC

In reply to Daniel J. Ogorchock

This patch sets the input device's uniq identifier to the controller's MAC address. This is useful for future association between an IMU input device with the normal input device as well as associating the controller with any serial joy-con driver.

---
 drivers/hid/hid-nintendo.c | 45 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 45 insertions(+)
drivers/hid/hid-nintendo.c +45 -0
index 24c4ec4e453a..c81bdcda76d4 100644
@@ -313,6 +313,8 @@ struct joycon_ctlr {
 	struct led_classdev home_led;
 	enum joycon_ctlr_state ctlr_state;
 	spinlock_t lock;
+	u8 mac_addr[6];
+	char *mac_addr_str;
 
 	/* The following members are used for synchronous sends/receives */
 	enum joycon_msg_type msg_type;
@@ -970,6 +972,7 @@ static int joycon_input_create(struct joycon_ctlr *ctlr)
 	ctlr->input->id.vendor = hdev->vendor;
 	ctlr->input->id.product = hdev->product;
 	ctlr->input->id.version = hdev->version;
+	ctlr->input->uniq = ctlr->mac_addr_str;
 	ctlr->input->name = name;
 	input_set_drvdata(ctlr->input, ctlr);
 
@@ -1250,6 +1253,41 @@ static int joycon_power_supply_create(struct joycon_ctlr *ctlr)
 	return 0;
 }
 
+static int joycon_read_mac(struct joycon_ctlr *ctlr)
+{
+	int ret;
+	int i;
+	int j;
+	struct joycon_subcmd_request req = { 0 };
+	struct joycon_input_report *report;
+
+	req.subcmd_id = JC_SUBCMD_REQ_DEV_INFO;
+	ret = joycon_send_subcmd(ctlr, &req, 0, HZ);
+	if (ret) {
+		hid_err(ctlr->hdev, "Failed to get joycon info; ret=%d\n", ret);
+		return ret;
+	}
+
+	report = (struct joycon_input_report *)ctlr->input_buf;
+
+	for (i = 4, j = 0; j < 6; i++, j++)
+		ctlr->mac_addr[j] = report->reply.data[i];
+
+	ctlr->mac_addr_str = devm_kasprintf(&ctlr->hdev->dev, GFP_KERNEL,
+					    "%02X:%02X:%02X:%02X:%02X:%02X",
+					    ctlr->mac_addr[0],
+					    ctlr->mac_addr[1],
+					    ctlr->mac_addr[2],
+					    ctlr->mac_addr[3],
+					    ctlr->mac_addr[4],
+					    ctlr->mac_addr[5]);
+	if (!ctlr->mac_addr_str)
+		return -ENOMEM;
+	hid_info(ctlr->hdev, "controller MAC = %s\n", ctlr->mac_addr_str);
+
+	return 0;
+}
+
 /* Common handler for parsing inputs */
 static int joycon_ctlr_read_handler(struct joycon_ctlr *ctlr, u8 *data,
 							      int size)
@@ -1428,6 +1466,13 @@ static int nintendo_hid_probe(struct hid_device *hdev,
 		goto err_mutex;
 	}
 
+	ret = joycon_read_mac(ctlr);
+	if (ret) {
+		hid_err(hdev, "Failed to retrieve controller MAC; ret=%d\n",
+			ret);
+		goto err_close;
+	}
+
 	mutex_unlock(&ctlr->output_mutex);
 
 	ret = joycon_input_create(ctlr);
Signature · 1 line
2.23.0

A message that is not in the archive (sent off-list or not yet received): CAKF84v1MoJFURpipRaAYA-T7+ZDz=9LvmXQnNYzDHeVX3B7WbQ@mail.gmail.com

#12 lore raw

Hi Siarhei,

Thanks for your time reviewing the driver, but there are some missing points below:

Quoted 18 lines · Siarhei Vishniakou

Hi Daniel,

I have a couple additional suggestions for this driver, mainly around probe / remove.

For typical touchscreen drivers, during probe(), the following pattern is followed:

probe () {
    error = input_register_device(info->input_dev);
    if (error) {
        goto some_error_label;
    }
    error = do_more_stuff();
    if (error) {
        goto error_after_input_register;
    }
error_after_input_register:
   input_unregister_device(info->input_dev);
Quoted 4 lines

some_error_label: // pass
}
And likewise, "input_unregister_device" will be called in "remove". Searching through hid-nintendo, I don't see any calls to "input_unregister_device".

This is because Daniel used the managed version devm_input_allocate_device():

* Managed input devices do not need to be explicitly unregistered or
* freed as it will be done automatically when owner device unbinds from
* its driver (or binding fails). Once managed input device is allocated,
* it is ready to be set up and registered in the same fashion as regular
* input device. There are no special devm_input_device_[un]register()
* variants, regular ones work with both managed and unmanaged devices,
* should you need them. In most cases however, managed input device need
* not be explicitly unregistered or freed.

Quoted 12 lines

Another thing that I noticed is the usage of the following pattern during probe:
probe() {
joycon_input_create()
joycon_leds_create()
}

Here, each of the two above functions requires communication with the controller using the commands.
The joystick might be already sending out the event reports during this time.
But in this case, probe() is still not finished. So there will be a mixture of commands and event reports coming in to the driver. Currently, this is guarded against by using joycon_ctlr_state, and all events received while probe hasn't finished are being dropped.

Quoted 4 lines

From the userspace, it will look like an input device is registered, but it is essentially guaranteed to not receive any events for some additional time because the events will be silently dropped (since probe is still not finished).

I suggest rearranging the probe code to first collect all of the initialization information from the driver using commands, and then start registering the devices with the system. Since currently the probe fails if some of the commands are not responded to properly, this would also prevent having to register/unregister devices during probe in case of errors.

Well, the code already does the initialization first, and then registers the user-space components.
But I agree that we should register the input node last, so that when userspace sees the input node, it will be able to look for the player LEDs and do the association without a race. So we need to first register power (it's independent of the rest), then LEDs, then input.

Quoted 2 lines

Another minor suggestion is to change joycon_ctlr_state into a bool probe_completed (or something like bool ready_to_process), I think it would be a bit more readable.

Well, right now it is a binary state, and maybe you are right, it might be more readable. But I have a feeling we will soon need a JOYCON_CTLR_STATE_DESTROY, and the enum will make more sense.

Quoted 2 lines

Thanks for your hard work on this!

Thanks for the look :)

Daniel, I am still planning to do a full review on it before v5.6 gets opened. No guarantees I'll be able to squeeze it this week, so I would appreciate any of the previous reviewers some time to also review this version :)

Cheers,
Benjamin

Quoted 113 lines

вт, 5 нояб. 2019 г. в 22:06, Daniel J. Ogorchock <[email protected]>:

Quoted 111 lines

This is a pretty minor change. Importantly it resolves a couple compiler errors when building the driver with a version of gcc prior to 8. It seems that gcc 8 and above are more relaxed about using const integers to initialize other const values and in case statement matching.

It also sets the input device's uniq value to the controller's MAC address. This will be useful once gyro/accelerometer support is added in the future (likely as a second input device). Since the joy-cons can also be used via uart on the nintendo switch's serial rails, this is also a useful mechanism for associating one joy-con between two drivers (hid-nintendo and any serdev joy-con driver written to run on the nintendo switch itself).

Version 9 changes:
- Fixed compiler errors on gcc versions older than 8.2
- Set input device's uniq value to the controller's MAC address

Version 8 changes:
- Corrected the handshaking protocol with USB pro controllers. A handshake now occurs both prior and after the baudrate set. This doesn't appear to have a noticeable difference, but it more accurately follows documentation found online.
- Fixed potential race condition which could lead to a slightly longer delay sending subcommands in rare circumstances.
- Moved the rumble worker to its own workqueue, since it can block. This prevents it from having a negative impact on the default kernel workqueue. It also prevents dropped subcommands due to something else blocking the kernel workqueue. The benefit is most obvious when using multiple controllers at once, since the controller subcommand timings are very picky.
- Added a patch to set the most significant bit of the hid hw version. Roderick had mentioned needing to probably do this awhile ago, but I had forgotten about it until now. This is the same thing hid-sony does. It allows SDL2 to have different mappings for the hid-nintendo driver vs the default hid mappings.

Version 7 changes:
- Changed name to hid-nintendo to fit modern naming conventions
- Removed joycon_ctlr_destroy(), since it wasn't needed an could potentially invalidate a mutex while it could be in use on other threads
- Implemented minor code improvements suggested by Silvan
- The driver now waits to send subcommands until after receiving an input report. This significantly reduces dropped subcommands.
- Reduced the number of error messages when disconnecting a controller.

Version 6 changes:
- Improved subcommand sending reliabilty
- Decreased rumble period to 50ms
- Added rumble queue to avoid missing ff_effects if sent too quickly
- Code cleanup and minor refactoring
- Added default analog stick calibration

Version 5 changes:
- Removed sysfs interface to control motor frequencies.
- Improved rumble reliability by using subcommands to set it.
- Changed mapping of the SL/SR triggers on the joy-cons to map to whichever triggers they lack (e.g. a left joycon's sl/sr map to TR and TR2). This allows userspace to distinguish between the normal and S triggers.
- Minor refactors

Version 4 changes:
- Added support for the Home button LED for the pro controller and right joy-con
- Changed name from hid-switchcon to hid-joycon
- Added rumble support
- Removed ctlr->type and use hdev->product instead
- Use POWER_SUPPLY_CAPACITY_LEVEL enum instead of manually translating to capacity percentages
- Misc. minor refactors based on v3 feedback

Version 3 changes:
- Added led_classdev support for the 4 player LEDs
- Added power_supply support for the controller's battery
- Made the controller number mutex static
- Minor refactoring/style fixes based on Roderick's feedback from v2

Version 2 changes:
- Switched to using a synchronous method for configuring the controller.
- Removed any pairing/orientation logic in the driver. Every controller now corresponds to its own input device.
- Store controller button data as a single u32.
- Style corrections

Daniel J. Ogorchock (10):
HID: nintendo: add nintendo switch controller driver
HID: nintendo: add player led support
HID: nintendo: add power supply support
HID: nintendo: add home led support
HID: nintendo: add rumble support
HID: nintendo: improve subcommand reliability
HID: nintendo: send subcommands after receiving input report
HID: nintendo: reduce device removal subcommand errors
HID: nintendo: patch hw version for userspace HID mappings
HID: nintendo: set controller uniq to MAC

 MAINTAINERS                |    6 +
 drivers/hid/Kconfig        |   24 +
 drivers/hid/Makefile       |    1 +
 drivers/hid/hid-ids.h      |    3 +
 drivers/hid/hid-nintendo.c | 1558 ++++++++++++++++++++++++++++++++++++
 5 files changed, 1592 insertions(+)
 create mode 100644 drivers/hid/hid-nintendo.c

--
2.23.0