HID: nintendo: Add preliminary Switch 2 controller driver
Subsystems (3)
Vicki Pfau
maintainerv6 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 an iteration on v6, fixing errors pointed out by sashiko and others, as well as adding an additional packet for the rumble initialization that seemed to be necessary in some instances.
It also adds retry-throttling that had been previously discussed, but I had called unnecessary. It will leave devices in a partially-initialized state and log and error. While it should be unnecessary for first-party controllers, once third-party controllers start shipping it may prove necessary.
I've removed the Reviewed-by and Tested-by as enough has changed that I think it could use a fresh review/test as needed.
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 | 1552 ++++++++++++++++- drivers/hid/hid-nintendo.h | 72 + drivers/input/joystick/Kconfig | 11 + drivers/input/joystick/Makefile | 1 + drivers/input/joystick/nintendo-switch2-usb.c | 396 +++++ 8 files changed, 2042 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 v6 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 | 1221 ++++++++++++++++- drivers/hid/hid-nintendo.h | 72 + drivers/input/joystick/Kconfig | 11 + drivers/input/joystick/Makefile | 1 + drivers/input/joystick/nintendo-switch2-usb.c | 396 ++++++ 8 files changed, 1707 insertions(+), 10 deletions(-) create mode 100644 drivers/hid/hid-nintendo.h create mode 100644 drivers/input/joystick/nintendo-switch2-usb.c
MAINTAINERS +1 -0
@@ -19051,6 +19051,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
@@ -1103,6 +1103,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 +1215 -6
1,300 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 +396 -0
396 lines not on this page · raw message
Signature · 1 line
2.54.0
Vicki Pfau
maintainerPATCH v6 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 | 194 ++++++++++++++++++++++++++++++++++++- 2 files changed, 196 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 +192 -2
270 lines not on this page · raw message
Signature · 1 line
2.54.0
Vicki Pfau
maintainerPATCH v6 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 | 153 +++++++++++++++++++++++++++++++++++-- 1 file changed, 147 insertions(+), 6 deletions(-)
drivers/hid/hid-nintendo.c +147 -6
@@ -2872,6 +2872,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
@@ -3119,6 +3149,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 , },
@@ -3136,6 +3182,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 , },
@@ -3157,6 +3220,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 , },
@@ -3174,6 +3258,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
@@ -3732,7 +3833,7 @@ static int switch2_event(struct hid_device *hdev, struct hid_report *report, uinif (report->type !=HID_INPUT_REPORT )return 0 ; -if (size <15 ) +if (size <17 )return -EINVAL ;guard (rcu)();
@@ -3743,11 +3844,51 @@ 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 : +if (size <0x3f ) +return -EINVAL ; + +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 v6 3/3] HID: nintendo: Add unified report format support
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Global minimum report size check incorrectly rejects valid legacy, non-unified reports. --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Global minimum report size check incorrectly rejects valid legacy, non-unified reports. --
commit ebbc8f2a738bc80390ec8c8785093f44578537e8
Author: Vicki Pfau <[email protected]>
HID: nintendo: Add unified report format support
This commit adds support for the unified report format that all controllers also support. It includes overlapping fields for like buttons and axes between them.
Quoted 4 lines
drivers/hid/hid-nintendo.c +0
-0
[ ... ]
drivers/hid/hid-nintendo.c static int switch2_event(struct hid_device *hdev, struct hid_report *report, uin · line 3838
Quoted 8 lines
drivers/hid/hid-nintendo.c +1
-1@@ -3732,7 +3833,7 @@ static int switch2_event(struct hid_device *hdev, struct hid_report *report, uinif (report->type !=HID_INPUT_REPORT )return 0 ; -if (size <15 ) +if (size <17 )return -EINVAL ;
[Severity: High]
Does this global size check incorrectly reject valid non-unified reports?
Since non-unified reports like NS2_REPORT_GC only access up to raw_data[14] and can legitimately have a size of exactly 15 bytes, it seems this check will cause those legitimate 15-byte or 16-byte reports to be dropped with -EINVAL in switch2_event().
Should this 17-byte requirement be scoped inside the case NS2_REPORT_UNIFIED:
block instead?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
[email protected]
AI reviewThank you for your contribution! Sashiko AI review found 14 potential issue(s) to consider: - [High] Early HID start before driver data is set causes NULL pointer dereference in event handler.…
Thank you for your contribution! Sashiko AI review found 14 potential issue(s) to consider:
- [High] Early HID start before driver data is set causes NULL pointer dereference in event handler.
- [High] Explicitly unregistering and freeing a devm-allocated input device violates input subsystem rules and causes double-frees.
- [High] LEDs registered with devm tied to input->dev lead to Use-After-Free when the parent ns2 structure is dynamically freed.
- [High] USB bulk input pipeline permanently stalls if URBs complete before the workqueue processes them.
- [High] Lockless modification of urb->state before unanchoring in USB output error path causes UAF and DMA corruption.
- [High] Concurrent driver unbind causes a Use-After-Free of struct switch2_controller.
- [High] Teardown ordering in switch2_usb_disconnect() frees bulk_out URBs before cancelling message_in_work.
- [High] Missing cancel_work_sync() in switch2_usb_probe error path leads to UAF of ns2_usb.
- [High] Calling hid_hw_close(hdev) after hid_hw_open(hdev) fails corrupts ll_open_count.
- [High] usb_free_coherent() is called while holding a spinlock with IRQs disabled.
- [Medium] Calling ida_free() with an unallocated player ID (U32_MAX) triggers a kernel warning.
- [Medium] Leaking OUT URBs on memory allocation failure in switch2_usb_probe.
- [Medium] Mixing goto error handling with guard() cleanup violates subsystem anti-pattern rules.
- [Low] Calling usb_make_path() introduces an undeclared hard dependency on the USB core.
--
commit 322f53e1d34ab62127ead48da7aeff5c1763e2a2
Author: Vicki Pfau <[email protected]>
HID: nintendo: Add preliminary Switch 2 controller driver
This commit introduces support for the Nintendo Switch 2 Joy-Cons, Pro Controller, and GameCube controllers. It implements a split-interface design using a main HID driver and a secondary configuration interface. Initial support handles general input and USB communications.
drivers/hid/Kconfig config HID_NINTENDO · line 844
Quoted 6 lines
drivers/hid/Kconfig +0
-0@@ -843,10 +843,13 @@ config HID_NINTENDO depends on LEDS_CLASS select POWER_SUPPLY
[Severity: Low]
Does this new configuration introduce an undeclared dependency?
The newly added switch2_probe() function in hid-nintendo.c calls usb_make_path(), which is an exported symbol from the USB core. However, CONFIG_HID_NINTENDO does not specify depends on USB.
If the kernel is built with CONFIG_HID_NINTENDO=y and CONFIG_USB=m, will the build fail during linking due to an unresolved reference to usb_make_path?
Quoted 3 lines
drivers/hid/hid-nintendo.c +0
-0
[ ... ]
Quoted 3 lines
drivers/hid/hid-nintendo.c +3
-0+static int switch2_init_input (struct switch2_controller *ns2) +{ +struct input_dev *input;
[ ... ]
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3234
Quoted 6 lines
drivers/hid/hid-nintendo.c +6
-0+ input =devm_input_allocate_device (&hdev->dev); +if (!input) +return -ENOMEM ; + +input_set_drvdata (input, ns2); + input->dev.parent = &hdev->dev;
[Severity: High]
Does explicitly unregistering and freeing a devm-allocated input device violate input subsystem rules and cause double-frees?
The driver allocates the input device using devm_input_allocate_device(). The input subsystem automatically handles cleanup when the provider device is unbound. However, the driver explicitly calls input_free_device() on failure paths in switch2_init_input() and input_unregister_device() in its teardown path switch2_controller_put().
Can this cause a double-free or double-unregister when the devres callbacks later attempt to clean up the same device? Additionally, is manually setting input->dev.parent redundant and prohibited for devm-allocated input devices?
[ ... ]
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+for (i =0 ; i <JC_NUM_LEDS ; i++) { +struct led_classdev *led = &ns2->leds[i];
[ ... ]
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3312
Quoted 8 lines
drivers/hid/hid-nintendo.c +8
-0+ ret =devm_led_classdev_register (&input->dev, led); +if (ret <0 ) { +dev_err (&input->dev,"Failed to register player %d LED; ret=%d\n" , + i +1 , ret); +input_unregister_device (input); +return ret; + } + }
[Severity: High]
Can tying the devm-managed LEDs to input->dev lead to a Use-After-Free when the parent ns2 structure is dynamically freed?
The LEDs are registered using devm_led_classdev_register() with input->dev. The ns2 structure containing the LEDs is manually freed via kfree(ns2) in switch2_controller_put().
The devres callbacks for input->dev execute when its refcount drops to zero. If userspace holds an open file descriptor to the input device, this cleanup can be arbitrarily delayed.
Will the driver free ns2 immediately while the LEDs remain registered and pointing to freed memory until the fd is closed, resulting in a Use-After-Free if sysfs LED attributes are accessed?
[ ... ]
Quoted 18 lines
drivers/hid/hid-nintendo.c +18
-0+static void switch2_controller_put (struct switch2_controller *ns2) +{ +struct input_dev *input; +bool do_free; + +guard (mutex)(&switch2_controllers_lock); +mutex_lock (&ns2->lock); + +rcu_read_lock (); + input =rcu_dereference (ns2->input); +rcu_read_unlock (); + +rcu_assign_pointer (ns2->input,NULL ); +synchronize_rcu (); + + ns2->init_step =0 ; + do_free = !ns2->hdev && !ns2->cfg; +mutex_unlock (&ns2->lock);
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3366
Quoted 10 lines
drivers/hid/hid-nintendo.c +10
-0+ +if (input) +input_unregister_device (input); + +if (do_free) { +list_del_init (&ns2->entry); +mutex_destroy (&ns2->lock); +kfree (ns2); + } +}
[Severity: High]
Could a concurrent driver unbind cause a Use-After-Free of the ns2 structure?
The guard(mutex)(&switch2_controllers_lock) holds the global lock for the entire function scope. If HID and USB disconnect concurrently, both clear their pointers and call switch2_controller_put().
If the first thread evaluates do_free as true, destroys the mutex, frees ns2, and returns, it releases the global lock.
Will the second thread, which was blocked waiting on the global lock, wake up and immediately call mutex_lock(&ns2->lock) using the pointer that was just freed?
[ ... ]
Quoted 4 lines
drivers/hid/hid-nintendo.c +4
-0+static int switch2_event (struct hid_device *hdev,struct hid_report *report,uint8_t *raw_data, +int size) +{ +struct switch2_controller *ns2 =hid_get_drvdata (hdev);
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3572
Quoted 10 lines
drivers/hid/hid-nintendo.c +10
-0+struct input_dev *input; + +if (report->type !=HID_INPUT_REPORT ) +return 0 ; + +if (size <15 ) +return -EINVAL ; + +guard (rcu)(); + input =rcu_dereference (ns2->input);
[Severity: High]
Could this event handler dereference uninitialized driver data during early hardware I/O startup?
The switch2_probe() function calls hid_hw_start(hdev, HID_CONNECT_HIDRAW) before assigning its private data with hid_set_drvdata(). This connects the device to hidraw, allowing userspace to immediately open it and trigger input events, or the underlying transport can send events.
If an event arrives during this race window, will switch2_event() call hid_get_drvdata(hdev) and receive a NULL pointer, leading to a kernel crash when calling rcu_dereference(ns2->input)?
[ ... ]
Quoted 20 lines
drivers/hid/hid-nintendo.c +20
-0+int switch2_receive_command (struct switch2_controller *ns2, +const uint8_t *message,size_t length) +{ +const struct switch2_cmd_header *header; +int ret =0 ; + +if (length <8 ) +return -EINVAL ; + +print_hex_dump_debug ("got cmd: " ,DUMP_PREFIX_OFFSET ,16 ,1 , message, length, false); + +guard (mutex)(&ns2->lock); + + header = (const struct switch2_cmd_header *)message; +if (!(header->flags &NS2_FLAG_OK )) { +dev_warn (ns2->cfg->dev,"Packet error %02x replying to command %x:%x" , + header->flags, header->command, header->subcommand); + ret = -EIO ; + goto exit; + }
[ ... ]
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3852
Quoted 6 lines
drivers/hid/hid-nintendo.c +6
-0+exit: +if (ns2->init_step <NS2_INIT_DONE ) +switch2_init_controller (ns2); + +return ret; +}
[Severity: Medium]
Does mixing goto error handling with guard() cleanup violate subsystem rules?
This function utilizes guard(mutex)(&ns2->lock) to acquire the lock using scope-based cleanup, but later uses goto exit to jump to a cleanup label on error paths.
The core kernel cleanup guidelines explicitly forbid mixing goto-based cleanup labels and guard() declarations in the same routine, as it creates confusing ownership semantics.
[ ... ]
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+static int switch2_probe (struct hid_device *hdev,const struct hid_device_id *id) +{
[ ... ]
Quoted 7 lines
drivers/hid/hid-nintendo.c +7
-0+ ret =hid_hw_start (hdev,HID_CONNECT_HIDRAW ); +if (ret) { +hid_err (hdev,"hw_start failed %d\n" , ret); +return ret; + } + + ns2 =switch2_get_controller (phys);
[ ... ]
Quoted 6 lines
drivers/hid/hid-nintendo.c +6
-0+ ns2->player_id =U32_MAX ; + ret =ida_alloc (&nintendo_player_id_allocator,GFP_KERNEL ); +if (ret <0 ) +hid_warn (hdev,"Failed to allocate player ID, skipping; ret=%d\n" , ret); +else + ns2->player_id = ret;
[ ... ]
Quoted 12 lines
drivers/hid/hid-nintendo.c +12
-0+hid_set_drvdata (hdev, ns2); + + ret =hid_hw_open (hdev); +if (ret) { +hid_err (hdev,"hw_open failed %d\n" , ret); + goto err_cleanup; + } + + ret =0 ; +if (ns2->cfg) + ret =switch2_init_controller (ns2); +
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3969
Quoted 10 lines
drivers/hid/hid-nintendo.c +10
-0+if (!ret) { +mutex_unlock (&ns2->lock); +return 0 ; + } + +err_cleanup: +hid_hw_close (hdev); +ida_free (&nintendo_player_id_allocator, ns2->player_id); + ns2->hdev =NULL ; +mutex_unlock (&ns2->lock);
[Severity: High]
If hid_hw_open() fails, does the unconditional call to hid_hw_close(hdev) corrupt the ll_open_count tracking?
If hid_hw_open(hdev) fails, execution jumps to the err_cleanup label, which unconditionally calls hid_hw_close(hdev).
Since hid_hw_open() does not increment ll_open_count on failure, will hid_hw_close() decrement the count from 0, wrapping it around to UINT_MAX and permanently silently preventing any future opens of the device?
[Severity: Medium]
Does this error path trigger a WARN_ON when trying to free an unallocated player ID?
The code initializes ns2->player_id to U32_MAX. If ida_alloc() fails, it skips allocation but retains the U32_MAX value.
In the err_cleanup path, or during switch2_remove(), the driver unconditionally calls ida_free(&nintendo_player_id_allocator, ns2->player_id).
Will passing -1 (U32_MAX) to ida_free() trigger a WARN_ON within the IDA framework?
Quoted 3 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 28 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +28
-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->bulk_in[i].state =NS2_URB_IN ; +continue ; + } + +if (ns2_usb->bulk_in[i].state !=NS2_URB_FREE ) +continue ; + + ns2_urb = &ns2_usb->bulk_in[i]; +usb_anchor_urb (ns2_urb->urb, &ns2_usb->bulk_in_anchor); + err =usb_submit_urb (ns2_urb->urb,GFP_ATOMIC ); +if (err) { +usb_unanchor_urb (ns2_urb->urb); +dev_dbg (&ns2_usb->udev->dev,"failed to queue input urb: %d\n" , err); + }else { + ns2_urb->state =NS2_URB_OUT ; + } + } +spin_unlock_irqrestore (&ns2_usb->bulk_in_lock, flags); + +if (schedule) +schedule_work (&ns2_usb->message_in_work); +}
[ ... ]
Quoted 2 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +2
-0+static void switch2_usb_message_in_work (struct work_struct *work) +{
[ ... ]
drivers/input/joystick/nintendo-switch2-usb.c line 206
Quoted 5 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +5
-0+spin_lock_irqsave (&ns2_usb->bulk_in_lock, flags); + urb->state =NS2_URB_FREE ; + } +spin_unlock_irqrestore (&ns2_usb->bulk_in_lock, flags); +}
[Severity: High]
Does this input URB handling stall the USB bulk input pipeline permanently if the URBs complete too quickly?
The driver manages IN URBs via a ping-pong mechanism. switch2_bulk_in() submits URBs in the NS2_URB_FREE state. The worker switch2_usb_message_in_work() clears processed URBs to NS2_URB_FREE but does not re-submit them.
If all active URBs complete in quick succession before the workqueue thread runs, they will all be marked NS2_URB_IN. The worker will process them and mark them FREE, but since no URBs are left active in the USB core to trigger the completion handler, will switch2_bulk_in() never be called again, permanently halting input?
[ ... ]
Quoted 3 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +3
-0+static int switch2_usb_send_cmd (enum switch2_cmd command,uint8_t subcommand, +const void *message,size_t size,struct switch2_cfg_intf *cfg) +{
[ ... ]
drivers/input/joystick/nintendo-switch2-usb.c line 180
Quoted 12 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +12
-0+usb_anchor_urb (urb->urb, &ns2_usb->bulk_out_anchor); + ret =usb_submit_urb (urb->urb,GFP_ATOMIC ); +if (ret) { +if (ret != -ENODEV ) +dev_warn (&ns2_usb->udev->dev,"failed to submit output urb: %i" , ret); + urb->state =NS2_URB_FREE ; +usb_unanchor_urb (urb->urb); +return ret; + } + +return 0 ; +}
[Severity: High]
Can this lockless modification of urb->state lead to a data race and potential DMA corruption?
If usb_submit_urb() fails, urb->state = NS2_URB_FREE is set without re-acquiring ns2_usb->bulk_out_lock. Additionally, it is marked FREE before calling usb_unanchor_urb().
Could a concurrent thread acquire the lock, claim this supposedly free URB, write to its DMA buffer, and submit it, right as the original thread unanchors it? During teardown, usb_kill_anchored_urbs() would not wait for this unanchored URB, potentially leading to its DMA buffer being freed while the hardware is still accessing it.
[ ... ]
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 9 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +9
-0+for (i =0 ; i <NS2_OUT_URBS ; i++) { +struct urb *urb; +uint8_t *data; + + urb =usb_alloc_urb (0 ,GFP_KERNEL ); +if (!urb) { + ret = -ENOMEM ; + goto err_free_in; + }
[ ... ]
Quoted 20 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +20
-0+ ret =switch2_controller_attach_cfg (phys, &ns2_usb->cfg); +if (ret <0 ) + goto err_free_out; + +return 0 ; + +err_free_out: +usb_kill_anchored_urbs (&ns2_usb->bulk_out_anchor); +spin_lock_irqsave (&ns2_usb->bulk_out_lock, flags); +for (i =0 ; i <NS2_OUT_URBS ; i++) { +if (!ns2_usb->bulk_out[i].urb) +continue ; + +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); +err_free_in: +usb_kill_anchored_urbs (&ns2_usb->bulk_in_anchor);
[ ... ]
drivers/input/joystick/nintendo-switch2-usb.c line 344
Quoted 4 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +4
-0+devm_kfree (&intf->dev, ns2_usb); + +return ret; +}
[Severity: Medium]
Does this error handling skip cleaning up successfully allocated OUT URBs?
During the loop allocating OUT URBs, if usb_alloc_urb() fails, the code branches to goto err_free_in. This skips the err_free_out block entirely.
Will this permanently leak the OUT URBs and their DMA buffers from any preceding successful loop iterations?
[Severity: High]
Does calling usb_free_coherent() inside the atomic critical section violate DMA API rules?
In the err_free_out block, usb_free_coherent() is called while the bulk_out_lock spinlock is held with IRQs disabled (using spin_lock_irqsave).
Since usb_free_coherent() is a wrapper for dma_free_coherent() and freeing memory allocated with GFP_KERNEL may sleep, will this cause deadlocks or kernel panics under CONFIG_DEBUG_ATOMIC_SLEEP?
[Severity: High]
Is a cancel_work_sync() missing from this error path, potentially causing a Use-After-Free?
An IN URB is submitted before calling switch2_controller_attach_cfg(). If the device responds immediately, switch2_bulk_in() will schedule ns2_usb->message_in_work.
If attach_cfg fails, the error path frees ns2_usb via devm_kfree() but never calls cancel_work_sync(&ns2_usb->message_in_work).
Could the scheduled work execute later on the freed memory footprint of ns2_usb?
[ ... ]
Quoted 7 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +7
-0+static void switch2_usb_disconnect (struct usb_interface *intf) +{ +struct switch2_usb *ns2_usb =usb_get_intfdata (intf); +unsigned long flags; +int i; + +usb_kill_anchored_urbs (&ns2_usb->bulk_out_anchor);
drivers/input/joystick/nintendo-switch2-usb.c line 362
Quoted 10 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +10
-0+spin_lock_irqsave (&ns2_usb->bulk_out_lock, flags); +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); + +usb_kill_anchored_urbs (&ns2_usb->bulk_in_anchor); +cancel_work_sync (&ns2_usb->message_in_work);
[Severity: High]
Does freeing the bulk_out URBs before cancelling the worker lead to a Use-After-Free and DMA corruption?
All bulk_out URBs and their DMA buffers are freed before the driver invokes cancel_work_sync(&ns2_usb->message_in_work).
Can the globally scheduled workqueue run concurrently during this gap, process incoming messages, and trigger a reply via switch2_usb_send_cmd()?
If so, will the send function claim a freed URB and write to the freed DMA buffer, leading to a Use-After-Free and submitting corrupted DMA to the USB controller?
[Severity: High]
Does calling usb_free_coherent() inside the atomic critical section violate DMA API rules?
Similar to the probe error path, usb_free_coherent() is called while the bulk_out_lock spinlock is held with IRQs disabled (using spin_lock_irqsave).
Since freeing memory allocated with GFP_KERNEL may sleep, will this cause deadlocks or kernel panics under CONFIG_DEBUG_ATOMIC_SLEEP?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
[email protected]
AI reviewRe: [PATCH v6 2/3] HID: nintendo: Add rumble support for Switch 2 controllers
In reply to Vicki PfauThank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider: - [High] Unsynchronized accesses to ns2->hdev allow rumble work to read a closing device pointer, leading…
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [High] Unsynchronized accesses to ns2->hdev allow rumble work to read a closing device pointer, leading to a TOCTOU NULL pointer dereference.
- [High] cancel_delayed_work_sync() is called on an uninitialized work structure if the configuration interface detaches without the HID interface probing.
- [High] Use-after-free of ns2 due to the input core's memless force feedback timer outliving the driver's private data.
- [Medium] Arithmetic underflow in schedule_delayed_work() delay calculation causes the rumble worker to permanently hang if its execution is delayed.
- [Low] Unused static constant array switch2_zero_data leads to dead code.
--
commit 93841885eb908e1356dc311955f33fee3d1428c6
Author: Vicki Pfau <[email protected]>
HID: nintendo: Add rumble support for Switch 2 controllers
This commit adds basic rumble support for the Switch 2 controllers. It introduces delayed work and force feedback support.
Quoted 4 lines
drivers/hid/hid-nintendo.c +0
-0
[ ... ]
drivers/hid/hid-nintendo.c static const uint8_t switch2_init_cmd_data[] = { · line 3188
Quoted 7 lines
drivers/hid/hid-nintendo.c +3
-0@@ -3133,9 +3183,12 @@ static const uint8_t switch2_init_cmd_data[] = { };static const uint8_t switch2_one_data[] = {0x01 ,0x00 ,0x00 ,0x00 }; +#if IS_ENABLED (CONFIG_NINTENDO_FF ) +static const uint8_t switch2_zero_data[] = {0x00 ,0x00 ,0x00 ,0x00 }; +#endif
[Severity: Low]
Is this unused variable intentional? It appears switch2_zero_data is never utilized anywhere in the codebase.
[ ... ]
drivers/hid/hid-nintendo.c static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type) · line 3226
Quoted 8 lines
drivers/hid/hid-nintendo.c +8
-0+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 ; + +guard (spinlock_irqsave)(&ns2->rumble_lock);
[Severity: High]
Can this result in a use-after-free when the input device outlives the driver data?
During device removal, switch2_controller_put() explicitly calls kfree(ns2). However, the input device is devres-managed and its lifetime is tied to userspace holding its file descriptor open. Since the input core's memless force feedback timer is only destroyed when the input device is released, the timer callback switch2_play_effect() could potentially fire after ns2 has been freed.
[ ... ]
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+static void switch2_rumble_work (struct work_struct *work) +{
[ ... ]
drivers/hid/hid-nintendo.c static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type) · line 3294
Quoted 10 lines
drivers/hid/hid-nintendo.c +10
-0+if (active) { +unsigned long interval =msecs_to_jiffies (2 ); +uint64_t current_jiffies =get_jiffies_64 (); + +if (!ns2->last_rumble_work) + ns2->last_rumble_work = current_jiffies; +else + ns2->last_rumble_work += interval; +schedule_delayed_work (&ns2->rumble_work, + ns2->last_rumble_work + interval - current_jiffies);
[Severity: Medium]
Could this delay calculation underflow?
If the worker thread is delayed by the scheduler such that current_jiffies exceeds the expected execution time (ns2->last_rumble_work + interval), the unsigned arithmetic could underflow to a value near ULONG_MAX. This would schedule the next rumble update weeks in the future, permanently hanging the force feedback mechanism.
drivers/hid/hid-nintendo.c static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type) · line 3303
Quoted 9 lines
drivers/hid/hid-nintendo.c +9
-0+ }else { + ns2->last_rumble_work =0 ; + } +spin_unlock_irqrestore (&ns2->rumble_lock, flags); + +if (!ns2->hdev) +cancel_delayed_work (&ns2->rumble_work); +else + ret =hid_hw_output_report (ns2->hdev, ns2->rumble_buffer,64 );
[Severity: High]
Is it possible for a concurrent removal to cause a NULL pointer dereference here?
Because ns2->hdev is read outside of any lock, there may be a window where it is verified as non-NULL, but then set to NULL by a concurrent switch2_remove() before being passed to hid_hw_output_report(). This appears structurally possible if userspace invokes switch2_play_effect() and reschedules the worker right after the initial cancellation in switch2_remove().
[ ... ]
drivers/hid/hid-nintendo.c static void switch2_controller_put(struct switch2_controller *ns2) · line 3526
Quoted 7 lines
drivers/hid/hid-nintendo.c +3
-0@@ -3358,6 +3521,10 @@ static void switch2_controller_put(struct switch2_controller *ns2)if (input)input_unregister_device (input); +#if IS_ENABLED (CONFIG_NINTENDO_FF ) +cancel_delayed_work_sync (&ns2->rumble_work); +#endif
[Severity: High]
Could this cancel operation act on an uninitialized work structure?
The switch2_probe() function initializes the work structure:
INIT_DELAYED_WORK(&ns2->rumble_work, switch2_rumble_work);
If the configuration interface detaches before the HID interface probes, ns2->rumble_work might remain zero-initialized. When switch2_controller_put() is called, unconditionally invoking cancel_delayed_work_sync() on this uninitialized work structure could trigger lockdep warnings and kernel panics.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
Vicki Pfau
maintainerRe: [PATCH v6 3/3] HID: nintendo: Add unified report format support
In reply to [email protected]Quoted 32 lines · On 6/24/26 10:13 PM, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Global minimum report size check incorrectly rejects valid legacy, non-unified reports. --commit
ebbc8f2a738bc80390ec8c8785093f44578537e8
Author: Vicki Pfau <[email protected]>HID: nintendo: Add unified report format support
This commit adds support for the unified report format that all controllers also support. It includes overlapping fields for like buttons and axes between them.
Quoted 4 lines
drivers/hid/hid-nintendo.c +0
-0[ ... ]
drivers/hid/hid-nintendo.c static int switch2_event(struct hid_device *hdev, struct hid_report *report, uin · line 3838
Quoted 8 lines
drivers/hid/hid-nintendo.c +1
-1@@ -3732,7 +3833,7 @@ static int switch2_event(struct hid_device *hdev, struct hid_report *report, uinif (report->type !=HID_INPUT_REPORT )return 0 ; -if (size <15 ) +if (size <17 )return -EINVAL ;[Severity: High]
Does this global size check incorrectly reject valid non-unified reports?
Quoted 8 lines
Since non-unified reports like
NS2_REPORT_GConly access up to raw_data[14] and can legitimately have a size of exactly 15 bytes, it seems this check will cause those legitimate 15-byte or 16-byte reports to be dropped with-EINVALinswitch2_event().Should this 17-byte requirement be scoped inside the case
NS2_REPORT_UNIFIED:
block instead?
Generally speaking, these reports should always be 63 bytes. This check is mostly here as a basic sanity check to make sure we don't accidentally reach out of bounds in the case of something very weird happening. It's fine if it seems a little overzealous since it's so far beyond normal operation already. I would guess than the Switch 2 rejects anything that short out-of-hand already.
Vicki Pfau
maintainerMore LLM hallucinations to deal with:
Quoted 37 lines · On 6/24/26 10:16 PM, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 14 potential issue(s) to consider:
- [High] Early HID start before driver data is set causes NULL pointer dereference in event handler.
- [High] Explicitly unregistering and freeing a devm-allocated input device violates input subsystem rules and causes double-frees.
- [High] LEDs registered with devm tied toinput->devlead to Use-After-Free when the parentns2structure is dynamically freed.
- [High] USB bulk input pipeline permanently stalls if URBs complete before the workqueue processes them.
- [High] Lockless modification ofurb->statebefore unanchoring in USB output error path causes UAF and DMA corruption.
- [High] Concurrent driver unbind causes a Use-After-Free ofstruct switch2_controller.
- [High] Teardown ordering inswitch2_usb_disconnect()freesbulk_outURBs before cancellingmessage_in_work.
- [High] Missingcancel_work_sync()inswitch2_usb_probeerror path leads to UAF ofns2_usb.
- [High] Callinghid_hw_close(hdev)afterhid_hw_open(hdev)fails corruptsll_open_count.
- [High]usb_free_coherent()is called while holding a spinlock with IRQs disabled.
- [Medium] Callingida_free()with an unallocated player ID (U32_MAX) triggers a kernel warning.
- [Medium] Leaking OUT URBs on memory allocation failure inswitch2_usb_probe.
- [Medium] Mixinggotoerror handling withguard()cleanup violates subsystem anti-pattern rules.
- [Low] Callingusb_make_path()introduces an undeclared hard dependency on the USB core.
--commit
322f53e1d34ab62127ead48da7aeff5c1763e2a2
Author: Vicki Pfau <[email protected]>HID: nintendo: Add preliminary Switch 2 controller driver
This commit introduces support for the Nintendo Switch 2 Joy-Cons, Pro Controller, and GameCube controllers. It implements a split-interface design using a main HID driver and a secondary configuration interface. Initial support handles general input and USB communications.
drivers/hid/Kconfig config HID_NINTENDO · line 844
Quoted 6 lines
drivers/hid/Kconfig +0
-0@@ -843,10 +843,13 @@ config HID_NINTENDO depends on LEDS_CLASS select POWER_SUPPLY[Severity: Low]
Does this new configuration introduce an undeclared dependency?
Quoted 3 lines
The newly added
switch2_probe()function inhid-nintendo.ccallsusb_make_path(), which is an exported symbol from the USB core. However,CONFIG_HID_NINTENDOdoes not specify depends on USB.
No it's not. It's a static inline function in a header and has been since 2.4.20 over 20 years ago.
Quoted 29 lines
If the kernel is built with
CONFIG_HID_NINTENDO=yandCONFIG_USB=m, will the build fail during linking due to an unresolved reference tousb_make_path?>Quoted 3 lines
drivers/hid/hid-nintendo.c +0
-0[ ... ]
Quoted 3 lines
drivers/hid/hid-nintendo.c +3
-0+static int switch2_init_input (struct switch2_controller *ns2) +{ +struct input_dev *input;[ ... ]
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3234
Quoted 6 lines
drivers/hid/hid-nintendo.c +6
-0+ input =devm_input_allocate_device (&hdev->dev); +if (!input) +return -ENOMEM ; + +input_set_drvdata (input, ns2); + input->dev.parent = &hdev->dev;[Severity: High]
Does explicitly unregistering and freeing a devm-allocated input device violate input subsystem rules and cause double-frees?The driver allocates the input device using
devm_input_allocate_device(). The input subsystem automatically handles cleanup when the provider device is unbound. However, the driver explicitly callsinput_free_device()on failure paths inswitch2_init_input()andinput_unregister_device()in its teardown pathswitch2_controller_put().
Quoted 3 lines
Can this cause a double-free or double-unregister when the devres callbacks later attempt to clean up the same device? Additionally, is manually setting
input->dev.parentredundant and prohibited for devm-allocated input devices?
I've already explained why this is wrong.
Quoted 22 lines
[ ... ]
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+for (i =0 ; i <JC_NUM_LEDS ; i++) { +struct led_classdev *led = &ns2->leds[i];[ ... ]
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3312
Quoted 8 lines
drivers/hid/hid-nintendo.c +8
-0+ ret =devm_led_classdev_register (&input->dev, led); +if (ret <0 ) { +dev_err (&input->dev,"Failed to register player %d LED; ret=%d\n" , + i +1 , ret); +input_unregister_device (input); +return ret; + } + }[Severity: High]
Can tying the devm-managed LEDs toinput->devlead to a Use-After-Free when the parent ns2 structure is dynamically freed?The LEDs are registered using
devm_led_classdev_register()withinput->dev. The ns2 structure containing the LEDs is manually freed via kfree(ns2) inswitch2_controller_put().
Quoted 7 lines
The devres callbacks for
input->devexecute when its refcount drops to zero. If userspace holds an open file descriptor to the input device, this cleanup can be arbitrarily delayed.Will the driver free ns2 immediately while the LEDs remain registered and pointing to freed memory until the fd is closed, resulting in a Use-After-Free if sysfs LED attributes are accessed?
While there is an exceedingly narrow window for this I think it is theoretically possible. I'll just treat issues creating the LEDs as non-fatal and continue onwards. They can get torn down at the end like everything else.
Quoted 38 lines
[ ... ]
Quoted 18 lines
drivers/hid/hid-nintendo.c +18
-0+static void switch2_controller_put (struct switch2_controller *ns2) +{ +struct input_dev *input; +bool do_free; + +guard (mutex)(&switch2_controllers_lock); +mutex_lock (&ns2->lock); + +rcu_read_lock (); + input =rcu_dereference (ns2->input); +rcu_read_unlock (); + +rcu_assign_pointer (ns2->input,NULL ); +synchronize_rcu (); + + ns2->init_step =0 ; + do_free = !ns2->hdev && !ns2->cfg; +mutex_unlock (&ns2->lock);drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3366
Quoted 10 lines
drivers/hid/hid-nintendo.c +10
-0+ +if (input) +input_unregister_device (input); + +if (do_free) { +list_del_init (&ns2->entry); +mutex_destroy (&ns2->lock); +kfree (ns2); + } +}[Severity: High]
Could a concurrent driver unbind cause a Use-After-Free of the ns2 structure?The guard(mutex)(&switch2_controllers_lock) holds the global lock for the entire function scope. If HID and USB disconnect concurrently, both clear their pointers and call
switch2_controller_put().
Quoted 6 lines
If the first thread evaluates
do_freeas true, destroys the mutex, frees ns2, and returns, it releases the global lock.Will the second thread, which was blocked waiting on the global lock, wake up and immediately call
mutex_lock(&ns2->lock)using the pointer that was just freed?
I'm unsure if that re-entry is possible from an external subsystem perspective, but if it is then this narrow hole also exists. I'll convert this to just a basic ref count.
Quoted 21 lines
[ ... ]
Quoted 4 lines
drivers/hid/hid-nintendo.c +4
-0+static int switch2_event (struct hid_device *hdev,struct hid_report *report,uint8_t *raw_data, +int size) +{ +struct switch2_controller *ns2 =hid_get_drvdata (hdev);drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3572
Quoted 10 lines
drivers/hid/hid-nintendo.c +10
-0+struct input_dev *input; + +if (report->type !=HID_INPUT_REPORT ) +return 0 ; + +if (size <15 ) +return -EINVAL ; + +guard (rcu)(); + input =rcu_dereference (ns2->input);[Severity: High]
Could this event handler dereference uninitialized driver data during early hardware I/O startup?
Quoted 8 lines
The
switch2_probe()function callshid_hw_start(hdev, HID_CONNECT_HIDRAW)before assigning its private data withhid_set_drvdata(). This connects the device to hidraw, allowing userspace to immediately open it and trigger input events, or the underlying transport can send events.If an event arrives during this race window, will
switch2_event()callhid_get_drvdata(hdev)and receive a NULL pointer, leading to a kernel crash when callingrcu_dereference(ns2->input)?
Seems I've misunderstood the difference between hid_hw_start and hid_hw_open. Fixing in v7.
Quoted 33 lines
[ ... ]
Quoted 20 lines
drivers/hid/hid-nintendo.c +20
-0+int switch2_receive_command (struct switch2_controller *ns2, +const uint8_t *message,size_t length) +{ +const struct switch2_cmd_header *header; +int ret =0 ; + +if (length <8 ) +return -EINVAL ; + +print_hex_dump_debug ("got cmd: " ,DUMP_PREFIX_OFFSET ,16 ,1 , message, length, false); + +guard (mutex)(&ns2->lock); + + header = (const struct switch2_cmd_header *)message; +if (!(header->flags &NS2_FLAG_OK )) { +dev_warn (ns2->cfg->dev,"Packet error %02x replying to command %x:%x" , + header->flags, header->command, header->subcommand); + ret = -EIO ; + goto exit; + }[ ... ]
drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3852
Quoted 6 lines
drivers/hid/hid-nintendo.c +6
-0+exit: +if (ns2->init_step <NS2_INIT_DONE ) +switch2_init_controller (ns2); + +return ret; +}[Severity: Medium]
Does mixing goto error handling withguard()cleanup violate subsystem rules?
Quoted 7 lines
This function utilizes guard(mutex)(&ns2->lock) to acquire the lock using scope-based cleanup, but later uses goto exit to jump to a cleanup label on error paths.
The core kernel cleanup guidelines explicitly forbid mixing goto-based cleanup labels and
guard()declarations in the same routine, as it creates confusing ownership semantics.
Ah, I guess I misunderstood the how this was forbidden. Easy enough to clean up now that I have a single exit.>
Quoted 46 lines
[ ... ]
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+static int switch2_probe (struct hid_device *hdev,const struct hid_device_id *id) +{[ ... ]
Quoted 7 lines
drivers/hid/hid-nintendo.c +7
-0+ ret =hid_hw_start (hdev,HID_CONNECT_HIDRAW ); +if (ret) { +hid_err (hdev,"hw_start failed %d\n" , ret); +return ret; + } + + ns2 =switch2_get_controller (phys);[ ... ]
Quoted 6 lines
drivers/hid/hid-nintendo.c +6
-0+ ns2->player_id =U32_MAX ; + ret =ida_alloc (&nintendo_player_id_allocator,GFP_KERNEL ); +if (ret <0 ) +hid_warn (hdev,"Failed to allocate player ID, skipping; ret=%d\n" , ret); +else + ns2->player_id = ret;[ ... ]
Quoted 12 lines
drivers/hid/hid-nintendo.c +12
-0+hid_set_drvdata (hdev, ns2); + + ret =hid_hw_open (hdev); +if (ret) { +hid_err (hdev,"hw_open failed %d\n" , ret); + goto err_cleanup; + } + + ret =0 ; +if (ns2->cfg) + ret =switch2_init_controller (ns2); +drivers/hid/hid-nintendo.c static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message) · line 3969
Quoted 10 lines
drivers/hid/hid-nintendo.c +10
-0+if (!ret) { +mutex_unlock (&ns2->lock); +return 0 ; + } + +err_cleanup: +hid_hw_close (hdev); +ida_free (&nintendo_player_id_allocator, ns2->player_id); + ns2->hdev =NULL ; +mutex_unlock (&ns2->lock);[Severity: High]
Ifhid_hw_open()fails, does the unconditional call tohid_hw_close(hdev)corrupt thell_open_counttracking?
Quoted 6 lines
If
hid_hw_open(hdev)fails, execution jumps to theerr_cleanuplabel, which unconditionally callshid_hw_close(hdev).Since
hid_hw_open()does not incrementll_open_counton failure, willhid_hw_close()decrement the count from 0, wrapping it around toUINT_MAXand permanently silently preventing any future opens of the device?
Fixing as part of other cleanup.
Quoted 5 lines
[Severity: Medium]
Does this error path trigger aWARN_ONwhen trying to free an unallocated player ID?
Quoted 8 lines
The code initializes
ns2->player_idtoU32_MAX. Ifida_alloc()fails, it skips allocation but retains theU32_MAXvalue.In the
err_cleanuppath, or duringswitch2_remove(), the driver unconditionally callsida_free(&nintendo_player_id_allocator, ns2->player_id).Will passing -1 (
U32_MAX) toida_free()trigger aWARN_ONwithin the IDA framework?
Already shown to be a hallucination in the last reply.
Quoted 55 lines
Quoted 4 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 28 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +28
-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->bulk_in[i].state =NS2_URB_IN ; +continue ; + } + +if (ns2_usb->bulk_in[i].state !=NS2_URB_FREE ) +continue ; + + ns2_urb = &ns2_usb->bulk_in[i]; +usb_anchor_urb (ns2_urb->urb, &ns2_usb->bulk_in_anchor); + err =usb_submit_urb (ns2_urb->urb,GFP_ATOMIC ); +if (err) { +usb_unanchor_urb (ns2_urb->urb); +dev_dbg (&ns2_usb->udev->dev,"failed to queue input urb: %d\n" , err); + }else { + ns2_urb->state =NS2_URB_OUT ; + } + } +spin_unlock_irqrestore (&ns2_usb->bulk_in_lock, flags); + +if (schedule) +schedule_work (&ns2_usb->message_in_work); +}[ ... ]
Quoted 2 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +2
-0+static void switch2_usb_message_in_work (struct work_struct *work) +{[ ... ]
drivers/input/joystick/nintendo-switch2-usb.c line 206
Quoted 5 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +5
-0+spin_lock_irqsave (&ns2_usb->bulk_in_lock, flags); + urb->state =NS2_URB_FREE ; + } +spin_unlock_irqrestore (&ns2_usb->bulk_in_lock, flags); +}[Severity: High]
Does this input URB handling stall the USB bulk input pipeline permanently if the URBs complete too quickly?The driver manages IN URBs via a ping-pong mechanism.
switch2_bulk_in()submits URBs in theNS2_URB_FREEstate. The workerswitch2_usb_message_in_work()clears processed URBs toNS2_URB_FREEbut does not re-submit them.
Quoted 5 lines
If all active URBs complete in quick succession before the workqueue thread runs, they will all be marked
NS2_URB_IN. The worker will process them and mark them FREE, but since no URBs are left active in the USB core to trigger the completion handler, willswitch2_bulk_in()never be called again, permanently halting input?
In theory, the Switch 2 controller should only send a bulk IN in reply to a bulk OUT, and we don't tend to schedule more than one of those at a time, but it'd be good to fix this anyway.>
Quoted 26 lines
[ ... ]
Quoted 3 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +3
-0+static int switch2_usb_send_cmd (enum switch2_cmd command,uint8_t subcommand, +const void *message,size_t size,struct switch2_cfg_intf *cfg) +{[ ... ]
drivers/input/joystick/nintendo-switch2-usb.c line 180
Quoted 12 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +12
-0+usb_anchor_urb (urb->urb, &ns2_usb->bulk_out_anchor); + ret =usb_submit_urb (urb->urb,GFP_ATOMIC ); +if (ret) { +if (ret != -ENODEV ) +dev_warn (&ns2_usb->udev->dev,"failed to submit output urb: %i" , ret); + urb->state =NS2_URB_FREE ; +usb_unanchor_urb (urb->urb); +return ret; + } + +return 0 ; +}[Severity: High]
Can this lockless modification ofurb->statelead to a data race and potential DMA corruption?If
usb_submit_urb()fails,urb->state=NS2_URB_FREEis set without re-acquiringns2_usb->bulk_out_lock. Additionally, it is marked FREE before callingusb_unanchor_urb().
Quoted 5 lines
Could a concurrent thread acquire the lock, claim this supposedly free URB, write to its DMA buffer, and submit it, right as the original thread unanchors it? During teardown,
usb_kill_anchored_urbs()would not wait for this unanchored URB, potentially leading to its DMA buffer being freed while the hardware is still accessing it.
Missed this. Fixing in v7. Wish the stochastic parrot had found this on v5.
Quoted 44 lines
[ ... ]
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 9 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +9
-0+for (i =0 ; i <NS2_OUT_URBS ; i++) { +struct urb *urb; +uint8_t *data; + + urb =usb_alloc_urb (0 ,GFP_KERNEL ); +if (!urb) { + ret = -ENOMEM ; + goto err_free_in; + }[ ... ]
Quoted 20 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +20
-0+ ret =switch2_controller_attach_cfg (phys, &ns2_usb->cfg); +if (ret <0 ) + goto err_free_out; + +return 0 ; + +err_free_out: +usb_kill_anchored_urbs (&ns2_usb->bulk_out_anchor); +spin_lock_irqsave (&ns2_usb->bulk_out_lock, flags); +for (i =0 ; i <NS2_OUT_URBS ; i++) { +if (!ns2_usb->bulk_out[i].urb) +continue ; + +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); +err_free_in: +usb_kill_anchored_urbs (&ns2_usb->bulk_in_anchor);[ ... ]
drivers/input/joystick/nintendo-switch2-usb.c line 344
Quoted 4 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +4
-0+devm_kfree (&intf->dev, ns2_usb); + +return ret; +}[Severity: Medium]
Does this error handling skip cleaning up successfully allocated OUT URBs?
Quoted 5 lines
During the loop allocating OUT URBs, if
usb_alloc_urb()fails, the code branches to gotoerr_free_in. This skips theerr_free_outblock entirely.Will this permanently leak the OUT URBs and their DMA buffers from any preceding successful loop iterations?
Fixed.
Quoted 11 lines
[Severity: High]
Does callingusb_free_coherent()inside the atomic critical section violate DMA API rules?In the
err_free_outblock,usb_free_coherent()is called while thebulk_out_lockspinlock is held with IRQs disabled (usingspin_lock_irqsave).Since
usb_free_coherent()is a wrapper fordma_free_coherent()and freeing memory allocated withGFP_KERNELmay sleep, will this cause deadlocks or kernel panics underCONFIG_DEBUG_ATOMIC_SLEEP?
Fixed.
Quoted 9 lines
[Severity: High]
Is acancel_work_sync()missing from this error path, potentially causing a Use-After-Free?An IN URB is submitted before calling
switch2_controller_attach_cfg(). If the device responds immediately,switch2_bulk_in()will schedulens2_usb->message_in_work.
Quoted 5 lines
If
attach_cfgfails, the error path freesns2_usbviadevm_kfree()but never callscancel_work_sync(&ns2_usb->message_in_work).Could the scheduled work execute later on the freed memory footprint of
ns2_usb?
Fixed.
Quoted 38 lines
[ ... ]
Quoted 7 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +7
-0+static void switch2_usb_disconnect (struct usb_interface *intf) +{ +struct switch2_usb *ns2_usb =usb_get_intfdata (intf); +unsigned long flags; +int i; + +usb_kill_anchored_urbs (&ns2_usb->bulk_out_anchor);drivers/input/joystick/nintendo-switch2-usb.c line 362
Quoted 10 lines
drivers/input/joystick/nintendo-switch2-usb.c new file +10
-0+spin_lock_irqsave (&ns2_usb->bulk_out_lock, flags); +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); + +usb_kill_anchored_urbs (&ns2_usb->bulk_in_anchor); +cancel_work_sync (&ns2_usb->message_in_work);[Severity: High]
Does freeing thebulk_outURBs before cancelling the worker lead to a Use-After-Free and DMA corruption?All
bulk_outURBs and their DMA buffers are freed before the driver invokescancel_work_sync(&ns2_usb->message_in_work).Can the globally scheduled workqueue run concurrently during this gap, process incoming messages, and trigger a reply via
switch2_usb_send_cmd()?If so, will the send function claim a freed URB and write to the freed DMA buffer, leading to a Use-After-Free and submitting corrupted DMA to the USB controller?
[Severity: High]
Does callingusb_free_coherent()inside the atomic critical section violate DMA API rules?
Quoted 6 lines
Similar to the probe error path,
usb_free_coherent()is called while thebulk_out_lockspinlock is held with IRQs disabled (usingspin_lock_irqsave).Since freeing memory allocated with
GFP_KERNELmay sleep, will this cause deadlocks or kernel panics underCONFIG_DEBUG_ATOMIC_SLEEP?
Fixed a bunch of things in this too.
I'm noticing a bunch of ordering stuff in this file that's rough to get right. Hopefully I've fixed it now and will be submitting v7 on Monday probably. Still need to review patch 2 and retest everything.
Vicki Pfau
maintainerRe: [PATCH v6 2/3] HID: nintendo: Add rumble support for Switch 2 controllers
In reply to [email protected]Quoted 26 lines · On 6/24/26 10:18 PM, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [High] Unsynchronized accesses tons2->hdevallow rumble work to read a closing device pointer, leading to a TOCTOU NULL pointer dereference.
- [High]cancel_delayed_work_sync()is called on an uninitialized work structure if the configuration interface detaches without the HID interface probing.
- [High] Use-after-free of ns2 due to the input core's memless force feedback timer outliving the driver's private data.
- [Medium] Arithmetic underflow inschedule_delayed_work()delay calculation causes the rumble worker to permanently hang if its execution is delayed.
- [Low] Unused static constant arrayswitch2_zero_dataleads to dead code.
--commit
93841885eb908e1356dc311955f33fee3d1428c6
Author: Vicki Pfau <[email protected]>HID: nintendo: Add rumble support for Switch 2 controllers
This commit adds basic rumble support for the Switch 2 controllers. It introduces delayed work and force feedback support.
Quoted 4 lines
drivers/hid/hid-nintendo.c +0
-0[ ... ]
Quoted 3 lines
drivers/hid/hid-nintendo.c +0
-0@@ -3133,9 +3183,12 @@ static const uint8_t switch2_init_cmd_data[] = { };
Quoted 8 lines
drivers/hid/hid-nintendo.c static const uint8_t switch2_init_cmd_data[] = { · line 3188
Quoted 4 lines
drivers/hid/hid-nintendo.c +3
-0static const uint8_t switch2_one_data[] = {0x01 ,0x00 ,0x00 ,0x00 }; +#if IS_ENABLED (CONFIG_NINTENDO_FF ) +static const uint8_t switch2_zero_data[] = {0x00 ,0x00 ,0x00 ,0x00 }; +#endif [Severity: Low]
Is this unused variable intentional? It appearsswitch2_zero_datais never utilized anywhere in the codebase.
Looks like leftover from a previous iteration. Removing.
Quoted 16 lines
[ ... ]
drivers/hid/hid-nintendo.c static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type) · line 3226
Quoted 8 lines
drivers/hid/hid-nintendo.c +8
-0+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 ; + +guard (spinlock_irqsave)(&ns2->rumble_lock);[Severity: High]
Can this result in a use-after-free when the input device outlives the driver data?
Quoted 6 lines
During device removal,
switch2_controller_put()explicitly calls kfree(ns2). However, the input device is devres-managed and its lifetime is tied to userspace holding its file descriptor open. Since the input core's memless force feedback timer is only destroyed when the input device is released, the timer callbackswitch2_play_effect()could potentially fire after ns2 has been freed.
I will see about tying this into the ref system I added for patch 1 to delay the free.>
Quoted 21 lines
[ ... ]
Quoted 2 lines
drivers/hid/hid-nintendo.c +2
-0+static void switch2_rumble_work (struct work_struct *work) +{[ ... ]
drivers/hid/hid-nintendo.c static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type) · line 3294
Quoted 10 lines
drivers/hid/hid-nintendo.c +10
-0+if (active) { +unsigned long interval =msecs_to_jiffies (2 ); +uint64_t current_jiffies =get_jiffies_64 (); + +if (!ns2->last_rumble_work) + ns2->last_rumble_work = current_jiffies; +else + ns2->last_rumble_work += interval; +schedule_delayed_work (&ns2->rumble_work, + ns2->last_rumble_work + interval - current_jiffies);[Severity: Medium]
Could this delay calculation underflow?
Quoted 5 lines
If the worker thread is delayed by the scheduler such that
current_jiffiesexceeds the expected execution time (ns2->last_rumble_work+ interval), the unsigned arithmetic could underflow to a value nearULONG_MAX. This would schedule the next rumble update weeks in the future, permanently hanging the force feedback mechanism.
I think I've seen this. I have trouble reproducing it but I'll fix this and hopefully it'll stop reproducing.
Quoted 15 lines
drivers/hid/hid-nintendo.c static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type) · line 3303
Quoted 10 lines
drivers/hid/hid-nintendo.c +9
-0+ }else { + ns2->last_rumble_work =0 ; + } +spin_unlock_irqrestore (&ns2->rumble_lock, flags); + +if (!ns2->hdev) +cancel_delayed_work (&ns2->rumble_work); +else + ret =hid_hw_output_report (ns2->hdev, ns2->rumble_buffer,64 );[Severity: High]
Is it possible for a concurrent removal to cause a NULL pointer dereference here?
Quoted 8 lines
Because
ns2->hdevis read outside of any lock, there may be a window where it is verified as non-NULL, but then set to NULL by a concurrentswitch2_remove()before being passed tohid_hw_output_report(). This appears structurally possible if userspace invokesswitch2_play_effect()and reschedules the worker right after the initial cancellation inswitch2_remove().[ ... ]
Fixing.
Quoted 12 lines
drivers/hid/hid-nintendo.c static void switch2_controller_put(struct switch2_controller *ns2) · line 3526
Quoted 8 lines
drivers/hid/hid-nintendo.c +3
-0@@ -3358,6 +3521,10 @@ static void switch2_controller_put(struct switch2_controller *ns2)if (input)input_unregister_device (input); +#if IS_ENABLED (CONFIG_NINTENDO_FF ) +cancel_delayed_work_sync (&ns2->rumble_work); +#endif [Severity: High]
Could this cancel operation act on an uninitialized work structure?
Quoted 9 lines
The
switch2_probe()function initializes the work structure:INIT_DELAYED_WORK(&ns2->rumble_work, switch2_rumble_work);If the configuration interface detaches before the HID interface probes,
ns2->rumble_workmight remain zero-initialized. Whenswitch2_controller_put()is called, unconditionally invokingcancel_delayed_work_sync()on this uninitialized work structure could trigger lockdep warnings and kernel panics.
This will be fixed by my probe refactor already.