Selaa lähdekoodia

usbhid: add wheel support for report-protocol mice

Parse a mouse's HID report descriptor and keep the exact report ID,
button bit offsets and X/Y/wheel field offsets and sizes.  A mouse whose
descriptor has X/Y and a wheel switches to report protocol, because the
fixed boot report has no wheel field; wheel-less mice, unusable
descriptors and devices that refuse the switch keep the boot decode.
The layout covers padded 8-bit, 12-bit and 16-bit reports.  One wheel
notch feeds the shared 48 px scroll accumulator like the PS/2 and
Logitech DJ paths.

Move the software cursor's 4 KB background save to a frame allocation
so the added code still fits below the 0x90000 kernel wall, and report
the USB protocol and wheel state through mouseinfo.  AGENTS.md and the
architecture pages document the parser, and make test-hid feeds it
synthetic descriptors on the host.
Johannes Zellner 47 minuuttia sitten
vanhempi
sitoutus
eab1e72347
13 muutettua tiedostoa jossa 914 lisäystä ja 79 poistoa
  1. 38 22
      AGENTS.md
  2. 12 4
      Makefile
  3. 2 0
      docs/development.html
  4. 17 10
      docs/drivers.html
  5. 2 0
      include/syscall.h
  6. 400 0
      kernel/hid_report.c
  7. 56 0
      kernel/hid_report.h
  8. 225 0
      kernel/hid_report_test.c
  9. 17 5
      kernel/mouse.c
  10. 5 2
      kernel/sys_info.c
  11. 129 31
      kernel/usbhid.c
  12. 7 4
      kernel/usbhid.h
  13. 4 1
      user/apps/mouseinfo/ucmd_mouseinfo.c

+ 38 - 22
AGENTS.md

@@ -1539,12 +1539,21 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   Cirrus thresholds alpha
   at 50% into its AND/XOR planes (white/black by luminance) and clamps the
   position at 0.  An image upload never runs from IRQ12, which only moves.
-  Animated shapes advance from `mouse_poll_update()`.  Scroll from every backend accumulates in
-  `mouse_scroll_y` and `mouse_scroll_take()` hands it to the WM in pixels;
-  one PS/2 wheel notch is 48 px.  `usbhid.c/h` — USB HID boot devices: find
+  Animated shapes advance from `mouse_poll_update()`.  Scroll from every
+  backend accumulates in `mouse_scroll_y` and `mouse_scroll_take()` hands it
+  to the WM in pixels; one wheel notch is 48 px.  The IntelliMouse 4th byte
+  and the USB HID Wheel usage have opposite raw signs; both map wheel-up to
+  earlier content.  The software cursor's 32x32 background save is one
+  frame-allocated page (hardware cursor backends never allocate it), so it
+  does not move the kernel's BSS wall.  `usbhid.c/h` — USB HID devices: find
   + configure a mouse and/or keyboard, arm their interrupt endpoints, decode
-  mouse reports and inject keyboard scancodes, watch for plug/unplug (boot
-  protocol has no wheel field, so the USB wheel output stays 0 for now).
+  mouse reports and inject keyboard scancodes, watch for plug/unplug.
+  `hid_report.c/h` parses a mouse's report descriptor: a report with X/Y and
+  a wheel (Generic Desktop usage 0x38) runs in report protocol — boot
+  protocol has no wheel field — with the descriptor's report ID, button bit
+  offsets and X/Y/wheel field offsets/sizes; a wheel-less mouse, a descriptor
+  it cannot use, or a refused protocol switch keeps the fixed 3-byte boot
+  decode.
 - **I2C touchpad**: `i2c.c/h` — polled Synopsys DesignWare APB I2C master
   for the LPSS blocks (fast mode, component-type probe, explicit LPSS
   reset-release so the FIFO drains); `touchpad.c/h` — Elan HID-over-I2C
@@ -3163,8 +3172,9 @@ briefly reporting disconnected.
   these devices.
 - **Debug**: `ohci:` / `uhci:` / `ehci:` / `usbhid:` lines go to COM1 (and
   through the netlog mirror on serial-less boards); `mouseinfo` shows the
-  active mouse backend, the Elan/Synaptics VID/PID when the I2C touchpad is present,
-  and whether a USB keyboard is attached; `usb.c`'s
+  active mouse backend, the Elan/Synaptics VID/PID when the I2C touchpad is
+  present, whether a USB keyboard is attached, and the USB mouse's protocol
+  (boot/report/DJ) and wheel support; `usb.c`'s
   `USB_DEBUG` and `usbhid.c`'s `USBHID_DEBUG` (both default 0) add
   scan/report tracing.  Headless tests: `make test-usb` runs
   `tools/qmp_cursor_test.py` (injects mouse motion with QMP
@@ -3172,16 +3182,22 @@ briefly reporting disconnected.
   `tools/qmp_keyboard_test.py` (types with QMP `send-key`, verifies the
   screen output); the cursor test takes `--uhci`, `--uhci72`, `--multi` and
   `--hub` (a USB2 hub with the mouse on its downstream port) and both take
-  `--hotplug`, `--xhci` and `--ehci`.
+  `--hotplug`, `--xhci` and `--ehci`.  `make test-hid` feeds synthetic
+  report descriptors (padded 8-bit, 12-bit and 16-bit axes, report IDs,
+  buttons, wheel) to `hid_report.c` and checks the decoded frames.
 - **Limits**: EHCI drives high-speed root-port devices only (no TT/split
   transactions for low/full-speed devices behind a high-speed hub), hotplug
   watches root ports only (a device behind a hub is only enumerated when a
-  scan runs), generic HID report IDs are not handled (a device that
-  prepends report IDs decodes as garbage; the Logitech Unifying DJ receiver
-  is decoded explicitly), absolute pointers/tablets are ignored, boot mice
-  have no wheel (the DJ path maps it), and no USB keyboard means no
-  keyboard at all if the BIOS legacy emulation was the only other source
-  (`make net-dev` still reloads the kernel).
+  scan runs).  A report-protocol mouse with a wheel is decoded from its
+  descriptor (report IDs, button bits, X/Y and wheel), but a wheel-less
+  report-protocol mouse and a report-protocol keyboard still use the fixed
+  boot layout, so a device with an unusual report ID there decodes as
+  garbage; a mouse whose descriptor is longer than the 240-byte read window
+  and has its wheel beyond it falls back to the boot layout (no wheel).  The
+  Logitech Unifying DJ receiver is decoded explicitly, absolute
+  pointers/tablets are ignored, and no USB keyboard means no keyboard at all
+  if the BIOS legacy emulation was the only other source (`make net-dev`
+  still reloads the kernel).
 
 ## Serial debug monitor (`dbg`)
 
@@ -3491,14 +3507,14 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     ~0x8bf20 once the frame bitmap moved out of BSS; with the ioremap
     window, the EHCI handoff fix, the boot-scan log ring, the init bootstrap,
     parent-pid tree kill, the tty control syscalls and `TTY_MAX` 16, the
-    early BSP LAPIC/EOI, the boot-stage markers, the Synaptics touchpad and
-    the three-source boot log (Boot/Serial/Scan) it is ~0x8fd60, ~0.7 KB
-    below the `0x90000` wall.  The WM and `sys_wm.o` build with `-Os` because
-    their extra settings code otherwise pushed the `.data` end across a page
-    boundary and moved the 4 KB-aligned BSS by a whole page; `bootcon.o`
-    builds with `-Os` for the same reason (its unified log reader at `-O2`
-    crossed that boundary).  The remaining limit is kernel code/buffers
-    only.
+    early BSP LAPIC/EOI, the boot-stage markers, the Synaptics touchpad, the
+    HID report-descriptor mouse layout and the three-source boot log
+    (Boot/Serial/Scan) it is ~0x8fda0, ~0.6 KB below the `0x90000` wall.
+    The WM and `sys_wm.o` build with `-Os` because their extra settings code
+    otherwise pushed the `.data` end across a page boundary and moved the
+    4 KB-aligned BSS by a whole page; `bootcon.o` builds with `-Os` for the
+    same reason (its unified log reader at `-O2` crossed that boundary).  The
+    remaining limit is kernel code/buffers only.
 
 22. Browser limits: JavaScript runs inline and external classic scripts on
     QuickJS (ES2025) with the DOM surface described above (creation/mutation/selectors/

+ 12 - 4
Makefile

@@ -71,7 +71,7 @@ EFI_LDFLAGS = -nostdlib -Wl,--subsystem,10 -Wl,-e,efi_main \
               -Wl,--image-base,0x0 -Wl,--dynamicbase \
               -Wl,--enable-reloc-section -Wl,--no-insert-timestamp
 
-.PHONY: all clean run run-smp run-floppy run-usb run-uhci run-ehci run-ehci-asix run-xhci run-xhci-asix run-net run-rndis run-e1000 run-ahci run-amd test-amd test-usb test-install run-serial floppy usb uefi run-uefi test-uefi flash dev net-dev net-install cmds-dev net-cmds browser-dev gallery-dev compat-serve netmon monitor test-crypto test-wpa test-ccmp test-images test-images-asan test-libc test-js test-font test-font-asan test-svg test-touchpad test-chat test-chat-e2e test-wifi-store test-cursors fonts appicons kernel-dev kernel-net-dev rootfs nowm
+.PHONY: all clean run run-smp run-floppy run-usb run-uhci run-ehci run-ehci-asix run-xhci run-xhci-asix run-net run-rndis run-e1000 run-ahci run-amd test-amd test-usb test-install run-serial floppy usb uefi run-uefi test-uefi flash dev net-dev net-install cmds-dev net-cmds browser-dev gallery-dev compat-serve netmon monitor test-crypto test-wpa test-ccmp test-images test-images-asan test-libc test-js test-font test-font-asan test-svg test-touchpad test-hid test-chat test-chat-e2e test-wifi-store test-cursors fonts appicons kernel-dev kernel-net-dev rootfs nowm
 
 all: floppy.img usb.img final.bin root.img image.bin
 
@@ -115,7 +115,7 @@ KERNEL_LINK_ORDER = vesa_stage entry kernel timer switch sched process init mm \
 	gfxbench gpu backlight ati cirrus intel nvidia nv50 radeon mtrr \
 	font_8x8 font_8x16 fbtext gfx display cursor mouse i2c touchpad \
 	touchpad_gesture uhci ohci ehci xhci asix rndis iwl_trans iwl_mvm \
-	iwl_dvm wifi_fw rtl8821au wifi ccmp usb usbmsc usbhid lsusb panic \
+	iwl_dvm wifi_fw rtl8821au wifi ccmp usb usbmsc hid_report usbhid lsusb panic \
 	bootcon blkdev sdhci ata ahci fatdetect fatformat format install vfs \
 	sys_fs sys_info sys_mem sys_net idle kexec kexec_tramp dbg lspci peek \
 	ne2000 r8168 e1000e netdev net netcore netkexec netlog dhcp dns ntp tcp \
@@ -130,7 +130,7 @@ KERNEL_OBJS = $(foreach n,$(KERNEL_LINK_ORDER),$(call kobj,$(n)))
 KERNEL_OS = terminal disk fat nvidia nv50 uhci ohci ehci xhci asix rndis \
 	iwl_trans iwl_mvm iwl_dvm wifi_fw rtl8821au wifi ccmp usb lsusb lspci \
 	peek ne2000 r8168 blkdev fatdetect fatformat format install usbmsc dbg vfs \
-	wm sys_wm ideapad i2c touchpad usbhid
+	wm sys_wm ideapad i2c touchpad hid_report usbhid
 $(addprefix $(B)/kernel/,$(addsuffix .o,$(KERNEL_OS))): OPT = -Os
 # bootcon.c carries the unified boot/serial/scan log reader; at -O2 its extra
 # text moved the .data end across a page boundary and shifted the 4 KB-aligned
@@ -672,6 +672,14 @@ touchpad_gesture_test: kernel/touchpad_gesture_test.c kernel/touchpad_gesture.c
 test-touchpad: touchpad_gesture_test
 	./touchpad_gesture_test
 
+# Host tests for the HID report-descriptor parser: field bit offsets for
+# padded/12-bit/16-bit mice, report IDs, buttons, the wheel and decoding.
+hid_report_test: kernel/hid_report_test.c kernel/hid_report.c kernel/hid_report.h
+	gcc -O2 -Wall -Wextra -o $@ kernel/hid_report_test.c kernel/hid_report.c
+
+test-hid: hid_report_test
+	./hid_report_test
+
 # Host tests for the chat client's pure modules: JSON, cookie jar and the
 # login page/reply/config parsers.
 CHAT_TEST_CFLAGS = -O1 -g -Wall -Wextra -fsanitize=address,undefined $(USER_INC)
@@ -1341,7 +1349,7 @@ clean:
 	      firmware/*.ucode firmware/*.tbl firmware/*.bin cursors/*.cur icons/*.icn \
 	      mkpack mkrootfs mkrtwtbl mkcursors mkicons mkappicons jsstrip cursor_test kexec_send netkexec_send netmonitor \
 	      browser-host host-curl \
-	      ufont_test ufont_test_asan svg_test touchpad_gesture_test \
+	      ufont_test ufont_test_asan svg_test touchpad_gesture_test hid_report_test \
 	      ujson_test uhttp_cookie_test chat_login_test tls_test wpa_test \
 	      wifi_store_test ccmp_test img_test img_test_asan malloc_test \
 	      format_test math_test div64_test setjmp_test js_test

+ 2 - 0
docs/development.html

@@ -236,6 +236,7 @@
 					<tr><td><code>make test-svg</code></td><td>Host tests (ASan/UBSan) for the inline-SVG rasterizer: exact rect coverage, antialiased edges, relative commands, nonzero vs even-odd, circle area, curves and arcs, transforms, number grammar and strokes; <code>./svg_test out.ppm</code> writes a specimen.</td></tr>
 					<tr><td><code>make test-cursors</code></td><td>Host test (ASan/UBSan) for the NBCUR1 cursor bundle built by <code>mkcursors</code>: header and shape count, sizes and hotspots against the Adwaita files, premultiplied pixels, no empty frame, and the 15-frame <code>wait</code>/<code>progress</code> spinners.</td></tr>
 					<tr><td><code>make test-touchpad</code></td><td>Host tests for the device-independent contact gesture engine: taps, right-click zones, physical-button latch, two-finger scroll, direction and pointer re-anchoring.</td></tr>
+					<tr><td><code>make test-hid</code></td><td>Host tests for the HID mouse report-descriptor parser: padded 8-bit, 12-bit and 16-bit axes, report IDs, buttons, wheel offsets and decoded frames; malformed and truncated descriptors are rejected.</td></tr>
 					<tr><td><code>make test-chat</code></td><td>Host tests (ASan/UBSan) for the chat client's JSON parser, cookie jar and the OIDC login page/reply/config parsers.</td></tr>
 					<tr><td><code>make test-chat-e2e</code></td><td>Boots QEMU with an NE2000 on slirp, starts <code>tools/mock_chat.py</code> and drives <code>chat</code> through QMP: native login, send, live poll, read marker, older paging, browse/join, new DM, saved-session resume and sign-out.  <code>CHAT_E2E=--totp|--consent|--passkey|--wrong</code> runs a login variant.</td></tr>
 					<tr><td><code>make compat-serve</code></td><td>Serve the browser compatibility ladder from <code>testdata/browser/compat/</code> on port 8000 for the board or QEMU guest.</td></tr>
@@ -352,6 +353,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 			<li><strong>Ring-3 libc.</strong> <code>make test-libc</code> runs the malloc stress test (64 MB simulated arena with poisoned pages), exact <code>snprintf</code> float/string checks against the host, x87 math values, the 64-bit division helpers and a 32-bit setjmp/longjmp test.</li>
 			<li><strong>Fonts.</strong> <code>make test-font</code> parses the checked-in Arimo subset on the host, measures Latin-1 text, renders composites (for example <code>Äé</code>) and writes a specimen PPM. The browser must also be exercised across a navigation to verify detach/reattach around <code>heap_reset()</code>.</li>
 			<li><strong>Touchpad gestures.</strong> <code>make test-touchpad</code> feeds synthetic contact frames to <span class="file">touchpad_gesture.c</span> and checks one/two-finger taps, the corner and physical-button mapping, scroll start/direction, pointer freeze and re-anchoring, and the option switches.</li>
+			<li><strong>HID mouse layouts.</strong> <code>make test-hid</code> feeds synthetic HID report descriptors to <span class="file">hid_report.c</span>: a three-button mouse with 5 bits of padding, report ID 2 with 16-bit axes, 12-bit axes packed across byte boundaries, Usage Minimum/Maximum axes, and malformed/truncated descriptors. It checks the computed bit offsets, report size and decoded buttons/dx/dy/wheel.</li>
 			<li><strong>Chat client.</strong> <code>make test-chat</code> covers the pure modules on the host.  <code>tools/mock_chat.py</code> is a two-origin mock of Cloudron Chat (port 18080) and the Cloudron OIDC login (18081) with <code>test</code>, <code>totp</code> (code 123456), <code>passkey</code> and <code>consent</code> accounts (password <code>test</code>) and <code>/debug/state</code>, <code>/debug/inject</code> endpoints; run it alone and enter <code>http://10.0.2.2:18080</code> in a QEMU guest's chat, or let <code>make test-chat-e2e</code> drive it.  Screenshots land in <code>chat-test-out/</code>.</li>
 			<li><strong>Browser compatibility.</strong> <code>make compat-serve</code> serves the numbered A/B ladder in <code>testdata/browser/compat/</code>. Open the index on the board (or at <code>http://10.0.2.2:8000/</code> from a QEMU guest with user networking) and compare each pair; the index table records the current status.</li>
 			<li><strong>Host browser harness.</strong> <code>make browser-host</code> builds the real browser, ngui, image/TLS code and QuickJS as a 32-bit Linux program against the same <code>SYS_*</code> ABI. <code>./browser-host testdata/browser/compat/010-block-width.html</code> opens an SDL3 window (native Wayland on this desktop); the address bar, wheel, links and keys use the normal browser paths. <code>./browser-host --headless --wait 3000 --shot /tmp/opencode/page.ppm URL</code> renders without a display for scripts and screenshots. The harness uses host sockets rather than the NebOS TCP stack, and an <code>mmap</code> arena with the ring-3 allocator, so it tests browser/HTML/CSS/JS/image/font/TLS logic rather than drivers.</li>

+ 17 - 10
docs/drivers.html

@@ -546,22 +546,27 @@
 		<p>
 			<span class="file">usbhid.c</span> gives every HID class-3 interface
 			with an interrupt-IN endpoint one of the six USB interrupt slots. Boot
-			interfaces (subclass 1, protocol 1/2) are used as-is; other class-3
-			interfaces are classified by reading their HID report descriptor.
-			Composite receivers and several devices can coexist; mouse reports
-			from all slots are merged.
+			interfaces (subclass 1, protocol 1/2) are used as-is, except a
+			wheel-capable mouse: its report descriptor is parsed and the mouse is
+			switched to report protocol, because the fixed boot report has no wheel
+			field. Other class-3 interfaces are classified by reading their HID
+			report descriptor. Composite receivers and several devices can
+			coexist; mouse reports from all slots are merged.
 		</p>
 		<ul>
-			<li><strong>Mouse.</strong> Three-byte boot reports: buttons in <code>b0 &amp; 7</code>, signed <code>dx/dy</code>. HID's +y is flipped to the PS/2 convention.</li>
+			<li><strong>Mouse.</strong> A mouse whose report descriptor has X/Y and a wheel runs in report protocol and is decoded from the descriptor's exact field layout (report ID, button bits, 8/12/16-bit X/Y and the wheel), so the wheel reaches the shared scroll accumulator; a wheel-less mouse, an unusable descriptor or a refused protocol switch keeps the fixed three-byte boot report (buttons in <code>b0 &amp; 7</code>, signed <code>dx/dy</code>). HID's +y is flipped to the PS/2 convention.</li>
 			<li><strong>Logitech Unifying receiver.</strong> The <code>046d:c52b</code> receiver's interface 2 is a vendor HID++/DJ channel. <span class="file">usbhid.c</span> claims it and decodes the paired device's DJ reports: report type 2 carries a 16-button, 12-bit X/Y, wheel and pan mouse report. Unlike Linux's <code>hid-logitech-dj</code> it does not send the HID++ switch command: a receiver in boot mode carries reports on the boot mouse interface (1), while one already in DJ mode (the warm-reboot case after Linux used it) sends DJ reports directly. The receiver's USB path is the second xHCI (the Lenovo USB-C hub), so both the controller and the DJ decode are needed for the M705.</li>
 			<li><strong>Keyboard.</strong> Eight-byte boot reports (modifier + six keycodes). Reports are diffed and decoded through a HID-usage → scancode-set-1 table, then injected with <code>io_inject_scancode()</code>.</li>
 			<li><strong>Repeat.</strong> A boot keyboard only reports changes, so <code>io.c</code> adds software typematic repeat (500 ms delay, 33 ms rate).</li>
-			<li><strong>PS/2.</strong> The i8042 path shares the cursor and keyboard code; the BIOS legacy USB emulation is disabled because the kernel owns the devices.</li>
+			<li><strong>PS/2.</strong> The i8042 path shares the cursor and keyboard code; an IntelliMouse ID 3/4 switches the packet to four bytes and its Z byte feeds the same 48 px/notch scroll accumulator. The BIOS legacy USB emulation is disabled because the kernel owns the devices.</li>
 		</ul>
 		<p>
-			<code>mouseinfo</code> shows the active backend and whether a USB
-			keyboard is attached. Headless regression tests inject mouse motion
-			and keys through QMP and verify the result with screen dumps.
+			<code>mouseinfo</code> shows the active backend, whether a USB
+			keyboard is attached, and the USB mouse's protocol and wheel
+			support. <code>make test-hid</code> checks the HID
+			report-descriptor parser on the host; headless regression tests inject
+			mouse motion, wheel and keys through QMP and verify the result with
+			screen dumps.
 		</p>
 
 		<h3>I2C touchpad</h3>
@@ -778,7 +783,7 @@
 			<li><strong>Polling.</strong> USB, storage and network drivers consume CPU time while waiting; there is no IRQ-driven data path outside PS/2, serial and the PIT.</li>
 			<li><strong>EHCI.</strong> High-speed root ports only; no split transactions for low/full-speed devices behind a high-speed hub.</li>
 			<li><strong>xHCI.</strong> USB2 and USB3 root ports; USB2 hubs behind xHCI work through the route string (a QEMU hub+mouse cursor test covers it), but USB3 hub port-status decoding is not implemented.</li>
-			<li><strong>HID.</strong> Generic report IDs are not handled (a device that prepends report IDs decodes as garbage; the Logitech Unifying DJ receiver is decoded explicitly), absolute pointers/tablets are ignored, and boot mice have no wheel (the DJ path maps it).</li>
+			<li><strong>HID.</strong> A report-protocol mouse with a wheel is decoded from its descriptor, including report IDs; a report-protocol keyboard or a wheel-less report-protocol mouse still assumes the fixed boot layout, so an unusual report ID there decodes as garbage. A descriptor longer than the 240-byte read window with its wheel beyond it keeps the boot layout (no wheel). The Logitech Unifying DJ receiver is decoded explicitly, and absolute pointers/tablets are ignored.</li>
 			<li><strong>AHCI.</strong> First controller only, no hotplug after boot, disks above 2 TB are clamped to 32-bit LBA.</li>
 			<li><strong>eMMC.</strong> Polled 1-bit/25 MHz PIO; no DMA, IRQ, CMD6 bus-width/high-speed/DDR switch or hotplug. Only the eMMC function is driven; the SDIO/SD functions and SD card reader are not.</li>
 			<li><strong>Storage serialization.</strong> A FAT/floppy operation sets <code>sys_fs_busy</code> and stalls process switching for its duration; the PIT keeps ticking.</li>
@@ -812,6 +817,8 @@
 			<li><code>kernel/install.c</code> — live-image clone installer</li>
 			<li><code>kernel/backlight.c</code>, <code>kernel/backlight.h</code> — Cherryview/Braswell panel PWM</li>
 			<li><code>kernel/usbhid.c</code>, <code>kernel/mouse.c</code>, <code>kernel/io.c</code> — input</li>
+			<li><code>kernel/hid_report.c</code>, <code>kernel/hid_report.h</code> — HID mouse report-descriptor parser (report protocol wheel)</li>
+			<li><code>kernel/hid_report_test.c</code> — host test (<code>make test-hid</code>)</li>
 			<li><code>kernel/i2c.c</code>, <code>kernel/i2c.h</code> — DesignWare/LPSS I2C master</li>
 			<li><code>kernel/touchpad.c</code>, <code>kernel/touchpad.h</code> — Elan/Synaptics HID-over-I2C touchpads</li>
 			<li><code>kernel/touchpad_gesture.c</code>, <code>kernel/touchpad_gesture.h</code> — device-independent contact gestures (tap, right-click zones, scroll)</li>

+ 2 - 0
include/syscall.h

@@ -568,6 +568,8 @@ struct sys_mouseinfo {
 	unsigned int usb_mps;
 	unsigned int usb_low;
 	unsigned int usb_keyboard;
+	unsigned int usb_report;   /* 0 boot, 1 report, 2 Logitech DJ */
+	unsigned int usb_wheel;    /* the active USB mouse has a wheel */
 	unsigned int cursor_visible;
 	char hcd[8];
 	char backend[16];

+ 400 - 0
kernel/hid_report.c

@@ -0,0 +1,400 @@
+/* Minimal HID report-descriptor parser for mouse reports.
+ *
+ * See hid_report.h.  The item walk keeps a global state (usage page, report
+ * size/count, logical minimum and report ID), a small push/pop stack and the
+ * local usages of the current main item.  Input items advance one bit
+ * position per report ID, so interleaved report IDs and non-byte-aligned
+ * fields (12-bit axes, 5 buttons + 3 bits of padding, ...) decode correctly.
+ */
+#include "hid_report.h"
+
+#define MAX_REPORTS 8
+#define MAX_USAGES  16
+#define MAX_PUSH    4
+
+/* Item type/tag values from the HID specification (6.2.2). */
+#define IT_MAIN   0u
+#define IT_GLOBAL 1u
+#define IT_LOCAL  2u
+
+#define GT_USAGE_PAGE   0x0u
+#define GT_LOGICAL_MIN  0x1u
+#define GT_REPORT_SIZE  0x7u
+#define GT_REPORT_ID    0x8u
+#define GT_REPORT_COUNT 0x9u
+#define GT_PUSH         0xAu
+#define GT_POP          0xBu
+
+#define LT_USAGE        0x0u
+#define LT_USAGE_MIN    0x1u
+#define LT_USAGE_MAX    0x2u
+
+#define MT_INPUT        0x8u
+
+/* Generic Desktop usages. */
+#define UD_X      0x30u
+#define UD_Y      0x31u
+#define UD_WHEEL  0x38u
+
+struct global {
+	unsigned int usage_page;
+	unsigned int report_size;
+	unsigned int report_count;
+	unsigned int report_id;
+	int logical_min;
+};
+
+struct report {
+	unsigned int id;
+	unsigned int bit;             /* next free input bit */
+	unsigned int x_off, y_off, wheel_off;
+	unsigned int x_size, y_size, wheel_size;
+	unsigned int x_signed, y_signed, wheel_signed;
+	unsigned int have_x, have_y, have_wheel;
+	unsigned int btn_bit[8];      /* bit offset + 1, 0 = absent */
+};
+
+static unsigned int item_u(const unsigned char *d, unsigned int pos,
+			   unsigned int size)
+{
+	unsigned int v = 0, k;
+
+	for (k = 0; k < size; k++)
+		v |= (unsigned int)d[pos + k] << (8u * k);
+	return v;
+}
+
+static int item_s(const unsigned char *d, unsigned int pos, unsigned int size)
+{
+	unsigned int v = item_u(d, pos, size);
+
+	if (size && size < 4 && (v & (1u << (8u * size - 1u))))
+		v |= ~0u << (8u * size);
+	return (int)v;
+}
+
+static unsigned int bits(const unsigned char *rep, unsigned int off,
+			 unsigned int size)
+{
+	unsigned int v = 0, i;
+
+	for (i = 0; i < size; i++)
+		if (rep[(off + i) >> 3] & (1u << ((off + i) & 7u)))
+			v |= 1u << i;
+	return v;
+}
+
+static int sbits(const unsigned char *rep, unsigned int off, unsigned int size)
+{
+	unsigned int v;
+
+	if (!size)
+		return 0;
+	v = bits(rep, off, size);
+	if (size < 32 && (v & (1u << (size - 1u))))
+		v |= ~0u << size;
+	return (int)v;
+}
+
+static struct report *report_for(struct report *reps, unsigned int *count,
+				 unsigned int id)
+{
+	unsigned int i;
+
+	for (i = 0; i < *count; i++) {
+		if (reps[i].id == id)
+			return &reps[i];
+	}
+	if (*count >= MAX_REPORTS)
+		return 0;
+	reps[*count].id = id;
+	reps[*count].bit = 0;
+	(*count)++;
+	return &reps[*count - 1];
+}
+
+/* Record one field of an Input item.  `off` is the field's first bit and
+ * `size` its width.  Only the fields needed for a mouse are kept. */
+static void add_field(struct report *r, unsigned int page,
+		      unsigned int usage, unsigned int off, unsigned int size,
+		      int signed_value)
+{
+	if (off + size > HID_REPORT_MAX * 8u)
+		return;
+
+	if (page == 0x01u) {
+		if (size > 32u)
+			return;
+		if (usage == UD_X && !r->have_x && size) {
+			r->x_off = off;
+			r->x_size = size;
+			r->x_signed = signed_value != 0;
+			r->have_x = 1;
+		} else if (usage == UD_Y && !r->have_y && size) {
+			r->y_off = off;
+			r->y_size = size;
+			r->y_signed = signed_value != 0;
+			r->have_y = 1;
+		} else if (usage == UD_WHEEL && !r->have_wheel && size) {
+			r->wheel_off = off;
+			r->wheel_size = size;
+			r->wheel_signed = signed_value != 0;
+			r->have_wheel = 1;
+		}
+	} else if (page == 0x09u && usage >= 1u && usage <= 8u && size == 1u) {
+		if (!r->btn_bit[usage - 1u] && off < 255u)
+			r->btn_bit[usage - 1u] = off + 1u;
+	}
+}
+
+int hid_parse_mouse(const unsigned char *desc, unsigned int len,
+		    struct hid_mouse_layout *out)
+{
+	struct global g, stack[MAX_PUSH];
+	struct report reps[MAX_REPORTS];
+	unsigned int local[MAX_USAGES];
+	unsigned int nlocal = 0;
+	unsigned int usemin = 0, usemax = 0;
+	unsigned int have_min = 0, have_max = 0;
+	unsigned int nreps = 0, any_id = 0, depth = 0;
+	unsigned int i = 0, k;
+
+	if (!desc || !out || len < 2)
+		return 0;
+	for (i = 0; i < sizeof(*out); i++)
+		((unsigned char *)out)[i] = 0;
+	for (i = 0; i < sizeof(reps); i++)
+		((unsigned char *)reps)[i] = 0;
+	for (i = 0; i < sizeof(g); i++)
+		((unsigned char *)&g)[i] = 0;
+	i = 0;
+
+	while (i < len) {
+		unsigned int item = desc[i++];
+		unsigned int size = item & 3u;
+		unsigned int type = (item >> 2) & 3u;
+		unsigned int tag = (item >> 4) & 0xFu;
+		unsigned int pos = i;
+		unsigned int data = 0;
+
+		if (size == 3u)
+			size = 4u;
+		if (i + size > len)
+			break;          /* truncated tail */
+		if (size)
+			data = item_u(desc, pos, size);
+		i += size;
+
+		if (type == IT_GLOBAL) {
+			switch (tag) {
+			case GT_USAGE_PAGE:
+				g.usage_page = data;
+				break;
+			case GT_LOGICAL_MIN:
+				g.logical_min = item_s(desc, pos, size);
+				break;
+			case GT_REPORT_SIZE:
+				g.report_size = data;
+				break;
+			case GT_REPORT_ID:
+				g.report_id = data & 0xFFu;
+				any_id = 1;
+				break;
+			case GT_REPORT_COUNT:
+				g.report_count = data;
+				break;
+			case GT_PUSH:
+				if (depth < MAX_PUSH)
+					stack[depth++] = g;
+				break;
+			case GT_POP:
+				if (depth)
+					g = stack[--depth];
+				break;
+			default:
+				break;
+			}
+		} else if (type == IT_LOCAL) {
+			if (tag == LT_USAGE) {
+				unsigned int page = g.usage_page;
+				unsigned int usage = data;
+
+				/* A four-byte Usage carries its own page. */
+				if (size == 4) {
+					page = data >> 16;
+					usage = data & 0xFFFFu;
+				}
+				if (nlocal < MAX_USAGES)
+					local[nlocal++] = (page << 16) | usage;
+			} else if (tag == LT_USAGE_MIN || tag == LT_USAGE_MAX) {
+				unsigned int page = g.usage_page;
+				unsigned int usage = data;
+
+				if (size == 4) {
+					page = data >> 16;
+					usage = data & 0xFFFFu;
+				}
+				if (tag == LT_USAGE_MIN) {
+					usemin = (page << 16) | usage;
+					have_min = 1;
+				} else {
+					usemax = (page << 16) | usage;
+					have_max = 1;
+				}
+			}
+		} else if (type == IT_MAIN) {
+			if (tag == MT_INPUT) {
+				struct report *r = report_for(reps, &nreps,
+							      g.report_id);
+				unsigned int variable = (data & 0x02u) != 0;
+				unsigned int constant = (data & 0x01u) != 0;
+				unsigned int fsize = g.report_size;
+				unsigned int count = g.report_count;
+				unsigned int total;
+
+				if (fsize && count > 0xFFFFu / fsize)
+					return 0;       /* malformed count */
+				total = fsize * count;
+				if (r && variable && !constant) {
+					for (k = 0; k < count; k++) {
+						unsigned int usage = 0;
+						unsigned int page;
+						int have = 0;
+
+						if (k < nlocal) {
+							usage = local[k];
+							have = 1;
+						} else if (have_min && have_max) {
+							unsigned int min_id =
+								usemin & 0xFFFFu;
+							unsigned int max_id =
+								usemax & 0xFFFFu;
+							unsigned int id = min_id + k;
+
+							if ((usemin >> 16) ==
+							    (usemax >> 16) &&
+							    id <= max_id) {
+								usage = (usemin &
+									 0xFFFF0000u) | id;
+								have = 1;
+							}
+						}
+						if (!have)
+							continue;
+						page = usage >> 16;
+						add_field(r, page,
+							  usage & 0xFFFFu,
+							  r->bit + k * fsize,
+							  fsize,
+							  g.logical_min < 0);
+					}
+				}
+				if (r)
+					r->bit += total;
+			}
+			/* Local items apply to one main item only. */
+			nlocal = 0;
+			have_min = have_max = 0;
+		}
+	}
+
+	/* Prefer a report that carries a wheel; otherwise the first one with
+	 * both axes is still a usable wheel-less mouse layout. */
+	{
+		struct report *pick = 0;
+		unsigned int end = 0;
+
+		for (k = 0; k < nreps; k++) {
+			struct report *r = &reps[k];
+
+			if (!r->have_x || !r->have_y)
+				continue;
+			if (!pick)
+				pick = r;
+			if (r->have_wheel) {
+				pick = r;
+				break;
+			}
+		}
+		if (!pick)
+			return 0;
+
+		out->x_off = (unsigned short)pick->x_off;
+		out->y_off = (unsigned short)pick->y_off;
+		out->wheel_off = (unsigned short)pick->wheel_off;
+		out->x_size = (unsigned char)pick->x_size;
+		out->y_size = (unsigned char)pick->y_size;
+		out->wheel_size = (unsigned char)pick->wheel_size;
+		out->report_id = (unsigned char)pick->id;
+		out->flags = HID_ML_VALID;
+		if (any_id && pick->id)
+			out->flags |= HID_ML_HAS_ID;
+		if (pick->x_signed)
+			out->flags |= HID_ML_X_SIGNED;
+		if (pick->y_signed)
+			out->flags |= HID_ML_Y_SIGNED;
+		if (pick->wheel_signed)
+			out->flags |= HID_ML_WHEEL_SIGNED;
+		for (k = 0; k < 8; k++)
+			out->btn_bit[k] = (unsigned char)pick->btn_bit[k];
+
+		end = pick->x_off + pick->x_size;
+		if (pick->y_off + pick->y_size > end)
+			end = pick->y_off + pick->y_size;
+		if (pick->have_wheel &&
+		    pick->wheel_off + pick->wheel_size > end)
+			end = pick->wheel_off + pick->wheel_size;
+		for (k = 0; k < 8; k++) {
+			if (pick->btn_bit[k] &&
+			    pick->btn_bit[k] > end)
+				end = pick->btn_bit[k];
+		}
+		out->report_bytes = (unsigned char)((end + 7u) / 8u);
+		if (out->flags & HID_ML_HAS_ID)
+			out->report_bytes++;
+		if (out->report_bytes > HID_REPORT_MAX)
+			return 0;
+	}
+	return 1;
+}
+
+int hid_mouse_decode(const struct hid_mouse_layout *l,
+		     const unsigned char *rep, unsigned int len,
+		     struct hid_mouse_frame *out)
+{
+	unsigned int base = 0, i;
+
+	if (!l || !rep || !out || !(l->flags & HID_ML_VALID))
+		return 0;
+	if (len < l->report_bytes)
+		return 0;
+	if (l->flags & HID_ML_HAS_ID) {
+		if (rep[0] != l->report_id)
+			return 0;
+		base = 8;
+	}
+
+	out->buttons = 0;
+	for (i = 0; i < 8; i++) {
+		unsigned int off;
+
+		if (!l->btn_bit[i])
+			continue;
+		off = base + l->btn_bit[i] - 1u;
+		if (rep[off >> 3] & (1u << (off & 7u)))
+			out->buttons |= 1u << i;
+	}
+	out->dx = (l->flags & HID_ML_X_SIGNED)
+		? sbits(rep, base + l->x_off, l->x_size)
+		: (int)bits(rep, base + l->x_off, l->x_size);
+	out->dy = (l->flags & HID_ML_Y_SIGNED)
+		? sbits(rep, base + l->y_off, l->y_size)
+		: (int)bits(rep, base + l->y_off, l->y_size);
+	out->wheel = 0;
+	if (l->wheel_size) {
+		out->wheel = (l->flags & HID_ML_WHEEL_SIGNED)
+			? sbits(rep, base + l->wheel_off, l->wheel_size)
+			: (int)bits(rep, base + l->wheel_off, l->wheel_size);
+	}
+	return 1;
+}

+ 56 - 0
kernel/hid_report.h

@@ -0,0 +1,56 @@
+/* Minimal HID report-descriptor parser for mouse reports.
+ *
+ * usbhid.c uses this to find a wheel (Generic Desktop usage 0x38) and the
+ * exact bit offsets of the mouse fields.  A USB boot mouse has no wheel
+ * field in its boot report, so a mouse whose report descriptor advertises
+ * one is switched to report protocol and decoded through this layout.  When
+ * the descriptor has no wheel, or the parser cannot make sense of it, the
+ * caller keeps the fixed boot-protocol decoder.
+ *
+ * Only the Input items a mouse needs are interpreted (buttons, X, Y, Wheel);
+ * the rest of the descriptor is skipped by its item size.  The parser is
+ * freestanding and has a host test (make test-hid).
+ */
+#ifndef HID_REPORT_H
+#define HID_REPORT_H
+
+/* A report longer than this cannot be received through the interrupt-IN
+ * path (USB_INT_MAX in usb_hcd.h), so the layout is rejected. */
+#define HID_REPORT_MAX 32
+
+/* Mouse layout flags. */
+#define HID_ML_VALID        0x01u   /* X and Y found; layout usable */
+#define HID_ML_HAS_ID       0x02u   /* reports start with report_id */
+#define HID_ML_X_SIGNED     0x04u
+#define HID_ML_Y_SIGNED     0x08u
+#define HID_ML_WHEEL_SIGNED 0x10u
+
+struct hid_mouse_layout {
+	unsigned short x_off, y_off, wheel_off;   /* bits, after the ID byte */
+	unsigned char x_size, y_size, wheel_size;
+	unsigned char flags;
+	unsigned char report_id;
+	unsigned char report_bytes;               /* including the ID byte */
+	unsigned char btn_bit[8];                 /* bit offset + 1, 0 = absent */
+};
+
+struct hid_mouse_frame {
+	unsigned int buttons;   /* bit0 left, bit1 right, bit2 middle, ... */
+	int dx, dy;             /* HID report values: +dy is down */
+	int wheel;              /* notches, +1 = away from the user */
+};
+
+/* Parse a report descriptor.  Returns 1 and fills `out` when a mouse report
+ * with X and Y was found; a layout with wheel_size != 0 also has a wheel.
+ * Returns 0 for a descriptor that is not a usable mouse layout. */
+int hid_parse_mouse(const unsigned char *desc, unsigned int len,
+		    struct hid_mouse_layout *out);
+
+/* Decode one report-protocol report through `layout`.  Returns 1 when the
+ * report belongs to the mouse report ID and carries every field the layout
+ * needs, 0 otherwise. */
+int hid_mouse_decode(const struct hid_mouse_layout *layout,
+		     const unsigned char *rep, unsigned int len,
+		     struct hid_mouse_frame *out);
+
+#endif

+ 225 - 0
kernel/hid_report_test.c

@@ -0,0 +1,225 @@
+/* Host-side checks for the HID mouse report-descriptor parser. */
+#include <stdio.h>
+#include <string.h>
+
+#include "hid_report.h"
+
+static int failures;
+
+static void check(const char *name, int cond)
+{
+	printf("%s: %s\n", cond ? "ok" : "FAIL", name);
+	if (!cond)
+		failures++;
+}
+
+/* Standard three-button mouse: buttons, 5 bits padding, X/Y/Wheel. */
+static const unsigned char desc_std[] = {
+	0x05, 0x01, 0x09, 0x02, 0xA1, 0x01,
+	0x09, 0x01, 0xA1, 0x00,
+	0x05, 0x09, 0x19, 0x01, 0x29, 0x03, 0x15, 0x00, 0x25, 0x01,
+	0x95, 0x03, 0x75, 0x01, 0x81, 0x02,
+	0x95, 0x01, 0x75, 0x05, 0x81, 0x01,
+	0x05, 0x01, 0x09, 0x30, 0x09, 0x31, 0x09, 0x38,
+	0x15, 0x81, 0x25, 0x7F, 0x75, 0x08, 0x95, 0x03, 0x81, 0x06,
+	0xC0, 0xC0
+};
+
+/* Report ID 2, five buttons, 16-bit X/Y, 8-bit wheel. */
+static const unsigned char desc16[] = {
+	0x05, 0x01, 0x09, 0x02, 0xA1, 0x01,
+	0x85, 0x02,
+	0x05, 0x09, 0x19, 0x01, 0x29, 0x05, 0x15, 0x00, 0x25, 0x01,
+	0x95, 0x05, 0x75, 0x01, 0x81, 0x02,
+	0x95, 0x03, 0x75, 0x01, 0x81, 0x01,
+	0x05, 0x01, 0x09, 0x30, 0x09, 0x31,
+	0x16, 0x00, 0x80, 0x26, 0xFF, 0x7F,
+	0x75, 0x10, 0x95, 0x02, 0x81, 0x06,
+	0x09, 0x38, 0x15, 0x81, 0x25, 0x7F,
+	0x75, 0x08, 0x95, 0x01, 0x81, 0x06,
+	0xC0
+};
+
+/* Five buttons, 12-bit X/Y and an 8-bit wheel (a gaming mouse). */
+static const unsigned char desc12[] = {
+	0x05, 0x01, 0x09, 0x02, 0xA1, 0x01,
+	0x05, 0x09, 0x19, 0x01, 0x29, 0x05, 0x15, 0x00, 0x25, 0x01,
+	0x95, 0x05, 0x75, 0x01, 0x81, 0x02,
+	0x95, 0x03, 0x75, 0x01, 0x81, 0x01,
+	0x05, 0x01, 0x09, 0x30, 0x09, 0x31,
+	0x15, 0x81, 0x25, 0x7F,
+	0x75, 0x0C, 0x95, 0x02, 0x81, 0x06,
+	0x09, 0x38, 0x15, 0x81, 0x25, 0x7F,
+	0x75, 0x08, 0x95, 0x01, 0x81, 0x06,
+	0xC0
+};
+
+/* X/Y through Usage Minimum/Maximum, no wheel. */
+static const unsigned char desc_minmax[] = {
+	0x05, 0x01, 0x09, 0x02, 0xA1, 0x01,
+	0x05, 0x09, 0x19, 0x01, 0x29, 0x03, 0x15, 0x00, 0x25, 0x01,
+	0x95, 0x03, 0x75, 0x01, 0x81, 0x02,
+	0x95, 0x01, 0x75, 0x05, 0x81, 0x01,
+	0x05, 0x01, 0x15, 0x81, 0x25, 0x7F,
+	0x19, 0x30, 0x29, 0x31,
+	0x75, 0x08, 0x95, 0x02, 0x81, 0x06,
+	0xC0
+};
+
+static void test_std(void)
+{
+	struct hid_mouse_layout l;
+	struct hid_mouse_frame f;
+	unsigned char rep[4];
+
+	memset(&l, 0, sizeof(l));
+	check("std: parses", hid_parse_mouse(desc_std, sizeof(desc_std), &l));
+	check("std: no report id", !(l.flags & HID_ML_HAS_ID));
+	check("std: buttons 1..3",
+	      l.btn_bit[0] == 1 && l.btn_bit[1] == 2 && l.btn_bit[2] == 3);
+	check("std: button 4 absent", l.btn_bit[3] == 0);
+	check("std: field offsets",
+	      l.x_off == 8 && l.y_off == 16 && l.wheel_off == 24);
+	check("std: field sizes",
+	      l.x_size == 8 && l.y_size == 8 && l.wheel_size == 8);
+	check("std: all signed",
+	      (l.flags & (HID_ML_X_SIGNED | HID_ML_Y_SIGNED |
+			  HID_ML_WHEEL_SIGNED)) ==
+	      (HID_ML_X_SIGNED | HID_ML_Y_SIGNED | HID_ML_WHEEL_SIGNED));
+	check("std: report is 4 bytes", l.report_bytes == 4);
+
+	memset(&f, 0, sizeof(f));
+	rep[0] = 0x05;          /* left + middle */
+	rep[1] = 0xF6;          /* -10 */
+	rep[2] = 0x14;          /* +20 */
+	rep[3] = 0x01;          /* wheel away */
+	check("std: decodes",
+	      hid_mouse_decode(&l, rep, sizeof(rep), &f));
+	check("std: frame",
+	      f.buttons == 0x05 && f.dx == -10 && f.dy == 20 && f.wheel == 1);
+
+	rep[3] = 0xFF;
+	check("std: negative wheel",
+	      hid_mouse_decode(&l, rep, sizeof(rep), &f) && f.wheel == -1);
+	check("std: short report rejected",
+	      !hid_mouse_decode(&l, rep, 3, &f));
+}
+
+static void test_report_id(void)
+{
+	struct hid_mouse_layout l;
+	struct hid_mouse_frame f;
+	unsigned char rep[7];
+
+	memset(&l, 0, sizeof(l));
+	check("id16: parses", hid_parse_mouse(desc16, sizeof(desc16), &l));
+	check("id16: report id 2",
+	      (l.flags & HID_ML_HAS_ID) && l.report_id == 2);
+	check("id16: field offsets",
+	      l.x_off == 8 && l.y_off == 24 && l.wheel_off == 40);
+	check("id16: field sizes",
+	      l.x_size == 16 && l.y_size == 16 && l.wheel_size == 8);
+	check("id16: report is 7 bytes", l.report_bytes == 7);
+
+	rep[0] = 2;
+	rep[1] = 0x03;
+	rep[2] = 0x18; rep[3] = 0xFC;   /* -1000 */
+	rep[4] = 0xE8; rep[5] = 0x03;   /* +1000 */
+	rep[6] = 0xFF;                  /* -1 */
+	check("id16: decodes",
+	      hid_mouse_decode(&l, rep, sizeof(rep), &f));
+	check("id16: frame",
+	      f.buttons == 0x03 && f.dx == -1000 && f.dy == 1000 &&
+	      f.wheel == -1);
+
+	rep[0] = 1;
+	check("id16: other report id ignored",
+	      !hid_mouse_decode(&l, rep, sizeof(rep), &f));
+	rep[0] = 2;
+	check("id16: short report rejected",
+	      !hid_mouse_decode(&l, rep, 6, &f));
+}
+
+static void test_12bit(void)
+{
+	struct hid_mouse_layout l;
+	struct hid_mouse_frame f;
+	unsigned char rep[5];
+
+	memset(&l, 0, sizeof(l));
+	check("12: parses", hid_parse_mouse(desc12, sizeof(desc12), &l));
+	check("12: field offsets",
+	      l.x_off == 8 && l.y_off == 20 && l.wheel_off == 32);
+	check("12: field sizes",
+	      l.x_size == 12 && l.y_size == 12 && l.wheel_size == 8);
+	check("12: report is 5 bytes", l.report_bytes == 5);
+	check("12: five buttons",
+	      l.btn_bit[0] == 1 && l.btn_bit[1] == 2 &&
+	      l.btn_bit[2] == 3 && l.btn_bit[3] == 4 && l.btn_bit[4] == 5);
+
+	rep[0] = 0x05;
+	rep[1] = 0xFB;          /* X low 8 */
+	rep[2] = 0x4F;          /* X high 4, Y low 4 */
+	rep[3] = 0x06;          /* Y high 8 */
+	rep[4] = 0x01;          /* wheel */
+	check("12: decodes",
+	      hid_mouse_decode(&l, rep, sizeof(rep), &f));
+	check("12: frame",
+	      f.buttons == 0x05 && f.dx == -5 && f.dy == 100 &&
+	      f.wheel == 1);
+}
+
+static void test_no_wheel(void)
+{
+	struct hid_mouse_layout l;
+	struct hid_mouse_frame f;
+	unsigned char rep[3];
+
+	memset(&l, 0, sizeof(l));
+	check("minmax: parses", hid_parse_mouse(desc_minmax,
+						sizeof(desc_minmax), &l));
+	check("minmax: X/Y", l.x_off == 8 && l.y_off == 16);
+	check("minmax: no wheel", l.wheel_size == 0);
+	check("minmax: report is 3 bytes", l.report_bytes == 3);
+
+	rep[0] = 0;
+	rep[1] = 5;
+	rep[2] = 0xFB;
+	check("minmax: decodes",
+	      hid_mouse_decode(&l, rep, sizeof(rep), &f));
+	check("minmax: frame", !f.buttons && f.dx == 5 && f.dy == -5 &&
+	      !f.wheel);
+}
+
+static void test_invalid(void)
+{
+	struct hid_mouse_layout l;
+	struct hid_mouse_frame f;
+	unsigned char rep[4] = { 0 };
+
+	memset(&l, 0, sizeof(l));
+	check("invalid: empty descriptor", !hid_parse_mouse(rep, 0, &l));
+	check("invalid: one byte", !hid_parse_mouse(rep, 1, &l));
+	check("invalid: truncated tail does not crash",
+	      hid_parse_mouse(desc_std, sizeof(desc_std) / 2, &l) == 0 ||
+	      (l.flags & HID_ML_VALID));
+	memset(&l, 0, sizeof(l));
+	check("invalid: no layout rejects decode",
+	      !hid_mouse_decode(&l, rep, sizeof(rep), &f));
+}
+
+int main(void)
+{
+	test_std();
+	test_report_id();
+	test_12bit();
+	test_no_wheel();
+	test_invalid();
+
+	if (failures) {
+		printf("%d check(s) failed\n", failures);
+		return 1;
+	}
+	printf("all HID report checks passed\n");
+	return 0;
+}

+ 17 - 5
kernel/mouse.c

@@ -3,6 +3,7 @@
 #include "cirrus.h"
 #include "cursor.h"
 #include "intel.h"
+#include "mm.h"
 #include "radeon.h"
 #include "timer.h"
 #include "touchpad.h"
@@ -40,7 +41,13 @@ static unsigned int fbw, fbh;
 static unsigned int cur_x, cur_y;
 static unsigned int saved_x, saved_y, saved_w, saved_h;
 static int saved_ox, saved_oy;       /* unclipped image origin of the save */
-static unsigned char cur_saved[CURSOR_MAX_DIM * CURSOR_MAX_DIM * 4];
+/* The software cursor's background save is exactly one frame (4 KB at
+ * CURSOR_MAX_DIM 32) and is only needed when no hardware cursor exists, so
+ * it lives in a page instead of moving the kernel's BSS wall. */
+static unsigned char *cur_saved;
+#if CURSOR_MAX_DIM * CURSOR_MAX_DIM * 4 > 4096
+#error "software cursor save buffer exceeds one page"
+#endif
 static struct cursor_image cur_img;  /* the frame on screen */
 static int cur_shape = CURSOR_DEFAULT;
 static unsigned int cur_frame, cur_frame_ms;
@@ -209,13 +216,13 @@ static void cursor_save_under(void)
 	cursor_calc_rect(&saved_x, &saved_y, &saved_w, &saved_h);
 	saved_ox = (int)cur_x - (int)cur_img.hot_x;
 	saved_oy = (int)cur_y - (int)cur_img.hot_y;
-	if (saved_w && saved_h)
+	if (saved_w && saved_h && cur_saved)
 		vga_fb_read_rect(saved_x, saved_y, saved_w, saved_h, cur_saved);
 }
 
 static void cursor_restore_under(void)
 {
-	if (saved_w && saved_h)
+	if (saved_w && saved_h && cur_saved)
 		vga_fb_write_rect(saved_x, saved_y, saved_w, saved_h, cur_saved);
 }
 
@@ -235,7 +242,7 @@ static void mouse_draw_cursor(void)
 	unsigned int pb = vga_fb_bpp() == 16 ? 2u : vga_fb_bpp() == 24 ? 3u : 4u;
 	unsigned int r, c;
 
-	if (!cur_img.px)
+	if (!cur_img.px || !cur_saved)
 		return;
 	for (r = 0; r < saved_h; r++) {
 		unsigned int iy = saved_y + r - (unsigned int)saved_oy;
@@ -473,6 +480,10 @@ static void mouse_cursor_setup(void)
 	   the display engine (see nv50.c); the software cursor is used. */
 
 	mouse_hw_cursor = 0;
+	if (!cur_saved)
+		cur_saved = (unsigned char *)mm_alloc_page();
+	if (!cur_saved)
+		return;
 	cur_x = 100;
 	cur_y = 100;
 	{
@@ -620,7 +631,8 @@ static void mouse_handle_packet(void)
 		return;
 	mouse_move(dx, dy);
 	if (mouse_pkt_size >= 4) {
-		/* IntelliMouse wheel: +1 is toward the user (later content). */
+		/* IntelliMouse wheel: +1 is toward the user (later content),
+		 * the opposite raw sign of the HID report's Wheel usage. */
 		int wheel = (int)(signed char)pkt[3];
 
 		if (wheel)

+ 5 - 2
kernel/sys_info.c

@@ -85,12 +85,15 @@ int sys_mouseinfo(struct sys_mouseinfo *out)
 	out->usb = usbhid_mouse_attached() ? 1 : 0;
 	if (out->usb) {
 		unsigned int ep, mps;
-		int low;
+		int low, report, wheel;
 
-		usbhid_get_info(&out->usb_ctrl, &out->usb_addr, &ep, &mps, &low);
+		usbhid_get_info(&out->usb_ctrl, &out->usb_addr, &ep, &mps, &low,
+				&report, &wheel);
 		out->usb_ep = ep;
 		out->usb_mps = mps;
 		out->usb_low = (unsigned int)low;
+		out->usb_report = (unsigned int)report;
+		out->usb_wheel = wheel ? 1u : 0u;
 		copy_str(out->hcd, usb_hcd_name_ctrl(out->usb_ctrl),
 			 sizeof(out->hcd));
 	}

+ 129 - 31
kernel/usbhid.c

@@ -14,7 +14,9 @@
  * keyboard.  Root ports are watched so devices can be plugged in later. */
 
 #include "usbhid.h"
+#include "hid_report.h"
 #include "io.h"
+#include "mm.h"
 #include "usb.h"
 #include "serial.h"
 #include "timer.h"
@@ -33,8 +35,19 @@
 /* Extended (0xE0-prefixed) PS/2 make codes in the mapping table. */
 #define K_EXT 0xE000u
 
-/* How much of a report descriptor to read for classification. */
-#define REPORT_MAX 64
+/* Report descriptors are read into one frame.  240 bytes is the largest
+ * control-IN transfer UHCI can build at an 8-byte EP0 (30 TDs), and it
+ * covers every ordinary mouse descriptor; a longer one is parsed from its
+ * first part, and the boot decoder stays the fallback if the wheel lies
+ * beyond it. */
+#define REPORT_MAX 240
+
+/* One PS/2/IntelliMouse wheel notch, shared with the DJ report path. */
+#define USB_WHEEL_PX 48
+
+#if HID_REPORT_MAX > USB_INT_MAX
+#error "HID mouse layout exceeds the interrupt-IN report buffer"
+#endif
 
 enum { KIND_FREE = 0, KIND_MOUSE, KIND_KBD, KIND_DJ };
 
@@ -47,6 +60,8 @@ struct hid_dev {
 	int low;
 	unsigned int err;         /* consecutive transfer errors */
 	unsigned int disc;        /* consecutive "port disconnected" reads */
+	unsigned int report_mode; /* 1 = decode with layout, 0 = boot format */
+	struct hid_mouse_layout layout;
 	/* keyboard report-diff state */
 	unsigned char prev[6];
 	unsigned char prev_mod;
@@ -155,21 +170,13 @@ static void kbd_decode(struct hid_dev *d, const unsigned char *r)
 /* Minimal HID item walk: find a Generic Desktop (usage page 1) mouse or
    keyboard collection.  Mouse detection accepts a Mouse/Pointer collection
    or a relative X/Y input item (so absolute tablets are not claimed). */
-static unsigned int hid_classify(const struct usb_iface_info *in)
+static unsigned int hid_classify(const unsigned char *rep, unsigned int n)
 {
-	static unsigned char rep[REPORT_MAX];
-	int n, mouse = 0, kbd = 0;
+	int mouse = 0, kbd = 0;
 	unsigned int i = 0, page = 0;
 	int loc_mouse = 0, loc_kbd = 0, loc_xy = 0;
 
-	n = usb_control_in(in->ctrl, in->addr, in->mps, in->low_speed,
-			   RT_DEV2HOST_CLS_IF, REQ_GET_DESCRIPTOR,
-			   (unsigned short)(0x22u << 8),
-			   (unsigned short)in->iface_num, rep, sizeof(rep));
-	if (n <= 0)
-		return KIND_FREE;
-
-	while (i < (unsigned int)n) {
+	while (i < n) {
 		unsigned int item = rep[i++];
 		unsigned int size = item & 3u;
 		unsigned int type = (item >> 2) & 3u;
@@ -216,28 +223,62 @@ static unsigned int hid_classify(const struct usb_iface_info *in)
 
 /* --- manager ------------------------------------------------------------ */
 
+/* Read up to `cap` bytes of the interface's HID report descriptor.  The
+ * request stays within UHCI's 30-TD control limit for an 8-byte EP0. */
+static int read_report_desc(const struct usb_iface_info *in,
+			    unsigned char *buf, unsigned int cap)
+{
+	return usb_control_in(in->ctrl, in->addr, in->mps, in->low_speed,
+			      RT_DEV2HOST_CLS_IF, REQ_GET_DESCRIPTOR,
+			      (unsigned short)(0x22u << 8),
+			      (unsigned short)in->iface_num, buf, cap);
+}
+
 static int hid_probe(const struct usb_iface_info *in)
 {
 	struct hid_dev *d = 0;
+	struct hid_mouse_layout layout;
+	unsigned char *desc = 0;
+	unsigned int desc_len = 0;
 	unsigned int kind, i;
+	int layout_ok = 0;
 
 	if (in->cls != 0x03u || !in->ep_addr || !(in->ep_addr & 0x80u))
 		return 0;
 
+	for (i = 0; i < sizeof(layout); i++)
+		((unsigned char *)&layout)[i] = 0;
+
 	/* Logitech Unifying receiver: interface 2 is the HID++/DJ channel
 	 * that carries the paired device's reports.  Its vendor report
 	 * descriptor is not a mouse collection, so claim it explicitly. */
 	if (in->vendor == 0x046du && in->product == 0xc52bu &&
 	    in->iface_num == 2 && in->subcls == 0x00u && in->proto == 0x00u)
 		kind = KIND_DJ;
-	else if (in->subcls == 0x01u && in->proto == 0x02u)
-		kind = KIND_MOUSE;
 	else if (in->subcls == 0x01u && in->proto == 0x01u)
 		kind = KIND_KBD;
-	else
-		kind = hid_classify(in);
-	if (kind == KIND_FREE)
+	else {
+		int n;
+
+		desc = (unsigned char *)mm_alloc_page();
+		if (desc) {
+			n = read_report_desc(in, desc, REPORT_MAX);
+			if (n > 0)
+				desc_len = (unsigned int)n;
+		}
+		if (in->subcls == 0x01u && in->proto == 0x02u)
+			kind = KIND_MOUSE;
+		else
+			kind = desc_len ? hid_classify(desc, desc_len) :
+					  KIND_FREE;
+		if (kind == KIND_MOUSE && desc_len)
+			layout_ok = hid_parse_mouse(desc, desc_len, &layout);
+	}
+	if (kind == KIND_FREE) {
+		if (desc)
+			mm_free_page((unsigned int)desc);
 		return 0;
+	}
 
 	for (i = 0; i < USB_HCD_INT_SLOTS; i++) {
 		if (!devs[i].present && !devs[i].claimed) {
@@ -245,18 +286,41 @@ static int hid_probe(const struct usb_iface_info *in)
 			break;
 		}
 	}
-	if (!d)
+	if (!d) {
+		if (desc)
+			mm_free_page((unsigned int)desc);
 		return 0;   /* every slot is busy */
+	}
+	d->report_mode = 0;
+	d->layout.flags = 0;
 
 	/* The endpoint is unusable until the device is configured. */
 	usb_control_out(in->ctrl, in->addr, in->mps, in->low_speed,
 			RT_HOST2DEV_STD, REQ_SET_CONFIGURATION,
 			(unsigned short)(in->config_value & 0xFFu), 0);
-	/* Boot protocol for boot-class devices; a stall is tolerated. */
-	if (in->subcls == 0x01u)
+
+	/* A wheel lives only in the report descriptor: boot protocol has no
+	 * field for it.  Such a mouse runs in report protocol, and the fixed
+	 * boot layout stays the fallback for everything else (and for a
+	 * device that refuses the protocol switch). */
+	if (kind == KIND_MOUSE && layout_ok && layout.wheel_size) {
+		if (in->subcls != 0x01u ||
+		    usb_control_out(in->ctrl, in->addr, in->mps, in->low_speed,
+				    RT_HOST2DEV_CLS, REQ_SET_PROTOCOL, 1,
+				    in->iface_num) == 0)
+			d->report_mode = 1;
+		else
+			usb_control_out(in->ctrl, in->addr, in->mps,
+					in->low_speed, RT_HOST2DEV_CLS,
+					REQ_SET_PROTOCOL, 0, in->iface_num);
+	} else if (in->subcls == 0x01u) {
+		/* Boot protocol for boot-class devices; a stall is tolerated. */
 		usb_control_out(in->ctrl, in->addr, in->mps, in->low_speed,
 				RT_HOST2DEV_CLS, REQ_SET_PROTOCOL, 0,
 				in->iface_num);
+	}
+	if (desc)
+		mm_free_page((unsigned int)desc);
 
 	d->kind = kind;
 	d->ctrl = in->ctrl;
@@ -265,8 +329,12 @@ static int hid_probe(const struct usb_iface_info *in)
 	d->mps = in->ep_mps ? in->ep_mps : 8;
 	d->xfer = kind == KIND_DJ ? USB_INT_MAX :
 		  (in->ep_mps ? in->ep_mps : 8);
+	if (d->xfer > USB_INT_MAX)
+		d->xfer = USB_INT_MAX;
 	d->port = in->port;
 	d->low = in->low_speed;
+	if (layout_ok)
+		d->layout = layout;
 	d->claimed = 1;
 	return 1;
 }
@@ -298,6 +366,8 @@ static void dev_attach(struct hid_dev *d, unsigned int slot)
 	serial_putdec(SERIAL_COM1, d->addr);
 	serial_puts(SERIAL_COM1, " ep ");
 	serial_putdec(SERIAL_COM1, 0x80u | d->ep);
+	if (d->report_mode)
+		serial_puts(SERIAL_COM1, ", report protocol + wheel");
 	serial_puts(SERIAL_COM1, ")\n");
 }
 
@@ -439,7 +509,7 @@ static void dj_decode(const unsigned char *r, unsigned int n,
 	*dx += x;
 	*dy -= y;                  /* HID +y down; mouse.c expects +y up */
 	if (scroll)
-		*scroll -= (int)(signed char)p[5] * 48;
+		*scroll -= (int)(signed char)p[5] * USB_WHEEL_PX;
 	*got = 1;
 	if (!dj_seen) {
 		dj_seen = 1;
@@ -497,15 +567,36 @@ int usbhid_poll(unsigned int *buttons, int *dx, int *dy, int *scroll)
 			continue;
 		n = dev_poll(d, i, buf, sizeof(buf));
 		if (n >= 3 && d->kind == KIND_MOUSE) {
-			b |= buf[0] & 0x07u;
-			x += (int)(signed char)buf[1];
-			/* HID: +y is down; mouse.c expects +y = up. */
-			y -= (int)(signed char)buf[2];
-			got = 1;
-			if (!mouse_seen) {
-				mouse_seen = 1;
-				serial_puts(SERIAL_COM1,
+			if (d->report_mode) {
+				struct hid_mouse_frame f;
+
+				if (hid_mouse_decode(&d->layout, buf,
+						     (unsigned int)n, &f)) {
+					b |= f.buttons;
+					x += f.dx;
+					/* HID: +y is down; mouse.c expects
+					 * +y = up. */
+					y -= f.dy;
+					if (scroll)
+						*scroll -= f.wheel * USB_WHEEL_PX;
+					got = 1;
+					if (!mouse_seen) {
+						mouse_seen = 1;
+						serial_puts(SERIAL_COM1,
+						    "usbhid: first report-protocol mouse report\n");
+					}
+				}
+			} else {
+				b |= buf[0] & 0x07u;
+				x += (int)(signed char)buf[1];
+				/* HID: +y is down; mouse.c expects +y = up. */
+				y -= (int)(signed char)buf[2];
+				got = 1;
+				if (!mouse_seen) {
+					mouse_seen = 1;
+					serial_puts(SERIAL_COM1,
 					    "usbhid: first boot mouse report\n");
+				}
 			}
 		} else if (d->kind == KIND_DJ && n >= 10) {
 			dj_decode(buf, (unsigned int)n, &b, &x, &y,
@@ -547,7 +638,8 @@ int usbhid_keyboard_attached(void)
 }
 
 void usbhid_get_info(unsigned int *ctrl, unsigned int *addr,
-		     unsigned int *ep, unsigned int *mps, int *low)
+		     unsigned int *ep, unsigned int *mps, int *low,
+		     int *report_mode, int *wheel)
 {
 	unsigned int i;
 
@@ -562,6 +654,10 @@ void usbhid_get_info(unsigned int *ctrl, unsigned int *addr,
 			*ep = d->ep;
 			*mps = d->mps;
 			*low = d->low;
+			*report_mode = d->kind == KIND_DJ ? 2 :
+				       (int)d->report_mode;
+			*wheel = d->kind == KIND_DJ ||
+				 (d->report_mode && d->layout.wheel_size);
 			return;
 		}
 	}
@@ -570,4 +666,6 @@ void usbhid_get_info(unsigned int *ctrl, unsigned int *addr,
 	*ep = 0;
 	*mps = 0;
 	*low = 0;
+	*report_mode = 0;
+	*wheel = 0;
 }

+ 7 - 4
kernel/usbhid.h

@@ -18,16 +18,19 @@ void usbhid_init(void);
 /* Service all endpoints (called once per WM loop iteration from
    mouse_poll_update()).  Returns 1 when a mouse report is available and
    fills buttons/dx/dy (PS/2 sign convention: dy > 0 = up) plus scroll in
-   pixels (boot-protocol mice have no wheel field; the Logitech DJ path
-   maps one wheel notch to 48 px). */
+   pixels.  A mouse whose report descriptor has a wheel runs in report
+   protocol and maps one wheel notch to 48 px; Logitech DJ reports use the
+   same scale. */
 int usbhid_poll(unsigned int *buttons, int *dx, int *dy, int *scroll);
 
 int usbhid_mouse_attached(void);
 int usbhid_keyboard_attached(void);
 
 /* For `mouseinfo`: controller instance, device address, endpoint number,
-   endpoint max packet size and the low-speed flag. */
+   endpoint max packet size, the low-speed flag, the report-protocol mode and
+   whether that layout has a wheel. */
 void usbhid_get_info(unsigned int *ctrl, unsigned int *addr,
-		     unsigned int *ep, unsigned int *mps, int *low);
+		     unsigned int *ep, unsigned int *mps, int *low,
+		     int *report_mode, int *wheel);
 
 #endif

+ 4 - 1
user/apps/mouseinfo/ucmd_mouseinfo.c

@@ -42,7 +42,8 @@ void _start(const char *arg)
 	if (m.usb) {
 		u_puts("mouse usb ");
 		u_puts(m.hcd);
-		u_puts(" hid boot\n");
+		u_puts(m.usb_report == 2 ? " hid dj\n" :
+		       m.usb_report ? " hid report\n" : " hid boot\n");
 		u_puts("mouse usb ctrl ");
 		u_putdec(m.usb_ctrl);
 		u_puts(" addr ");
@@ -53,6 +54,8 @@ void _start(const char *arg)
 		u_puts("mouse usb mps ");
 		u_putdec(m.usb_mps);
 		u_puts(m.usb_low ? " (low speed)\n" : " (full speed)\n");
+		u_puts("mouse usb wheel ");
+		u_puts(m.usb_wheel ? "yes\n" : "no\n");
 	}
 
 	if (m.touchpad) {