Skip to contentSkip to conversation

Input: xbox_gip - Add new driver for Xbox GIP

PATCH In review Vicki Pfau 3 participants 26 messages Sep 12 – Nov 16

Subsystems (3)
lore
Share & tools
lore

Vicki Pfau

author
#0 lore raw

v7 cover Input: xbox_gip - Add new driver for Xbox GIP

This is a new version of the previously submitted xbox-gip series.

This introduces a new driver for the Xbox One/Series controller protocol, officially known as the Gaming Input Protocol, or GIP for short.

Microsoft released documentation on (some of) GIP in late 2024, upon which this driver is based. Though the documentation was incomplete, it still provided enough information to warrant a clean start over the previous, incomplete implementation.

This driver is already at feature parity with the GIP support in xpad, along with several more enhancements:

- Proper support for parsing message length and fragmented messages
- Metadata parsing, allowing for auto-detection on various parameters, including the presence and location in the message of the share button, as well as detection of specific device types
- Controllable LED support
- HID passthrough for the Chatpad
- Battery information support
- Arcade stick support
- Racing wheel support
- Support for the security flow, allowing use with wireless controllers that include their own dongles. (This does not include support for the first-party dongle yet.)

The framework set out in this driver also allows future expansion for specialized device types and additional features more cleanly than xpad.

Future plans include:

- Adding support for more device types, such as flight sticks.
- Exposing a raw character device to enable sending vendor-specific commands from userspace.
- Event logging to either sysfs or dmesg.
- Support for the headphone jack.

This version cleans up more issues found by sashiko.

Vicki Pfau (12):
Input: xbox_gip - Add new driver for Xbox GIP
Input: xpad - Remove Xbox One support
Input: xbox_gip - Add controllable LED support
Input: xbox_gip - Add HID relaying
Input: xbox_gip - Add battery support
Input: xbox_gip - Allow sending fragmented and ACME messages
Input: xbox_gip - Add security implementation from xone
Input: xbox_gip - Add arcade stick support
Input: xbox_gip - Add support for PDP guitar controllers
Input: Add ABS_CLUTCH, HANDBRAKE, and SHIFTER
HID: Map more automobile simulation inputs
Input: xbox_gip - Add wheel support

 Documentation/input/devices/xpad.rst          |   17 +-
 MAINTAINERS                                   |    6 +
 drivers/hid/hid-debug.c                       |   16 +-
 drivers/hid/hid-input.c                       |    2 +
 drivers/input/joystick/Kconfig                |    2 +
 drivers/input/joystick/Makefile               |    1 +
 drivers/input/joystick/gip/Kconfig            |   24 +
 drivers/input/joystick/gip/Makefile           |    8 +
 drivers/input/joystick/gip/gip-arcade-stick.c |  173 +
 drivers/input/joystick/gip/gip-core.c         | 3320 +++++++++++++++++
 drivers/input/joystick/gip/gip-drivers.c      |  222 ++
 drivers/input/joystick/gip/gip-pdp-jaguar.c   |  129 +
 drivers/input/joystick/gip/gip-security.c     |  810 ++++
 drivers/input/joystick/gip/gip-wheel.c        |  351 ++
 drivers/input/joystick/gip/gip.h              |  441 +++
 drivers/input/joystick/xpad.c                 |  684 +---
 include/uapi/linux/input-event-codes.h        |    3 +
 include/uapi/linux/input.h                    |    1 +
 18 files changed, 5513 insertions(+), 697 deletions(-)
 create mode 100644 drivers/input/joystick/gip/Kconfig
 create mode 100644 drivers/input/joystick/gip/Makefile
 create mode 100644 drivers/input/joystick/gip/gip-arcade-stick.c
 create mode 100644 drivers/input/joystick/gip/gip-core.c
 create mode 100644 drivers/input/joystick/gip/gip-drivers.c
 create mode 100644 drivers/input/joystick/gip/gip-pdp-jaguar.c
 create mode 100644 drivers/input/joystick/gip/gip-security.c
 create mode 100644 drivers/input/joystick/gip/gip-wheel.c
 create mode 100644 drivers/input/joystick/gip/gip.h
Signature · 1 line
2.54.0
author
#1 lore raw

PATCH v7 1/12 Input: xbox_gip - Add new driver for Xbox GIP

This introduces a new driver for the Xbox One/Series controller protocol, officially known as the Gaming Input Protocol, or GIP for short.

Microsoft released documentation on (some of) GIP in late 2024, upon which this driver is based. Though the documentation was incomplete, it still provided enough information to warrant a clean start over the previous, incomplete implementation.

This driver is already at feature parity with the GIP support in xpad, along with several more enhancements:

- Proper support for parsing message length and fragmented messages
- Metadata parsing, allowing for auto-detection on various parameters, including the presence and location in the message of the share button, as well as detection of specific device types

The framework set out in this driver also allows future expansion for specialized device types and additional features more cleanly than xpad.

Future plans include:

- Adding support for more device types, such as arcade sticks, racing wheels and flight sticks.
- Support for the security handshake, which is required for devices that use wireless dongles.
- Exposing a raw character device to enable sending vendor-specific commands from userspace.
- Event logging to either sysfs or dmesg.
- Support for the headphone jack.

---
 MAINTAINERS                              |    6 +
 drivers/input/joystick/Kconfig           |    2 +
 drivers/input/joystick/Makefile          |    1 +
 drivers/input/joystick/gip/Kconfig       |   21 +
 drivers/input/joystick/gip/Makefile      |    4 +
 drivers/input/joystick/gip/gip-core.c    | 2622 ++++++++++++++++++++++
 drivers/input/joystick/gip/gip-drivers.c |  204 ++
 drivers/input/joystick/gip/gip.h         |  351 +++
 8 files changed, 3211 insertions(+)
 create mode 100644 drivers/input/joystick/gip/Kconfig
 create mode 100644 drivers/input/joystick/gip/Makefile
 create mode 100644 drivers/input/joystick/gip/gip-core.c
 create mode 100644 drivers/input/joystick/gip/gip-drivers.c
 create mode 100644 drivers/input/joystick/gip/gip.h
MAINTAINERS +6 -0
index 806bd2d80d15..7fdf1b989667 100644
@@ -29347,6 +29347,12 @@ S:	Maintained
 F:	drivers/media/rc/keymaps/rc-xbox-dvd.c
 F:	drivers/media/rc/xbox_remote.c
 
+XBOX GIP
+M:	Vicki Pfau <[email protected]>
+L:	[email protected]
+S:	Maintained
+F:	drivers/input/joystick/gip/
+
 XC2028/3028 TUNER DRIVER
 M:	Mauro Carvalho Chehab <[email protected]>
 L:	[email protected]
drivers/input/joystick/Kconfig +2 -0
index 7755e5b454d2..d4665c80a371 100644
@@ -291,6 +291,8 @@ config JOYSTICK_JOYDUMP
 	  To compile this driver as a module, choose M here: the
 	  module will be called joydump.
 
+source "drivers/input/joystick/gip/Kconfig"
+
 config JOYSTICK_XPAD
 	tristate "Xbox gamepad support"
 	depends on USB_ARCH_HAS_HCD
drivers/input/joystick/Makefile +1 -0
index 9976f596a920..323392921b7d 100644
@@ -39,5 +39,6 @@ obj-$(CONFIG_JOYSTICK_TURBOGRAFX)	+= turbografx.o
 obj-$(CONFIG_JOYSTICK_TWIDJOY)		+= twidjoy.o
 obj-$(CONFIG_JOYSTICK_WARRIOR)		+= warrior.o
 obj-$(CONFIG_JOYSTICK_WALKERA0701)	+= walkera0701.o
+obj-$(CONFIG_JOYSTICK_XBOX_GIP)		+= gip/
 obj-$(CONFIG_JOYSTICK_XPAD)		+= xpad.o
 obj-$(CONFIG_JOYSTICK_ZHENHUA)		+= zhenhua.o
drivers/input/joystick/gip/Kconfig new file +21 -0
new file mode 100644
index 000000000000..2ce789d23178
@@ -0,0 +1,21 @@
+# SPDX-License-Identifier: GPL-2.0-or-later
+#
+# Gaming Input Protocol  driver configuration
+#
+config JOYSTICK_XBOX_GIP
+	tristate "Xbox One/Series controller support"
+	depends on USB && USB_ARCH_HAS_HCD
+	help
+	  Say Y here if you want to use Xbox One and Series controllers with your
+	  computer. Make sure to say Y to "Joystick support" (CONFIG_INPUT_JOYDEV)
+	  and/or "Event interface support" (CONFIG_INPUT_EVDEV) as well.
+
+	  To compile this driver as a module, choose M here: the
+	  module will be called xbox_gip.
+
+config JOYSTICK_XBOX_GIP_FF
+	bool "Xbox One/Series controller rumble support"
+	depends on JOYSTICK_XBOX_GIP && INPUT
+	select INPUT_FF_MEMLESS
+	help
+	  Say Y here if you want to take advantage of Xbox One/Series rumble.
drivers/input/joystick/gip/Makefile new file +4 -0
new file mode 100644
index 000000000000..d39f946db1ae
@@ -0,0 +1,4 @@
+# SPDX-License-Identifier: GPL-2.0-or-later
+obj-$(CONFIG_JOYSTICK_XBOX_GIP)	+= xbox-gip.o
+# Base driver
+xbox-gip-y := gip-core.o gip-drivers.o
drivers/input/joystick/gip/gip-core.c new file +2622 -0

2,622 lines not on this page · raw message

drivers/input/joystick/gip/gip-drivers.c new file +204 -0

204 lines not on this page · raw message

drivers/input/joystick/gip/gip.h new file +351 -0

123 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.54.0

Part of the diff is not shown here. View the raw message.

#2 lore raw
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider: - [High] Missing and misordered work cancellations lead to Use-After-Free during device teardown and probe…

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [High] Missing and misordered work cancellations lead to Use-After-Free during device teardown and probe failure
- [High] Memory leak of input device due to dynamic devm allocation during logical device reset
- [High] Input devices are improperly destroyed during system suspend
- [High] Incorrect metadata version check logic causes parsing failures on older controllers
- [Low] Race condition when checking !urb->anchor to determine if an URB is idle
--

commit 16c368dc90338176b4ca692834653e9db715d0b4
Author: Vicki Pfau <[email protected]>
Subject: Input: xbox_gip - Add new driver for Xbox GIP

This commit introduces a new driver for the Xbox One/Series controller protocol, also known as the Gaming Input Protocol. It adds a scalable framework for specialized Xbox devices by parsing dynamic capabilities through device metadata.

Quoted 4 lines
drivers/input/joystick/gip/gip-core.c new file +0 -0
index 0000000000000..b662cd7bddfa2

[ ... ]

Quoted 4 lines
drivers/input/joystick/gip/gip-core.c new file +4 -0
+static int gip_send_raw_message(struct gip_attachment *attachment,
+	uint8_t message_type, uint8_t flags, uint8_t seq, const uint8_t *bytes,
+	int num_bytes)
+{

[ ... ]

drivers/input/joystick/gip/gip-core.c line 513

Quoted 6 lines
drivers/input/joystick/gip/gip-core.c new file +6 -0
+	for (i = 0; i < MAX_OUT_MESSAGES && !urb; i++) {
+		if (!intf->out_queue[i].urb)
+			continue;
+		if (!intf->out_queue[i].urb->anchor)
+			urb = &intf->out_queue[i];
+	}

[Severity: Low]
Is this check for a free URB safe against concurrent completion handlers?

The USB core unanchors the URB via usb_unanchor_urb() just before executing the completion handler. Checking !urb->anchor allows picking and modifying this URB while its previous completion handler is still running, which can lead to data races.

[ ... ]

Quoted 4 lines
drivers/input/joystick/gip/gip-core.c new file +4 -0
+static int gip_parse_device_metadata(struct device *dev,
+	struct gip_metadata *metadata, const uint8_t *bytes, int num_bytes,
+	int *offset)
+{

[ ... ]

drivers/input/joystick/gip/gip-core.c line 720

Quoted 4 lines
drivers/input/joystick/gip/gip-core.c new file +4 -0
+	bytes = &bytes[*offset];
+	num_bytes -= *offset;
+	if (num_bytes < sizeof(*header))
+		return -EINVAL;

[Severity: High]
Does this unconditionally require the buffer to be large enough for the full v1.1 header structure?

Older devices running v0.1 metadata protocols would send a naturally shorter header, which would cause initialization to fail entirely here.

[ ... ]

drivers/input/joystick/gip/gip-core.c line 803

Quoted 2 lines
drivers/input/joystick/gip/gip-core.c new file +2 -0
+	if (metadata->version_major > 1 || metadata->version_minor >= 1) {
+		/* HID descriptor support added in metadata version 1.1 */

[Severity: High]
Will this logic incorrectly pass for older metadata versions like 0.1 and 0.2?

Because the condition uses an OR operator, a version with version_major == 0 and version_minor >= 1 evaluates to true. This would cause the driver to attempt parsing v1.1 fields (hid_descriptor_offset) out of bounds on a shorter v0.x header.

Could this be checked as:
version_major > 1 || (version_major == 1 && version_minor >= 1)?

[ ... ]

Quoted 5 lines
drivers/input/joystick/gip/gip-core.c new file +5 -0
+static int gip_setup_input_device(struct gip_attachment *attachment)
+{
+	struct input_dev *input;
+	int rc;
+

drivers/input/joystick/gip/gip-core.c line 1122

Quoted 10 lines
drivers/input/joystick/gip/gip-core.c new file +10 -0
+	if (!attachment->driver || !attachment->driver->setup_input)
+		return -ENODEV;
+
+	rcu_read_lock();
+	input = rcu_dereference(attachment->input);
+	rcu_read_unlock();
+	if (input)
+		return 0;
+
+	input = devm_input_allocate_device(to_gip_device(attachment));

[Severity: High]
Does this dynamically allocate devm resources that are leaked on logical resets?

This allocates the input device using devres tied to the parent usb_interface. When the controller is logically reset (e.g. handling a new GIP_CMD_HELLO_DEVICE), gip_reset_attachment() explicitly unregisters this device but does not destroy the devm allocation action.

[ ... ]

Quoted 3 lines
drivers/input/joystick/gip/gip-core.c new file +3 -0
+static void gip_free_devices(struct gip_attachment *attachment)
+{
+	struct input_dev *input;

[ ... ]

drivers/input/joystick/gip/gip-core.c line 1306

Quoted 3 lines
drivers/input/joystick/gip/gip-core.c new file +3 -0
+	if (input)
+		input_unregister_device(input);
+}

[Severity: High]
Could this leave the devres action tracking the input device intact on the parent?

Successive re-enumerations will allocate additional input_dev instances without freeing the old ones, leaking memory linearly over time until the physical USB device is unbound.

[ ... ]

Quoted 2 lines
drivers/input/joystick/gip/gip-core.c new file +2 -0
+static int gip_probe(struct usb_interface *intf, const struct usb_device_id *id)
+{

[ ... ]

Quoted 13 lines
drivers/input/joystick/gip/gip-core.c new file +13 -0
+	/* Pre-create the first attachment, as it should always exist */
+	attachment = gip_ensure_attachment(gip, 0);
+	if (IS_ERR(attachment)) {
+		gip_deinit_input(&gip->data);
+		gip_deinit_output(&gip->data);
+		if (gip->audio.intf) {
+			gip_deinit_input(&gip->audio);
+			gip_deinit_output(&gip->audio);
+		}
+		rc = PTR_ERR(attachment);
+		goto err_cleanup;
+	}
+

drivers/input/joystick/gip/gip-core.c line 2462

Quoted 10 lines
drivers/input/joystick/gip/gip-core.c new file +10 -0
+	/* Don't init audio interface -- we aren't using it yet */
+
+	usb_set_intfdata(intf, gip);
+	return 0;
+
+err_cleanup:
+	devm_kfree(to_gip_device(gip), gip);
+
+	return rc;
+}

[Severity: High]
Does this error path fail to cancel the gip->receive_message work?

If gip_ensure_attachment() fails, gip_deinit_input() kills the URB, but the scheduled work is not canceled before freeing the gip structure via devm_kfree(), leading to a use-after-free.

[ ... ]

Quoted 5 lines
drivers/input/joystick/gip/gip-core.c new file +5 -0
+static void gip_disconnect(struct usb_interface *intf)
+{
+	struct gip_device *gip = usb_get_intfdata(intf);
+	int i;
+

drivers/input/joystick/gip/gip-core.c line 2504

Quoted 10 lines
drivers/input/joystick/gip/gip-core.c new file +10 -0
+	if (!gip)
+		return;
+
+	gip_shutdown(gip);
+
+	usb_kill_anchored_urbs(&gip->data.out_anchor);
+	if (gip->audio.intf)
+		usb_kill_anchored_urbs(&gip->audio.out_anchor);
+
+	gip_deinit_input(&gip->data);

[Severity: High]
Can a late URB completion handler re-queue work after gip_shutdown() runs?

gip_shutdown() synchronously cancels gip->receive_message and attachment->rumble_work, but the input URB is not killed until later in gip_deinit_input().

If the URB completes in this window, gip_urb_in() will re-queue the receive_message work. usb_kill_urb() waits for the completion handler but doesn't cancel newly queued work. gip_disconnect() then frees the memory, causing the pending work to execute on a freed gip structure.

Additionally, gip_shutdown() cancels attachment->rumble_work before input_unregister_device() runs. A concurrent userspace ioctl could trigger gip_play_effect() to re-queue the work right before the attachment is freed.

[ ... ]

Quoted 2 lines
drivers/input/joystick/gip/gip-core.c new file +2 -0
+static int gip_suspend(struct usb_interface *intf, pm_message_t message)
+{

[ ... ]

Quoted 7 lines
drivers/input/joystick/gip/gip-core.c new file +7 -0
+	gip_shutdown(gip);
+
+	return 0;
+}
+
+static int gip_resume(struct usb_interface *intf)
+{

drivers/input/joystick/gip/gip-core.c line 2569

Quoted 10 lines
drivers/input/joystick/gip/gip-core.c new file +10 -0
+	struct gip_device *gip = usb_get_intfdata(intf);
+
+	if (!gip)
+		return 0;
+
+	if (usb_submit_urb(gip->data.urb_in, GFP_KERNEL))
+		return -EIO;
+
+	return 0;
+}

[Severity: High]
Are input devices destroyed during suspend and never properly restored?

gip_suspend() calls gip_shutdown(), which unregisters and destroys all input devices. Upon gip_resume(), the driver only resubmits the input URB but fails to recreate the input devices.

If the controller doesn't automatically send a GIP_CMD_HELLO_DEVICE, the input device is permanently lost. Even if it does, it will create a brand new evdev node, breaking the state of hotplug-unaware userspace applications across system suspend/resume cycles.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author
#3 lore raw

PATCH v7 2/12 Input: xpad - Remove Xbox One support

In reply to Vicki Pfau

It has been superseded by xbox_gip. As the new driver is already at feature parity, removing the fairly rough Xbox One support from xpad is safe and will prevent any potential conflicts.

---
 Documentation/input/devices/xpad.rst  |  17 +-
 drivers/input/joystick/gip/gip-core.c |   2 +-
 drivers/input/joystick/xpad.c         | 684 +-------------------------
 3 files changed, 12 insertions(+), 691 deletions(-)
Documentation/input/devices/xpad.rst +7 -10
index a480bc781565..eed7cca1158a 100644
@@ -2,19 +2,19 @@
 xpad - Linux USB driver for Xbox compatible controllers
 =======================================================
 
-This driver exposes all first-party and third-party Xbox compatible
-controllers. It has a long history and has enjoyed considerable usage
-as Windows' xinput library caused most PC games to focus on Xbox
-controller compatibility.
+This driver exposes all first-party and third-party Xbox and Xbox 360
+compatible controllers. It has a long history and has enjoyed considerable
+usage as Windows' xinput library caused most PC games to focus on Xbox
+controller compatibility. Xbox One/Series controller support has been
+superseded by the xbox_gip driver, which specializes in the Gaming Input
+Protocol that is introduced on the Xbox One.
 
 Due to backwards compatibility all buttons are reported as digital.
 This only affects Original Xbox controllers. All later controller models
 have only digital face buttons.
 
 Rumble is supported on some models of Xbox 360 controllers but not of
-Original Xbox controllers nor on Xbox One controllers. As of writing
-the Xbox One's rumble protocol has not been reverse-engineered but in
-the future could be supported.
+Original Xbox controllers.
 
 
 Notes
@@ -98,9 +98,6 @@ All generations of Xbox controllers speak USB over the wire.
 - Wireless Xbox 360 controllers require a 'Xbox 360 Wireless Gaming Receiver
   for Windows'
 - Wired Xbox 360 controllers use standard USB connectors.
-- Xbox One controllers can be wireless but speak Wi-Fi Direct and are not
-  yet supported.
-- Xbox One controllers can be wired and use standard Micro-USB connectors.
 
 
 
drivers/input/joystick/gip/gip-core.c +1 -1
index b662cd7bddfa..b67b38c880cd 100644
@@ -858,7 +858,7 @@ static int gip_parse_message_metadata(struct device *dev,
 	return 0;
 }
 
-static bool gip_parse_metadata(struct device *dev,
+static int gip_parse_metadata(struct device *dev,
 	struct gip_metadata *metadata, const uint8_t *bytes, int num_bytes)
 {
 	int header_size;
drivers/input/joystick/xpad.c +4 -680

1,024 lines not on this page · raw message

Signature · 1 line
2.54.0
#4 lore raw

Re: [PATCH v7 02/12] Input: xpad - Remove Xbox One support

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:

Pre-existing issues:
- [High] Accumulation of leaked input_dev structures in the devres list across logical device resets.
- [High] Race condition in gip_shutdown() where asynchronous force-feedback work is cancelled before the input device is unregistered, leading to a Use-After-Free.
- [Medium] gip_parse_metadata() returns success (0) instead of an error code when the metadata message is unexpectedly truncated, causing the caller to accept an uninitialized metadata structure. --

commit 3f01a3076f0a08c3208bada0c0eb3d4a4be23e2c
Author: Vicki Pfau <[email protected]>

Input: xpad - Remove Xbox One support

It has been superseded by xbox_gip. As the new driver is already at feature parity, removing the fairly rough Xbox One support from xpad is safe and will prevent any potential conflicts.

Quoted 3 lines
drivers/input/joystick/gip/gip-core.c +0 -0

[ ... ]

Quoted 5 lines
drivers/input/joystick/gip/gip-core.c +1 -1
-static bool gip_parse_metadata(struct device *dev,
+static int gip_parse_metadata(struct device *dev,
 	struct gip_metadata *metadata, const uint8_t *bytes, int num_bytes)
 {
 	int header_size;

[ ... ]

drivers/input/joystick/gip/gip-core.c

Quoted 6 lines
drivers/input/joystick/gip/gip-core.c +0 -0
 	rc = gip_parse_device_metadata(dev, metadata, bytes, num_bytes, &offset);
 	if (rc)
 		goto parse_err;
 
 	if (offset >= num_bytes)
 		goto parse_err;

[Severity: Medium]
This isn't a bug introduced by this patch, but does this error path return success instead of an error code?

If the offset exceeds num_bytes, rc is still 0 from the preceding successful call to gip_parse_device_metadata(). Jumping to parse_err will return 0.

Could this cause the driver to accept a zeroed-out metadata structure if a misbehaving device sends a truncated message?

[ ... ]

Quoted 5 lines

static int gip_setup_input_device(struct gip_attachment *attachment) {

drivers/input/joystick/gip/gip-core.c +0 -0
 	struct input_dev *input;
 	int rc;
 

drivers/input/joystick/gip/gip-core.c

Quoted 10 lines
drivers/input/joystick/gip/gip-core.c +0 -0
 	if (!attachment->driver || !attachment->driver->setup_input)
 		return -ENODEV;
 
 	rcu_read_lock();
 	input = rcu_dereference(attachment->input);
 	rcu_read_unlock();
 	if (input)
 		return 0;
 
 	input = devm_input_allocate_device(to_gip_device(attachment));

[Severity: High]
This is a pre-existing issue, but does this lead to a memory leak of input_dev structures?

When the controller resets (e.g. repeatedly sending GIP_CMD_HELLO_DEVICE), this calls input_unregister_device(), but because the device was allocated with devm_input_allocate_device() on the parent USB interface, the memory is intentionally deferred to devres teardown.

Since the devm reference isn't dropped, if the driver allocates a new input_dev during re-initialization, it seems the old structures will accumulate indefinitely. Could this be triggered by an untrusted USB device to out-of-memory the host kernel?

[ ... ]

Quoted 12 lines

static void gip_shutdown(struct gip_device *gip)
{

drivers/input/joystick/gip/gip-core.c +0 -0
 	int i;
 
 	cancel_work_sync(&gip->receive_message);
 
 	for (i = 0; i < MAX_ATTACHMENTS; i++) {
 		struct gip_attachment *attachment;
 
 		mutex_lock(&gip->attachment_lock);
 		attachment = gip->attachments[i];
 		mutex_unlock(&gip->attachment_lock);

drivers/input/joystick/gip/gip-core.c

Quoted 10 lines
drivers/input/joystick/gip/gip-core.c +0 -0
 
 		if (!attachment)
 			continue;
 
 		cancel_delayed_work_sync(&attachment->metadata_next);
 		cancel_delayed_work_sync(&attachment->in_fragment_timeout);
 		cancel_work_sync(&attachment->rumble_work);
 
 		guard(mutex)(&attachment->lock);
 		gip_reset_attachment(attachment);

[Severity: High]
This is a pre-existing issue, but is there a use-after-free race condition during driver unbind?

In gip_shutdown(), cancel_work_sync(&attachment->rumble_work) is called before the input device is unregistered. If an active ff-memless background timer fires right after this, it can invoke gip_play_effect() and re-schedule the work.

gip_shutdown() then acquires the lock and calls gip_reset_attachment(), which uses the non-synchronous cancel_work():

drivers/input/joystick/gip/gip-core.c:gip_reset_attachment() {
    ...
	cancel_work(&attachment->rumble_work);
    ...
}

If the re-scheduled work has already started executing, it will block on attachment->lock (held by gip_shutdown). Once gip_shutdown() unregisters the device and the attachment is freed by devres, the blocked work would resume and access freed memory.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author
#5 lore raw

PATCH v7 3/12 Input: xbox_gip - Add controllable LED support

In reply to Vicki Pfau

Xbox One controllers have two different types of controllable LED support:

- Monochrome white, which most controllers have.
- RGBW addressible, which the Elite 2 controllers have.

This exposes both types as led cdevs.

---
 drivers/input/joystick/gip/Kconfig    |   2 +-
 drivers/input/joystick/gip/gip-core.c | 115 ++++++++++++++++++++++++++
 drivers/input/joystick/gip/gip.h      |   6 +-
 3 files changed, 121 insertions(+), 2 deletions(-)
drivers/input/joystick/gip/Kconfig +1 -1
index 2ce789d23178..3422bf84cb89 100644
@@ -4,7 +4,7 @@
 #
 config JOYSTICK_XBOX_GIP
 	tristate "Xbox One/Series controller support"
-	depends on USB && USB_ARCH_HAS_HCD
+	depends on USB && USB_ARCH_HAS_HCD && LEDS_CLASS_MULTICOLOR
 	help
 	  Say Y here if you want to use Xbox One and Series controllers with your
 	  computer. Make sure to say Y to "Joystick support" (CONFIG_INPUT_JOYDEV)
drivers/input/joystick/gip/gip-core.c +115 -0

130 lines not on this page · raw message

drivers/input/joystick/gip/gip.h +5 -1
index 669ce6548d42..dc972ff168d7 100644
@@ -12,6 +12,7 @@
 #ifndef _GIP_H
 #define _GIP_H
 
+#include <linux/led-class-multicolor.h>
 #include <linux/rcupdate.h>
 #include <linux/usb/input.h>
 
@@ -240,6 +241,10 @@ struct gip_attachment {
 	uint8_t seq_vendor;
 
 	uint8_t device_state;
+	union {
+		struct led_classdev standard;
+		struct led_classdev_mc color;
+	} guide_led;
 
 	struct gip_extended_status status;
 
@@ -251,7 +256,6 @@ struct gip_attachment {
 	int extra_axes;
 
 	bool dpad_as_buttons;
-	struct hid_device __rcu *hdev;
 };
 
 struct gip_urb {
Signature · 1 line
2.54.0
#6 lore raw

Re: [PATCH v7 03/12] Input: xbox_gip - Add controllable LED support

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:

New issues:
- [Critical] LED class devices remain registered after the driver's private data (struct gip_attachment) is freed, leading to a Use-After-Free via sysfs attributes.
- [High] Double registration of the same embedded led_classdev during device reset causes list corruption.

Pre-existing issues:
- [Critical] This problem wasn't introduced by this patch, but a race condition in driver teardown leaves a window where gip_rumble_work can be scheduled and executed after attachment is freed, causing a Use-After-Free. --

commit 2f28cf978dca855a5f6208e26764df2b03de1082
Author: Vicki Pfau <[email protected]>

Input: xbox_gip - Add controllable LED support

Xbox One controllers have two different types of controllable LED support:

- Monochrome white, which most controllers have.
- RGBW addressible, which the Elite 2 controllers have.

This exposes both types as led cdevs.

Quoted 4 lines
drivers/input/joystick/gip/gip-core.c +0 -0
index b67b38c880cd3..9371d860a59b8 100644

[ ... ]

Quoted 1 line
drivers/input/joystick/gip/gip-core.c +0 -0
@@ -1056,9 +1056,120 @@ static int gip_send_guide_button_led(struct gip_attachment *attachment,

[ ... ]

Quoted 2 lines
drivers/input/joystick/gip/gip-core.c +2 -0
+static int gip_guide_led_probe(struct gip_attachment *attachment, struct device *dev)
+{

[ ... ]

drivers/input/joystick/gip/gip-core.c static int gip_send_guide_button_led(struct gip_attachment *attachment, · line 1148

Quoted 3 lines
drivers/input/joystick/gip/gip-core.c +3 -0
+		if (!rc)
+			rc = devm_led_classdev_multicolor_register(dev,
+				mc_cdev);

[Severity: High]
Can this cause a double registration of the same embedded led_classdev during a device reset?

If the controller unexpectedly resets (e.g., receiving a GIP_CMD_HELLO_DEVICE message), the driver calls gip_reset_attachment(), which unregisters the input_dev. It then re-initializes and allocates a new input_dev, calling gip_guide_led_probe() again.

Because the previous input_dev's devres hasn't executed (if userspace kept it open), the original LED registration is never undone. The driver then calls devm_led_classdev_multicolor_register() on the exact same statically embedded mc_cdev (which is still actively linked in leds_list). Double-registering a node into a linked list corrupts its pointers.

Quoted 6 lines
drivers/input/joystick/gip/gip-core.c +6 -0
+
+		if (rc)
+			devm_kfree(dev, mc_led_info);
+	} else {
+		struct led_classdev *cdev = &attachment->guide_led.standard;
+

drivers/input/joystick/gip/gip-core.c static int gip_send_guide_button_led(struct gip_attachment *attachment, · line 1164

Quoted 10 lines
drivers/input/joystick/gip/gip-core.c +10 -0
+		cdev->max_brightness = GIP_LED_GUIDE_MAX_BRIGHTNESS;
+		cdev->brightness = GIP_LED_GUIDE_INIT_BRIGHTNESS;
+		cdev->flags = LED_CORE_SUSPENDRESUME | LED_RETAIN_AT_SHUTDOWN;
+		cdev->brightness_set_blocking = gip_guide_led_set;
+		cdev->name = devm_kasprintf(dev, GFP_KERNEL,
+			"%s:white:power", dev_name(dev));
+		if (!cdev->name)
+			return -ENOMEM;
+
+		rc = devm_led_classdev_register(dev, cdev);

[Severity: High]
Similarly, does registering the standard embedded cdev here expose it to the same double-registration vulnerability during a device reset?

Quoted 7 lines
drivers/input/joystick/gip/gip-core.c +7 -0
+
+		if (rc)
+			devm_kfree(dev, cdev->name);
+	}
+
+	return rc;
+}

[ ... ]

drivers/input/joystick/gip/gip-core.c static int gip_setup_input_device(struct gip_attachment *attachment) · line 1283

Quoted 5 lines
drivers/input/joystick/gip/gip-core.c +1 -0
@@ -1169,6 +1280,10 @@ static int gip_setup_input_device(struct gip_attachment *attachment)
 	if (rc)
 		goto err_free_device;
 
+	rc = gip_guide_led_probe(attachment, &input->dev);

[Severity: Critical]
Can tying the devres lifecycle of the LED to &input->dev lead to a use-after-free?

During a physical disconnect, gip_disconnect() explicitly frees the attachment structure. However, if userspace holds an open file descriptor on the input device (e.g., via evdev), the input_dev reference count remains positive, delaying its devres execution.

This leaves the embedded led_classdev registered and pointing to freed memory. A subsequent write to the LED's sysfs attribute calls gip_guide_led_set(), which dereferences the freed attachment structure.

[Severity: Critical]
This is a pre-existing issue, but does a race condition in driver teardown leave a window where gip_rumble_work can be scheduled and executed after attachment is freed, causing a use-after-free?

In gip_shutdown(), work is canceled synchronously:

    cancel_work_sync(&attachment->rumble_work);

However, while the input_dev is still registered, a concurrent thread in userspace can invoke the EVIOCSFF ioctl, calling gip_play_effect() to re-schedule the work.

Later in the teardown, gip_reset_attachment() uses the non-blocking cancel_work():

    cancel_work(&attachment->rumble_work);

If the worker thread has already started executing, cancel_work() does not wait for it. The worker blocks on guard(mutex)(&attachment->lock) held by gip_shutdown(). gip_shutdown() then unregisters the input device and returns. gip_disconnect() then immediately frees the attachment structure. Finally, the worker thread unblocks, acquiring the lock and accessing the freed attachment.

Quoted 4 lines
drivers/input/joystick/gip/gip-core.c +3 -0
+	if (rc)
+		gip_err(attachment, "Failed to register LEDs: %d\n", rc);
+
 	return 0;
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
author
#7 lore raw

PATCH v7 4/12 Input: xbox_gip - Add HID relaying

In reply to Vicki Pfau

GIP allows tunneling of HID packets, with the HID descriptor embedded in the GIP metadata exchanged during the initial handshake. This patch creates a hid_device for this HID descriptor if found, as well as relaying the HID packets.

---
 drivers/input/joystick/gip/gip-core.c | 116 +++++++++++++++++++++++++-
 drivers/input/joystick/gip/gip.h      |   2 +
 include/uapi/linux/input.h            |   1 +
 3 files changed, 116 insertions(+), 3 deletions(-)
drivers/input/joystick/gip/gip-core.c +113 -3
index 9371d860a59b..411b67399e01 100644
@@ -560,6 +560,54 @@ int gip_send_vendor_message(struct gip_attachment *attachment,
 		bytes, num_bytes);
 }
 
+static int gip_hid_ll_parse(struct hid_device *hdev)
+{
+	struct gip_attachment *attachment = hdev->driver_data;
+
+	return hid_parse_report(hdev,
+		attachment->metadata.device.hid_descriptor,
+		attachment->metadata.device.hid_descriptor_size);
+}
+
+static int gip_hid_ll_start(struct hid_device *hdev)
+{
+	return 0;
+}
+
+static void gip_hid_ll_stop(struct hid_device *hdev)
+{
+}
+
+static int gip_hid_ll_open(struct hid_device *hdev)
+{
+	return 0;
+}
+
+static void gip_hid_ll_close(struct hid_device *hdev)
+{
+}
+
+static int gip_hid_ll_raw_request(struct hid_device *hdev,
+	unsigned char reportnum, uint8_t *buf, size_t count,
+	unsigned char report_type, int reqtype)
+{
+	/*
+	 * TODO: Based on the metadata, output reports appear to be possible,
+	 * but the chatpad doesn't have the LEDs it claims to support, so
+	 * it's not clear how to test we're sending them properly.
+	 */
+	return 0;
+}
+
+static const struct hid_ll_driver gip_hid_ll_driver = {
+	.parse = gip_hid_ll_parse,
+	.start = gip_hid_ll_start,
+	.stop = gip_hid_ll_stop,
+	.open = gip_hid_ll_open,
+	.close = gip_hid_ll_close,
+	.raw_request = gip_hid_ll_raw_request,
+};
+
 static void gip_metadata_free(struct device *dev, struct gip_metadata *metadata)
 {
 	devm_kfree(dev, metadata->device.audio_formats);
@@ -1322,6 +1370,51 @@ static int gip_init_input_device(struct gip_attachment *attachment)
 	return rc;
 }
 
+static int gip_create_hdev(struct gip_attachment *attachment)
+{
+	struct hid_device *hdev;
+	int rc;
+
+	if (!attachment->metadata.device.hid_descriptor)
+		return 0;
+
+	rcu_read_lock();
+	hdev = rcu_dereference(attachment->hdev);
+	rcu_read_unlock();
+	if (hdev)
+		return 0;
+
+	hdev = hid_allocate_device();
+
+	if (IS_ERR(hdev))
+		return PTR_ERR(hdev);
+
+	hdev->ll_driver = &gip_hid_ll_driver;
+	hdev->bus = BUS_GIP;
+	hdev->vendor = attachment->vendor_id;
+	hdev->product = attachment->product_id;
+	hdev->version = 0x0100;
+	hdev->country = 0;
+	hdev->dev.parent = to_gip_device(attachment);
+	hdev->driver_data = attachment;
+	if (attachment->name)
+		strscpy(hdev->name, attachment->name);
+	else
+		strscpy(hdev->name, "Xbox Chatpad");
+	strscpy(hdev->phys, attachment->phys);
+	strscpy(hdev->uniq, attachment->uniq);
+	rc = hid_add_device(hdev);
+	if (rc) {
+		gip_err(attachment, "HID device add failed: %d\n", rc);
+		hid_destroy_device(hdev);
+	} else {
+		rcu_assign_pointer(attachment->hdev, hdev);
+		synchronize_rcu();
+	}
+
+	return rc;
+}
+
 static int gip_send_init_sequence(struct gip_attachment *attachment)
 {
 	int rc = 0;
@@ -1387,7 +1480,11 @@ static int gip_send_init_sequence(struct gip_attachment *attachment)
 	if (rc)
 		return rc;
 
-	return 0;
+	rc = gip_create_hdev(attachment);
+	if (rc)
+		return rc;
+
+	return rc;
 }
 
 static void gip_fragment_timeout(struct work_struct *work)
@@ -1405,19 +1502,25 @@ static void gip_fragment_timeout(struct work_struct *work)
 static void gip_free_devices(struct gip_attachment *attachment)
 {
 	struct input_dev *input;
+	struct hid_device *hdev;
 
 	if (attachment->driver && attachment->driver->remove)
 		attachment->driver->remove(attachment);
 
 	rcu_read_lock();
 	input = rcu_dereference(attachment->input);
+	hdev = rcu_dereference(attachment->hdev);
 	rcu_read_unlock();
 
 	rcu_assign_pointer(attachment->input, NULL);
+	rcu_assign_pointer(attachment->hdev, NULL);
 	synchronize_rcu();
 
 	if (input)
 		input_unregister_device(input);
+
+	if (hdev)
+		hid_destroy_device(hdev);
 }
 
 static void gip_reset_metadata(struct gip_attachment *attachment)
@@ -1783,9 +1886,16 @@ static int gip_handle_command_firmware(struct gip_attachment *attachment,
 static int gip_handle_command_hid_report(struct gip_attachment *attachment,
 	const struct gip_header *header, uint8_t *bytes, int num_bytes)
 {
-	gip_warn_ratelimited(attachment, "Unimplemented HID report message\n");
+	struct hid_device *hdev;
 
-	return -EOPNOTSUPP;
+	guard(rcu)();
+	hdev = rcu_dereference(attachment->hdev);
+	if (hdev)
+		return hid_input_report(hdev, HID_INPUT_REPORT, bytes, num_bytes, true);
+
+	gip_warn(attachment, "Got HID report with no HID descriptor\n");
+
+	return -EPROTO;
 }
 
 static int gip_handle_command_extended(struct gip_attachment *attachment,
drivers/input/joystick/gip/gip.h +2 -0
index dc972ff168d7..525d04b83837 100644
@@ -12,6 +12,7 @@
 #ifndef _GIP_H
 #define _GIP_H
 
+#include <linux/hid.h>
 #include <linux/led-class-multicolor.h>
 #include <linux/rcupdate.h>
 #include <linux/usb/input.h>
@@ -256,6 +257,7 @@ struct gip_attachment {
 	int extra_axes;
 
 	bool dpad_as_buttons;
+	struct hid_device __rcu *hdev;
 };
 
 struct gip_urb {
include/uapi/linux/input.h +1 -0
index 6aa703fcfcfb..d9c630ff8292 100644
@@ -276,6 +276,7 @@ struct input_mask {
 #define BUS_INTEL_ISHTP		0x1F
 #define BUS_AMD_SFH		0x20
 #define BUS_SDW			0x21
+#define BUS_GIP			0x22
 
 /*
  * MT_TOOL types
Signature · 1 line
2.54.0
#8 lore raw

Re: [PATCH v7 04/12] Input: xbox_gip - Add HID relaying

Thank you for your contribution! Sashiko AI review found 7 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 7 potential issue(s) to consider:

New issues:
- [High] Use of hid_input_report instead of hid_safe_input_report can lead to out-of-bounds reads.
- [High] gip_hid_ll_raw_request returns 0 for an unimplemented feature, causing an infinite loop in userspace.
- [High] Calling strscpy() with a potentially NULL source pointer will cause a kernel panic.
- [High] The patch removes ratelimiting from a warning triggered by incoming USB packets, which can lead to kernel log spam.
- [Medium] Hardware HID reporting is enabled before the HID device is fully created and published, leading to dropped early reports.
- [Low] Unnecessary synchronize_rcu() after publishing a new RCU pointer.

Pre-existing issues:
- [Critical] Potential use-after-free of the gip structure during device disconnect because the receive_message workqueue can be rescheduled after it is cancelled. --

commit a00262371994fa8e8d98c8d8041e5850d744198e
Author: Vicki Pfau <[email protected]>

Input: xbox_gip - Add HID relaying

GIP allows tunneling of HID packets, with the HID descriptor embedded in the GIP metadata exchanged during the initial handshake. This patch creates a hid_device for this HID descriptor if found, as well as relaying the HID packets.

Quoted 4 lines
drivers/input/joystick/gip/gip-core.c +0 -0
index 9371d860a59b8..411b67399e018 100644

[ ... ]

drivers/input/joystick/gip/gip-core.c int gip_send_vendor_message(struct gip_attachment *attachment, · line 570

Quoted 12 lines
drivers/input/joystick/gip/gip-core.c +11 -0
@@ -560,6 +560,54 @@ int gip_send_vendor_message(struct gip_attachment *attachment,
+static int gip_hid_ll_raw_request(struct hid_device *hdev,
+	unsigned char reportnum, uint8_t *buf, size_t count,
+	unsigned char report_type, int reqtype)
+{
+	/*
+	 * TODO: Based on the metadata, output reports appear to be possible,
+	 * but the chatpad doesn't have the LEDs it claims to support, so
+	 * it's not clear how to test we're sending them properly.
+	 */
+	return 0;
+}

[Severity: High]
Returning 0 indicates success with 0 bytes transferred. When a userspace application calls write() on the hidraw device node, it will eventually call this raw_request callback. Won't returning 0 here cause standard userspace write loops to continuously retry indefinitely, resulting in a 100% CPU infinite loop? Should this return a negative error code like -EOPNOTSUPP instead?

[ ... ]

Quoted 1 line
drivers/input/joystick/gip/gip-core.c +0 -0
@@ -1322,6 +1370,51 @@ static int gip_init_input_device(struct gip_attachment *attachment)

[ ... ]

drivers/input/joystick/gip/gip-core.c static int gip_init_input_device(struct gip_attachment *attachment) · line 1405

Quoted 6 lines
drivers/input/joystick/gip/gip-core.c +6 -0
+	if (attachment->name)
+		strscpy(hdev->name, attachment->name);
+	else
+		strscpy(hdev->name, "Xbox Chatpad");
+	strscpy(hdev->phys, attachment->phys);
+	strscpy(hdev->uniq, attachment->uniq);

[Severity: High]
If attachment->uniq remains NULL (for example, if the earlier dynamic allocation via devm_kasprintf() failed under memory pressure), strscpy() will be called with a NULL source pointer. Since strscpy() doesn't gracefully handle NULL source pointers, won't this trigger a kernel panic during device hotplug?

drivers/input/joystick/gip/gip-core.c static int gip_init_input_device(struct gip_attachment *attachment) · line 1412

Quoted 7 lines
drivers/input/joystick/gip/gip-core.c +7 -0
+	rc = hid_add_device(hdev);
+	if (rc) {
+		gip_err(attachment, "HID device add failed: %d\n", rc);
+		hid_destroy_device(hdev);
+	} else {
+		rcu_assign_pointer(attachment->hdev, hdev);
+		synchronize_rcu();

[Severity: Low]
Because there are no pre-existing readers that could be accessing the newly published hdev pointer, is synchronize_rcu() needed here? Does this just add an unnecessary latency penalty during device initialization?

Quoted 4 lines
drivers/input/joystick/gip/gip-core.c +4 -0
+	}
+
+	return rc;
+}

[ ... ]

drivers/input/joystick/gip/gip-core.c static int gip_send_init_sequence(struct gip_attachment *attachment) · line 1488

Quoted 11 lines
drivers/input/joystick/gip/gip-core.c +5 -1
@@ -1387,7 +1480,11 @@ static int gip_send_init_sequence(struct gip_attachment *attachment)
 	if (rc)
 		return rc;
 
-	return 0;
+	rc = gip_create_hdev(attachment);
+	if (rc)
+		return rc;
+
+	return rc;
 }

[Severity: Medium]
Earlier in gip_send_init_sequence(), the driver sends a GIP_STATE_START command to the device, instructing it to begin reporting state. Because the HID device is created and published here after that hardware command, won't any early input reports arriving before gip_create_hdev() completes be dropped and trigger spurious kernel warnings?

[ ... ]

drivers/input/joystick/gip/gip-core.c static int gip_handle_command_firmware(struct gip_attachment *attachment, · line 1894

Quoted 12 lines
drivers/input/joystick/gip/gip-core.c +5 -2
@@ -1783,9 +1886,16 @@ static int gip_handle_command_firmware(struct gip_attachment *attachment,
 static int gip_handle_command_hid_report(struct gip_attachment *attachment,
 	const struct gip_header *header, uint8_t *bytes, int num_bytes)
 {
-	gip_warn_ratelimited(attachment, "Unimplemented HID report message\n");
+	struct hid_device *hdev;
 
-	return -EOPNOTSUPP;
+	guard(rcu)();
+	hdev = rcu_dereference(attachment->hdev);
+	if (hdev)
+		return hid_input_report(hdev, HID_INPUT_REPORT, bytes, num_bytes, true);

[Severity: High]
If a malicious or malfunctioning USB device crafts a report exceeding bounds because the descriptor defines more fields than the actual payload size, could using hid_input_report() here cause an out-of-bounds read in the HID core? The HID subsystem guidelines require transport drivers to use hid_safe_input_report() so the core can perform boundary checks against the allocated buffer size.

drivers/input/joystick/gip/gip-core.c static int gip_handle_command_firmware(struct gip_attachment *attachment, · line 1896

Quoted 2 lines
drivers/input/joystick/gip/gip-core.c +2 -0
+
+	gip_warn(attachment, "Got HID report with no HID descriptor\n");

[Severity: High]
By changing gip_warn_ratelimited() to a standard gip_warn(), a malfunctioning or malicious unprivileged USB device could send continuous HID report packets before a descriptor is configured. Could this flood the kernel log and lead to a denial of service?

[ ... ]

[Severity: Critical]
This isn't a bug introduced by this patch, but I noticed a potential use-after-free of the gip structure during device disconnect in the base driver.

Looking at gip_disconnect() in gip-core.c:

gip_disconnect()
gip_shutdown(gip); // synchronously cancels gip->receive_message

   usb_kill_anchored_urbs(&gip->data.out_anchor);
   if (gip->audio.intf)
       usb_kill_anchored_urbs(&gip->audio.out_anchor);

gip_deinit_input(&gip->data); // kills IN URB here

Because the USB IN URB is not killed until gip_deinit_input(), if the IN URB completes between gip_shutdown() and gip_deinit_input(), gip_urb_in() will execute and reschedule gip->receive_message.

When gip_disconnect() subsequently frees the gip structure, won't the rescheduled work execute on freed memory?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
author
#9 lore raw

PATCH v7 5/12 Input: xbox_gip - Add battery support

In reply to Vicki Pfau

Controllers are required to give information about the battery in the controller, if present. This patch exposes that information as a power_supply device.

---
 drivers/input/joystick/gip/gip-core.c | 116 +++++++++++++++++++++++++-
 drivers/input/joystick/gip/gip.h      |   4 +
 2 files changed, 116 insertions(+), 4 deletions(-)
drivers/input/joystick/gip/gip-core.c +112 -4
index 411b67399e01..92bfdd6d7682 100644
@@ -255,6 +255,13 @@ static const struct gip_audio_format gip_audio_format_table[MAX_GIP_AUDIO_FORMAT
 };
 
 
+static enum power_supply_property gip_battery_props[] = {
+	POWER_SUPPLY_PROP_PRESENT,
+	POWER_SUPPLY_PROP_CAPACITY_LEVEL,
+	POWER_SUPPLY_PROP_SCOPE,
+	POWER_SUPPLY_PROP_STATUS,
+};
+
 static const struct gip_quirks base_quirks[] = {
 	{ GIP_VID_PDP, GIP_PID_PDP_ROCK_CANDY, 0, .quirks = GIP_QUIRK_NO_HELLO },
 
@@ -1218,6 +1225,97 @@ static int gip_guide_led_probe(struct gip_attachment *attachment, struct device
 	return rc;
 }
 
+static int gip_battery_get_property(struct power_supply *psy,
+	enum power_supply_property psp, union power_supply_propval *val)
+{
+	struct gip_attachment *attachment = power_supply_get_drvdata(psy);
+
+	guard(spinlock_irqsave)(&attachment->battery_lock);
+	switch (psp) {
+	case POWER_SUPPLY_PROP_PRESENT:
+		val->intval = attachment->status.base.battery_type != GIP_BATTERY_ABSENT;
+		break;
+	case POWER_SUPPLY_PROP_SCOPE:
+		val->intval = POWER_SUPPLY_SCOPE_DEVICE;
+		break;
+	case POWER_SUPPLY_PROP_STATUS:
+		if (attachment->status.base.battery_type == GIP_BATTERY_ABSENT) {
+			val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING;
+		} else {
+			switch (attachment->status.base.charge) {
+			case GIP_CHARGING:
+				if (attachment->status.base.battery_level == GIP_BATTERY_FULL)
+					val->intval = POWER_SUPPLY_STATUS_FULL;
+				else
+					val->intval = POWER_SUPPLY_STATUS_CHARGING;
+				break;
+			case GIP_NOT_CHARGING:
+				val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
+				break;
+			case GIP_CHARGE_ERROR:
+			default:
+				val->intval = POWER_SUPPLY_STATUS_UNKNOWN;
+				break;
+			}
+		}
+		break;
+	case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
+		if (attachment->status.base.battery_type == GIP_BATTERY_ABSENT) {
+			val->intval = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
+		} else {
+			switch (attachment->status.base.battery_level) {
+			case GIP_BATTERY_CRITICAL:
+				val->intval = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
+				break;
+			case GIP_BATTERY_LOW:
+				val->intval = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
+				break;
+			case GIP_BATTERY_MEDIUM:
+				val->intval = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
+				break;
+			case GIP_BATTERY_FULL:
+				val->intval = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
+				break;
+			default:
+				val->intval = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
+				break;
+			}
+			break;
+		}
+		break;
+	default:
+		return -EINVAL;
+	}
+	return 0;
+}
+
+static int gip_battery_create(struct gip_attachment *attachment, struct device *dev)
+{
+	struct power_supply_config supply_config = { .drv_data = attachment, };
+	int rc;
+
+	attachment->battery_desc.properties = gip_battery_props;
+	attachment->battery_desc.num_properties = ARRAY_SIZE(gip_battery_props);
+	attachment->battery_desc.get_property = gip_battery_get_property;
+	attachment->battery_desc.type = POWER_SUPPLY_TYPE_BATTERY;
+	attachment->battery_desc.name = devm_kasprintf(dev, GFP_KERNEL, "gip-%s", dev_name(dev));
+
+	if (!attachment->battery_desc.name)
+		return -ENOMEM;
+
+	attachment->battery = devm_power_supply_register(dev,
+		&attachment->battery_desc, &supply_config);
+	if (IS_ERR(attachment->battery)) {
+		rc = PTR_ERR(attachment->battery);
+		attachment->battery = NULL;
+		devm_kfree(dev, attachment->battery_desc.name);
+		return rc;
+	}
+
+	power_supply_powers(attachment->battery, dev);
+	return 0;
+}
+
 static bool gip_send_set_device_state(struct gip_attachment *attachment, uint8_t state)
 {
 	uint8_t buffer[] = { state };
@@ -1331,6 +1429,9 @@ static int gip_setup_input_device(struct gip_attachment *attachment)
 	rc = gip_guide_led_probe(attachment, &input->dev);
 	if (rc)
 		gip_err(attachment, "Failed to register LEDs: %d\n", rc);
+	rc = gip_battery_create(attachment, &input->dev);
+	if (rc)
+		gip_err(attachment, "Failed to register battery: %d\n", rc);
 
 	return 0;
 
@@ -1514,6 +1615,8 @@ static void gip_free_devices(struct gip_attachment *attachment)
 
 	rcu_assign_pointer(attachment->input, NULL);
 	rcu_assign_pointer(attachment->hdev, NULL);
+	/* The following are freed by devres */
+	attachment->battery = NULL;
 	synchronize_rcu();
 
 	if (input)
@@ -1647,10 +1750,14 @@ static int gip_handle_command_status_device(struct gip_attachment *attachment,
 	if (num_bytes < 1)
 		return -EINVAL;
 
-	attachment->status.base.battery_level = bytes[0] & 3;
-	attachment->status.base.battery_type = (bytes[0] >> 2) & 3;
-	attachment->status.base.charge = (bytes[0] >> 4) & 3;
-	attachment->status.base.power_level = (bytes[0] >> 6) & 3;
+	scoped_guard(spinlock_irqsave, &attachment->battery_lock) {
+		attachment->status.base.battery_level = bytes[0] & 3;
+		attachment->status.base.battery_type = (bytes[0] >> 2) & 3;
+		attachment->status.base.charge = (bytes[0] >> 4) & 3;
+		attachment->status.base.power_level = (bytes[0] >> 6) & 3;
+	}
+	if (attachment->battery)
+		power_supply_changed(attachment->battery);
 
 	if (num_bytes >= 4) {
 		attachment->status.device_active = bytes[1] & 1;
@@ -2145,6 +2252,7 @@ static struct gip_attachment *gip_ensure_attachment(struct gip_device *device,
 		mutex_init(&attachment->lock);
 		guard(mutex)(&attachment->lock);
 		device->attachments[attachment_index] = attachment;
+		spin_lock_init(&attachment->battery_lock);
 		INIT_DELAYED_WORK(&attachment->in_fragment_timeout, gip_fragment_timeout);
 		INIT_DELAYED_WORK(&attachment->metadata_next, gip_retry_metadata);
 #ifdef CONFIG_JOYSTICK_XBOX_GIP_FF
drivers/input/joystick/gip/gip.h +4 -0
index 525d04b83837..42b46b473b7e 100644
@@ -14,6 +14,7 @@
 
 #include <linux/hid.h>
 #include <linux/led-class-multicolor.h>
+#include <linux/power_supply.h>
 #include <linux/rcupdate.h>
 #include <linux/usb/input.h>
 
@@ -247,6 +248,9 @@ struct gip_attachment {
 		struct led_classdev_mc color;
 	} guide_led;
 
+	spinlock_t battery_lock;
+	struct power_supply *battery;
+	struct power_supply_desc battery_desc;
 	struct gip_extended_status status;
 
 	enum gip_elite_button_format xbe_format;
Signature · 1 line
2.54.0
#10 lore raw

Re: [PATCH v7 05/12] Input: xbox_gip - Add battery support

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:

New issues:
- [Critical] The devm-managed power supply is tied to the input_dev's lifecycle instead of the physical device, leading to a Use-After-Free of attachment when sysfs properties are read after unplug.
- [High] Memory and device leak of the power supply across metadata resets due to a devres mismatch when unregistering the input device.
- [High] Data race and potential Use-After-Free on attachment->battery during concurrent device status URB processing and device teardown.

Pre-existing issues:
- [Critical] Use-after-free of gip_device and gip_attachment due to incorrect teardown order of the URB and workqueue in gip_disconnect. --

commit e93493b8a8fc4d66dfb37174e70166cba8bd408c
Author: Vicki Pfau <[email protected]>

Input: xbox_gip - Add battery support

Controllers are required to give information about the battery in the controller, if present. This patch exposes that information as a power_supply device.

Quoted 4 lines
drivers/input/joystick/gip/gip-core.c +0 -0
index 411b67399e018..92bfdd6d76826 100644

[ ... ]

Quoted 1 line
drivers/input/joystick/gip/gip-core.c +0 -0
@@ -1218,6 +1225,97 @@ static int gip_guide_led_probe(struct gip_attachment *attachment, struct device

[ ... ]

Quoted 6 lines
drivers/input/joystick/gip/gip-core.c +6 -0
+static int gip_battery_create(struct gip_attachment *attachment, struct device *dev)
+{
+	struct power_supply_config supply_config = { .drv_data = attachment, };
+	int rc;
+
+	attachment->battery_desc.properties = gip_battery_props;

drivers/input/joystick/gip/gip-core.c static int gip_guide_led_probe(struct gip_attachment *attachment, struct device · line 1307

Quoted 10 lines
drivers/input/joystick/gip/gip-core.c +10 -0
+	attachment->battery_desc.num_properties = ARRAY_SIZE(gip_battery_props);
+	attachment->battery_desc.get_property = gip_battery_get_property;
+	attachment->battery_desc.type = POWER_SUPPLY_TYPE_BATTERY;
+	attachment->battery_desc.name = devm_kasprintf(dev, GFP_KERNEL, "gip-%s", dev_name(dev));
+
+	if (!attachment->battery_desc.name)
+		return -ENOMEM;
+
+	attachment->battery = devm_power_supply_register(dev,
+		&attachment->battery_desc, &supply_config);

[Severity: Critical]
Does this tie the power supply's devres lifecycle to the child input_dev rather than the parent attachment?

If dev is &input->dev, the power supply will outlive the attachment structure if a user unplugs the device while keeping the input device open.

Since attachment is explicitly freed on disconnect, couldn't this lead to a use-after-free when the user subsequently reads sysfs properties (via gip_battery_get_property) which dereferences the freed attachment?

Quoted 10 lines
drivers/input/joystick/gip/gip-core.c +10 -0
+	if (IS_ERR(attachment->battery)) {
+		rc = PTR_ERR(attachment->battery);
+		attachment->battery = NULL;
+		devm_kfree(dev, attachment->battery_desc.name);
+		return rc;
+	}
+
+	power_supply_powers(attachment->battery, dev);
+	return 0;
+}

[ ... ]

drivers/input/joystick/gip/gip-core.c static void gip_free_devices(struct gip_attachment *attachment) · line 1622

Quoted 9 lines
drivers/input/joystick/gip/gip-core.c +2 -0
@@ -1514,6 +1615,8 @@ static void gip_free_devices(struct gip_attachment *attachment)
 
 	rcu_assign_pointer(attachment->input, NULL);
 	rcu_assign_pointer(attachment->hdev, NULL);
+	/* The following are freed by devres */
+	attachment->battery = NULL;
 	synchronize_rcu();
 
 	if (input)

[Severity: High]
Does this code assume devres will immediately free the battery upon calling input_unregister_device()?

Because the devres lifecycle of input_dev depends on its parent (the USB interface), its refcount doesn't drop to zero until the USB interface unbinds.

If a device sends repeated reset requests that invoke gip_free_devices(), could this leak power_supply devices and their sysfs entries indefinitely across metadata resets?

Quoted 6 lines
drivers/input/joystick/gip/gip-core.c +0 -2
@@ -1647,10 +1750,14 @@ static int gip_handle_command_status_device(struct gip_attachment *attachment,
 	if (num_bytes < 1)
 		return -EINVAL;
 
-	attachment->status.base.battery_level = bytes[0] & 3;
-	attachment->status.base.battery_type = (bytes[0] >> 2) & 3;

drivers/input/joystick/gip/gip-core.c static int gip_handle_command_status_device(struct gip_attachment *attachment, · line 1760

Quoted 10 lines
drivers/input/joystick/gip/gip-core.c +8 -2
-	attachment->status.base.charge = (bytes[0] >> 4) & 3;
-	attachment->status.base.power_level = (bytes[0] >> 6) & 3;
+	scoped_guard(spinlock_irqsave, &attachment->battery_lock) {
+		attachment->status.base.battery_level = bytes[0] & 3;
+		attachment->status.base.battery_type = (bytes[0] >> 2) & 3;
+		attachment->status.base.charge = (bytes[0] >> 4) & 3;
+		attachment->status.base.power_level = (bytes[0] >> 6) & 3;
+	}
+	if (attachment->battery)
+		power_supply_changed(attachment->battery);

[Severity: High]
Is it safe to access attachment->battery here without RCU read-side protection or READ_ONCE()?

Since gip_handle_command_status_device() executes concurrently with device teardown, gip_free_devices() might concurrently clear the pointer (attachment->battery = NULL) and call synchronize_rcu().

Without rcu_read_lock() held here, synchronize_rcu() will not wait, potentially allowing the battery pointer to be freed underneath this reader, leading to a use-after-free.

[Severity: Critical]
This is a pre-existing issue, but can a use-after-free of gip_device and gip_attachment happen due to an incorrect teardown order in gip_disconnect()?

Looking at gip_disconnect(), it calls gip_shutdown() which cancels the receive_message workqueue. However, the URB that re-queues this work is not killed until gip_deinit_input() runs later.

Could this open a race window where an interrupt packet arrives just after cancel_work_sync(&gip->receive_message), allowing gip_urb_in() to reschedule the work?

The device structures would then be freed by devm_kfree() at the end of disconnect, and the newly scheduled work would dereference freed memory when it executes.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
author
#11 lore raw

PATCH v7 6/12 Input: xbox_gip - Allow sending fragmented and ACME messages

In reply to Vicki Pfau

GIP supports sending messages that exceed the length of the MTU using a fragmented message flow. It sits on top of a reliable message transmission flow, which uses the ACME flag to signal that a message must be ACKed if it is received properly. We already supported receiving and coalescing these messages, but the ability to send them wasn't yet present due to not needing it for basic usage. This patch adds it for future use with the security flow.

---
 drivers/input/joystick/gip/gip-core.c | 394 ++++++++++++++++++++++++--
 drivers/input/joystick/gip/gip.h      |  20 ++
 2 files changed, 396 insertions(+), 18 deletions(-)
drivers/input/joystick/gip/gip-core.c +376 -18
index 92bfdd6d7682..1bfb559f5f7a 100644
@@ -8,7 +8,6 @@
  * - Audio device support
  * - Security packet handshake
  * - Event logging
- * - Sending fragmented messages
  * - Raw character device
  * - Wheel support
  * - Flight stick support
@@ -28,6 +27,7 @@
 #define GIP_WIRED_INTF_DATA 0
 #define GIP_WIRED_INTF_AUDIO 1
 
+#define GIP_DUAL_LENGTH 6
 #define MAX_MESSAGE_LENGTH 0x4000
 
 #define MAX_AUDIO_MESSAGES 9
@@ -40,6 +40,9 @@
 #define GIP_DATA_CLASS_SHIFT 5
 #define GIP_DATA_CLASS_MASK (7u << 5)
 
+#define GIP_ACME_RETRY_TIME	(HZ / 10)
+#define GIP_ACME_MAX_RETRIES	8
+
 /* Undocumented Elite 2 vendor messages */
 #define GIP_CMD_RAW_REPORT		0x0c
 #define GIP_CMD_GUIDE_COLOR		0x0e
@@ -437,6 +440,13 @@ static uint8_t gip_sequence_next(struct gip_attachment *attachment,
 	return seq;
 }
 
+static unsigned int gip_fragment_id(const struct gip_attachment *attachment,
+	const struct gip_out_fragment *fragment)
+{
+	return BIT(attachment->attachment_index * MAX_OUT_FRAGMENTS +
+		(unsigned int) (fragment - attachment->out_fragments));
+}
+
 static void gip_handle_quirks_array(struct gip_attachment *attachment,
 	const struct gip_quirks *quirks)
 {
@@ -479,6 +489,51 @@ static void gip_handle_quirks(struct gip_attachment *attachment)
 		gip_handle_quirks_array(attachment, attachment->driver->quirks);
 }
 
+static struct gip_out_fragment *gip_find_fragment(struct gip_attachment *attachment,
+	uint8_t message_type, uint8_t flags, uint8_t seq, bool strict)
+{
+	int i;
+
+	for (i = 0; i < MAX_OUT_FRAGMENTS; i++) {
+		if (!attachment->out_fragments[i].active)
+			continue;
+		if (attachment->out_fragments[i].message != message_type)
+			continue;
+		if ((attachment->out_fragments[i].flags ^ flags) & GIP_FLAG_SYSTEM)
+			continue;
+		if (attachment->out_fragments[i].seq != seq) {
+			if (strict)
+				continue;
+
+			/*
+			 * Found one with  the wrong sequence number. For some
+			 * reason the official driver allows this.
+			 */
+			gip_warn(attachment,
+				"Found fragment with different sequence number %02x, wanted %02x\n",
+				attachment->out_fragments[i].seq, seq);
+		}
+
+		return &attachment->out_fragments[i];
+	}
+	return NULL;
+}
+
+static void gip_free_fragment(struct gip_out_fragment *fragment)
+{
+	cancel_delayed_work(&fragment->timeout);
+	kfree(fragment->data);
+	fragment->data = NULL;
+	fragment->active = false;
+	fragment->acked = false;
+	fragment->message = 0;
+	fragment->flags = 0;
+	fragment->seq = 0;
+	fragment->retries = 0;
+	fragment->total_length = 0;
+	fragment->fragment_offset = 0;
+}
+
 static int gip_send_raw_message(struct gip_attachment *attachment,
 	uint8_t message_type, uint8_t flags, uint8_t seq, const uint8_t *bytes,
 	int num_bytes)
@@ -486,20 +541,25 @@ static int gip_send_raw_message(struct gip_attachment *attachment,
 	struct gip_interface *intf;
 	int offset = 3;
 	struct gip_urb *urb = NULL;
+	struct gip_out_fragment *fragment = NULL;
 	int i;
 	int rc = 0;
+	int mtu = gip_data_class_mtu[message_type >> GIP_DATA_CLASS_SHIFT];
+	int reduced_mtu = mtu - GIP_DUAL_LENGTH;
+	/*
+	 * This buffer size shouldn't need to be more than 6 (there should never
+	 * be more than 3 length bytes), but add enough extra to fit fully
+	 * extended bignums for 32 bit (5 bytes) + 16 bit (3 bytes) values to be
+	 * safe and then WARN_ON if we go over. If this ever happens it would be
+	 * due to driver bugs.
+	 */
+	uint8_t header[11];
 
 	if (num_bytes < 0) {
 		gip_warn(attachment, "Invalid message length %d\n", num_bytes);
 		return -EINVAL;
 	}
 
-	if (num_bytes + 6 > gip_data_class_mtu[message_type >> GIP_DATA_CLASS_SHIFT]) {
-		gip_err(attachment,
-			"Attempted to send a message that requires fragmenting, which is not yet supported.\n");
-		return -EOPNOTSUPP;
-	}
-
 	if ((message_type & GIP_DATA_CLASS_MASK) == GIP_DATA_CLASS_AUDIO)
 		intf = &attachment->device->audio;
 	else
@@ -511,6 +571,89 @@ static int gip_send_raw_message(struct gip_attachment *attachment,
 		return -EOPNOTSUPP;
 	}
 
+	header[0] = message_type;
+	header[2] = seq;
+
+	if (num_bytes > reduced_mtu ||
+		(flags & (GIP_FLAG_ACME | GIP_FLAG_FRAGMENT)) == GIP_FLAG_ACME) {
+		for (i = 0; i < MAX_OUT_FRAGMENTS; i++) {
+			if (attachment->out_fragments[i].active)
+				continue;
+
+			fragment = &attachment->out_fragments[i];
+			break;
+		}
+
+		if (!fragment) {
+			gip_err(attachment, "Fragmented message queue is full; dropping message\n");
+			return -EALREADY;
+		}
+
+		fragment->data = kzalloc(num_bytes, GFP_KERNEL);
+		if (!fragment->data)
+			return -ENOMEM;
+		fragment->active = true;
+		fragment->message = message_type;
+		fragment->flags = flags & GIP_FLAG_SYSTEM;
+		fragment->seq = seq;
+		fragment->total_length = num_bytes;
+		fragment->fragment_offset = 0;
+		memcpy(fragment->data, bytes, num_bytes);
+		bytes = fragment->data;
+
+		if (num_bytes > reduced_mtu) {
+			gip_dbg(attachment, "Starting new reliable message: %02x%02x%02x, total length %u\n",
+				message_type, flags, seq, num_bytes);
+			flags |= GIP_FLAG_INIT_FRAG | GIP_FLAG_FRAGMENT | GIP_FLAG_ACME;
+			fragment->flags |= GIP_FLAG_FRAGMENT;
+			/* The spec says to extend the value to fit in 3 bytes */
+			offset += gip_encode_length(reduced_mtu, &header[offset], sizeof(header));
+			if (offset == 4 && reduced_mtu < 0x80 && num_bytes < 0x80) {
+				header[3] |= 0x80;
+				header[4] = 0;
+				offset = 5;
+			}
+			offset += gip_encode_length(num_bytes, &header[offset],
+				sizeof(header) - offset);
+			WARN_ON(offset != GIP_DUAL_LENGTH);
+			num_bytes = mtu - offset;
+		} else {
+			offset += gip_encode_length(num_bytes, &header[offset],
+				sizeof(header) - offset);
+		}
+	} else if (flags & GIP_FLAG_FRAGMENT) {
+		fragment = gip_find_fragment(attachment, message_type, flags, seq, true);
+		if (!fragment) {
+			gip_err(attachment,
+				"Attempted to send message fragment with no associated message\n");
+			return -EINVAL;
+		}
+
+		num_bytes = min(reduced_mtu, fragment->total_length - fragment->fragment_offset);
+		offset += gip_encode_length(num_bytes, &header[offset],
+			sizeof(header) - offset);
+		if (offset == 4 && num_bytes < 0x80 && fragment->fragment_offset < 0x80) {
+			header[3] |= 0x80;
+			header[4] = 0;
+			offset = 5;
+		}
+		offset += gip_encode_length(fragment->fragment_offset, &header[offset],
+			sizeof(header) - offset);
+		WARN_ON(offset != GIP_DUAL_LENGTH);
+
+		if (num_bytes && fragment->fragment_offset + num_bytes == fragment->total_length) {
+			/* The final fragment in a fragmented message must be ACKed */
+			flags |= GIP_FLAG_ACME;
+			fragment->acked = false;
+		}
+		bytes = &fragment->data[fragment->fragment_offset];
+	} else if (num_bytes >= 0) {
+		offset += gip_encode_length(num_bytes, &header[offset],
+			sizeof(header) - offset);
+	}
+
+	header[1] = flags;
+
 	guard(spinlock_irqsave)(&attachment->device->message_lock);
 	for (i = 0; i < MAX_OUT_MESSAGES && !urb; i++) {
 		if (!intf->out_queue[i].urb)
@@ -520,17 +663,14 @@ static int gip_send_raw_message(struct gip_attachment *attachment,
 	}
 	if (!urb) {
 		gip_err(attachment, "Output queue is full; dropping message\n");
+		if (fragment)
+			gip_free_fragment(fragment);
 		return -ENOSPC;
 	}
-	urb->data[0] = message_type;
-	urb->data[1] = flags;
-	urb->data[2] = seq;
-	offset += gip_encode_length(num_bytes, &urb->data[offset],
-		sizeof(urb->data) - offset);
 
+	memcpy(urb->data, header, offset);
 	if (num_bytes > 0)
 		memcpy(&urb->data[offset], bytes, num_bytes);
-
 	num_bytes += offset;
 	urb->urb->transfer_buffer_length = num_bytes;
 
@@ -544,12 +684,109 @@ static int gip_send_raw_message(struct gip_attachment *attachment,
 			"%s - usb_submit_urb failed with result %d\n",
 			__func__, rc);
 		usb_unanchor_urb(urb->urb);
-		rc = -EIO;
+		if (fragment)
+			gip_free_fragment(fragment);
+		return -EIO;
+	}
+
+	if (fragment) {
+		/*
+		 * Sending further fragments is handled in gip_urb_out if this fragment doesn't need
+		 * ACKing or in gip_handle_command_protocol_control if it does. The flag should also
+		 * be cleared if we're done sending this packet.
+		 */
+		if (fragment->total_length > reduced_mtu && !(flags & GIP_FLAG_ACME))
+			intf->has_pending_out |= gip_fragment_id(attachment, fragment);
+		else
+			intf->has_pending_out &= ~gip_fragment_id(attachment, fragment);
+		if (flags & GIP_FLAG_ACME)
+			schedule_delayed_work(&fragment->timeout, GIP_ACME_RETRY_TIME);
 	}
 
 	return rc;
 }
 
+static int gip_send_next_fragment(struct gip_attachment *attachment,
+	struct gip_out_fragment *fragment)
+{
+	struct gip_interface *intf;
+	int next_bytes;
+	int flags = GIP_FLAG_FRAGMENT | fragment->flags | attachment->attachment_index;
+	int mtu;
+	int rc;
+
+	mtu = gip_data_class_mtu[fragment->message >> GIP_DATA_CLASS_SHIFT] - GIP_DUAL_LENGTH;
+	if (fragment->fragment_offset == fragment->total_length) {
+		if ((fragment->message & GIP_DATA_CLASS_MASK) == GIP_DATA_CLASS_AUDIO)
+			intf = &attachment->device->audio;
+		else
+			intf = &attachment->device->data;
+
+		next_bytes = 0;
+		guard(spinlock_irqsave)(&intf->device->message_lock);
+		intf->has_pending_out &= ~gip_fragment_id(attachment, fragment);
+	} else if (fragment->fragment_offset + mtu >= fragment->total_length) {
+		next_bytes = fragment->total_length - fragment->fragment_offset;
+		flags |= GIP_FLAG_ACME;
+	} else {
+		if (fragment->fragment_offset == 0)
+			flags |= GIP_FLAG_INIT_FRAG | GIP_FLAG_ACME;
+		next_bytes = mtu;
+	}
+
+	rc = gip_send_raw_message(attachment, fragment->message, flags,
+		fragment->seq, &fragment->data[fragment->fragment_offset],
+		next_bytes);
+
+	if (rc < 0)
+		return rc;
+
+	if (fragment->acked)
+		fragment->fragment_offset += next_bytes;
+	if (next_bytes == 0 && !(fragment->flags & GIP_FLAG_ACME)) {
+		/* Finished sending the message */
+		gip_free_fragment(fragment);
+	} else if (flags & GIP_FLAG_ACME) {
+		fragment->acked = false;
+		schedule_delayed_work(&fragment->timeout, GIP_ACME_RETRY_TIME);
+	}
+	return next_bytes;
+}
+
+static void gip_send_fragment_work(struct work_struct *work)
+{
+	struct gip_interface *intf = container_of(work, struct gip_interface, send_fragment);
+	struct gip_out_fragment *fragment;
+	unsigned int has_pending_out;
+	unsigned long flags;
+	int i, j;
+
+	spin_lock_irqsave(&intf->device->message_lock, flags);
+	has_pending_out = intf->has_pending_out;
+	spin_unlock_irqrestore(&intf->device->message_lock, flags);
+	for (i = 0; i < MAX_ATTACHMENTS; i++) {
+		struct gip_attachment *attachment;
+
+		mutex_lock(&intf->device->attachment_lock);
+		attachment = intf->device->attachments[i];
+		mutex_unlock(&intf->device->attachment_lock);
+
+		for (j = 0; j < MAX_OUT_FRAGMENTS; j++) {
+			/* Check for pending output fragments */
+			if (!(has_pending_out & BIT(i * MAX_OUT_FRAGMENTS + j)))
+				continue;
+
+			guard(mutex)(&attachment->lock);
+			fragment = &attachment->out_fragments[j];
+			if (!fragment->active)
+				continue;
+			if (!(fragment->flags & GIP_FLAG_FRAGMENT))
+				continue;
+			gip_send_next_fragment(attachment, fragment);
+		}
+	}
+}
+
 int gip_send_system_message(struct gip_attachment *attachment,
 	uint8_t message_type, uint8_t flags, const void *bytes, int num_bytes)
 {
@@ -1600,6 +1837,25 @@ static void gip_fragment_timeout(struct work_struct *work)
 	gip_free_in_fragment(attachment);
 }
 
+static void gip_out_fragment_timeout(struct work_struct *work)
+{
+	struct gip_out_fragment *fragment = container_of(to_delayed_work(work),
+		struct gip_out_fragment, timeout);
+	struct gip_attachment *attachment = fragment->attachment;
+
+	guard(mutex)(&attachment->lock);
+	if (!fragment->active || !fragment->data || fragment->acked)
+		return;
+
+	fragment->retries++;
+	if (fragment->retries >= GIP_ACME_MAX_RETRIES) {
+		gip_free_fragment(fragment);
+		gip_warn(attachment, "Reliable message transmission failed\n");
+		return;
+	}
+	gip_send_next_fragment(attachment, fragment);
+}
+
 static void gip_free_devices(struct gip_attachment *attachment)
 {
 	struct input_dev *input;
@@ -1670,6 +1926,12 @@ static int gip_ensure_metadata(struct gip_attachment *attachment)
 
 static void gip_reset_attachment(struct gip_attachment *attachment)
 {
+	int i;
+	int pending_out_bits =
+		BIT((attachment->attachment_index + 1) * MAX_OUT_FRAGMENTS) -
+		BIT(attachment->attachment_index * MAX_OUT_FRAGMENTS);
+	unsigned long flags;
+
 	cancel_delayed_work(&attachment->metadata_next);
 	cancel_delayed_work(&attachment->in_fragment_timeout);
 	cancel_work(&attachment->rumble_work);
@@ -1677,15 +1939,91 @@ static void gip_reset_attachment(struct gip_attachment *attachment)
 	if (attachment->in_fragment_data)
 		gip_free_in_fragment(attachment);
 
+	spin_lock_irqsave(&attachment->device->message_lock, flags);
+	attachment->device->data.has_pending_out &= ~pending_out_bits;
+	attachment->device->audio.has_pending_out &= ~pending_out_bits;
+	spin_unlock_irqrestore(&attachment->device->message_lock, flags);
+
+	for (i = 0; i < MAX_OUT_FRAGMENTS; i++) {
+		if (attachment->out_fragments[i].active)
+			gip_free_fragment(&attachment->out_fragments[i]);
+	}
+
 	gip_free_devices(attachment);
+
 }
 
 static int gip_handle_command_protocol_control(struct gip_attachment *attachment,
 	const struct gip_header *header, const uint8_t *bytes, int num_bytes)
 {
-	/* TODO */
-	gip_warn_ratelimited(attachment, "Unimplemented Protocol Control message\n");
-	return -EOPNOTSUPP;
+	const struct gip_protocol_control_ack *ack;
+	struct gip_out_fragment *fragment = NULL;
+	uint32_t fragment_offset;
+	uint16_t remaining_buffer;
+	bool ok = true;
+	int mtu;
+	int rc;
+
+	if (num_bytes < 1)
+		return -EINVAL;
+
+	if (bytes[0] != GIP_CONTROL_CODE_ACK) {
+		gip_warn_ratelimited(attachment,
+			"Unimplemented Protocol Control code %i message\n", bytes[0]);
+		return -EOPNOTSUPP;
+	}
+
+	if (num_bytes < sizeof(*ack))
+		return -EINVAL;
+
+	ack = (const struct gip_protocol_control_ack *)bytes;
+
+	fragment = gip_find_fragment(attachment, ack->message_type, ack->flags,
+		header->sequence_id, false);
+	if (!fragment) {
+		gip_warn(attachment, "Received ACK for unknown message\n");
+		return -EINVAL;
+	}
+
+
+	fragment_offset = le32_to_cpu(ack->fragment_offset);
+	remaining_buffer = le16_to_cpu(ack->remaining_buffer);
+
+	if (fragment_offset > fragment->total_length)
+		ok = false;
+	mtu = gip_data_class_mtu[fragment->message >> GIP_DATA_CLASS_SHIFT] - GIP_DUAL_LENGTH;
+	if (!ok) {
+		gip_warn(attachment, "Received invalid buffer offset in ACK, "
+			"got offset=%u + remaining=%u, expected offset=%u + remaining=%u\n",
+			fragment_offset, remaining_buffer,
+			fragment->fragment_offset, fragment->total_length - fragment->fragment_offset);
+		rc = -EINVAL;
+		goto resend;
+	} else if ((fragment->flags & GIP_FLAG_FRAGMENT) &&
+		(fragment->fragment_offset > fragment_offset ||
+		fragment->fragment_offset + mtu < fragment_offset)) {
+		gip_warn(attachment, "Received unexpected buffer offset in ACK, "
+			"got offset=%u, expected offset=%u\n",
+			fragment_offset, fragment->fragment_offset + mtu);
+	}
+
+	fragment->acked = true;
+	fragment->retries = 0;
+	cancel_delayed_work(&fragment->timeout);
+	if (fragment->flags & GIP_FLAG_FRAGMENT) {
+		fragment->fragment_offset = fragment_offset;
+		rc = gip_send_next_fragment(attachment, fragment);
+		if (rc < 0)
+			return rc;
+	} else {
+		gip_free_fragment(fragment);
+	}
+
+	return 0;
+
+resend:
+	gip_send_next_fragment(attachment, fragment);
+	return rc;
 }
 
 static bool gip_handle_command_hello_device(struct gip_attachment *attachment,
@@ -2232,6 +2570,7 @@ static struct gip_attachment *gip_ensure_attachment(struct gip_device *device,
 	uint8_t attachment_index)
 {
 	struct gip_attachment *attachment;
+	int i;
 
 	guard(mutex)(&device->attachment_lock);
 	attachment = device->attachments[attachment_index];
@@ -2249,6 +2588,11 @@ static struct gip_attachment *gip_ensure_attachment(struct gip_device *device,
 			attachment->product_id = device->udev->descriptor.idProduct;
 		}
 
+		for (i = 0; i < MAX_OUT_FRAGMENTS; i++) {
+			attachment->out_fragments[i].attachment = attachment;
+			INIT_DELAYED_WORK(&attachment->out_fragments[i].timeout, gip_out_fragment_timeout);
+		}
+
 		mutex_init(&attachment->lock);
 		guard(mutex)(&attachment->lock);
 		device->attachments[attachment_index] = attachment;
@@ -2561,6 +2905,7 @@ static void gip_urb_out(struct urb *urb)
 	switch (status) {
 	case 0:
 		/* success */
+		schedule_work(&intf->send_fragment);
 		break;
 
 	case -ECONNRESET:
@@ -2758,9 +3103,11 @@ static int gip_probe(struct usb_interface *intf, const struct usb_device_id *id)
 	gip->data.device = gip;
 	gip->data.intf = intf;
 	gip->data.mtu = BASE_GIP_MTU;
+	INIT_WORK(&gip->data.send_fragment, gip_send_fragment_work);
 	gip->audio.device = gip;
 	gip->audio.mtu = MAX_GIP_MTU;
 	gip->audio.isoc_messages = MAX_AUDIO_MESSAGES;
+	INIT_WORK(&gip->audio.send_fragment, gip_send_fragment_work);
 
 	INIT_WORK(&gip->receive_message, gip_receive_work);
 	spin_lock_init(&gip->message_lock);
@@ -2797,8 +3144,17 @@ static int gip_probe(struct usb_interface *intf, const struct usb_device_id *id)
 static void gip_shutdown(struct gip_device *gip)
 {
 	int i;
+	unsigned long flags;
+
+	spin_lock_irqsave(&gip->message_lock, flags);
+	gip->data.has_pending_out = 0;
+	gip->audio.has_pending_out = 0;
+	spin_unlock_irqrestore(&gip->message_lock, flags);
 
 	cancel_work_sync(&gip->receive_message);
+	cancel_work_sync(&gip->data.send_fragment);
+	if (gip->audio.intf)
+		cancel_work_sync(&gip->audio.send_fragment);
 
 	for (i = 0; i < MAX_ATTACHMENTS; i++) {
 		struct gip_attachment *attachment;
@@ -2823,7 +3179,7 @@ static void gip_shutdown(struct gip_device *gip)
 static void gip_disconnect(struct usb_interface *intf)
 {
 	struct gip_device *gip = usb_get_intfdata(intf);
-	int i;
+	int i, j;
 
 	if (!gip)
 		return;
@@ -2850,6 +3206,8 @@ static void gip_disconnect(struct usb_interface *intf)
 		if (!attachment)
 			continue;
 
+		for (j = 0; j < MAX_OUT_FRAGMENTS; j++)
+			cancel_delayed_work_sync(&attachment->out_fragments[i].timeout);
 		devm_kfree(to_gip_device(attachment), attachment->uniq);
 		devm_kfree(to_gip_device(attachment), attachment);
 		gip->attachments[i] = NULL;
drivers/input/joystick/gip/gip.h +20 -0
index 42b46b473b7e..fa97f5bfb50a 100644
@@ -25,6 +25,7 @@
 
 #define MAX_IN_MESSAGES 8
 #define MAX_OUT_MESSAGES 8
+#define MAX_OUT_FRAGMENTS 2
 
 #define GIP_VID_MICROSOFT	0x045e
 #define GIP_VID_PDP		0x0e6f
@@ -194,6 +195,20 @@ struct gip_extended_status {
 	struct gip_status_event events[5];
 };
 
+struct gip_out_fragment {
+	struct gip_attachment *attachment;
+	bool active;
+	bool acked;
+	uint8_t message;
+	uint8_t flags;
+	uint8_t seq;
+	uint8_t retries;
+	uint16_t total_length;
+	uint32_t fragment_offset;
+	uint8_t *data;
+	struct delayed_work timeout;
+};
+
 struct gip_attachment;
 typedef int (*gip_command_handler)(struct gip_attachment *a, const struct gip_header *header,
 		const uint8_t *bytes, int num_bytes);
@@ -222,6 +237,8 @@ struct gip_attachment {
 	struct delayed_work in_fragment_timeout;
 	int in_fragment_retries;
 
+	struct gip_out_fragment out_fragments[MAX_OUT_FRAGMENTS];
+
 	uint16_t firmware_major_version;
 	uint16_t firmware_minor_version;
 
@@ -281,6 +298,9 @@ struct gip_interface {
 
 	struct usb_anchor out_anchor;
 	struct gip_urb out_queue[MAX_OUT_MESSAGES];
+
+	struct work_struct send_fragment;
+	unsigned int has_pending_out;
 };
 
 struct gip_device {
Signature · 1 line
2.54.0
#12 lore raw

Re: [PATCH v7 06/12] Input: xbox_gip - Allow sending fragmented and ACME messages

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:

New issues:
- [Critical] Loop index typo in gip_disconnect causes OOB array access and failure to cancel delayed work.
- [High] Retrying reliable (ACME) messages corrupts their headers due to incorrect flag and length field encoding.
- [High] Teardown sequence race condition causing Use-After-Free of device structures due to URBs re-scheduling cancelled works.

Pre-existing issues:
- [High] AB-BA deadlock during device reset due to unregistering input device under lock.
- [High] Teardown ordering race condition causing UAF of rumble_work and attachment memory. --

commit d64a449cbd12693ac78473a4f8297a24eb7916f4
Author: Vicki Pfau <[email protected]>
Subject: Input: xbox_gip - Allow sending fragmented and ACME messages

This patch adds support for sending fragmented and ACME (reliable) messages in the xbox_gip driver. It sits on top of a reliable message transmission flow for messages that exceed the MTU and handles the required sequence and acknowledgment tracking.

Quoted 3 lines
drivers/input/joystick/gip/gip-core.c +0 -0

[ ... ]

drivers/input/joystick/gip/gip-core.c static int gip_send_raw_message(struct gip_attachment *attachment, · line 714

Quoted 6 lines
drivers/input/joystick/gip/gip-core.c +6 -0
+static int gip_send_next_fragment(struct gip_attachment *attachment,
+	struct gip_out_fragment *fragment)
+{
+	struct gip_interface *intf;
+	int next_bytes;
+	int flags = GIP_FLAG_FRAGMENT | fragment->flags | attachment->attachment_index;

[Severity: High]
Does this unconditionally force GIP_FLAG_FRAGMENT onto all retries? If an unfragmented reliable message times out, retrying it with this flag will cause gip_send_raw_message() to process it as a fragment. When processed as a fragment, it encodes the fragment_offset (which is 0) instead of the total_length, resulting in a corrupted header that the hardware may reject.

Quoted 2 lines
drivers/input/joystick/gip/gip-core.c +2 -0
+	int mtu;
+	int rc;

[ ... ]

Quoted 2 lines
drivers/input/joystick/gip/gip-core.c +0 -0
@@ -3144,17 +3179,17 @@ static void gip_shutdown(struct gip_device *gip)
 {

[ ... ]

Quoted 6 lines
drivers/input/joystick/gip/gip-core.c +0 -0
 	for (i = 0; i < MAX_ATTACHMENTS; i++) {
 		struct gip_attachment *attachment;
 
 		mutex_lock(&gip->attachment_lock);
 		attachment = gip->attachments[i];
 		mutex_unlock(&gip->attachment_lock);

drivers/input/joystick/gip/gip-core.c

Quoted 10 lines
drivers/input/joystick/gip/gip-core.c +0 -0
 
 		if (!attachment)
 			continue;
 
 		cancel_delayed_work_sync(&attachment->metadata_next);
 		cancel_delayed_work_sync(&attachment->in_fragment_timeout);
 		cancel_work_sync(&attachment->rumble_work);
 
 		guard(mutex)(&attachment->lock);
 		gip_reset_attachment(attachment);

[Severity: High]
This is a pre-existing issue, but does this teardown sequence leave a race window open for rumble_work to be rescheduled? The rumble_work is cancelled before gip_reset_attachment() unregisters the input device. A concurrent ioctl or ff-memless timer can call gip_play_effect() and reschedule the work while the device is still registered, leading to a Use-After-Free when the attachment memory is freed.

[Severity: High]
This isn't a bug introduced by this patch, but is there a risk of an AB-BA deadlock here during device reset?

When a hardware reconnect triggers gip_receive_message() and eventually gip_reset_attachment(), it acquires attachment->lock and calls input_unregister_device() via gip_free_devices(). The unregistration process synchronously removes sysfs groups, which blocks waiting for all active kernfs references to drain.

If a local user concurrently writes to the LED sysfs brightness attribute, gip_guide_led_set() acquires an active kernfs reference and then blocks attempting to acquire attachment->lock, completing the deadlock.

Quoted 6 lines
drivers/input/joystick/gip/gip-core.c +0 -0
 		gip_reset_metadata(attachment);
 	}
 }
 
 static void gip_disconnect(struct usb_interface *intf)
 {

drivers/input/joystick/gip/gip-core.c static void gip_shutdown(struct gip_device *gip)

Quoted 10 lines
drivers/input/joystick/gip/gip-core.c +1 -1
 	struct gip_device *gip = usb_get_intfdata(intf);
-	int i;
+	int i, j;
 
 	if (!gip)
 		return;
 
 	gip_shutdown(gip);
 
 	usb_kill_anchored_urbs(&gip->data.out_anchor);

[Severity: High]
Is this the correct teardown sequence? If gip_shutdown() cancels the send_fragment work before usb_kill_anchored_urbs() is called, active URBs might complete in the window between them. If an URB completes and triggers gip_urb_out(), it will reschedule the send_fragment work. After gip_disconnect() frees the device structures, the rescheduled work could execute and access freed memory. Should usb_kill_anchored_urbs() be called before gip_shutdown()?

[ ... ]

drivers/input/joystick/gip/gip-core.c static void gip_disconnect(struct usb_interface *intf) · line 3221

Quoted 6 lines
drivers/input/joystick/gip/gip-core.c +2 -0
@@ -3206,8 +3217,8 @@ static void gip_disconnect(struct usb_interface *intf)
 		if (!attachment)
 			continue;
 
+		for (j = 0; j < MAX_OUT_FRAGMENTS; j++)
+			cancel_delayed_work_sync(&attachment->out_fragments[i].timeout);

[Severity: Critical]
Does this inner loop mistakenly use the outer index i instead of j? Iterating up to MAX_OUT_FRAGMENTS using the outer attachment index i could lead to an out-of-bounds access when i is larger than the fragment array bounds. Additionally, it fails to cancel the actual delayed work items at indexes j, which could lead to a Use-After-Free if they execute after the attachment is freed.

Quoted 2 lines
drivers/input/joystick/gip/gip-core.c +0 -0
 		devm_kfree(to_gip_device(attachment), attachment->uniq);
 		devm_kfree(to_gip_device(attachment), attachment);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
author
#13 lore raw

PATCH v7 7/12 Input: xbox_gip - Add security implementation from xone

In reply to Vicki Pfau

This patch imports and adapts the security message implementation from the out-of-tree xone driver, which is licensed under the GPL 2.0. This message is necessary for most controllers that use wireless dongles. The implementation is largely unchanged, with minor changes being made to adapt it to the xbox_gip driver and renaming components as appropriate for the official terminology from the released spec.

---
 drivers/input/joystick/gip/Kconfig        |   3 +
 drivers/input/joystick/gip/Makefile       |   2 +-
 drivers/input/joystick/gip/gip-core.c     |  48 +-
 drivers/input/joystick/gip/gip-drivers.c  |   8 +
 drivers/input/joystick/gip/gip-security.c | 810 ++++++++++++++++++++++
 drivers/input/joystick/gip/gip.h          |  54 +-
 6 files changed, 900 insertions(+), 25 deletions(-)
 create mode 100644 drivers/input/joystick/gip/gip-security.c
drivers/input/joystick/gip/Kconfig +3 -0
index 3422bf84cb89..ad799a2df345 100644
@@ -5,6 +5,9 @@
 config JOYSTICK_XBOX_GIP
 	tristate "Xbox One/Series controller support"
 	depends on USB && USB_ARCH_HAS_HCD && LEDS_CLASS_MULTICOLOR
+	select CRYPTO_ECDH
+	select CRYPTO_LIB_SHA256
+	select CRYPTO_RSA
 	help
 	  Say Y here if you want to use Xbox One and Series controllers with your
 	  computer. Make sure to say Y to "Joystick support" (CONFIG_INPUT_JOYDEV)
drivers/input/joystick/gip/Makefile +1 -1
index d39f946db1ae..a5ad301a9063 100644
@@ -1,4 +1,4 @@
 # SPDX-License-Identifier: GPL-2.0-or-later
 obj-$(CONFIG_JOYSTICK_XBOX_GIP)	+= xbox-gip.o
 # Base driver
-xbox-gip-y := gip-core.o gip-drivers.o
+xbox-gip-y := gip-core.o gip-drivers.o gip-security.o
drivers/input/joystick/gip/gip-core.c +25 -23

96 lines not on this page · raw message

drivers/input/joystick/gip/gip-drivers.c +8 -0
index 2c2297b1fed8..74bc858e71cc 100644
@@ -81,6 +81,14 @@ const struct gip_driver gip_driver_gamepad = {
 		0xa3, 0x12, 0x7a, 0xf1, 0x97, 0xb5),
 
 	.quirks = (const struct gip_quirks[]) {
+		/* PowerA Xbox One Classic Controller */
+		{ GIP_VID_BDA, GIP_PID_BDA_XB1_CLASSIC, 0,
+			.quirks = GIP_QUIRK_SKIP_SECURITY },
+
+		/* PowerA Xbox One Fusion Pro */
+		{ GIP_VID_BDA, GIP_PID_BDA_XB1_FUSION_PRO, 0,
+			.quirks = GIP_QUIRK_SKIP_SECURITY },
+
 		/* Xbox One Controller (model 1573) */
 		{ GIP_VID_MICROSOFT, GIP_PID_XBOX_ONE_1573, 0,
 			.override_name = "Xbox One Controller" },
drivers/input/joystick/gip/gip-security.c new file +810 -0

810 lines not on this page · raw message

drivers/input/joystick/gip/gip.h +53 -1

117 lines not on this page · raw message

Signature · 1 line
2.54.0
#14 lore raw

Re: [PATCH v7 07/12] Input: xbox_gip - Add security implementation from xone

Thank you for your contribution! Sashiko AI review found 7 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 7 potential issue(s) to consider:

New issues:
- [High] Use-After-Free during device disconnect due to asynchronous cancellation of security workqueues.
- [High] Dynamic INIT_WORK() calls in gip_security_start_handshake() can corrupt workqueue state if re-entered.
- [High] Data race on shared security state (transcript, random_client, pubkey_client) due to lack of synchronization.
- [High] Heap variables embedded directly in a dynamically allocated struct are passed to scatterlists, risking DMA memory corruption.
- [Medium] Transcript hash incorrectly includes the message trailer, causing a protocol mismatch.
- [Medium] Sensitive session key is left on the kernel stack without explicit zeroization.

Pre-existing issues:
- [High] Index typo in gip_disconnect() causes out_fragments delayed works to not be cancelled, leading to a Use-After-Free. --

commit 90b08fdfc4b71ac21c6c33cfb71aa69cf4b03d4c
Author: Vicki Pfau <[email protected]>

Input: xbox_gip - Add security implementation from xone

This patch imports and adapts the security message implementation from the out-of-tree xone driver. This message is necessary for most controllers that use wireless dongles.

drivers/input/joystick/gip/gip-core.c

Quoted 4 lines
drivers/input/joystick/gip/gip-core.c +0 -0
index 1bfb559f5f7a2..ec21740bba50c 100644

[ ... ]

This is a pre-existing issue, but I noticed a potential use-after-free bug in the disconnect flow.

Looking at gip_disconnect() in drivers/input/joystick/gip/gip-core.c:

	mutex_lock(&gip->attachment_lock);
	for (i = 0; i < MAX_ATTACHMENTS; i++) {
		struct gip_attachment *attachment = gip->attachments[i];

		if (!attachment)
			continue;

		for (j = 0; j < MAX_OUT_FRAGMENTS; j++)
			cancel_delayed_work_sync(&attachment->out_fragments[i].timeout);
		devm_kfree(to_gip_device(attachment), attachment->uniq);
		devm_kfree(to_gip_device(attachment), attachment);
		gip->attachments[i] = NULL;
	}
	mutex_unlock(&gip->attachment_lock);

[Severity: High]
Does this code use the outer loop index i (attachment index) instead of the inner loop index j (fragment index)?

If i is used, timeouts for fragments other than the one at index i are never cancelled. The function then proceeds to free the attachment structure. If any of the un-cancelled delayed works execute later, they will access the freed attachment, leading to a use-after-free.

Quoted 7 lines
drivers/input/joystick/gip/gip-security.c new file +1 -0
new file mode 100644
index 0000000000000..1850850b60e67
@@ -0,0 +1,810 @@
+// SPDX-License-Identifier: GPL-2.0-or-later

[ ... ]

drivers/input/joystick/gip/gip-security.c line 311

Quoted 13 lines
drivers/input/joystick/gip/gip-security.c new file +13 -0
+static int gip_security_ecdh_get_secret(struct crypto_kpp *tfm, u8 *pubkey,
+	int pubkey_len, u8 *secret, int secret_len)
+{
+	struct kpp_request *req;
+	struct scatterlist src, dest;
+	DECLARE_CRYPTO_WAIT(wait);
+	int err;
+
+	req = kpp_request_alloc(tfm, GFP_KERNEL);
+	if (!req)
+		return -ENOMEM;
+
+	sg_init_one(&src, pubkey, pubkey_len);
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

[Severity: High]
Can passing these embedded, unaligned struct fields directly to sg_init_one() cause DMA memory corruption?

The fields security->pubkey_client2 and security->pms are embedded directly inside struct gip_security, which itself is embedded in
struct gip_attachment. If the underlying crypto backend uses hardware DMA, the DMA transfer will share a cacheline with adjacent fields in the gip_attachment structure. A simultaneous CPU access to these adjacent fields while the DMA is ongoing can corrupt either the DMA payload or the adjacent struct fields.

[ ... ]

Quoted 26 lines
drivers/input/joystick/gip/gip-security.c new file +26 -0
+static void gip_security_complete_handshake(struct work_struct *work)
+{
+	struct gip_security *security = container_of(work, typeof(*security), work_complete);
+	struct gip_attachment *attachment = container_of(security, struct gip_attachment, security);
+	struct gip_security_header_control hdr = {
+		.context = GIP_SECURITY_CTX_CONTROL,
+		.control = GIP_SECURITY_CTRL_COMPLETE,
+	};
+	u8 random[GIP_SECURITY_RANDOM_LEN * 2];
+	u8 key[GIP_SECURITY_SESSION_KEY_LEN];
+	int err;
+
+	guard(mutex)(&attachment->lock);
+	if (security->status != GIP_SECURITY_SENT)
+		return;
+
+	memcpy(random, security->random_host, sizeof(security->random_host));
+	memcpy(random + sizeof(security->random_host), security->random_client,
+		sizeof(security->random_client));
+
+	gip_security_compute_prf(
+		"EXPORTER DAWN data channel session key for controller",
+		security->master_secret, sizeof(security->master_secret),
+		random, sizeof(random), key, sizeof(key));
+
+	gip_dbg(security, "%s: key=%*phD\n", __func__, (int)sizeof(key), key);

drivers/input/joystick/gip/gip-security.c line 686

Quoted 10 lines
drivers/input/joystick/gip/gip-security.c new file +10 -0
+
+	err = gip_send_system_message(attachment, GIP_CMD_SECURITY,
+		0, &hdr, sizeof(hdr));
+	if (err) {
+		gip_err(security, "%s: send complete failed: %d\n", __func__, err);
+		return;
+	}
+
+	security->status = GIP_SECURITY_DONE;
+}
    ^^^

[Severity: Medium]
Should memzero_explicit() be used to wipe the sensitive session key material from the stack?

The symmetric session key key and the pre-master secret/random data random are generated into local stack arrays. After sending the completion message, the function returns without zeroing out this sensitive cryptographic material, which could be exposed if a subsequent kernel vulnerability allows reading uninitialized stack memory.

[ ... ]

Quoted 36 lines
drivers/input/joystick/gip/gip-security.c new file +36 -0
+int gip_security_handle_message(struct gip_security *security, const void *bytes, int num_bytes)
+{
+	const struct gip_security_header_handshake *handshake = bytes;
+	const struct gip_security_header_full *hdr;
+	int err;
+
+	if (num_bytes < sizeof(*handshake))
+		return -EINVAL;
+
+	if (security->status != GIP_SECURITY_SENT) {
+		gip_err(security, "%s: security message received when none expected: 0x%02x\n",
+			__func__, handshake->command);
+		return -EPROTO;
+	}
+
+	if (handshake->error)
+		return -EPROTO;
+
+	if (handshake->options & GIP_SECURITY_OPT_ACKNOWLEDGE) {
+		if (handshake->command == 0x01)
+			return gip_security_handle_acknowledge(security);
+
+		gip_err(security, "%s: handshake failed: 0x%02x\n",
+			__func__, handshake->command);
+		return -EPROTO;
+	}
+
+	if (num_bytes < sizeof(*hdr))
+		return -EINVAL;
+
+	hdr = bytes;
+	/* client uses v2 */
+	if (num_bytes < sizeof(*hdr) || handshake->command != hdr->data.command) {
+		/* reset transcript hash and restart handshake */
+		gip_dbg(security, "%s: protocol upgrade\n", __func__);
+		sha256_init(&security->transcript);

drivers/input/joystick/gip/gip-security.c line 756

Quoted 10 lines
drivers/input/joystick/gip/gip-security.c new file +10 -0
+		return gip_security2_send_hello(security);
+	}
+
+	err = gip_security_dispatch_message(security, hdr->data.command,
+		bytes + sizeof(*hdr), num_bytes - sizeof(*hdr));
+	if (err)
+		return err;
+
+	sha256_update(&security->transcript, bytes + sizeof(hdr->handshake),
+		num_bytes - sizeof(hdr->handshake));
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

[Severity: High]
Is there a data race on the shared security state (transcript, random_client, pubkey_client) due to lack of synchronization?

Incoming messages are processed by gip_receive_work, which calls gip_security_handle_message() without acquiring attachment->lock. This function modifies shared state such as security->transcript and security->pubkey_client.

Concurrently, asynchronous work items (like gip_security_exchange_rsa) acquire attachment->lock and call gip_security_send_message(), which also updates the transcript hash. Since one side does not hold the lock, these threads can race and corrupt the internal state of the SHA256 context or copy torn data.

[Severity: Medium]
Does this transcript hash incorrectly include the message trailer?

The transcript hash is updated using num_bytes - sizeof(hdr->handshake). If the received packet includes the 8-byte trailer, num_bytes encompasses it, and the trailer gets hashed. However, the sender (gip_security_send_message()) specifically excludes the trailer from the hash. This discrepancy causes a transcript mismatch during the Finished step.

drivers/input/joystick/gip/gip-security.c line 768

Quoted 12 lines
drivers/input/joystick/gip/gip-security.c new file +12 -0
+
+	return 0;
+}
+
+void gip_security_release(struct gip_security *security)
+{
+	if (security->status < GIP_SECURITY_SENT)
+		return;
+
+	cancel_work(&security->work_exchange_rsa);
+	cancel_work(&security->work_exchange_ecdh);
+	cancel_work(&security->work_complete);
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

[Severity: High]
Is it safe to use the non-blocking cancel_work() instead of cancel_work_sync() here?

During device disconnect, gip_disconnect() calls gip_shutdown() which calls gip_security_release(). This uses the non-blocking cancel_work() to cancel the security work items.

gip_disconnect() then explicitly frees the attachment structure using devm_kfree(). If a security work item is actively executing on another CPU, it will continue running and attempt to acquire the freed attachment->lock or access other freed fields (such as inside gip_security_exchange_rsa()), resulting in a use-after-free.

Quoted 7 lines
drivers/input/joystick/gip/gip-security.c new file +7 -0
+
+	memzero_explicit(&security->transcript, sizeof(security->transcript));
+	memzero_explicit(&security->pms, sizeof(security->pms));
+	memzero_explicit(&security->master_secret, sizeof(security->master_secret));
+
+	security->status = GIP_SECURITY_PENDING;
+}

drivers/input/joystick/gip/gip-security.c line 785

Quoted 10 lines
drivers/input/joystick/gip/gip-security.c new file +10 -0
+
+int gip_security_start_handshake(struct gip_security *security)
+{
+	int err;
+
+	sha256_init(&security->transcript);
+
+	INIT_WORK(&security->work_exchange_rsa, gip_security_exchange_rsa);
+	INIT_WORK(&security->work_exchange_ecdh, gip_security2_exchange_ecdh);
+	INIT_WORK(&security->work_complete, gip_security_complete_handshake);
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

[Severity: High]
Can dynamically re-initializing these work items corrupt the workqueue state if they are re-entered?

INIT_WORK() is dynamically invoked every time gip_security_start_handshake() runs. If the handshake fails or is reset (e.g., via HELLO_DEVICE), gip_security_release() cancels the work asynchronously.

A subsequent STATUS_DEVICE message will call gip_security_start_handshake() again. If the previous work item is still executing (because cancel_work() is asynchronous), calling INIT_WORK() will overwrite its internal work_data_bits and list pointers, leading to workqueue corruption.

Quoted 8 lines
drivers/input/joystick/gip/gip-security.c new file +8 -0
+
+	err = gip_security_send_hello(security);
+	if (err < 0)
+		return err;
+
+	security->status = GIP_SECURITY_SENT;
+	return 0;
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
author
#15 lore raw

PATCH v7 8/12 Input: xbox_gip - Add arcade stick support

In reply to Vicki Pfau

This adds support for the arcade stick device type. Currently I'm only aware of one Xbox controller that uses this device type, the Razer Atrox, so testing coverage is limited.

---
 drivers/input/joystick/gip/Makefile           |   2 +
 drivers/input/joystick/gip/gip-arcade-stick.c | 173 ++++++++++++++++++
 drivers/input/joystick/gip/gip-core.c         |   6 +-
 drivers/input/joystick/gip/gip.h              |   4 +-
 4 files changed, 181 insertions(+), 4 deletions(-)
 create mode 100644 drivers/input/joystick/gip/gip-arcade-stick.c
drivers/input/joystick/gip/Makefile +2 -0
index a5ad301a9063..9ed59caec4d9 100644
@@ -2,3 +2,5 @@
 obj-$(CONFIG_JOYSTICK_XBOX_GIP)	+= xbox-gip.o
 # Base driver
 xbox-gip-y := gip-core.o gip-drivers.o gip-security.o
+# Additional device support
+xbox-gip-y += gip-arcade-stick.o
drivers/input/joystick/gip/gip-arcade-stick.c new file +173 -0

173 lines not on this page · raw message

drivers/input/joystick/gip/gip-core.c +4 -2
index ec21740bba50..ff8844b4e293 100644
@@ -10,7 +10,8 @@
  * - Raw character device
  * - Wheel support
  * - Flight stick support
- * - Arcade stick support
+ * - More arcade stick testing
+ * - Arcade stick extra buttons
  * - Split into driver-per-attachment GIP-as-a-bus approach drivers
  *
  * This driver is based on the Microsoft GIP spec at:
@@ -331,6 +332,7 @@ struct gip_direct_motor {
 static const struct gip_driver *base_drivers[] = {
 	&gip_driver_navigation,
 	&gip_driver_gamepad,
+	&gip_driver_arcade_stick,
 	NULL /* Sentinel */
 };
 
@@ -1598,7 +1600,7 @@ static int gip_handle_command_raw_report(struct gip_attachment *attachment,
 	return 0;
 }
 
-static int gip_setup_input_device(struct gip_attachment *attachment)
+int gip_setup_input_device(struct gip_attachment *attachment)
 {
 	struct input_dev *input;
 	int rc;
drivers/input/joystick/gip/gip.h +2 -2
index 5e8daf651317..77e3fa8b2a2c 100644
@@ -413,6 +413,8 @@ static inline struct device *gip_security_dev(struct gip_security *security)
 	return gip_attachment_dev(container_of(security, struct gip_attachment, security));
 }
 
+int gip_setup_input_device(struct gip_attachment *attachment);
+
 bool gip_supports_vendor_message(struct gip_attachment *attachment, uint8_t command, bool upstream);
 
 int gip_send_system_message(struct gip_attachment *attachment,
@@ -428,6 +430,4 @@ void gip_security_release(struct gip_security *security);
 extern const struct gip_driver gip_driver_navigation;
 extern const struct gip_driver gip_driver_gamepad;
 extern const struct gip_driver gip_driver_arcade_stick;
-extern const struct gip_driver gip_driver_wheel;
-extern const struct gip_driver gip_driver_flight_stick;
 #endif
Signature · 1 line
2.54.0
#16 lore raw

Re: [PATCH v7 08/12] Input: xbox_gip - Add arcade stick support

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Delegating to the base report handler before validating the report length causes unsynchronized…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Delegating to the base report handler before validating the report length causes unsynchronized partial events to be injected into the input core. --

commit 40e27212434b70f4e87708396c3c1b8a00c35e55
Author: Vicki Pfau <[email protected]>

Input: xbox_gip - Add arcade stick support

This commit adds support for the arcade stick device type to the Xbox GIP driver.

Quoted 5 lines
drivers/input/joystick/gip/gip-arcade-stick.c new file +0 -0
new file mode 100644
index 0000000000000..11ededfab8555

[ ... ]

Quoted 7 lines
drivers/input/joystick/gip/gip-arcade-stick.c new file +7 -0
+static int gip_handle_arcade_stick_report(struct gip_attachment *attachment,
+	struct input_dev *input, const uint8_t *bytes, int num_bytes)
+{
+	struct gip_arcade_stick_info *info = attachment->driver_data;
+	int rc;
+
+	if (!info)

drivers/input/joystick/gip/gip-arcade-stick.c line 111

Quoted 10 lines
drivers/input/joystick/gip/gip-arcade-stick.c new file +10 -0
+		return -ENODEV;
+
+	rc = gip_driver_navigation.handle_input_report(attachment, input, bytes, num_bytes);
+	if (rc < 0)
+		return rc;
+
+	if (num_bytes < 6) {
+		gip_dbg(attachment, "Discarding too-short input report\n");
+		return -EINVAL;
+	}

[Severity: High]
Can this sequence leave the userspace input state out of sync?

If a device sends a short input report (between 2 and 5 bytes inclusive), gip_driver_navigation.handle_input_report() will process the events since it only requires num_bytes >= 2. However, this function then checks for num_bytes < 6 and returns -EINVAL.

When the caller sees this error, it will return immediately without calling input_sync(). This allows unsynchronized partial events to be injected into the input core, which could lead to inconsistent input state in userspace.

Should the num_bytes < 6 check be performed before delegating to the base report handler?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
author
#17 lore raw

PATCH v7 9/12 Input: xbox_gip - Add support for PDP guitar controllers

In reply to Vicki Pfau

This patch adds support for the PDP guitar controllers, namely the Fender Jaguar and RiffMaster models. These use mostly the same protocol, but the RiffMaster appears t use a slightly newer variant.

---
 drivers/input/joystick/gip/Makefile         |   1 +
 drivers/input/joystick/gip/gip-core.c       |   1 +
 drivers/input/joystick/gip/gip-pdp-jaguar.c | 129 ++++++++++++++++++++
 drivers/input/joystick/gip/gip.h            |   2 +
 4 files changed, 133 insertions(+)
 create mode 100644 drivers/input/joystick/gip/gip-pdp-jaguar.c
drivers/input/joystick/gip/Makefile +1 -0
index 9ed59caec4d9..62c016d6c11e 100644
@@ -4,3 +4,4 @@ obj-$(CONFIG_JOYSTICK_XBOX_GIP)	+= xbox-gip.o
 xbox-gip-y := gip-core.o gip-drivers.o gip-security.o
 # Additional device support
 xbox-gip-y += gip-arcade-stick.o
+xbox-gip-y += gip-pdp-jaguar.o
drivers/input/joystick/gip/gip-core.c +1 -0
index ff8844b4e293..720b9a075ed3 100644
@@ -333,6 +333,7 @@ static const struct gip_driver *base_drivers[] = {
 	&gip_driver_navigation,
 	&gip_driver_gamepad,
 	&gip_driver_arcade_stick,
+	&gip_driver_pdp_jaguar,
 	NULL /* Sentinel */
 };
 
drivers/input/joystick/gip/gip-pdp-jaguar.c new file +129 -0

129 lines not on this page · raw message

drivers/input/joystick/gip/gip.h +2 -0
index 77e3fa8b2a2c..f9b2e08ea60f 100644
@@ -41,6 +41,7 @@
 #define GIP_PID_XBOX_WIRELESS			0x0b12
 
 #define GIP_PID_PDP_ROCK_CANDY	0x0246
+#define GIP_PID_PDP_RIFFMASTER	0x0248
 
 #define GIP_PID_BDA_XB1_CLASSIC		0x581a
 #define GIP_PID_BDA_XB1_FUSION_PRO	0x591a
@@ -430,4 +431,5 @@ void gip_security_release(struct gip_security *security);
 extern const struct gip_driver gip_driver_navigation;
 extern const struct gip_driver gip_driver_gamepad;
 extern const struct gip_driver gip_driver_arcade_stick;
+extern const struct gip_driver gip_driver_pdp_jaguar;
 #endif
Signature · 1 line
2.54.0
#18 lore raw

Re: [PATCH v7 09/12] Input: xbox_gip - Add support for PDP guitar controllers

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Payload-dependent format parsing causes inconsistent button mapping and aliasing on the…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Payload-dependent format parsing causes inconsistent button mapping and aliasing on the RiffMaster. --

commit f157752e23d4ee774cfa5a7ee1c93ecfd2cc8d44
Author: Vicki Pfau <[email protected]>

Input: xbox_gip - Add support for PDP guitar controllers

This commit adds support for the PDP guitar controllers (Fender Jaguar and RiffMaster models) to the xbox_gip driver. It introduces custom input mapping capabilities and specific report parsing for the two variants of the device.

Quoted 5 lines
drivers/input/joystick/gip/gip-pdp-jaguar.c new file +0 -0
new file mode 100644
index 0000000000000..ec0e9d811d125

[ ... ]

Quoted 3 lines
drivers/input/joystick/gip/gip-pdp-jaguar.c new file +3 -0
+static int gip_handle_pdp_jaguar_report(struct gip_attachment *attachment,
+	struct input_dev *input, const uint8_t *bytes, int num_bytes)
+{

[ ... ]

drivers/input/joystick/gip/gip-pdp-jaguar.c line 67

Quoted 1 line
drivers/input/joystick/gip/gip-pdp-jaguar.c new file +1 -0
+	if (num_bytes >= 7 && (bytes[5] || bytes[6])) {

[Severity: High]
Does this payload-dependent condition break the RiffMaster layout when all frets are released?

If a RiffMaster user releases all neck frets, bytes[5] and bytes[6] become 0. This causes the condition to fail, dropping the driver into the legacy Jaguar format in the else block below.

Quoted 3 lines
drivers/input/joystick/gip/gip-pdp-jaguar.c new file +3 -0
+		/* Newer report version on the RiffMaster */
+		input_report_key(input, BTN_TRIGGER_HAPPY1, bytes[5] & BIT(0));
+		input_report_key(input, BTN_TRIGGER_HAPPY2, bytes[5] & BIT(1));

[ ... ]

drivers/input/joystick/gip/gip-pdp-jaguar.c line 81

Quoted 4 lines
drivers/input/joystick/gip/gip-pdp-jaguar.c new file +4 -0
+		input_report_key(input, BTN_TRIGGER_HAPPY9, bytes[6] & BIT(3));
+		input_report_key(input, BTN_TRIGGER_HAPPY10, bytes[6] & BIT(4));
+	} else {
+		lower = bytes[1] & BIT(6);

[Severity: High]
When falling back to this legacy path for the RiffMaster, doesn't it cause unintended button aliasing?

On the RiffMaster, bytes[1] & BIT(6) is mapped to BTN_THUMBR.

If the driver falls back to this path because all frets were temporarily released, and the user happens to be holding the right stick button (or other standard buttons located in bytes[0]), won't those inputs falsely register as fret presses (BTN_TRIGGER_HAPPY1 through 10)?

Could this layout format decision use the static hardware quirk (attachment->quirks & GIP_QUIRK_PDP_HAS_RIGHT_STICK) instead of relying on transient payload data to distinguish between the controller variants?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
author
#19 lore raw

PATCH v7 10/12 Input: Add ABS_CLUTCH, HANDBRAKE, and SHIFTER

In reply to Vicki Pfau

Add new absolute axes for racing game controllers

---
 drivers/hid/hid-debug.c                | 16 +++++++++-------
 include/uapi/linux/input-event-codes.h |  3 +++
 2 files changed, 12 insertions(+), 7 deletions(-)
drivers/hid/hid-debug.c +9 -7
index f44e6e708404..7a1b56311e9b 100644
@@ -3511,13 +3511,15 @@ static const char *absolutes[ABS_CNT] = {
 	[ABS_RY] = "Ry",		[ABS_RZ] = "Rz",
 	[ABS_THROTTLE] = "Throttle",	[ABS_RUDDER] = "Rudder",
 	[ABS_WHEEL] = "Wheel",		[ABS_GAS] = "Gas",
-	[ABS_BRAKE] = "Brake",		[ABS_HAT0X] = "Hat0X",
-	[ABS_HAT0Y] = "Hat0Y",		[ABS_HAT1X] = "Hat1X",
-	[ABS_HAT1Y] = "Hat1Y",		[ABS_HAT2X] = "Hat2X",
-	[ABS_HAT2Y] = "Hat2Y",		[ABS_HAT3X] = "Hat3X",
-	[ABS_HAT3Y] = "Hat 3Y",		[ABS_PRESSURE] = "Pressure",
-	[ABS_DISTANCE] = "Distance",	[ABS_TILT_X] = "XTilt",
-	[ABS_TILT_Y] = "YTilt",		[ABS_TOOL_WIDTH] = "ToolWidth",
+	[ABS_BRAKE] = "Brake",		[ABS_CLUTCH] = "Clutch",
+	[ABS_HANDBRAKE] = "Handbrake",	[ABS_SHIFTER] = "Shifter",
+	[ABS_HAT0X] = "Hat0X",		[ABS_HAT0Y] = "Hat0Y",
+	[ABS_HAT1X] = "Hat1X",		[ABS_HAT1Y] = "Hat1Y",
+	[ABS_HAT2X] = "Hat2X",		[ABS_HAT2Y] = "Hat2Y",
+	[ABS_HAT3X] = "Hat3X",		[ABS_HAT3Y] = "Hat3Y",
+	[ABS_PRESSURE] = "Pressure",	[ABS_DISTANCE] = "Distance",
+	[ABS_TILT_X] = "XTilt",		[ABS_TILT_Y] = "YTilt",
+	[ABS_TOOL_WIDTH] = "ToolWidth",
 	[ABS_VOLUME] = "Volume",	[ABS_PROFILE] = "Profile",
 	[ABS_SND_PROFILE] = "SoundProfile",
 	[ABS_MISC] = "Misc",
include/uapi/linux/input-event-codes.h +3 -0
index 3528168f7c6d..5c881ed44177 100644
@@ -879,6 +879,9 @@
 #define ABS_WHEEL		0x08
 #define ABS_GAS			0x09
 #define ABS_BRAKE		0x0a
+#define ABS_CLUTCH		0x0b
+#define ABS_HANDBRAKE		0x0c
+#define ABS_SHIFTER		0x0d
 #define ABS_HAT0X		0x10
 #define ABS_HAT0Y		0x11
 #define ABS_HAT1X		0x12
Signature · 1 line
2.54.0
#20 lore raw

Re: [PATCH v7 10/12] Input: Add ABS_CLUTCH, HANDBRAKE, and SHIFTER

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] The loop adjusting fuzz and deadzone for racing wheel axes in hid-universal-pidff.c skips the…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The loop adjusting fuzz and deadzone for racing wheel axes in hid-universal-pidff.c skips the newly added ABS_CLUTCH, ABS_HANDBRAKE, and ABS_SHIFTER. --

commit 95df0be5d5d52e727b1a90b0fb81bb2a045e5743
Author: Vicki Pfau <[email protected]>

Input: Add ABS_CLUTCH, HANDBRAKE, and SHIFTER

This commit adds new absolute axes (ABS_CLUTCH, ABS_HANDBRAKE, and ABS_SHIFTER) for racing game controllers.

include/uapi/linux/input-event-codes.h line 884

Quoted 11 lines
include/uapi/linux/input-event-codes.h +3 -0
index 3528168f7c6d7..5c881ed441771 100644
@@ -879,6 +879,9 @@
 #define ABS_WHEEL		0x08
 #define ABS_GAS			0x09
 #define ABS_BRAKE		0x0a
+#define ABS_CLUTCH		0x0b
+#define ABS_HANDBRAKE		0x0c
+#define ABS_SHIFTER		0x0d

[Severity: Medium]
Does this leave out the newly added simulation axes from deadzone and fuzz adjustment in hid-universal-pidff.c?

Looking at universal_pidff_input_configured() in drivers/hid/hid-universal-pidff.c, the code loops up to ABS_BRAKE to adjust racing wheel axes:

drivers/hid/hid-universal-pidff.c:universal_pidff_input_configured() {
    ...
	for (axis = ABS_X; axis <= ABS_BRAKE; axis++) {
		if (!test_bit(axis, input->absbit))
			continue;
    ...
}

Because this loop bounded by ABS_BRAKE implicitly assumes it covers the contiguous block of all analogous simulation axes, adding ABS_CLUTCH, ABS_HANDBRAKE, and ABS_SHIFTER after it means they will be skipped.

Could this result in inconsistent default axis behaviors for the new clutch and handbrake axes, as they will not have their fuzz and deadzone parameters adjusted to match other racing wheel axes like ABS_GAS and ABS_BRAKE?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
author
#21 lore raw

PATCH v7 11/12 HID: Map more automobile simulation inputs

In reply to Vicki Pfau

The HID usage tables section 5.3 specify clutch and shifter values that had previously been ignored. As the ABS_CLUTCH and ABS_SHIFTER bits now exist, we should use them appropriately.

---
 drivers/hid/hid-input.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/hid/hid-input.c +2 -0
index 3487600cadb4..6ade969412c6 100644
@@ -828,6 +828,8 @@ static void hidinput_configure_usage(struct hid_input *hidinput, struct hid_fiel
 		case 0xbb: map_abs(ABS_THROTTLE); break;
 		case 0xc4: map_abs(ABS_GAS);      break;
 		case 0xc5: map_abs(ABS_BRAKE);    break;
+		case 0xc6: map_abs(ABS_CLUTCH);   break;
+		case 0xc7: map_abs(ABS_SHIFTER);  break;
 		case 0xc8: map_abs(ABS_WHEEL);    break;
 		default:   goto ignore;
 		}
Signature · 1 line
2.54.0
#22 lore raw

Re: [PATCH v7 11/12] HID: Map more automobile simulation inputs

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] hid-universal-pidff: Loop boundary hardcodes ABS_BRAKE, missing the newly added ABS_CLUTCH and…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] hid-universal-pidff: Loop boundary hardcodes ABS_BRAKE, missing the newly added ABS_CLUTCH and ABS_SHIFTER axes. --

commit 5a43f61b9ef2583fea1214cddf577437072e1c07
Author: Vicki Pfau <[email protected]>

HID: Map more automobile simulation inputs

This commit maps the previously ignored HID usages for clutch and shifter to ABS_CLUTCH and ABS_SHIFTER in hidinput_configure_usage.

drivers/hid/hid-input.c static void hidinput_configure_usage(struct hid_input *hidinput, struct hid_fiel · line 832

Quoted 10 lines
drivers/hid/hid-input.c +2 -0
index 3487600cadb42..6ade969412c67 100644
@@ -828,6 +828,8 @@ static void hidinput_configure_usage(struct hid_input *hidinput, struct hid_fiel
 		case 0xbb: map_abs(ABS_THROTTLE); break;
 		case 0xc4: map_abs(ABS_GAS);      break;
 		case 0xc5: map_abs(ABS_BRAKE);    break;
+		case 0xc6: map_abs(ABS_CLUTCH);   break;
+		case 0xc7: map_abs(ABS_SHIFTER);  break;

[Severity: Medium]
Does this change unintentionally leave the new simulation axes with large default deadzones on devices handled by the hid-universal-pidff driver?

In drivers/hid/hid-universal-pidff.c, the universal_pidff_input_configured function explicitly attempts to clear default deadzones for simulation axes to ensure high precision. However, it relies on a hardcoded loop boundary:

for (axis = ABS_X; axis <= ABS_BRAKE; axis++) {
        ...
}

Since ABS_CLUTCH and ABS_SHIFTER are numerically greater than ABS_BRAKE, the loop will miss these newly mapped axes. This introduces an unwanted default deadzone of 1/16th of their range on the clutch and shifter axes, which might degrade the simulation experience for users of high-end sim racing wheels.

Should the loop boundary in universal_pidff_input_configured be updated to include these new axes?

Quoted 3 lines
drivers/hid/hid-input.c +0 -0
 		case 0xc8: map_abs(ABS_WHEEL);    break;
 		default:   goto ignore;
 		}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
author
#23 lore raw

PATCH v7 12/12 Input: xbox_gip - Add wheel support

In reply to Vicki Pfau

This adds preliminary support for racing wheel support in xbox_gip, exposing them mapped to the newly added axes.

---
 drivers/input/joystick/gip/Makefile      |   1 +
 drivers/input/joystick/gip/gip-core.c    |   4 +-
 drivers/input/joystick/gip/gip-drivers.c |  10 +
 drivers/input/joystick/gip/gip-wheel.c   | 351 +++++++++++++++++++++++
 drivers/input/joystick/gip/gip.h         |   6 +
 5 files changed, 371 insertions(+), 1 deletion(-)
 create mode 100644 drivers/input/joystick/gip/gip-wheel.c
drivers/input/joystick/gip/Makefile +1 -0
index 62c016d6c11e..7d4209eb32c3 100644
@@ -5,3 +5,4 @@ xbox-gip-y := gip-core.o gip-drivers.o gip-security.o
 # Additional device support
 xbox-gip-y += gip-arcade-stick.o
 xbox-gip-y += gip-pdp-jaguar.o
+xbox-gip-y += gip-wheel.o
drivers/input/joystick/gip/gip-core.c +3 -1
index 720b9a075ed3..42e191f0aef2 100644
@@ -8,7 +8,7 @@
  * - Audio device support
  * - Event logging
  * - Raw character device
- * - Wheel support
+ * - Wheel force feedback
  * - Flight stick support
  * - More arcade stick testing
  * - Arcade stick extra buttons
@@ -334,6 +334,8 @@ static const struct gip_driver *base_drivers[] = {
 	&gip_driver_gamepad,
 	&gip_driver_arcade_stick,
 	&gip_driver_pdp_jaguar,
+	&gip_driver_trueforce_wheel,
+	&gip_driver_wheel,
 	NULL /* Sentinel */
 };
 
drivers/input/joystick/gip/gip-drivers.c +10 -0
index 74bc858e71cc..7ba11b19c8ee 100644
@@ -142,6 +142,11 @@ static int gip_setup_navigation_input(struct gip_attachment *attachment, struct
 	input_set_capability(input, EV_KEY, BTN_TR);
 	input_set_capability(input, EV_KEY, BTN_TL);
 
+	if (attachment->quirks & GIP_QUIRK_FORCE_GAMEPAD_SB) {
+		input_set_capability(input, EV_KEY, BTN_THUMBR);
+		input_set_capability(input, EV_KEY, BTN_THUMBL);
+	}
+
 	attachment->dpad_as_buttons = dpad_as_buttons;
 	if (attachment->dpad_as_buttons) {
 		input_set_capability(input, EV_KEY, BTN_DPAD_UP);
@@ -193,6 +198,11 @@ static int gip_handle_navigation_report(struct gip_attachment *attachment,
 		input_report_key(input, BTN_TR, bytes[1] & BIT(5));
 	}
 
+	if (attachment->quirks & GIP_QUIRK_FORCE_GAMEPAD_SB) {
+		input_report_key(input, BTN_THUMBL, bytes[1] & BIT(6));
+		input_report_key(input, BTN_THUMBR, bytes[1] & BIT(7));
+	}
+
 	return 0;
 }
 
drivers/input/joystick/gip/gip-wheel.c new file +351 -0

351 lines not on this page · raw message

drivers/input/joystick/gip/gip.h +6 -0
index f9b2e08ea60f..eaf11059efd9 100644
@@ -28,10 +28,13 @@
 #define MAX_OUT_MESSAGES 8
 #define MAX_OUT_FRAGMENTS 2
 
+#define GIP_VID_THRUSTMASTER	0x044f
 #define GIP_VID_MICROSOFT	0x045e
 #define GIP_VID_PDP		0x0e6f
 #define GIP_VID_BDA		0x24c6
 
+#define GIP_PID_THRUSTMASTER_T128X	0xb69c
+
 #define GIP_PID_XBOX_ONE_1573			0x02d1
 #define GIP_PID_XBOX_ONE_1697			0x02dd
 #define GIP_PID_XBOX_ELITE			0x02e3
@@ -50,6 +53,7 @@
 #define GIP_QUIRK_NO_IMPULSE_VIBRATION	BIT(1)
 #define GIP_QUIRK_SWAP_LB_RB		BIT(2)
 #define GIP_QUIRK_SKIP_SECURITY		BIT(3)
+#define GIP_QUIRK_FORCE_GAMEPAD_SB	BIT(4)
 /*
  * Driver-specific quirks should start from 31 and go downwards to avoid
  * conflicts with newly-added core quirks
@@ -432,4 +436,6 @@ extern const struct gip_driver gip_driver_navigation;
 extern const struct gip_driver gip_driver_gamepad;
 extern const struct gip_driver gip_driver_arcade_stick;
 extern const struct gip_driver gip_driver_pdp_jaguar;
+extern const struct gip_driver gip_driver_wheel;
+extern const struct gip_driver gip_driver_trueforce_wheel;
 #endif
Signature · 1 line
2.54.0
#24 lore raw

Re: [PATCH v7 12/12] Input: xbox_gip - Add wheel support

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:

New issues:
- [Medium] Late length checks in input report handlers leave events unsynchronized on truncated packets.
- [Medium] Incorrect modulo arithmetic for relative dial causes erratic reverse jumps.
- [Medium] Static configuration of max_angle with 0 precision causes integer underflow, bypassing validation.

Pre-existing issues:
- [High] AB-BA deadlock between LED sysfs operations and device unregistration. --

commit 533e8fbcd84078cc304b29f07232970fb0a6e7d7
Author: Vicki Pfau <[email protected]>

Input: xbox_gip - Add wheel support

This adds preliminary support for racing wheel support in xbox_gip, exposing them mapped to the newly added axes.

Quoted 4 lines
drivers/input/joystick/gip/gip-core.c +0 -0
index 720b9a075ed3a..42e191f0aef24 100644

[ ... ]

drivers/input/joystick/gip/gip-core.c static const struct gip_driver *base_drivers[] = { · line 338

Quoted 6 lines
drivers/input/joystick/gip/gip-core.c +2 -0
@@ -334,6 +334,8 @@ static const struct gip_driver *base_drivers[] = {
 	&gip_driver_gamepad,
 	&gip_driver_arcade_stick,
 	&gip_driver_pdp_jaguar,
+	&gip_driver_trueforce_wheel,
+	&gip_driver_wheel,

[Severity: High]
This is a pre-existing issue, but does adding these devices expose them to the AB-BA deadlock between LED sysfs operations and device unregistration?

During device disconnect, gip_reset_attachment() acquires attachment->lock and calls gip_free_devices(), which manually calls input_unregister_device(). If there are no open evdev handles, this synchronously tears down the device and its devres resources, invoking led_classdev_unregister(). This function blocks in kernfs_drain waiting for active sysfs operations to complete. Concurrently, a sysfs write to the LED brightness holds the kernfs active reference and calls gip_guide_led_set(), which blocks trying to acquire attachment->lock.

Quoted 5 lines
drivers/input/joystick/gip/gip-wheel.c new file +0 -0
new file mode 100644
index 0000000000000..bd281b295eac1

[ ... ]

Quoted 5 lines
drivers/input/joystick/gip/gip-wheel.c new file +5 -0
+static int gip_handle_wheel_report(struct gip_attachment *attachment,
+	struct input_dev *input, const uint8_t *bytes, int num_bytes)
+{
+	uint8_t connections;
+	struct gip_wheel_info *info = attachment->driver_data;

drivers/input/joystick/gip/gip-wheel.c line 168

Quoted 10 lines
drivers/input/joystick/gip/gip-wheel.c new file +10 -0
+	int rc = gip_driver_navigation.handle_input_report(attachment, input, bytes, num_bytes);
+
+	if (rc < 0)
+		return rc;
+
+	if (!info)
+		return -ENODEV;
+
+	if (num_bytes < 17)
+		return -EINVAL;

[Severity: Medium]
Will this length check leave partial events unsynchronized if the packet is truncated?

If num_bytes is less than 17, this returns -EINVAL after gip_driver_navigation.handle_input_report() has already reported events via input_report_key(). The outer function will then skip input_sync(), leaving the reported events stuck in the input core's buffers until the next sync.

[ ... ]

drivers/input/joystick/gip/gip-wheel.c line 214

Quoted 12 lines
drivers/input/joystick/gip/gip-wheel.c new file +12 -0
+static int gip_handle_wheel_ll_static_configuration(struct gip_attachment *attachment,
+	const struct gip_header *header, const uint8_t *bytes, int num_bytes)
+{
+	struct gip_wheel_info *info = attachment->driver_data;
+
+	if (!info)
+		return -ENODEV;
+
+	if (num_bytes < 11)
+		return -EINVAL;
+
+	info->max_angle = BIT(min(bytes[0], 16)) / 2 - 1;

[Severity: Medium]
Could this formula cause an integer underflow if bytes[0] is 0?

If a 0-bit precision configuration is received, BIT(0) is 1, and 1 / 2 - 1 evaluates to -1, which underflows the uint16_t info->max_angle to 65535. This could bypass validation checks and assign corrupted bounds to ABS_WHEEL.

[ ... ]

drivers/input/joystick/gip/gip-wheel.c line 314

Quoted 12 lines
drivers/input/joystick/gip/gip-wheel.c new file +12 -0
+static int gip_handle_trueforce_wheel_report(struct gip_attachment *attachment,
+	struct input_dev *input, const uint8_t *bytes, int num_bytes)
+{
+	int rc = gip_driver_wheel.handle_input_report(attachment, input, bytes, num_bytes);
+	struct gip_trueforce_wheel_state *state = attachment->driver_data;
+	int dial;
+
+	if (rc < 0)
+		return rc;
+
+	if (num_bytes < 18)
+		return -EINVAL;

[Severity: Medium]
Will this length check leave partial events unsynchronized if the packet is truncated?

Similar to the check in gip_handle_wheel_report(), this returns -EINVAL after the base wheel handler has already injected state changes, causing the core loop to abort before calling input_sync().

[ ... ]

drivers/input/joystick/gip/gip-wheel.c line 330

Quoted 8 lines
drivers/input/joystick/gip/gip-wheel.c new file +8 -0
+	/* Dial states only change one at a time, so we can easily check for wraparound */
+	if (dial == 0 && state->dial == 7)
+		input_report_rel(input, REL_DIAL, -1);
+	else if (dial == 7 && state->dial == 0)
+		input_report_rel(input, REL_DIAL, 1);
+	else if (state->dial >= 0)
+		input_report_rel(input, REL_DIAL,
+			state->dial - dial);

[Severity: Medium]
Could this cause erratic relative dial jumps if the dial skips a step?

If the dial moves rapidly across the 0-7 boundary and skips a step (e.g., from previous state 6 to current dial 0), the hardcoded wraparound checks fail. It then falls back to state->dial - dial (6 - 0 = 6), reporting +6 instead of the actual shortest distance of -2.

Should standard modulo arithmetic be used here instead?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
#25 lore raw
In reply to Vicki Pfau

Hi Dmitry,

Sorry to bother but this patch series has been floating in mail list for a long time.. I think your review is needed here?

Best regards,
Shengyu

Quoted 82 lines · Vicki Pfau

This is a new version of the previously submitted xbox-gip series.

This introduces a new driver for the Xbox One/Series controller protocol, officially known as the Gaming Input Protocol, or GIP for short.

Microsoft released documentation on (some of) GIP in late 2024, upon which this driver is based. Though the documentation was incomplete, it still provided enough information to warrant a clean start over the previous, incomplete implementation.

This driver is already at feature parity with the GIP support in xpad, along with several more enhancements:

- Proper support for parsing message length and fragmented messages
- Metadata parsing, allowing for auto-detection on various parameters, including the presence and location in the message of the share button, as well as detection of specific device types
- Controllable LED support
- HID passthrough for the Chatpad
- Battery information support
- Arcade stick support
- Racing wheel support
- Support for the security flow, allowing use with wireless controllers that include their own dongles. (This does not include support for the first-party dongle yet.)

The framework set out in this driver also allows future expansion for specialized device types and additional features more cleanly than xpad.

Future plans include:

- Adding support for more device types, such as flight sticks.
- Exposing a raw character device to enable sending vendor-specific commands from userspace.
- Event logging to either sysfs or dmesg.
- Support for the headphone jack.

This version cleans up more issues found by sashiko.

Vicki Pfau (12):
Input: xbox_gip - Add new driver for Xbox GIP
Input: xpad - Remove Xbox One support
Input: xbox_gip - Add controllable LED support
Input: xbox_gip - Add HID relaying
Input: xbox_gip - Add battery support
Input: xbox_gip - Allow sending fragmented and ACME messages
Input: xbox_gip - Add security implementation from xone
Input: xbox_gip - Add arcade stick support
Input: xbox_gip - Add support for PDP guitar controllers
Input: Add ABS_CLUTCH, HANDBRAKE, and SHIFTER
HID: Map more automobile simulation inputs
Input: xbox_gip - Add wheel support

  Documentation/input/devices/xpad.rst          |   17 +-
  MAINTAINERS                                   |    6 +
  drivers/hid/hid-debug.c                       |   16 +-
  drivers/hid/hid-input.c                       |    2 +
  drivers/input/joystick/Kconfig                |    2 +
  drivers/input/joystick/Makefile               |    1 +
  drivers/input/joystick/gip/Kconfig            |   24 +
  drivers/input/joystick/gip/Makefile           |    8 +
  drivers/input/joystick/gip/gip-arcade-stick.c |  173 +
  drivers/input/joystick/gip/gip-core.c         | 3320 +++++++++++++++++
  drivers/input/joystick/gip/gip-drivers.c      |  222 ++
  drivers/input/joystick/gip/gip-pdp-jaguar.c   |  129 +
  drivers/input/joystick/gip/gip-security.c     |  810 ++++
  drivers/input/joystick/gip/gip-wheel.c        |  351 ++
  drivers/input/joystick/gip/gip.h              |  441 +++
  drivers/input/joystick/xpad.c                 |  684 +---
  include/uapi/linux/input-event-codes.h        |    3 +
  include/uapi/linux/input.h                    |    1 +
  18 files changed, 5513 insertions(+), 697 deletions(-)

create mode 100644 drivers/input/joystick/gip/Kconfig create mode 100644 drivers/input/joystick/gip/Makefile create mode 100644 drivers/input/joystick/gip/gip-arcade-stick.c create mode 100644 drivers/input/joystick/gip/gip-core.c create mode 100644 drivers/input/joystick/gip/gip-drivers.c create mode 100644 drivers/input/joystick/gip/gip-pdp-jaguar.c create mode 100644 drivers/input/joystick/gip/gip-security.c create mode 100644 drivers/input/joystick/gip/gip-wheel.c create mode 100644 drivers/input/joystick/gip/gip.h