Skip to contentSkip to conversation

Input: discard pre-registration events and test state seeding

PATCH Superseded Karlos Abel 3 participants 8 messages Oct 10 – Oct 14

Subsystems (6)

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

cover Input: discard pre-registration events and test state seeding

This series prevents input handlers from receiving buffered initialization events after device registration. On a ThinkPad T14 Gen 6, a later LED update flushed a stale SW_RFKILL_ALL event seeded by thinkpad_acpi. The fix drops the pending events and their timestamp before handlers attach, while retaining the seeded switch and absolute-axis state.

Patch 1 contains the six-line runtime fix. Patch 2 adds KUnit coverage for registration with and without event-buffer resizing. The test uses a virtual SW_DOCK device and performs no real radio operations.

Tested on mainline 3857c2fe5449541e24afc5efdb0f81a8a8f9a3a0 (7.3.0-rc6):
- Tests alone on the unmodified input core: four pass, two fail. The non-resizing case replays one stale switch event; both cases retain the initialization timestamp.
- Patch 1 alone: all four existing input-core tests pass.
- Both patches: all six input-core tests pass.
Both source commits were built and tested under UML without compiler warnings. The final files match the earlier failing/passing comparison.

The same runtime fix was also tested with QEMU/KVM on Arch 7.2.7 and on the ThinkPad.

AI assistance: OpenAI Codex assisted source analysis, the fix, regression tests and this text. The submitter performed the physical hardware comparisons.

Karlos Abel (2):
Input: discard pre-registration events before attaching handlers
Input: test state seeding across device registration

 drivers/input/input.c            |   6 ++
 drivers/input/tests/input_test.c | 168 +++++++++++++++++++++++++++++++
 2 files changed, 174 insertions(+)

base-commit: 3857c2fe5449541e24afc5efdb0f81a8a8f9a3a0

#1 lore raw

PATCH 1/2 Input: discard pre-registration events before attaching handlers

input_event() permits drivers to seed switch and absolute-axis state before registration without delivering those events to input handlers. After event-buffer allocation moved to input_allocate_device(), such initialization events can remain queued across input_register_device() when the buffer does not need resizing.

A later injected LED event followed by SYN_REPORT then delivers the old switch event to newly attached handlers. This was observed with the initial SW_RFKILL_ALL event from thinkpad_acpi on a ThinkPad T14 Gen 6:
an LED update replayed the initial radio-switch event after registration. Registration can also leave a pre-registration timestamp attached to the first real event packet, including when the event buffer is resized.

Clear the pending event count and monotonic timestamp under event_lock before attaching handlers. Keep the switch and absolute-axis state that was seeded by those events. Resetting the monotonic timestamp follows the existing flush path and lets the next packet obtain a fresh timestamp.

Fixes 0cd587735205 ("Input: preallocate memory to hold event values")
Assisted-by LLM
---
 drivers/input/input.c | 6 ++++++
 1 file changed, 6 insertions(+)
drivers/input/input.c +6 -0
index 01c91fec9..d59d62caa 100644
@@ -2445,6 +2445,12 @@ int input_register_device(struct input_dev *dev)
 
 	error = -EINTR;
 	scoped_cond_guard(mutex_intr, goto err_device_del, &input_mutex) {
+		/* Keep seeded state, but do not replay pre-registration events. */
+		scoped_guard(spinlock_irq, &dev->event_lock) {
+			dev->num_vals = 0;
+			dev->timestamp[INPUT_CLK_MONO] = ktime_set(0, 0);
+		}
+
 		list_add_tail(&dev->node, &input_dev_list);
 
 		list_for_each_entry(handler, &input_handler_list, node)
#2 lore raw

PATCH 2/2 Input: test state seeding across device registration

In reply to Karlos Abel

Add KUnit coverage for input events used to initialize device state before registration. Register a handler for a virtual switch/LED device, seed a switch before input_register_device(), and inject a later LED update and SYN_REPORT. Verify that the initial state is retained without replaying its event or reusing its timestamp, and that a real later change arrives.

Exercise both the original event buffer and registration with a larger buffer. Also verify preservation and subsequent delivery of absolute-axis state in the resizing case. Use SW_DOCK to avoid real radio operations.

These tests depend on the preceding pre-registration event fix. Against the unpatched input core, the non-resizing case delivers one stale switch event and both cases retain the initialization timestamp. Both tests pass with the fix, together with the four existing input-core tests.

Assisted-by LLM
---
 drivers/input/tests/input_test.c | 168 +++++++++++++++++++++++++++++++
 1 file changed, 168 insertions(+)
drivers/input/tests/input_test.c +168 -0
index e105ce71a..889d9e7ec 100644
@@ -161,11 +161,179 @@ static void input_test_grab(struct kunit *test)
 	input_put_device(input_dev);
 }
 
+struct input_seed_test {
+	struct input_dev *dev;
+	struct input_handler handler;
+	struct input_handle handle;
+	unsigned int switch_events;
+	unsigned int abs_events;
+	ktime_t led_timestamp;
+	bool connected;
+};
+
+static void input_seed_event(struct input_handle *handle, unsigned int type,
+			     unsigned int code, int value)
+{
+	struct input_seed_test *seed = handle->private;
+
+	if (type == EV_SW && code == SW_DOCK)
+		seed->switch_events++;
+	if (type == EV_ABS && code == ABS_X)
+		seed->abs_events++;
+	if (type == EV_LED && code == LED_NUML)
+		seed->led_timestamp = input_get_timestamp(handle->dev)[INPUT_CLK_MONO];
+}
+
+static bool input_seed_match(struct input_handler *handler,
+			     struct input_dev *dev)
+{
+	struct input_seed_test *seed = container_of(handler, struct input_seed_test,
+						  handler);
+
+	return seed->dev == dev;
+}
+
+static int input_seed_connect(struct input_handler *handler,
+			      struct input_dev *dev,
+			      const struct input_device_id *id)
+{
+	struct input_seed_test *seed = container_of(handler, struct input_seed_test,
+						  handler);
+	int error;
+
+	seed->handle.dev = dev;
+	seed->handle.handler = handler;
+	seed->handle.name = "input-seed-test";
+	seed->handle.private = seed;
+	error = input_register_handle(&seed->handle);
+	if (error)
+		return error;
+
+	error = input_open_device(&seed->handle);
+	if (error) {
+		input_unregister_handle(&seed->handle);
+		return error;
+	}
+
+	seed->connected = true;
+	return 0;
+}
+
+static void input_seed_disconnect(struct input_handle *handle)
+{
+	input_close_device(handle);
+	input_unregister_handle(handle);
+}
+
+static const struct input_device_id input_seed_ids[] = {
+	{ .flags = INPUT_DEVICE_ID_MATCH_BUS, .bustype = BUS_VIRTUAL },
+	{ }
+};
+
+static void input_test_seed_events(struct kunit *test, bool resize)
+{
+	const ktime_t seed_timestamp = ktime_set(123456, 789);
+	struct input_seed_test *seed;
+	int error;
+
+	seed = kunit_kzalloc(test, sizeof(*seed), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, seed);
+	seed->dev = input_allocate_device();
+	KUNIT_ASSERT_NOT_NULL(test, seed->dev);
+
+	seed->dev->name = "Input pre-registration events";
+	seed->dev->id.bustype = BUS_VIRTUAL;
+	input_set_capability(seed->dev, EV_SW, SW_DOCK);
+	input_set_capability(seed->dev, EV_LED, LED_NUML);
+	/* An ABS axis also raises the estimated event-buffer size. */
+	if (resize) {
+		input_set_abs_params(seed->dev, ABS_X, 0, 100, 0, 0);
+		seed->dev->hint_events_per_packet = 128;
+	}
+
+	seed->handler.event = input_seed_event;
+	seed->handler.match = input_seed_match;
+	seed->handler.connect = input_seed_connect;
+	seed->handler.disconnect = input_seed_disconnect;
+	seed->handler.name = "input-seed-test";
+	seed->handler.id_table = input_seed_ids;
+	error = input_register_handler(&seed->handler);
+	KUNIT_EXPECT_EQ(test, error, 0);
+	if (error)
+		goto free_device;
+
+	/* Initialize state before registration, without a SYN_REPORT. */
+	input_set_timestamp(seed->dev, seed_timestamp);
+	input_report_switch(seed->dev, SW_DOCK, 1);
+	if (resize)
+		input_report_abs(seed->dev, ABS_X, 42);
+	error = input_register_device(seed->dev);
+	KUNIT_EXPECT_EQ(test, error, 0);
+	if (error)
+		goto unregister_handler;
+
+	KUNIT_EXPECT_TRUE(test, seed->connected);
+	if (!seed->connected)
+		goto unregister_device;
+
+	KUNIT_EXPECT_TRUE(test, test_bit(SW_DOCK, seed->dev->sw));
+	if (resize)
+		KUNIT_EXPECT_EQ(test, input_abs_get_val(seed->dev, ABS_X), 42);
+	KUNIT_EXPECT_EQ(test, seed->switch_events, 0);
+	KUNIT_EXPECT_EQ(test, seed->abs_events, 0);
+
+	/* A later LED write must not replay the initialization events. */
+	input_inject_event(&seed->handle, EV_LED, LED_NUML, 1);
+	input_inject_event(&seed->handle, EV_SYN, SYN_REPORT, 0);
+	KUNIT_EXPECT_EQ(test, seed->switch_events, 0);
+	KUNIT_EXPECT_EQ(test, seed->abs_events, 0);
+	KUNIT_EXPECT_NE(test, seed->led_timestamp, seed_timestamp);
+	KUNIT_EXPECT_NE(test, seed->led_timestamp, ktime_set(0, 0));
+
+	/* Genuine post-registration state changes must still be delivered. */
+	seed->switch_events = 0;
+	seed->abs_events = 0;
+	input_report_switch(seed->dev, SW_DOCK, 0);
+	if (resize)
+		input_report_abs(seed->dev, ABS_X, 77);
+	input_sync(seed->dev);
+	KUNIT_EXPECT_EQ(test, seed->switch_events, 1);
+	KUNIT_EXPECT_EQ(test, seed->abs_events, resize ? 1 : 0);
+	KUNIT_EXPECT_FALSE(test, test_bit(SW_DOCK, seed->dev->sw));
+	if (resize)
+		KUNIT_EXPECT_EQ(test, input_abs_get_val(seed->dev, ABS_X), 77);
+	input_inject_event(&seed->handle, EV_SYN, SYN_REPORT, 0);
+	KUNIT_EXPECT_EQ(test, seed->switch_events, 1);
+	KUNIT_EXPECT_EQ(test, seed->abs_events, resize ? 1 : 0);
+
+unregister_device:
+	input_unregister_device(seed->dev);
+	input_unregister_handler(&seed->handler);
+	return;
+
+unregister_handler:
+	input_unregister_handler(&seed->handler);
+free_device:
+	input_free_device(seed->dev);
+}
+
+static void input_test_seed(struct kunit *test)
+{
+	input_test_seed_events(test, false);
+}
+
+static void input_test_seed_resize(struct kunit *test)
+{
+	input_test_seed_events(test, true);
+}
+
 static struct kunit_case input_tests[] = {
 	KUNIT_CASE(input_test_polling),
 	KUNIT_CASE(input_test_timestamp),
 	KUNIT_CASE(input_test_match_device_id),
 	KUNIT_CASE(input_test_grab),
+	KUNIT_CASE(input_test_seed),
+	KUNIT_CASE(input_test_seed_resize),
 	{ /* sentinel */ }
 };
 
#3 lore raw

Re: [PATCH 2/2] Input: test state seeding across device registration

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] input: missing absinfo allocation check in input_set_abs_params causes NULL pointer dereference…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] input: missing absinfo allocation check in input_set_abs_params causes NULL pointer dereference
- [Medium] input: dangling pointer match in test teardown allows accidental binding to unrelated devices --

commit 2e31a0267a25d47a7a2da67f7fbb5534d7ebbae1
Author: Karlos Abel <[email protected]>

Input: test state seeding across device registration

This commit adds KUnit coverage for input events used to initialize device state before registration. It exercises both original event buffers and larger resizing buffers, verifying the correct retention and delivery of states.

Quoted 4 lines
drivers/input/tests/input_test.c +0 -0
index e105ce71a920a..889d9e7ec922f 100644

[ ... ]

Quoted 1 line
drivers/input/tests/input_test.c +0 -0
@@ -161,11 +161,179 @@ static void input_test_grab(struct kunit *test)

[ ... ]

Quoted 8 lines
drivers/input/tests/input_test.c +8 -0
+static bool input_seed_match(struct input_handler *handler,
+			     struct input_dev *dev)
+{
+	struct input_seed_test *seed = container_of(handler, struct input_seed_test,
+						  handler);
+
+	return seed->dev == dev;
+}

[ ... ]

drivers/input/tests/input_test.c static void input_test_grab(struct kunit *test) · line 252

Quoted 5 lines
drivers/input/tests/input_test.c +5 -0
+	/* An ABS axis also raises the estimated event-buffer size. */
+	if (resize) {
+		input_set_abs_params(seed->dev, ABS_X, 0, 100, 0, 0);
+		seed->dev->hint_events_per_packet = 128;
+	}

[Severity: High]
Does this code risk a NULL pointer dereference if the internal allocation for absinfo fails?

Functions like input_set_abs_params() set EV_ABS in dev->evbit and the specific axis in dev->absbit before calling input_alloc_absinfo(). If this allocation fails (e.g., due to memory pressure), they return silently, leaving the capability bits permanently set while dev->absinfo remains NULL.

[ ... ]

drivers/input/tests/input_test.c static void input_test_grab(struct kunit *test) · line 269

Quoted 5 lines
drivers/input/tests/input_test.c +5 -0
+	/* Initialize state before registration, without a SYN_REPORT. */
+	input_set_timestamp(seed->dev, seed_timestamp);
+	input_report_switch(seed->dev, SW_DOCK, 1);
+	if (resize)
+		input_report_abs(seed->dev, ABS_X, 42);

Because this test explicitly relies on seeding initial absolute axis state via input_report_abs() before registration, if the allocation failed during input_set_abs_params(), this subsequent event injection causes input_handle_abs_event() to unconditionally dereference dev->absinfo[code].value. This results in a NULL pointer dereference regression before the delayed missing-absinfo check in input_register_device() can catch it.

Should the failure state of input_set_abs_params() be checked here, or should input_alloc_absinfo() be verified to have succeeded before continuing?

[ ... ]

drivers/input/tests/input_test.c static void input_test_grab(struct kunit *test) · line 311

Quoted 3 lines
drivers/input/tests/input_test.c +3 -0
+unregister_device:
+	input_unregister_device(seed->dev);
+	input_unregister_handler(&seed->handler);

[Severity: Medium]
Can this sequence lead to a use-after-free regression and accidental binding to unrelated devices?

In this teardown path of input_test_seed_events(), input_unregister_device() is called before input_unregister_handler(). For a non-devres device, unregistering calls input_put_device(), dropping the final reference and immediately freeing the device memory. However, the custom test handler remains on the global input_handler_list.

If another input device registers concurrently during this window, the input core iterates all handlers and calls input_seed_match(). This function evaluates seed->dev == dev using the freed memory. If the slab allocator reused that exact memory address for the newly registered device, the match will incorrectly return true, and the test handler will erroneously attempt to bind to the unrelated device.

Should input_unregister_handler() be called before input_unregister_device() to avoid this race condition?

Quoted 7 lines
drivers/input/tests/input_test.c +7 -0
+	return;
+
+unregister_handler:
+	input_unregister_handler(&seed->handler);
+free_device:
+	input_free_device(seed->dev);
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
maintainer
#4 lore raw
In reply to Karlos Abel

Hi Karlos,

Quoted 5 lines · Karlos Abel

This series prevents input handlers from receiving buffered initialization events after device registration. On a ThinkPad T14 Gen 6, a later LED update flushed a stale SW_RFKILL_ALL event seeded by thinkpad_acpi. The fix drops the pending events and their timestamp before handlers attach, while retaining the seeded switch and absolute-axis state.

Could you explain why these seeded events give you trouble? Is it because thinkpad_acpi() forgets to send input_sync() and so the timestamp is stale/wrong?

Thanks.

Signature · 1 line
Dmitry
#5 lore raw

Resending in plain text; the mailing lists rejected my previous reply because it contained HTML.

Hi Dmitry,

The observed problem is the initial switch event being delivered later and undoing a subsequent Bluetooth soft-block. It does not depend on the event timestamp.

hotkey_init() seeds SW_RFKILL_ALL=1 before registering the input device, without calling input_sync(). That updates the switch state, but also leaves the event queued across registration.

In the unpatched hardware trace:

At 74.486 seconds, Bluetooth is explicitly soft-blocked.
At 80.300 seconds, Xorg injects LED updates followed by SYN_REPORT. There is already one event queued.
That flush delivers the old SW_RFKILL_ALL=1 to rfkill_event(), which schedules a global unblock and turns Bluetooth back on.

rfkill_start() already reads the initial switch state when the handler attaches; this later delivery produces an additional action after userspace has changed the soft-block state.

Regarding the missing input_sync(): from reading the initialization path, simply adding it alongside the seed would be ignored because EV_SYN is not enabled on this device until input_register_device().

I targeted registration because input_event() documents pre-registration seeding as updating initial state without delivering those events to handlers. The patch retains that state while discarding the pending events. The timestamp reset addresses a separate stale-timestamp case covered by the tests.

Thanks very much,

Karlos

Quoted 19 lines · Dmitry Torokhov

Hi Karlos,

Quoted 1 line · Karlos Abel

This series prevents input handlers from receiving buffered

initialization

Quoted 4 lines

events after device registration. On a ThinkPad T14 Gen 6, a later LED update flushed a stale SW_RFKILL_ALL event seeded by thinkpad_acpi. The fix drops the pending events and their timestamp before handlers attach, while retaining the seeded switch and absolute-axis state.

Could you explain why these seeded events give you trouble? Is it because thinkpad_acpi() forgets to send input_sync() and so the timestamp is stale/wrong?

Thanks.

--
Dmitry

maintainer
#6 lore raw

Hi Karlos,

Quoted 16 lines · Karlos Abel

The observed problem is the initial switch event being delivered later and undoing a subsequent Bluetooth soft-block. It does not depend on the event timestamp.

hotkey_init() seeds SW_RFKILL_ALL=1 before registering the input device, without calling input_sync(). That updates the switch state, but also leaves the event queued across registration.

In the unpatched hardware trace:

At 74.486 seconds, Bluetooth is explicitly soft-blocked.
At 80.300 seconds, Xorg injects LED updates followed by SYN_REPORT. There is already one event queued.
That flush delivers the old SW_RFKILL_ALL=1 to rfkill_event(), which schedules a global unblock and turns Bluetooth back on.

Quoted 7 lines

rfkill_start() already reads the initial switch state when the handler attaches; this later delivery produces an additional action after userspace has changed the soft-block state.

Regarding the missing input_sync(): from reading the initialization path, simply adding it alongside the seed would be ignored because EV_SYN is not enabled on this device until input_register_device().

Thank you for the trace - that makes the whole picture clear.

If input core handles EV_SYN properly from the start without requiring it to be set in dev->evbit, calling input_sync() while seeding initial device state will flush dev->vals right away. Then those seeded events will not stay stuck in the queue and handlers attached later will never see them, so there is no need to explicitly reset the queue in input_register_device().

I will apply a patch to input core to always accept EV_SYN events. Could you please send a patch for thinkpad_acpi adding the missing input_sync(tpacpi_inputdev) after reporting the initial switch states in hotkey_init()?

Thanks.

Signature · 1 line
Dmitry
#7 lore raw

PATCH 1/1 platform/x86: thinkpad_acpi: Sync initial switch states

hotkey_init() reports the initial switch states before registering the input device, but does not terminate the packet with input_sync(). Since input event buffers are allocated before registration, these events can remain queued until a later SYN_REPORT.

On a ThinkPad, a userspace LED update and SYN_REPORT delivered the initial SW_RFKILL_ALL=1 event to the rfkill input handler after registration. This undid a software radio block that had already been applied.

Call input_sync() after reporting the initial switch states to flush the packet before input handlers attach. This requires the input-core fix to accept EV_SYN events before registration.

Fixes 0cd587735205 ("Input: preallocate memory to hold event values")
Assisted-by LLM

---
This is the companion driver change requested in the linked discussion. It depends on Dmitry's "Input: always accept EV_SYN in input_event()":
https://lore.kernel.org/r/[email protected]
The prerequisite patch ID is included below.

Validation on 3857c2fe5449 plus that core patch:
- KUnit/UML: all six input tests pass with lockdep enabled. The two regression tests fail with either the core change or the pre-registration sync removed, and with both removed.
- The tests model the driver's event sequence with a virtual input device; they do not execute hotkey_init() or operate real radios.
- The actual ThinkPad driver object builds without warnings with W=1, configured both built-in and as a module (x86-64/GCC).
- No new physical-hardware run of this pair yet.

AI assistance covered the change, message, and regression validation.

 drivers/platform/x86/lenovo/thinkpad_acpi.c | 1 +
 1 file changed, 1 insertion(+)
drivers/platform/x86/lenovo/thinkpad_acpi.c +1 -0
index 1661f070c..ea8679398 100644
@@ -3497,6 +3497,7 @@ static int __init hotkey_init(struct ibm_init_struct *iibm)
 		input_report_switch(tpacpi_inputdev,
 				    SW_TABLET_MODE, tabletsw_state);
 	}
+	input_sync(tpacpi_inputdev);
 
 	/* Do not issue duplicate brightness change events to
 	 * userspace. tpacpi_detect_brightness_capabilities() must have

base-commit: 3857c2fe5449541e24afc5efdb0f81a8a8f9a3a0
prerequisite-patch-id: f8539bd5b5201ef9795823552ba68a73b7dd6298

Signature · 1 line
2.56.0