Explorar o código

Add Android USB tethering over RNDIS

Johannes Zellner hai 1 semana
pai
achega
97ef63715d
Modificáronse 13 ficheiros con 1094 adicións e 20 borrados
  1. 24 5
      AGENTS.md
  2. 13 3
      Makefile
  3. 1 0
      docs/development.html
  4. 17 1
      docs/drivers.html
  5. 1 1
      docs/index.html
  6. 17 4
      docs/network.html
  7. 2 0
      kernel.c
  8. 12 5
      netdev.c
  9. 977 0
      rndis.c
  10. 12 0
      rndis.h
  11. 6 1
      uhci.c
  12. 8 0
      usb.c
  13. 4 0
      usb.h

+ 24 - 5
AGENTS.md

@@ -61,6 +61,7 @@ make run-uhci   # like `make run` but with a UHCI controller + USB mouse
 make run-ehci   # EHCI + UHCI companion: high-speed storage on EHCI, HID on UHCI
 make run-ehci   # EHCI + UHCI companion: high-speed storage on EHCI, HID on UHCI
 make run-ehci-asix # pass through a real ASIX AX88772 dongle on EHCI
 make run-ehci-asix # pass through a real ASIX AX88772 dongle on EHCI
 make run-net    # like `make run` + a PCI NE2000 NIC on QEMU's user network (slirp; DHCP/DNS/NAT)
 make run-net    # like `make run` + a PCI NE2000 NIC on QEMU's user network (slirp; DHCP/DNS/NAT)
+make run-rndis  # xHCI + QEMU usb-net RNDIS tethering device on slirp (rndis netdev)
 make run-ahci   # like `make run` + an ICH9 AHCI controller and a 512 MB SATA disk (sata0)
 make run-ahci   # like `make run` + an ICH9 AHCI controller and a 512 MB SATA disk (sata0)
 make uefi       # build BOOTX64.EFI and the dual-boot usb-efi.img
 make uefi       # build BOOTX64.EFI and the dual-boot usb-efi.img
 make run-uefi   # boot usb-efi.img under OVMF (x86-64 UEFI; serial log in /tmp/opencode)
 make run-uefi   # boot usb-efi.img under OVMF (x86-64 UEFI; serial log in /tmp/opencode)
@@ -529,11 +530,14 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   global MAC reset while the link is up, because the PCH/ME wedges on the
   global MAC reset while the link is up, because the PCH/ME wedges on the
   CTRL_RST access), `r8168.c`
   CTRL_RST access), `r8168.c`
   RTL8111/8168 (PCIe, polled, C+ mode, 64-entry RX ring), `ne2000.c`
   RTL8111/8168 (PCIe, polled, C+ mode, 64-entry RX ring), `ne2000.c`
-  RTL8029 (QEMU/ISA) and `asix.c` AX88772 USB Ethernet (bulk over the USB
-  core, so an EHCI/xHCI dongle is usable).  `netdev [name]` is a kernel
-  command that shows the active driver or switches it (`netdev asix`,
-  `netdev e1000e`, ...); it calls the selected driver's probe and leaves the
-  current driver untouched on failure.  `net.c` — ARP + ICMP echo, IPv4/UDP
+  RTL8029 (QEMU/ISA), `asix.c` AX88772 USB Ethernet (bulk over the USB
+  core, so an EHCI/xHCI dongle is usable) and `rndis.c` USB RNDIS tethering
+  (Android phones and QEMU `usb-net`; device-level config scan, RNDIS
+  INIT/QUERY/packet-filter, 44-byte packet header and an Ethernet netdev).
+  `netdev [name]` is a kernel command that shows the active driver or
+  switches it (`netdev rndis`, `netdev asix`, `netdev e1000e`, ...); it calls
+  the selected driver's probe and leaves the current driver untouched on
+  failure.  `net.c` — ARP + ICMP echo, IPv4/UDP
   send + parse helpers,
   send + parse helpers,
   shared ARP resolution (`net_arp_resolve`) and routing (`net_next_hop`), frame
   shared ARP resolution (`net_arp_resolve`) and routing (`net_next_hop`), frame
   decode, `net_checksum()`/`net_checksum_tcp()`.  `dhcp.c` — minimal DHCP client
   decode, `net_checksum()`/`net_checksum_tcp()`.  `dhcp.c` — minimal DHCP client
@@ -1786,3 +1790,18 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     leaves the target untouched, while a target-write failure can leave it
     leaves the target untouched, while a target-write failure can leave it
     incomplete (the MBR is written last).  IDE, SATA and eMMC sources work
     incomplete (the MBR is written last).  IDE, SATA and eMMC sources work
     without USB, but a target smaller than the image is refused.
     without USB, but a target smaller than the image is refused.
+
+33. USB tethering is RNDIS only (`rndis.c`): Android phones and QEMU
+    `usb-net` work, but CDC-ECM/CDC-NCM (many iPhones and some Android
+    builds), IPv6, multiple phones and the RNDIS interrupt status endpoint
+    are not implemented.  The notification endpoint is ignored because
+    responses are polled on the control channel; a phone that insists on
+    `RESPONSE_AVAILABLE` needs an interrupt-slot allocator.  A hotplugged
+    phone becomes the active NIC but does not run DHCP automatically; use
+    `netdev rndis` and then `dhcp`.  Bulk transfers exist only on EHCI/xHCI;
+    each bulk-IN transfer is capped at 2 KB and messages are reassembled in
+    a 4 KB stream (a partial message larger than that is dropped).
+    `net_stop()` only clears software state: it cannot cancel an already
+    armed bulk-IN transfer, so kexec relies on the next USB controller reset.
+    QEMU's `usb-net` is full-speed, so `make run-rndis` exercises full-speed
+    bulk on xHCI rather than the phone's high-speed path.

+ 13 - 3
Makefile

@@ -66,7 +66,7 @@ EFI_LDFLAGS = -nostdlib -Wl,--subsystem,10 -Wl,-e,efi_main \
               -Wl,--image-base,0x0 -Wl,--dynamicbase \
               -Wl,--image-base,0x0 -Wl,--dynamicbase \
               -Wl,--enable-reloc-section -Wl,--no-insert-timestamp
               -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-e1000 run-ahci test-usb test-install run-serial floppy usb uefi run-uefi test-uefi flash dev net-dev cmds-dev net-cmds browser-dev gallery-dev compat-serve netmon monitor test-crypto test-images test-images-asan test-libc test-font test-font-asan test-touchpad fonts kernel-dev kernel-net-dev rootfs
+.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 test-usb test-install run-serial floppy usb uefi run-uefi test-uefi flash dev net-dev cmds-dev net-cmds browser-dev gallery-dev compat-serve netmon monitor test-crypto test-images test-images-asan test-libc test-font test-font-asan test-touchpad fonts kernel-dev kernel-net-dev rootfs
 
 
 all: floppy.img usb.img final.bin root.img
 all: floppy.img usb.img final.bin root.img
 
 
@@ -211,6 +211,9 @@ xhci.o: xhci.c xhci.h usb_hcd.h pci.h paging.h mm.h serial.h timer.h spinlock.h
 asix.o: asix.c asix.h netdev.h usb.h io.h serial.h timer.h
 asix.o: asix.c asix.h netdev.h usb.h io.h serial.h timer.h
 	$(CC) $(CFLAGS) -Os -o $@ $<
 	$(CC) $(CFLAGS) -Os -o $@ $<
 
 
+rndis.o: rndis.c rndis.h netdev.h usb.h io.h serial.h timer.h
+	$(CC) $(CFLAGS) -Os -o $@ $<
+
 usb.o: usb.c usb.h usb_hcd.h io.h serial.h timer.h
 usb.o: usb.c usb.h usb_hcd.h io.h serial.h timer.h
 	$(CC) $(CFLAGS) -Os -o $@ $<
 	$(CC) $(CFLAGS) -Os -o $@ $<
 
 
@@ -400,7 +403,7 @@ sys_net.o: sys_net.c sys_net.h syscall.h dhcp.h dns.h net.h netcore.h netdev.h n
 syscall_stub.o: syscall_stub.S irqret.inc
 syscall_stub.o: syscall_stub.S irqret.inc
 	$(AS) $(ASFLAGS) -o $@ $<
 	$(AS) $(ASFLAGS) -o $@ $<
 
 
-kernel.elf: kernel.ld vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o reboot.o poweroff.o disk.o fat.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o ec.o cros_ec.o power_src.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o display.o mouse.o i2c.o touchpad.o touchpad_gesture.o uhci.o ohci.o ehci.o xhci.o asix.o usb.o usbmsc.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o sdhci.o ata.o ahci.o fatdetect.o fatformat.o format.o install.o vfs.o sys_fs.o sys_info.o sys_mem.o sys_net.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netcore.o netkexec.o netlog.o dhcp.o dns.o ntp.o tcp.o acpi.o lapic.o smp.o ap_tramp_embed.o inflate.o ramfs.o share.o payload.o
+kernel.elf: kernel.ld vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o reboot.o poweroff.o disk.o fat.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o ec.o cros_ec.o power_src.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o display.o mouse.o i2c.o touchpad.o touchpad_gesture.o uhci.o ohci.o ehci.o xhci.o asix.o rndis.o usb.o usbmsc.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o sdhci.o ata.o ahci.o fatdetect.o fatformat.o format.o install.o vfs.o sys_fs.o sys_info.o sys_mem.o sys_net.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netcore.o netkexec.o netlog.o dhcp.o dns.o ntp.o tcp.o acpi.o lapic.o smp.o ap_tramp_embed.o inflate.o ramfs.o share.o payload.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $(filter-out kernel.ld,$^)
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $(filter-out kernel.ld,$^)
 
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
@@ -1009,6 +1012,13 @@ run-xhci: floppy.img root.img
 	qemu-system-i386 -M pc -m $(QEMU_MEM) -device qemu-xhci -device usb-mouse -device usb-kbd -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy 2>/dev/null || \
 	qemu-system-i386 -M pc -m $(QEMU_MEM) -device qemu-xhci -device usb-mouse -device usb-kbd -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy 2>/dev/null || \
 	qemu-system-x86_64 -M pc -m $(QEMU_MEM) -device qemu-xhci -device usb-mouse -device usb-kbd -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy
 	qemu-system-x86_64 -M pc -m $(QEMU_MEM) -device qemu-xhci -device usb-mouse -device usb-kbd -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy
 
 
+# RNDIS variant: QEMU's usb-net is a full-speed RNDIS function.  It sits on
+# xHCI (QEMU's USB2 root ports), and `-nic none` keeps the PCI e1000 out of
+# the way so the phone/tethering link is the active NIC.
+run-rndis: floppy.img root.img
+	qemu-system-i386 -M pc -m $(QEMU_MEM) -nic none -device qemu-xhci -device usb-mouse -device usb-kbd -device usb-net,netdev=n1 -netdev user,id=n1 -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy 2>/dev/null || \
+	qemu-system-x86_64 -M pc -m $(QEMU_MEM) -nic none -device qemu-xhci -device usb-mouse -device usb-kbd -device usb-net,netdev=n1 -netdev user,id=n1 -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy
+
 # EHCI variant (USB 2.0 high-speed root ports).  usb-storage is high-speed
 # EHCI variant (USB 2.0 high-speed root ports).  usb-storage is high-speed
 # and lands on EHCI; the mouse/keyboard are full-speed and use the UHCI
 # and lands on EHCI; the mouse/keyboard are full-speed and use the UHCI
 # companion, exercising the multi-controller USB core.
 # companion, exercising the multi-controller USB core.
@@ -1198,4 +1208,4 @@ kernel-net-dev: kernel.bin netkexec_send
 	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$entry kernel.bin
 	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$entry kernel.bin
 
 
 clean:
 clean:
-	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o disk.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o ec.o cros_ec.o power_src.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o display.o mouse.o i2c.o touchpad.o touchpad_gesture.o uhci.o ohci.o ehci.o xhci.o asix.o usb.o usbmsc.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o sdhci.o ata.o ahci.o fatdetect.o fatformat.o format.o install.o vfs.o sys_fs.o sys_info.o sys_mem.o inflate.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netcore.o netkexec.o netlog.o dhcp.o dns.o ntp.o tcp.o acpi.o lapic.o smp.o ap_tramp.o ap_tramp.elf ap_tramp.bin ap_tramp_embed.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img hello.elf cmds.pack cmds_pack_gz.bin cmds_pack.o rootfs.bin cmds.img mkrootfs ramfs.o share.o payload.o mkpack uwm_lib.o ngui.o img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o img_jpeg.o img_tga.o img_pnm.o img_ico.o img_pam.o img_gif_anim.o img_file.o browser.o browser_html.o uhttp.o browser.elf img_test img_test_asan *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) gallery.o gallery.elf $(TLSLIB_OBJS) tls_test kexec_send netkexec_send netmonitor BOOTX64.EFI esp.img usb-efi.img efi/main.o efi/payload.o efi/tramp.o efi/tramp.elf efi/tramp.bin efi/efi_entry.h libc.a libc/*.o malloc_test format_test math_test div64_test setjmp_test mujs_test js_browser.o $(MUJS_DIR)/mujs.o ufont.o ufont_ttf.o ufont_draw.o ufont_file.o ufont_test ufont_test_asan touchpad_gesture_test
+	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o disk.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o ec.o cros_ec.o power_src.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o display.o mouse.o i2c.o touchpad.o touchpad_gesture.o uhci.o ohci.o ehci.o xhci.o asix.o rndis.o usb.o usbmsc.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o sdhci.o ata.o ahci.o fatdetect.o fatformat.o format.o install.o vfs.o sys_fs.o sys_info.o sys_mem.o inflate.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netcore.o netkexec.o netlog.o dhcp.o dns.o ntp.o tcp.o acpi.o lapic.o smp.o ap_tramp.o ap_tramp.elf ap_tramp.bin ap_tramp_embed.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img hello.elf cmds.pack cmds_pack_gz.bin cmds_pack.o rootfs.bin cmds.img mkrootfs ramfs.o share.o payload.o mkpack uwm_lib.o ngui.o img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o img_jpeg.o img_tga.o img_pnm.o img_ico.o img_pam.o img_gif_anim.o img_file.o browser.o browser_html.o uhttp.o browser.elf img_test img_test_asan *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) gallery.o gallery.elf $(TLSLIB_OBJS) tls_test kexec_send netkexec_send netmonitor BOOTX64.EFI esp.img usb-efi.img efi/main.o efi/payload.o efi/tramp.o efi/tramp.elf efi/tramp.bin efi/efi_entry.h libc.a libc/*.o malloc_test format_test math_test div64_test setjmp_test mujs_test js_browser.o $(MUJS_DIR)/mujs.o ufont.o ufont_ttf.o ufont_draw.o ufont_file.o ufont_test ufont_test_asan touchpad_gesture_test

+ 1 - 0
docs/development.html

@@ -165,6 +165,7 @@
 					<tr><td><code>make run-uhci</code> / <code>run-ehci</code> / <code>run-xhci</code></td><td>Exercise the USB backends with a mouse/keyboard; the EHCI target also attaches a USB mass-storage disk, and the installer test covers EHCI and xHCI storage.</td></tr>
 					<tr><td><code>make run-uhci</code> / <code>run-ehci</code> / <code>run-xhci</code></td><td>Exercise the USB backends with a mouse/keyboard; the EHCI target also attaches a USB mass-storage disk, and the installer test covers EHCI and xHCI storage.</td></tr>
 					<tr><td><code>make run-ehci-asix</code> / <code>run-xhci-asix</code></td><td>Pass through a real ASIX AX88772 dongle.</td></tr>
 					<tr><td><code>make run-ehci-asix</code> / <code>run-xhci-asix</code></td><td>Pass through a real ASIX AX88772 dongle.</td></tr>
 					<tr><td><code>make run-net</code></td><td>Add a PCI NE2000 on QEMU's slirp network with host port 8080 forwarded.</td></tr>
 					<tr><td><code>make run-net</code></td><td>Add a PCI NE2000 on QEMU's slirp network with host port 8080 forwarded.</td></tr>
+					<tr><td><code>make run-rndis</code></td><td>Boot with <code>qemu-xhci</code> and QEMU's full-speed <code>usb-net</code> RNDIS device on slirp; the tethering link gets DHCP from QEMU.</td></tr>
 					<tr><td><code>make run-ahci</code></td><td>Add an ICH9 AHCI controller and a 512 MB SATA disk.</td></tr>
 					<tr><td><code>make run-ahci</code></td><td>Add an ICH9 AHCI controller and a 512 MB SATA disk.</td></tr>
 					<tr><td><code>make uefi</code> / <code>run-uefi</code> / <code>test-uefi</code></td><td>Build the dual-boot image, boot it under OVMF, or run the headless serial check.</td></tr>
 					<tr><td><code>make uefi</code> / <code>run-uefi</code> / <code>test-uefi</code></td><td>Build the dual-boot image, boot it under OVMF, or run the headless serial check.</td></tr>
 					<tr><td><code>make rootfs</code></td><td>Rebuild <code>cmds.img</code> only.</td></tr>
 					<tr><td><code>make rootfs</code></td><td>Rebuild <code>cmds.img</code> only.</td></tr>

+ 17 - 1
docs/drivers.html

@@ -83,7 +83,7 @@
 					<tr><td>SATA</td><td><span class="file">ahci.c</span></td><td>PCI AHCI MMIO</td><td>Polled, READ/WRITE DMA EXT</td></tr>
 					<tr><td>SATA</td><td><span class="file">ahci.c</span></td><td>PCI AHCI MMIO</td><td>Polled, READ/WRITE DMA EXT</td></tr>
 					<tr><td>eMMC</td><td><span class="file">sdhci.c</span></td><td>Intel Braswell SDHCI, PCI <code>00:10.0</code> (<code>8086:2294</code>)</td><td>Polled PIO, 1-bit/25 MHz; no DMA/IRQ</td></tr>
 					<tr><td>eMMC</td><td><span class="file">sdhci.c</span></td><td>Intel Braswell SDHCI, PCI <code>00:10.0</code> (<code>8086:2294</code>)</td><td>Polled PIO, 1-bit/25 MHz; no DMA/IRQ</td></tr>
 					<tr><td>USB</td><td><span class="file">usb.c</span> + <span class="file">uhci.c</span> <span class="file">ohci.c</span> <span class="file">ehci.c</span> <span class="file">xhci.c</span></td><td>PCI I/O ports or MMIO</td><td>Polled; hotplug watcher in the WM loop</td></tr>
 					<tr><td>USB</td><td><span class="file">usb.c</span> + <span class="file">uhci.c</span> <span class="file">ohci.c</span> <span class="file">ehci.c</span> <span class="file">xhci.c</span></td><td>PCI I/O ports or MMIO</td><td>Polled; hotplug watcher in the WM loop</td></tr>
-					<tr><td>Network</td><td><span class="file">e1000e.c</span> <span class="file">r8168.c</span> <span class="file">ne2000.c</span> <span class="file">asix.c</span></td><td>PCI or USB</td><td>Polled, one active receiver</td></tr>
+					<tr><td>Network</td><td><span class="file">e1000e.c</span> <span class="file">r8168.c</span> <span class="file">ne2000.c</span> <span class="file">asix.c</span> <span class="file">rndis.c</span></td><td>PCI or USB</td><td>Polled, one active receiver</td></tr>
 					<tr><td>PS/2</td><td><span class="file">mouse.c</span>, <span class="file">io.c</span></td><td>i8042</td><td>IRQ 1 keyboard, IRQ 12 mouse; polling fallback</td></tr>
 					<tr><td>PS/2</td><td><span class="file">mouse.c</span>, <span class="file">io.c</span></td><td>i8042</td><td>IRQ 1 keyboard, IRQ 12 mouse; polling fallback</td></tr>
 					<tr><td>Touchpad</td><td><span class="file">i2c.c</span>, <span class="file">touchpad.c</span>, <span class="file">touchpad_gesture.c</span></td><td>LPSS DesignWare I2C, slave <code>0x15</code></td><td>Polled input register every 25 ms; software tap and two-finger scroll gestures; no GPIO interrupt driver</td></tr>
 					<tr><td>Touchpad</td><td><span class="file">i2c.c</span>, <span class="file">touchpad.c</span>, <span class="file">touchpad_gesture.c</span></td><td>LPSS DesignWare I2C, slave <code>0x15</code></td><td>Polled input register every 25 ms; software tap and two-finger scroll gestures; no GPIO interrupt driver</td></tr>
 					<tr><td>Serial</td><td><span class="file">serial.c</span></td><td>16550 UART, COM1</td><td>IRQ 4 ring buffer + polled transmitter</td></tr>
 					<tr><td>Serial</td><td><span class="file">serial.c</span></td><td>16550 UART, COM1</td><td>IRQ 4 ring buffer + polled transmitter</td></tr>
@@ -321,6 +321,21 @@
 			live image into RAM first and then writes the target, so slow eMMC
 			live image into RAM first and then writes the target, so slow eMMC
 			writes cannot leave the USB source idle between chunks.
 			writes cannot leave the USB source idle between chunks.
 		</p>
 		</p>
+
+		<h3>USB tethering</h3>
+		<p>
+			<span class="file">rndis.c</span> is another device-level probe. It
+			scans every configuration for an RNDIS control function
+			(<code>02/02/FF</code>, <code>E0/01/03</code> or an <code>EF</code>
+			variant) and a data interface with bulk endpoints, selects that
+			configuration, then sends RNDIS INIT/QUERY/packet-filter messages
+			over the control interface. Ethernet frames travel in 44-byte RNDIS
+			packet headers on the bulk pair, so the existing IPv4 stack sees a
+			normal netdev named <code>rndis</code>. This is Android USB
+			tethering, not WiFi; QEMU's full-speed <code>usb-net</code> device is
+			the test target (<code>make run-rndis</code>). CDC-ECM/NCM and the
+			RNDIS interrupt notification endpoint are not implemented.
+		</p>
 	</section>
 	</section>
 
 
 	<section id="hid">
 	<section id="hid">
@@ -515,6 +530,7 @@
 			<li><code>usb.c</code>, <code>usb_hcd.h</code> — USB core</li>
 			<li><code>usb.c</code>, <code>usb_hcd.h</code> — USB core</li>
 			<li><code>uhci.c</code>, <code>ohci.c</code>, <code>ehci.c</code>, <code>xhci.c</code></li>
 			<li><code>uhci.c</code>, <code>ohci.c</code>, <code>ehci.c</code>, <code>xhci.c</code></li>
 			<li><code>usbmsc.c</code>, <code>usbmsc.h</code> — USB BOT/SCSI mass storage</li>
 			<li><code>usbmsc.c</code>, <code>usbmsc.h</code> — USB BOT/SCSI mass storage</li>
+			<li><code>rndis.c</code>, <code>rndis.h</code> — USB RNDIS tethering</li>
 			<li><code>install.c</code> — live-image clone installer</li>
 			<li><code>install.c</code> — live-image clone installer</li>
 			<li><code>usbhid.c</code>, <code>mouse.c</code>, <code>io.c</code> — input</li>
 			<li><code>usbhid.c</code>, <code>mouse.c</code>, <code>io.c</code> — input</li>
 			<li><code>i2c.c</code>, <code>i2c.h</code> — DesignWare/LPSS I2C master</li>
 			<li><code>i2c.c</code>, <code>i2c.h</code> — DesignWare/LPSS I2C master</li>

+ 1 - 1
docs/index.html

@@ -217,7 +217,7 @@
 			</a>
 			</a>
 			<a class="card" href="network.html">
 			<a class="card" href="network.html">
 				<h3>Networking</h3>
 				<h3>Networking</h3>
-				<p>NIC registry, ARP/ICMP/UDP, DHCP, DNS, NTP, TCP client and listener, TLS 1.3, netconsole and netkexec.</p>
+				<p>NIC registry, ARP/ICMP/UDP, DHCP, DNS, NTP, TCP client and listener, TLS 1.3, USB tethering, netconsole and netkexec.</p>
 				<span class="card-tag">network.html</span>
 				<span class="card-tag">network.html</span>
 			</a>
 			</a>
 			<a class="card" href="userland.html">
 			<a class="card" href="userland.html">

+ 17 - 4
docs/network.html

@@ -138,9 +138,21 @@
 			<code>struct netdev</code> drivers; the first one whose probe succeeds
 			<code>struct netdev</code> drivers; the first one whose probe succeeds
 			becomes active. All drivers are polled and share the same transmit,
 			becomes active. All drivers are polled and share the same transmit,
 			receive, register-dump and reset interface. <code>netdev</code> with
 			receive, register-dump and reset interface. <code>netdev</code> with
-			no argument shows the active driver; <code>netdev asix</code> switches
-			to a named one, leaving the current driver untouched if the probe
-			fails.
+			no argument shows the active driver; <code>netdev rndis</code> or
+			<code>netdev asix</code> switches to a named one, leaving the current
+			driver untouched if the probe fails.
+		</p>
+		<p>
+			<span class="file">rndis.c</span> is the USB tethering path, not a
+			WiFi driver: an Android phone (or QEMU's <code>usb-net</code>) is
+			parsed for an RNDIS control/data interface pair, initialized with
+			RNDIS INIT/QUERY/SET messages, and then presented as an ordinary
+			Ethernet NIC. <code>netdev rndis</code> selects it and
+			<code>dhcp</code> obtains the phone's tethering address. QEMU has no
+			phone dependency: <code>make run-rndis</code> boots with
+			<code>qemu-xhci</code> and <code>usb-net</code> on slirp. RNDIS only;
+			CDC-ECM/NCM, IPv6 and automatic DHCP after a hotplug are not
+			implemented.
 		</p>
 		</p>
 		<div class="table-wrap">
 		<div class="table-wrap">
 			<table>
 			<table>
@@ -152,6 +164,7 @@
 					<tr><td><span class="file">r8168.c</span></td><td>RTL8111/8168</td><td>PCIe MMIO</td><td>C+ mode, 64-entry RX ring, polled.</td></tr>
 					<tr><td><span class="file">r8168.c</span></td><td>RTL8111/8168</td><td>PCIe MMIO</td><td>C+ mode, 64-entry RX ring, polled.</td></tr>
 					<tr><td><span class="file">ne2000.c</span></td><td>RTL8029</td><td>ISA / QEMU PCI</td><td>Simple DP8390 path used by <code>make run-net</code>.</td></tr>
 					<tr><td><span class="file">ne2000.c</span></td><td>RTL8029</td><td>ISA / QEMU PCI</td><td>Simple DP8390 path used by <code>make run-net</code>.</td></tr>
 					<tr><td><span class="file">asix.c</span></td><td>AX88772</td><td>USB bulk</td><td>Runs over the USB core; usable on EHCI/xHCI dongles.</td></tr>
 					<tr><td><span class="file">asix.c</span></td><td>AX88772</td><td>USB bulk</td><td>Runs over the USB core; usable on EHCI/xHCI dongles.</td></tr>
+					<tr><td><span class="file">rndis.c</span></td><td>Android USB tethering, QEMU <code>usb-net</code></td><td>USB control + bulk</td><td>RNDIS INIT/QUERY/packet filter; presents the phone's tethering link as an Ethernet netdev.</td></tr>
 				</tbody>
 				</tbody>
 			</table>
 			</table>
 		</div>
 		</div>
@@ -355,7 +368,7 @@
 		<h2>Source map</h2>
 		<h2>Source map</h2>
 		<ul class="filelist">
 		<ul class="filelist">
 			<li><code>netdev.c</code>, <code>netdev.h</code> — registry</li>
 			<li><code>netdev.c</code>, <code>netdev.h</code> — registry</li>
-			<li><code>e1000e.c</code>, <code>r8168.c</code>, <code>ne2000.c</code>, <code>asix.c</code></li>
+			<li><code>e1000e.c</code>, <code>r8168.c</code>, <code>ne2000.c</code>, <code>asix.c</code>, <code>rndis.c</code></li>
 			<li><code>net.c</code>, <code>net.h</code> — ARP cache/ICMP/UDP/IP</li>
 			<li><code>net.c</code>, <code>net.h</code> — ARP cache/ICMP/UDP/IP</li>
 			<li><code>netcore.c</code>, <code>netcore.h</code> — shared receive pump and IRQ helpers</li>
 			<li><code>netcore.c</code>, <code>netcore.h</code> — shared receive pump and IRQ helpers</li>
 			<li><code>dhcp.c</code>, <code>dns.c</code>, <code>ntp.c</code></li>
 			<li><code>dhcp.c</code>, <code>dns.c</code>, <code>ntp.c</code></li>

+ 2 - 0
kernel.c

@@ -21,6 +21,7 @@
 #include "power.h"
 #include "power.h"
 #include "process.h"
 #include "process.h"
 #include "ramfs.h"
 #include "ramfs.h"
+#include "rndis.h"
 #include "sched.h"
 #include "sched.h"
 #include "thermal.h"
 #include "thermal.h"
 #include "timer.h"
 #include "timer.h"
@@ -451,6 +452,7 @@ void kernel_main(void)
 	 * watcher in the WM loop. */
 	 * watcher in the WM loop. */
 	asix_register();
 	asix_register();
 	usbmsc_register();
 	usbmsc_register();
+	rndis_register();
 	usbhid_init();
 	usbhid_init();
 	boot_trace("usb");
 	boot_trace("usb");
 	vga_shadow_init();
 	vga_shadow_init();

+ 12 - 5
netdev.c

@@ -8,6 +8,7 @@
 #include "net.h"
 #include "net.h"
 #include "process.h"
 #include "process.h"
 #include "r8168.h"
 #include "r8168.h"
+#include "rndis.h"
 #include "tcp.h"
 #include "tcp.h"
 static const struct netdev *const netdev_drivers[] = {
 static const struct netdev *const netdev_drivers[] = {
 	/* e1000e is the active test NIC; the ASIX is kept as the management
 	/* e1000e is the active test NIC; the ASIX is kept as the management
@@ -16,6 +17,7 @@ static const struct netdev *const netdev_drivers[] = {
 	&r8168_netdev,
 	&r8168_netdev,
 	&ne2000_netdev,
 	&ne2000_netdev,
 	&asix_netdev,
 	&asix_netdev,
+	&rndis_netdev,
 };
 };
 
 
 static const struct netdev *active;
 static const struct netdev *active;
@@ -101,9 +103,9 @@ const struct netdev *netdev_mgmt(void)
 	return netdev_active();
 	return netdev_active();
 }
 }
 
 
-/* Called from the ASIX device probe after a successful hotplug
- * enumeration.  The boot-time probe caches a NULL result, so without this a
- * dongle plugged in later would only be usable through `netdev asix`. */
+/* Called from a USB NIC probe after a successful hotplug enumeration.  The
+ * boot-time probe caches a NULL result, so without this a dongle or phone
+ * plugged in later would only be usable through `netdev <name>`. */
 void netdev_hotplug(void)
 void netdev_hotplug(void)
 {
 {
 	if (active || !probed)
 	if (active || !probed)
@@ -111,6 +113,11 @@ void netdev_hotplug(void)
 	if (asix_netdev.init() == 0) {
 	if (asix_netdev.init() == 0) {
 		active = &asix_netdev;
 		active = &asix_netdev;
 		netdev_apply_defaults(active);
 		netdev_apply_defaults(active);
+		return;
+	}
+	if (rndis_netdev.init() == 0) {
+		active = &rndis_netdev;
+		netdev_apply_defaults(active);
 	}
 	}
 }
 }
 
 
@@ -166,7 +173,7 @@ int netdev_select(const char *name)
 			continue;
 			continue;
 		if (active == netdev_drivers[i]) {
 		if (active == netdev_drivers[i]) {
 			probed = 1;
 			probed = 1;
-			return 0;
+			return netdev_drivers[i]->init() == 0 ? 0 : -1;
 		}
 		}
 		if (netdev_drivers[i]->init() != 0)
 		if (netdev_drivers[i]->init() != 0)
 			return -1;
 			return -1;
@@ -213,5 +220,5 @@ void program_netdev_main(const char *arg)
 	if (mgmt && mgmt != netdev_active())
 	if (mgmt && mgmt != netdev_active())
 		print_netdev("mgmt   ", mgmt);
 		print_netdev("mgmt   ", mgmt);
 	if (!(arg && *arg))
 	if (!(arg && *arg))
-		io_putstr("netdev: use netdev asix|e1000e|r8168|ne2000\n");
+		io_putstr("netdev: use netdev asix|rndis|e1000e|r8168|ne2000\n");
 }
 }

+ 977 - 0
rndis.c

@@ -0,0 +1,977 @@
+/* USB RNDIS tethering driver.
+ *
+ * Android phones expose their USB tethering link as an RNDIS function: a
+ * CDC-style control interface with encapsulated RNDIS commands and a data
+ * interface with bulk IN/OUT endpoints.  The phone is a soft MAC; the host
+ * sends the RNDIS INIT/QUERY/SET messages, then Ethernet frames travel in
+ * RNDIS packet messages over the bulk endpoints.
+ *
+ * QEMU's usb-net device implements the same protocol, so the driver can be
+ * exercised without a phone (`make run-rndis`).  QEMU uses configuration
+ * value 2 and class 02/02/FF; Android usually uses E0/01/03 (and some
+ * devices use an EF class).  Both are parsed here.
+ *
+ * This is not WiFi: the phone's own WiFi/cellular connection is shared with
+ * the board over USB, and the kernel sees it as a normal netdev.
+ */
+
+#include "rndis.h"
+#include "io.h"
+#include "netdev.h"
+#include "serial.h"
+#include "timer.h"
+#include "usb.h"
+
+/* RNDIS message types. */
+#define RNDIS_MSG_PACKET        0x00000001u
+#define RNDIS_MSG_INIT          0x00000002u
+#define RNDIS_MSG_HALT          0x00000003u
+#define RNDIS_MSG_QUERY         0x00000004u
+#define RNDIS_MSG_SET           0x00000005u
+#define RNDIS_MSG_RESET         0x00000006u
+#define RNDIS_MSG_INDICATE      0x00000007u
+#define RNDIS_MSG_KEEPALIVE     0x00000008u
+#define RNDIS_MSG_COMPLETION    0x80000000u
+
+#define RNDIS_MSG_INIT_C        (RNDIS_MSG_INIT | RNDIS_MSG_COMPLETION)
+#define RNDIS_MSG_QUERY_C       (RNDIS_MSG_QUERY | RNDIS_MSG_COMPLETION)
+#define RNDIS_MSG_SET_C         (RNDIS_MSG_SET | RNDIS_MSG_COMPLETION)
+#define RNDIS_MSG_KEEPALIVE_C   (RNDIS_MSG_KEEPALIVE | RNDIS_MSG_COMPLETION)
+
+#define RNDIS_STATUS_SUCCESS            0x00000000u
+#define RNDIS_STATUS_MEDIA_CONNECT      0x4001000Bu
+#define RNDIS_STATUS_MEDIA_DISCONNECT   0x4001000Cu
+
+/* Information objects used during bring-up. */
+#define RNDIS_OID_GEN_CURRENT_PACKET_FILTER 0x0001010Eu
+#define RNDIS_OID_GEN_MEDIA_CONNECT_STATUS  0x00010114u
+#define RNDIS_OID_802_3_PERMANENT_ADDRESS   0x01010101u
+#define RNDIS_OID_802_3_CURRENT_ADDRESS     0x01010102u
+
+/* Packet filter bits.  A phone's DHCP and ARP traffic needs broadcast and
+ * directed frames; multicast keeps DNS/mDNS from disappearing. */
+#define RNDIS_PACKET_TYPE_DIRECTED      0x00000001u
+#define RNDIS_PACKET_TYPE_MULTICAST     0x00000002u
+#define RNDIS_PACKET_TYPE_ALL_MULTICAST 0x00000004u
+#define RNDIS_PACKET_TYPE_BROADCAST     0x00000008u
+#define RNDIS_PACKET_TYPE_PROMISCUOUS   0x00000020u
+#define RNDIS_PACKET_FILTER_DEFAULT \
+	(RNDIS_PACKET_TYPE_DIRECTED | RNDIS_PACKET_TYPE_MULTICAST | \
+	 RNDIS_PACKET_TYPE_ALL_MULTICAST | RNDIS_PACKET_TYPE_BROADCAST | \
+	 RNDIS_PACKET_TYPE_PROMISCUOUS)
+
+#define RNDIS_INIT_MAX_TRANSFER 2048u
+#define RNDIS_RX_MAX            2048u
+#define RNDIS_RX_ASSEMBLY       4096u
+#define RNDIS_TX_MAX            1600u
+#define RNDIS_CTRL_MAX          1025u
+#define RNDIS_CFG_MAX           1024u
+
+#define RNDIS_CONTROL_TIMEOUT_MS 200u
+#define RNDIS_POLL_MS             20u
+
+/* USB interface classes that identify an RNDIS control function. */
+#define RNDIS_CLASS_COMM        0x02u
+#define RNDIS_SUBCLASS_ACM      0x02u
+#define RNDIS_PROTO_VENDOR      0xFFu
+#define RNDIS_CLASS_WIRELESS    0xE0u
+#define RNDIS_CLASS_MISC        0xEFu
+#define RNDIS_CLASS_DATA        0x0Au
+
+struct rndis_dev {
+	int present;
+	int ready;
+	int link;
+	unsigned int ctrl, addr, mps, port, config;
+	int low;
+	unsigned int ctrl_iface, data_iface;
+	unsigned int ep_in, ep_in_mps;
+	unsigned int ep_out, ep_out_mps;
+	unsigned int ep_int, ep_int_mps;
+	unsigned char mac[6];
+	unsigned int max_transfer;
+	unsigned int align;
+	unsigned int xid;
+	unsigned int gen;
+	unsigned int rx_pos, rx_len;
+	unsigned int rx_frames, tx_frames, rx_errors, tx_errors;
+	/* Bulk reads always land in raw_buf; rx_buf is the reassembly
+	 * stream.  xHCI arms directly into the caller's buffer, so the read
+	 * buffer must stay at a fixed address while a transfer is pending. */
+	unsigned char rx_buf[RNDIS_RX_ASSEMBLY] __attribute__((aligned(64)));
+	unsigned char raw_buf[RNDIS_RX_MAX] __attribute__((aligned(64)));
+	unsigned char tx_buf[RNDIS_TX_MAX] __attribute__((aligned(64)));
+	unsigned char ctrl_buf[RNDIS_CTRL_MAX] __attribute__((aligned(64)));
+};
+
+static struct rndis_dev dev;
+static unsigned char cfg_buf[RNDIS_CFG_MAX] __attribute__((aligned(64)));
+
+/* Small part of the device state needed to undo a probe of an unrelated USB
+ * device.  The USB core calls every device probe for every device, so a
+ * mouse/keyboard probe after a working phone must not clear its state. */
+struct rndis_saved {
+	int present, ready, link;
+	unsigned int ctrl, addr, mps, port, config;
+	int low;
+	unsigned int ctrl_iface, data_iface;
+	unsigned int ep_in, ep_in_mps, ep_out, ep_out_mps;
+	unsigned int ep_int, ep_int_mps;
+	unsigned char mac[6];
+	unsigned int max_transfer, align, xid, gen;
+	unsigned int rx_pos, rx_len;
+};
+
+static void rndis_save(struct rndis_saved *s)
+{
+	s->present = dev.present;
+	s->ready = dev.ready;
+	s->link = dev.link;
+	s->ctrl = dev.ctrl;
+	s->addr = dev.addr;
+	s->mps = dev.mps;
+	s->port = dev.port;
+	s->config = dev.config;
+	s->low = dev.low;
+	s->ctrl_iface = dev.ctrl_iface;
+	s->data_iface = dev.data_iface;
+	s->ep_in = dev.ep_in;
+	s->ep_in_mps = dev.ep_in_mps;
+	s->ep_out = dev.ep_out;
+	s->ep_out_mps = dev.ep_out_mps;
+	s->ep_int = dev.ep_int;
+	s->ep_int_mps = dev.ep_int_mps;
+	{
+		unsigned int i;
+
+		for (i = 0; i < 6; i++)
+			s->mac[i] = dev.mac[i];
+	}
+	s->max_transfer = dev.max_transfer;
+	s->align = dev.align;
+	s->xid = dev.xid;
+	s->gen = dev.gen;
+	s->rx_pos = dev.rx_pos;
+	s->rx_len = dev.rx_len;
+}
+
+static void rndis_restore(const struct rndis_saved *s)
+{
+	unsigned int i;
+
+	dev.present = s->present;
+	dev.ready = s->ready;
+	dev.link = s->link;
+	dev.ctrl = s->ctrl;
+	dev.addr = s->addr;
+	dev.mps = s->mps;
+	dev.port = s->port;
+	dev.config = s->config;
+	dev.low = s->low;
+	dev.ctrl_iface = s->ctrl_iface;
+	dev.data_iface = s->data_iface;
+	dev.ep_in = s->ep_in;
+	dev.ep_in_mps = s->ep_in_mps;
+	dev.ep_out = s->ep_out;
+	dev.ep_out_mps = s->ep_out_mps;
+	dev.ep_int = s->ep_int;
+	dev.ep_int_mps = s->ep_int_mps;
+	for (i = 0; i < 6; i++)
+		dev.mac[i] = s->mac[i];
+	dev.max_transfer = s->max_transfer;
+	dev.align = s->align;
+	dev.xid = s->xid;
+	dev.gen = s->gen;
+	dev.rx_pos = s->rx_pos;
+	dev.rx_len = s->rx_len;
+}
+
+/* A failed probe normally restores the previous phone.  If the failed probe
+ * is for another device on the phone's own root port, the phone was
+ * unplugged and replaced between hotplug polls, so do not resurrect it. */
+static void rndis_restore_after_probe(const struct rndis_saved *saved,
+				      unsigned int ctrl, unsigned int port,
+				      unsigned int gen)
+{
+	if (saved->present && saved->port != 0xFFu &&
+	    saved->ctrl == ctrl && saved->port == port) {
+		dev.present = 0;
+		dev.ready = 0;
+		dev.link = 0;
+		dev.gen = gen;
+		return;
+	}
+	rndis_restore(saved);
+}
+
+static unsigned int rd32le(const unsigned char *p)
+{
+	return (unsigned int)p[0] | ((unsigned int)p[1] << 8) |
+	       ((unsigned int)p[2] << 16) | ((unsigned int)p[3] << 24);
+}
+
+static unsigned int rd16le(const unsigned char *p)
+{
+	return (unsigned int)p[0] | ((unsigned int)p[1] << 8);
+}
+
+static void wr32le(unsigned char *p, unsigned int v)
+{
+	p[0] = (unsigned char)(v & 0xFF);
+	p[1] = (unsigned char)((v >> 8) & 0xFF);
+	p[2] = (unsigned char)((v >> 16) & 0xFF);
+	p[3] = (unsigned char)((v >> 24) & 0xFF);
+}
+
+static void rndis_delay(unsigned int ms)
+{
+	unsigned int t0 = get_ticks_ms();
+
+	while (get_ticks_ms() - t0 < ms)
+		;
+}
+
+static void put_mac_serial(void)
+{
+	static const char hex[] = "0123456789ABCDEF";
+	unsigned int i;
+
+	for (i = 0; i < 6; i++) {
+		if (i)
+			serial_putc(SERIAL_COM1, ':');
+		serial_putc(SERIAL_COM1, hex[(dev.mac[i] >> 4) & 0xF]);
+		serial_putc(SERIAL_COM1, hex[dev.mac[i] & 0xF]);
+	}
+}
+
+static void put_mac_io(void)
+{
+	static const char hex[] = "0123456789ABCDEF";
+	unsigned int i;
+
+	for (i = 0; i < 6; i++) {
+		if (i)
+			io_putchar(':');
+		io_putchar(hex[(dev.mac[i] >> 4) & 0xF]);
+		io_putchar(hex[dev.mac[i] & 0xF]);
+	}
+}
+
+static int rndis_ctrl_send(const unsigned char *buf, unsigned int len)
+{
+	int r = usb_control_out_data(dev.ctrl, dev.addr, dev.mps, dev.low,
+				     0x21, 0x00, 0,
+				     (unsigned short)dev.ctrl_iface,
+				     buf, len);
+	return r < 0 ? -1 : 0;
+}
+
+static int rndis_ctrl_poll(unsigned char *buf, unsigned int len)
+{
+	return usb_control_in(dev.ctrl, dev.addr, dev.mps, dev.low,
+			      0xA1, 0x01, 0,
+			      (unsigned short)dev.ctrl_iface, buf, len);
+}
+
+static void rndis_send_keepalive_c(unsigned int xid)
+{
+	unsigned char msg[16];
+
+	wr32le(msg + 0, RNDIS_MSG_KEEPALIVE_C);
+	wr32le(msg + 4, sizeof(msg));
+	wr32le(msg + 8, xid);
+	wr32le(msg + 12, RNDIS_STATUS_SUCCESS);
+	(void)rndis_ctrl_send(msg, sizeof(msg));
+}
+
+/* Wait for the completion of the current request.  RNDIS queues responses on
+ * the control channel; the interrupt endpoint only says "a response is
+ * available" and is deliberately not required here. */
+static int rndis_wait(unsigned int expect)
+{
+	unsigned int tries = RNDIS_CONTROL_TIMEOUT_MS / RNDIS_POLL_MS;
+
+	while (tries--) {
+		int n;
+
+		if (dev.port != 0xFFu &&
+		    !usb_port_connected(dev.ctrl, dev.port))
+			return -1;
+		n = rndis_ctrl_poll(dev.ctrl_buf, RNDIS_CTRL_MAX);
+		if (n >= 8) {
+			unsigned int type = rd32le(dev.ctrl_buf);
+
+			if (type == expect && n >= 16 &&
+			    rd32le(dev.ctrl_buf + 8) == dev.xid)
+				return n;
+			if (type == RNDIS_MSG_INDICATE && n >= 12) {
+				unsigned int status = rd32le(dev.ctrl_buf + 8);
+
+				if (status == RNDIS_STATUS_MEDIA_CONNECT)
+					dev.link = 1;
+				else if (status == RNDIS_STATUS_MEDIA_DISCONNECT)
+					dev.link = 0;
+			} else if (type == RNDIS_MSG_KEEPALIVE && n >= 12) {
+				rndis_send_keepalive_c(rd32le(dev.ctrl_buf + 8));
+			}
+		}
+		rndis_delay(RNDIS_POLL_MS);
+	}
+	return -1;
+}
+
+static void rndis_send_halt(void)
+{
+	unsigned char msg[12];
+
+	wr32le(msg + 0, RNDIS_MSG_HALT);
+	wr32le(msg + 4, sizeof(msg));
+	wr32le(msg + 8, 0);
+	(void)rndis_ctrl_send(msg, sizeof(msg));
+}
+
+static int rndis_msg_init(void)
+{
+	int n;
+	unsigned int status, max_transfer, alignment;
+
+	dev.xid++;
+	if (!dev.xid)
+		dev.xid++;
+	for (n = 0; n < (int)24; n++)
+		dev.ctrl_buf[n] = 0;
+	wr32le(dev.ctrl_buf + 0, RNDIS_MSG_INIT);
+	wr32le(dev.ctrl_buf + 4, 24);
+	wr32le(dev.ctrl_buf + 8, dev.xid);
+	wr32le(dev.ctrl_buf + 12, 1);             /* RNDIS 1.0 */
+	wr32le(dev.ctrl_buf + 16, 0);
+	wr32le(dev.ctrl_buf + 20, RNDIS_INIT_MAX_TRANSFER);
+
+	if (rndis_ctrl_send(dev.ctrl_buf, 24) < 0)
+		return -1;
+	n = rndis_wait(RNDIS_MSG_INIT_C);
+	if (n < 52)
+		return -1;
+
+	status = rd32le(dev.ctrl_buf + 12);
+	if (status != RNDIS_STATUS_SUCCESS)
+		return -1;
+	max_transfer = rd32le(dev.ctrl_buf + 36);
+	alignment = rd32le(dev.ctrl_buf + 40);
+	if (alignment > 3)
+		alignment = 3;
+	dev.align = 1u << alignment;
+	dev.max_transfer = max_transfer;
+	if (max_transfer && max_transfer < 1558u) {
+		serial_puts(SERIAL_COM1, "rndis: warning: small max transfer ");
+		serial_putdec(SERIAL_COM1, max_transfer);
+		serial_puts(SERIAL_COM1, "\n");
+	}
+	return 0;
+}
+
+static int rndis_query(unsigned int oid, unsigned int in_len,
+		       unsigned char *out, unsigned int out_max,
+		       unsigned int *out_len)
+{
+	unsigned int len = 28 + in_len;
+	unsigned int off, rlen;
+	int n;
+
+	if (len > RNDIS_CTRL_MAX)
+		return -1;
+	dev.xid++;
+	if (!dev.xid)
+		dev.xid++;
+	for (n = 0; n < (int)len; n++)
+		dev.ctrl_buf[n] = 0;
+	wr32le(dev.ctrl_buf + 0, RNDIS_MSG_QUERY);
+	wr32le(dev.ctrl_buf + 4, len);
+	wr32le(dev.ctrl_buf + 8, dev.xid);
+	wr32le(dev.ctrl_buf + 12, oid);
+	wr32le(dev.ctrl_buf + 16, in_len);
+	wr32le(dev.ctrl_buf + 20, 20);
+	wr32le(dev.ctrl_buf + 24, 0);
+
+	if (rndis_ctrl_send(dev.ctrl_buf, len) < 0)
+		return -1;
+	n = rndis_wait(RNDIS_MSG_QUERY_C);
+	if (n < 24)
+		return -1;
+	if (rd32le(dev.ctrl_buf + 12) != RNDIS_STATUS_SUCCESS)
+		return -1;
+
+	rlen = rd32le(dev.ctrl_buf + 16);
+	off = rd32le(dev.ctrl_buf + 20);
+	if (rlen > out_max)
+		return -1;
+	if (off > (unsigned int)n || rlen > (unsigned int)n - off ||
+	    8u + off + rlen > (unsigned int)n)
+		return -1;
+	{
+		unsigned int i;
+
+		for (i = 0; i < rlen; i++)
+			out[i] = dev.ctrl_buf[8 + off + i];
+	}
+	*out_len = rlen;
+	return 0;
+}
+
+static int rndis_set_filter(void)
+{
+	unsigned int len = 32;
+	int n;
+
+	for (n = 0; n < (int)len; n++)
+		dev.ctrl_buf[n] = 0;
+	wr32le(dev.ctrl_buf + 0, RNDIS_MSG_SET);
+	wr32le(dev.ctrl_buf + 4, len);
+	dev.xid++;
+	if (!dev.xid)
+		dev.xid++;
+	wr32le(dev.ctrl_buf + 8, dev.xid);
+	wr32le(dev.ctrl_buf + 12, RNDIS_OID_GEN_CURRENT_PACKET_FILTER);
+	wr32le(dev.ctrl_buf + 16, 4);
+	wr32le(dev.ctrl_buf + 20, 20);
+	wr32le(dev.ctrl_buf + 24, 0);
+	wr32le(dev.ctrl_buf + 28, RNDIS_PACKET_FILTER_DEFAULT);
+
+	if (rndis_ctrl_send(dev.ctrl_buf, len) < 0)
+		return -1;
+	n = rndis_wait(RNDIS_MSG_SET_C);
+	if (n < 16)
+		return -1;
+	return rd32le(dev.ctrl_buf + 12) == RNDIS_STATUS_SUCCESS ? 0 : -1;
+}
+
+static int rndis_start(void)
+{
+	unsigned char macbuf[16];
+	unsigned int mac_len = 0;
+	unsigned int status = 0;
+	unsigned int status_len = 0;
+	unsigned int i;
+	int mac_ok = 0;
+
+	if (!dev.present)
+		return -1;
+	if (dev.ready)
+		return 0;
+
+	if (rndis_msg_init() < 0)
+		goto fail;
+
+	if (rndis_query(RNDIS_OID_802_3_PERMANENT_ADDRESS, 48,
+			macbuf, sizeof(macbuf), &mac_len) == 0 && mac_len >= 6)
+		mac_ok = 1;
+	else if (rndis_query(RNDIS_OID_802_3_CURRENT_ADDRESS, 48,
+			     macbuf, sizeof(macbuf), &mac_len) == 0 &&
+		 mac_len >= 6)
+		mac_ok = 1;
+	if (!mac_ok)
+		goto fail;
+	for (i = 0; i < 6; i++)
+		dev.mac[i] = macbuf[i];
+	{
+		unsigned int zero = 1;
+
+		for (i = 0; i < 6; i++)
+			if (dev.mac[i])
+				zero = 0;
+		if (zero)
+			goto fail;
+	}
+
+	/* A phone with tethering switched off may report "disconnected"; keep
+	 * the link usable and let a later DHCP attempt discover the state. */
+	if (rndis_query(RNDIS_OID_GEN_MEDIA_CONNECT_STATUS, 4,
+			(unsigned char *)&status, sizeof(status),
+			&status_len) == 0 && status_len >= 4)
+		dev.link = (status == 0);
+	else
+		dev.link = 1;
+
+	if (rndis_set_filter() < 0)
+		goto fail;
+
+	dev.ready = 1;
+	dev.rx_pos = dev.rx_len = 0;
+	serial_puts(SERIAL_COM1, "rndis: ready, MAC ");
+	put_mac_serial();
+	serial_puts(SERIAL_COM1, dev.link ? ", link up\n" : ", link down\n");
+	return 0;
+
+fail:
+	serial_puts(SERIAL_COM1, "rndis: initialization failed\n");
+	rndis_send_halt();
+	dev.ready = 0;
+	dev.link = 0;
+	return -1;
+}
+
+static int rndis_is_control(unsigned int cls, unsigned int sub,
+			    unsigned int proto)
+{
+	return (cls == RNDIS_CLASS_COMM && sub == RNDIS_SUBCLASS_ACM &&
+		proto == RNDIS_PROTO_VENDOR) ||
+	       (cls == RNDIS_CLASS_WIRELESS && sub == 0x01 && proto == 0x03) ||
+	       (cls == RNDIS_CLASS_MISC && sub == 0x01 && proto == 0x01) ||
+	       (cls == RNDIS_CLASS_MISC && sub == 0x04 && proto == 0x01);
+}
+
+struct rndis_cfg {
+	unsigned int config;
+	unsigned int ctrl_iface;
+	unsigned int data_iface;
+	unsigned int data_alt;
+	unsigned int ep_in, ep_in_mps;
+	unsigned int ep_out, ep_out_mps;
+	unsigned int ep_int, ep_int_mps;
+};
+
+static int rndis_parse_config(unsigned int total, struct rndis_cfg *out)
+{
+	unsigned int i = 0;
+	unsigned int iface = 0, alt = 0, cls = 0;
+	unsigned int ctrl_iface = 0, data_iface = 0, data_alt = 0;
+	unsigned int int_ep = 0, int_mps = 0;
+	unsigned int in_ep = 0, in_mps = 0, in_alt = 0;
+	unsigned int out_ep = 0, out_mps = 0, out_alt = 0;
+	int have_ctrl = 0;
+	int have_data = 0;
+
+	while (i + 2 <= total) {
+		unsigned int blen = cfg_buf[i];
+		unsigned int type = cfg_buf[i + 1];
+
+		if (blen < 2 || i + blen > total)
+			break;
+		if (type == 0x04 && blen >= 9) {
+			iface = cfg_buf[i + 2];
+			alt = cfg_buf[i + 3];
+			cls = cfg_buf[i + 5];
+			if (alt == 0 && !have_ctrl &&
+			    rndis_is_control(cfg_buf[i + 5], cfg_buf[i + 6],
+					     cfg_buf[i + 7])) {
+				have_ctrl = 1;
+				ctrl_iface = iface;
+			}
+			if (alt == 0 && cls == RNDIS_CLASS_DATA && !have_data) {
+				data_iface = iface;
+				have_data = 1;
+			}
+		} else if (type == 0x05 && blen >= 7) {
+			unsigned int epa = cfg_buf[i + 2];
+			unsigned int attr = cfg_buf[i + 3] & 3u;
+			unsigned int mps = rd16le(cfg_buf + i + 4) & 0x7FFu;
+
+			if (attr == 2 && (cls == RNDIS_CLASS_DATA ||
+					  iface == ctrl_iface)) {
+				if (cls == RNDIS_CLASS_DATA && !have_data) {
+					data_iface = iface;
+					have_data = 1;
+				}
+				if (epa & 0x80) {
+					if (!in_ep) {
+						in_ep = epa & 0x0F;
+						in_mps = mps;
+						in_alt = alt;
+					}
+				} else if (!out_ep) {
+					out_ep = epa & 0x0F;
+					out_mps = mps;
+					out_alt = alt;
+				}
+			} else if (attr == 3 && (epa & 0x80) &&
+				   iface == ctrl_iface && !int_ep) {
+				int_ep = epa & 0x0F;
+				int_mps = mps;
+			}
+		}
+		i += blen;
+	}
+
+	if (!have_ctrl || !in_ep || !out_ep || !cfg_buf[5])
+		return 0;
+	if (in_alt != out_alt)
+		return 0;
+	if (!have_data)
+		data_iface = ctrl_iface;
+	data_alt = in_alt;
+
+	out->config = cfg_buf[5];
+	out->ctrl_iface = ctrl_iface;
+	out->data_iface = data_iface;
+	out->data_alt = data_alt;
+	out->ep_in = in_ep;
+	out->ep_in_mps = in_mps ? in_mps : 64;
+	out->ep_out = out_ep;
+	out->ep_out_mps = out_mps ? out_mps : 64;
+	out->ep_int = int_ep;
+	out->ep_int_mps = int_mps;
+	return 1;
+}
+
+static int rndis_read_config(unsigned int index, unsigned int *total_out)
+{
+	unsigned char hdr[9];
+	unsigned int total;
+	int n;
+
+	n = usb_control_in(dev.ctrl, dev.addr, dev.mps, dev.low,
+			   0x80, 0x06, (unsigned short)((2u << 8) | index), 0,
+			   hdr, sizeof(hdr));
+	if (n < 9 || hdr[1] != 0x02)
+		return -1;
+	total = rd16le(hdr + 2);
+	if (total < 9 || total > RNDIS_CFG_MAX)
+		return -1;
+	n = usb_control_in(dev.ctrl, dev.addr, dev.mps, dev.low,
+			   0x80, 0x06, (unsigned short)((2u << 8) | index), 0,
+			   cfg_buf, total);
+	if (n < 9 || cfg_buf[1] != 0x02)
+		return -1;
+	if ((unsigned int)n < total)
+		total = (unsigned int)n;
+	*total_out = total;
+	return 0;
+}
+
+static int rndis_choose_config(void)
+{
+	unsigned char desc[18];
+	unsigned int ncfg, i;
+	int n;
+
+	n = usb_control_in(dev.ctrl, dev.addr, dev.mps, dev.low,
+			   0x80, 0x06, (unsigned short)(1u << 8), 0,
+			   desc, sizeof(desc));
+	if (n < 18)
+		return -1;
+	ncfg = desc[17];
+	if (!ncfg)
+		ncfg = 1;
+	if (ncfg > 8)
+		ncfg = 8;
+
+	for (i = 0; i < ncfg; i++) {
+		struct rndis_cfg cfg;
+		unsigned int total;
+
+		if (rndis_read_config(i, &total) < 0)
+			continue;
+		if (!rndis_parse_config(total, &cfg))
+			continue;
+		if (usb_control_out(dev.ctrl, dev.addr, dev.mps, dev.low,
+				    0x00, 0x09,
+				    (unsigned short)cfg.config, 0) < 0)
+			continue;
+		rndis_delay(10);
+		if (cfg.data_alt != 0 &&
+		    usb_control_out(dev.ctrl, dev.addr, dev.mps, dev.low,
+				    0x01, 0x0B,
+				    (unsigned short)cfg.data_alt,
+				    (unsigned short)cfg.data_iface) < 0)
+			continue;
+		dev.config = cfg.config;
+		dev.ctrl_iface = cfg.ctrl_iface;
+		dev.data_iface = cfg.data_iface;
+		dev.ep_in = cfg.ep_in;
+		dev.ep_in_mps = cfg.ep_in_mps;
+		dev.ep_out = cfg.ep_out;
+		dev.ep_out_mps = cfg.ep_out_mps;
+		dev.ep_int = cfg.ep_int;
+		dev.ep_int_mps = cfg.ep_int_mps;
+		serial_puts(SERIAL_COM1, "rndis: config ");
+		serial_putdec(SERIAL_COM1, dev.config);
+		serial_puts(SERIAL_COM1, ", iface ");
+		serial_putdec(SERIAL_COM1, dev.ctrl_iface);
+		serial_puts(SERIAL_COM1, "/");
+		serial_putdec(SERIAL_COM1, dev.data_iface);
+		serial_puts(SERIAL_COM1, ", ep ");
+		serial_putdec(SERIAL_COM1, dev.ep_in);
+		serial_puts(SERIAL_COM1, "/");
+		serial_putdec(SERIAL_COM1, dev.ep_out);
+		serial_puts(SERIAL_COM1, "\n");
+		return 0;
+	}
+	return -1;
+}
+
+static void rndis_check(void)
+{
+	if (!dev.present)
+		return;
+	if (dev.gen != usb_generation() ||
+	    (dev.port != 0xFFu && !usb_port_connected(dev.ctrl, dev.port))) {
+		dev.present = 0;
+		dev.ready = 0;
+		dev.link = 0;
+	}
+}
+
+static int net_init(void)
+{
+	rndis_check();
+	if (!dev.present)
+		return -1;
+	if (dev.ready)
+		return 0;
+	return rndis_start();
+}
+
+static void net_get_mac(unsigned char mac[6])
+{
+	unsigned int i;
+
+	for (i = 0; i < 6; i++)
+		mac[i] = dev.mac[i];
+}
+
+static int net_rx(unsigned char *buf, unsigned int maxlen)
+{
+	rndis_check();
+	if (!dev.present || !dev.ready)
+		return -1;
+
+	for (;;) {
+		/* Parse every complete message in the current chunk. */
+		while (dev.rx_pos + 44 <= dev.rx_len) {
+			unsigned int msg_type = rd32le(dev.rx_buf + dev.rx_pos);
+			unsigned int msg_len = rd32le(dev.rx_buf + dev.rx_pos + 4);
+			unsigned int data_off, data_len, advance, data_pos, i;
+
+			if (msg_type != RNDIS_MSG_PACKET ||
+			    msg_len < 44 || msg_len > RNDIS_RX_MAX) {
+				dev.rx_pos = dev.rx_len;
+				dev.rx_errors++;
+				return -1;
+			}
+			/* A message split across bulk transfers: keep the
+			 * tail and append the next transfer. */
+			if (msg_len > dev.rx_len - dev.rx_pos)
+				break;
+
+			data_off = rd32le(dev.rx_buf + dev.rx_pos + 8);
+			data_len = rd32le(dev.rx_buf + dev.rx_pos + 12);
+			advance = msg_len;
+			if (dev.align > 1)
+				advance = (advance + dev.align - 1) &
+					  ~(dev.align - 1);
+			if (data_len > msg_len || data_off > msg_len - data_len ||
+			    msg_len - data_len - data_off < 8) {
+				dev.rx_pos += advance;
+				if (dev.rx_pos > dev.rx_len)
+					dev.rx_pos = dev.rx_len;
+				dev.rx_errors++;
+				continue;
+			}
+			data_pos = dev.rx_pos + 8 + data_off;
+			dev.rx_pos += advance;
+			if (dev.rx_pos > dev.rx_len)
+				dev.rx_pos = dev.rx_len;
+
+			if (data_len > maxlen || data_len < 14) {
+				dev.rx_errors++;
+				continue;
+			}
+			for (i = 0; i < data_len; i++)
+				buf[i] = dev.rx_buf[data_pos + i];
+			dev.rx_frames++;
+			return (int)data_len;
+		}
+
+		/* Move an incomplete message to the start and append more
+		 * bytes from the next bulk transfer. */
+		if (dev.rx_pos > 0) {
+			unsigned int rem;
+
+			if (dev.rx_pos > dev.rx_len) {
+				dev.rx_pos = dev.rx_len = 0;
+			} else {
+				rem = dev.rx_len - dev.rx_pos;
+				{
+					unsigned int i;
+
+					for (i = 0; i < rem; i++)
+						dev.rx_buf[i] =
+							dev.rx_buf[dev.rx_pos + i];
+				}
+				dev.rx_pos = 0;
+				dev.rx_len = rem;
+			}
+		}
+		if (dev.rx_len >= sizeof(dev.rx_buf)) {
+			dev.rx_pos = dev.rx_len = 0;
+			dev.rx_errors++;
+			return -1;
+		}
+		{
+			int n = usb_bulk_in(dev.ctrl, dev.addr, dev.ep_in,
+					    dev.ep_in_mps, dev.raw_buf,
+					    sizeof(dev.raw_buf));
+			unsigned int i;
+
+			if (n <= 0)
+				return -1;
+			if (dev.rx_len + (unsigned int)n > sizeof(dev.rx_buf)) {
+				dev.rx_pos = dev.rx_len = 0;
+				dev.rx_errors++;
+				return -1;
+			}
+			for (i = 0; i < (unsigned int)n; i++)
+				dev.rx_buf[dev.rx_len + i] = dev.raw_buf[i];
+			dev.rx_len += (unsigned int)n;
+		}
+	}
+}
+
+static int net_tx(const unsigned char *buf, unsigned int len)
+{
+	unsigned int i;
+
+	rndis_check();
+	if (!dev.present || !dev.ready || len > 1514)
+		return -1;
+	if (dev.max_transfer && 44 + len > dev.max_transfer)
+		return -1;
+
+	for (i = 0; i < 44; i++)
+		dev.tx_buf[i] = 0;
+	wr32le(dev.tx_buf + 0, RNDIS_MSG_PACKET);
+	wr32le(dev.tx_buf + 4, 44 + len);
+	wr32le(dev.tx_buf + 8, 36);       /* offset from the 8-byte prefix */
+	wr32le(dev.tx_buf + 12, len);
+	for (i = 0; i < len; i++)
+		dev.tx_buf[44 + i] = buf[i];
+
+	if (usb_bulk_out(dev.ctrl, dev.addr, dev.ep_out, dev.ep_out_mps,
+			 dev.tx_buf, 44 + len) != 0) {
+		dev.tx_errors++;
+		return -1;
+	}
+	dev.tx_frames++;
+	return 0;
+}
+
+static void net_print_info(void)
+{
+	rndis_check();
+	io_putstr("Android USB tethering (RNDIS)\n");
+	io_putstr("  MAC ");
+	put_mac_io();
+	io_putstr("\n");
+	if (!dev.present) {
+		io_putstr("  not attached\n");
+		return;
+	}
+	if (!dev.ready)
+		io_putstr("  RNDIS not initialized\n");
+	else if (dev.link)
+		io_putstr("  link up (DHCP)\n");
+	else
+		io_putstr("  link down (enable USB tethering on the phone)\n");
+}
+
+static void net_reset(void)
+{
+	dev.ready = 0;
+	dev.link = 0;
+	dev.rx_pos = dev.rx_len = 0;
+	if (!dev.present)
+		return;
+	rndis_send_halt();
+	if (rndis_choose_config() < 0) {
+		dev.present = 0;
+		dev.ready = 0;
+		dev.link = 0;
+		return;
+	}
+	(void)rndis_start();
+}
+
+static void net_stop(void)
+{
+	dev.ready = 0;
+	dev.link = 0;
+	dev.rx_pos = dev.rx_len = 0;
+}
+
+const struct netdev rndis_netdev = {
+	"rndis",
+	"Android USB tethering (RNDIS)",
+	net_init,
+	net_get_mac,
+	net_rx,
+	net_tx,
+	net_print_info,
+	0,
+	0,
+	net_reset,
+	0,
+	0,
+	0,
+	0,
+	0,
+	net_stop,
+};
+
+static int device_probe(unsigned int ctrl, unsigned int addr,
+			unsigned int mps, int low_speed, unsigned int port,
+			unsigned int vendor, unsigned int product)
+{
+	struct rndis_saved saved;
+	unsigned int gen = usb_generation();
+	int was_ready = dev.ready;
+
+	(void)vendor;
+	(void)product;
+
+	if (!usb_bulk_supported(ctrl))
+		return 0;
+
+	/* A probe runs for every USB device, not just ours.  Save the current
+	 * phone state and put it back if this device is not an RNDIS
+	 * function.  Do not clear an old ready state on a generation change
+	 * here: a full scan may probe a mouse before the phone. */
+	rndis_save(&saved);
+
+	dev.ctrl = ctrl;
+	dev.addr = addr;
+	dev.mps = mps;
+	dev.low = low_speed;
+	dev.port = port;
+	dev.config = 0;
+	dev.ready = 0;
+	dev.link = 0;
+	dev.rx_pos = dev.rx_len = 0;
+	dev.xid = 0;
+	dev.present = 1;
+
+	if (rndis_choose_config() < 0) {
+		rndis_restore_after_probe(&saved, ctrl, port, gen);
+		return 0;
+	}
+
+	/* Do not run the RNDIS control handshake for a fresh boot-time probe:
+	 * an Ethernet NIC may be the active link.  If the phone was already
+	 * ready before this scan, re-establish it now (a full `lsusb` scan
+	 * resets the device configuration). */
+	dev.gen = gen;
+	if (was_ready) {
+		if (rndis_start() < 0 && saved.present &&
+		    (saved.ctrl != ctrl || saved.port != port ||
+		     saved.addr != addr)) {
+			rndis_restore(&saved);
+			return 0;
+		}
+	}
+	netdev_hotplug();
+	return 1;
+}
+
+void rndis_register(void)
+{
+	usb_register_device_probe(device_probe);
+}

+ 12 - 0
rndis.h

@@ -0,0 +1,12 @@
+/* USB RNDIS tethering driver (Android phones and QEMU usb-net). */
+#ifndef RNDIS_H
+#define RNDIS_H
+
+#include "netdev.h"
+
+extern const struct netdev rndis_netdev;
+
+/* Register the USB device probe; call before the first USB scan. */
+void rndis_register(void);
+
+#endif

+ 6 - 1
uhci.c

@@ -69,7 +69,10 @@ struct uhci_qh {
 	unsigned int element;
 	unsigned int element;
 } __attribute__((aligned(16)));
 } __attribute__((aligned(16)));
 
 
-#define UHCI_NUM_TD 16
+/* Control transfers are built from SETUP + one TD per max-packet chunk +
+ * STATUS in this fixed array.  32 entries cover a full 2 KB descriptor read
+ * at 64-byte packets (and the RNDIS 1 KB control/config buffers). */
+#define UHCI_NUM_TD 32
 
 
 /* Frame list lives in low memory (below the kernel at 0x7E00) to avoid
 /* Frame list lives in low memory (below the kernel at 0x7E00) to avoid
    bloating the kernel's BSS past its link-time budget (see kernel.ld). It
    bloating the kernel's BSS past its link-time budget (see kernel.ld). It
@@ -351,6 +354,8 @@ static int control_transfer(unsigned int dev_addr, unsigned int mps,
 		return -1;
 		return -1;
 	if (mps == 0 || mps > 64)
 	if (mps == 0 || mps > 64)
 		mps = 64;
 		mps = 64;
+	if (len > (UHCI_NUM_TD - 2) * mps)
+		return -1;
 
 
 	for (i = 0; i < 8; i++)
 	for (i = 0; i < 8; i++)
 		setup_buf[i] = setup[i];
 		setup_buf[i] = setup[i];

+ 8 - 0
usb.c

@@ -741,6 +741,14 @@ int usb_bulk_in(unsigned int ctrl, unsigned int addr, unsigned int ep,
 					    mps, buf, len);
 					    mps, buf, len);
 }
 }
 
 
+int usb_bulk_supported(unsigned int ctrl)
+{
+	if (ctrl >= n_usb_ctrls)
+		return 0;
+	return usb_ctrls[ctrl].ops->bulk_in != 0 &&
+	       usb_ctrls[ctrl].ops->bulk_out != 0;
+}
+
 int usb_scan(usb_probe_fn probe)
 int usb_scan(usb_probe_fn probe)
 {
 {
 	unsigned int c, p;
 	unsigned int c, p;

+ 4 - 0
usb.h

@@ -55,6 +55,10 @@ int usb_bulk_out(unsigned int ctrl, unsigned int addr, unsigned int ep,
 int usb_bulk_in(unsigned int ctrl, unsigned int addr, unsigned int ep,
 int usb_bulk_in(unsigned int ctrl, unsigned int addr, unsigned int ep,
 		unsigned int mps, unsigned char *buf, unsigned int len);
 		unsigned int mps, unsigned char *buf, unsigned int len);
 
 
+/* 1 when the controller behind `ctrl` implements both bulk directions.
+ * UHCI/OHCI do not, so device drivers that need bulk must check this. */
+int usb_bulk_supported(unsigned int ctrl);
+
 /* Device-level probe for drivers that do not use HID interfaces (the
 /* Device-level probe for drivers that do not use HID interfaces (the
  * USB Ethernet and mass-storage drivers parse the whole configuration
  * USB Ethernet and mass-storage drivers parse the whole configuration
  * themselves).  Return 1 when the device was claimed.  Several probes may
  * themselves).  Return 1 when the device was claimed.  Several probes may