HID: nintendo: Add preliminary Switch 2 controller driver
Subsystems (3)
Vicki Pfau
maintainerv5 cover HID: nintendo: Add preliminary Switch 2 controller driver
This series adds preliminary support for Switch 2 controllers using the same split-driver model as previous versions. This is a minor iteration on v4, fixing some leaked input_dev objects in error paths as well as fixing a merge/rebase error when CONFIG_PM ifdefs got removed in 7.0.
Vicki Pfau (3):
HID: nintendo: Add preliminary Switch 2 controller driver
HID: nintendo: Add rumble support for Switch 2 controllers
HID: nintendo: Add unified report format support
MAINTAINERS | 1 + drivers/hid/Kconfig | 19 +- drivers/hid/hid-ids.h | 4 + drivers/hid/hid-nintendo.c | 1504 ++++++++++++++++- drivers/hid/hid-nintendo.h | 72 + drivers/input/joystick/Kconfig | 11 + drivers/input/joystick/Makefile | 1 + drivers/input/joystick/nintendo-switch2-usb.c | 353 ++++ 8 files changed, 1951 insertions(+), 14 deletions(-) create mode 100644 drivers/hid/hid-nintendo.h create mode 100644 drivers/input/joystick/nintendo-switch2-usb.c
Signature · 1 line
2.54.0
Vicki Pfau
maintainerPATCH v5 1/3 HID: nintendo: Add preliminary Switch 2 controller driver
This adds a new driver for the Switch 2 controllers. The Switch 2 uses an unusual split-interface design such that input and rumble occur on the main HID interface, but all other communication occurs over a "configuration" interface. This is the case on both USB and Bluetooth, so this new driver uses a split-driver design with the HID interface being the "main" driver and the configuration interface is a secondary driver that looks up to the HID interface, sharing resources on a common struct.
Due to using a non-standard pairing interface as well as Bluetooth communications being extremely limited in the kernel, a custom interface between userspace and the kernel will need to be designed, along with bringup in BlueZ. That is beyond the scope of this initial patch, which only contains the generic HID and USB configuration interface drivers.
This initial work supports general input for the Joy-Con 2, Pro Controller 2, and GameCube NSO controllers. IMU, rumble and battery support is not yet present.
--- MAINTAINERS | 1 + drivers/hid/Kconfig | 11 +- drivers/hid/hid-ids.h | 4 + drivers/hid/hid-nintendo.c | 1191 ++++++++++++++++- drivers/hid/hid-nintendo.h | 72 + drivers/input/joystick/Kconfig | 11 + drivers/input/joystick/Makefile | 1 + drivers/input/joystick/nintendo-switch2-usb.c | 353 +++++ 8 files changed, 1634 insertions(+), 10 deletions(-) create mode 100644 drivers/hid/hid-nintendo.h create mode 100644 drivers/input/joystick/nintendo-switch2-usb.c
MAINTAINERS +1 -0
@@ -18882,6 +18882,7 @@ F: drivers/scsi/nsp32* NINTENDO HID DRIVER M: Daniel J. Ogorchock <[email protected]> +M: Vicki Pfau <[email protected]> L: [email protected] S: Maintained F: drivers/hid/hid-nintendo*
drivers/hid/Kconfig +7 -4
@@ -843,10 +843,13 @@ config HID_NINTENDO depends on LEDS_CLASS select POWER_SUPPLY help - Adds support for the Nintendo Switch Joy-Cons, NSO, Pro Controller. - All controllers support bluetooth, and the Pro Controller also supports - its USB mode. This also includes support for the Nintendo Switch Online - Controllers which include the NES, Genesis, SNES, and N64 controllers. + Adds support for the Nintendo Switch Joy-Cons, NSO, Pro Controller, as + well as Nintendo Switch 2 Joy-Cons, Pro Controller, and NSO GameCube + controllers. All Switch controllers support bluetooth, and the Pro + Controller also supports its USB mode. This also includes support for + the Nintendo Switch Online Controllers which include the NES, Genesis, + SNES, and N64 controllers. Switch 2 controllers currently only support + USB mode. To compile this driver as a module, choose M here: the module will be called hid-nintendo.
drivers/hid/hid-ids.h +4 -0
@@ -1098,6 +1098,10 @@#define USB_DEVICE_ID_NINTENDO_SNESCON 0x2017#define USB_DEVICE_ID_NINTENDO_GENCON 0x201e#define USB_DEVICE_ID_NINTENDO_N64CON 0x2019 +#define USB_DEVICE_ID_NINTENDO_NS2_JOYCONR 0x2066 +#define USB_DEVICE_ID_NINTENDO_NS2_JOYCONL 0x2067 +#define USB_DEVICE_ID_NINTENDO_NS2_PROCON 0x2069 +#define USB_DEVICE_ID_NINTENDO_NS2_GCCON 0x2073#define USB_VENDOR_ID_NOVATEK 0x0603#define USB_DEVICE_ID_NOVATEK_PCT 0x0600
drivers/hid/hid-nintendo.c +1185 -6
1,270 lines not on this page · raw message
drivers/hid/hid-nintendo.h new file +72 -0
72 lines not on this page · raw message
drivers/input/joystick/Kconfig +11 -0
@@ -422,4 +422,15 @@ config JOYSTICK_SEESAW To compile this driver as a module, choose M here: the module will be called adafruit-seesaw. +config JOYSTICK_NINTENDO_SWITCH2_USB + tristate "Wired Nintendo Switch 2 controller support" + depends on HID_NINTENDO + depends on USB + help + Say Y here if you want to enable support for wired Nintendo Switch 2 + controllers. + + To compile this driver as a module, choose M here: the + module will be called nintendo-switch2-usb. + endif
drivers/input/joystick/Makefile +1 -0
@@ -34,6 +34,7 @@ obj-$(CONFIG_JOYSTICK_SIDEWINDER) += sidewinder.o obj-$(CONFIG_JOYSTICK_SPACEBALL) += spaceball.o obj-$(CONFIG_JOYSTICK_SPACEORB) += spaceorb.o obj-$(CONFIG_JOYSTICK_STINGER) += stinger.o +obj-$(CONFIG_JOYSTICK_NINTENDO_SWITCH2_USB) += nintendo-switch2-usb.o obj-$(CONFIG_JOYSTICK_TMDC) += tmdc.o obj-$(CONFIG_JOYSTICK_TURBOGRAFX) += turbografx.o obj-$(CONFIG_JOYSTICK_TWIDJOY) += twidjoy.o
drivers/input/joystick/nintendo-switch2-usb.c new file +353 -0
353 lines not on this page · raw message
Signature · 1 line
2.54.0
[email protected]
AI reviewThank you for your contribution! Sashiko AI review found 11 potential issue(s) to consider: - [High] Sleeping in atomic context and AB-BA deadlock in `switch2_usb_disconnect` - [High] Race condition…
Thank you for your contribution! Sashiko AI review found 11 potential issue(s) to consider:
- [High] Sleeping in atomic context and AB-BA deadlock in switch2_usb_disconnect
- [High] Race condition in IN URB tracking causes permanent starvation
- [High] Dangling pointers and use-after-free on probe failure
- [High] Memory corruption and double free due to incorrect devm input lifecycle management
- [High] NULL pointer dereference in USB probe error path
- [High] Division by zero crash from unvalidated trigger calibration data
- [High] BUG_ON kernel panic when ida_free is called with U32_MAX
- [High] Out-of-bounds read when parsing NS2_CMD_FW_INFO response
- [High] Race condition due to URB submission before initialization of synchronization primitives
- [Medium] Infinite USB retry storm on protocol errors
- [Medium] Unaligned memory access on byte array casts
--
commit 00cb7265ad5983144c6923702e2ee2c3c047d29e
Author: Vicki Pfau <[email protected]>
Subject: HID: nintendo: Add preliminary Switch 2 controller driver
This adds a new driver for the Switch 2 controllers. The Switch 2 uses an unusual split-interface design such that input and rumble occur on the main HID interface, but all other communication occurs over a "configuration" interface.
Quoted 4 lines
drivers/hid/hid-nintendo.c +0
-0
[ ... ]
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+static int switch2_init_input (struct switch2_controller *ns2) +{
[ ... ]
Quoted 3 lines
drivers/hid/hid-nintendo.c +3
-0+ input =devm_input_allocate_device (&hdev->dev); +if (!input) +return -ENOMEM ;
[ ... ]
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3238
Quoted 4 lines
drivers/hid/hid-nintendo.c +4
-0+ ret =input_register_device (input); +if (ret <0 ) { +hid_err (ns2->hdev,"Failed to register input; ret=%d\n" , ret); +input_free_device (input);
Calling input_free_device or input_unregister_device on a devm-managed input device can cause double frees when devres cleanup fires. Can this lead to memory corruption?
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+return ret; + }
[ ... ]
Quoted 4 lines
drivers/hid/hid-nintendo.c +4
-0+static void switch2_controller_put (struct switch2_controller *ns2) +{ +struct input_dev *input; +bool do_free;
[ ... ]
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3309
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+if (input) +input_unregister_device (input);
Calling input_unregister_device on a devm-managed input device can cause issues. If the input device remains alive (tied to the HID device devres) and its child LEDs are not released, will reconnecting the USB cable allocate a new input device and corrupt the LED lists by re-registering the exact same ns2->leds structures?
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+ +if (do_free) {
[ ... ]
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3502
Quoted 3 lines
drivers/hid/hid-nintendo.c +3
-0+static void switch2_report_trigger (struct input_dev *input,uint8_t zero,int abs,uint8_t data) +{ +int value = (NS2_TRIGGER_RANGE +1 ) * (data - zero) / (232 - zero);
The zero variable is loaded directly from the controller's factory calibration flash. If a device reports a zero point of exactly 232, will this trigger a division by zero exception and crash the kernel?
Quoted 3 lines
drivers/hid/hid-nintendo.c +3
-0+ +input_report_abs (input, abs,clamp (value,0 ,NS2_TRIGGER_RANGE )); +}
[ ... ]
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3597
Quoted 8 lines
drivers/hid/hid-nintendo.c +8
-0+static int switch2_read_flash (struct switch2_controller *ns2,uint32_t address, +uint8_t size) +{ +uint8_t message[8 ] = { size,0x7e }; + +if (!ns2->cfg) +return -ENOTCONN ; + *(__le32 *)&message[4 ] =__cpu_to_le32 (address);
The driver directly casts &message[4] to __le32. Since message is a uint8_t array, it is only guaranteed to be 1-byte aligned. On strict architectures, will this unaligned memory write trigger a hardware alignment fault?
Quoted 3 lines
drivers/hid/hid-nintendo.c +3
-0+return ns2->cfg->send_command (NS2_CMD_FLASH ,NS2_SUBCMD_FLASH_READ , message, +sizeof (message), ns2->cfg); +}
[ ... ]
Quoted 3 lines
drivers/hid/hid-nintendo.c +3
-0+int switch2_receive_command (struct switch2_controller *ns2, +const uint8_t *message,size_t length) +{
[ ... ]
Quoted 7 lines
drivers/hid/hid-nintendo.c +7
-0+ header = (const struct switch2_cmd_header *)message; +if (!(header->flags &NS2_FLAG_OK )) { + ret = -EIO ; + goto exit; + } + message = &message[8 ]; +switch (header->command) {
[ ... ]
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3773
Quoted 7 lines
drivers/hid/hid-nintendo.c +7
-0+case NS2_CMD_FW_INFO : +if (header->subcommand ==NS2_SUBCMD_FW_INFO_GET ) { +if (length <sizeof (ns2->version)) { + ret = -EINVAL ; + goto exit; + } +memcpy (&ns2->version, message,sizeof (ns2->version));
The message pointer is advanced by 8 bytes to skip the header, but length is not decremented. The bounds check compares length against sizeof(ns2->version). If length is exactly sizeof(ns2->version), the check passes, but the advanced message pointer only has length - 8 valid bytes remaining. Will the memcpy over-read into uninitialized memory?
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3784
Quoted 11 lines
drivers/hid/hid-nintendo.c +11
-0+ ns2->ctlr_type = ns2->version.ctlr_type; +switch2_init_step_done (ns2,NS2_INIT_GET_FIRMWARE_INFO ); + } +break ; +default : +break ; + } + +exit: +if (ns2->init_step <NS2_INIT_DONE ) +switch2_init_controller (ns2);
If a command response has the NACK flag set or encounters another error, the code jumps to exit and invokes switch2_init_controller. Since ns2->init_step has not advanced, the state machine will immediately re-send the exact same command. Can this cause an infinite tight feedback loop of failures and retries, flooding the USB bus?
Quoted 3 lines
drivers/hid/hid-nintendo.c +3
-0+ +return ret; +}
[ ... ]
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+int switch2_controller_attach_cfg (const char *phys,struct switch2_cfg_intf *cfg) +{
[ ... ]
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3804
Quoted 6 lines
drivers/hid/hid-nintendo.c +6
-0+guard (mutex)(&ns2->lock); +WARN_ON (ns2->cfg); + ns2->cfg = cfg; + +if (ns2->hdev) +return switch2_init_controller (ns2);
If switch2_init_controller fails here or in switch2_probe, the error is returned immediately without unrolling the state. Will ns2->cfg or ns2->hdev remain set, potentially leading to a use-after-free when subsequent device events occur?
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+return 0 ; +}
[ ... ]
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3908
Quoted 10 lines
drivers/hid/hid-nintendo.c +10
-0+static void switch2_remove (struct hid_device *hdev) +{ +struct switch2_controller *ns2 =hid_get_drvdata (hdev); + +hid_hw_close (hdev); +mutex_lock (&ns2->lock); +WARN_ON (ns2->hdev != hdev); + ns2->hdev =NULL ; +mutex_unlock (&ns2->lock); +ida_free (&nintendo_player_id_allocator, ns2->player_id);
If ida_alloc fails during probe, ns2->player_id remains at its default value of U32_MAX. When ida_free is called, the IDA framework enforces a check on the ID. Casting U32_MAX to a signed integer yields -1. Will this trigger the BUG_ON and cause a kernel panic?
Quoted 3 lines
drivers/hid/hid-nintendo.c +3
-0+switch2_controller_put (ns2); +hid_hw_stop (hdev); +}
[ ... ]
Quoted 5 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +0
-0
[ ... ]
Quoted 2 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +2
-0+static void switch2_bulk_in (struct urb *urb) +{
[ ... ]
drivers/input/joystick/nintendo-switch2-usb.c line 72
Quoted 7 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +7
-0+spin_lock_irqsave (&ns2_usb->bulk_in_lock, flags); +for (i =0 ; i <NS2_IN_URBS ; i++) { +int err; +struct switch2_urb *ns2_urb; + +if (ns2_usb->bulk_in[i].urb == urb) { + ns2_usb->message_in = i;
If multiple URBs complete in quick succession before the work item executes, the message_in index is overwritten. Will this cause the work item to only process the last completed URB, leaving earlier URBs indefinitely active and leading to starvation of the URB pool?
Quoted 2 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +2
-0+continue ; + }
[ ... ]
Quoted 2 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +2
-0+static int switch2_usb_probe (struct usb_interface *intf,const struct usb_device_id *id) +{
[ ... ]
drivers/input/joystick/nintendo-switch2-usb.c line 271
Quoted 10 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +10
-0+ ns2_usb->bulk_in[0 ].active = true; + ret =usb_submit_urb (ns2_usb->bulk_in[0 ].urb,GFP_ATOMIC ); +if (ret <0 ) + goto err_free_out; + +init_usb_anchor (&ns2_usb->bulk_out_anchor); +spin_lock_init (&ns2_usb->bulk_out_lock); +init_usb_anchor (&ns2_usb->bulk_in_anchor); +spin_lock_init (&ns2_usb->bulk_in_lock); +INIT_WORK (&ns2_usb->message_in_work, switch2_usb_message_in_work);
usb_submit_urb is invoked for bulk_in[0] before the initialization of the spinlocks, anchors, and work struct. If the URB completes immediately, the completion handler will execute and attempt to use uninitialized synchronization primitives. Can this cause a crash?
Quoted 2 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +2
-0+ +usb_set_intfdata (intf, ns2_usb);
[ ... ]
drivers/input/joystick/nintendo-switch2-usb.c line 295
Quoted 12 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +12
-0+err_kill_urb: +usb_kill_urb (ns2_usb->bulk_in[0 ].urb); +err_free_out: +for (i =0 ; i <NS2_OUT_URBS ; i++) { +usb_free_coherent (ns2_usb->udev,NS2_BULK_SIZE , ns2_usb->bulk_out[i].data, + ns2_usb->bulk_out[i].urb->transfer_dma); +usb_free_urb (ns2_usb->bulk_out[i].urb); + } +err_free_in: +for (i =0 ; i <NS2_IN_URBS ; i++) { +usb_free_coherent (ns2_usb->udev,NS2_BULK_SIZE , ns2_usb->bulk_in[i].data, + ns2_usb->bulk_in[i].urb->transfer_dma);
If usb_alloc_urb fails during the loop, it jumps to err_free_in. During cleanup, it accesses ns2_usb->bulk_in[i].urb->transfer_dma. Since urb is NULL for the failed index, will this trigger a NULL pointer dereference?
Quoted 5 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +5
-0+usb_free_urb (ns2_usb->bulk_in[i].urb); + } +devm_kfree (&intf->dev, ns2_usb); + +return ret;
drivers/input/joystick/nintendo-switch2-usb.c line 310
Quoted 10 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +10
-0+} + +static void switch2_usb_disconnect (struct usb_interface *intf) +{ +struct switch2_usb *ns2_usb =usb_get_intfdata (intf); +unsigned long flags; +int i; + +spin_lock_irqsave (&ns2_usb->bulk_out_lock, flags); +usb_kill_anchored_urbs (&ns2_usb->bulk_out_anchor);
Both usb_kill_anchored_urbs and cancel_work_sync can sleep. Is it safe to call them while holding a spinlock?
drivers/input/joystick/nintendo-switch2-usb.c line 320
Quoted 10 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +10
-0+for (i =0 ; i <NS2_OUT_URBS ; i++) { +usb_free_coherent (ns2_usb->udev,NS2_BULK_SIZE , ns2_usb->bulk_out[i].data, + ns2_usb->bulk_out[i].urb->transfer_dma); +usb_free_urb (ns2_usb->bulk_out[i].urb); + } +spin_unlock_irqrestore (&ns2_usb->bulk_out_lock, flags); + +spin_lock_irqsave (&ns2_usb->bulk_in_lock, flags); +usb_kill_anchored_urbs (&ns2_usb->bulk_in_anchor); +cancel_work_sync (&ns2_usb->message_in_work);
Furthermore, cancel_work_sync waits for message_in_work which attempts to acquire bulk_in_lock. Does this cause a deadlock since the lock is already held by the disconnecting thread?
Quoted 1 line
drivers/input/joystick/nintendo-switch2-usb.c new file +1
-0+for (i =0 ; i <NS2_IN_URBS ; i++) {
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Heyhey!
Below some comments regarding the findings (note that I am not an expert on neither Linux kernel drivers in general nor USB HID specifically).
Quoted 35 lines · [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 11 potential issue(s) to consider:
- [High] Sleeping in atomic context and AB-BA deadlock inswitch2_usb_disconnect
- [High] Race condition in IN URB tracking causes permanent starvation
- [High] Dangling pointers and use-after-free on probe failure
- [High] Memory corruption and double free due to incorrect devm input lifecycle management
- [High] NULL pointer dereference in USB probe error path
- [High] Division by zero crash from unvalidated trigger calibration data
- [High]BUG_ONkernel panic whenida_freeis called withU32_MAX
- [High] Out-of-bounds read when parsingNS2_CMD_FW_INFOresponse
- [High] Race condition due to URB submission before initialization of synchronization primitives
- [Medium] Infinite USB retry storm on protocol errors
- [Medium] Unaligned memory access on byte array casts
--commit
00cb7265ad5983144c6923702e2ee2c3c047d29e
Author: Vicki Pfau <[email protected]>
Subject: HID: nintendo: Add preliminary Switch 2 controller driverThis adds a new driver for the Switch 2 controllers. The Switch 2 uses an unusual split-interface design such that input and rumble occur on the main HID interface, but all other communication occurs over a "configuration" interface.
Quoted 4 lines
drivers/hid/hid-nintendo.c +0
-0[ ... ]
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+static int switch2_init_input (struct switch2_controller *ns2) +{[ ... ]
Quoted 3 lines
drivers/hid/hid-nintendo.c +3
-0+ input =devm_input_allocate_device (&hdev->dev); +if (!input) +return -ENOMEM ;[ ... ]
Quoted 8 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3238
Quoted 4 lines
drivers/hid/hid-nintendo.c +4
-0+ ret =input_register_device (input); +if (ret <0 ) { +hid_err (ns2->hdev,"Failed to register input; ret=%d\n" , ret); +input_free_device (input);Calling
input_free_deviceorinput_unregister_deviceon a devm-managed input device can cause double frees when devres cleanup fires. Can this lead to memory corruption?
I think sashiko is actually correct here, unfortunately. The documentation for devm_input_allocate_device states that
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). ...
Looks like we can remove all the input_unregister_device and input_free_device calls here.
Quoted 9 lines
Quoted 3 lines
drivers/hid/hid-nintendo.c +2
-0+return ret; + }[ ... ]
Quoted 4 lines
drivers/hid/hid-nintendo.c +4
-0+static void switch2_controller_put (struct switch2_controller *ns2) +{ +struct input_dev *input; +bool do_free;[ ... ]
Quoted 8 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3309
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+if (input) +input_unregister_device (input);Calling
input_unregister_deviceon a devm-managed input device can cause issues. If the input device remains alive (tied to the HID device devres) and its child LEDs are not released, will reconnecting the USB cable allocate a new input device and corrupt the LED lists by re-registering the exact samens2->ledsstructures?
This input_unregister_device can also be removed.
Quoted 11 lines
Quoted 3 lines
drivers/hid/hid-nintendo.c +2
-0+ +if (do_free) {[ ... ]
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3502
Quoted 3 lines
drivers/hid/hid-nintendo.c +3
-0+static void switch2_report_trigger (struct input_dev *input,uint8_t zero,int abs,uint8_t data) +{ +int value = (NS2_TRIGGER_RANGE +1 ) * (data - zero) / (232 - zero);The zero variable is loaded directly from the controller's factory calibration flash. If a device reports a zero point of exactly 232, will this trigger a division by zero exception and crash the kernel?
Not sure this is an issue in practice, but we might want to protect the code in any case by doing something like the below perhaps (untested).
int value = (NS2_TRIGGER_RANGE + 1) * (data - zero) / max_t(int, (232 - zero), 1);
Quoted 5 lines
Quoted 4 lines
drivers/hid/hid-nintendo.c +3
-0+ +input_report_abs (input, abs,clamp (value,0 ,NS2_TRIGGER_RANGE )); +}[ ... ]
Quoted 12 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3597
Quoted 8 lines
drivers/hid/hid-nintendo.c +8
-0+static int switch2_read_flash (struct switch2_controller *ns2,uint32_t address, +uint8_t size) +{ +uint8_t message[8 ] = { size,0x7e }; + +if (!ns2->cfg) +return -ENOTCONN ; + *(__le32 *)&message[4 ] =__cpu_to_le32 (address);The driver directly casts &message[4] to
__le32. Since message is auint8_tarray, it is only guaranteed to be 1-byte aligned. On strict architectures, will this unaligned memory write trigger a hardware alignment fault?
I assume this could be an issue and we should just use something like the below (only compile-tested).
put_unaligned_le32(__cpu_to_le32(address), &message[4]);
Quoted 17 lines
Quoted 4 lines
drivers/hid/hid-nintendo.c +3
-0+return ns2->cfg->send_command (NS2_CMD_FLASH ,NS2_SUBCMD_FLASH_READ , message, +sizeof (message), ns2->cfg); +}[ ... ]
Quoted 3 lines
drivers/hid/hid-nintendo.c +3
-0+int switch2_receive_command (struct switch2_controller *ns2, +const uint8_t *message,size_t length) +{[ ... ]
Quoted 7 lines
drivers/hid/hid-nintendo.c +7
-0+ header = (const struct switch2_cmd_header *)message; +if (!(header->flags &NS2_FLAG_OK )) { + ret = -EIO ; + goto exit; + } + message = &message[8 ]; +switch (header->command) {[ ... ]
Quoted 13 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3773
Quoted 7 lines
drivers/hid/hid-nintendo.c +7
-0+case NS2_CMD_FW_INFO : +if (header->subcommand ==NS2_SUBCMD_FW_INFO_GET ) { +if (length <sizeof (ns2->version)) { + ret = -EINVAL ; + goto exit; + } +memcpy (&ns2->version, message,sizeof (ns2->version));The message pointer is advanced by 8 bytes to skip the header, but length is not decremented. The bounds check compares length against
sizeof(ns2->version). If length is exactlysizeof(ns2->version), the check passes, but the advanced message pointer only has length - 8 valid bytes remaining. Will the memcpy over-read into uninitialized memory?
Sounds like something that we should fix by either decreasing length or increasing the size in the check.
Quoted 10 lines
Quoted 10 lines
drivers/hid/hid-nintendo.c +9
-0+ ns2->ctlr_type = ns2->version.ctlr_type; +switch2_init_step_done (ns2,NS2_INIT_GET_FIRMWARE_INFO ); + } +break ; +default : +break ; + } + +exit:
Quoted 8 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3784
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+if (ns2->init_step <NS2_INIT_DONE ) +switch2_init_controller (ns2);If a command response has the NACK flag set or encounters another error, the code jumps to exit and invokes
switch2_init_controller. Sincens2->init_stephas not advanced, the state machine will immediately re-send the exact same command. Can this cause an infinite tight feedback loop of failures and retries, flooding the USB bus?
We have discussed this before and it doesn't seem to be an issue in practice.
If we want to be on the safe side, we could pass a retry count and abort on too many error retries, perhaps?
Quoted 7 lines
Quoted 3 lines
drivers/hid/hid-nintendo.c +3
-0+ +return ret; +}[ ... ]
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+int switch2_controller_attach_cfg (const char *phys,struct switch2_cfg_intf *cfg) +{[ ... ]
Quoted 11 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3804
Quoted 6 lines
drivers/hid/hid-nintendo.c +6
-0+guard (mutex)(&ns2->lock); +WARN_ON (ns2->cfg); + ns2->cfg = cfg; + +if (ns2->hdev) +return switch2_init_controller (ns2);If
switch2_init_controllerfails here or inswitch2_probe, the error is returned immediately without unrolling the state. Willns2->cfgorns2->hdevremain set, potentially leading to a use-after-free when subsequent device events occur?
AFAICT, since we are always checking for both ns2->cfg and ns2->hdev before doing any processing in switch2_init_controller, there should never be a use-after-free
It *is* true that we don't call hid_hw_{close,stop} in switch2_probe, if the switch2_init_controller call fails though. It might make sense to return a specific error and use it to check whether we want to give up and call these?
Quoted 4 lines
Quoted 3 lines
drivers/hid/hid-nintendo.c +2
-0+return 0 ; +}[ ... ]
Quoted 15 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3908
Quoted 10 lines
drivers/hid/hid-nintendo.c +10
-0+static void switch2_remove (struct hid_device *hdev) +{ +struct switch2_controller *ns2 =hid_get_drvdata (hdev); + +hid_hw_close (hdev); +mutex_lock (&ns2->lock); +WARN_ON (ns2->hdev != hdev); + ns2->hdev =NULL ; +mutex_unlock (&ns2->lock); +ida_free (&nintendo_player_id_allocator, ns2->player_id);If
ida_allocfails during probe,ns2->player_idremains at its default value ofU32_MAX. Whenida_freeis called, the IDA framework enforces a check on the ID. CastingU32_MAXto a signed integer yields -1. Will this trigger theBUG_ONand cause a kernel panic?
ida_free seems to return early on
if ((int)id < 0)
return;
so that should be fine as is.
Quoted 33 lines
Quoted 4 lines
drivers/hid/hid-nintendo.c +3
-0+switch2_controller_put (ns2); +hid_hw_stop (hdev); +}[ ... ]
Quoted 5 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +0
-0[ ... ]
Quoted 2 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +2
-0+static void switch2_bulk_in (struct urb *urb) +{[ ... ]
drivers/input/joystick/nintendo-switch2-usb.c line 72
Quoted 7 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +7
-0+spin_lock_irqsave (&ns2_usb->bulk_in_lock, flags); +for (i =0 ; i <NS2_IN_URBS ; i++) { +int err; +struct switch2_urb *ns2_urb; + +if (ns2_usb->bulk_in[i].urb == urb) { + ns2_usb->message_in = i;If multiple URBs complete in quick succession before the work item executes, the
message_inindex is overwritten. Will this cause the work item to only process the last completed URB, leaving earlier URBs indefinitely active and leading to starvation of the URB pool?Quoted 2 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +2
-0+continue ; + }[ ... ]
Quoted 2 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +2
-0+static int switch2_usb_probe (struct usb_interface *intf,const struct usb_device_id *id) +{[ ... ]
Quoted 15 lines
drivers/input/joystick/nintendo-switch2-usb.c line 271
Quoted 10 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +10
-0+ ns2_usb->bulk_in[0 ].active = true; + ret =usb_submit_urb (ns2_usb->bulk_in[0 ].urb,GFP_ATOMIC ); +if (ret <0 ) + goto err_free_out; + +init_usb_anchor (&ns2_usb->bulk_out_anchor); +spin_lock_init (&ns2_usb->bulk_out_lock); +init_usb_anchor (&ns2_usb->bulk_in_anchor); +spin_lock_init (&ns2_usb->bulk_in_lock); +INIT_WORK (&ns2_usb->message_in_work, switch2_usb_message_in_work);
usb_submit_urbis invoked for bulk_in[0] before the initialization of the spinlocks, anchors, and work struct. If the URB completes immediately, the completion handler will execute and attempt to use uninitialized synchronization primitives. Can this cause a crash?
As the documentation for usb_submit_urb mentions that the call is async, I assume that this is indeed a theoretical possibility.
Quoted 4 lines
Quoted 3 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +2
-0+ +usb_set_intfdata (intf, ns2_usb);[ ... ]
Quoted 16 lines
drivers/input/joystick/nintendo-switch2-usb.c line 295
Quoted 12 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +12
-0+err_kill_urb: +usb_kill_urb (ns2_usb->bulk_in[0 ].urb); +err_free_out: +for (i =0 ; i <NS2_OUT_URBS ; i++) { +usb_free_coherent (ns2_usb->udev,NS2_BULK_SIZE , ns2_usb->bulk_out[i].data, + ns2_usb->bulk_out[i].urb->transfer_dma); +usb_free_urb (ns2_usb->bulk_out[i].urb); + } +err_free_in: +for (i =0 ; i <NS2_IN_URBS ; i++) { +usb_free_coherent (ns2_usb->udev,NS2_BULK_SIZE , ns2_usb->bulk_in[i].data, + ns2_usb->bulk_in[i].urb->transfer_dma);If
usb_alloc_urbfails during the loop, it jumps toerr_free_in. During cleanup, it accesses ns2_usb->bulk_in[i].urb->transfer_dma. Since urb is NULL for the failed index, will this trigger a NULL pointer dereference?
Yes, most likely we would need a new label for this case.
Quoted 11 lines
Quoted 11 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +10
-0+usb_free_urb (ns2_usb->bulk_in[i].urb); + } +devm_kfree (&intf->dev, ns2_usb); + +return ret; +} + +static void switch2_usb_disconnect (struct usb_interface *intf) +{ +struct switch2_usb *ns2_usb =usb_get_intfdata (intf);
Quoted 8 lines
drivers/input/joystick/nintendo-switch2-usb.c line 310
Quoted 5 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +5
-0+unsigned long flags; +int i; + +spin_lock_irqsave (&ns2_usb->bulk_out_lock, flags); +usb_kill_anchored_urbs (&ns2_usb->bulk_out_anchor);Both
usb_kill_anchored_urbsandcancel_work_synccan sleep. Is it safe to call them while holding a spinlock?
According to some googling, this indeed seems to be an isuse. The non-sleeping way to cancel transfer requests would be to use
https://www.kernel.org/doc/html/v6.1/driver-api/usb/usb.html#c.usb_unlink_anchored_urbs
Quoted 15 lines
drivers/input/joystick/nintendo-switch2-usb.c line 320
Quoted 11 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +10
-0+for (i =0 ; i <NS2_OUT_URBS ; i++) { +usb_free_coherent (ns2_usb->udev,NS2_BULK_SIZE , ns2_usb->bulk_out[i].data, + ns2_usb->bulk_out[i].urb->transfer_dma); +usb_free_urb (ns2_usb->bulk_out[i].urb); + } +spin_unlock_irqrestore (&ns2_usb->bulk_out_lock, flags); + +spin_lock_irqsave (&ns2_usb->bulk_in_lock, flags); +usb_kill_anchored_urbs (&ns2_usb->bulk_in_anchor); +cancel_work_sync (&ns2_usb->message_in_work);Furthermore,
cancel_work_syncwaits formessage_in_workwhich attempts to acquirebulk_in_lock. Does this cause a deadlock since the lock is already held by the disconnecting thread?
Yes, this looks like a real concern as well.
Cheers,
Silvan
Quoted 2 lines
Quoted 2 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +1
-0+for (i =0 ; i <NS2_IN_URBS ; i++) {
Vicki Pfau
maintainerQuoted 53 lines · Silvan Jegen
Heyhey!
Below some comments regarding the findings (note that I am not an expert on neither Linux kernel drivers in general nor USB HID specifically).
Quoted 35 lines · [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 11 potential issue(s) to consider:
- [High] Sleeping in atomic context and AB-BA deadlock inswitch2_usb_disconnect
- [High] Race condition in IN URB tracking causes permanent starvation
- [High] Dangling pointers and use-after-free on probe failure
- [High] Memory corruption and double free due to incorrect devm input lifecycle management
- [High] NULL pointer dereference in USB probe error path
- [High] Division by zero crash from unvalidated trigger calibration data
- [High]BUG_ONkernel panic whenida_freeis called withU32_MAX
- [High] Out-of-bounds read when parsingNS2_CMD_FW_INFOresponse
- [High] Race condition due to URB submission before initialization of synchronization primitives
- [Medium] Infinite USB retry storm on protocol errors
- [Medium] Unaligned memory access on byte array casts
--commit
00cb7265ad5983144c6923702e2ee2c3c047d29e
Author: Vicki Pfau <[email protected]>
Subject: HID: nintendo: Add preliminary Switch 2 controller driverThis adds a new driver for the Switch 2 controllers. The Switch 2 uses an unusual split-interface design such that input and rumble occur on the main HID interface, but all other communication occurs over a "configuration" interface.
Quoted 4 lines
drivers/hid/hid-nintendo.c +0
-0[ ... ]
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+static int switch2_init_input (struct switch2_controller *ns2) +{[ ... ]
Quoted 3 lines
drivers/hid/hid-nintendo.c +3
-0+ input =devm_input_allocate_device (&hdev->dev); +if (!input) +return -ENOMEM ;[ ... ]
Quoted 8 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3238
Quoted 4 lines
drivers/hid/hid-nintendo.c +4
-0+ ret =input_register_device (input); +if (ret <0 ) { +hid_err (ns2->hdev,"Failed to register input; ret=%d\n" , ret); +input_free_device (input);Calling
input_free_deviceorinput_unregister_deviceon a devm-managed input device can cause double frees when devres cleanup fires. Can this lead to memory corruption?I think sashiko is actually correct here, unfortunately. The documentation for
devm_input_allocate_devicestates that
Quoted 6 lines
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). ...
Looks like we can remove all the
input_unregister_deviceandinput_free_devicecalls here.
sashiko is not correct. See my previous reply.
Quoted 33 lines
Quoted 10 lines
Quoted 4 lines
drivers/hid/hid-nintendo.c +2
-0+return ret; + }[ ... ]
Quoted 4 lines
drivers/hid/hid-nintendo.c +4
-0+static void switch2_controller_put (struct switch2_controller *ns2) +{ +struct input_dev *input; +bool do_free;[ ... ]
Quoted 8 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3309
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+if (input) +input_unregister_device (input);Calling
input_unregister_deviceon a devm-managed input device can cause issues. If the input device remains alive (tied to the HID device devres) and its child LEDs are not released, will reconnecting the USB cable allocate a new input device and corrupt the LED lists by re-registering the exact samens2->ledsstructures?This
input_unregister_devicecan also be removed.Quoted 11 lines
Quoted 3 lines
drivers/hid/hid-nintendo.c +2
-0+ +if (do_free) {[ ... ]
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3502
Quoted 3 lines
drivers/hid/hid-nintendo.c +3
-0+static void switch2_report_trigger (struct input_dev *input,uint8_t zero,int abs,uint8_t data) +{ +int value = (NS2_TRIGGER_RANGE +1 ) * (data - zero) / (232 - zero);The zero variable is loaded directly from the controller's factory calibration flash. If a device reports a zero point of exactly 232, will this trigger a division by zero exception and crash the kernel?
Quoted 6 lines
Not sure this is an issue in practice, but we might want to protect the code in any case by doing something like the below perhaps (untested).
int value = (
NS2_TRIGGER_RANGE+ 1) * (data - zero) /max_t(int, (232 - zero), 1);
It won't be an issue in practice but it's harmless to fix.
Quoted 18 lines
Quoted 5 lines
Quoted 4 lines
drivers/hid/hid-nintendo.c +3
-0+ +input_report_abs (input, abs,clamp (value,0 ,NS2_TRIGGER_RANGE )); +}[ ... ]
Quoted 12 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3597
Quoted 8 lines
drivers/hid/hid-nintendo.c +8
-0+static int switch2_read_flash (struct switch2_controller *ns2,uint32_t address, +uint8_t size) +{ +uint8_t message[8 ] = { size,0x7e }; + +if (!ns2->cfg) +return -ENOTCONN ; + *(__le32 *)&message[4 ] =__cpu_to_le32 (address);The driver directly casts &message[4] to
__le32. Since message is auint8_tarray, it is only guaranteed to be 1-byte aligned. On strict architectures, will this unaligned memory write trigger a hardware alignment fault?
Quoted 5 lines
I assume this could be an issue and we should just use something like the below (only compile-tested).
put_unaligned_le32(__cpu_to_le32(address), &message[4]);
Correct.
Quoted 54 lines
Quoted 18 lines
Quoted 5 lines
drivers/hid/hid-nintendo.c +3
-0+return ns2->cfg->send_command (NS2_CMD_FLASH ,NS2_SUBCMD_FLASH_READ , message, +sizeof (message), ns2->cfg); +}[ ... ]
Quoted 3 lines
drivers/hid/hid-nintendo.c +3
-0+int switch2_receive_command (struct switch2_controller *ns2, +const uint8_t *message,size_t length) +{[ ... ]
Quoted 7 lines
drivers/hid/hid-nintendo.c +7
-0+ header = (const struct switch2_cmd_header *)message; +if (!(header->flags &NS2_FLAG_OK )) { + ret = -EIO ; + goto exit; + } + message = &message[8 ]; +switch (header->command) {[ ... ]
Quoted 13 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3773
Quoted 7 lines
drivers/hid/hid-nintendo.c +7
-0+case NS2_CMD_FW_INFO : +if (header->subcommand ==NS2_SUBCMD_FW_INFO_GET ) { +if (length <sizeof (ns2->version)) { + ret = -EINVAL ; + goto exit; + } +memcpy (&ns2->version, message,sizeof (ns2->version));The message pointer is advanced by 8 bytes to skip the header, but length is not decremented. The bounds check compares length against
sizeof(ns2->version). If length is exactlysizeof(ns2->version), the check passes, but the advanced message pointer only has length - 8 valid bytes remaining. Will the memcpy over-read into uninitialized memory?Sounds like something that we should fix by either decreasing length or increasing the size in the check.
Quoted 10 lines
Quoted 10 lines
drivers/hid/hid-nintendo.c +9
-0+ ns2->ctlr_type = ns2->version.ctlr_type; +switch2_init_step_done (ns2,NS2_INIT_GET_FIRMWARE_INFO ); + } +break ; +default : +break ; + } + +exit:Quoted 8 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3784
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+if (ns2->init_step <NS2_INIT_DONE ) +switch2_init_controller (ns2);If a command response has the NACK flag set or encounters another error, the code jumps to exit and invokes
switch2_init_controller. Sincens2->init_stephas not advanced, the state machine will immediately re-send the exact same command. Can this cause an infinite tight feedback loop of failures and retries, flooding the USB bus?
Quoted 5 lines
We have discussed this before and it doesn't seem to be an issue in practice.
If we want to be on the safe side, we could pass a retry count and abort on too many error retries, perhaps?
I had considered a retry count but getting it to work properly was fiddly. This should only go wrong if there's a malicious device attached, as in practice the Switch 2 controllers won't do this, and bus abuse is trivial with a malicious device regardless.
Quoted 21 lines
Quoted 9 lines
Quoted 5 lines
drivers/hid/hid-nintendo.c +3
-0+ +return ret; +}[ ... ]
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+int switch2_controller_attach_cfg (const char *phys,struct switch2_cfg_intf *cfg) +{[ ... ]
Quoted 11 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3804
Quoted 6 lines
drivers/hid/hid-nintendo.c +6
-0+guard (mutex)(&ns2->lock); +WARN_ON (ns2->cfg); + ns2->cfg = cfg; + +if (ns2->hdev) +return switch2_init_controller (ns2);If
switch2_init_controllerfails here or inswitch2_probe, the error is returned immediately without unrolling the state. Willns2->cfgorns2->hdevremain set, potentially leading to a use-after-free when subsequent device events occur?
Quoted 8 lines
AFAICT, since we are always checking for both
ns2->cfgandns2->hdevbefore doing any processing inswitch2_init_controller, there should never be a use-after-freeIt *is* true that we don't call hid_hw_{close,stop} in
switch2_probe, if theswitch2_init_controllercall fails though. It might make sense to return a specific error and use it to check whether we want to give up and call these?
The problem was that it will return an error after setting ns2->cfg, which causes the caller to free it without removing it. That's a real bug that can cause UAF.
Quoted 123 lines
Quoted 5 lines
Quoted 4 lines
drivers/hid/hid-nintendo.c +2
-0+return 0 ; +}[ ... ]
Quoted 15 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3908
Quoted 10 lines
drivers/hid/hid-nintendo.c +10
-0+static void switch2_remove (struct hid_device *hdev) +{ +struct switch2_controller *ns2 =hid_get_drvdata (hdev); + +hid_hw_close (hdev); +mutex_lock (&ns2->lock); +WARN_ON (ns2->hdev != hdev); + ns2->hdev =NULL ; +mutex_unlock (&ns2->lock); +ida_free (&nintendo_player_id_allocator, ns2->player_id);If
ida_allocfails during probe,ns2->player_idremains at its default value ofU32_MAX. Whenida_freeis called, the IDA framework enforces a check on the ID. CastingU32_MAXto a signed integer yields -1. Will this trigger theBUG_ONand cause a kernel panic?
ida_freeseems to return early onif ((int)id < 0)
return;so that should be fine as is.
Quoted 33 lines
Quoted 4 lines
drivers/hid/hid-nintendo.c +3
-0+switch2_controller_put (ns2); +hid_hw_stop (hdev); +}[ ... ]
Quoted 5 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +0
-0[ ... ]
Quoted 2 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +2
-0+static void switch2_bulk_in (struct urb *urb) +{[ ... ]
drivers/input/joystick/nintendo-switch2-usb.c line 72
Quoted 7 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +7
-0+spin_lock_irqsave (&ns2_usb->bulk_in_lock, flags); +for (i =0 ; i <NS2_IN_URBS ; i++) { +int err; +struct switch2_urb *ns2_urb; + +if (ns2_usb->bulk_in[i].urb == urb) { + ns2_usb->message_in = i;If multiple URBs complete in quick succession before the work item executes, the
message_inindex is overwritten. Will this cause the work item to only process the last completed URB, leaving earlier URBs indefinitely active and leading to starvation of the URB pool?Quoted 2 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +2
-0+continue ; + }[ ... ]
Quoted 2 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +2
-0+static int switch2_usb_probe (struct usb_interface *intf,const struct usb_device_id *id) +{[ ... ]
Quoted 15 lines
drivers/input/joystick/nintendo-switch2-usb.c line 271
Quoted 10 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +10
-0+ ns2_usb->bulk_in[0 ].active = true; + ret =usb_submit_urb (ns2_usb->bulk_in[0 ].urb,GFP_ATOMIC ); +if (ret <0 ) + goto err_free_out; + +init_usb_anchor (&ns2_usb->bulk_out_anchor); +spin_lock_init (&ns2_usb->bulk_out_lock); +init_usb_anchor (&ns2_usb->bulk_in_anchor); +spin_lock_init (&ns2_usb->bulk_in_lock); +INIT_WORK (&ns2_usb->message_in_work, switch2_usb_message_in_work);
usb_submit_urbis invoked for bulk_in[0] before the initialization of the spinlocks, anchors, and work struct. If the URB completes immediately, the completion handler will execute and attempt to use uninitialized synchronization primitives. Can this cause a crash?As the documentation for
usb_submit_urbmentions that the call is async, I assume that this is indeed a theoretical possibility.Quoted 4 lines
Quoted 3 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +2
-0+ +usb_set_intfdata (intf, ns2_usb);[ ... ]
Quoted 16 lines
drivers/input/joystick/nintendo-switch2-usb.c line 295
Quoted 12 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +12
-0+err_kill_urb: +usb_kill_urb (ns2_usb->bulk_in[0 ].urb); +err_free_out: +for (i =0 ; i <NS2_OUT_URBS ; i++) { +usb_free_coherent (ns2_usb->udev,NS2_BULK_SIZE , ns2_usb->bulk_out[i].data, + ns2_usb->bulk_out[i].urb->transfer_dma); +usb_free_urb (ns2_usb->bulk_out[i].urb); + } +err_free_in: +for (i =0 ; i <NS2_IN_URBS ; i++) { +usb_free_coherent (ns2_usb->udev,NS2_BULK_SIZE , ns2_usb->bulk_in[i].data, + ns2_usb->bulk_in[i].urb->transfer_dma);If
usb_alloc_urbfails during the loop, it jumps toerr_free_in. During cleanup, it accesses ns2_usb->bulk_in[i].urb->transfer_dma. Since urb is NULL for the failed index, will this trigger a NULL pointer dereference?Yes, most likely we would need a new label for this case.
Quoted 11 lines
Quoted 11 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +10
-0+usb_free_urb (ns2_usb->bulk_in[i].urb); + } +devm_kfree (&intf->dev, ns2_usb); + +return ret; +} + +static void switch2_usb_disconnect (struct usb_interface *intf) +{ +struct switch2_usb *ns2_usb =usb_get_intfdata (intf);Quoted 8 lines
drivers/input/joystick/nintendo-switch2-usb.c line 310
Quoted 5 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +5
-0+unsigned long flags; +int i; + +spin_lock_irqsave (&ns2_usb->bulk_out_lock, flags); +usb_kill_anchored_urbs (&ns2_usb->bulk_out_anchor);Both
usb_kill_anchored_urbsandcancel_work_synccan sleep. Is it safe to call them while holding a spinlock?
Quoted 3 lines
According to some googling, this indeed seems to be an isuse. The non-sleeping way to cancel transfer requests would be to use
https://www.kernel.org/doc/html/v6.1/driver-api/usb/usb.html#c.usb_unlink_anchored_urbs
This was removed in 6.17 and has been unused since 2009.
Quoted 25 lines
Quoted 17 lines
drivers/input/joystick/nintendo-switch2-usb.c line 320
Quoted 13 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +10
-0+for (i =0 ; i <NS2_OUT_URBS ; i++) { +usb_free_coherent (ns2_usb->udev,NS2_BULK_SIZE , ns2_usb->bulk_out[i].data, + ns2_usb->bulk_out[i].urb->transfer_dma); +usb_free_urb (ns2_usb->bulk_out[i].urb); + } +spin_unlock_irqrestore (&ns2_usb->bulk_out_lock, flags); + +spin_lock_irqsave (&ns2_usb->bulk_in_lock, flags); +usb_kill_anchored_urbs (&ns2_usb->bulk_in_anchor); +cancel_work_sync (&ns2_usb->message_in_work);Furthermore,
cancel_work_syncwaits formessage_in_workwhich attempts to acquirebulk_in_lock. Does this cause a deadlock since the lock is already held by the disconnecting thread?Yes, this looks like a real concern as well.
Cheers,
SilvanQuoted 2 lines
Quoted 2 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +1
-0+for (i =0 ; i <NS2_IN_URBS ; i++) {
Vicki Pfau
maintainerGuess I'm doing LLM review replies now.
Quoted 35 lines · On 5/13/26 5:15 PM, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 11 potential issue(s) to consider:
- [High] Sleeping in atomic context and AB-BA deadlock inswitch2_usb_disconnect
- [High] Race condition in IN URB tracking causes permanent starvation
- [High] Dangling pointers and use-after-free on probe failure
- [High] Memory corruption and double free due to incorrect devm input lifecycle management
- [High] NULL pointer dereference in USB probe error path
- [High] Division by zero crash from unvalidated trigger calibration data
- [High]BUG_ONkernel panic whenida_freeis called withU32_MAX
- [High] Out-of-bounds read when parsingNS2_CMD_FW_INFOresponse
- [High] Race condition due to URB submission before initialization of synchronization primitives
- [Medium] Infinite USB retry storm on protocol errors
- [Medium] Unaligned memory access on byte array casts
--commit
00cb7265ad5983144c6923702e2ee2c3c047d29e
Author: Vicki Pfau <[email protected]>
Subject: HID: nintendo: Add preliminary Switch 2 controller driverThis adds a new driver for the Switch 2 controllers. The Switch 2 uses an unusual split-interface design such that input and rumble occur on the main HID interface, but all other communication occurs over a "configuration" interface.
Quoted 4 lines
drivers/hid/hid-nintendo.c +0
-0[ ... ]
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+static int switch2_init_input (struct switch2_controller *ns2) +{[ ... ]
Quoted 3 lines
drivers/hid/hid-nintendo.c +3
-0+ input =devm_input_allocate_device (&hdev->dev); +if (!input) +return -ENOMEM ;[ ... ]
Quoted 8 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3238
Quoted 4 lines
drivers/hid/hid-nintendo.c +4
-0+ ret =input_register_device (input); +if (ret <0 ) { +hid_err (ns2->hdev,"Failed to register input; ret=%d\n" , ret); +input_free_device (input);Calling
input_free_deviceorinput_unregister_deviceon a devm-managed input device can cause double frees when devres cleanup fires. Can this lead to memory corruption?
False positive. The documentation clearly states there is no devm equivalent and input_unregister_device works fine on devm-managed devices. The source of input_free_device also clearly shows logic for handling devm, and the source of input_device_unregister calls into a static devm_input_device_unregister if needed.
Quoted 9 lines
Quoted 3 lines
drivers/hid/hid-nintendo.c +2
-0+return ret; + }[ ... ]
Quoted 4 lines
drivers/hid/hid-nintendo.c +4
-0+static void switch2_controller_put (struct switch2_controller *ns2) +{ +struct input_dev *input; +bool do_free;[ ... ]
Quoted 8 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3309
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+if (input) +input_unregister_device (input);Calling
input_unregister_deviceon a devm-managed input device can cause issues. If the input device remains alive (tied to the HID device devres) and its child LEDs are not released, will reconnecting the USB cable allocate a new input device and corrupt the LED lists by re-registering the exact samens2->ledsstructures?
Same false positive
Quoted 11 lines
Quoted 3 lines
drivers/hid/hid-nintendo.c +2
-0+ +if (do_free) {[ ... ]
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3502
Quoted 3 lines
drivers/hid/hid-nintendo.c +3
-0+static void switch2_report_trigger (struct input_dev *input,uint8_t zero,int abs,uint8_t data) +{ +int value = (NS2_TRIGGER_RANGE +1 ) * (data - zero) / (232 - zero);The zero variable is loaded directly from the controller's factory calibration flash. If a device reports a zero point of exactly 232, will this trigger a division by zero exception and crash the kernel?
Ok, an actual finding. I'll have this fixed in v6.
Quoted 5 lines
Quoted 4 lines
drivers/hid/hid-nintendo.c +3
-0+ +input_report_abs (input, abs,clamp (value,0 ,NS2_TRIGGER_RANGE )); +}[ ... ]
Quoted 12 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3597
Quoted 8 lines
drivers/hid/hid-nintendo.c +8
-0+static int switch2_read_flash (struct switch2_controller *ns2,uint32_t address, +uint8_t size) +{ +uint8_t message[8 ] = { size,0x7e }; + +if (!ns2->cfg) +return -ENOTCONN ; + *(__le32 *)&message[4 ] =__cpu_to_le32 (address);The driver directly casts &message[4] to
__le32. Since message is auint8_tarray, it is only guaranteed to be 1-byte aligned. On strict architectures, will this unaligned memory write trigger a hardware alignment fault?
Good catch. Fixed in v6.
Quoted 17 lines
Quoted 4 lines
drivers/hid/hid-nintendo.c +3
-0+return ns2->cfg->send_command (NS2_CMD_FLASH ,NS2_SUBCMD_FLASH_READ , message, +sizeof (message), ns2->cfg); +}[ ... ]
Quoted 3 lines
drivers/hid/hid-nintendo.c +3
-0+int switch2_receive_command (struct switch2_controller *ns2, +const uint8_t *message,size_t length) +{[ ... ]
Quoted 7 lines
drivers/hid/hid-nintendo.c +7
-0+ header = (const struct switch2_cmd_header *)message; +if (!(header->flags &NS2_FLAG_OK )) { + ret = -EIO ; + goto exit; + } + message = &message[8 ]; +switch (header->command) {[ ... ]
Quoted 13 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3773
Quoted 7 lines
drivers/hid/hid-nintendo.c +7
-0+case NS2_CMD_FW_INFO : +if (header->subcommand ==NS2_SUBCMD_FW_INFO_GET ) { +if (length <sizeof (ns2->version)) { + ret = -EINVAL ; + goto exit; + } +memcpy (&ns2->version, message,sizeof (ns2->version));The message pointer is advanced by 8 bytes to skip the header, but length is not decremented. The bounds check compares length against
sizeof(ns2->version). If length is exactlysizeof(ns2->version), the check passes, but the advanced message pointer only has length - 8 valid bytes remaining. Will the memcpy over-read into uninitialized memory?
Fixed in v6.
Quoted 10 lines
Quoted 10 lines
drivers/hid/hid-nintendo.c +9
-0+ ns2->ctlr_type = ns2->version.ctlr_type; +switch2_init_step_done (ns2,NS2_INIT_GET_FIRMWARE_INFO ); + } +break ; +default : +break ; + } + +exit:
Quoted 8 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3784
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+if (ns2->init_step <NS2_INIT_DONE ) +switch2_init_controller (ns2);If a command response has the NACK flag set or encounters another error, the code jumps to exit and invokes
switch2_init_controller. Sincens2->init_stephas not advanced, the state machine will immediately re-send the exact same command. Can this cause an infinite tight feedback loop of failures and retries, flooding the USB bus?
This doesn't happen for problems already described in the thread previously.
Quoted 8 lines
Quoted 4 lines
drivers/hid/hid-nintendo.c +3
-0+ +return ret; +}[ ... ]
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+int switch2_controller_attach_cfg (const char *phys,struct switch2_cfg_intf *cfg) +{[ ... ]
Quoted 11 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3804
Quoted 6 lines
drivers/hid/hid-nintendo.c +6
-0+guard (mutex)(&ns2->lock); +WARN_ON (ns2->cfg); + ns2->cfg = cfg; + +if (ns2->hdev) +return switch2_init_controller (ns2);If
switch2_init_controllerfails here or inswitch2_probe, the error is returned immediately without unrolling the state. Willns2->cfgorns2->hdevremain set, potentially leading to a use-after-free when subsequent device events occur?
This is a good catch. I'm not sure what the right fix is though; obviously a half-configured state is bad, but I'm not sure a full teardown is the best approach; it can leave it in a weird state, even if it's not a UAF risk. I'll go with a full teardown for now at least.
Quoted 4 lines
Quoted 3 lines
drivers/hid/hid-nintendo.c +2
-0+return 0 ; +}[ ... ]
Quoted 15 lines
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3908
Quoted 10 lines
drivers/hid/hid-nintendo.c +10
-0+static void switch2_remove (struct hid_device *hdev) +{ +struct switch2_controller *ns2 =hid_get_drvdata (hdev); + +hid_hw_close (hdev); +mutex_lock (&ns2->lock); +WARN_ON (ns2->hdev != hdev); + ns2->hdev =NULL ; +mutex_unlock (&ns2->lock); +ida_free (&nintendo_player_id_allocator, ns2->player_id);If
ida_allocfails during probe,ns2->player_idremains at its default value ofU32_MAX. Whenida_freeis called, the IDA framework enforces a check on the ID. CastingU32_MAXto a signed integer yields -1. Will this trigger theBUG_ONand cause a kernel panic?
I can't find any evidence of such a BUG_ON. A negative number will just early return. This seems like a hallucination.
Quoted 14 lines
Quoted 4 lines
drivers/hid/hid-nintendo.c +3
-0+switch2_controller_put (ns2); +hid_hw_stop (hdev); +}[ ... ]
Quoted 5 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +0
-0[ ... ]
Quoted 2 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +2
-0+static void switch2_bulk_in (struct urb *urb) +{[ ... ]
Quoted 13 lines
drivers/input/joystick/nintendo-switch2-usb.c line 72
Quoted 7 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +7
-0+spin_lock_irqsave (&ns2_usb->bulk_in_lock, flags); +for (i =0 ; i <NS2_IN_URBS ; i++) { +int err; +struct switch2_urb *ns2_urb; + +if (ns2_usb->bulk_in[i].urb == urb) { + ns2_usb->message_in = i;If multiple URBs complete in quick succession before the work item executes, the
message_inindex is overwritten. Will this cause the work item to only process the last completed URB, leaving earlier URBs indefinitely active and leading to starvation of the URB pool?
In practice this probably won't happen but I guess it's worth fixing.
Quoted 6 lines
Quoted 2 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +2
-0+continue ; + }[ ... ]
Quoted 2 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +2
-0+static int switch2_usb_probe (struct usb_interface *intf,const struct usb_device_id *id) +{[ ... ]
Quoted 15 lines
drivers/input/joystick/nintendo-switch2-usb.c line 271
Quoted 10 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +10
-0+ ns2_usb->bulk_in[0 ].active = true; + ret =usb_submit_urb (ns2_usb->bulk_in[0 ].urb,GFP_ATOMIC ); +if (ret <0 ) + goto err_free_out; + +init_usb_anchor (&ns2_usb->bulk_out_anchor); +spin_lock_init (&ns2_usb->bulk_out_lock); +init_usb_anchor (&ns2_usb->bulk_in_anchor); +spin_lock_init (&ns2_usb->bulk_in_lock); +INIT_WORK (&ns2_usb->message_in_work, switch2_usb_message_in_work);
usb_submit_urbis invoked for bulk_in[0] before the initialization of the spinlocks, anchors, and work struct. If the URB completes immediately, the completion handler will execute and attempt to use uninitialized synchronization primitives. Can this cause a crash?
I don't know if this is possible but I guess I'll fix it.
Quoted 4 lines
Quoted 3 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +2
-0+ +usb_set_intfdata (intf, ns2_usb);[ ... ]
Quoted 16 lines
drivers/input/joystick/nintendo-switch2-usb.c line 295
Quoted 12 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +12
-0+err_kill_urb: +usb_kill_urb (ns2_usb->bulk_in[0 ].urb); +err_free_out: +for (i =0 ; i <NS2_OUT_URBS ; i++) { +usb_free_coherent (ns2_usb->udev,NS2_BULK_SIZE , ns2_usb->bulk_out[i].data, + ns2_usb->bulk_out[i].urb->transfer_dma); +usb_free_urb (ns2_usb->bulk_out[i].urb); + } +err_free_in: +for (i =0 ; i <NS2_IN_URBS ; i++) { +usb_free_coherent (ns2_usb->udev,NS2_BULK_SIZE , ns2_usb->bulk_in[i].data, + ns2_usb->bulk_in[i].urb->transfer_dma);If
usb_alloc_urbfails during the loop, it jumps toerr_free_in. During cleanup, it accesses ns2_usb->bulk_in[i].urb->transfer_dma. Since urb is NULL for the failed index, will this trigger a NULL pointer dereference?
I removed the NULL check due to checkpatch telling me I didn't need it but I guess I'll put it back.
Quoted 11 lines
Quoted 11 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +10
-0+usb_free_urb (ns2_usb->bulk_in[i].urb); + } +devm_kfree (&intf->dev, ns2_usb); + +return ret; +} + +static void switch2_usb_disconnect (struct usb_interface *intf) +{ +struct switch2_usb *ns2_usb =usb_get_intfdata (intf);
Quoted 8 lines
drivers/input/joystick/nintendo-switch2-usb.c line 310
Quoted 5 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +5
-0+unsigned long flags; +int i; + +spin_lock_irqsave (&ns2_usb->bulk_out_lock, flags); +usb_kill_anchored_urbs (&ns2_usb->bulk_out_anchor);Both
usb_kill_anchored_urbsandcancel_work_synccan sleep. Is it safe to call them while holding a spinlock?
Fixing in v6.
Quoted 15 lines
drivers/input/joystick/nintendo-switch2-usb.c line 320
Quoted 11 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +10
-0+for (i =0 ; i <NS2_OUT_URBS ; i++) { +usb_free_coherent (ns2_usb->udev,NS2_BULK_SIZE , ns2_usb->bulk_out[i].data, + ns2_usb->bulk_out[i].urb->transfer_dma); +usb_free_urb (ns2_usb->bulk_out[i].urb); + } +spin_unlock_irqrestore (&ns2_usb->bulk_out_lock, flags); + +spin_lock_irqsave (&ns2_usb->bulk_in_lock, flags); +usb_kill_anchored_urbs (&ns2_usb->bulk_in_anchor); +cancel_work_sync (&ns2_usb->message_in_work);Furthermore,
cancel_work_syncwaits formessage_in_workwhich attempts to acquirebulk_in_lock. Does this cause a deadlock since the lock is already held by the disconnecting thread?
Likewise.
Quoted 3 lines
Quoted 2 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +1
-0+for (i =0 ; i <NS2_IN_URBS ; i++) {
PATCH 1/1 HID: nintendo: fix clang build of switch2_probe guard/goto
In reply to Vicki Pfauclang rejects the forward goto err_close/err_stop in switch2_probe() because they jump across the scope of the guard(mutex)(&ns2->lock) cleanup variable ("cannot jump from this goto statement to its label"). All three early error paths run before the lock is acquired, so replace the gotos with explicit hid_hw_close()/hid_hw_stop() cleanup and drop the now-unused labels. No functional change; gcc accepted the original.
---
Hi Vicki, I've been testing your Switch 2 series on a local machine here with JC2, GC, and Pro all over USB and hits this clang build break, Patch below , feel free to just squash it in.
drivers/hid/hid-nintendo.c:4147:3: error: cannot jump from this goto statement to its labeldrivers/hid/hid-nintendo.c:4153:3: error: cannot jump from this goto statement to its label
with the explanatory notes pointing at:
note: jump bypasses initialization of variable with __attribute__((cleanup))
guard(mutex)(&ns2->lock);
drivers/hid/hid-nintendo.c | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-)
drivers/hid/hid-nintendo.c +5 -9
@@ -4144,13 +4144,16 @@ static int switch2_probe(struct hid_device *hdev, const struct hid_device_id *id ret =hid_hw_open (hdev);if (ret) {hid_err (hdev,"hw_open failed %d\n" , ret); - goto err_stop; +hid_hw_stop (hdev); +return ret; } ns2 =switch2_get_controller (phys);if (IS_ERR (ns2)) { ret =PTR_ERR (ns2); - goto err_close; +hid_hw_close (hdev); +hid_hw_stop (hdev); +return ret; }guard (mutex)(&ns2->lock);
@@ -4194,13 +4197,6 @@ static int switch2_probe(struct hid_device *hdev, const struct hid_device_id *idreturn switch2_init_controller (ns2);return 0 ; - -err_close: -hid_hw_close (hdev); -err_stop: -hid_hw_stop (hdev); - -return ret; }static void switch2_remove (struct hid_device *hdev)
Signature · 1 line
2.54.0
Vicki Pfau
maintainerPATCH v5 2/3 HID: nintendo: Add rumble support for Switch 2 controllers
In reply to Vicki PfauThis adds rumble support for both the "HD Rumble" linear resonant actuator type as used in the Joy-Cons and Pro Controller, as well as the eccentric rotating mass type used in the GameCube controller. Note that since there's currently no API for exposing full control of LRAs with evdev, it only simulates a basic rumble for now.
--- drivers/hid/Kconfig | 8 +- drivers/hid/hid-nintendo.c | 179 ++++++++++++++++++++++++++++++++++++- 2 files changed, 181 insertions(+), 6 deletions(-)
drivers/hid/Kconfig +4 -4
@@ -859,10 +859,10 @@ config NINTENDO_FF 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, the pro - controller, and the NSO N64 controller. For the pro controller, both - rumble motors can be controlled individually. + Say Y here if you have a Nintendo Switch or Switch 2 controller and want + to enable force feedback support for it. This works for Joy-Cons, the Pro + Controllers, and the NSO N64 and GameCube controller. For the Pro + Controller, both rumble motors can be controlled individually. config HID_NTI tristate "NTI keyboard adapters"
drivers/hid/hid-nintendo.c +177 -2
231 lines not on this page · raw message
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v5 2/3] HID: nintendo: Add rumble support for Switch 2 controllers
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider: - [High] Mixing jiffies and milliseconds in delayed work scheduling logic causes an integer underflow…
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [High] Mixing jiffies and milliseconds in delayed work scheduling logic causes an integer underflow, permanently stalling the haptic rumble.
- [High] A guaranteed NULL pointer dereference occurs in the error logging path of switch2_rumble_work, as well as a TOCTOU race condition.
- [Medium] ns2->ctlr_type is checked before it is dynamically initialized, causing union corruption for GameCube controllers.
- [Low] Implicit type promotion in the max() macro causes a compiler warning.
- [Low] Kconfig documentation claims individual motor control for the Pro Controller, but the implementation identicalizes the rumble data for both motors. --
commit d72f0f8e0dadde2cacc27050b92088c2e5cbea0e
Author: Vicki Pfau <[email protected]>
Subject: HID: nintendo: Add rumble support for Switch 2 controllers
This commit introduces rumble support for Switch 2 controllers, handling both HD Rumble linear resonant actuators and eccentric rotating mass haptics. It adds state machines for rumble scheduling and output reporting via hdev.
Quoted 6 lines
drivers/hid/Kconfig +0
-0@@ -850,10 +850,10 @@ config NINTENDO_FF depends on HID_NINTENDO
drivers/hid/Kconfig config NINTENDO_FF · line 856
Quoted 10 lines
drivers/hid/Kconfig +4
-4select 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, the pro - controller, and the NSO N64 controller. For the pro controller, both - rumble motors can be controlled individually. + Say Y here if you have a Nintendo Switch or Switch 2 controller and want + to enable force feedback support for it. This works for Joy-Cons, the Pro + Controllers, and the NSO N64 and GameCube controller. For the Pro + Controller, both rumble motors can be controlled individually.
This isn't a bug, but is the help text accurate regarding individual motor control? The implementation in switch2_rumble_work() appears to encode the exact same rumble configuration to both the left and right motor offsets, which would make both motors vibrate identically.
Quoted 4 lines
drivers/hid/hid-nintendo.c +0
-0
[ ... ]
Quoted 15 lines
drivers/hid/hid-nintendo.c +11
-0@@ -3103,6 +3155,107 @@ static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type)return type ==NS2_CTLR_TYPE_JCL || type ==NS2_CTLR_TYPE_JCR ; } +#if IS_ENABLED (CONFIG_NINTENDO_FF ) +static void switch2_encode_rumble (struct switch2_hd_rumble *rumble,uint8_t buffer[5 ]) +{ + buffer[0 ] = rumble->hi_freq; + buffer[1 ] = (rumble->hi_freq >>8 ) | (rumble->hi_amp <<2 ); + buffer[2 ] = (rumble->hi_amp >>6 ) | (rumble->lo_freq <<4 ); + buffer[3 ] = (rumble->lo_freq >>4 ) | (rumble->lo_amp <<6 ); + buffer[4 ] = rumble->lo_amp >>2 ; +} + +static int switch2_play_effect (struct input_dev *dev,void *data,struct ff_effect *effect)
drivers/hid/hid-nintendo.c static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type) · line 3178
Quoted 10 lines
drivers/hid/hid-nintendo.c +10
-0+{ +struct switch2_controller *ns2 =input_get_drvdata (dev); + +if (effect->type !=FF_RUMBLE ) +return 0 ; + +guard (spinlock_irqsave)(&ns2->rumble_lock); +if (ns2->ctlr_type ==NS2_CTLR_TYPE_GC ) { + ns2->rumble.sd.amplitude =max (effect->u.rumble.strong_magnitude, + effect->u.rumble.weak_magnitude >>1 );
Will this max calculation trigger a compiler warning? The strict type checking in the max macro might fail because effect->u.rumble.weak_magnitude >> 1 promotes to an int, while strong_magnitude is a u16.
Quoted 19 lines
drivers/hid/hid-nintendo.c +19
-0+ }else { + ns2->rumble.hd.hi_amp = effect->u.rumble.weak_magnitude *RUMBLE_MAX >>16 ; + ns2->rumble.hd.lo_amp = effect->u.rumble.strong_magnitude *RUMBLE_MAX >>16 ; + } + +if (ns2->hdev) +schedule_delayed_work (&ns2->rumble_work,0 ); + +return 0 ; +} + +static void switch2_rumble_work (struct work_struct *work) +{ +struct switch2_controller *ns2 =container_of (to_delayed_work (work), + struct switch2_controller, rumble_work); +unsigned long current_ms =jiffies_to_msecs (get_jiffies_64 ()); +unsigned long flags; +bool active; +int ret;
[ ... ]
drivers/hid/hid-nintendo.c static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type) · line 3241
Quoted 9 lines
drivers/hid/hid-nintendo.c +9
-0+if (active) { +unsigned long interval =msecs_to_jiffies (4 ); + +if (!ns2->last_rumble_work) + ns2->last_rumble_work = current_ms; +else + ns2->last_rumble_work += interval; +schedule_delayed_work (&ns2->rumble_work, + ns2->last_rumble_work + interval - current_ms);
Does this code underflow the scheduled delay?
The current_ms variable is retrieved in milliseconds using jiffies_to_msecs(), but interval is calculated in jiffies using msecs_to_jiffies(). Since ns2->last_rumble_work is initialized to milliseconds but incremented by jiffies, subtracting current_ms could yield a negative value.
On systems where HZ is not 1000, could this underflow the delay parameter and schedule the next work millions of jiffies in the future?
Quoted 4 lines
drivers/hid/hid-nintendo.c +4
-0+ }else { + ns2->last_rumble_work =0 ; + } +spin_unlock_irqrestore (&ns2->rumble_lock, flags);
drivers/hid/hid-nintendo.c static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type) · line 3255
Quoted 10 lines
drivers/hid/hid-nintendo.c +10
-0+ +if (!ns2->hdev) { +cancel_delayed_work (&ns2->rumble_work); + ret = -ENODEV ; + }else { + ret =hid_hw_output_report (ns2->hdev, ns2->rumble_buffer,64 ); + } + +if (ret <0 ) +hid_dbg (ns2->hdev,"Failed to send output report ret=%d\n" , ret);
If ns2->hdev is NULL, we set ret = -ENODEV and then reach this hid_dbg call. Could this result in a NULL pointer dereference, as the hid_dbg macro passes ns2->hdev to dev_dbg()?
Also, since ns2->hdev is accessed locklessly and without READ_ONCE(), is there a time-of-check to time-of-use race where the compiler might reload the pointer between the check and hid_hw_output_report()?
[ ... ]
drivers/hid/hid-nintendo.c static int switch2_probe(struct hid_device *hdev, const struct hid_device_id *id · line 4055
Quoted 9 lines
drivers/hid/hid-nintendo.c +5
-0@@ -3881,6 +4048,14 @@ static int switch2_probe(struct hid_device *hdev, const struct hid_device_id *idswitch2_leds_create (ns2); +#if IS_ENABLED (CONFIG_NINTENDO_FF ) +if (ns2->ctlr_type !=NS2_CTLR_TYPE_GC ) { + ns2->rumble.hd.hi_freq =RUMBLE_HI_FREQ ; + ns2->rumble.hd.lo_freq =RUMBLE_LO_FREQ ; + }
Are we checking ns2->ctlr_type before it is dynamically initialized?
During probe, ns2->ctlr_type appears to be 0 since the struct is freshly allocated and the type is discovered later during the init state machine. This would cause the high and low frequencies to always be written.
Since hd and sd share a union, could this corrupt the sd.error and sd.amplitude fields for actual GameCube controllers?
Quoted 4 lines
drivers/hid/hid-nintendo.c +3
-0+spin_lock_init (&ns2->rumble_lock); +INIT_DELAYED_WORK (&ns2->rumble_work, switch2_rumble_work); +#endif hid_set_drvdata (hdev, ns2);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
Re: [PATCH v5 2/3] HID: nintendo: Add rumble support for Switch 2 controllers
Quoted 29 lines · [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [High] Mixing jiffies and milliseconds in delayed work scheduling logic causes an integer underflow, permanently stalling the haptic rumble.
- [High] A guaranteed NULL pointer dereference occurs in the error logging path ofswitch2_rumble_work, as well as a TOCTOU race condition.
- [Medium]ns2->ctlr_typeis checked before it is dynamically initialized, causing union corruption for GameCube controllers.
- [Low] Implicit type promotion in themax()macro causes a compiler warning.
- [Low]Kconfigdocumentation claims individual motor control for the Pro Controller, but the implementation identicalizes the rumble data for both motors. --commit
d72f0f8e0dadde2cacc27050b92088c2e5cbea0e
Author: Vicki Pfau <[email protected]>
Subject: HID: nintendo: Add rumble support for Switch 2 controllersThis commit introduces rumble support for Switch 2 controllers, handling both HD Rumble linear resonant actuators and eccentric rotating mass haptics. It adds state machines for rumble scheduling and output reporting via hdev.
Quoted 13 lines
drivers/hid/Kconfig +1
-4@@ -850,10 +850,10 @@ config NINTENDO_FF 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, the pro - controller, and the NSO N64 controller. For the pro controller, both - rumble motors can be controlled individually. + Say Y here if you have a Nintendo Switch or Switch 2 controller and want
Quoted 8 lines
drivers/hid/Kconfig config NINTENDO_FF · line 865
Quoted 3 lines
drivers/hid/Kconfig +3
-0+ to enable force feedback support for it. This works for Joy-Cons, the Pro + Controllers, and the NSO N64 and GameCube controller. For the Pro + Controller, both rumble motors can be controlled individually.This isn't a bug, but is the help text accurate regarding individual motor control? The implementation in
switch2_rumble_work()appears to encode the exact same rumble configuration to both the left and right motor offsets, which would make both motors vibrate identically.
As pointers to different offsets into the rumble_buffer are passed, I assume that the vibrations will actually not be identical.
Quoted 29 lines
Quoted 5 lines
drivers/hid/hid-nintendo.c +0
-0[ ... ]
Quoted 21 lines
drivers/hid/hid-nintendo.c +17
-0@@ -3103,6 +3155,107 @@ static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type)return type ==NS2_CTLR_TYPE_JCL || type ==NS2_CTLR_TYPE_JCR ; } +#if IS_ENABLED (CONFIG_NINTENDO_FF ) +static void switch2_encode_rumble (struct switch2_hd_rumble *rumble,uint8_t buffer[5 ]) +{ + buffer[0 ] = rumble->hi_freq; + buffer[1 ] = (rumble->hi_freq >>8 ) | (rumble->hi_amp <<2 ); + buffer[2 ] = (rumble->hi_amp >>6 ) | (rumble->lo_freq <<4 ); + buffer[3 ] = (rumble->lo_freq >>4 ) | (rumble->lo_amp <<6 ); + buffer[4 ] = rumble->lo_amp >>2 ; +} + +static int switch2_play_effect (struct input_dev *dev,void *data,struct ff_effect *effect) +{ +struct switch2_controller *ns2 =input_get_drvdata (dev); + +if (effect->type !=FF_RUMBLE ) +return 0 ; +
Quoted 8 lines
drivers/hid/hid-nintendo.c static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type) · line 3178
Quoted 4 lines
drivers/hid/hid-nintendo.c +4
-0+guard (spinlock_irqsave)(&ns2->rumble_lock); +if (ns2->ctlr_type ==NS2_CTLR_TYPE_GC ) { + ns2->rumble.sd.amplitude =max (effect->u.rumble.strong_magnitude, + effect->u.rumble.weak_magnitude >>1 );Will this max calculation trigger a compiler warning? The strict type checking in the max macro might fail because
effect->u.rumble.weak_magnitude>> 1 promotes to an int, whilestrong_magnitudeis a u16.
Apparently it is not strict enough to emit a warning on my machine at least ...
Quoted 35 lines
Quoted 20 lines
drivers/hid/hid-nintendo.c +19
-0+ }else { + ns2->rumble.hd.hi_amp = effect->u.rumble.weak_magnitude *RUMBLE_MAX >>16 ; + ns2->rumble.hd.lo_amp = effect->u.rumble.strong_magnitude *RUMBLE_MAX >>16 ; + } + +if (ns2->hdev) +schedule_delayed_work (&ns2->rumble_work,0 ); + +return 0 ; +} + +static void switch2_rumble_work (struct work_struct *work) +{ +struct switch2_controller *ns2 =container_of (to_delayed_work (work), + struct switch2_controller, rumble_work); +unsigned long current_ms =jiffies_to_msecs (get_jiffies_64 ()); +unsigned long flags; +bool active; +int ret;[ ... ]
drivers/hid/hid-nintendo.c static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type) · line 3241
Quoted 9 lines
drivers/hid/hid-nintendo.c +9
-0+if (active) { +unsigned long interval =msecs_to_jiffies (4 ); + +if (!ns2->last_rumble_work) + ns2->last_rumble_work = current_ms; +else + ns2->last_rumble_work += interval; +schedule_delayed_work (&ns2->rumble_work, + ns2->last_rumble_work + interval - current_ms);Does this code underflow the scheduled delay?
Quoted 7 lines
The
current_msvariable is retrieved in milliseconds usingjiffies_to_msecs(), but interval is calculated in jiffies usingmsecs_to_jiffies(). Sincens2->last_rumble_workis initialized to milliseconds but incremented by jiffies, subtractingcurrent_mscould yield a negative value.On systems where HZ is not 1000, could this underflow the delay parameter and schedule the next work millions of jiffies in the future?
It's definitely suspicious that we are adding jiffies to milliseconds. We should probably fix that.
Quoted 11 lines
Quoted 11 lines
drivers/hid/hid-nintendo.c +10
-0+ }else { + ns2->last_rumble_work =0 ; + } +spin_unlock_irqrestore (&ns2->rumble_lock, flags); + +if (!ns2->hdev) { +cancel_delayed_work (&ns2->rumble_work); + ret = -ENODEV ; + }else { + ret =hid_hw_output_report (ns2->hdev, ns2->rumble_buffer,64 );
Quoted 8 lines
drivers/hid/hid-nintendo.c static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type) · line 3255
Quoted 4 lines
drivers/hid/hid-nintendo.c +4
-0+ } + +if (ret <0 ) +hid_dbg (ns2->hdev,"Failed to send output report ret=%d\n" , ret);If
ns2->hdevis NULL, we set ret =-ENODEVand then reach thishid_dbgcall. Could this result in a NULL pointer dereference, as thehid_dbgmacro passesns2->hdevtodev_dbg()?
Since we set ret = -ENODEV when ns2->hdev is NULL we would indeed end up calling hid_dbg() with a NULL argument.
Quoted 19 lines
Also, since
ns2->hdevis accessed locklessly and withoutREAD_ONCE(), is there a time-of-check to time-of-use race where the compiler might reload the pointer between the check andhid_hw_output_report()?[ ... ]
drivers/hid/hid-nintendo.c static int switch2_probe(struct hid_device *hdev, const struct hid_device_id *id · line 4055
Quoted 9 lines
drivers/hid/hid-nintendo.c +5
-0@@ -3881,6 +4048,14 @@ static int switch2_probe(struct hid_device *hdev, const struct hid_device_id *idswitch2_leds_create (ns2); +#if IS_ENABLED (CONFIG_NINTENDO_FF ) +if (ns2->ctlr_type !=NS2_CTLR_TYPE_GC ) { + ns2->rumble.hd.hi_freq =RUMBLE_HI_FREQ ; + ns2->rumble.hd.lo_freq =RUMBLE_LO_FREQ ; + }Are we checking
ns2->ctlr_typebefore it is dynamically initialized?
Quoted 3 lines
During probe,
ns2->ctlr_typeappears to be 0 since the struct is freshly allocated and the type is discovered later during the init state machine. This would cause the high and low frequencies to always be written.
As switch2_init_controller is called from the other driver's probe function, this might be fine. To avoid writing these values if the initialisation has not happened yet, we should probably guard against a 0 value.
Cheers,
Silvan
Quoted 8 lines
Since hd and sd share a union, could this corrupt the sd.error and sd.amplitude fields for actual GameCube controllers?
Quoted 4 lines
drivers/hid/hid-nintendo.c +3
-0+spin_lock_init (&ns2->rumble_lock); +INIT_DELAYED_WORK (&ns2->rumble_work, switch2_rumble_work); +#endif hid_set_drvdata (hdev, ns2);
Vicki Pfau
maintainerRe: [PATCH v5 2/3] HID: nintendo: Add rumble support for Switch 2 controllers
In reply to [email protected]Let's tackle some more hallucinations.
Quoted 29 lines · On 5/13/26 5:53 PM, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [High] Mixing jiffies and milliseconds in delayed work scheduling logic causes an integer underflow, permanently stalling the haptic rumble.
- [High] A guaranteed NULL pointer dereference occurs in the error logging path ofswitch2_rumble_work, as well as a TOCTOU race condition.
- [Medium]ns2->ctlr_typeis checked before it is dynamically initialized, causing union corruption for GameCube controllers.
- [Low] Implicit type promotion in themax()macro causes a compiler warning.
- [Low]Kconfigdocumentation claims individual motor control for the Pro Controller, but the implementation identicalizes the rumble data for both motors. --commit
d72f0f8e0dadde2cacc27050b92088c2e5cbea0e
Author: Vicki Pfau <[email protected]>
Subject: HID: nintendo: Add rumble support for Switch 2 controllersThis commit introduces rumble support for Switch 2 controllers, handling both HD Rumble linear resonant actuators and eccentric rotating mass haptics. It adds state machines for rumble scheduling and output reporting via hdev.
Quoted 13 lines
drivers/hid/Kconfig +1
-4@@ -850,10 +850,10 @@ config NINTENDO_FF 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, the pro - controller, and the NSO N64 controller. For the pro controller, both - rumble motors can be controlled individually. + Say Y here if you have a Nintendo Switch or Switch 2 controller and want
Quoted 8 lines
drivers/hid/Kconfig config NINTENDO_FF · line 865
Quoted 3 lines
drivers/hid/Kconfig +3
-0+ to enable force feedback support for it. This works for Joy-Cons, the Pro + Controllers, and the NSO N64 and GameCube controller. For the Pro + Controller, both rumble motors can be controlled individually.This isn't a bug, but is the help text accurate regarding individual motor control? The implementation in
switch2_rumble_work()appears to encode the exact same rumble configuration to both the left and right motor offsets, which would make both motors vibrate identically.
I didn't add this text, so I'm ingoring this.
Quoted 29 lines
Quoted 5 lines
drivers/hid/hid-nintendo.c +0
-0[ ... ]
Quoted 21 lines
drivers/hid/hid-nintendo.c +17
-0@@ -3103,6 +3155,107 @@ static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type)return type ==NS2_CTLR_TYPE_JCL || type ==NS2_CTLR_TYPE_JCR ; } +#if IS_ENABLED (CONFIG_NINTENDO_FF ) +static void switch2_encode_rumble (struct switch2_hd_rumble *rumble,uint8_t buffer[5 ]) +{ + buffer[0 ] = rumble->hi_freq; + buffer[1 ] = (rumble->hi_freq >>8 ) | (rumble->hi_amp <<2 ); + buffer[2 ] = (rumble->hi_amp >>6 ) | (rumble->lo_freq <<4 ); + buffer[3 ] = (rumble->lo_freq >>4 ) | (rumble->lo_amp <<6 ); + buffer[4 ] = rumble->lo_amp >>2 ; +} + +static int switch2_play_effect (struct input_dev *dev,void *data,struct ff_effect *effect) +{ +struct switch2_controller *ns2 =input_get_drvdata (dev); + +if (effect->type !=FF_RUMBLE ) +return 0 ; +
Quoted 8 lines
drivers/hid/hid-nintendo.c static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type) · line 3178
Quoted 4 lines
drivers/hid/hid-nintendo.c +4
-0+guard (spinlock_irqsave)(&ns2->rumble_lock); +if (ns2->ctlr_type ==NS2_CTLR_TYPE_GC ) { + ns2->rumble.sd.amplitude =max (effect->u.rumble.strong_magnitude, + effect->u.rumble.weak_magnitude >>1 );Will this max calculation trigger a compiler warning? The strict type checking in the max macro might fail because
effect->u.rumble.weak_magnitude>> 1 promotes to an int, whilestrong_magnitudeis a u16.
It doesn't cause a warning locally, but my warnings seem lax for some reason. I'm not sure how to fix that, but I guess adding a cast here is harmless.
Quoted 35 lines
Quoted 20 lines
drivers/hid/hid-nintendo.c +19
-0+ }else { + ns2->rumble.hd.hi_amp = effect->u.rumble.weak_magnitude *RUMBLE_MAX >>16 ; + ns2->rumble.hd.lo_amp = effect->u.rumble.strong_magnitude *RUMBLE_MAX >>16 ; + } + +if (ns2->hdev) +schedule_delayed_work (&ns2->rumble_work,0 ); + +return 0 ; +} + +static void switch2_rumble_work (struct work_struct *work) +{ +struct switch2_controller *ns2 =container_of (to_delayed_work (work), + struct switch2_controller, rumble_work); +unsigned long current_ms =jiffies_to_msecs (get_jiffies_64 ()); +unsigned long flags; +bool active; +int ret;[ ... ]
drivers/hid/hid-nintendo.c static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type) · line 3241
Quoted 9 lines
drivers/hid/hid-nintendo.c +9
-0+if (active) { +unsigned long interval =msecs_to_jiffies (4 ); + +if (!ns2->last_rumble_work) + ns2->last_rumble_work = current_ms; +else + ns2->last_rumble_work += interval; +schedule_delayed_work (&ns2->rumble_work, + ns2->last_rumble_work + interval - current_ms);Does this code underflow the scheduled delay?
Quoted 7 lines
The
current_msvariable is retrieved in milliseconds usingjiffies_to_msecs(), but interval is calculated in jiffies usingmsecs_to_jiffies(). Sincens2->last_rumble_workis initialized to milliseconds but incremented by jiffies, subtractingcurrent_mscould yield a negative value.On systems where HZ is not 1000, could this underflow the delay parameter and schedule the next work millions of jiffies in the future?
Fixing in v6.
Quoted 11 lines
Quoted 11 lines
drivers/hid/hid-nintendo.c +10
-0+ }else { + ns2->last_rumble_work =0 ; + } +spin_unlock_irqrestore (&ns2->rumble_lock, flags); + +if (!ns2->hdev) { +cancel_delayed_work (&ns2->rumble_work); + ret = -ENODEV ; + }else { + ret =hid_hw_output_report (ns2->hdev, ns2->rumble_buffer,64 );
Quoted 8 lines
drivers/hid/hid-nintendo.c static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type) · line 3255
Quoted 4 lines
drivers/hid/hid-nintendo.c +4
-0+ } + +if (ret <0 ) +hid_dbg (ns2->hdev,"Failed to send output report ret=%d\n" , ret);If
ns2->hdevis NULL, we set ret =-ENODEVand then reach thishid_dbgcall. Could this result in a NULL pointer dereference, as thehid_dbgmacro passesns2->hdevtodev_dbg()?
Fixing in v6
Quoted 4 lines
Also, since
ns2->hdevis accessed locklessly and withoutREAD_ONCE(), is there a time-of-check to time-of-use race where the compiler might reload the pointer between the check andhid_hw_output_report()?
This can only get changed in switch2_remove, which is missing a cancel_delayed_work_sync. Fixing in v6.
Quoted 15 lines
[ ... ]
drivers/hid/hid-nintendo.c static int switch2_probe(struct hid_device *hdev, const struct hid_device_id *id · line 4055
Quoted 9 lines
drivers/hid/hid-nintendo.c +5
-0@@ -3881,6 +4048,14 @@ static int switch2_probe(struct hid_device *hdev, const struct hid_device_id *idswitch2_leds_create (ns2); +#if IS_ENABLED (CONFIG_NINTENDO_FF ) +if (ns2->ctlr_type !=NS2_CTLR_TYPE_GC ) { + ns2->rumble.hd.hi_freq =RUMBLE_HI_FREQ ; + ns2->rumble.hd.lo_freq =RUMBLE_LO_FREQ ; + }Are we checking
ns2->ctlr_typebefore it is dynamically initialized?
Quoted 6 lines
During probe,
ns2->ctlr_typeappears to be 0 since the struct is freshly allocated and the type is discovered later during the init state machine. This would cause the high and low frequencies to always be written.Since hd and sd share a union, could this corrupt the sd.error and sd.amplitude fields for actual GameCube controllers?
Really, really unimportant and technically "works by accident" territory but I'll move the logic anyway.
Quoted 6 lines
Quoted 5 lines
drivers/hid/hid-nintendo.c +3
-0+spin_lock_init (&ns2->rumble_lock); +INIT_DELAYED_WORK (&ns2->rumble_work, switch2_rumble_work); +#endif hid_set_drvdata (hdev, ns2);
Vicki Pfau
maintainerPATCH v5 3/3 HID: nintendo: Add unified report format support
In reply to Vicki PfauThis adds support for the "unified" report format that all controllers also support, which has overlapping fields for like buttons and axes between them.
--- drivers/hid/hid-nintendo.c | 148 +++++++++++++++++++++++++++++++++++-- 1 file changed, 143 insertions(+), 5 deletions(-)
drivers/hid/hid-nintendo.c +143 -5
@@ -2824,6 +2824,36 @@ static int joycon_suspend(struct hid_device *hdev, pm_message_t message)#define NS2_BTN3_SR BIT(6)#define NS2_BTN3_SL BIT(7) +#define NS2_BTN_U1_Y BIT(0) +#define NS2_BTN_U1_X BIT(1) +#define NS2_BTN_U1_B BIT(2) +#define NS2_BTN_U1_A BIT(3) +#define NS2_BTN_U1_SR BIT(4) +#define NS2_BTN_U1_SL BIT(5) +#define NS2_BTN_U1_R BIT(6) +#define NS2_BTN_U1_ZR BIT(7) + +#define NS2_BTN_U2_MINUS BIT(0) +#define NS2_BTN_U2_PLUS BIT(1) +#define NS2_BTN_U2_RS BIT(2) +#define NS2_BTN_U2_LS BIT(3) +#define NS2_BTN_U2_HOME BIT(4) +#define NS2_BTN_U2_CAPTURE BIT(5) +#define NS2_BTN_U2_C BIT(6) + +#define NS2_BTN_U3_DOWN BIT(0) +#define NS2_BTN_U3_UP BIT(1) +#define NS2_BTN_U3_RIGHT BIT(2) +#define NS2_BTN_U3_LEFT BIT(3) +#define NS2_BTN_U3_SR BIT(4) +#define NS2_BTN_U3_SL BIT(5) +#define NS2_BTN_U3_L BIT(6) +#define NS2_BTN_U3_ZL BIT(7) + +#define NS2_BTN_U4_GR BIT(0) +#define NS2_BTN_U4_GL BIT(1) +#define NS2_BTN_U4_HEADSET BIT(5) +#define NS2_BTN_JCR_HOME BIT(0)#define NS2_BTN_JCR_GR BIT(2)#define NS2_BTN_JCR_C NS2_BTN3_C
@@ -3069,6 +3099,22 @@ static const struct switch2_ctlr_button_mapping ns2_left_joycon_button_mappings[ { /* sentinel */ }, }; +static const struct switch2_ctlr_button_mapping ns2_left_joycon_button_unified_mappings[] = { + {BTN_DPAD_LEFT ,2 ,NS2_BTN_U3_LEFT , }, + {BTN_DPAD_UP ,2 ,NS2_BTN_U3_UP , }, + {BTN_DPAD_DOWN ,2 ,NS2_BTN_U3_DOWN , }, + {BTN_DPAD_RIGHT ,2 ,NS2_BTN_U3_RIGHT , }, + {BTN_TL ,2 ,NS2_BTN_U3_L , }, + {BTN_TL2 ,2 ,NS2_BTN_U3_ZL , }, + {BTN_SELECT ,1 ,NS2_BTN_U2_MINUS , }, + {BTN_THUMBL ,1 ,NS2_BTN_U2_LS , }, + {KEY_RECORD ,1 ,NS2_BTN_U2_CAPTURE , }, + {BTN_GRIPR ,2 ,NS2_BTN_U3_SL , }, + {BTN_GRIPR2 ,2 ,NS2_BTN_U3_SR , }, + {BTN_GRIPL ,3 ,NS2_BTN_U4_GL , }, + {/* sentinel */ }, +}; +static const struct switch2_ctlr_button_mapping ns2_right_joycon_button_mappings[] = { {BTN_SOUTH ,0 ,NS2_BTNR_A , }, {BTN_EAST ,0 ,NS2_BTNR_B , },
@@ -3086,6 +3132,23 @@ static const struct switch2_ctlr_button_mapping ns2_right_joycon_button_mappings { /* sentinel */ }, }; +static const struct switch2_ctlr_button_mapping ns2_right_joycon_button_unified_mappings[] = { + {BTN_SOUTH ,0 ,NS2_BTN_U1_A , }, + {BTN_EAST ,0 ,NS2_BTN_U1_B , }, + {BTN_NORTH ,0 ,NS2_BTN_U1_X , }, + {BTN_WEST ,0 ,NS2_BTN_U1_Y , }, + {BTN_TR ,0 ,NS2_BTN_U1_R , }, + {BTN_TR2 ,0 ,NS2_BTN_U1_ZR }, + {BTN_START ,1 ,NS2_BTN_U2_PLUS , }, + {BTN_THUMBR ,1 ,NS2_BTN_U2_RS , }, + {BTN_C ,1 ,NS2_BTN_U2_C , }, + {BTN_MODE ,1 ,NS2_BTN_U2_HOME , }, + {BTN_GRIPL2 ,0 ,NS2_BTN_U1_SL , }, + {BTN_GRIPL ,0 ,NS2_BTN_U1_SR , }, + {BTN_GRIPR ,3 ,NS2_BTN_U4_GR , }, + {/* sentinel */ }, +}; +static const struct switch2_ctlr_button_mapping ns2_procon_mappings[] = { {BTN_SOUTH ,0 ,NS2_BTNR_A , }, {BTN_EAST ,0 ,NS2_BTNR_B , },
@@ -3107,6 +3170,27 @@ static const struct switch2_ctlr_button_mapping ns2_procon_mappings[] = { { /* sentinel */ }, }; +static const struct switch2_ctlr_button_mapping ns2_procon_unified_mappings[] = { + {BTN_SOUTH ,0 ,NS2_BTN_U1_A , }, + {BTN_EAST ,0 ,NS2_BTN_U1_B , }, + {BTN_NORTH ,0 ,NS2_BTN_U1_X , }, + {BTN_WEST ,0 ,NS2_BTN_U1_Y , }, + {BTN_TL ,2 ,NS2_BTN_U3_L , }, + {BTN_TR ,0 ,NS2_BTN_U1_R , }, + {BTN_TL2 ,2 ,NS2_BTN_U3_ZL , }, + {BTN_TR2 ,0 ,NS2_BTN_U1_ZR , }, + {BTN_SELECT ,1 ,NS2_BTN_U2_MINUS , }, + {BTN_START ,1 ,NS2_BTN_U2_PLUS , }, + {BTN_THUMBL ,1 ,NS2_BTN_U2_LS , }, + {BTN_THUMBR ,1 ,NS2_BTN_U2_RS , }, + {BTN_MODE ,1 ,NS2_BTN_U2_HOME }, + {KEY_RECORD ,1 ,NS2_BTN_U2_CAPTURE }, + {BTN_GRIPR ,3 ,NS2_BTN_U4_GR }, + {BTN_GRIPL ,3 ,NS2_BTN_U4_GL }, + {BTN_C ,1 ,NS2_BTN_U2_C }, + {/* sentinel */ }, +}; +static const struct switch2_ctlr_button_mapping ns2_gccon_mappings[] = { {BTN_SOUTH ,0 ,NS2_BTNR_A , }, {BTN_EAST ,0 ,NS2_BTNR_B , },
@@ -3124,6 +3208,23 @@ static const struct switch2_ctlr_button_mapping ns2_gccon_mappings[] = { { /* sentinel */ }, }; +static const struct switch2_ctlr_button_mapping ns2_gccon_unified_mappings[] = { + {BTN_SOUTH ,0 ,NS2_BTN_U1_A , }, + {BTN_EAST ,0 ,NS2_BTN_U1_B , }, + {BTN_NORTH ,0 ,NS2_BTN_U1_X , }, + {BTN_WEST ,0 ,NS2_BTN_U1_Y , }, + {BTN_TL2 ,2 ,NS2_BTN_U3_L , }, + {BTN_TR2 ,0 ,NS2_BTN_U1_R , }, + {BTN_TL ,2 ,NS2_BTN_U3_ZL }, + {BTN_TR ,0 ,NS2_BTN_U1_ZR }, + {BTN_SELECT ,1 ,NS2_BTN_U2_MINUS , }, + {BTN_START ,1 ,NS2_BTN_U2_PLUS , }, + {BTN_MODE ,1 ,NS2_BTN_U2_HOME }, + {KEY_RECORD ,1 ,NS2_BTN_U2_CAPTURE }, + {BTN_C ,1 ,NS2_BTN_U2_C }, + {/* sentinel */ }, +}; +static const uint8_t switch2_init_cmd_data[] = {/* * The last 6 bytes of this packet are the MAC address of
@@ -3690,11 +3791,48 @@ static int switch2_event(struct hid_device *hdev, struct hid_report *report, uinswitch (report->id) {case NS2_REPORT_UNIFIED : -/* -* TODO -* This won't be sent unless the report type gets changed via command -* 03-0A, but we should support it at some point regardless. -*/ +switch (ns2->ctlr_type) { +case NS2_CTLR_TYPE_JCL : +switch2_report_stick (input, &ns2->stick_calib[0 ], +ABS_X , false,ABS_Y , true, &raw_data[11 ]); +switch2_report_buttons (input, &raw_data[5 ], + ns2_left_joycon_button_unified_mappings); +break ; +case NS2_CTLR_TYPE_JCR : +switch2_report_stick (input, &ns2->stick_calib[0 ], +ABS_X , false,ABS_Y , true, &raw_data[14 ]); +switch2_report_buttons (input, &raw_data[5 ], + ns2_right_joycon_button_unified_mappings); +break ; +case NS2_CTLR_TYPE_GC : +input_report_abs (input,ABS_HAT0X , + !!(raw_data[7 ] &NS2_BTN_U3_RIGHT ) - + !!(raw_data[7 ] &NS2_BTN_U3_LEFT )); +input_report_abs (input,ABS_HAT0Y , + !!(raw_data[7 ] &NS2_BTN_U3_DOWN ) - + !!(raw_data[7 ] &NS2_BTN_U3_UP )); +switch2_report_buttons (input, &raw_data[5 ], ns2_gccon_unified_mappings); +switch2_report_stick (input, &ns2->stick_calib[0 ], +ABS_X , false,ABS_Y , true, &raw_data[11 ]); +switch2_report_stick (input, &ns2->stick_calib[1 ], +ABS_RX , false,ABS_RY , true, &raw_data[14 ]); +switch2_report_trigger (input, ns2->lt_zero,ABS_Z , raw_data[0x3d ]); +switch2_report_trigger (input, ns2->rt_zero,ABS_RZ , raw_data[0x3e ]); +break ; +case NS2_CTLR_TYPE_PRO : +input_report_abs (input,ABS_HAT0X , + !!(raw_data[7 ] &NS2_BTN_U3_RIGHT ) - + !!(raw_data[7 ] &NS2_BTN_U3_LEFT )); +input_report_abs (input,ABS_HAT0Y , + !!(raw_data[7 ] &NS2_BTN_U3_DOWN ) - + !!(raw_data[7 ] &NS2_BTN_U3_UP )); +switch2_report_buttons (input, &raw_data[5 ], ns2_procon_unified_mappings); +switch2_report_stick (input, &ns2->stick_calib[0 ], +ABS_X , false,ABS_Y , true, &raw_data[11 ]); +switch2_report_stick (input, &ns2->stick_calib[1 ], +ABS_RX , false,ABS_RY , true, &raw_data[14 ]); +break ; + }break ;case NS2_REPORT_JCL : switch2_report_stick(input, &ns2->stick_calib[0], ABS_X, false,
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v5 3/3] HID: nintendo: Add unified report format support
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] Insufficient bounds checking for NS2_REPORT_UNIFIED payload leads to out-of-bounds reads. - [High]…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] Insufficient bounds checking for NS2_REPORT_UNIFIED payload leads to out-of-bounds reads.
- [High] Divide-by-zero kernel panic in switch2_report_trigger() caused by attacker-controlled calibration data. --
commit 6e45b564fde8014fc6ade8452a1b793097b3bee4
Author: Vicki Pfau <[email protected]>
Subject: HID: nintendo: Add unified report format support
This commit adds support for the "unified" report format to the nintendo hid driver. It introduces new mappings for overlapping button and axis fields across different controller types.
Quoted 4 lines
drivers/hid/hid-nintendo.c +0
-0
[ ... ]
Quoted 9 lines
drivers/hid/hid-nintendo.c +0
-5@@ -3690,11 +3791,48 @@ static int switch2_event(struct hid_device *hdev, struct hid_report *report, uinswitch (report->id) {case NS2_REPORT_UNIFIED : -/* -* TODO -* This won't be sent unless the report type gets changed via command -* 03-0A, but we should support it at some point regardless. -*/
drivers/hid/hid-nintendo.c static int switch2_event(struct hid_device *hdev, struct hid_report *report, uin · line 3803
Quoted 10 lines
drivers/hid/hid-nintendo.c +10
-0+switch (ns2->ctlr_type) { +case NS2_CTLR_TYPE_JCL : +switch2_report_stick (input, &ns2->stick_calib[0 ], +ABS_X , false,ABS_Y , true, &raw_data[11 ]); +switch2_report_buttons (input, &raw_data[5 ], + ns2_left_joycon_button_unified_mappings); +break ; +case NS2_CTLR_TYPE_JCR : +switch2_report_stick (input, &ns2->stick_calib[0 ], +ABS_X , false,ABS_Y , true, &raw_data[14 ]);
Is this safe if the report size is exactly 15 bytes?
Earlier in switch2_event(), there is a global size check:
if (size < 15)
return -EINVAL;However, switch2_report_stick() reads up to 3 bytes from the provided data pointer (indices 0, 1, and 2). Passing &raw_data[14] means it will read raw_data[14], raw_data[15], and raw_data[16].
Could this cause an out-of-bounds read if an undersized report is sent?
Quoted 7 lines
drivers/hid/hid-nintendo.c +7
-0+switch2_report_buttons (input, &raw_data[5 ], + ns2_right_joycon_button_unified_mappings); +break ; +case NS2_CTLR_TYPE_GC : +input_report_abs (input,ABS_HAT0X , + !!(raw_data[7 ] &NS2_BTN_U3_RIGHT ) - + !!(raw_data[7 ] &NS2_BTN_U3_LEFT ));
drivers/hid/hid-nintendo.c static int switch2_event(struct hid_device *hdev, struct hid_report *report, uin · line 3820
Quoted 10 lines
drivers/hid/hid-nintendo.c +10
-0+input_report_abs (input,ABS_HAT0Y , + !!(raw_data[7 ] &NS2_BTN_U3_DOWN ) - + !!(raw_data[7 ] &NS2_BTN_U3_UP )); +switch2_report_buttons (input, &raw_data[5 ], ns2_gccon_unified_mappings); +switch2_report_stick (input, &ns2->stick_calib[0 ], +ABS_X , false,ABS_Y , true, &raw_data[11 ]); +switch2_report_stick (input, &ns2->stick_calib[1 ], +ABS_RX , false,ABS_RY , true, &raw_data[14 ]); +switch2_report_trigger (input, ns2->lt_zero,ABS_Z , raw_data[0x3d ]); +switch2_report_trigger (input, ns2->rt_zero,ABS_RZ , raw_data[0x3e ]);
Similarly, does this code read past the end of the buffer?
Accessing raw_data[0x3d] (index 61) and raw_data[0x3e] (index 62) requires the report size to be at least 63 bytes, but the global check only guarantees 15 bytes.
Additionally, could this new path trigger a divide-by-zero panic?
While this issue pre-dates this commit, switch2_report_trigger() contains the following calculation:
int value = (NS2_TRIGGER_RANGE + 1) * (data - zero) / (232 - zero);
The zero parameter here comes from the device's factory calibration data (ns2->lt_zero and ns2->rt_zero). If a device advertises 232 as its zero calibration point, this division evaluates to 0.
Since this patch exposes a new way to call switch2_report_trigger(), might it be worth adding validation to prevent a zero divisor?
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+break ; +case NS2_CTLR_TYPE_PRO :
[ ... ]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Re: [PATCH v5 3/3] HID: nintendo: Add unified report format support
Quoted 42 lines · [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] Insufficient bounds checking forNS2_REPORT_UNIFIEDpayload leads to out-of-bounds reads.
- [High] Divide-by-zero kernel panic inswitch2_report_trigger()caused by attacker-controlled calibration data. --commit
6e45b564fde8014fc6ade8452a1b793097b3bee4
Author: Vicki Pfau <[email protected]>
Subject: HID: nintendo: Add unified report format supportThis commit adds support for the "unified" report format to the nintendo hid driver. It introduces new mappings for overlapping button and axis fields across different controller types.
Quoted 4 lines
drivers/hid/hid-nintendo.c +0
-0[ ... ]
Quoted 9 lines
drivers/hid/hid-nintendo.c +0
-5@@ -3690,11 +3791,48 @@ static int switch2_event(struct hid_device *hdev, struct hid_report *report, uinswitch (report->id) {case NS2_REPORT_UNIFIED : -/* -* TODO -* This won't be sent unless the report type gets changed via command -* 03-0A, but we should support it at some point regardless. -*/ drivers/hid/hid-nintendo.c static int switch2_event(struct hid_device *hdev, struct hid_report *report, uin · line 3803
Quoted 10 lines
drivers/hid/hid-nintendo.c +10
-0+switch (ns2->ctlr_type) { +case NS2_CTLR_TYPE_JCL : +switch2_report_stick (input, &ns2->stick_calib[0 ], +ABS_X , false,ABS_Y , true, &raw_data[11 ]); +switch2_report_buttons (input, &raw_data[5 ], + ns2_left_joycon_button_unified_mappings); +break ; +case NS2_CTLR_TYPE_JCR : +switch2_report_stick (input, &ns2->stick_calib[0 ], +ABS_X , false,ABS_Y , true, &raw_data[14 ]);Is this safe if the report size is exactly 15 bytes?
Earlier in
switch2_event(), there is a global size check:
Quoted 8 lines
if (size < 15) return -EINVAL;However,
switch2_report_stick()reads up to 3 bytes from the provided data pointer (indices 0, 1, and 2). Passing &raw_data[14] means it will read raw_data[14], raw_data[15], and raw_data[16].Could this cause an out-of-bounds read if an undersized report is sent?
Yes, I assume we would have to check for a bigger size here.
Quoted 21 lines
Quoted 8 lines
drivers/hid/hid-nintendo.c +7
-0+switch2_report_buttons (input, &raw_data[5 ], + ns2_right_joycon_button_unified_mappings); +break ; +case NS2_CTLR_TYPE_GC : +input_report_abs (input,ABS_HAT0X , + !!(raw_data[7 ] &NS2_BTN_U3_RIGHT ) - + !!(raw_data[7 ] &NS2_BTN_U3_LEFT ));drivers/hid/hid-nintendo.c static int switch2_event(struct hid_device *hdev, struct hid_report *report, uin · line 3820
Quoted 10 lines
drivers/hid/hid-nintendo.c +10
-0+input_report_abs (input,ABS_HAT0Y , + !!(raw_data[7 ] &NS2_BTN_U3_DOWN ) - + !!(raw_data[7 ] &NS2_BTN_U3_UP )); +switch2_report_buttons (input, &raw_data[5 ], ns2_gccon_unified_mappings); +switch2_report_stick (input, &ns2->stick_calib[0 ], +ABS_X , false,ABS_Y , true, &raw_data[11 ]); +switch2_report_stick (input, &ns2->stick_calib[1 ], +ABS_RX , false,ABS_RY , true, &raw_data[14 ]); +switch2_report_trigger (input, ns2->lt_zero,ABS_Z , raw_data[0x3d ]); +switch2_report_trigger (input, ns2->rt_zero,ABS_RZ , raw_data[0x3e ]);Similarly, does this code read past the end of the buffer?
Quoted 3 lines
Accessing raw_data[0x3d] (index 61) and raw_data[0x3e] (index 62) requires the report size to be at least 63 bytes, but the global check only guarantees 15 bytes.
Same here.
Quoted 6 lines
Additionally, could this new path trigger a divide-by-zero panic?
While this issue pre-dates this commit,
switch2_report_trigger()contains the following calculation:
Quoted 8 lines
int value = (NS2_TRIGGER_RANGE + 1) * (data - zero) / (232 - zero);The zero parameter here comes from the device's factory calibration data (
ns2->lt_zeroandns2->rt_zero). If a device advertises 232 as its zero calibration point, this division evaluates to 0.Since this patch exposes a new way to call
switch2_report_trigger(), might it be worth adding validation to prevent a zero divisor?
This one has been reported already in one of the earlier emails.
Cheers,
Silvan
Quoted 4 lines
Quoted 3 lines
drivers/hid/hid-nintendo.c +2
-0+break ; +case NS2_CTLR_TYPE_PRO :[ ... ]
Jiri Kosina
maintainerQuoted 10 lines · Vicki Pfau
This series adds preliminary support for Switch 2 controllers using the same split-driver model as previous versions. This is a minor iteration on v4, fixing some leaked
input_devobjects in error paths as well as fixing a merge/rebase error whenCONFIG_PMifdefs got removed in 7.0.Vicki Pfau (3):
HID: nintendo: Add preliminary Switch 2 controller driver
HID: nintendo: Add rumble support for Switch 2 controllers
HID: nintendo: Add unified report format support
Quoted 11 lines
MAINTAINERS | 1 + drivers/hid/Kconfig | 19 +- drivers/hid/hid-ids.h | 4 + drivers/hid/hid-nintendo.c | 1504 ++++++++++++++++- drivers/hid/hid-nintendo.h | 72 + drivers/input/joystick/Kconfig | 11 + drivers/input/joystick/Makefile | 1 + drivers/input/joystick/nintendo-switch2-usb.c | 353 ++++ 8 files changed, 1951 insertions(+), 14 deletions(-) create mode 100644 drivers/hid/hid-nintendo.h create mode 100644 drivers/input/joystick/nintendo-switch2-usb.c
Dmitry, do you have any review comments to the changes under drivers/input/joystick, please?
Thanks,
Signature · 2 lines
Jiri Kosina SUSE Labs