Просмотр исходного кода

Add Intel 7265D/3165 WiFi with WPA2-PSK for the Chromebook

The Braswell Chromebook has no wired NIC.  Drive its built-in Intel
7265D/3165 as a normal netdev so DHCP, DNS, TCP, curl and the browser
work over WiFi.

Kernel (~20 KB, all buffers page-allocated):
- iwl_trans.c: polled PCIe transport after Linux iwlwifi (7000 family):
  APM init, legacy RX ring, gen1 TFD queues, firmware section DMA,
  wide-header host commands.
- iwl_mvm.c: 7265D-29 firmware flow: INIT image with NVM/calibration,
  runtime image with PHY-DB replay, DQA, aux station, LMAC scan,
  PHY/MAC/binding/quota contexts, AP station, time event, CCMP keys.
- wifi.c: 802.11 station (auth/assoc, beacon/RSN parsing, Ethernet <->
  802.11 + CCMP header), EAPOL queue, `wifi` netdev and SYS_WIFI (110).
- netdev gains an optional link_up() hook; boot DHCP skips a down link.
  netdev_shutdown() always stops the card before a kexec.

Ring 3:
- wifi command (status/up/scan/connect/disconnect) and a background
  helper for group rekeys.
- wpa.c/wpa_crypto.c: WPA2-PSK 4-way and group handshake (SHA-1, HMAC,
  PBKDF2, PRF, AES-128, RFC 3394 unwrap); host test `make test-wpa`.

Build: iwlwifi-7265D-29.ucode is packed under firmware/ from the host's
linux-firmware (WIFI_FW overrides); PACK_MAX/CMDS_GZ_MAX raised to 2 MB;
floppy images use a firmware-less lite pack.

Not yet tested on the hardware.  Docs and AGENTS.md updated (known
issue 35 lists the limits).
Johannes Zellner 1 неделя назад
Родитель
Сommit
e21ed52300
33 измененных файлов с 5168 добавлено и 44 удалено
  1. 2 0
      .gitignore
  2. 86 20
      AGENTS.md
  3. 74 11
      Makefile
  4. 1 0
      asix.c
  5. 11 6
      docs/boot.html
  6. 5 0
      docs/development.html
  7. 64 0
      docs/drivers.html
  8. 6 1
      docs/index.html
  9. 1 0
      docs/memory.html
  10. 18 0
      docs/network.html
  11. 6 4
      docs/userland.html
  12. 1 0
      e1000e.c
  13. 1126 0
      iwl_mvm.c
  14. 58 0
      iwl_mvm.h
  15. 1170 0
      iwl_trans.c
  16. 106 0
      iwl_trans.h
  17. 2 1
      kernel.c
  18. 1 0
      ne2000.c
  19. 8 0
      netdev.c
  20. 4 0
      netdev.h
  21. 1 0
      r8168.c
  22. 1 0
      rndis.c
  23. 3 0
      syscall.c
  24. 73 0
      syscall.h
  25. 497 0
      ucmd_wifi.c
  26. 1 1
      vesa_stage.S
  27. 805 0
      wifi.c
  28. 18 0
      wifi.h
  29. 298 0
      wpa.c
  30. 54 0
      wpa.h
  31. 383 0
      wpa_crypto.c
  32. 36 0
      wpa_crypto.h
  33. 248 0
      wpa_test.c

+ 2 - 0
.gitignore

@@ -29,3 +29,5 @@ ujson_test
 uhttp_cookie_test
 chat_login_test
 chat-test-out/
+wpa_test
+firmware/

+ 86 - 20
AGENTS.md

@@ -81,6 +81,7 @@ make test-mujs  # host smoke test for the vendored MuJS engine
 make test-font  # host TrueType parser/rasterizer specimen test
 make test-font-asan  # ASan/UBSan variant
 make test-touchpad  # host tests for the contact gesture engine
+make test-wpa   # host tests for the WPA2-PSK supplicant (SHA-1/PBKDF2/PRF/AES, 4-way)
 make test-chat  # host tests: JSON parser, cookie jar, chat login parsers (ASan)
 make test-chat-e2e  # QEMU + tools/mock_chat.py chat end-to-end (CHAT_E2E=--totp...)
 make compat-serve  # serve the browser A/B ladder on port 8000
@@ -94,10 +95,15 @@ make clean
   matching `MM_MAX_PHYS` in `phys.h`; all run and UEFI targets pass `-m`.
 - The command pack is the system rootfs: `cmds.pack` (NBPAK1), gzip-compressed
   to `cmds_pack_gz.bin`, wrapped by `mkrootfs` with a one-sector `NBROOT1`
-  header into `rootfs.bin` (floppy append) and `cmds.img` (the 8 MB USB
-  partition image).  The kernel itself no longer carries the pack; the boot
-  path loads it into RAM and `ramfs_init` takes a private copy (`bin/<name>`
-  mounted at `/ramfs`).
+  header into `cmds.img` (the 8 MB USB partition image) and `BOOTX64.EFI`.
+  The floppy images append `rootfs.bin`, built the same way from
+  `cmds-lite.pack` (everything but `firmware/*`), because the ~1 MB WiFi
+  firmware does not fit a 1.44 MB floppy.  The kernel itself no longer
+  carries the pack; the boot path loads it into RAM and `ramfs_init` takes a
+  private copy (`bin/<name>` mounted at `/ramfs`).
+- The WiFi firmware `firmware/iwlwifi-7265D-29.ucode` is decompressed from
+  the host's linux-firmware (`WIFI_FW` overrides the search; `zstd` needed for
+  `.zst`).  Without it the build prints a note and packs no firmware.
 - `root.img` is a second FAT12 floppy holding the disk fallback copies of the
   browser/gallery (`BROWSER`, `GALLERY`) and its `DEMO.HTM`/`JS.HTM` test
   pages plus `PIC.BMP`, and a few test files; it requires `mtools` to build.
@@ -107,9 +113,10 @@ make clean
   builds the legacy floppy/USB images normally.
 - `usb.img` is 9 MB: partition 1 (type `0x06`, LBA 63, 1024 sectors) is the
   boot sector + kernel and partition 2 (type `0x7F`, LBA 1088) is the 8 MB
-  rootfs image (`cmds.img`), 512 KB behind the boot sector.  The header and
-  the 242 KB gzip pack therefore still live in the first 1.44 MB, which even a
-  CHS-only USB BIOS can read.  The boot sector's `pack_lba` field points the
+  rootfs image (`cmds.img`), 512 KB behind the boot sector.  With the WiFi
+  firmware the gzip pack is ~1 MB, so it now ends past the first 1.44 MB: a
+  BIOS that boots the stick as a CHS-only floppy can no longer read all of
+  it (fixed-disk LBA boots are fine).  The boot sector's `pack_lba` field points the
   VESA stage at partition 2.  `usb-efi.img` (17 MB) adds an 8 MB FAT16 ESP
   as partition 3 (type `0xEF`, LBA 18432); `BOOTX64.EFI` embeds the kernel +
   gz pack.  The `install` command clones this used image (MBR through the
@@ -138,7 +145,7 @@ make clean
    12-dword `struct boot_info` (magic/checksum/rsdp/flags/pack range) to
    `0x500`, enters protected mode and jumps to `kernel_entry` (`entry.S`,
    re-points ESP to the current stack top, then `kernel_main`).  The pack
-   never occupies the low gap, so the cap is `PACK_MAX` (1 MB) and the
+   never occupies the low gap, so the cap is `PACK_MAX` (2 MB) and the
    kernel BSS/boot stack may extend past `0x60000`.  The stage prints
    `Loading rootfs [d=<drive> lba=<hex> e=<0|1> m=<C|L>]...`, then a dot
    after the header and one per 16 KB chunk, so a BIOS hang is localised.
@@ -546,7 +553,9 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `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
+  failure.  `wifi.c` (the Intel 7265D/3165 netdev, see the WiFi bullet) is
+  last in the table; `struct netdev` has an optional `link_up()` hook, and
+  the boot DHCP is skipped while it returns 0.  `net.c` — ARP + ICMP echo, IPv4/UDP
   send + parse helpers,
   shared ARP resolution (`net_arp_resolve`) and routing (`net_next_hop`), frame
   decode, `net_checksum()`/`net_checksum_tcp()`.  `dhcp.c` — minimal DHCP client
@@ -584,6 +593,41 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   lives in the command pack, so `make net-cmds` updates it without a
   kernel reload.  Static IP default `192.168.178.240`, mask/gateway learned
   from DHCP (off-subnet traffic goes via the router).
+- **WiFi (Intel 7265D/3165, the HP Chromebook)**: `iwl_trans.c/h` — PCIe
+  transport after Linux iwlwifi (7000 family): PCI scan for
+  `8086:095a/095b/3165/3166`, D0, BAR0 mapped with `process_map_mmio_all`,
+  APM init, one legacy RX queue (256 x 4 KB RBDs), gen1 128-byte TFD queues
+  with dword byte-count tables, firmware TLV parse and section DMA through
+  the FH service channel (128 KB bounce, `LMPM_CHICK` for the extended
+  range), polled `CSR_INT`.  Everything is page-allocated; the NIC is kept
+  awake (MAC access request held) and INTx is disabled.  Host commands use
+  the wide header (legacy ids go out as group 1, like Linux's `DEF_ID`).
+  `iwl_mvm.c/h` — firmware commands for the 7265D-29 API: INIT image (BT
+  config, NVM HW section -> MAC at word 0x15, TX antennas, PHY config,
+  `CALIB_RES_NOTIF_PHY_DB` collection until `INIT_COMPLETE`), runtime image
+  (PHY-DB replay, PHY config, BT config, DQA enable, aux station 0 on queue
+  1, PHY context 0, CAM power, MCC `ZZ`, MAC context 0), LMAC scan
+  (`SCAN_OFFLOAD_REQUEST`, wildcard active, 37 channels), connect (PHY
+  context, binding + quota, `SCD_QUEUE_CFG` queue 4, AP station 1, time
+  event), `ADD_STA_KEY` v1, `TX_CMD` v6 (fixed legacy rates: 1M CCK / 6M
+  mgmt, 12M OFDM data), legacy `RX_PHY`/`RX_MPDU` parsing.  `wifi.c/h` —
+  802.11 station: beacon/probe parsing (SSID, DS channel, TIM DTIM, RSN with
+  PSK + CCMP pairwise/group), open-system auth and a non-QoS association
+  request (no WMM/HT IEs), Ethernet <-> 802.11 data + LLC/SNAP + host-built
+  CCMP header/PN, an EAPOL queue (ethertype 0x888e never reaches
+  `net_pump()`), the `wifi` netdev and `SYS_WIFI` (110, multiplexed op).
+  The firmware is loaded on the first `wifi` command, not at boot.
+  `netdev_shutdown()` always calls `wifi_shutdown()` before a kexec (the RX
+  ring would keep writing into reused pages).  The ring-3 side is
+  `ucmd_wifi.c` (`wifi`, `wifi up|scan|connect <ssid> [pass]|disconnect`),
+  `wpa.c/h` (4-way + group handshake, key descriptor v2) and
+  `wpa_crypto.c/h` (SHA-1, HMAC, PBKDF2, PRF, AES-128, RFC 3394 unwrap; host
+  test `make test-wpa`).  After the handshake `wifi connect` installs the
+  TK/GTK, calls `SYS_WIFI_AUTHORIZE` (data port open + `netdev_select
+  ("wifi")`), runs DHCP and leaves `wifi __keep` running for group rekeys.
+  There is no QEMU model: test on the Chromebook over `make net-dev` with
+  the RNDIS phone/ASIX dongle as the management link and `make netmon` for
+  the `iwl:`/`wifi:` trail.
 - **Hot-reload (kexec)**: `kexec.c/h`, `kexec_tramp.S`, `entry.S`, and the
   host-side `kexec_send.c` — reload the kernel over serial without rebooting
   (C-light: reuses the current framebuffer, re-runs `kernel_main`).
@@ -1116,7 +1160,7 @@ filesystem commands operate inside a mount, e.g. `cat /floppy1/HELLO.TXT`).
 `cpuinfo`, `ls`, `cat`, `save`, `rm`, `mkdir`, `rmdir`, `meminfo`, `top`, `spin`,
 `clock`, `colors`, `settime`, `date`, `files`, `gallery`, `chat`, `view`, `sensors`, `powerinfo`, `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
 `pong`, `netsend`, `netrecv`, `netlog`, `netconsole`, `netregs`, `netloop`,
-`netreset`, `websrv`, `curl`, `solitaire` and `hello` are files in `/ramfs/bin`
+`netreset`, `websrv`, `curl`, `wifi`, `solitaire` and `hello` are files in `/ramfs/bin`
 (packed by the Makefile), found through the shell's PATH; the rest are kernel
 commands spawned as processes, or builtins (`cd`, `path`, `help`, `clear`).
 
@@ -1167,15 +1211,17 @@ The commands live in `cmds.pack` (`bin/<name>` entries, built by `mkpack`),
 compressed with `libdeflate-gzip -12` when it is installed (falling back to
 `gzip -9`) to `cmds_pack_gz.bin` and wrapped by `mkrootfs` with a
 one-sector `NBROOT1` header (magic, version, exact `pack_bytes`, checksum,
-gzip flag).  The build rejects a pack above the `PACK_MAX` cap (1 MB);
+gzip flag).  The build rejects a pack above the `PACK_MAX` cap (2 MB,
+`CMDS_GZ_MAX` in the Makefile, `PACK_MAX` in `vesa_stage.S`);
 `libdeflate` buys several KB over `gzip -9` and is still preferred.  The boot
 path loads the gz pack into RAM — the legacy stage copies it directly to
 `0x900000` with INT 15h AH=87h, the UEFI loader into a loader-data buffer
 below 512 MB, kexec via its staging buffer — and `ramfs_init()`
 inflates it into page-allocated memory and mounts it read-only at `/ramfs`.
 The kernel image no longer contains it, so the pack no longer moves `_end`;
-the high-memory legacy path supports up to 1 MB (known issue 8).  The UI
-font subsets live in the pack under `fonts/`.
+the high-memory legacy path supports up to 2 MB (known issue 8).  The UI
+font subsets live in the pack under `fonts/`, the WiFi firmware under
+`firmware/`.  The floppy images use `cmds-lite.pack` (no firmware).
 
 `rootfs.bin` is the floppy append (header + pack); `cmds.img` is the 8 MB
 rootfs partition image written to USB partition 2.  `cmds-dev`/`net-cmds`
@@ -1583,12 +1629,14 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
    load (the USB rootfs partition is 8 MB, so this only bites if the cap is
    raised without a bigger partition).  The legacy stage now copies the
    compressed pack directly to `0x900000` with INT 15h AH=87h, so the cap is
-   `PACK_MAX` 1 MB (not the old ~255 KB low-gap limit).  The browser and
+   `PACK_MAX` 2 MB (raised from 1 MB for the WiFi firmware).  The browser and
    its ring-3 dependencies are compiled with function sections and linked
-   with `--gc-sections`; the current pack with the UI fonts is ~445 KiB
-   (455591 bytes), leaving ~580 KiB under the cap.  `libdeflate-gzip -12` is
-   still preferred for the extra headroom, though the 1 MB cap leaves room
-   for `gzip -9` as a fallback.
+   with `--gc-sections`; the current full pack with the UI fonts and the
+   1,036,312-byte WiFi firmware is ~982 KiB gzip (1005719 bytes), inflating
+   to ~2 MB, which adds roughly half a second to the boot; the floppy lite
+   pack is ~540 KiB.  `libdeflate-gzip -12` is still preferred.  Over
+   115200 serial a raw `cmds-dev` pack now takes about three minutes; use
+   `net-cmds`.
 9. SMP is **ACPI/MADT only**: no Intel MP-table fallback, so a Pentium II SMP
     board that exposes only MP tables stays UP (deliberate; there is no test
     hardware).
@@ -1644,8 +1692,9 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
 
 21. The TCP backlog's early-request buffers cost 8 KB of kernel BSS
     (8 slots x 1 KB), and the FAT listing cache another 5 KB.  The command
-    pack is out of the kernel now, so `_end` keeps ~70 KB of headroom below
-    the `0x90000` wall; the remaining limit is kernel code/buffers only.
+    pack is out of the kernel now; after the WiFi driver `_end` is ~0x88750,
+    ~31 KB below the `0x90000` wall, and the remaining limit is kernel
+    code/buffers only.
 
 22. Browser limits: JavaScript runs inline and external classic scripts on
     MuJS with the DOM surface described above (creation/mutation/selectors/
@@ -1874,3 +1923,20 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     attachments/images/GIFs, edits or deletes beyond what a reload shows;
     messages over 4 KB are truncated, history holds 240 messages, times are
     UTC and text is Latin-1.  Network calls block the UI for their duration.
+
+35. WiFi limits (`iwl_trans.c`, `iwl_mvm.c`, `wifi.c`): Intel 7265 rev D and
+    3165 only (one firmware, `iwlwifi-7265D-29`); a non-D 7265 is logged and
+    will likely fail.  Open networks and WPA2-PSK with CCMP pairwise *and*
+    group only: no WPA3/SAE, PMF/802.11w, 802.1X, TKIP, WEP or hidden-SSID
+    connects.  Legacy rates only (12 Mb/s data, no LQ/rate scaling, no
+    HT/VHT, no aggregation, non-QoS association), no power save, roaming,
+    background scan or scan while associated, no regulatory database beyond
+    the firmware's MCC `ZZ` default.  Polled RX (the WM idle loop and every
+    stack call drain it).  The connect and firmware load hold the BKL for up
+    to a few seconds.  Group rekeys need the background `wifi __keep` helper
+    (it carries the PTK in its argument and memory); if it is killed the link
+    drops at the next rekey.  The SNonce comes from the weak TLS DRBG.  The
+    driver was written against the Linux iwlwifi sources without hardware
+    in the loop; expect bring-up debugging on the Chromebook.  The kernel
+    budget is tight: WiFi added ~20 KB, `_end` is ~0x88750 (31 KB below the
+    `0x90000` wall).

Разница между файлами не показана из-за своего большого размера
+ 74 - 11
Makefile


+ 1 - 0
asix.c

@@ -369,6 +369,7 @@ const struct netdev asix_netdev = {
 	asix_default_mask,
 	0,
 	0,
+	0,
 };
 
 /* Read and parse the configuration descriptor.  The AX88772 has one

+ 11 - 6
docs/boot.html

@@ -169,7 +169,8 @@
 		</ol>
 		<p>
 			The pack no longer occupies the old <code>0x60000..0x9FBFF</code>
-			low gap, so the legacy cap is <code>PACK_MAX</code> (1 MB) and the
+			low gap, so the legacy cap is <code>PACK_MAX</code> (2 MB, raised
+			from 1 MB for the WiFi firmware) and the
 			kernel BSS/boot stack may use the gap. The kernel image only has to
 			stay below <code>0x90000</code> so the top of low memory and the
 			EBDA remain untouched; <span class="file">kernel.ld</span> enforces
@@ -279,8 +280,12 @@
 		<h2>Disk image layout</h2>
 		<p>
 			The build produces several images from the same boot sector, kernel
-			and rootfs. The layouts are intentionally conservative: the first
-			1.44 MB must remain readable by a CHS-only BIOS.
+			and rootfs. The floppy images append the <em>lite</em> pack
+			(<code>rootfs.bin</code> from <code>cmds-lite.pack</code>, everything
+			but <code>firmware/*</code>) so they still fit 1.44 MB. The USB
+			rootfs partition carries the full pack (about 1 MB gzip with the
+			WiFi firmware), which now ends past the first 1.44 MB: a BIOS that
+			boots the stick as a CHS-only floppy can no longer read all of it.
 		</p>
 
 		<figure class="figure">
@@ -295,7 +300,7 @@
 				<rect class="svg-box green" x="432" y="42" width="210" height="24" rx="3"/>
 				<rect class="svg-box" x="646" y="42" width="244" height="24" rx="3"/>
 				<text class="svg-tiny" x="186" y="59">kernel</text>
-				<text class="svg-tiny" x="440" y="59">rootfs.bin</text>
+				<text class="svg-tiny" x="440" y="59">rootfs.bin (lite)</text>
 				<text class="svg-tiny" x="654" y="59">zero padding</text>
 
 				<text class="svg-text" x="12" y="106">usb.img</text>
@@ -322,7 +327,7 @@
 				<text class="svg-tiny" x="232" y="288">gzip command pack</text>
 
 				<line class="svg-line" x1="160" y1="314" x2="890" y2="314"/>
-				<text class="svg-tiny" x="160" y="334">Schematic, not to scale. The first 1.44 MB keeps the pack reachable by CHS-only USB BIOSes.</text>
+				<text class="svg-tiny" x="160" y="334">Schematic, not to scale. Floppy images carry the lite pack (no firmware); the USB rootfs carries the full pack.</text>
 			</svg>
 			<figcaption>
 				<strong>Three images, one source tree.</strong> The dual-boot image
@@ -400,7 +405,7 @@
 		<h2>Failure modes to know</h2>
 		<ul>
 			<li><strong>No VBE mode.</strong> The legacy stage cannot produce a framebuffer; the kernel may start headless or the boot stops in the stage.</li>
-			<li><strong>Pack larger than the cap.</strong> The legacy BIOS path caps the compressed pack at 1 MB <code>PACK_MAX</code>; UEFI and kexec can carry larger packs up to the 8 MB ramfs cap.</li>
+			<li><strong>Pack larger than the cap.</strong> The legacy BIOS path caps the compressed pack at 2 MB <code>PACK_MAX</code> (<code>CMDS_GZ_MAX</code> in the Makefile); UEFI and kexec can carry larger packs up to the 8 MB ramfs cap. The WiFi firmware makes the full pack about 1 MB, and inflating it adds roughly half a second to the boot.</li>
 			<li><strong>PIT not ticking.</strong> <code>kernel_main</code> prints <code>*** PIT NOT TICKING ***</code> and halts; no process scheduling is possible.</li>
 			<li><strong>UEFI Secure Boot.</strong> The unsigned <code>BOOTX64.EFI</code> is rejected before any NebOS code runs.</li>
 			<li><strong>Stale boot info.</strong> The checksum makes an invalid <code>0x500</code> block read as absent rather than as a bogus pack or RSDP.</li>

+ 5 - 0
docs/development.html

@@ -80,6 +80,7 @@
 			<li><strong>User commands.</strong> Linked at <code>0x40000000</code> with <code>ucmd.ld</code>, stripped, and packed as <code>bin/&lt;name&gt;</code>.</li>
 			<li><strong>UEFI.</strong> <code>x86_64-w64-mingw32-gcc</code> builds <code>BOOTX64.EFI</code>; <code>make all</code> does not require it.</li>
 			<li><strong>Images.</strong> <code>mtools</code> builds <code>root.img</code> and the ESP.</li>
+			<li><strong>WiFi firmware.</strong> The pack includes <code>firmware/iwlwifi-7265D-29.ucode</code>, decompressed with <code>zstd</code> from the host's linux-firmware (<code>WIFI_FW=/path/to/file[.zst]</code> overrides the search). Without it the build prints a note and packs no firmware; the floppy images always use the firmware-less <code>cmds-lite.pack</code>.</li>
 		</ul>
 	</section>
 
@@ -179,6 +180,7 @@
 					<tr><td><code>make test-install</code></td><td>Boots the dual image with a USB mass-storage source and a blank target, types <code>install ide1</code>, verifies the clone and boots the target in BIOS and UEFI.</td></tr>
 					<tr><td><code>make test-images</code> / <code>test-images-asan</code></td><td>Host image-decoder and blit tests, with an AddressSanitizer variant.</td></tr>
 					<tr><td><code>make test-crypto</code></td><td>Host vectors for SHA-256, ChaCha20-Poly1305, X25519 and TLS helpers.</td></tr>
+					<tr><td><code>make test-wpa</code></td><td>Host vectors for the WPA2 supplicant: SHA-1, RFC 6070 PBKDF2, the 802.11 PSK and PRF examples, FIPS-197 AES, RFC 3394 unwrap, plus a simulated 4-way handshake, group rekey, replay and wrong-passphrase case.</td></tr>
 					<tr><td><code>make test-libc</code></td><td>Host tests for the ring-3 malloc, stdio/float formatting, math, 64-bit division helpers and setjmp/longjmp.</td></tr>
 					<tr><td><code>make test-mujs</code></td><td>Host smoke test for the vendored MuJS engine: arithmetic, strings, Math, Date, JSON, exceptions and the run limit.</td></tr>
 					<tr><td><code>make test-font</code> / <code>test-font-asan</code></td><td>Host specimen test for the fixed-point TrueType parser/rasterizer and glyph cache, with an AddressSanitizer/UBSan variant.</td></tr>
@@ -259,6 +261,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 			<li><strong>Existing processes are unaffected.</strong> They already loaded their ELF.</li>
 			<li><strong>The next spawn sees the new files.</strong></li>
 			<li><strong>RAM only.</strong> A cold boot uses the flashed rootfs; reflash after changing the bundle.</li>
+			<li><strong>Size.</strong> The raw pack is about 2 MB with the WiFi firmware, so <code>cmds-dev</code> over 115200 serial takes roughly three minutes; prefer <code>net-cmds</code>.</li>
 		</ul>
 	</section>
 
@@ -269,6 +272,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 			<li><strong>Installer.</strong> <code>make test-install</code> boots the dual image with its USB mass-storage source and a blank target, types <code>install ide1</code> through QMP, verifies the clone and boots the target in BIOS and (under OVMF) UEFI.</li>
 			<li><strong>Image library.</strong> <code>make test-images</code> decodes a corpus of PNG/JPEG/GIF/BMP/TGA/PNM/ICO/PAM files and checks blits; the ASan variant catches memory errors.</li>
 			<li><strong>Crypto.</strong> <code>make test-crypto</code> runs host vectors for the freestanding crypto code.</li>
+			<li><strong>WPA2.</strong> <code>make test-wpa</code> runs <span class="file">wpa_test.c</span> against <span class="file">wpa_crypto.c</span> and <span class="file">wpa.c</span>. The WiFi driver itself has no QEMU model: test it on the Chromebook over <code>make net-dev</code> with the RNDIS phone or ASIX dongle as the management link and <code>make netmon</code> for the <code>iwl:</code>/<code>wifi:</code> trail.</li>
 			<li><strong>Ring-3 libc.</strong> <code>make test-libc</code> runs the malloc stress test (32 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>
@@ -352,6 +356,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 			<li><code>panic.c</code> — fatal exception dump</li>
 			<li><code>kernel.ld</code>, <code>ucmd.ld</code> — link limits</li>
 			<li><code>tools/</code> — QMP USB and installer tests</li>
+			<li><code>wpa_test.c</code> — WPA2 supplicant host test (<code>make test-wpa</code>)</li>
 			<li><code>AGENTS.md</code> — developer notes and maintenance rule</li>
 		</ul>
 	</section>

+ 64 - 0
docs/drivers.html

@@ -55,6 +55,7 @@
 			<li><a href="#pci">PCI &amp; discovery</a></li>
 			<li><a href="#storage">Storage</a></li>
 			<li><a href="#usb">USB stack</a></li>
+			<li><a href="#wifi">WiFi (Intel 7265D/3165)</a></li>
 			<li><a href="#hid">Input</a></li>
 			<li><a href="#serial">Serial</a></li>
 			<li><a href="#sensors">Sensors &amp; power</a></li>
@@ -84,6 +85,7 @@
 					<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>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>WiFi</td><td><span class="file">iwl_trans.c</span> <span class="file">iwl_mvm.c</span> <span class="file">wifi.c</span></td><td>PCIe, Intel 7265D/3165 (<code>8086:095a/095b/3165/3166</code>)</td><td>Polled RX ring; firmware from <code>/ramfs/firmware</code>, loaded on first use</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>Serial</td><td><span class="file">serial.c</span></td><td>16550 UART, COM1</td><td>IRQ 4 ring buffer + polled transmitter</td></tr>
@@ -338,6 +340,64 @@
 		</p>
 	</section>
 
+	<section id="wifi">
+		<h2>WiFi (Intel 7265D/3165)</h2>
+		<p>
+			The HP Chromebook (Braswell) has no wired NIC; its built-in Intel
+			Wireless-AC 7265 rev D or 3165 is driven in three layers, all
+			polled. The kernel part is about 20 KB of code; every ring and
+			buffer is page-allocated so nothing new lands in the kernel BSS.
+		</p>
+		<figure class="figure">
+			<svg viewBox="0 0 920 300" role="img" aria-labelledby="wifi-title wifi-desc">
+				<title id="wifi-title">WiFi software layers</title>
+				<desc id="wifi-desc">The ring-3 wifi command runs the WPA2 handshake and talks to wifi.c through SYS_WIFI; the network stack uses wifi.c as a normal netdev. wifi.c uses iwl_mvm.c for firmware commands, which uses the iwl_trans.c PCIe transport to reach the card.</desc>
+
+				<rect class="svg-box blue" x="40" y="20" width="400" height="56" rx="9"/>
+				<text class="svg-text" x="60" y="44">wifi command + wpa.c (ring 3)</text>
+				<text class="svg-sub" x="60" y="64">scan · PBKDF2 · 4-way / group handshake</text>
+
+				<rect class="svg-box blue" x="480" y="20" width="400" height="56" rx="9"/>
+				<text class="svg-text" x="500" y="44">net stack</text>
+				<text class="svg-sub" x="500" y="64">DHCP · DNS · TCP via struct netdev</text>
+
+				<rect class="svg-box accent" x="40" y="112" width="840" height="50" rx="9"/>
+				<text class="svg-text" x="60" y="134">wifi.c — 802.11 station + the wifi netdev</text>
+				<text class="svg-sub" x="60" y="152">auth/assoc · 802.11 ↔ Ethernet (LLC/SNAP, CCMP header) · EAPOL queue · SYS_WIFI</text>
+
+				<rect class="svg-box" x="40" y="182" width="840" height="44" rx="9"/>
+				<text class="svg-text" x="60" y="209">iwl_mvm.c — firmware commands: INIT/RT image, NVM, scan, contexts, stations, keys</text>
+
+				<rect class="svg-box green" x="40" y="246" width="840" height="44" rx="9"/>
+				<text class="svg-text" x="60" y="273">iwl_trans.c — CSR/PRPH access, TFD + RX rings, firmware section DMA (PCIe)</text>
+
+				<path class="svg-line blue" d="M240 76v28"/>
+				<path class="svg-line blue" d="M234 98l6 7 6-7"/>
+				<path class="svg-line blue" d="M680 76v28"/>
+				<path class="svg-line blue" d="M674 98l6 7 6-7"/>
+				<path class="svg-line" d="M460 162v14"/>
+				<path class="svg-line" d="M460 226v14"/>
+			</svg>
+			<figcaption>
+				<strong>Keys stay in ring 3 until installed.</strong> The supplicant
+				derives the PTK and unwraps the GTK; the kernel only moves EAPOL
+				frames and hands the TK/GTK to the firmware, which does CCMP.
+				Sources: <span class="file">ucmd_wifi.c</span>,
+				<span class="file">wpa.c</span>, <span class="file">wifi.c</span>,
+				<span class="file">iwl_mvm.c</span>, <span class="file">iwl_trans.c</span>.
+			</figcaption>
+		</figure>
+		<ul>
+			<li><strong>Transport.</strong> <span class="file">iwl_trans.c</span> follows Linux iwlwifi for the 7000 family: APM init, one legacy RX queue of 256 × 4 KB RBDs, gen1 128-byte TFDs, byte-count tables in dwords, and the FH service channel loading firmware sections through a 128 KB bounce buffer. The NIC is kept awake (MAC access request held) and interrupts stay masked; PCI INTx is disabled. Host commands use the wide 8-byte header (legacy commands go out as group 1).</li>
+			<li><strong>Firmware.</strong> <code>iwlwifi-7265D-29.ucode</code> ships in the command pack as <code>firmware/iwlwifi-7265D-29.ucode</code> (1,036,312 bytes). It is a single-CPU image with LMAC scan, DQA queues and the old station API. <span class="file">iwl_mvm.c</span> runs the INIT image (NVM read for the MAC address, calibration, PHY-DB collection), then the runtime image (PHY-DB replay, DQA, aux station, PHY context, CAM power, MCC <code>ZZ</code>, station MAC context).</li>
+			<li><strong>Queues.</strong> Command queue 0 (FIFO 7), aux queue 1 (scan probes), BSS queue 4 for the AP station (management and data, BE FIFO).</li>
+			<li><strong>Station.</strong> <span class="file">wifi.c</span> builds open-system authentication and the association request itself, without WMM or HT IEs, so data frames are plain non-QoS 802.11 + LLC/SNAP. Management frames go at 1 Mb/s CCK (6 Mb/s on 5 GHz), data at a fixed 12 Mb/s OFDM (no rate scaling table yet).</li>
+			<li><strong>Security.</strong> WPA2-PSK with CCMP only. The 4-way and group handshakes run in ring 3 (<span class="file">wpa.c</span>); the kernel queues EAPOL frames, installs the TK/GTK with <code>ADD_STA_KEY</code>, and the firmware does CCMP. The host builds the 8-byte CCMP header and its packet number.</li>
+			<li><strong>Bring-up on first use.</strong> The boot probe only finds the PCI function. The firmware is loaded by the first <code>wifi</code> command, so boot time and RAM do not change when WiFi is unused. The netdev reports <code>link_up() = 0</code> until it is connected, so the boot DHCP is skipped.</li>
+			<li><strong>kexec.</strong> <code>netdev_shutdown()</code> always stops the card through <code>wifi_shutdown()</code>, even when it is not the active netdev, because its RX ring would keep writing into pages the next kernel reuses.</li>
+		</ul>
+	</section>
+
 	<section id="hid">
 		<h2>Input</h2>
 		<p>
@@ -515,6 +575,7 @@
 			<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>
 			<li><strong>EC.</strong> The Chrome EC path uses the ACPI v2 memmap only: no MEC host-command interface, EC SCI events, charger current/voltage, charging limit or EC firmware version. The ThinkPad H8 path is limited to its page-selected battery window and has no SCI handler. Battery/AC is polled by the WM once a second.</li>
+			<li><strong>WiFi.</strong> Intel 7265 rev D and 3165 only (the 7265D firmware); WPA2-PSK/CCMP and open networks, no WPA3/SAE, 802.1X, TKIP or WEP. No roaming, power save, background scan, HT/VHT, aggregation or rate scaling. Group rekeys need the background <code>wifi __keep</code> helper running.</li>
 			<li><strong>Suspend.</strong> There is no S0ix/suspend path; package C-states and the EC sleep handshake remain firmware-managed.</li>
 		</ul>
 	</section>
@@ -531,6 +592,9 @@
 			<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>rndis.c</code>, <code>rndis.h</code> — USB RNDIS tethering</li>
+			<li><code>iwl_trans.c</code>, <code>iwl_trans.h</code> — Intel 7265D/3165 PCIe transport</li>
+			<li><code>iwl_mvm.c</code>, <code>iwl_mvm.h</code> — WiFi firmware commands</li>
+			<li><code>wifi.c</code>, <code>wifi.h</code> — 802.11 station, <code>wifi</code> netdev, <code>SYS_WIFI</code></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>i2c.c</code>, <code>i2c.h</code> — DesignWare/LPSS I2C master</li>

+ 6 - 1
docs/index.html

@@ -217,9 +217,14 @@
 			</a>
 			<a class="card" href="network.html">
 				<h3>Networking</h3>
-				<p>NIC registry, ARP/ICMP/UDP, DHCP, DNS, NTP, TCP client and listener, TLS 1.3, USB tethering, netconsole and netkexec.</p>
+				<p>NIC registry, ARP/ICMP/UDP, DHCP, DNS, NTP, TCP client and listener, TLS 1.3, USB tethering, WiFi, netconsole and netkexec.</p>
 				<span class="card-tag">network.html</span>
 			</a>
+			<a class="card" href="drivers.html#wifi">
+				<h3>WiFi</h3>
+				<p>Intel 7265D/3165 on the Chromebook: PCIe transport, firmware from the command pack, LMAC scan, open and WPA2-PSK/CCMP with the handshake in ring 3.</p>
+				<span class="card-tag">drivers.html#wifi</span>
+			</a>
 			<a class="card" href="network.html#chat">
 				<h3>Chat client</h3>
 				<p>Native Cloudron Chat app: OIDC username/password/TOTP login without a browser, a uhttp cookie jar, an arena JSON parser and REST polling.</p>

+ 1 - 0
docs/memory.html

@@ -293,6 +293,7 @@
 	<section id="pack">
 		<h2>Rootfs pack lifetime</h2>
 		<ol>
+			<li>The compressed pack is at most 2 MB (<code>PACK_MAX</code>), so the legacy copy ends below <code>0xB00000</code>; inflated it is about 2 MB with the WiFi firmware (the 8 MB <code>RAMFS_MAX_DECOMPRESSED</code> cap applies).</li>
 			<li>The boot path places the gzip pack in RAM: the legacy stage copies it directly to <code>0x900000</code> with <code>INT 15h AH=87h</code>, UEFI into a loader-data buffer below 512 MB, kexec in its staging buffer.</li>
 			<li><code>mm_init</code> reserves <code>[pack_addr, pack_addr + pack_size)</code> so the frame allocator cannot reuse it.</li>
 			<li><code>ramfs_init</code> takes a private page-allocated copy, validates the <code>NBROOT1</code> header and inflates the pack into it.</li>

+ 18 - 0
docs/network.html

@@ -155,6 +155,20 @@
 			CDC-ECM/NCM, IPv6 and automatic DHCP after a hotplug are not
 			implemented.
 		</p>
+		<p>
+			<span class="file">wifi.c</span> is the built-in WiFi of the
+			Chromebook (Intel 7265D/3165, see the
+			<a href="drivers.html#wifi">driver page</a>). It is last in the
+			registry, so it only becomes active when nothing wired probes, and
+			it reports <code>link_up() = 0</code> until it is connected: the boot
+			DHCP checks that optional hook and skips the 4 s attempt. The
+			<code>wifi</code> command scans, associates, runs the WPA2-PSK
+			handshake in ring 3 and then calls <code>SYS_WIFI_AUTHORIZE</code>,
+			which opens the data port and selects the <code>wifi</code> netdev.
+			Data frames are converted between Ethernet and non-QoS 802.11 +
+			LLC/SNAP; EAPOL (ethertype <code>0x888e</code>) never reaches
+			<code>net_pump()</code> and is queued for the supplicant instead.
+		</p>
 		<div class="table-wrap">
 			<table>
 				<thead>
@@ -166,6 +180,7 @@
 					<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">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>
+					<tr><td><span class="file">wifi.c</span></td><td>Intel 7265D / 3165 (Chromebook)</td><td>PCIe (firmware)</td><td>Open and WPA2-PSK/CCMP; firmware loaded on first use; link down until <code>wifi connect</code>.</td></tr>
 				</tbody>
 			</table>
 		</div>
@@ -401,6 +416,7 @@
 					<tr><td>TLS DRBG</td><td>Weak (RDTSC/ticks/MAC)</td><td>Not suitable for high-value secrets.</td></tr>
 					<tr><td>WebDAV</td><td>No authentication</td><td>Anyone on the LAN can read mounts and write <code>/share</code>.</td></tr>
 					<tr><td>Chat session</td><td>Cookie saved in <code>/share/chat.cfg</code></td><td>A bearer credential in RAM until sign-out; the password is sent over unverified TLS and never stored.</td></tr>
+					<tr><td>WiFi WPA2</td><td>PSK/CCMP, handshake in ring 3</td><td>The SNonce comes from the weak TLS DRBG. The PTK lives in the <code>wifi __keep</code> helper's memory (and its argument) for group rekeys; no WPA3/PMF.</td></tr>
 					<tr><td>NTP</td><td>Unauthenticated SNTP</td><td>Anyone who can answer for the server name can set the clock.</td></tr>
 					<tr><td>NIC ownership</td><td>Raw lease for packet commands; shared TCP client table</td><td>Raw commands are mutually exclusive; up to twelve processes can hold one TCP connection each.  A killed owner is force-released.</td></tr>
 					<tr><td>Kernel/user isolation</td><td>None (identity map)</td><td>A ring-3 bug can reach any mapped kernel page.</td></tr>
@@ -414,6 +430,8 @@
 		<ul class="filelist">
 			<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>, <code>rndis.c</code></li>
+			<li><code>wifi.c</code>, <code>iwl_mvm.c</code>, <code>iwl_trans.c</code> — Intel 7265D/3165 WiFi</li>
+			<li><code>wpa.c</code>, <code>wpa_crypto.c</code>, <code>ucmd_wifi.c</code> — WPA2-PSK supplicant and the <code>wifi</code> command (<code>make test-wpa</code>)</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>dhcp.c</code>, <code>dns.c</code>, <code>ntp.c</code></li>

+ 6 - 4
docs/userland.html

@@ -4,7 +4,7 @@
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title>Userland | NebOS Architecture</title>
-<meta name="description" content="NebOS userland: ring-3 address space, ELF loading, the syscall ABI, the shell and PATH dispatch, the 46-command pack, GUI applications and the browser.">
+<meta name="description" content="NebOS userland: ring-3 address space, ELF loading, the syscall ABI, the shell and PATH dispatch, the 47-command pack, GUI applications and the browser.">
 <link rel="icon" href="favicon.svg" type="image/svg+xml">
 <link rel="stylesheet" href="style.css">
 </head>
@@ -38,12 +38,12 @@
 			Ring-3 programs are static ELFs linked at <code>0x40000000</code>.
 			The shell resolves a command name against builtins, the per-terminal
 			PATH and the kernel command registry, then spawns it with one
-			argument string. The command pack supplies 46 PATH commands by default.
+			argument string. The command pack supplies 47 PATH commands by default.
 		</p>
 		<div class="meta">
 			<span class="pill">int 0x80</span>
 			<span class="pill">one string argument</span>
-			<span class="pill">46 PATH commands</span>
+			<span class="pill">47 PATH commands</span>
 			<span class="pill">8 TTYs · 8 windows</span>
 		</div>
 	</div>
@@ -226,6 +226,7 @@
 					<tr><td>Window &amp; WM</td><td>55, 57–72, 80, 83–87, 109</td><td>key poll, WM attach/info/map/present/create_term, window create/present/input/resize/scroll</td></tr>
 					<tr><td>Process &amp; memory</td><td>73–79, 81, 88–90, 108</td><td>TTY, spawn, getpid, alive, kill, chdir, scheduler info, heap alloc/grow/free</td></tr>
 					<tr><td>TCP server</td><td>93–97, 99–101</td><td>listen, accept, server recv/send/close, peer, speed, MAC set</td></tr>
+					<tr><td>WiFi</td><td>110</td><td><code>SYS_WIFI(op, a2, a3)</code>: up, status, scan/results, connect/disconnect, EAPOL RX/TX, set key, authorize (<span class="file">wifi.c</span>)</td></tr>
 				</tbody>
 			</table>
 		</div>
@@ -311,7 +312,7 @@
 			</div>
 			<div class="card">
 				<h3>Network</h3>
-				<p><code>netinfo</code> <code>netip</code> <code>netdns</code> <code>host</code> <code>dhcp</code> <code>ping</code> <code>pong</code> <code>netsend</code> <code>netrecv</code> <code>netlog</code> <code>netconsole</code> <code>netregs</code> <code>netloop</code> <code>netreset</code> <code>net100</code> <code>netmac</code> <code>curl</code> <code>websrv</code></p>
+				<p><code>netinfo</code> <code>netip</code> <code>netdns</code> <code>host</code> <code>dhcp</code> <code>ping</code> <code>pong</code> <code>netsend</code> <code>netrecv</code> <code>netlog</code> <code>netconsole</code> <code>netregs</code> <code>netloop</code> <code>netreset</code> <code>net100</code> <code>netmac</code> <code>curl</code> <code>websrv</code> <code>wifi</code></p>
 			</div>
 			<div class="card">
 				<h3>GUI</h3>
@@ -417,6 +418,7 @@
 			<li><code>ngui.c</code> — GUI toolkit; <code>fonts/*.ttf</code> — UI subsets</li>
 			<li><code>browser.c</code>, <code>browser_html.c</code>, <code>js_browser.c/h</code>, <code>third_party/mujs/</code>, <code>gallery.c</code></li>
 			<li><code>ucmd_chat.c</code>, <code>chat_login.c</code>, <code>ujson.c</code>, <code>uhttp_cookie.c</code> — chat client</li>
+			<li><code>ucmd_wifi.c</code>, <code>wpa.c</code>, <code>wpa_crypto.c</code> — <code>wifi</code> command and the WPA2-PSK supplicant</li>
 		</ul>
 	</section>
 </main>

+ 1 - 0
e1000e.c

@@ -2293,4 +2293,5 @@ const struct netdev e1000e_netdev = {
 	e1000e_dump_regs, 0, e1000e_reset, e1000e_set_speed, e1000e_set_mac,
 	e1000e_default_ip, e1000e_default_mask, e1000e_dump_rx,
 	e1000e_stop,
+	0,
 };

+ 1126 - 0
iwl_mvm.c

@@ -0,0 +1,1126 @@
+/* Intel 7265D/3165 firmware command layer: see iwl_mvm.h.
+ *
+ * Follows Linux iwlmvm for the 7265D-29 API (no unified image, LMAC scan,
+ * DQA queues, old station API, ADD_STA v7, ADD_STA_KEY v1, PHY context v1,
+ * MAC context v1, TX_CMD v6, legacy RX_PHY + RX_MPDU):
+ *
+ *   INIT image: ALIVE -> BT config -> NVM (HW + SW sections) -> TX antennas
+ *     -> PHY_CONFIGURATION -> CALIB_RES_NOTIF_PHY_DB ... INIT_COMPLETE
+ *   runtime image: ALIVE -> TX antennas -> PHY DB replay -> PHY config ->
+ *     BT config -> DQA enable -> aux station -> PHY context -> device power
+ *     (CAM) -> MCC "ZZ" -> MAC context (station)
+ *
+ * Legacy rates only (no LQ table, no aggregation): management frames at
+ * 1 Mb/s CCK (2.4 GHz) or 6 Mb/s OFDM, data at 12 Mb/s OFDM. */
+
+#include "iwl_mvm.h"
+#include "iwl_trans.h"
+#include "mm.h"
+#include "serial.h"
+
+/* ---- command ids (fw/api/commands.h) ------------------------------------ */
+#define UCODE_ALIVE_NTFY         0x01
+#define REPLY_ERROR              0x02
+#define INIT_COMPLETE_NOTIF      0x04
+#define PHY_CONTEXT_CMD          0x08
+#define ADD_STA_KEY              0x17
+#define ADD_STA                  0x18
+#define REMOVE_STA               0x19
+#define TX_CMD                   0x1c
+#define SCD_QUEUE_CFG            0x1d
+#define MAC_CONTEXT_CMD          0x28
+#define TIME_EVENT_CMD           0x29
+#define TIME_EVENT_NOTIFICATION  0x2a
+#define BINDING_CONTEXT_CMD      0x2b
+#define TIME_QUOTA_CMD           0x2c
+#define SCAN_OFFLOAD_REQUEST_CMD 0x51
+#define SCAN_OFFLOAD_ABORT_CMD   0x52
+#define PHY_CONFIGURATION_CMD    0x6a
+#define CALIB_RES_NOTIF_PHY_DB   0x6b
+#define PHY_DB_CMD               0x6c
+#define SCAN_OFFLOAD_COMPLETE    0x6d
+#define POWER_TABLE_CMD          0x77
+#define NVM_ACCESS_CMD           0x88
+#define TX_ANT_CONFIGURATION_CMD 0x98
+#define BT_CONFIG                0x9b
+#define REPLY_RX_PHY_CMD         0xc0
+#define REPLY_RX_MPDU_CMD        0xc1
+#define MCC_UPDATE_CMD           0xc8
+#define DQA_ENABLE_CMD           ((5u << 8) | 0x00)   /* DATA_PATH_GROUP */
+
+#define ACTION_ADD     1
+#define ACTION_MODIFY  2
+#define ACTION_REMOVE  3
+#define CTXT_INVALID   0xffffffffu
+#define MAC_INDEX_AUX  4
+
+#define RATE_CCK       (1u << 9)
+#define RATE_ANT_A     (1u << 14)
+#define PLCP_1M        10
+#define PLCP_6M        13
+#define PLCP_12M       5
+
+#define TX_FLG_ACK      (1u << 3)
+#define TX_FLG_SEQ_CTL  (1u << 13)
+#define TX_FLG_BT_DIS   (1u << 12)
+
+/* ---- wire structures (packed, little endian) --------------------------- */
+#define PACKED __attribute__((packed))
+
+struct phy_ctx_cmd {                 /* PHY_CONTEXT_CMD_API_VER_1 */
+	unsigned int id_and_color, action, apply_time, tx_param_color;
+	unsigned char band, channel, width, ctrl_pos;
+	unsigned int txchain_info, rxchain_info, acquisition_data, dsp_cfg_flags;
+} PACKED;
+
+struct ac_qos {
+	unsigned short cw_min, cw_max;
+	unsigned char aifsn, fifos_mask;
+	unsigned short edca_txop;
+} PACKED;
+
+struct mac_ctx_cmd {                 /* MAC_CONTEXT_CMD_API_S_VER_1 */
+	unsigned int id_and_color, action, mac_type, tsf_id;
+	unsigned char node_addr[6];
+	unsigned short res0;
+	unsigned char bssid_addr[6];
+	unsigned short res1;
+	unsigned int cck_rates, ofdm_rates, protection_flags;
+	unsigned int cck_short_preamble, short_slot, filter_flags, qos_flags;
+	struct ac_qos ac[5];
+	/* struct iwl_mac_data_sta (+ p2p ctwin padding of the union) */
+	unsigned int is_assoc, dtim_time;
+	unsigned int dtim_tsf_lo, dtim_tsf_hi;
+	unsigned int bi, res2, dtim_interval, data_policy, listen_interval;
+	unsigned int assoc_id, assoc_beacon_arrive_time;
+	unsigned int union_pad;
+} PACKED;
+
+struct binding_cmd {                 /* BINDING_CMD_API_S_VER_1 */
+	unsigned int id_and_color, action, macs[3], phy;
+} PACKED;
+
+struct quota_cmd {                   /* TIME_QUOTA_ALLOCATION_CMD v1 */
+	struct { unsigned int id_and_color, quota, max_duration; } q[4];
+} PACKED;
+
+struct add_sta_cmd {                 /* ADD_STA_CMD_API_S_VER_7 */
+	unsigned char add_modify, awake_acs;
+	unsigned short tid_disable_tx;
+	unsigned int mac_id_n_color;
+	unsigned char addr[6];
+	unsigned short res2;
+	unsigned char sta_id, modify_mask;
+	unsigned short res3;
+	unsigned int station_flags, station_flags_msk;
+	unsigned char add_ba_tid, remove_ba_tid;
+	unsigned short add_ba_ssn, sleep_tx_count, sleep_state_flags;
+	unsigned short assoc_id, beamform_flags;
+	unsigned int tfd_queue_msk;
+} PACKED;
+
+struct sta_key_cmd {                 /* ADD_MODIFY_STA_KEY_API_S_VER_1 */
+	unsigned char sta_id, key_offset;
+	unsigned short key_flags;
+	unsigned char key[32];
+	unsigned char rx_secur_seq_cnt[16];
+	unsigned char tkip_rx_tsc_byte2, res;
+	unsigned short tkip_rx_ttak[5];
+} PACKED;
+
+struct scd_cfg_cmd {                 /* SCD_QUEUE_CFG_CMD_API_S_VER_1 */
+	unsigned char token, sta_id, tid, scd_queue, action, aggregate;
+	unsigned char tx_fifo, window;
+	unsigned short ssn, res;
+} PACKED;
+
+struct time_event_cmd {              /* MAC_TIME_EVENT_CMD_API_S_VER_2 */
+	unsigned int id_and_color, action, id, apply_time, max_delay;
+	unsigned int depends_on, interval, duration;
+	unsigned char repeat, max_frags;
+	unsigned short policy;
+} PACKED;
+
+struct tx_cmd {                      /* TX_CMD_API_S_VER_6 */
+	unsigned short len, offload_assist;
+	unsigned int tx_flags;
+	unsigned char try_cnt, btkill_cnt;
+	unsigned short scratch_res;
+	unsigned int rate_n_flags;
+	unsigned char sta_id, sec_ctl, initial_rate_index, res2;
+	unsigned char key[16];
+	unsigned int res3, life_time, dram_lsb_ptr;
+	unsigned char dram_msb_ptr, rts_retry_limit, data_retry_limit, tid_tspec;
+	unsigned short pm_frame_timeout, res4;
+} PACKED;
+
+struct scan_req_lmac {               /* SCAN_REQUEST_FIXED_PART_API_S_VER_7 */
+	unsigned int res1;
+	unsigned char n_channels, active_dwell, passive_dwell, fragmented_dwell;
+	unsigned char extended_dwell, res2;
+	unsigned short rx_chain_select;
+	unsigned int scan_flags, max_out_time, suspend_time;
+	unsigned int flags, filter_flags;
+	struct { unsigned int tx_flags, rate_n_flags;
+		 unsigned char sta_id, res[3]; } tx_cmd[2];
+	struct { unsigned char id, len, ssid[32]; } direct_scan[20];
+	unsigned int scan_prio, iter_num, delay;
+	struct { unsigned short delay; unsigned char iterations, full_scan_mul; }
+		schedule[2];
+	struct { unsigned short flags, non_ebs_ratio; } channel_opt[2];
+} PACKED;
+
+struct scan_chan_lmac {
+	unsigned int flags;
+	unsigned short channel_num, iter_count;
+	unsigned int iter_interval;
+} PACKED;
+
+typedef char chk1[sizeof(struct mac_ctx_cmd) == 148 ? 1 : -1];
+typedef char chk2[sizeof(struct add_sta_cmd) == 44 ? 1 : -1];
+typedef char chk3[sizeof(struct sta_key_cmd) == 64 ? 1 : -1];
+typedef char chk4[sizeof(struct tx_cmd) == 56 ? 1 : -1];
+typedef char chk5[sizeof(struct scan_req_lmac) == 764 ? 1 : -1];
+typedef char chk6[sizeof(struct phy_ctx_cmd) == 36 ? 1 : -1];
+
+/* ---- state ------------------------------------------------------------- */
+#define PHYDB_PAGES  8
+#define NVM_CHUNK    2048
+
+static struct {
+	int up;
+	const char *state;
+	unsigned char mac[6];
+	unsigned char bssid[6];
+	unsigned int chan;           /* current PHY context channel */
+	int bound;                   /* binding + quota active */
+	int ap_sta;                  /* AP station added */
+	unsigned int alive_status, scd_base, err_table;
+	int alive;
+	int init_complete;
+	unsigned char *phydb;        /* [type u16][chg u16][len u16][pad][data] */
+	unsigned int phydb_len;
+	unsigned char *scratch;      /* 8 KB command scratch */
+	int scanning, scan_ok;
+	int last_rssi, last_chan;
+	int te_started;
+	unsigned char tk[16];
+	int have_tk;
+	unsigned int valid_tx_ant, valid_rx_ant;
+} M;
+
+static void logs(const char *s)
+{
+	iwl_log(s);
+}
+
+static void put16(unsigned char *p, unsigned int v)
+{
+	p[0] = v; p[1] = v >> 8;
+}
+
+static unsigned int get16(const unsigned char *p)
+{
+	return p[0] | (p[1] << 8);
+}
+
+static unsigned int get32(const unsigned char *p)
+{
+	return p[0] | (p[1] << 8) | (p[2] << 16) | ((unsigned int)p[3] << 24);
+}
+
+static int cmd(unsigned int id, const void *data, unsigned int len)
+{
+	return iwl_send_cmd(id, data, len, 0, 0) < 0 ? -1 : 0;
+}
+
+/* Command with a 32-bit status response (iwl_mvm_send_cmd_pdu_status). */
+static int cmd_status(unsigned int id, const void *data, unsigned int len,
+		      unsigned int *status)
+{
+	unsigned char r[4] = { 0, 0, 0, 0 };
+	int n = iwl_send_cmd(id, data, len, r, 4);
+
+	if (n < 0)
+		return -1;
+	*status = get32(r);
+	return 0;
+}
+
+/* ---- PHY DB ------------------------------------------------------------ */
+static void phydb_store(const unsigned char *d, unsigned int n)
+{
+	unsigned int type, len, chg = 0, rec;
+
+	if (n < 4 || !M.phydb)
+		return;
+	type = get16(d);
+	len = get16(d + 2);
+	if (len + 4 > n)
+		return;
+	if ((type == 4 || type == 5) && len >= 2)
+		chg = get16(d + 4);
+	rec = (8 + len + 3) & ~3u;
+	if (M.phydb_len + rec > PHYDB_PAGES * 4096) {
+		logs("phy db full");
+		return;
+	}
+	put16(M.phydb + M.phydb_len, type);
+	put16(M.phydb + M.phydb_len + 2, chg);
+	put16(M.phydb + M.phydb_len + 4, len);
+	iwl_memcpy(M.phydb + M.phydb_len + 8, d + 4, len);
+	M.phydb_len += rec;
+}
+
+static int phydb_send_type(unsigned int type)
+{
+	unsigned int chg, off, sent = 0, maxchg = 0;
+
+	for (off = 0; off < M.phydb_len;) {
+		unsigned int len = get16(M.phydb + off + 4);
+
+		if (get16(M.phydb + off) == type && get16(M.phydb + off + 2) > maxchg)
+			maxchg = get16(M.phydb + off + 2);
+		off += (8 + len + 3) & ~3u;
+	}
+	for (chg = 0; chg <= maxchg; chg++) {
+		for (off = 0; off < M.phydb_len;) {
+			unsigned int len = get16(M.phydb + off + 4);
+
+			if (get16(M.phydb + off) == type &&
+			    get16(M.phydb + off + 2) == chg) {
+				/* struct iwl_phy_db_cmd: type, length, data */
+				put16(M.scratch, type);
+				put16(M.scratch + 2, len);
+				iwl_memcpy(M.scratch + 4, M.phydb + off + 8, len);
+				if (cmd(PHY_DB_CMD, M.scratch, 4 + len) < 0)
+					return -1;
+				sent++;
+			}
+			off += (8 + len + 3) & ~3u;
+		}
+		if (type < 4)
+			break;
+	}
+	if (!sent && type < 4) {
+		logs("phy db section missing");
+		return -1;
+	}
+	return 0;
+}
+
+/* ---- RX dispatch -------------------------------------------------------- */
+static void rx_mpdu(const struct iwl_pkt *pkt)
+{
+	unsigned int plen = iwl_pkt_payload_len(pkt), len, status;
+	const unsigned char *d = pkt->data;
+
+	if (plen < 8)
+		return;
+	len = get16(d);
+	if (4 + len + 4 > plen)
+		return;
+	status = get32(d + 4 + len);
+	if (!(status & IWL_RX_CRC_OK) || !(status & IWL_RX_OVERRUN_OK))
+		return;
+	wifi_rx_frame(d + 4, len, M.last_rssi, status, (unsigned int)M.last_chan);
+}
+
+static void rx_phy(const struct iwl_pkt *pkt)
+{
+	const unsigned char *d = pkt->data;
+	int ea, eb, best;
+	unsigned int energy;
+
+	if (iwl_pkt_payload_len(pkt) < 68)
+		return;
+	M.last_chan = get16(d + 22);
+	/* non_cfg_phy[IWL_RX_INFO_ENERGY_ANT_ABC_IDX = 1]: energy per chain,
+	 * in -dBm (0 = no measurement). */
+	energy = get32(d + 24 + 4);
+	ea = energy & 0xff;
+	eb = (energy >> 8) & 0xff;
+	ea = ea ? -ea : -128;
+	eb = eb ? -eb : -128;
+	best = ea > eb ? ea : eb;
+	M.last_rssi = best;
+}
+
+static void rx_handler(const struct iwl_pkt *pkt)
+{
+	const unsigned char *d = pkt->data;
+	unsigned int n = iwl_pkt_payload_len(pkt);
+
+	if (pkt->group > 1)
+		return;
+	switch (pkt->cmd) {
+	case UCODE_ALIVE_NTFY:
+		if (n >= 44) {
+			M.alive_status = get16(d);
+			M.err_table = get32(d + 20);
+			M.scd_base = get32(d + 40);
+			M.alive = 1;
+		}
+		break;
+	case INIT_COMPLETE_NOTIF:
+		M.init_complete = 1;
+		break;
+	case CALIB_RES_NOTIF_PHY_DB:
+		phydb_store(d, n);
+		break;
+	case REPLY_RX_PHY_CMD:
+		rx_phy(pkt);
+		break;
+	case REPLY_RX_MPDU_CMD:
+		rx_mpdu(pkt);
+		break;
+	case TX_CMD:
+		/* struct iwl_mvm_tx_resp_v3: status at byte 32. */
+		iwl_tx_reclaim((pkt->seq >> 8) & 0x1f, pkt->seq & 0xff);
+		if (n > 33 && (d[32] & 0xff) != 1 && (d[32] & 0xff) != 2) {
+			serial_puts(SERIAL_COM1, "iwl: tx status ");
+			serial_puthex(SERIAL_COM1, get16(d + 32));
+			serial_puts(SERIAL_COM1, "\n");
+		}
+		break;
+	case SCAN_OFFLOAD_COMPLETE:
+		M.scanning = 0;
+		M.scan_ok = n >= 3 && d[2] == 1;
+		wifi_scan_done(M.scan_ok);
+		break;
+	case TIME_EVENT_NOTIFICATION:
+		/* struct iwl_time_event_notif: action at 16 (1 = start). */
+		if (n >= 24 && (get32(d + 16) & 1))
+			M.te_started = 1;
+		break;
+	case REPLY_ERROR:
+		if (n >= 8) {
+			serial_puts(SERIAL_COM1, "iwl: REPLY_ERROR type ");
+			serial_puthex(SERIAL_COM1, get32(d));
+			serial_puts(SERIAL_COM1, " cmd ");
+			serial_puthex(SERIAL_COM1, d[4]);
+			serial_puts(SERIAL_COM1, "\n");
+		}
+		break;
+	default:
+		break;
+	}
+}
+
+int iwl_mvm_poll(void)
+{
+	return iwl_rx_poll();
+}
+
+/* ---- bring-up ---------------------------------------------------------- */
+static void dump_error_log(void)
+{
+	unsigned int i;
+
+	if (!M.err_table || M.err_table >= 0x01000000u)
+		return;
+	serial_puts(SERIAL_COM1, "iwl: error log:");
+	for (i = 0; i < 16; i++) {
+		serial_puts(SERIAL_COM1, " ");
+		serial_puthex(SERIAL_COM1, iwl_mem_rd32(M.err_table + i * 4));
+	}
+	serial_puts(SERIAL_COM1, "\n");
+}
+
+static int load_and_wait_alive(int img)
+{
+	unsigned int t;
+
+	M.alive = 0;
+	if (iwl_load_fw(img) < 0)
+		return -1;
+	for (t = 0; t < 2000 && !M.alive; t++) {
+		if (iwl_rx_poll() < 0)
+			break;
+		if (!M.alive)
+			iwl_udelay(1000);
+	}
+	if (!M.alive) {
+		logs("no ALIVE from firmware");
+		return -1;
+	}
+	if (M.alive_status != 0xcafe) {
+		iwl_loghex("ALIVE status", M.alive_status);
+		return -1;
+	}
+	iwl_fw_alive(M.scd_base);
+	return 0;
+}
+
+static int send_tx_ant(void)
+{
+	unsigned int v = M.valid_tx_ant;
+
+	return cmd(TX_ANT_CONFIGURATION_CMD, &v, 4);
+}
+
+static int send_phy_cfg(int img)
+{
+	const struct iwl_fw_info *fw = iwl_fw();
+	unsigned int c[3];
+
+	c[0] = (fw->phy_sku & ~0x00ff0000u) | (M.valid_tx_ant << 16) |
+	       (M.valid_rx_ant << 20);
+	c[1] = fw->flow_trigger[img == IWL_IMG_INIT ? 1 : 0];
+	c[2] = fw->event_trigger[img == IWL_IMG_INIT ? 1 : 0];
+	return cmd(PHY_CONFIGURATION_CMD, c, sizeof(c));
+}
+
+static int send_bt_config(void)
+{
+	unsigned int c[2] = { 3 /* BT_COEX_WIFI */, 0 };
+
+	return cmd(BT_CONFIG, c, sizeof(c));
+}
+
+static int nvm_read(unsigned int section, unsigned char *out,
+		    unsigned int max)
+{
+	unsigned int off = 0;
+	unsigned char req[8];
+
+	while (off < max) {
+		int n;
+		unsigned int got, status;
+
+		req[0] = 0;            /* NVM_READ_OPCODE */
+		req[1] = 0;            /* target: cached */
+		put16(req + 2, section);
+		put16(req + 4, off);
+		put16(req + 6, NVM_CHUNK);
+		n = iwl_send_cmd(NVM_ACCESS_CMD, req, 8, M.scratch, 8 + NVM_CHUNK);
+		if (n < 8)
+			return -1;
+		status = get16(M.scratch + 6);
+		got = get16(M.scratch + 2);
+		if (status) {
+			if (off)
+				break;     /* section size is a multiple of 2 KB */
+			return -1;
+		}
+		if (got > NVM_CHUNK || off + got > max)
+			got = off + got > max ? max - off : got;
+		iwl_memcpy(out + off, M.scratch + 8, got);
+		off += got;
+		if (got < NVM_CHUNK)
+			break;
+	}
+	return (int)off;
+}
+
+static int read_nvm(void)
+{
+	unsigned char *buf = M.scratch + 4096;   /* 4 KB is plenty for HW */
+	const unsigned char *a;
+	int n;
+
+	/* NVM HW section (nvm_hw_section_num = 0 on the 7000 family): the MAC
+	 * address is at word 0x15, stored as little-endian 16-bit words. */
+	n = nvm_read(0, buf, 4096 - 2048);
+	if (n < (0x15 + 3) * 2) {
+		logs("NVM HW section read failed");
+		return -1;
+	}
+	a = buf + 0x15 * 2;
+	M.mac[0] = a[1]; M.mac[1] = a[0];
+	M.mac[2] = a[3]; M.mac[3] = a[2];
+	M.mac[4] = a[5]; M.mac[5] = a[4];
+	if ((M.mac[0] & 1) || !(M.mac[0] | M.mac[1] | M.mac[2] | M.mac[3] |
+				 M.mac[4] | M.mac[5])) {
+		logs("NVM MAC address invalid");
+		return -1;
+	}
+	return 0;
+}
+
+static int run_init_image(void)
+{
+	unsigned int t;
+
+	M.state = "init image";
+	if (iwl_start_hw() < 0)
+		return -1;
+	M.phydb_len = 0;
+	M.init_complete = 0;
+	if (load_and_wait_alive(IWL_IMG_INIT) < 0)
+		return -1;
+	if (send_bt_config() < 0 || read_nvm() < 0)
+		return -1;
+	if (iwl_rfkill()) {
+		logs("radio is off (hardware RF-kill)");
+		return -1;
+	}
+	if (send_tx_ant() < 0 || send_phy_cfg(IWL_IMG_INIT) < 0)
+		return -1;
+	for (t = 0; t < 2000 && !M.init_complete; t++) {
+		if (iwl_rx_poll() < 0)
+			break;
+		if (!M.init_complete)
+			iwl_udelay(1000);
+	}
+	if (!M.init_complete) {
+		logs("INIT calibration did not complete");
+		dump_error_log();
+		return -1;
+	}
+	return 0;
+}
+
+static int enable_queue(int q, unsigned int sta, unsigned int tid,
+			unsigned int fifo)
+{
+	struct scd_cfg_cmd c;
+
+	iwl_memzero(&c, sizeof(c));
+	iwl_txq_enable(q, 0);
+	c.sta_id = sta;
+	c.tid = tid;
+	c.scd_queue = q;
+	c.action = 1;              /* SCD_CFG_ENABLE_QUEUE */
+	c.tx_fifo = fifo;
+	c.window = 64;
+	c.ssn = iwl_txq_wptr(q);
+	return cmd(SCD_QUEUE_CFG, &c, sizeof(c));
+}
+
+static int add_sta(struct add_sta_cmd *c)
+{
+	unsigned int status = 0;
+
+	if (cmd_status(ADD_STA, c, sizeof(*c), &status) < 0)
+		return -1;
+	if ((status & 0xff) != 1) {
+		iwl_loghex("ADD_STA failed, status", status);
+		return -1;
+	}
+	return 0;
+}
+
+static int add_aux_sta(void)
+{
+	struct add_sta_cmd c;
+
+	if (enable_queue(IWL_Q_AUX, IWL_STA_AUX, 8, 5 /* MCAST FIFO */) < 0)
+		return -1;
+	iwl_memzero(&c, sizeof(c));
+	c.sta_id = IWL_STA_AUX;
+	c.mac_id_n_color = MAC_INDEX_AUX;
+	c.tfd_queue_msk = 1u << IWL_Q_AUX;
+	c.tid_disable_tx = 0xffff;
+	return add_sta(&c);
+}
+
+static int phy_ctx(unsigned int action, unsigned int chan)
+{
+	struct phy_ctx_cmd c;
+	unsigned int rx = M.valid_rx_ant;
+
+	iwl_memzero(&c, sizeof(c));
+	c.id_and_color = 0;
+	c.action = action;
+	c.band = chan <= 14 ? 1 : 0;        /* PHY_BAND_24 / PHY_BAND_5 */
+	c.channel = chan;
+	c.width = 0;                         /* 20 MHz */
+	c.ctrl_pos = 0;
+	c.txchain_info = M.valid_tx_ant;
+	/* valid chains, idle/active count 1 (no MIMO) */
+	c.rxchain_info = (rx << 1) | (1u << 10) | (1u << 12);
+	if (cmd(PHY_CONTEXT_CMD, &c, sizeof(c)) < 0)
+		return -1;
+	M.chan = chan;
+	return 0;
+}
+
+static void fill_mac(struct mac_ctx_cmd *c, unsigned int action, int assoc,
+		     unsigned short aid, unsigned int bi, unsigned int dtim)
+{
+	unsigned int i;
+
+	iwl_memzero(c, sizeof(*c));
+	c->id_and_color = 0;
+	c->action = action;
+	c->mac_type = 5;                    /* FW_MAC_TYPE_BSS_STA */
+	c->tsf_id = 0;
+	iwl_memcpy(c->node_addr, M.mac, 6);
+	if (M.ap_sta || assoc)
+		iwl_memcpy(c->bssid_addr, M.bssid, 6);
+	else
+		for (i = 0; i < 6; i++)
+			c->bssid_addr[i] = 0xff;
+	/* ACK rates: 1/2/5.5/11 CCK, 6/12/24 OFDM (iwl_mvm_ack_rates). */
+	c->cck_rates = M.chan && M.chan > 14 ? 0 : 0x0f;
+	c->ofdm_rates = 0x15;
+	c->short_slot = (1u << 4);
+	/* Non-QoS EDCA (mac80211 defaults): CW 15/1023, AIFS 2, per-AC FIFO. */
+	for (i = 0; i < 4; i++) {
+		c->ac[i].cw_min = 15;
+		c->ac[i].cw_max = 1023;
+		c->ac[i].aifsn = 2;
+		c->ac[i].fifos_mask = 1u << i;
+	}
+	c->filter_flags = (1u << 2);        /* ACCEPT_GRP */
+	if (assoc) {
+		c->is_assoc = 1;
+		c->assoc_id = aid;
+	} else {
+		c->filter_flags |= (1u << 6);   /* IN_BEACON */
+	}
+	c->bi = bi;
+	c->dtim_interval = bi * (dtim ? dtim : 1);
+	c->listen_interval = 10;
+}
+
+static int mac_ctx(unsigned int action, int assoc, unsigned short aid,
+		   unsigned int bi, unsigned int dtim)
+{
+	struct mac_ctx_cmd c;
+
+	fill_mac(&c, action, assoc, aid, bi, dtim);
+	return cmd(MAC_CONTEXT_CMD, &c, sizeof(c));
+}
+
+static int run_rt_image(void)
+{
+	unsigned int one = 0;
+	unsigned char mcc[28];          /* LAR_UPDATE_MCC_CMD_API_S_VER_2 */
+
+	M.state = "runtime image";
+	iwl_stop_device();
+	if (iwl_start_hw() < 0)
+		return -1;
+	if (load_and_wait_alive(IWL_IMG_RT) < 0)
+		return -1;
+	if (send_tx_ant() < 0)
+		return -1;
+	if (phydb_send_type(1) < 0 || phydb_send_type(2) < 0 ||
+	    phydb_send_type(4) < 0 || phydb_send_type(5) < 0)
+		return -1;
+	if (send_phy_cfg(IWL_IMG_RT) < 0 || send_bt_config() < 0)
+		return -1;
+	if (cmd(DQA_ENABLE_CMD, &one, 4) < 0)     /* cmd_queue = 0 */
+		return -1;
+	if (add_aux_sta() < 0)
+		return -1;
+	if (phy_ctx(ACTION_ADD, 1) < 0)
+		return -1;
+	one = 0;                                   /* device power: CAM */
+	if (cmd(POWER_TABLE_CMD, &one, 4) < 0)
+		return -1;
+	/* LAR: ask for the current (NVM default) regulatory domain. */
+	iwl_memzero(mcc, sizeof(mcc));
+	mcc[0] = 'Z'; mcc[1] = 'Z';                /* le16: 'Z' << 8 | 'Z' */
+	mcc[2] = 0x10;                             /* MCC_SOURCE_GET_CURRENT */
+	if (iwl_send_cmd(MCC_UPDATE_CMD, mcc, sizeof(mcc), 0, 0) < 0)
+		logs("MCC update failed (continuing)");
+	if (mac_ctx(ACTION_ADD, 0, 0, 100, 1) < 0)
+		return -1;
+	return 0;
+}
+
+int iwl_mvm_up(unsigned char mac[6])
+{
+	const struct iwl_fw_info *fw;
+
+	if (M.up) {
+		iwl_memcpy(mac, M.mac, 6);
+		return 0;
+	}
+	if (iwl_probe() < 0) {
+		M.state = "no card";
+		return -1;
+	}
+	if (iwl_fw_parse() < 0) {
+		M.state = "firmware missing";
+		return -1;
+	}
+	fw = iwl_fw();
+	if (!M.phydb) {
+		M.phydb = (unsigned char *)mm_alloc_pages(PHYDB_PAGES);
+		M.scratch = (unsigned char *)mm_alloc_pages(2);
+		if (!M.phydb || !M.scratch) {
+			M.state = "out of memory";
+			return -1;
+		}
+	}
+	M.valid_tx_ant = (fw->phy_sku >> 16) & 0xf;
+	M.valid_rx_ant = (fw->phy_sku >> 20) & 0xf;
+	if (!M.valid_tx_ant)
+		M.valid_tx_ant = 1;
+	if (!M.valid_rx_ant)
+		M.valid_rx_ant = 1;
+	iwl_set_rx_handler(rx_handler);
+	if (run_init_image() < 0 || run_rt_image() < 0) {
+		dump_error_log();
+		iwl_stop_device();
+		if (M.state && M.state[0] != 'r' && M.state[0] != 'i')
+			return -1;
+		M.state = "firmware start failed";
+		return -1;
+	}
+	M.up = 1;
+	M.bound = M.ap_sta = 0;
+	M.state = "ready";
+	iwl_memcpy(mac, M.mac, 6);
+	logs("firmware running");
+	return 0;
+}
+
+int iwl_mvm_is_up(void)
+{
+	return M.up;
+}
+
+const char *iwl_mvm_state(void)
+{
+	return M.state ? M.state : "down";
+}
+
+void iwl_mvm_down(void)
+{
+	if (iwl_present())
+		iwl_stop_device();
+	M.up = 0;
+	M.scanning = 0;
+	M.bound = M.ap_sta = 0;
+	M.have_tk = 0;
+	M.state = "down";
+}
+
+/* ---- scan -------------------------------------------------------------- */
+static const unsigned char scan_channels[] = {
+	1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
+	36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120,
+	124, 128, 132, 136, 140, 149, 153, 157, 161, 165,
+};
+
+int iwl_mvm_scan_running(void)
+{
+	return M.scanning;
+}
+
+int iwl_mvm_scan_start(void)
+{
+	struct scan_req_lmac *c;
+	struct scan_chan_lmac *ch;
+	unsigned char *preq, *buf;
+	unsigned int i, n = sizeof(scan_channels), total, rx = M.valid_rx_ant;
+	static const unsigned char rates24[] = { 1, 8, 0x82, 0x84, 0x8b, 0x96,
+						 0x0c, 0x12, 0x18, 0x24,
+						 50, 4, 0x30, 0x48, 0x60, 0x6c };
+	static const unsigned char rates5[] = { 1, 8, 0x8c, 0x12, 0x98, 0x24,
+						0xb0, 0x48, 0x60, 0x6c };
+
+	if (!M.up || M.scanning)
+		return -1;
+	if (n > 40)
+		n = 40;                          /* n_scan_channels TLV */
+	buf = M.scratch;
+	iwl_memzero(buf, 4096);
+	c = (struct scan_req_lmac *)buf;
+	c->n_channels = n;
+	c->active_dwell = 10;
+	c->passive_dwell = 110;
+	c->fragmented_dwell = 44;
+	c->extended_dwell = 90;
+	c->rx_chain_select = (rx << 1) | (rx << 7) | (rx << 4) | 1;
+	/* PASS_ALL | EXTENDED_DWELL */
+	c->scan_flags = (1u << 0) | (1u << 7);
+	c->flags = 1;                            /* first channel: 2.4 GHz */
+	c->filter_flags = (1u << 2) | (1u << 6); /* ACCEPT_GRP | IN_BEACON */
+	c->tx_cmd[0].tx_flags = TX_FLG_SEQ_CTL | TX_FLG_BT_DIS;
+	c->tx_cmd[0].rate_n_flags = PLCP_1M | RATE_CCK | RATE_ANT_A;
+	c->tx_cmd[0].sta_id = IWL_STA_AUX;
+	c->tx_cmd[1].tx_flags = TX_FLG_SEQ_CTL | TX_FLG_BT_DIS;
+	c->tx_cmd[1].rate_n_flags = PLCP_6M | RATE_ANT_A;
+	c->tx_cmd[1].sta_id = IWL_STA_AUX;
+	c->scan_prio = 6;                        /* IWL_SCAN_PRIORITY_EXT_6 */
+	c->iter_num = 1;
+	c->schedule[0].iterations = 1;
+	c->schedule[0].full_scan_mul = 1;
+	ch = (struct scan_chan_lmac *)(buf + sizeof(*c));
+	for (i = 0; i < n; i++) {
+		ch[i].channel_num = scan_channels[i];
+		ch[i].iter_count = 1;
+		ch[i].flags = 1u << 28;          /* UNIFIED_SCAN_CHANNEL_PARTIAL */
+	}
+	/* struct iwl_scan_probe_req_v1 after n_scan_channels (40) entries:
+	 * mac_header, band_data[2], common_data segments, then 512 bytes. */
+	preq = buf + sizeof(*c) + 40 * sizeof(struct scan_chan_lmac);
+	{
+		unsigned char *f = preq + 16;
+		unsigned int o = 0;
+
+		f[0] = 0x40;                      /* probe request */
+		for (i = 0; i < 6; i++) {
+			f[4 + i] = 0xff;
+			f[10 + i] = M.mac[i];
+			f[16 + i] = 0xff;
+		}
+		f[24] = 0;                        /* SSID IE, filled by fw */
+		f[25] = 0;
+		put16(preq + 0, 0);               /* mac_header offset */
+		put16(preq + 2, 26);              /* + empty SSID */
+		o = 26;
+		iwl_memcpy(f + o, rates24, sizeof(rates24));
+		put16(preq + 4, o);
+		put16(preq + 6, sizeof(rates24));
+		o += sizeof(rates24);
+		iwl_memcpy(f + o, rates5, sizeof(rates5));
+		put16(preq + 8, o);
+		put16(preq + 10, sizeof(rates5));
+		o += sizeof(rates5);
+		put16(preq + 12, o);              /* common data: none */
+		put16(preq + 14, 0);
+	}
+	total = sizeof(*c) + 40 * sizeof(struct scan_chan_lmac) + 16 + 512;
+	M.scanning = 1;
+	M.scan_ok = 0;
+	if (cmd(SCAN_OFFLOAD_REQUEST_CMD, buf, total) < 0) {
+		M.scanning = 0;
+		return -1;
+	}
+	return 0;
+}
+
+/* ---- connection --------------------------------------------------------- */
+static int bind_and_quota(unsigned int action)
+{
+	struct binding_cmd b;
+	struct quota_cmd q;
+	unsigned int status = 0, i;
+
+	/* Removal: drop the quota first, then the binding (Linux order in
+	 * iwl_mvm_unassign_vif_chanctx()). */
+	if (action == ACTION_REMOVE) {
+		for (i = 0; i < 4; i++) {
+			q.q[i].id_and_color = CTXT_INVALID;
+			q.q[i].quota = 0;
+			q.q[i].max_duration = 0;
+		}
+		if (cmd(TIME_QUOTA_CMD, &q, sizeof(q)) < 0)
+			return -1;
+	}
+	b.id_and_color = 0;               /* binding id = PHY context 0 */
+	b.action = action;
+	b.macs[0] = action == ACTION_REMOVE ? CTXT_INVALID : 0;
+	b.macs[1] = b.macs[2] = CTXT_INVALID;
+	b.phy = 0;
+	if (cmd_status(BINDING_CONTEXT_CMD, &b, sizeof(b), &status) < 0 || status) {
+		iwl_loghex("binding failed, status", status);
+		return -1;
+	}
+	if (action == ACTION_REMOVE)
+		return 0;
+	for (i = 0; i < 4; i++) {
+		q.q[i].id_and_color = CTXT_INVALID;
+		q.q[i].quota = 0;
+		q.q[i].max_duration = 0;
+	}
+	q.q[0].id_and_color = 0;
+	q.q[0].quota = 128;
+	return cmd(TIME_QUOTA_CMD, &q, sizeof(q));
+}
+
+static int add_ap_sta(int modify, unsigned short aid)
+{
+	struct add_sta_cmd c;
+
+	iwl_memzero(&c, sizeof(c));
+	c.add_modify = modify ? 1 : 0;
+	c.sta_id = IWL_STA_AP;
+	c.mac_id_n_color = 0;
+	iwl_memcpy(c.addr, M.bssid, 6);
+	c.tid_disable_tx = 0xffff;
+	c.station_flags_msk = (3u << 26) | (3u << 28) | (1u << 17);
+	c.tfd_queue_msk = 1u << IWL_Q_BSS;
+	c.assoc_id = aid;
+	return add_sta(&c);
+}
+
+static int remove_sta(unsigned int id)
+{
+	unsigned char c[4] = { (unsigned char)id, 0, 0, 0 };
+	unsigned int status;
+
+	return cmd_status(REMOVE_STA, c, 4, &status);
+}
+
+int iwl_mvm_prepare_connect(const unsigned char bssid[6], unsigned int chan,
+			    unsigned int beacon_int)
+{
+	struct time_event_cmd te;
+	unsigned int t;
+
+	if (!M.up)
+		return -1;
+	if (M.ap_sta)
+		iwl_mvm_disconnect();
+	iwl_memcpy(M.bssid, bssid, 6);
+	if (phy_ctx(ACTION_MODIFY, chan) < 0)
+		return -1;
+	if (!M.bound) {
+		if (bind_and_quota(ACTION_ADD) < 0)
+			return -1;
+		M.bound = 1;
+	}
+	if (enable_queue(IWL_Q_BSS, IWL_STA_AP, 0, 1 /* BE FIFO */) < 0)
+		return -1;
+	if (add_ap_sta(0, 0) < 0)
+		return -1;
+	M.ap_sta = 1;
+	if (mac_ctx(ACTION_MODIFY, 0, 0, beacon_int, 1) < 0)
+		return -1;
+	/* Session protection: stay on the channel for the auth/assoc
+	 * exchange (TE_BSS_STA_AGGRESSIVE_ASSOC, ~1 s). */
+	iwl_memzero(&te, sizeof(te));
+	te.id_and_color = 0;
+	te.action = ACTION_ADD;
+	te.id = 0;
+	te.max_delay = 500;
+	te.interval = 1;
+	te.duration = 1000;
+	te.repeat = 1;
+	te.max_frags = 0;
+	te.policy = (1u << 0) | (1u << 1) | (1u << 11);
+	M.te_started = 0;
+	if (cmd(TIME_EVENT_CMD, &te, sizeof(te)) < 0)
+		return -1;
+	for (t = 0; t < 600 && !M.te_started; t++) {
+		if (iwl_rx_poll() < 0)
+			return -1;
+		if (!M.te_started)
+			iwl_udelay(1000);
+	}
+	if (!M.te_started)
+		logs("time event did not start (continuing)");
+	return 0;
+}
+
+int iwl_mvm_set_assoc(unsigned short aid, unsigned int beacon_int,
+		      unsigned int dtim)
+{
+	if (!M.ap_sta)
+		return -1;
+	if (add_ap_sta(1, aid) < 0)
+		return -1;
+	return mac_ctx(ACTION_MODIFY, 1, aid, beacon_int, dtim);
+}
+
+void iwl_mvm_disconnect(void)
+{
+	if (!M.up)
+		return;
+	if (M.ap_sta) {
+		struct scd_cfg_cmd c;
+
+		/* Disable the queue, then remove the station (iwl_mvm_rm_sta()
+		 * order); the next connect enables the queue again. */
+		iwl_memzero(&c, sizeof(c));
+		c.sta_id = IWL_STA_AP;
+		c.tid = 0;
+		c.scd_queue = IWL_Q_BSS;
+		c.action = 0;                    /* SCD_CFG_DISABLE_QUEUE */
+		cmd(SCD_QUEUE_CFG, &c, sizeof(c));
+		remove_sta(IWL_STA_AP);
+		M.ap_sta = 0;
+	}
+	M.have_tk = 0;
+	mac_ctx(ACTION_MODIFY, 0, 0, 100, 1);
+	if (M.bound) {
+		bind_and_quota(ACTION_REMOVE);
+		M.bound = 0;
+	}
+}
+
+/* ---- TX ---------------------------------------------------------------- */
+static int tx_frame(const unsigned char *frame, unsigned int len, int mgmt,
+		    int protect)
+{
+	struct tx_cmd c;
+	int q = M.ap_sta ? IWL_Q_BSS : IWL_Q_AUX;
+	unsigned int sta = M.ap_sta ? IWL_STA_AP : IWL_STA_AUX;
+	int bcast = frame[4] & 1;
+	unsigned int stype = (frame[0] >> 4) & 0xf;
+
+	iwl_memzero(&c, sizeof(c));
+	c.len = len;
+	c.tx_flags = TX_FLG_SEQ_CTL | (bcast ? 0 : TX_FLG_ACK);
+	if (mgmt) {
+		c.rate_n_flags = M.chan <= 14 ? (PLCP_1M | RATE_CCK | RATE_ANT_A)
+					      : (PLCP_6M | RATE_ANT_A);
+		c.tid_tspec = 8;                 /* IWL_MAX_TID_COUNT */
+		c.pm_frame_timeout = (stype == 0 || stype == 2) ? 3 : 2;
+	} else {
+		c.rate_n_flags = PLCP_12M | RATE_ANT_A;
+		c.tid_tspec = 0;                 /* IWL_TID_NON_QOS */
+		c.pm_frame_timeout = 0;
+	}
+	c.sta_id = sta;
+	c.life_time = 0xffffffffu;
+	c.rts_retry_limit = 60;
+	c.data_retry_limit = mgmt ? 3 : 15;
+	if (protect) {
+		if (!M.have_tk)
+			return -1;
+		c.sec_ctl = 0x02;                /* TX_CMD_SEC_CCM */
+		iwl_memcpy(c.key, M.tk, 16);
+	}
+	return iwl_tx(q, &c, sizeof(c), frame, len, sta, protect ? 8 : 0);
+}
+
+int iwl_mvm_tx_mgmt(const unsigned char *frame, unsigned int len)
+{
+	return M.up ? tx_frame(frame, len, 1, 0) : -1;
+}
+
+int iwl_mvm_tx_data(const unsigned char *frame, unsigned int len, int protect)
+{
+	return M.up && M.ap_sta ? tx_frame(frame, len, 0, protect) : -1;
+}
+
+/* ---- keys -------------------------------------------------------------- */
+int iwl_mvm_set_key(int pairwise, int keyidx, const unsigned char key[16],
+		    const unsigned char rsc[6])
+{
+	struct sta_key_cmd c;
+	unsigned int status = 0;
+
+	if (!M.ap_sta)
+		return -1;
+	iwl_memzero(&c, sizeof(c));
+	c.sta_id = IWL_STA_AP;
+	c.key_offset = pairwise ? 0 : (unsigned char)(1 + (keyidx & 3));
+	c.key_flags = (unsigned short)(((keyidx & 3) << 8) | (1u << 3) | 2u);
+	if (!pairwise)
+		c.key_flags |= 1u << 14;         /* STA_KEY_MULTICAST */
+	iwl_memcpy(c.key, key, 16);
+	if (rsc) {
+		/* API v1: PN bytes 0,1 then a 2-byte hole, then 2..5. */
+		c.rx_secur_seq_cnt[0] = rsc[0];
+		c.rx_secur_seq_cnt[1] = rsc[1];
+		c.rx_secur_seq_cnt[4] = rsc[2];
+		c.rx_secur_seq_cnt[5] = rsc[3];
+		c.rx_secur_seq_cnt[6] = rsc[4];
+		c.rx_secur_seq_cnt[7] = rsc[5];
+	}
+	if (cmd_status(ADD_STA_KEY, &c, sizeof(c), &status) < 0 ||
+	    (status & 0xff) != 1) {
+		iwl_loghex("ADD_STA_KEY failed, status", status);
+		return -1;
+	}
+	if (pairwise) {
+		iwl_memcpy(M.tk, key, 16);
+		M.have_tk = 1;
+	}
+	return 0;
+}
+
+void iwl_mvm_clear_keys(void)
+{
+	M.have_tk = 0;
+}

+ 58 - 0
iwl_mvm.h

@@ -0,0 +1,58 @@
+/* Intel 7265D/3165 firmware command layer ("mvm"): see iwl_mvm.c.
+ *
+ * One station interface: MAC context 0, PHY context 0 (= binding 0), the aux
+ * station 0 for scan probes and the AP station 1 on TX queue 4. */
+#ifndef IWL_MVM_H
+#define IWL_MVM_H
+
+#define IWL_STA_AUX 0
+#define IWL_STA_AP  1
+
+/* RX MPDU status bits (fw/api/rx.h). */
+#define IWL_RX_CRC_OK        (1u << 0)
+#define IWL_RX_OVERRUN_OK    (1u << 1)
+#define IWL_RX_MIC_OK        (1u << 6)
+#define IWL_RX_SEC_MSK       (7u << 8)
+#define IWL_RX_SEC_CCM       (2u << 8)
+
+/* Upcalls into wifi.c. */
+void wifi_rx_frame(const unsigned char *frame, unsigned int len, int rssi,
+		   unsigned int status, unsigned int channel);
+void wifi_scan_done(int ok);
+
+/* Bring the card up (INIT image + calibration + NVM, then the runtime
+ * image).  Fills the NVM MAC address.  0 on success. */
+int  iwl_mvm_up(unsigned char mac[6]);
+int  iwl_mvm_is_up(void);
+void iwl_mvm_down(void);
+const char *iwl_mvm_state(void);    /* short status for `wifi` */
+
+/* Poll the firmware RX ring (notifications, frames, TX responses). */
+int  iwl_mvm_poll(void);
+
+int  iwl_mvm_scan_start(void);      /* wildcard active scan, all channels */
+int  iwl_mvm_scan_running(void);
+
+/* Connection: PHY context to `chan`, binding + quota, MAC with the BSSID,
+ * AP station + queue, session protection.  Then the 802.11 frames go out
+ * with iwl_mvm_tx_mgmt(). */
+int  iwl_mvm_prepare_connect(const unsigned char bssid[6], unsigned int chan,
+			     unsigned int beacon_int);
+int  iwl_mvm_set_assoc(unsigned short aid, unsigned int beacon_int,
+		       unsigned int dtim);
+void iwl_mvm_disconnect(void);
+
+/* Raw 802.11 frames (header included).  Management frames go at the
+ * lowest rate; data at a fixed OFDM rate.  `protect`: CCMP with the
+ * pairwise key (the frame must already carry the 8-byte CCMP header). */
+int  iwl_mvm_tx_mgmt(const unsigned char *frame, unsigned int len);
+int  iwl_mvm_tx_data(const unsigned char *frame, unsigned int len,
+		     int protect);
+
+/* Install a CCMP key: pairwise (key index 0) or group (`keyidx`, with the
+ * 6-byte receive sequence counter from the EAPOL frame). */
+int  iwl_mvm_set_key(int pairwise, int keyidx, const unsigned char key[16],
+		     const unsigned char rsc[6]);
+void iwl_mvm_clear_keys(void);
+
+#endif

+ 1170 - 0
iwl_trans.c

@@ -0,0 +1,1170 @@
+/* Intel 7265D/3165 PCIe transport: see iwl_trans.h.
+ *
+ * Register sequences follow Linux iwlwifi (pcie/trans.c, pcie/rx.c,
+ * pcie/tx.c) for the 7000 device family: no MSI-X, no ICT, legacy single
+ * RX queue (256 x 4 KB RBDs), gen1 128-byte TFDs, byte-count table in
+ * dwords.  Everything is polled; CSR_INT_MASK stays zero and PCI INTx is
+ * disabled, so the card never raises an interrupt.
+ *
+ * The NIC is kept awake (MAC_ACCESS_REQ held) the whole time it is up: the
+ * firmware is configured without power save, and holding the request is
+ * what Linux does while host commands are in flight (apmg_wake_up_wa). */
+
+#include "iwl_trans.h"
+#include "mm.h"
+#include "paging.h"
+#include "pci.h"
+#include "process.h"
+#include "ramfs.h"
+#include "serial.h"
+
+#define FW_PATH "firmware/iwlwifi-7265D-29.ucode"
+
+/* ---- CSR / HBUS / FH / PRPH registers (iwl-csr.h, iwl-fh.h, iwl-prph.h) */
+#define CSR_HW_IF_CONFIG_REG     0x000
+#define CSR_INT_COALESCING       0x004
+#define CSR_INT                  0x008
+#define CSR_INT_MASK             0x00c
+#define CSR_FH_INT_STATUS        0x010
+#define CSR_RESET                0x020
+#define CSR_GP_CNTRL             0x024
+#define CSR_HW_REV               0x028
+#define CSR_GIO_REG              0x03c
+#define CSR_UCODE_DRV_GP1_CLR    0x05c
+#define CSR_MBOX_SET_REG         0x088
+#define CSR_MAC_SHADOW_REG_CTRL  0x0a8
+#define CSR_GIO_CHICKEN_BITS     0x100
+#define CSR_DBG_HPET_MEM_REG     0x240
+#define CSR_DBG_LINK_PWR_MGMT_REG 0x250
+
+#define HW_IF_NIC_READY          0x00400000u
+#define HW_IF_PREPARE            0x08000000u
+#define HW_IF_HAP_WAKE_L1A       0x00080000u
+#define INT_FH_RX                (1u << 31)
+#define INT_HW_ERR               (1u << 29)
+#define INT_FH_TX                (1u << 27)
+#define INT_SW_ERR               (1u << 25)
+#define INT_SW_RX                (1u << 3)
+#define INT_ALIVE                (1u << 0)
+#define RESET_SW_RESET           0x00000080u
+#define RESET_MASTER_DISABLED    0x00000100u
+#define RESET_STOP_MASTER        0x00000200u
+#define GP_MAC_CLOCK_READY       0x00000001u
+#define GP_INIT_DONE             0x00000004u
+#define GP_MAC_ACCESS_REQ        0x00000008u
+#define GP_GOING_TO_SLEEP        0x00000010u
+#define GP_HW_RF_KILL_SW         0x08000000u
+#define UCODE_SW_BIT_RFKILL      0x00000002u
+#define UCODE_CMD_BLOCKED        0x00000004u
+#define MBOX_OS_ALIVE            (1u << 5)
+#define GIO_L0S_DISABLED         0x00000002u
+#define GIO_CHICKEN_L1A_NO_L0S_RX 0x00800000u
+#define GIO_CHICKEN_DIS_L0S_TIMER 0x20000000u
+#define LINK_PWR_MGMT_DISABLED   0x80000000u
+
+#define HBUS_TARG_MEM_WADDR      0x410
+#define HBUS_TARG_MEM_WDAT       0x418
+#define HBUS_TARG_PRPH_WADDR     0x444
+#define HBUS_TARG_PRPH_RADDR     0x448
+#define HBUS_TARG_PRPH_WDAT      0x44c
+#define HBUS_TARG_PRPH_RDAT      0x450
+#define HBUS_TARG_WRPTR          0x460
+
+#define FH_KW_MEM_ADDR_REG       0x197c
+#define FH_RSCSR_STTS_WPTR       0x1bc0
+#define FH_RSCSR_RBDCB_BASE      0x1bc4
+#define FH_RSCSR_RBDCB_WPTR      0x1bc8
+#define FH_RSCSR_RDPTR           0x1bcc
+#define FH_RCSR_CONFIG           0x1c00
+#define FH_RCSR_RBDCB_WPTR       0x1c08
+#define FH_RCSR_FLUSH_RB_REQ     0x1c10
+#define FH_TFDIB_CTRL0(c)        (0x1900 + 8 * (c))
+#define FH_TFDIB_CTRL1(c)        (0x1904 + 8 * (c))
+#define FH_TCSR_CONFIG(c)        (0x1d00 + 0x20 * (c))
+#define FH_TCSR_BUF_STS(c)       (0x1d08 + 0x20 * (c))
+#define FH_SRVC_CHNL             9
+#define FH_SRVC_SRAM_ADDR        0x19c8
+#define FH_TX_CHICKEN_BITS       0x1e98
+#define FH_TCSR_DMA_ENABLE       0x80000000u
+#define FH_TCSR_CREDIT_ENABLE    0x00000008u
+#define FH_TCSR_HOST_ENDTFD      0x00100000u
+#define FH_MEM_TB_MAX_LENGTH     0x20000u
+
+#define APMG_CLK_EN_REG          0x3004
+#define APMG_PS_CTRL_REG         0x300c
+#define APMG_PCIDEV_STT_REG      0x3010
+#define APMG_RTC_INT_STT_REG     0x301c
+#define APMG_CLK_DMA_RQT         0x00000200u
+#define APMG_PS_PWR_SRC_MSK      0x03000000u
+#define APMG_PCIDEV_L1_ACT_DIS   0x00000800u
+#define APMG_PCIDEV_WAKE_ME      0x00004000u
+#define APMG_RTC_INT_RFKILL      0x10000000u
+#define LMPM_CHICK               0xa01ff8
+#define LMPM_EXTENDED_ADDR       0x1u
+#define FW_MEM_EXT_START         0x40000u
+#define FW_MEM_EXT_END           0x57fffu
+
+#define SCD_BASE                 0xa02c00
+#define SCD_SRAM_BASE_ADDR       (SCD_BASE + 0x0)
+#define SCD_DRAM_BASE_ADDR       (SCD_BASE + 0x8)
+#define SCD_TXFACT               (SCD_BASE + 0x10)
+#define SCD_QUEUECHAIN_SEL       (SCD_BASE + 0xe8)
+#define SCD_AGGR_SEL             (SCD_BASE + 0x248)
+#define SCD_GP_CTRL              (SCD_BASE + 0x1a8)
+#define SCD_EN_CTRL              (SCD_BASE + 0x254)
+#define SCD_GP_AUTO_ACTIVE       (1u << 18)
+#define SCD_GP_31_QUEUES         (1u << 0)
+#define SCD_CONTEXT_MEM          0x600
+#define SCD_TRANS_TBL_MEM        0x7e0
+#define SCD_STTS_ACTIVE          3
+#define SCD_STTS_TXF             0
+#define SCD_STTS_WSL             4
+#define SCD_STTS_ACT_EN          19
+#define SCD_STTS_MSK             0x017f0000u
+
+static unsigned int scd_queue_rdptr(unsigned int q)
+{
+	return q < 20 ? SCD_BASE + 0x68 + q * 4 : SCD_BASE + 0x2b4 + q * 4;
+}
+
+static unsigned int scd_queue_status(unsigned int q)
+{
+	return q < 20 ? SCD_BASE + 0x10c + q * 4 : SCD_BASE + 0x334 + (q - 20) * 4;
+}
+
+static unsigned int fh_cbbc(unsigned int q)
+{
+	if (q < 16)
+		return 0x19d0 + 4 * q;
+	if (q < 20)
+		return 0x1bf0 + 4 * (q - 16);
+	return 0x1b20 + 4 * (q - 20);
+}
+
+/* ---- device state ------------------------------------------------------ */
+#define RX_RING      256
+#define TFD_SIZE     128
+#define TFD_RING     256
+#define BC_ENTRIES   320            /* 256 + 64 duplicate */
+#define CMD_SLOTS    32
+#define CMD_BUF      4096           /* one page per command slot */
+#define DATA_SLOTS   32
+#define DATA_BUF     2048
+#define FIRST_TB     20             /* IWL_FIRST_TB_SIZE */
+
+struct txq {
+	unsigned char *tfds;        /* 256 x 128-byte TFDs */
+	unsigned char *bufs;        /* slots x bufsize */
+	unsigned int nslots, bufsize;
+	unsigned int wptr, rptr;    /* 0..255 */
+	int active;
+};
+
+struct iwl_state {
+	volatile unsigned char *mmio;
+	unsigned int bar, bus, dev, func, devid, hw_rev;
+	const char *chip;
+	unsigned int *rbd;          /* RX descriptors (page) */
+	unsigned char *rb[RX_RING]; /* RX buffers (4 KB pages) */
+	volatile unsigned short *rb_stts;
+	unsigned int rx_read;
+	unsigned short *bc;         /* byte-count tables, IWL_NUM_Q x 320 */
+	unsigned char *kw;          /* keep-warm page */
+	unsigned char *fwbuf;       /* 128 KB firmware chunk bounce buffer */
+	struct txq q[IWL_NUM_Q];
+	unsigned int scd_base;
+	iwl_rx_handler handler;
+	/* synchronous command bookkeeping */
+	int waiting;                /* a command is waiting for its response */
+	unsigned short wait_seq;
+	void *resp;
+	unsigned int resp_max;
+	int resp_len, resp_done;
+	unsigned char wait_notif;
+	int notif_seen;
+	int fatal;
+	struct iwl_fw_info fw;
+	const unsigned char *fw_data;
+	unsigned int fw_size;
+};
+
+static struct iwl_state *S;   /* page-allocated on probe */
+typedef char iwl_state_fits_page[sizeof(struct iwl_state) <= 4096 ? 1 : -1];
+
+void iwl_log(const char *s)
+{
+	serial_puts(SERIAL_COM1, "iwl: ");
+	serial_puts(SERIAL_COM1, s);
+	serial_puts(SERIAL_COM1, "\n");
+}
+
+void iwl_loghex(const char *s, unsigned int v)
+{
+	serial_puts(SERIAL_COM1, "iwl: ");
+	serial_puts(SERIAL_COM1, s);
+	serial_puts(SERIAL_COM1, " ");
+	serial_puthex(SERIAL_COM1, v);
+	serial_puts(SERIAL_COM1, "\n");
+}
+
+/* Byte helpers: the kernel has no libc, and `rep` string ops keep gcc from
+ * turning a loop back into a memcpy/memset call. */
+void iwl_memcpy(void *dst, const void *src, unsigned int n)
+{
+	__asm__ volatile ("cld; rep movsb"
+			  : "+D"(dst), "+S"(src), "+c"(n) : : "memory");
+}
+
+void iwl_memzero(void *dst, unsigned int n)
+{
+	__asm__ volatile ("cld; rep stosb"
+			  : "+D"(dst), "+c"(n) : "a"(0) : "memory");
+}
+
+/* ~1 us per port-0x80 write on every chipset; works with interrupts off
+ * (some network syscalls run with IF=0, which freezes get_ticks_ms()). */
+void iwl_udelay(unsigned int us)
+{
+	while (us--)
+		port_outb(0x80, 0);
+}
+
+unsigned int iwl_rd(unsigned int reg)
+{
+	return *(volatile unsigned int *)(S->mmio + reg);
+}
+
+void iwl_wr(unsigned int reg, unsigned int val)
+{
+	*(volatile unsigned int *)(S->mmio + reg) = val;
+}
+
+static void iwl_set(unsigned int reg, unsigned int bits)
+{
+	iwl_wr(reg, iwl_rd(reg) | bits);
+}
+
+static void iwl_clr(unsigned int reg, unsigned int bits)
+{
+	iwl_wr(reg, iwl_rd(reg) & ~bits);
+}
+
+/* Poll until (reg & mask) == (bits & mask); timeout in microseconds. */
+static int iwl_poll(unsigned int reg, unsigned int bits, unsigned int mask,
+		    unsigned int us)
+{
+	unsigned int t;
+
+	for (t = 0; t < us; t += 10) {
+		if ((iwl_rd(reg) & mask) == (bits & mask))
+			return 0;
+		iwl_udelay(10);
+	}
+	return -1;
+}
+
+unsigned int iwl_rd_prph(unsigned int addr)
+{
+	iwl_wr(HBUS_TARG_PRPH_RADDR, (addr & 0x000fffffu) | (3u << 24));
+	return iwl_rd(HBUS_TARG_PRPH_RDAT);
+}
+
+void iwl_wr_prph(unsigned int addr, unsigned int val)
+{
+	iwl_wr(HBUS_TARG_PRPH_WADDR, (addr & 0x000fffffu) | (3u << 24));
+	iwl_wr(HBUS_TARG_PRPH_WDAT, val);
+}
+
+static void prph_set(unsigned int addr, unsigned int bits)
+{
+	iwl_wr_prph(addr, iwl_rd_prph(addr) | bits);
+}
+
+static void prph_clr(unsigned int addr, unsigned int bits)
+{
+	iwl_wr_prph(addr, iwl_rd_prph(addr) & ~bits);
+}
+
+unsigned int iwl_mem_rd32(unsigned int addr)
+{
+	iwl_wr(0x40c /* HBUS_TARG_MEM_RADDR */, addr);
+	return iwl_rd(0x41c /* HBUS_TARG_MEM_RDAT */);
+}
+
+static void mem_wr32(unsigned int addr, unsigned int val)
+{
+	iwl_wr(HBUS_TARG_MEM_WADDR, addr);
+	iwl_wr(HBUS_TARG_MEM_WDAT, val);
+}
+
+static void mem_zero(unsigned int addr, unsigned int dwords)
+{
+	iwl_wr(HBUS_TARG_MEM_WADDR, addr);
+	while (dwords--)
+		iwl_wr(HBUS_TARG_MEM_WDAT, 0);
+}
+
+/* Wake the MAC and keep it awake (MAC_ACCESS_REQ stays set). */
+static int grab_nic(void)
+{
+	iwl_set(CSR_GP_CNTRL, GP_MAC_ACCESS_REQ);
+	if (iwl_poll(CSR_GP_CNTRL, GP_MAC_CLOCK_READY,
+		     GP_MAC_CLOCK_READY | GP_GOING_TO_SLEEP, 15000) < 0) {
+		iwl_loghex("nic access timeout, GP_CNTRL", iwl_rd(CSR_GP_CNTRL));
+		return -1;
+	}
+	return 0;
+}
+
+/* ---- probe --------------------------------------------------------------- */
+static const char *chip_for(unsigned int devid)
+{
+	switch (devid) {
+	case 0x095a: case 0x095b: return "Intel Wireless 7265";
+	case 0x3165: case 0x3166: return "Intel Wireless 3165";
+	}
+	return 0;
+}
+
+int iwl_present(void)
+{
+	return S != 0;
+}
+
+const char *iwl_chip_name(void)
+{
+	return S ? S->chip : "none";
+}
+
+unsigned int iwl_hw_rev(void)
+{
+	return S ? S->hw_rev : 0;
+}
+
+const struct iwl_fw_info *iwl_fw(void)
+{
+	return S ? &S->fw : 0;
+}
+
+const unsigned char *iwl_fw_data(unsigned int *size)
+{
+	if (!S)
+		return 0;
+	*size = S->fw_size;
+	return S->fw_data;
+}
+
+/* Put the function in D0 (PCI PM capability), as pci_enable_device()
+ * does; firmware can leave an unused WiFi card in D3hot. */
+static void pci_d0(unsigned int bus, unsigned int dev, unsigned int func)
+{
+	unsigned int cap, n;
+
+	if (!((pci_cfg_read32(bus, dev, func, 0x04) >> 16) & 0x10))
+		return;
+	cap = pci_cfg_read32(bus, dev, func, 0x34) & 0xfcu;
+	for (n = 0; cap && n < 48; n++) {
+		unsigned int hdr = pci_cfg_read32(bus, dev, func, cap);
+
+		if ((hdr & 0xff) == 0x01) {
+			unsigned int pmcsr = pci_cfg_read32(bus, dev, func, cap + 4);
+
+			if (pmcsr & 3u) {
+				pci_cfg_write32(bus, dev, func, cap + 4,
+						pmcsr & ~3u);
+				iwl_udelay(10000);
+				iwl_log("PCI D3 -> D0");
+			}
+			return;
+		}
+		cap = (hdr >> 8) & 0xfcu;
+	}
+}
+
+int iwl_probe(void)
+{
+	unsigned int bus, dev, func;
+
+	if (S)
+		return 0;
+	for (bus = 0; bus < 256; bus++) {
+		for (dev = 0; dev < 32; dev++) {
+			unsigned int id = pci_cfg_read32(bus, dev, 0, 0);
+			unsigned int nfunc;
+
+			if (id == 0xffffffffu || id == 0)
+				continue;
+			nfunc = (pci_cfg_read32(bus, dev, 0, 0x0c) & 0x800000u) ? 8 : 1;
+			for (func = 0; func < nfunc; func++) {
+				unsigned int idf = pci_cfg_read32(bus, dev, func, 0);
+				unsigned int bar, cmd, page;
+				const char *name;
+
+				if ((idf & 0xffffu) != 0x8086)
+					continue;
+				name = chip_for(idf >> 16);
+				if (!name)
+					continue;
+				bar = pci_cfg_read32(bus, dev, func, 0x10);
+				if (bar & 1u)
+					continue;
+				bar &= 0xfffffff0u;
+				if (!bar) {
+					iwl_log("BAR0 unassigned");
+					continue;
+				}
+				page = mm_alloc_page();
+				if (!page)
+					return -1;
+				S = (struct iwl_state *)page;
+				iwl_memzero(S, 4096);
+				S->bar = bar;
+				S->bus = bus;
+				S->dev = dev;
+				S->func = func;
+				S->devid = idf >> 16;
+				S->chip = name;
+				pci_d0(bus, dev, func);
+				/* Memory + bus master, INTx off (polled). */
+				cmd = pci_cfg_read32(bus, dev, func, 0x04);
+				pci_cfg_write32(bus, dev, func, 0x04,
+						(cmd & 0xffffu) | 0x0006u | 0x0400u);
+				/* PCI_CFG_RETRY_TIMEOUT (0x41) = 0, like Linux. */
+				pci_cfg_write8(bus, dev, func, 0x41, 0);
+				/* Map the 8 KB CSR window in every address space
+				 * (probe may run after processes exist). */
+				process_map_mmio_all(bar, 0x2000);
+				S->mmio = (volatile unsigned char *)bar;
+				iwl_wr(CSR_INT_MASK, 0);
+				S->hw_rev = iwl_rd(CSR_HW_REV);
+				serial_puts(SERIAL_COM1, "iwl: ");
+				serial_puts(SERIAL_COM1, name);
+				serial_puts(SERIAL_COM1, " dev ");
+				serial_puthex(SERIAL_COM1, S->devid);
+				serial_puts(SERIAL_COM1, " hw_rev ");
+				serial_puthex(SERIAL_COM1, S->hw_rev);
+				serial_puts(SERIAL_COM1, " bar ");
+				serial_puthex(SERIAL_COM1, bar);
+				serial_puts(SERIAL_COM1, "\n");
+				if (S->hw_rev == 0xffffffffu) {
+					iwl_log("HW_REV reads ~0: PCI issue");
+					S = 0;
+					return -1;
+				}
+				/* 0x095a/b: only rev-D silicon runs the 7265D
+				 * firmware (Linux: CSR_HW_REV_TYPE_7265D). */
+				if (S->devid != 0x3165 && S->devid != 0x3166 &&
+				    (S->hw_rev & 0xfff0u) != 0x210u)
+					iwl_log("warning: not a 7265D; the 7265D firmware may fail");
+				return 0;
+			}
+		}
+	}
+	return -1;
+}
+
+/* ---- firmware file ------------------------------------------------------- */
+#define TLV_INST          1
+#define TLV_FLAGS         18
+#define TLV_SEC_RT        19
+#define TLV_SEC_INIT      20
+#define TLV_DEF_CALIB     22
+#define TLV_PHY_SKU       23
+#define TLV_API_CHANGES   29
+#define TLV_ENABLED_CAPA  30
+
+static unsigned int le32(const unsigned char *p)
+{
+	return p[0] | (p[1] << 8) | (p[2] << 16) | ((unsigned int)p[3] << 24);
+}
+
+int iwl_fw_parse(void)
+{
+	const unsigned char *d;
+	unsigned int size, off, i;
+
+	if (!S)
+		return -1;
+	if (S->fw.present)
+		return 0;
+	d = ramfs_lookup(FW_PATH, &size);
+	if (!d || size < 88 || le32(d) != 0 || le32(d + 4) != 0x0a4c5749u) {
+		iwl_log("firmware " FW_PATH " missing or not a TLV image");
+		return -1;
+	}
+	S->fw_data = d;
+	S->fw_size = size;
+	for (i = 0; i < sizeof(S->fw.human) - 1 && d[8 + i]; i++)
+		S->fw.human[i] = (char)d[8 + i];
+	S->fw.ver = le32(d + 72);
+	off = 88;
+	while (off + 8 <= size) {
+		unsigned int t = le32(d + off), l = le32(d + off + 4);
+		const unsigned char *p = d + off + 8;
+
+		if (off + 8 + l > size)
+			break;
+		if (t == TLV_API_CHANGES && l >= 8 && le32(p) < 4)
+			S->fw.api[le32(p)] = le32(p + 4);
+		else if (t == TLV_ENABLED_CAPA && l >= 8 && le32(p) < 4)
+			S->fw.capa[le32(p)] = le32(p + 4);
+		else if (t == TLV_PHY_SKU && l >= 4)
+			S->fw.phy_sku = le32(p);
+		else if (t == TLV_DEF_CALIB && l >= 12) {
+			unsigned int type = le32(p);
+			/* enum iwl_ucode_type: 0 REGULAR, 1 INIT */
+			if (type < 2) {
+				S->fw.flow_trigger[type] = le32(p + 4);
+				S->fw.event_trigger[type] = le32(p + 8);
+			}
+		}
+		off += 8 + ((l + 3) & ~3u);
+	}
+	S->fw.present = 1;
+	iwl_log(S->fw.human);
+	return 0;
+}
+
+/* ---- hardware bring-up ------------------------------------------------- */
+int iwl_rfkill(void)
+{
+	return S && !(iwl_rd(CSR_GP_CNTRL) & GP_HW_RF_KILL_SW);
+}
+
+static int set_hw_ready(void)
+{
+	iwl_set(CSR_HW_IF_CONFIG_REG, HW_IF_NIC_READY);
+	if (iwl_poll(CSR_HW_IF_CONFIG_REG, HW_IF_NIC_READY, HW_IF_NIC_READY, 50) < 0)
+		return -1;
+	iwl_set(CSR_MBOX_SET_REG, MBOX_OS_ALIVE);
+	return 0;
+}
+
+static int prepare_card(void)
+{
+	int iter, t;
+
+	if (set_hw_ready() == 0)
+		return 0;
+	iwl_set(CSR_DBG_LINK_PWR_MGMT_REG, LINK_PWR_MGMT_DISABLED);
+	iwl_udelay(1000);
+	for (iter = 0; iter < 10; iter++) {
+		iwl_set(CSR_HW_IF_CONFIG_REG, HW_IF_PREPARE);
+		for (t = 0; t < 150000; t += 200) {
+			if (set_hw_ready() == 0)
+				return 0;
+			iwl_udelay(200);
+		}
+		iwl_udelay(25000);
+	}
+	iwl_log("card not ready (owned by ME/AMT?)");
+	return -1;
+}
+
+static int apm_init(void)
+{
+	iwl_set(CSR_GIO_CHICKEN_BITS, GIO_CHICKEN_DIS_L0S_TIMER);
+	iwl_set(CSR_GIO_CHICKEN_BITS, GIO_CHICKEN_L1A_NO_L0S_RX);
+	iwl_set(CSR_DBG_HPET_MEM_REG, 0xffff0000u);
+	iwl_set(CSR_HW_IF_CONFIG_REG, HW_IF_HAP_WAKE_L1A);
+	iwl_set(CSR_GIO_REG, GIO_L0S_DISABLED);
+	/* iwl_finish_nic_init(): INIT_DONE, then wait for the MAC clock. */
+	iwl_set(CSR_GP_CNTRL, GP_INIT_DONE);
+	if (iwl_poll(CSR_GP_CNTRL, GP_MAC_CLOCK_READY, GP_MAC_CLOCK_READY,
+		     25000) < 0) {
+		iwl_log("MAC clock not ready");
+		return -1;
+	}
+	if (grab_nic() < 0)
+		return -1;
+	iwl_wr_prph(APMG_CLK_EN_REG, APMG_CLK_DMA_RQT);
+	iwl_udelay(20);
+	prph_set(APMG_PCIDEV_STT_REG, APMG_PCIDEV_L1_ACT_DIS);
+	iwl_wr_prph(APMG_RTC_INT_STT_REG, APMG_RTC_INT_RFKILL);
+	return 0;
+}
+
+static void stop_master(void)
+{
+	iwl_set(CSR_RESET, RESET_STOP_MASTER);
+	if (iwl_poll(CSR_RESET, RESET_MASTER_DISABLED, RESET_MASTER_DISABLED,
+		     100) < 0)
+		iwl_log("master disable timed out");
+}
+
+int iwl_start_hw(void)
+{
+	if (!S)
+		return -1;
+	if (prepare_card() < 0)
+		return -1;
+	iwl_set(CSR_RESET, RESET_SW_RESET);
+	iwl_udelay(6000);
+	if (prepare_card() < 0)
+		return -1;
+	if (apm_init() < 0)
+		return -1;
+	iwl_wr(CSR_INT, 0xffffffffu);
+	iwl_wr(CSR_FH_INT_STATUS, 0xffffffffu);
+	return 0;
+}
+
+static void rx_stop(void)
+{
+	iwl_wr(FH_RCSR_CONFIG, 0);
+	iwl_poll(0x1c44 /* FH_MEM_RSSR_RX_STATUS_REG */, 0x01000000u,
+		 0x01000000u, 1000);
+}
+
+void iwl_stop_device(void)
+{
+	unsigned int c;
+
+	if (!S || !S->mmio)
+		return;
+	iwl_wr(CSR_INT_MASK, 0);
+	if (iwl_rd(CSR_GP_CNTRL) & GP_MAC_CLOCK_READY) {
+		/* Stop the scheduler, every TX DMA channel and RX DMA. */
+		iwl_wr_prph(SCD_TXFACT, 0);
+		for (c = 0; c < 8; c++)
+			iwl_wr(FH_TCSR_CONFIG(c), 0);
+		rx_stop();
+		iwl_wr_prph(APMG_CLK_EN_REG, APMG_CLK_DMA_RQT);
+		/* Inform ME that we are leaving (7000 family). */
+		prph_set(APMG_PCIDEV_STT_REG, APMG_PCIDEV_WAKE_ME);
+		iwl_udelay(5000);
+	}
+	stop_master();
+	iwl_set(CSR_RESET, RESET_SW_RESET);
+	iwl_udelay(6000);
+	iwl_clr(CSR_GP_CNTRL, GP_INIT_DONE | GP_MAC_ACCESS_REQ);
+	iwl_wr(CSR_INT, 0xffffffffu);
+	iwl_wr(CSR_FH_INT_STATUS, 0xffffffffu);
+	for (c = 0; c < IWL_NUM_Q; c++)
+		S->q[c].active = 0;
+}
+
+/* ---- ring allocation ---------------------------------------------------- */
+static void *alloc_zero(unsigned int pages)
+{
+	unsigned int p = mm_alloc_pages(pages);
+
+	if (p)
+		iwl_memzero((void *)p, pages * 4096);
+	return (void *)p;
+}
+
+static int alloc_txq(int qn, unsigned int slots, unsigned int bufsize)
+{
+	struct txq *q = &S->q[qn];
+
+	if (!q->tfds) {
+		q->tfds = alloc_zero(TFD_RING * TFD_SIZE / 4096);
+		q->bufs = alloc_zero((slots * bufsize + 4095) / 4096);
+		if (!q->tfds || !q->bufs)
+			return -1;
+		q->nslots = slots;
+		q->bufsize = bufsize;
+	}
+	iwl_memzero(q->tfds, TFD_RING * TFD_SIZE);
+	q->wptr = q->rptr = 0;
+	q->active = 0;
+	return 0;
+}
+
+static int alloc_rings(void)
+{
+	unsigned int i;
+
+	if (!S->rbd) {
+		S->rbd = alloc_zero(1);
+		S->rb_stts = alloc_zero(1);
+		S->bc = alloc_zero((IWL_NUM_Q * BC_ENTRIES * 2 + 4095) / 4096);
+		S->kw = alloc_zero(1);
+		S->fwbuf = alloc_zero(FH_MEM_TB_MAX_LENGTH / 4096);
+		if (!S->rbd || !S->rb_stts || !S->bc || !S->kw || !S->fwbuf)
+			return -1;
+		for (i = 0; i < RX_RING; i++) {
+			S->rb[i] = (unsigned char *)mm_alloc_page();
+			if (!S->rb[i])
+				return -1;
+		}
+	}
+	if (alloc_txq(IWL_Q_CMD, CMD_SLOTS, CMD_BUF) < 0 ||
+	    alloc_txq(IWL_Q_AUX, 8, DATA_BUF) < 0 ||
+	    alloc_txq(IWL_Q_BSS, DATA_SLOTS, DATA_BUF) < 0)
+		return -1;
+	return 0;
+}
+
+static void rx_init(void)
+{
+	unsigned int i;
+
+	for (i = 0; i < RX_RING; i++) {
+		*(volatile unsigned int *)S->rb[i] = 0x55550000u; /* FRAME_INVALID */
+		S->rbd[i] = (unsigned int)S->rb[i] >> 8;
+	}
+	iwl_memzero((void *)S->rb_stts, 16);
+	S->rx_read = 0;
+
+	iwl_wr(FH_RCSR_CONFIG, 0);
+	iwl_wr(FH_RCSR_RBDCB_WPTR, 0);
+	iwl_wr(FH_RCSR_FLUSH_RB_REQ, 0);
+	iwl_wr(FH_RSCSR_RDPTR, 0);
+	iwl_wr(FH_RSCSR_RBDCB_WPTR, 0);
+	iwl_wr(FH_RSCSR_RBDCB_BASE, (unsigned int)S->rbd >> 8);
+	iwl_wr(FH_RSCSR_STTS_WPTR, (unsigned int)S->rb_stts >> 4);
+	/* enable | ignore RXF empty | irq to host | 4K RBs | RB timeout 0x11 |
+	 * 256 RBDs (log 8). */
+	iwl_wr(FH_RCSR_CONFIG, 0x80000000u | 0x4u | 0x1000u | 0 |
+	       (0x11u << 4) | (8u << 20));
+	*(volatile unsigned char *)(S->mmio + CSR_INT_COALESCING) = 0x40;
+	/* Hand every buffer but the last 8 to the hardware (write pointer
+	 * moves in multiples of 8). */
+	iwl_wr(FH_RSCSR_RBDCB_WPTR, (RX_RING - 8) & ~7u);
+}
+
+static void tx_init(void)
+{
+	unsigned int q;
+
+	iwl_wr_prph(SCD_TXFACT, 0);
+	iwl_wr(FH_KW_MEM_ADDR_REG, (unsigned int)S->kw >> 4);
+	for (q = 0; q < IWL_NUM_Q; q++)
+		if (S->q[q].tfds)
+			iwl_wr(fh_cbbc(q), (unsigned int)S->q[q].tfds >> 8);
+	prph_set(SCD_GP_CTRL, SCD_GP_AUTO_ACTIVE | SCD_GP_31_QUEUES);
+}
+
+/* ---- firmware load ------------------------------------------------------ */
+static int load_chunk(unsigned int dst, const unsigned char *src,
+		      unsigned int n)
+{
+	int ext = dst >= FW_MEM_EXT_START && dst <= FW_MEM_EXT_END;
+	unsigned int t;
+
+	iwl_memcpy(S->fwbuf, src, n);
+	if (ext)
+		prph_set(LMPM_CHICK, LMPM_EXTENDED_ADDR);
+	iwl_wr(CSR_INT, INT_FH_TX);
+	iwl_wr(CSR_FH_INT_STATUS, 0xffffffffu);
+	iwl_wr(FH_TCSR_CONFIG(FH_SRVC_CHNL), 0);
+	iwl_wr(FH_SRVC_SRAM_ADDR, dst);
+	iwl_wr(FH_TFDIB_CTRL0(FH_SRVC_CHNL), (unsigned int)S->fwbuf);
+	iwl_wr(FH_TFDIB_CTRL1(FH_SRVC_CHNL), n);
+	iwl_wr(FH_TCSR_BUF_STS(FH_SRVC_CHNL), (1u << 20) | (1u << 12) | 3u);
+	iwl_wr(FH_TCSR_CONFIG(FH_SRVC_CHNL),
+	       FH_TCSR_DMA_ENABLE | FH_TCSR_HOST_ENDTFD);
+	for (t = 0; t < 5000000; t += 10) {
+		if (iwl_rd(CSR_INT) & INT_FH_TX)
+			break;
+		iwl_udelay(10);
+	}
+	iwl_wr(CSR_INT, INT_FH_TX);
+	iwl_wr(CSR_FH_INT_STATUS, 0xffffffffu);
+	if (ext)
+		prph_clr(LMPM_CHICK, LMPM_EXTENDED_ADDR);
+	if (t >= 5000000) {
+		iwl_loghex("firmware chunk timeout at", dst);
+		return -1;
+	}
+	return 0;
+}
+
+static int load_sections(int img)
+{
+	unsigned int want = img == IWL_IMG_INIT ? TLV_SEC_INIT : TLV_SEC_RT;
+	const unsigned char *d = S->fw_data;
+	unsigned int off = 88, nsec = 0;
+
+	while (off + 8 <= S->fw_size) {
+		unsigned int t = le32(d + off), l = le32(d + off + 4);
+		const unsigned char *p = d + off + 8;
+
+		if (t == want && l > 4) {
+			unsigned int dst = le32(p), len = l - 4, o;
+
+			/* CPU1_CPU2 / paging separators end the CPU1 list
+			 * (single-CPU image: nothing follows that we load). */
+			if (dst == 0xffffccccu || dst == 0xaaaabbbbu)
+				break;
+			for (o = 0; o < len; o += FH_MEM_TB_MAX_LENGTH) {
+				unsigned int n = len - o;
+
+				if (n > FH_MEM_TB_MAX_LENGTH)
+					n = FH_MEM_TB_MAX_LENGTH;
+				if (load_chunk(dst + o, p + 4 + o, n) < 0)
+					return -1;
+			}
+			nsec++;
+		}
+		off += 8 + ((l + 3) & ~3u);
+	}
+	return nsec ? 0 : -1;
+}
+
+int iwl_load_fw(int img)
+{
+	if (!S || !S->fw.present)
+		return -1;
+	if (prepare_card() < 0)
+		return -1;
+	iwl_wr(CSR_INT, 0xffffffffu);
+	iwl_wr(CSR_UCODE_DRV_GP1_CLR, UCODE_SW_BIT_RFKILL);
+	iwl_wr(CSR_UCODE_DRV_GP1_CLR, UCODE_CMD_BLOCKED);
+	iwl_wr(CSR_INT, 0xffffffffu);
+	/* iwl_pcie_nic_init(): APM, power source VMAIN, NIC config, rings. */
+	if (apm_init() < 0)
+		return -1;
+	iwl_wr_prph(APMG_PS_CTRL_REG,
+		    iwl_rd_prph(APMG_PS_CTRL_REG) & ~APMG_PS_PWR_SRC_MSK);
+	if (alloc_rings() < 0) {
+		iwl_log("out of memory for rings");
+		return -1;
+	}
+	S->fatal = 0;
+	S->waiting = 0;
+	rx_init();
+	tx_init();
+	iwl_wr(CSR_MAC_SHADOW_REG_CTRL,
+	       iwl_rd(CSR_MAC_SHADOW_REG_CTRL) | 0x800fffffu);
+	iwl_wr(CSR_UCODE_DRV_GP1_CLR, UCODE_SW_BIT_RFKILL);
+	if (load_sections(img) < 0) {
+		iwl_log("firmware section load failed");
+		return -1;
+	}
+	iwl_wr(CSR_INT, 0xffffffffu);
+	iwl_wr(CSR_RESET, 0);           /* release the CPU */
+	return 0;
+}
+
+/* After ALIVE: scheduler context, byte-count tables, cmd queue on FIFO 7,
+ * TX DMA channels (iwl_pcie_tx_start()). */
+void iwl_fw_alive(unsigned int scd_base)
+{
+	struct txq *q = &S->q[IWL_Q_CMD];
+	unsigned int c;
+
+	S->scd_base = iwl_rd_prph(SCD_SRAM_BASE_ADDR);
+	if (scd_base && scd_base != S->scd_base)
+		iwl_loghex("scd base mismatch, alive says", scd_base);
+	mem_zero(S->scd_base + SCD_CONTEXT_MEM,
+		 (((SCD_TRANS_TBL_MEM + IWL_NUM_Q * 2) & 0xfffcu) -
+		  SCD_CONTEXT_MEM) / 4);
+	iwl_wr_prph(SCD_DRAM_BASE_ADDR, (unsigned int)S->bc >> 10);
+
+	/* iwl_trans_ac_txq_enable(cmd queue, FIFO 7). */
+	iwl_wr_prph(SCD_EN_CTRL, 0);
+	iwl_wr_prph(scd_queue_status(IWL_Q_CMD), 1u << SCD_STTS_ACT_EN);
+	prph_clr(SCD_AGGR_SEL, 1u << IWL_Q_CMD);
+	q->wptr = q->rptr = 0;
+	iwl_wr(HBUS_TARG_WRPTR, 0 | (IWL_Q_CMD << 8));
+	iwl_wr_prph(scd_queue_rdptr(IWL_Q_CMD), 0);
+	mem_wr32(S->scd_base + SCD_CONTEXT_MEM + IWL_Q_CMD * 8, 0);
+	mem_wr32(S->scd_base + SCD_CONTEXT_MEM + IWL_Q_CMD * 8 + 4,
+		 (64u & 0x7f) | ((64u << 16) & 0x7f0000u));
+	iwl_wr_prph(scd_queue_status(IWL_Q_CMD),
+		    (1u << SCD_STTS_ACTIVE) | (7u << SCD_STTS_TXF) |
+		    (1u << SCD_STTS_WSL) | SCD_STTS_MSK);
+	iwl_wr_prph(SCD_EN_CTRL, 1u << IWL_Q_CMD);
+	q->active = 1;
+
+	iwl_wr_prph(SCD_TXFACT, 0xffu);                 /* FIFOs 0..7 */
+	for (c = 0; c < 8; c++)
+		iwl_wr(FH_TCSR_CONFIG(c),
+		       FH_TCSR_DMA_ENABLE | FH_TCSR_CREDIT_ENABLE);
+	iwl_wr(FH_TX_CHICKEN_BITS, iwl_rd(FH_TX_CHICKEN_BITS) | 0x2u);
+	prph_clr(APMG_PCIDEV_STT_REG, APMG_PCIDEV_L1_ACT_DIS);
+}
+
+/* DQA data/mgmt queue (iwl_trans_pcie_txq_enable() with cfg == NULL: the
+ * firmware's SCD_QUEUE_CFG command configures the scheduler itself). */
+void iwl_txq_enable(int qn, unsigned short ssn)
+{
+	struct txq *q = &S->q[qn];
+
+	/* SCD write-pointer quirk: never move by a multiple of 0x40. */
+	if (!((ssn - q->wptr) & 0x3f) && ssn != q->wptr)
+		ssn++;
+	q->rptr = q->wptr = ssn & 0xff;
+	iwl_wr(HBUS_TARG_WRPTR, (ssn & 0xff) | ((unsigned int)qn << 8));
+	q->active = 1;
+}
+
+unsigned int iwl_txq_wptr(int q)
+{
+	return S->q[q].wptr;
+}
+
+/* ---- TX ---------------------------------------------------------------- */
+static void tfd_set(unsigned char *tfd, unsigned int tb, unsigned int addr,
+		    unsigned int len)
+{
+	unsigned char *e = tfd + 4 + tb * 6;
+
+	e[0] = addr; e[1] = addr >> 8; e[2] = addr >> 16; e[3] = addr >> 24;
+	e[4] = (len << 4) & 0xf0;
+	e[5] = len >> 4;
+	tfd[3] = (unsigned char)(tb + 1);
+}
+
+static void bc_set(int qn, unsigned int idx, unsigned int bytes,
+		   unsigned int sta)
+{
+	unsigned short *t = S->bc + qn * BC_ENTRIES;
+	unsigned short v;
+
+	/* + CRC + delimiter, in dwords (bc_table_dword on 7000). */
+	v = (unsigned short)((((bytes + 8) + 3) / 4) | (sta << 12));
+	t[idx] = v;
+	if (idx < BC_ENTRIES - TFD_RING)
+		t[TFD_RING + idx] = v;
+}
+
+static int txq_space(struct txq *q)
+{
+	return ((q->wptr - q->rptr) & 0xff) < q->nslots - 1;
+}
+
+static unsigned char *slot_buf(struct txq *q, unsigned int idx)
+{
+	return q->bufs + (idx & (q->nslots - 1)) * q->bufsize;
+}
+
+static void ring_doorbell(int qn)
+{
+	struct txq *q = &S->q[qn];
+
+	q->wptr = (q->wptr + 1) & 0xff;
+	iwl_wr(HBUS_TARG_WRPTR, q->wptr | ((unsigned int)qn << 8));
+}
+
+static int enqueue_cmd(unsigned int id, const void *data, unsigned int len,
+		       unsigned short *seq_out)
+{
+	struct txq *q = &S->q[IWL_Q_CMD];
+	/* mvm sets wide_cmd_header: legacy (group 0) commands are sent as
+	 * group 1 with the 8-byte header (iwl_trans_send_cmd(), DEF_ID). */
+	unsigned char group = (id >> 8) & 0xff ? (id >> 8) & 0xff : 1;
+	unsigned char *buf, *tfd;
+	unsigned int hdr = 8, total = hdr + len, idx;
+	unsigned short seq;
+
+	if (!q->active || total > CMD_BUF)
+		return -1;
+	if (!txq_space(q)) {
+		/* Command responses reclaim; every one we sent was synchronous,
+		 * so the ring can simply be considered drained. */
+		q->rptr = q->wptr;
+	}
+	idx = q->wptr;
+	buf = slot_buf(q, idx);
+	seq = (unsigned short)((IWL_Q_CMD << 8) | idx);
+	buf[0] = id & 0xff;
+	buf[1] = group;
+	buf[2] = seq & 0xff;
+	buf[3] = seq >> 8;
+	buf[4] = len & 0xff;
+	buf[5] = len >> 8;
+	buf[6] = 0;
+	buf[7] = (id >> 16) & 0xff;
+	iwl_memcpy(buf + hdr, data, len);
+	tfd = q->tfds + idx * TFD_SIZE;
+	iwl_memzero(tfd, TFD_SIZE);
+	if (total <= FIRST_TB) {
+		tfd_set(tfd, 0, (unsigned int)buf, total);
+	} else {
+		tfd_set(tfd, 0, (unsigned int)buf, FIRST_TB);
+		tfd_set(tfd, 1, (unsigned int)buf + FIRST_TB, total - FIRST_TB);
+	}
+	*seq_out = seq;
+	ring_doorbell(IWL_Q_CMD);
+	return 0;
+}
+
+int iwl_tx(int qn, const void *txcmd, unsigned int txlen,
+	   const void *frame, unsigned int flen, unsigned char sta_id,
+	   unsigned int mic_len)
+{
+	struct txq *q = &S->q[qn];
+	unsigned char *buf, *tfd;
+	unsigned int idx, total, t;
+
+	if (!q->active || 4 + txlen + flen > q->bufsize)
+		return -1;
+	for (t = 0; !txq_space(q); t++) {
+		if (t > 2000 || iwl_rx_poll() < 0)
+			return -1;
+		iwl_udelay(50);
+	}
+	idx = q->wptr;
+	buf = slot_buf(q, idx);
+	/* struct iwl_device_tx_cmd: 4-byte header (TX_CMD, seq) + tx_cmd. */
+	buf[0] = 0x1c;              /* TX_CMD */
+	buf[1] = 0;
+	buf[2] = idx;
+	buf[3] = (unsigned char)qn;
+	iwl_memcpy(buf + 4, txcmd, txlen);
+	iwl_memcpy(buf + 4 + txlen, frame, flen);
+	/* dram_lsb_ptr/msb: where the firmware writes the tx_cmd scratch
+	 * (offset 8 of struct iwl_tx_cmd), as iwl_pcie_tx() does. */
+	if (txlen >= 56) {
+		unsigned int scratch = (unsigned int)buf + 4 + 8;
+
+		buf[4 + 44] = scratch;
+		buf[4 + 45] = scratch >> 8;
+		buf[4 + 46] = scratch >> 16;
+		buf[4 + 47] = scratch >> 24;
+		buf[4 + 48] = 0;
+	}
+	total = 4 + txlen + flen;
+	tfd = q->tfds + idx * TFD_SIZE;
+	iwl_memzero(tfd, TFD_SIZE);
+	tfd_set(tfd, 0, (unsigned int)buf, FIRST_TB);
+	tfd_set(tfd, 1, (unsigned int)buf + FIRST_TB, total - FIRST_TB);
+	/* Byte count: the over-the-air MPDU (tx_cmd->len) plus the MIC the
+	 * firmware appends for a hardware-encrypted frame. */
+	bc_set(qn, idx, flen + mic_len, sta_id);
+	ring_doorbell(qn);
+	return 0;
+}
+
+void iwl_tx_reclaim(int qn, unsigned int idx)
+{
+	if (qn >= 0 && qn < IWL_NUM_Q)
+		S->q[qn].rptr = (idx + 1) & 0xff;
+}
+
+/* ---- RX ---------------------------------------------------------------- */
+void iwl_set_rx_handler(iwl_rx_handler h)
+{
+	S->handler = h;
+}
+
+static void handle_pkt(const struct iwl_pkt *pkt)
+{
+	if (S->waiting && !(pkt->seq & 0x8000u) && pkt->seq == S->wait_seq) {
+		unsigned int n = iwl_pkt_payload_len(pkt);
+
+		if (n > S->resp_max)
+			n = S->resp_max;
+		if (S->resp && n)
+			iwl_memcpy(S->resp, pkt->data, n);
+		S->resp_len = (int)iwl_pkt_payload_len(pkt);
+		S->resp_done = 1;
+		return;
+	}
+	if (S->wait_notif && pkt->group == 0 && pkt->cmd == S->wait_notif)
+		S->notif_seen = 1;
+	if (S->handler)
+		S->handler(pkt);
+}
+
+int iwl_rx_poll(void)
+{
+	unsigned int r, n = 0, ints;
+
+	if (!S || !S->rbd)
+		return 0;
+	ints = iwl_rd(CSR_INT);
+	if (ints & (INT_SW_ERR | INT_HW_ERR)) {
+		if (!S->fatal) {
+			iwl_loghex("firmware/hardware error, CSR_INT", ints);
+			iwl_loghex("GP_CNTRL", iwl_rd(CSR_GP_CNTRL));
+		}
+		S->fatal = 1;
+		iwl_wr(CSR_INT, ints);
+		return -1;
+	}
+	if (ints)
+		iwl_wr(CSR_INT, ints);
+	if (iwl_rd(CSR_FH_INT_STATUS))
+		iwl_wr(CSR_FH_INT_STATUS, 0xffffffffu);
+
+	r = S->rb_stts[0] & 0x0fff;
+	r &= RX_RING - 1;
+	while (S->rx_read != r) {
+		unsigned char *page = S->rb[S->rx_read];
+		unsigned int off = 0;
+
+		while (off + 12 < 4096) {
+			const struct iwl_pkt *pkt =
+				(const struct iwl_pkt *)(page + off);
+			unsigned int len;
+
+			if (pkt->len_n_flags == 0x55550000u)
+				break;
+			len = (pkt->len_n_flags & 0x3fffu) + 4;
+			if (len < 8 || off + len > 4096)
+				break;
+			handle_pkt(pkt);
+			off += (len + 63) & ~63u;
+		}
+		*(volatile unsigned int *)page = 0x55550000u;
+		S->rx_read = (S->rx_read + 1) & (RX_RING - 1);
+		n++;
+		/* Give the hardware the slot 8 behind us (multiple of 8). */
+		if ((S->rx_read & 7) == 0)
+			iwl_wr(FH_RSCSR_RBDCB_WPTR,
+			       (S->rx_read + RX_RING - 8) & (RX_RING - 1));
+	}
+	return S->fatal ? -1 : (int)n;
+}
+
+int iwl_wait_notif(unsigned char cmd, unsigned int ms)
+{
+	unsigned int t;
+
+	S->wait_notif = cmd;
+	S->notif_seen = 0;
+	for (t = 0; t < ms * 10; t++) {
+		if (iwl_rx_poll() < 0)
+			break;
+		if (S->notif_seen)
+			break;
+		iwl_udelay(100);
+	}
+	S->wait_notif = 0;
+	return S->notif_seen ? 0 : -1;
+}
+
+int iwl_send_cmd(unsigned int id, const void *data, unsigned int len,
+		 void *resp, unsigned int resp_max)
+{
+	unsigned short seq;
+	unsigned int t;
+
+	if (!S || S->fatal)
+		return -1;
+	S->resp = resp;
+	S->resp_max = resp_max;
+	S->resp_done = 0;
+	S->resp_len = -1;
+	if (enqueue_cmd(id, data, len, &seq) < 0)
+		return -1;
+	S->wait_seq = seq;
+	S->waiting = 1;
+	for (t = 0; t < 20000 && !S->resp_done; t++) {   /* 2 s */
+		if (iwl_rx_poll() < 0)
+			break;
+		if (!S->resp_done)
+			iwl_udelay(100);
+	}
+	S->waiting = 0;
+	S->q[IWL_Q_CMD].rptr = S->q[IWL_Q_CMD].wptr;
+	if (!S->resp_done) {
+		iwl_loghex("command timeout, id", id);
+		return -1;
+	}
+	return S->resp_len;
+}
+
+int iwl_send_cmd_async(unsigned int id, const void *data, unsigned int len)
+{
+	unsigned short seq;
+
+	if (!S || S->fatal)
+		return -1;
+	return enqueue_cmd(id, data, len, &seq);
+}

+ 106 - 0
iwl_trans.h

@@ -0,0 +1,106 @@
+/* Intel 7265D/3165 (iwlwifi "7000" family) PCIe transport.
+ *
+ * Polled, single RX queue, gen1 TFD TX queues.  Every ring and buffer comes
+ * from the page allocator (nothing big in BSS: the kernel image must stay
+ * below 0x90000).  iwl_mvm.c sits on top and speaks the firmware command
+ * protocol; wifi.c is the netdev / 802.11 layer. */
+#ifndef IWL_TRANS_H
+#define IWL_TRANS_H
+
+/* TX queues used in DQA mode (fw/api/txq.h). */
+#define IWL_Q_CMD   0     /* host commands, FIFO 7 */
+#define IWL_Q_AUX   1     /* aux station (scan probes) */
+#define IWL_Q_BSS   4     /* AP station: management + data */
+#define IWL_NUM_Q   31
+
+/* Firmware images in the .ucode file. */
+#define IWL_IMG_RT    0
+#define IWL_IMG_INIT  1
+
+/* Received firmware packet (struct iwl_rx_packet). */
+struct iwl_pkt {
+	unsigned int len_n_flags;   /* bits 0..13: length incl. 4-byte hdr */
+	unsigned char cmd;
+	unsigned char group;
+	unsigned short seq;         /* bit 15: unsolicited (SEQ_RX_FRAME) */
+	unsigned char data[];
+} __attribute__((packed));
+
+static inline unsigned int iwl_pkt_payload_len(const struct iwl_pkt *p)
+{
+	unsigned int l = p->len_n_flags & 0x3FFFu;
+	return l >= 4 ? l - 4 : 0;
+}
+
+/* Notification handler (set by iwl_mvm.c): called for every packet that is
+ * not the response a synchronous command is waiting for. */
+typedef void (*iwl_rx_handler)(const struct iwl_pkt *pkt);
+
+struct iwl_fw_info {
+	unsigned int api[4], capa[4];
+	unsigned int phy_sku;
+	unsigned int flow_trigger[2], event_trigger[2];   /* [IWL_IMG_*] */
+	unsigned int ver;           /* ucode API version from the header */
+	char human[24];
+	int present;
+};
+
+/* --- probe / lifecycle ------------------------------------------------- */
+int  iwl_probe(void);                  /* PCI scan + BAR map: 0 = found */
+int  iwl_present(void);
+const char *iwl_chip_name(void);
+unsigned int iwl_hw_rev(void);
+const struct iwl_fw_info *iwl_fw(void);
+
+int  iwl_fw_parse(void);               /* find + parse firmware in /ramfs */
+int  iwl_start_hw(void);               /* prepare, reset, APM init */
+int  iwl_load_fw(int img);             /* rings + sections + release reset */
+void iwl_fw_alive(unsigned int scd_base); /* SCD setup + cmd queue enable */
+void iwl_stop_device(void);            /* stop DMA, APM stop (kexec, retry) */
+int  iwl_rfkill(void);                 /* 1 = hardware RF-kill asserted */
+
+/* --- firmware I/O ------------------------------------------------------- */
+void iwl_set_rx_handler(iwl_rx_handler h);
+/* Poll the RX ring once; returns the number of packets handled, -1 on a
+ * firmware error (CSR_INT SW_ERR / HW_ERR). */
+int  iwl_rx_poll(void);
+/* Wait for a notification (cmd id in the legacy group) for up to `ms`.
+ * The handler still sees it; returns 0 when it arrived. */
+int  iwl_wait_notif(unsigned char cmd, unsigned int ms);
+/* Synchronous host command.  `id` is (group << 8) | opcode; `resp` (may be
+ * NULL) receives up to `resp_max` payload bytes.  Returns the payload
+ * length, or -1 on timeout/error. */
+int  iwl_send_cmd(unsigned int id, const void *data, unsigned int len,
+		  void *resp, unsigned int resp_max);
+/* Fire-and-forget command (no response expected or awaited). */
+int  iwl_send_cmd_async(unsigned int id, const void *data, unsigned int len);
+
+/* TX_CMD on a data/management queue: `txcmd` is the struct iwl_tx_cmd
+ * (header copied in, 802.11 header + payload follow in `frame`). */
+int  iwl_tx(int q, const void *txcmd, unsigned int txlen,
+	    const void *frame, unsigned int flen, unsigned char sta_id,
+	    unsigned int mic_len);
+/* TX response for queue q, slot idx: release the entries up to idx. */
+void iwl_tx_reclaim(int q, unsigned int idx);
+/* Activate a data/mgmt queue (trans side of SCD_QUEUE_CFG, DQA mode). */
+void iwl_txq_enable(int q, unsigned short ssn);
+unsigned int iwl_txq_wptr(int q);
+
+/* Firmware section data (for the NVM/PHY-DB helpers): returns the image. */
+const unsigned char *iwl_fw_data(unsigned int *size);
+
+/* Byte helpers (`rep movsb/stosb`; the kernel has no libc). */
+void iwl_memcpy(void *dst, const void *src, unsigned int n);
+void iwl_memzero(void *dst, unsigned int n);
+unsigned int iwl_mem_rd32(unsigned int addr);   /* device SRAM */
+
+/* Register helpers (also used by the mvm layer for diagnostics). */
+unsigned int iwl_rd(unsigned int reg);
+void iwl_wr(unsigned int reg, unsigned int val);
+unsigned int iwl_rd_prph(unsigned int addr);
+void iwl_wr_prph(unsigned int addr, unsigned int val);
+void iwl_udelay(unsigned int us);
+void iwl_log(const char *s);
+void iwl_loghex(const char *s, unsigned int v);
+
+#endif

+ 2 - 1
kernel.c

@@ -545,7 +545,8 @@ void kernel_main(void)
 	/* With a NIC present, try DHCP; on failure the static default stays.
 	 * Deliberately after the WM: a missing cable or DHCP server must not
 	 * delay the first frame. */
-	if (netdev_active() && !net_kept)
+	if (netdev_active() && !net_kept &&
+	    (!netdev_active()->link_up || netdev_active()->link_up()))
 		dhcp_run(4000);
 	boot_trace(net_kept ? "dhcp skipped" : "dhcp");
 

+ 1 - 0
ne2000.c

@@ -403,4 +403,5 @@ const struct netdev ne2000_netdev = {
 	"ne2000", "RTL8029AS",
 	ne2000_init, ne2000_get_mac, ne2000_rx, ne2000_tx, ne2000_print_info, 0, 0, 0,
 	0, 0, 0, 0, 0, 0,
+	0,
 };

+ 8 - 0
netdev.c

@@ -10,6 +10,7 @@
 #include "r8168.h"
 #include "rndis.h"
 #include "tcp.h"
+#include "wifi.h"
 static const struct netdev *const netdev_drivers[] = {
 	/* e1000e is the active test NIC; the ASIX is kept as the management
 	 * link by netdev_mgmt() even while e1000e is active. */
@@ -18,6 +19,9 @@ static const struct netdev *const netdev_drivers[] = {
 	&ne2000_netdev,
 	&asix_netdev,
 	&rndis_netdev,
+	/* Last: it only wins when nothing wired is present, and its link is
+	 * down until `wifi connect` (boot DHCP checks link_up). */
+	&wifi_netdev,
 };
 
 static const struct netdev *active;
@@ -132,6 +136,10 @@ void netdev_shutdown(void)
 		mgmt->stop();
 	if (act && act != mgmt && act->stop)
 		act->stop();
+	/* The WiFi card DMAs into its RX ring even when it is not the active
+	 * netdev; stop it so the next kernel does not get its pages written. */
+	if (act != &wifi_netdev && mgmt != &wifi_netdev)
+		wifi_shutdown();
 }
 
 int netdev_get_mac(unsigned char mac[6])

+ 4 - 0
netdev.h

@@ -29,6 +29,10 @@ struct netdev {
 	void (*dump_brief)(void);
 	/* Stop DMA before a kexec jump; may be NULL. */
 	void (*stop)(void);
+	/* Link state for drivers whose link can be down for long (WiFi before
+	 * association): 0 = no link, so the boot DHCP is skipped.  NULL means
+	 * "always up" (the wired drivers). */
+	int (*link_up)(void);
 };
 
 /* First registered driver that probes successfully (probe result is cached);

+ 1 - 0
r8168.c

@@ -986,4 +986,5 @@ const struct netdev r8168_netdev = {
 	r8168_init, r8168_get_mac, r8168_rx, r8168_tx, r8168_print_info,
 	r8168_dump_regs, r8168_set_loopback, r8168_reset,
 	0, 0, 0, 0, 0, 0,
+	0,
 };

+ 1 - 0
rndis.c

@@ -915,6 +915,7 @@ const struct netdev rndis_netdev = {
 	0,
 	0,
 	net_stop,
+	0,
 };
 
 static int device_probe(unsigned int ctrl, unsigned int addr,

+ 3 - 0
syscall.c

@@ -15,6 +15,7 @@
 #include "timer.h"
 #include "tty.h"
 #include "vfs.h"
+#include "wifi.h"
 
 static int copy_user_string(char *dst, unsigned int max, const char *src)
 {
@@ -407,6 +408,8 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 	}
 	case SYS_GETPID:
 		return (int)current_proc()->pid;
+	case SYS_WIFI:
+		return sys_wifi(a1, a2, a3);
 	case SYS_ALIVE:
 		return process_is_alive((unsigned int)a1);
 	case SYS_KILL:

+ 73 - 0
syscall.h

@@ -163,6 +163,31 @@
 /* Current process id (used for per-process temporary paths). */
 #define SYS_GETPID        108  /* () -> pid */
 
+/* Intel 7265D/3165 WiFi (wifi.c).  One multiplexed call: (op, a2, a3). */
+#define SYS_WIFI          110
+#define SYS_WIFI_UP          0  /* () -> 0 / -1: load firmware, read NVM */
+#define SYS_WIFI_STATUS      1  /* (struct sys_wifi_status *out) -> 0/-1 */
+#define SYS_WIFI_SCAN        2  /* () -> 0 / -1: start a scan */
+#define SYS_WIFI_RESULTS     3  /* (struct sys_wifi_bss *out, max) -> n,
+				   -2 while the scan is still running */
+#define SYS_WIFI_CONNECT     4  /* (const struct sys_wifi_connect *) ->
+				   0 associated, -1 failed (auth/assoc) */
+#define SYS_WIFI_DISCONNECT  5  /* () -> 0 */
+#define SYS_WIFI_EAPOL_RX    6  /* (buf, max) -> len, 0 none, -1 */
+#define SYS_WIFI_EAPOL_TX    7  /* (buf, len) -> 0/-1 (EAPOL PDU) */
+#define SYS_WIFI_SET_KEY     8  /* (const struct sys_wifi_key *) -> 0/-1 */
+#define SYS_WIFI_AUTHORIZE   9  /* () -> 0/-1: open the data port and make
+				   the WiFi card the active netdev */
+
+#define SYS_WIFI_SEC_OPEN    0
+#define SYS_WIFI_SEC_PSK     1  /* RSN, PSK AKM, CCMP pairwise + group */
+#define SYS_WIFI_SEC_OTHER   2  /* WEP/WPA1/TKIP/802.1X/SAE: unsupported */
+
+#define SYS_WIFI_ST_DOWN     0
+#define SYS_WIFI_ST_IDLE     1  /* firmware up, not associated */
+#define SYS_WIFI_ST_ASSOC    2  /* associated, port closed */
+#define SYS_WIFI_ST_LINK     3  /* associated, data port open */
+
 /* Stat one path (the file service has no open handle). */
 #define SYS_FS_STAT        98  /* (path, struct sys_stat *out) -> 0/<0 */
 
@@ -421,6 +446,54 @@ struct sys_blkdev {
 	unsigned int total_sectors;
 };
 
+struct sys_wifi_bss {
+	unsigned char bssid[6];
+	unsigned char channel;
+	signed char rssi;              /* dBm */
+	unsigned short beacon_int;     /* TU */
+	unsigned short capab;
+	unsigned char dtim;
+	unsigned char security;        /* SYS_WIFI_SEC_* */
+	unsigned char ssid_len;
+	unsigned char rsn_len;         /* AP's RSN IE (id/len included) */
+	unsigned char ssid[32];
+	unsigned char rsn[64];
+};
+
+struct sys_wifi_status {
+	int state;                     /* SYS_WIFI_ST_* */
+	unsigned char mac[6];
+	unsigned char bssid[6];
+	unsigned char channel;
+	signed char rssi;
+	unsigned char ssid_len;
+	unsigned char present;         /* card found on PCI */
+	unsigned char ssid[32];
+	char chip[24];
+	char fw[24];
+	char detail[24];               /* firmware state / last error */
+	unsigned int rx_frames, tx_frames, rx_dropped;
+	unsigned int conn_id;          /* bumped by every SYS_WIFI_CONNECT */
+};
+
+struct sys_wifi_connect {
+	unsigned char bssid[6];
+	unsigned char channel;
+	unsigned char ssid_len;
+	unsigned short beacon_int;
+	unsigned char dtim;
+	unsigned char ie_len;          /* our RSN IE for the assoc request */
+	unsigned char ssid[32];
+	unsigned char ie[64];
+};
+
+struct sys_wifi_key {
+	int pairwise;                  /* 1 = TK, 0 = GTK */
+	int keyidx;                    /* GTK key id 1..3 */
+	unsigned char key[16];
+	unsigned char rsc[8];          /* GTK receive sequence counter */
+};
+
 int syscall_dispatch(int num, int a1, int a2, int a3);
 
 #endif

+ 497 - 0
ucmd_wifi.c

@@ -0,0 +1,497 @@
+/* wifi: ring-3 WiFi command for the Intel 7265D/3165 (see wifi.c).
+ *
+ *   wifi                         status
+ *   wifi up                      load the firmware, show the MAC address
+ *   wifi scan                    list networks (strongest first)
+ *   wifi connect <ssid> [pass]   join an open or WPA2-PSK (CCMP) network,
+ *                                run DHCP; quote an SSID with spaces
+ *   wifi disconnect
+ *
+ * The WPA2 handshake (wpa.c) runs here; a small background copy of this
+ * command (`wifi __keep <state>`) stays alive after `connect` to answer
+ * group-key rekeys, and exits when the connection changes. */
+
+#include "ucmd_lib.h"
+#include "tls_rng.h"
+#include "wpa.h"
+
+#define MAX_BSS 32
+
+static struct sys_wifi_bss bss[MAX_BSS];
+
+static int wifi(int op, int a2, int a3)
+{
+	return u_syscall3(SYS_WIFI, op, a2, a3);
+}
+
+static void put_ssid(const unsigned char *s, unsigned int n)
+{
+	unsigned int i;
+
+	for (i = 0; i < n; i++)
+		u_putc(s[i] >= 32 && s[i] < 127 ? (char)s[i] : '?');
+}
+
+static int slen(const char *s)
+{
+	int n = 0;
+
+	while (s[n])
+		n++;
+	return n;
+}
+
+static int starts(const char *s, const char *p)
+{
+	while (*p)
+		if (*s++ != *p++)
+			return 0;
+	return 1;
+}
+
+static const char *skip_ws(const char *s)
+{
+	while (*s == ' ')
+		s++;
+	return s;
+}
+
+/* Next word or "quoted string" into out; returns the rest. */
+static const char *word(const char *s, char *out, unsigned int max)
+{
+	unsigned int n = 0;
+	char end = ' ';
+
+	s = skip_ws(s);
+	if (*s == '"') {
+		end = '"';
+		s++;
+	}
+	while (*s && *s != end) {
+		if (n + 1 < max)
+			out[n++] = *s;
+		s++;
+	}
+	if (*s == end)
+		s++;
+	out[n] = 0;
+	return s;
+}
+
+static void put_dbm(int v)
+{
+	if (v < 0) {
+		u_putc('-');
+		v = -v;
+	}
+	u_putdec((unsigned int)v);
+	u_puts(" dBm");
+}
+
+static const char *sec_name(unsigned int s)
+{
+	return s == SYS_WIFI_SEC_OPEN ? "open" :
+	       s == SYS_WIFI_SEC_PSK ? "WPA2" : "other";
+}
+
+static int cmd_status(void)
+{
+	struct sys_wifi_status st;
+	static const char *const names[] = { "down", "idle", "associated",
+					     "connected" };
+	unsigned char ip[4];
+
+	if (wifi(SYS_WIFI_STATUS, (int)&st, 0) < 0) {
+		u_puts("wifi: status failed\n");
+		return 1;
+	}
+	if (!st.present) {
+		u_puts("wifi: no Intel 7265/3165 card found\n");
+		return 1;
+	}
+	u_puts("chip:     "); u_puts(st.chip);
+	u_puts("\nstate:    "); u_puts(names[st.state & 3]);
+	u_puts(" ("); u_puts(st.detail); u_puts(")\n");
+	if (st.fw[0]) {
+		u_puts("firmware: "); u_puts(st.fw); u_puts("\n");
+	}
+	if (st.state != SYS_WIFI_ST_DOWN) {
+		u_puts("mac:      "); u_put_mac(st.mac); u_puts("\n");
+	}
+	if (st.state >= SYS_WIFI_ST_ASSOC) {
+		u_puts("network:  \""); put_ssid(st.ssid, st.ssid_len);
+		u_puts("\" "); u_put_mac(st.bssid);
+		u_puts(" ch "); u_putdec(st.channel);
+		u_puts(" "); put_dbm(st.rssi); u_puts("\n");
+		u_syscall1(SYS_NET_GET_IP, (int)ip);
+		u_puts("ip:       "); u_put_ip(ip); u_puts("\n");
+		u_puts("frames:   rx "); u_putdec(st.rx_frames);
+		u_puts(" tx "); u_putdec(st.tx_frames);
+		u_puts(" dropped "); u_putdec(st.rx_dropped); u_puts("\n");
+	}
+	return 0;
+}
+
+static int bring_up(void)
+{
+	struct sys_wifi_status st;
+
+	u_puts("wifi: loading firmware...\n");
+	if (wifi(SYS_WIFI_UP, 0, 0) < 0) {
+		wifi(SYS_WIFI_STATUS, (int)&st, 0);
+		u_puts("wifi: bring-up failed: ");
+		u_puts(st.detail);
+		u_puts(" (details on the serial/netmon log)\n");
+		return -1;
+	}
+	return 0;
+}
+
+/* Scan and return the number of entries, sorted by RSSI. */
+static int do_scan(void)
+{
+	int n, i, j;
+	unsigned int t0;
+
+	if (wifi(SYS_WIFI_SCAN, 0, 0) < 0) {
+		u_puts("wifi: scan failed (disconnect first?)\n");
+		return -1;
+	}
+	t0 = u_ticks_ms();
+	while ((n = wifi(SYS_WIFI_RESULTS, (int)bss, MAX_BSS)) == -2) {
+		if (u_ticks_ms() - t0 > 15000) {
+			u_puts("wifi: scan timed out\n");
+			return -1;
+		}
+		u_sleep_ms(100);
+	}
+	if (n < 0)
+		return -1;
+	for (i = 1; i < n; i++)
+		for (j = i; j > 0 && bss[j].rssi > bss[j - 1].rssi; j--) {
+			struct sys_wifi_bss t = bss[j];
+
+			bss[j] = bss[j - 1];
+			bss[j - 1] = t;
+		}
+	return n;
+}
+
+static int cmd_scan(void)
+{
+	int n, i;
+
+	if (bring_up() < 0)
+		return 1;
+	u_puts("wifi: scanning...\n");
+	n = do_scan();
+	if (n < 0)
+		return 1;
+	if (n == 0)
+		u_puts("no networks found\n");
+	for (i = 0; i < n; i++) {
+		put_dbm(bss[i].rssi);
+		u_puts(bss[i].channel < 10 ? "  ch   " :
+		       bss[i].channel < 100 ? "  ch  " : "  ch ");
+		u_putdec(bss[i].channel);
+		u_puts("  ");
+		u_puts(sec_name(bss[i].security));
+		u_puts(bss[i].security == SYS_WIFI_SEC_PSK ? "   " : "   ");
+		if (bss[i].ssid_len)
+			put_ssid(bss[i].ssid, bss[i].ssid_len);
+		else
+			u_puts("(hidden)");
+		u_puts("\n");
+	}
+	return 0;
+}
+
+static int hexval(char c)
+{
+	if (c >= '0' && c <= '9')
+		return c - '0';
+	if (c >= 'a' && c <= 'f')
+		return c - 'a' + 10;
+	if (c >= 'A' && c <= 'F')
+		return c - 'A' + 10;
+	return -1;
+}
+
+static int unhex(const char *s, unsigned char *out, unsigned int n)
+{
+	unsigned int i;
+
+	for (i = 0; i < n; i++) {
+		int a = hexval(s[2 * i]), b = hexval(s[2 * i + 1]);
+
+		if (a < 0 || b < 0)
+			return -1;
+		out[i] = (unsigned char)(a * 16 + b);
+	}
+	return 0;
+}
+
+static void tohex(const unsigned char *in, unsigned int n, char *out)
+{
+	static const char hx[] = "0123456789abcdef";
+	unsigned int i;
+
+	for (i = 0; i < n; i++) {
+		out[2 * i] = hx[in[i] >> 4];
+		out[2 * i + 1] = hx[in[i] & 15];
+	}
+	out[2 * n] = 0;
+}
+
+static int set_gtk(struct wpa_sm *sm)
+{
+	struct sys_wifi_key k;
+	unsigned int i;
+
+	k.pairwise = 0;
+	k.keyidx = sm->gtk_idx;
+	for (i = 0; i < 16; i++)
+		k.key[i] = sm->gtk[i];
+	for (i = 0; i < 8; i++)
+		k.rsc[i] = sm->gtk_rsc[i];
+	return wifi(SYS_WIFI_SET_KEY, (int)&k, 0);
+}
+
+/* Run the 4-way handshake: msg1 -> msg2, msg3 -> msg4 + keys. */
+static int handshake(struct wpa_sm *sm)
+{
+	static unsigned char frame[1024], reply[256];
+	unsigned int t0 = u_ticks_ms(), rlen;
+	int n, r;
+
+	while (u_ticks_ms() - t0 < 8000) {
+		n = wifi(SYS_WIFI_EAPOL_RX, (int)frame, sizeof(frame));
+		if (n < 0)
+			return -1;
+		if (n == 0) {
+			u_sleep_ms(20);
+			continue;
+		}
+		r = wpa_rx(sm, frame, (unsigned int)n, reply, &rlen, tls_random);
+		if (r == WPA_ERR) {
+			u_puts("wifi: handshake: ");
+			u_puts(sm->error ? sm->error : "error");
+			u_puts("\n");
+			return -1;
+		}
+		if (r == WPA_NONE)
+			continue;
+		if (wifi(SYS_WIFI_EAPOL_TX, (int)reply, (int)rlen) < 0)
+			return -1;
+		if (r == WPA_PTK) {
+			struct sys_wifi_key k;
+			unsigned int i;
+
+			k.pairwise = 1;
+			k.keyidx = 0;
+			for (i = 0; i < 16; i++)
+				k.key[i] = WPA_TK(sm)[i];
+			for (i = 0; i < 8; i++)
+				k.rsc[i] = 0;
+			u_sleep_ms(20);      /* let message 4 leave in the clear */
+			if (wifi(SYS_WIFI_SET_KEY, (int)&k, 0) < 0 ||
+			    set_gtk(sm) < 0) {
+				u_puts("wifi: key install failed\n");
+				return -1;
+			}
+			return 0;
+		}
+	}
+	u_puts("wifi: handshake timed out (no EAPOL from the AP)\n");
+	return -1;
+}
+
+static void spawn_keeper(struct wpa_sm *sm, unsigned int conn_id)
+{
+	static char arg[8 + 96 + 16 + 12 + 4];
+	char *p = arg;
+	unsigned int i;
+
+	for (i = 0; "__keep "[i]; i++)
+		*p++ = "__keep "[i];
+	tohex(sm->ptk, 48, p);
+	p += 96;
+	*p++ = ' ';
+	tohex(sm->replay, 8, p);
+	p += 16;
+	*p++ = ' ';
+	{
+		unsigned char id[4] = { conn_id >> 24, conn_id >> 16,
+					conn_id >> 8, conn_id };
+		tohex(id, 4, p);
+		p += 8;
+	}
+	*p = 0;
+	if (u_spawn("/ramfs/bin/wifi", arg, 0, "/") < 0)
+		u_puts("wifi: note: rekey helper did not start; the link will "
+		       "drop at the next group rekey\n");
+}
+
+static int cmd_connect(const char *args)
+{
+	char ssid[33], pass[80];
+	struct sys_wifi_connect c;
+	struct sys_wifi_status st;
+	static struct wpa_sm sm;
+	unsigned char pmk[32];
+	struct sys_wifi_bss *b = 0;
+	int n, i, r;
+	unsigned int ssid_len;
+
+	args = word(args, ssid, sizeof(ssid));
+	word(args, pass, sizeof(pass));
+	ssid_len = (unsigned int)slen(ssid);
+	if (!ssid_len) {
+		u_puts("usage: wifi connect <ssid> [passphrase]\n");
+		return 1;
+	}
+	if (bring_up() < 0)
+		return 1;
+	wifi(SYS_WIFI_DISCONNECT, 0, 0);
+	u_puts("wifi: scanning for \""); u_puts(ssid); u_puts("\"...\n");
+	n = do_scan();
+	if (n < 0)
+		return 1;
+	for (i = 0; i < n; i++) {
+		unsigned int j;
+
+		if (bss[i].ssid_len != ssid_len)
+			continue;
+		for (j = 0; j < ssid_len && bss[i].ssid[j] == (unsigned char)ssid[j]; j++)
+			;
+		if (j == ssid_len) {
+			b = &bss[i];       /* sorted: first match is strongest */
+			break;
+		}
+	}
+	if (!b) {
+		u_puts("wifi: network not found\n");
+		return 1;
+	}
+	if (b->security == SYS_WIFI_SEC_OTHER) {
+		u_puts("wifi: unsupported security (only open and WPA2-PSK/CCMP)\n");
+		return 1;
+	}
+	if (b->security == SYS_WIFI_SEC_PSK && !pass[0]) {
+		u_puts("wifi: this network needs a passphrase\n");
+		return 1;
+	}
+	for (i = 0; i < (int)sizeof(c); i++)
+		((unsigned char *)&c)[i] = 0;
+	for (i = 0; i < 6; i++)
+		c.bssid[i] = b->bssid[i];
+	c.channel = b->channel;
+	c.ssid_len = ssid_len;
+	for (i = 0; i < (int)ssid_len; i++)
+		c.ssid[i] = (unsigned char)ssid[i];
+	c.beacon_int = b->beacon_int;
+	c.dtim = b->dtim;
+	if (b->security == SYS_WIFI_SEC_PSK) {
+		int plen = slen(pass);
+
+		if (plen == 64 && unhex(pass, pmk, 32) == 0) {
+			/* raw 256-bit PSK */
+		} else if (plen >= 8 && plen <= 63) {
+			u_puts("wifi: deriving key...\n");
+			wpa_pmk(pass, c.ssid, ssid_len, pmk);
+		} else {
+			u_puts("wifi: a WPA2 passphrase has 8..63 characters\n");
+			return 1;
+		}
+		c.ie_len = (unsigned char)wpa_rsn_ie(c.ie);
+	}
+	u_puts("wifi: joining "); u_put_mac(c.bssid);
+	u_puts(" on channel "); u_putdec(c.channel); u_puts("\n");
+	if (wifi(SYS_WIFI_CONNECT, (int)&c, 0) < 0) {
+		wifi(SYS_WIFI_STATUS, (int)&st, 0);
+		u_puts("wifi: "); u_puts(st.detail); u_puts("\n");
+		return 1;
+	}
+	wifi(SYS_WIFI_STATUS, (int)&st, 0);
+	if (b->security == SYS_WIFI_SEC_PSK) {
+		wpa_init(&sm, pmk, c.bssid, st.mac, c.ie, c.ie_len,
+			 b->rsn, b->rsn_len);
+		u_puts("wifi: 4-way handshake...\n");
+		if (handshake(&sm) < 0) {
+			wifi(SYS_WIFI_DISCONNECT, 0, 0);
+			return 1;
+		}
+	}
+	r = wifi(SYS_WIFI_AUTHORIZE, 0, 0);
+	if (r < 0)
+		u_puts("wifi: connected, but the WiFi card could not become the "
+		       "active netdev (close TCP users, then `netdev wifi`)\n");
+	else
+		u_puts("wifi: connected\n");
+	if (b->security == SYS_WIFI_SEC_PSK)
+		spawn_keeper(&sm, st.conn_id);
+	if (r == 0 && u_syscall1(SYS_DHCP_RUN, 6000) != 0)
+		u_puts("wifi: DHCP failed; set an address with netip\n");
+	return 0;
+}
+
+/* Background: answer group-key rekeys until the connection changes. */
+static int keeper(const char *args)
+{
+	static struct wpa_sm sm;
+	static unsigned char frame[1024], reply[256];
+	struct sys_wifi_status st;
+	unsigned char id[4];
+	unsigned int conn_id, rlen;
+
+	args = skip_ws(args);
+	if (slen(args) < 96 + 1 + 16 + 1 + 8 ||
+	    unhex(args, sm.ptk, 48) < 0 ||
+	    unhex(args + 97, sm.replay, 8) < 0 ||
+	    unhex(args + 114, id, 4) < 0)
+		return 1;
+	conn_id = ((unsigned int)id[0] << 24) | (id[1] << 16) | (id[2] << 8) | id[3];
+	sm.have_replay = 1;
+	sm.ptk_ok = 1;
+	for (;;) {
+		int n;
+
+		if (wifi(SYS_WIFI_STATUS, (int)&st, 0) < 0 ||
+		    st.conn_id != conn_id || st.state < SYS_WIFI_ST_ASSOC)
+			return 0;
+		n = wifi(SYS_WIFI_EAPOL_RX, (int)frame, sizeof(frame));
+		if (n > 0 && wpa_rx(&sm, frame, (unsigned int)n, reply, &rlen,
+				    tls_random) == WPA_GTK) {
+			wifi(SYS_WIFI_EAPOL_TX, (int)reply, (int)rlen);
+			set_gtk(&sm);
+		}
+		u_sleep_ms(200);
+	}
+}
+
+void _start(const char *arg)
+{
+	const char *a = skip_ws(arg ? arg : "");
+	int r = 0;
+
+	if (!*a)
+		r = cmd_status();
+	else if (starts(a, "__keep "))
+		r = keeper(a + 7);
+	else if (starts(a, "up")) {
+		r = bring_up() < 0;
+		if (!r)
+			r = cmd_status();
+	} else if (starts(a, "scan"))
+		r = cmd_scan();
+	else if (starts(a, "connect "))
+		r = cmd_connect(a + 8);
+	else if (starts(a, "disconnect")) {
+		wifi(SYS_WIFI_DISCONNECT, 0, 0);
+		u_puts("wifi: disconnected\n");
+	} else {
+		u_puts("usage: wifi [up|scan|connect <ssid> [pass]|disconnect]\n");
+		r = 1;
+	}
+	u_exit(r);
+}

+ 1 - 1
vesa_stage.S

@@ -25,7 +25,7 @@
 
 /* Rootfs/boot-info constants (must match rootfs.h / bootinfo.h). */
 .equ ROOTFS_VERSION,   1
-.equ PACK_MAX,         0x100000      /* 1 MB compressed rootfs cap */
+.equ PACK_MAX,         0x200000      /* 2 MB compressed rootfs cap */
 .equ PACK_HIGH_ADDR,   0x900000      /* above the 8 MB VGA-shadow reserve */
 .equ BOOT_INFO_MAGIC,  0x4E425349
 .equ BOOT_INFO_VERSION, 2

+ 805 - 0
wifi.c

@@ -0,0 +1,805 @@
+/* WiFi station: see wifi.h.
+ *
+ * MLME-lite: open-system authentication and (re)association are built and
+ * parsed here; the RSN IE for the association request and the whole WPA2
+ * 4-way/group handshake come from the ring-3 `wifi` command (wpa.c), which
+ * exchanges EAPOL frames through SYS_WIFI_EAPOL_RX/TX and installs the
+ * TK/GTK with SYS_WIFI_SET_KEY.  CCMP runs in the firmware.
+ *
+ * Data frames are non-QoS (the association request has no WMM/HT IE), so
+ * every frame is a plain 24-byte-header 802.11 data frame + LLC/SNAP.
+ * Page-allocated buffers only: the kernel image must stay below 0x90000. */
+
+#include "wifi.h"
+#include "iwl_mvm.h"
+#include "iwl_trans.h"
+#include "io.h"
+#include "mm.h"
+#include "net.h"
+#include "paging.h"
+#include "process.h"
+#include "serial.h"
+#include "syscall.h"
+
+#define MAX_BSS      32
+#define RXQ_SLOTS    16
+#define RXQ_FRAME    1536
+#define EAPOLQ_SLOTS 4
+#define EAPOL_MAX    1024
+
+struct rxq_slot {
+	unsigned short len;
+	unsigned char data[RXQ_FRAME];
+};
+
+struct eapol_slot {
+	unsigned short len;
+	unsigned char data[EAPOL_MAX];
+};
+
+static struct {
+	int present;                  /* probed on PCI */
+	int state;                    /* SYS_WIFI_ST_* */
+	unsigned char mac[6];
+	struct sys_wifi_bss *bss;     /* page: MAX_BSS entries */
+	unsigned int nbss;
+	struct sys_wifi_bss cur;      /* the BSS we are joining / joined */
+	int protect;                  /* RSN association: CCMP data */
+	unsigned long long pn;        /* CCMP TX packet number */
+	/* MLME waits */
+	int auth_done, auth_status;
+	int assoc_done, assoc_status;
+	unsigned short aid;
+	/* queues (page-allocated) */
+	struct rxq_slot *rxq;
+	unsigned int rxq_head, rxq_tail;
+	struct eapol_slot *eapq;
+	unsigned int eapq_head, eapq_tail;
+	unsigned char *txbuf;         /* one 2 KB frame build buffer */
+	unsigned int rx_frames, tx_frames, rx_dropped;
+	unsigned int conn_id;
+	const char *detail;
+} W;
+
+static void wmemcpy(void *d, const void *s, unsigned int n)
+{
+	iwl_memcpy(d, s, n);
+}
+
+static int meq(const unsigned char *a, const unsigned char *b, unsigned int n)
+{
+	while (n--)
+		if (*a++ != *b++)
+			return 0;
+	return 1;
+}
+
+static void put16(unsigned char *p, unsigned int v)
+{
+	p[0] = v; p[1] = v >> 8;
+}
+
+static unsigned int get16(const unsigned char *p)
+{
+	return p[0] | (p[1] << 8);
+}
+
+static int alloc_buffers(void)
+{
+	if (W.bss)
+		return 0;
+	W.bss = (struct sys_wifi_bss *)mm_alloc_pages(
+		(MAX_BSS * sizeof(struct sys_wifi_bss) + 4095) / 4096);
+	W.rxq = (struct rxq_slot *)mm_alloc_pages(
+		(RXQ_SLOTS * sizeof(struct rxq_slot) + 4095) / 4096);
+	W.eapq = (struct eapol_slot *)mm_alloc_pages(
+		(EAPOLQ_SLOTS * sizeof(struct eapol_slot) + 4095) / 4096);
+	W.txbuf = (unsigned char *)mm_alloc_page();
+	if (!W.bss || !W.rxq || !W.eapq || !W.txbuf) {
+		W.bss = 0;
+		return -1;
+	}
+	return 0;
+}
+
+static int wifi_up(void)
+{
+	if (W.state != SYS_WIFI_ST_DOWN)
+		return 0;
+	if (alloc_buffers() < 0) {
+		W.detail = "out of memory";
+		return -1;
+	}
+	if (iwl_mvm_up(W.mac) < 0) {
+		W.detail = iwl_mvm_state();
+		return -1;
+	}
+	W.present = 1;
+	W.state = SYS_WIFI_ST_IDLE;
+	W.detail = "ready";
+	return 0;
+}
+
+/* ---- management frame parsing ------------------------------------------ */
+static void parse_rsn(struct sys_wifi_bss *b, const unsigned char *ie,
+		      unsigned int len)
+{
+	static const unsigned char oui[3] = { 0x00, 0x0f, 0xac };
+	unsigned int n, i, p = 2;
+	int ccmp = 0, psk = 0, group_ok = 0;
+
+	if (len + 2 > sizeof(b->rsn))
+		len = sizeof(b->rsn) - 2;
+	b->rsn[0] = 48;
+	b->rsn[1] = len;
+	wmemcpy(b->rsn + 2, ie, len);
+	b->rsn_len = len + 2;
+	/* version(2) group(4) npair(2) pair[] nakm(2) akm[] caps */
+	if (len < 8)
+		goto out;
+	group_ok = meq(ie + p, oui, 3) && ie[p + 3] == 4;
+	p += 4;
+	n = get16(ie + p);
+	p += 2;
+	for (i = 0; i < n && p + 4 <= len; i++, p += 4)
+		if (meq(ie + p, oui, 3) && ie[p + 3] == 4)
+			ccmp = 1;
+	if (p + 2 > len)
+		goto out;
+	n = get16(ie + p);
+	p += 2;
+	for (i = 0; i < n && p + 4 <= len; i++, p += 4)
+		if (meq(ie + p, oui, 3) && ie[p + 3] == 2)
+			psk = 1;
+out:
+	b->security = (ccmp && psk && group_ok) ? SYS_WIFI_SEC_PSK
+						: SYS_WIFI_SEC_OTHER;
+}
+
+static void rx_beacon(const unsigned char *f, unsigned int len, int rssi,
+		      unsigned int phy_chan)
+{
+	struct sys_wifi_bss tmp, *b = 0;
+	unsigned int off = 36, i;
+
+	if (len < 36 || !W.bss)
+		return;
+	iwl_memzero(&tmp, sizeof(tmp));
+	wmemcpy(tmp.bssid, f + 16, 6);
+	tmp.beacon_int = get16(f + 32);
+	tmp.capab = get16(f + 34);
+	tmp.rssi = (signed char)rssi;
+	tmp.channel = phy_chan;
+	tmp.dtim = 1;
+	tmp.security = (tmp.capab & 0x10) ? SYS_WIFI_SEC_OTHER : SYS_WIFI_SEC_OPEN;
+	while (off + 2 <= len) {
+		unsigned int id = f[off], l = f[off + 1];
+		const unsigned char *ie = f + off + 2;
+
+		if (off + 2 + l > len)
+			break;
+		if (id == 0 && l <= 32) {
+			tmp.ssid_len = l;
+			wmemcpy(tmp.ssid, ie, l);
+		} else if (id == 3 && l >= 1) {
+			tmp.channel = ie[0];
+		} else if (id == 5 && l >= 2) {
+			tmp.dtim = ie[1] ? ie[1] : 1;
+		} else if (id == 48) {
+			parse_rsn(&tmp, ie, l);
+		}
+		off += 2 + l;
+	}
+	for (i = 0; i < W.nbss; i++)
+		if (meq(W.bss[i].bssid, tmp.bssid, 6)) {
+			b = &W.bss[i];
+			break;
+		}
+	if (!b) {
+		if (W.nbss < MAX_BSS) {
+			b = &W.bss[W.nbss++];
+		} else {
+			/* replace the weakest entry if this one is stronger */
+			b = &W.bss[0];
+			for (i = 1; i < MAX_BSS; i++)
+				if (W.bss[i].rssi < b->rssi)
+					b = &W.bss[i];
+			if (b->rssi >= tmp.rssi)
+				return;
+		}
+	}
+	*b = tmp;
+}
+
+static void rx_mgmt(const unsigned char *f, unsigned int len, int rssi,
+		    unsigned int chan)
+{
+	unsigned int stype = (f[0] >> 4) & 0xf;
+
+	if (stype == 8 || stype == 5) {             /* beacon / probe resp */
+		rx_beacon(f, len, rssi, chan);
+		if (W.state >= SYS_WIFI_ST_ASSOC && meq(f + 16, W.cur.bssid, 6))
+			W.cur.rssi = (signed char)rssi;
+		return;
+	}
+	if (len < 24 || !meq(f + 4, W.mac, 6) || !meq(f + 16, W.cur.bssid, 6))
+		return;
+	if (stype == 11 && len >= 30) {             /* authentication */
+		if (get16(f + 26) == 2) {
+			W.auth_status = get16(f + 28);
+			W.auth_done = 1;
+		}
+	} else if ((stype == 1 || stype == 3) && len >= 30) { /* assoc resp */
+		W.assoc_status = get16(f + 26);
+		W.aid = get16(f + 28) & 0x3fff;
+		W.assoc_done = 1;
+	} else if (stype == 12 || stype == 10) {    /* deauth / disassoc */
+		if (W.state >= SYS_WIFI_ST_ASSOC) {
+			serial_puts(SERIAL_COM1, "wifi: deauthenticated, reason ");
+			serial_putdec(SERIAL_COM1, len >= 26 ? get16(f + 24) : 0);
+			serial_puts(SERIAL_COM1, "\n");
+			W.state = SYS_WIFI_ST_IDLE;
+			W.detail = "deauthenticated by AP";
+			iwl_mvm_disconnect();
+		}
+	}
+}
+
+static void queue_eapol(const unsigned char *p, unsigned int len)
+{
+	struct eapol_slot *s;
+
+	if (len > EAPOL_MAX ||
+	    ((W.eapq_head + 1) % EAPOLQ_SLOTS) == W.eapq_tail)
+		return;
+	s = &W.eapq[W.eapq_head];
+	s->len = len;
+	wmemcpy(s->data, p, len);
+	W.eapq_head = (W.eapq_head + 1) % EAPOLQ_SLOTS;
+}
+
+static void rx_data(const unsigned char *f, unsigned int len,
+		    unsigned int status)
+{
+	static const unsigned char snap[6] = { 0xaa, 0xaa, 0x03, 0, 0, 0 };
+	unsigned int hdr = 24, stype = (f[0] >> 4) & 0xf, type, plen;
+	const unsigned char *p;
+	struct rxq_slot *s;
+	int prot = (f[1] & 0x40) != 0;
+
+	if (W.state < SYS_WIFI_ST_ASSOC || (f[1] & 0x03) != 0x02)
+		return;                              /* FromDS only */
+	if (!meq(f + 10, W.cur.bssid, 6))
+		return;
+	if (stype & 4)
+		return;                              /* null / no data */
+	if (stype & 8)
+		hdr += 2;                            /* QoS control */
+	if (prot) {
+		if ((status & IWL_RX_SEC_MSK) != IWL_RX_SEC_CCM ||
+		    !(status & IWL_RX_MIC_OK)) {
+			W.rx_dropped++;
+			return;
+		}
+		hdr += 8;                            /* CCMP header */
+		if (len < hdr + 8)
+			return;
+		len -= 8;                            /* MIC */
+	}
+	if (len < hdr + 8 || !meq(f + hdr, snap, 6))
+		return;
+	type = (f[hdr + 6] << 8) | f[hdr + 7];
+	p = f + hdr + 8;
+	plen = len - hdr - 8;
+	if (type == 0x888e) {
+		queue_eapol(p, plen);
+		return;
+	}
+	/* Before the keys are in, or unprotected after: drop. */
+	if (W.state != SYS_WIFI_ST_LINK || (W.protect && !prot)) {
+		W.rx_dropped++;
+		return;
+	}
+	if (plen + 14 > RXQ_FRAME ||
+	    ((W.rxq_head + 1) % RXQ_SLOTS) == W.rxq_tail) {
+		W.rx_dropped++;
+		return;
+	}
+	s = &W.rxq[W.rxq_head];
+	wmemcpy(s->data, f + 4, 6);                  /* DA = A1 */
+	wmemcpy(s->data + 6, f + 16, 6);             /* SA = A3 */
+	s->data[12] = type >> 8;
+	s->data[13] = type;
+	wmemcpy(s->data + 14, p, plen);
+	s->len = plen + 14;
+	W.rxq_head = (W.rxq_head + 1) % RXQ_SLOTS;
+	W.rx_frames++;
+}
+
+void wifi_rx_frame(const unsigned char *frame, unsigned int len, int rssi,
+		   unsigned int status, unsigned int channel)
+{
+	unsigned int type;
+
+	if (len < 24)
+		return;
+	type = (frame[0] >> 2) & 3;
+	if (type == 0)
+		rx_mgmt(frame, len, rssi, channel);
+	else if (type == 2)
+		rx_data(frame, len, status);
+}
+
+void wifi_scan_done(int ok)
+{
+	if (!ok)
+		serial_puts(SERIAL_COM1, "wifi: scan aborted\n");
+}
+
+/* ---- TX ---------------------------------------------------------------- */
+/* Build and send an 802.11 data frame to the AP: header, [CCMP header],
+ * LLC/SNAP, ethertype, payload. */
+static int tx_data(const unsigned char *dst, unsigned int ethertype,
+		   const unsigned char *payload, unsigned int plen)
+{
+	unsigned char *f = W.txbuf;
+	unsigned int o = 24;
+	int prot = W.protect && W.state == SYS_WIFI_ST_LINK;
+
+	if (W.state < SYS_WIFI_ST_ASSOC || plen + 24 + 8 + 8 > 2048)
+		return -1;
+	iwl_memzero(f, 24);
+	f[0] = 0x08;                                 /* data */
+	f[1] = 0x01 | (prot ? 0x40 : 0);             /* ToDS [| protected] */
+	wmemcpy(f + 4, W.cur.bssid, 6);
+	wmemcpy(f + 10, W.mac, 6);
+	wmemcpy(f + 16, dst, 6);
+	if (prot) {
+		unsigned long long pn = ++W.pn;
+
+		f[o + 0] = pn;
+		f[o + 1] = pn >> 8;
+		f[o + 2] = 0;
+		f[o + 3] = 0x20;                     /* ExtIV, key id 0 */
+		f[o + 4] = pn >> 16;
+		f[o + 5] = pn >> 24;
+		f[o + 6] = pn >> 32;
+		f[o + 7] = pn >> 40;
+		o += 8;
+	}
+	f[o++] = 0xaa; f[o++] = 0xaa; f[o++] = 0x03;
+	f[o++] = 0; f[o++] = 0; f[o++] = 0;
+	f[o++] = ethertype >> 8;
+	f[o++] = ethertype;
+	wmemcpy(f + o, payload, plen);
+	if (iwl_mvm_tx_data(f, o + plen, prot) < 0)
+		return -1;
+	W.tx_frames++;
+	return 0;
+}
+
+static int tx_mgmt_frame(unsigned int stype, const unsigned char *body,
+			 unsigned int blen)
+{
+	unsigned char *f = W.txbuf;
+
+	if (24 + blen > 2048)
+		return -1;
+	iwl_memzero(f, 24);
+	f[0] = stype << 4;
+	wmemcpy(f + 4, W.cur.bssid, 6);
+	wmemcpy(f + 10, W.mac, 6);
+	wmemcpy(f + 16, W.cur.bssid, 6);
+	wmemcpy(f + 24, body, blen);
+	return iwl_mvm_tx_mgmt(f, 24 + blen);
+}
+
+static int wait_flag(int *flag, unsigned int ms)
+{
+	unsigned int t;
+
+	for (t = 0; t < ms && !*flag; t++) {
+		if (iwl_mvm_poll() < 0)
+			return -1;
+		if (!*flag)
+			iwl_udelay(1000);
+	}
+	return *flag ? 0 : -1;
+}
+
+static int do_connect(const struct sys_wifi_connect *c)
+{
+	unsigned char body[160];
+	unsigned int o, i, tries;
+	static const unsigned char r24[] = { 1, 8, 0x82, 0x84, 0x8b, 0x96,
+					     0x0c, 0x12, 0x18, 0x24,
+					     50, 4, 0x30, 0x48, 0x60, 0x6c };
+	static const unsigned char r5[] = { 1, 8, 0x8c, 0x12, 0x98, 0x24,
+					    0xb0, 0x48, 0x60, 0x6c };
+
+	if (W.state == SYS_WIFI_ST_DOWN && wifi_up() < 0)
+		return -1;
+	if (W.state >= SYS_WIFI_ST_ASSOC) {
+		iwl_mvm_disconnect();
+		W.state = SYS_WIFI_ST_IDLE;
+	}
+	if (c->ssid_len > 32 || c->ie_len > sizeof(c->ie) || !c->channel)
+		return -1;
+	W.conn_id++;
+	iwl_memzero(&W.cur, sizeof(W.cur));
+	wmemcpy(W.cur.bssid, c->bssid, 6);
+	W.cur.channel = c->channel;
+	W.cur.ssid_len = c->ssid_len;
+	wmemcpy(W.cur.ssid, c->ssid, c->ssid_len);
+	W.cur.beacon_int = c->beacon_int ? c->beacon_int : 100;
+	W.cur.dtim = c->dtim ? c->dtim : 1;
+	W.protect = c->ie_len != 0;
+	W.pn = 0;
+	W.eapq_head = W.eapq_tail = 0;
+	W.rxq_head = W.rxq_tail = 0;
+
+	if (iwl_mvm_prepare_connect(c->bssid, c->channel, W.cur.beacon_int) < 0) {
+		W.detail = "firmware connect setup failed";
+		return -1;
+	}
+	/* Open-system authentication: alg 0, seq 1, status 0. */
+	for (tries = 0; tries < 3; tries++) {
+		W.auth_done = 0;
+		put16(body, 0);
+		put16(body + 2, 1);
+		put16(body + 4, 0);
+		if (tx_mgmt_frame(11, body, 6) < 0)
+			break;
+		if (wait_flag(&W.auth_done, 300) == 0)
+			break;
+	}
+	if (!W.auth_done || W.auth_status) {
+		W.detail = W.auth_done ? "authentication refused"
+				       : "no authentication reply";
+		iwl_mvm_disconnect();
+		return -1;
+	}
+	/* Association request: capability, listen interval, SSID, rates,
+	 * [RSN IE]. */
+	o = 0;
+	put16(body, 0x0001 | (W.protect ? 0x0010 : 0) | 0x0400);
+	put16(body + 2, 10);
+	o = 4;
+	body[o++] = 0;
+	body[o++] = c->ssid_len;
+	for (i = 0; i < c->ssid_len; i++)
+		body[o++] = c->ssid[i];
+	if (c->channel <= 14) {
+		wmemcpy(body + o, r24, sizeof(r24));
+		o += sizeof(r24);
+	} else {
+		wmemcpy(body + o, r5, sizeof(r5));
+		o += sizeof(r5);
+	}
+	if (c->ie_len) {
+		wmemcpy(body + o, c->ie, c->ie_len);
+		o += c->ie_len;
+	}
+	for (tries = 0; tries < 3; tries++) {
+		W.assoc_done = 0;
+		if (tx_mgmt_frame(0, body, o) < 0)
+			break;
+		if (wait_flag(&W.assoc_done, 500) == 0)
+			break;
+	}
+	if (!W.assoc_done || W.assoc_status) {
+		W.detail = W.assoc_done ? "association refused"
+					: "no association reply";
+		if (W.assoc_done) {
+			serial_puts(SERIAL_COM1, "wifi: assoc status ");
+			serial_putdec(SERIAL_COM1, W.assoc_status);
+			serial_puts(SERIAL_COM1, "\n");
+		}
+		iwl_mvm_disconnect();
+		return -1;
+	}
+	if (iwl_mvm_set_assoc(W.aid, W.cur.beacon_int, W.cur.dtim) < 0) {
+		W.detail = "firmware association update failed";
+		iwl_mvm_disconnect();
+		return -1;
+	}
+	W.state = SYS_WIFI_ST_ASSOC;
+	W.detail = W.protect ? "associated, waiting for keys" : "associated";
+	serial_puts(SERIAL_COM1, "wifi: associated, aid ");
+	serial_putdec(SERIAL_COM1, W.aid);
+	serial_puts(SERIAL_COM1, "\n");
+	return 0;
+}
+
+static void do_disconnect(void)
+{
+	static const unsigned char reason[2] = { 3, 0 };   /* leaving */
+
+	if (W.state >= SYS_WIFI_ST_ASSOC) {
+		tx_mgmt_frame(12, reason, 2);
+		iwl_mvm_poll();
+		iwl_mvm_disconnect();
+	}
+	if (W.state != SYS_WIFI_ST_DOWN)
+		W.state = SYS_WIFI_ST_IDLE;
+	W.detail = "disconnected";
+}
+
+/* ---- netdev ------------------------------------------------------------- */
+static int nd_init(void)
+{
+	if (W.state != SYS_WIFI_ST_DOWN)
+		return 0;
+	/* Boot probe: find the card only.  The firmware is loaded on first
+	 * use (`wifi`), so boot time and RAM are unchanged without WiFi. */
+	if (iwl_probe() < 0)
+		return -1;
+	W.present = 1;
+	W.detail = "firmware not loaded";
+	return 0;
+}
+
+static void nd_get_mac(unsigned char mac[6])
+{
+	wmemcpy(mac, W.mac, 6);
+}
+
+static int nd_rx(unsigned char *buf, unsigned int maxlen)
+{
+	struct rxq_slot *s;
+	unsigned int n;
+
+	if (W.state == SYS_WIFI_ST_DOWN)
+		return -1;
+	if (W.rxq_head == W.rxq_tail)
+		iwl_mvm_poll();
+	if (W.rxq_head == W.rxq_tail)
+		return -1;
+	s = &W.rxq[W.rxq_tail];
+	n = s->len < maxlen ? s->len : maxlen;
+	wmemcpy(buf, s->data, n);
+	W.rxq_tail = (W.rxq_tail + 1) % RXQ_SLOTS;
+	return (int)n;
+}
+
+static int nd_tx(const unsigned char *buf, unsigned int len)
+{
+	if (len < 14 || W.state != SYS_WIFI_ST_LINK)
+		return -1;
+	return tx_data(buf, (buf[12] << 8) | buf[13], buf + 14, len - 14);
+}
+
+static void print_hex6(const unsigned char *m)
+{
+	unsigned int i;
+
+	for (i = 0; i < 6; i++) {
+		static const char hx[] = "0123456789abcdef";
+		char s[4];
+
+		s[0] = hx[m[i] >> 4];
+		s[1] = hx[m[i] & 15];
+		s[2] = i < 5 ? ':' : 0;
+		s[3] = 0;
+		io_putstr(s);
+	}
+}
+
+static void print_dec(unsigned int v)
+{
+	char b[12];
+	int i = 11;
+
+	b[i] = 0;
+	do {
+		b[--i] = (char)('0' + v % 10);
+		v /= 10;
+	} while (v && i > 0);
+	io_putstr(b + i);
+}
+
+static void nd_print_info(void)
+{
+	static const char *const st[] = { "down", "idle", "associated", "link up" };
+
+	io_putstr("chip:  ");
+	io_putstr(iwl_chip_name());
+	io_putstr("\nstate: ");
+	io_putstr(st[W.state & 3]);
+	io_putstr(" (");
+	io_putstr(W.detail ? W.detail : "-");
+	io_putstr(")\nmac:   ");
+	print_hex6(W.mac);
+	if (W.state >= SYS_WIFI_ST_ASSOC) {
+		char ssid[33];
+		unsigned int i;
+
+		for (i = 0; i < W.cur.ssid_len && i < 32; i++)
+			ssid[i] = W.cur.ssid[i] >= 32 && W.cur.ssid[i] < 127
+				  ? (char)W.cur.ssid[i] : '?';
+		ssid[i] = 0;
+		io_putstr("\nbss:   ");
+		print_hex6(W.cur.bssid);
+		io_putstr(" \"");
+		io_putstr(ssid);
+		io_putstr("\" ch ");
+		print_dec(W.cur.channel);
+	}
+	io_putstr("\n");
+}
+
+static void nd_stop(void)
+{
+	wifi_shutdown();
+}
+
+static int nd_link_up(void)
+{
+	return W.state == SYS_WIFI_ST_LINK;
+}
+
+const struct netdev wifi_netdev = {
+	"wifi",
+	"Intel 7265D/3165 WiFi",
+	nd_init,
+	nd_get_mac,
+	nd_rx,
+	nd_tx,
+	nd_print_info,
+	0,
+	0,
+	0,
+	0,
+	0,
+	0,
+	0,
+	0,
+	nd_stop,
+	nd_link_up,
+};
+
+void wifi_shutdown(void)
+{
+	if (W.state != SYS_WIFI_ST_DOWN || iwl_present())
+		iwl_mvm_down();
+	if (W.state != SYS_WIFI_ST_DOWN)
+		W.state = SYS_WIFI_ST_DOWN;
+}
+
+/* ---- SYS_WIFI ------------------------------------------------------------ */
+static int user_ok(int ptr, unsigned int len, int write)
+{
+	return ptr && paging_user_range_ok(current_proc()->cr3,
+					   (unsigned int)ptr, len, write);
+}
+
+static void copy_str(char *dst, unsigned int max, const char *src)
+{
+	unsigned int i;
+
+	for (i = 0; src && src[i] && i + 1 < max; i++)
+		dst[i] = src[i];
+	dst[i] = 0;
+}
+
+int sys_wifi(int op, int a2, int a3)
+{
+	switch (op) {
+	case SYS_WIFI_UP:
+		if (!W.present && nd_init() < 0)
+			return -1;
+		return wifi_up();
+	case SYS_WIFI_STATUS: {
+		struct sys_wifi_status *s = (struct sys_wifi_status *)a2;
+		const struct iwl_fw_info *fw;
+
+		if (!user_ok(a2, sizeof(*s), 1))
+			return -1;
+		if (!W.present && iwl_probe() == 0)
+			W.present = 1;
+		iwl_memzero(s, sizeof(*s));
+		s->state = W.state;
+		s->present = (unsigned char)W.present;
+		wmemcpy(s->mac, W.mac, 6);
+		if (W.state >= SYS_WIFI_ST_ASSOC) {
+			wmemcpy(s->bssid, W.cur.bssid, 6);
+			s->channel = W.cur.channel;
+			s->rssi = W.cur.rssi;
+			s->ssid_len = W.cur.ssid_len;
+			wmemcpy(s->ssid, W.cur.ssid, W.cur.ssid_len);
+		}
+		copy_str(s->chip, sizeof(s->chip), W.present ? iwl_chip_name() : "none");
+		fw = iwl_fw();
+		copy_str(s->fw, sizeof(s->fw), fw && fw->present ? fw->human : "");
+		copy_str(s->detail, sizeof(s->detail),
+			 W.detail ? W.detail : (W.present ? "firmware not loaded"
+							  : "no card"));
+		s->rx_frames = W.rx_frames;
+		s->tx_frames = W.tx_frames;
+		s->rx_dropped = W.rx_dropped;
+		s->conn_id = W.conn_id;
+		return 0;
+	}
+	case SYS_WIFI_SCAN:
+		if (W.state == SYS_WIFI_ST_DOWN && sys_wifi(SYS_WIFI_UP, 0, 0) < 0)
+			return -1;
+		if (W.state >= SYS_WIFI_ST_ASSOC)
+			return -1;        /* scanning while associated: not yet */
+		W.nbss = 0;
+		return iwl_mvm_scan_start();
+	case SYS_WIFI_RESULTS: {
+		unsigned int max = (unsigned int)a3, n;
+
+		if (W.state == SYS_WIFI_ST_DOWN)
+			return -1;
+		iwl_mvm_poll();
+		if (iwl_mvm_scan_running())
+			return -2;
+		if (max > W.nbss)
+			max = W.nbss;
+		if (max && !user_ok(a2, max * sizeof(struct sys_wifi_bss), 1))
+			return -1;
+		for (n = 0; n < max; n++)
+			((struct sys_wifi_bss *)a2)[n] = W.bss[n];
+		return (int)max;
+	}
+	case SYS_WIFI_CONNECT: {
+		struct sys_wifi_connect c;
+
+		if (!user_ok(a2, sizeof(c), 0))
+			return -1;
+		wmemcpy(&c, (const void *)a2, sizeof(c));
+		return do_connect(&c);
+	}
+	case SYS_WIFI_DISCONNECT:
+		do_disconnect();
+		return 0;
+	case SYS_WIFI_EAPOL_RX: {
+		struct eapol_slot *s;
+		unsigned int n;
+
+		if (W.state < SYS_WIFI_ST_ASSOC)
+			return -1;
+		iwl_mvm_poll();
+		if (W.eapq_head == W.eapq_tail)
+			return 0;
+		s = &W.eapq[W.eapq_tail];
+		n = s->len < (unsigned int)a3 ? s->len : (unsigned int)a3;
+		if (!user_ok(a2, n, 1))
+			return -1;
+		wmemcpy((void *)a2, s->data, n);
+		W.eapq_tail = (W.eapq_tail + 1) % EAPOLQ_SLOTS;
+		return (int)n;
+	}
+	case SYS_WIFI_EAPOL_TX: {
+		unsigned int len = (unsigned int)a3;
+
+		if (W.state < SYS_WIFI_ST_ASSOC || len > EAPOL_MAX ||
+		    !user_ok(a2, len, 0))
+			return -1;
+		/* Stage behind the 2 KB frame build area of the TX page. */
+		wmemcpy(W.txbuf + 2048, (const void *)a2, len);
+		return tx_data(W.cur.bssid, 0x888e, W.txbuf + 2048, len);
+	}
+	case SYS_WIFI_SET_KEY: {
+		struct sys_wifi_key k;
+
+		if (W.state < SYS_WIFI_ST_ASSOC || !user_ok(a2, sizeof(k), 0))
+			return -1;
+		wmemcpy(&k, (const void *)a2, sizeof(k));
+		return iwl_mvm_set_key(k.pairwise, k.keyidx, k.key,
+				       k.pairwise ? 0 : k.rsc);
+	}
+	case SYS_WIFI_AUTHORIZE:
+		if (W.state < SYS_WIFI_ST_ASSOC)
+			return -1;
+		W.state = SYS_WIFI_ST_LINK;
+		W.detail = "connected";
+		if (netdev_active() != &wifi_netdev && netdev_select("wifi") != 0) {
+			W.detail = "connected (netdev busy)";
+			return -1;
+		}
+		return 0;
+	}
+	return -1;
+}

+ 18 - 0
wifi.h

@@ -0,0 +1,18 @@
+/* WiFi station (Intel 7265D/3165): 802.11 MLME, Ethernet <-> 802.11 data
+ * path, EAPOL queue for the ring-3 supplicant, and the `wifi` netdev.  The
+ * firmware and the PCIe transport are iwl_mvm.c / iwl_trans.c. */
+#ifndef WIFI_H
+#define WIFI_H
+
+#include "netdev.h"
+
+extern const struct netdev wifi_netdev;
+
+/* SYS_WIFI dispatcher (syscall.c). */
+int sys_wifi(int op, int a2, int a3);
+
+/* Stop the card's DMA before a kexec, even when it is not the active
+ * netdev (its RX ring would otherwise keep writing into freed pages). */
+void wifi_shutdown(void);
+
+#endif

+ 298 - 0
wpa.c

@@ -0,0 +1,298 @@
+/* Minimal WPA2-PSK supplicant: see wpa.h.
+ *
+ * EAPOL-Key frame offsets (from the EAPOL header):
+ *   0 version, 1 type (3 = Key), 2..3 body length (BE)
+ *   4 descriptor type (2 = RSN), 5..6 key info (BE), 7..8 key length
+ *   9..16 replay counter, 17..48 nonce, 49..64 IV, 65..72 RSC,
+ *   73..80 reserved, 81..96 MIC, 97..98 key data length, 99.. key data */
+
+#include "wpa.h"
+#include "wpa_crypto.h"
+
+#define KI_VER_MSK   0x0007
+#define KI_PAIRWISE  0x0008
+#define KI_INSTALL   0x0040
+#define KI_ACK       0x0080
+#define KI_MIC       0x0100
+#define KI_SECURE    0x0200
+#define KI_ENC_DATA  0x1000
+
+#define OFF_INFO   5
+#define OFF_REPLAY 9
+#define OFF_NONCE  17
+#define OFF_RSC    65
+#define OFF_MIC    81
+#define OFF_DLEN   97
+#define OFF_DATA   99
+
+static void cpy(unsigned char *d, const unsigned char *s, unsigned int n)
+{
+	while (n--)
+		*d++ = *s++;
+}
+
+static void zero(unsigned char *d, unsigned int n)
+{
+	while (n--)
+		*d++ = 0;
+}
+
+static int cmp(const unsigned char *a, const unsigned char *b, unsigned int n)
+{
+	unsigned int i;
+
+	for (i = 0; i < n; i++)
+		if (a[i] != b[i])
+			return a[i] < b[i] ? -1 : 1;
+	return 0;
+}
+
+static unsigned int be16(const unsigned char *p)
+{
+	return (p[0] << 8) | p[1];
+}
+
+void wpa_pmk(const char *pass, const unsigned char *ssid, unsigned int ssid_len,
+	     unsigned char pmk[32])
+{
+	unsigned int n = 0;
+
+	while (pass[n])
+		n++;
+	pbkdf2_sha1((const unsigned char *)pass, n, ssid, ssid_len, 4096,
+		    pmk, 32);
+}
+
+unsigned int wpa_rsn_ie(unsigned char out[22])
+{
+	static const unsigned char ie[22] = {
+		48, 20, 1, 0,
+		0x00, 0x0f, 0xac, 4,          /* group: CCMP */
+		1, 0, 0x00, 0x0f, 0xac, 4,    /* pairwise: CCMP */
+		1, 0, 0x00, 0x0f, 0xac, 2,    /* AKM: PSK */
+		0, 0,                         /* RSN capabilities */
+	};
+
+	cpy(out, ie, 22);
+	return 22;
+}
+
+void wpa_init(struct wpa_sm *sm, const unsigned char pmk[32],
+	      const unsigned char aa[6], const unsigned char spa[6],
+	      const unsigned char *ie, unsigned int ie_len,
+	      const unsigned char *ap_ie, unsigned int ap_ie_len)
+{
+	zero((unsigned char *)sm, sizeof(*sm));
+	cpy(sm->pmk, pmk, 32);
+	cpy(sm->aa, aa, 6);
+	cpy(sm->spa, spa, 6);
+	if (ie_len > sizeof(sm->ie))
+		ie_len = sizeof(sm->ie);
+	cpy(sm->ie, ie, ie_len);
+	sm->ie_len = ie_len;
+	if (ap_ie_len > sizeof(sm->ap_ie))
+		ap_ie_len = sizeof(sm->ap_ie);
+	cpy(sm->ap_ie, ap_ie, ap_ie_len);
+	sm->ap_ie_len = ap_ie_len;
+}
+
+static void derive_ptk(struct wpa_sm *sm)
+{
+	unsigned char b[6 + 6 + 32 + 32];
+	int am = cmp(sm->aa, sm->spa, 6) < 0;
+	int an = cmp(sm->anonce, sm->snonce, 32) < 0;
+
+	cpy(b, am ? sm->aa : sm->spa, 6);
+	cpy(b + 6, am ? sm->spa : sm->aa, 6);
+	cpy(b + 12, an ? sm->anonce : sm->snonce, 32);
+	cpy(b + 44, an ? sm->snonce : sm->anonce, 32);
+	wpa_prf(sm->pmk, 32, "Pairwise key expansion", b, sizeof(b),
+		sm->ptk, 48);
+}
+
+/* HMAC-SHA1-128 over the frame with the MIC field zeroed:
+ * [0, OFF_MIC) | 16 zero bytes | [OFF_MIC + 16, len). */
+static void calc_mic(const unsigned char *kck, const unsigned char *f,
+		     unsigned int len, unsigned char mic[16])
+{
+	unsigned char tmp[1024], h[20];
+
+	if (len > sizeof(tmp))
+		len = sizeof(tmp);
+	cpy(tmp, f, len);
+	zero(tmp + OFF_MIC, 16);
+	hmac_sha1(kck, 16, tmp, len, h);
+	cpy(mic, h, 16);
+}
+
+static int check_mic(struct wpa_sm *sm, const unsigned char *f,
+		     unsigned int len)
+{
+	unsigned char mic[16];
+
+	calc_mic(WPA_KCK(sm), f, len, mic);
+	return cmp(mic, f + OFF_MIC, 16) == 0;
+}
+
+/* Build a reply EAPOL-Key frame; key data optional. */
+static unsigned int build(struct wpa_sm *sm, const unsigned char *rx,
+			  unsigned int info, const unsigned char *nonce,
+			  const unsigned char *data, unsigned int dlen,
+			  unsigned char *out)
+{
+	unsigned int body = 95 + dlen, len = 4 + body;
+
+	zero(out, len);
+	out[0] = rx[0] ? rx[0] : 1;        /* mirror the AP's EAPOL version */
+	out[1] = 3;
+	out[2] = body >> 8;
+	out[3] = body;
+	out[4] = 2;                        /* RSN key descriptor */
+	out[OFF_INFO] = info >> 8;
+	out[OFF_INFO + 1] = info;
+	cpy(out + OFF_REPLAY, rx + OFF_REPLAY, 8);
+	if (nonce)
+		cpy(out + OFF_NONCE, nonce, 32);
+	out[OFF_DLEN] = dlen >> 8;
+	out[OFF_DLEN + 1] = dlen;
+	if (dlen)
+		cpy(out + OFF_DATA, data, dlen);
+	calc_mic(WPA_KCK(sm), out, len, out + OFF_MIC);
+	return len;
+}
+
+/* Walk the decrypted key data for the GTK KDE (and the RSN IE in msg 3). */
+static int parse_kde(struct wpa_sm *sm, const unsigned char *d,
+		     unsigned int n, int want_ie)
+{
+	unsigned int o = 0;
+	int gtk = 0, ie_ok = !want_ie || !sm->ap_ie_len;
+
+	while (o + 2 <= n) {
+		unsigned int id = d[o], l = d[o + 1];
+
+		if (id == 0xdd && l == 0)
+			break;                         /* padding */
+		if (o + 2 + l > n)
+			break;
+		if (id == 48 && want_ie && sm->ap_ie_len) {
+			/* Downgrade check: same RSN IE as the beacon. */
+			ie_ok = l + 2 == sm->ap_ie_len &&
+				cmp(d + o, sm->ap_ie, l + 2) == 0;
+		} else if (id == 0xdd && l >= 6 + 16 && d[o + 2] == 0x00 &&
+			   d[o + 3] == 0x0f && d[o + 4] == 0xac &&
+			   d[o + 5] == 1) {
+			unsigned int glen = l - 6;
+
+			if (glen > sizeof(sm->gtk))
+				return -1;
+			sm->gtk_idx = d[o + 6] & 3;
+			cpy(sm->gtk, d + o + 8, glen);
+			sm->gtk_len = glen;
+			gtk = 1;
+		}
+		o += 2 + l;
+	}
+	if (!ie_ok) {
+		sm->error = "RSN IE mismatch (downgrade?)";
+		return -1;
+	}
+	if (!gtk) {
+		sm->error = "no GTK in key data";
+		return -1;
+	}
+	return 0;
+}
+
+static int decrypt_data(struct wpa_sm *sm, const unsigned char *f,
+			unsigned int dlen, unsigned char *out)
+{
+	if (dlen < 24 || dlen % 8 || dlen > 512 ||
+	    aes_unwrap(WPA_KEK(sm), f + OFF_DATA, dlen, out) < 0) {
+		sm->error = "key data unwrap failed";
+		return -1;
+	}
+	return (int)dlen - 8;
+}
+
+int wpa_rx(struct wpa_sm *sm, const unsigned char *f, unsigned int len,
+	   unsigned char *reply, unsigned int *rlen,
+	   void (*rng)(unsigned char *out, unsigned int n))
+{
+	unsigned int info, dlen, flen;
+	unsigned char plain[512];
+	int n;
+
+	*rlen = 0;
+	if (len < OFF_DATA || f[1] != 3 || f[4] != 2)
+		return WPA_NONE;
+	flen = 4 + be16(f + 2);
+	if (flen > len)
+		return WPA_NONE;
+	len = flen;
+	info = be16(f + OFF_INFO);
+	dlen = be16(f + OFF_DLEN);
+	if ((info & KI_VER_MSK) != 2 || OFF_DATA + dlen > len) {
+		sm->error = "unsupported key descriptor";
+		return WPA_ERR;
+	}
+	if (!(info & KI_ACK))
+		return WPA_NONE;
+	if (sm->have_replay && cmp(f + OFF_REPLAY, sm->replay, 8) <= 0 &&
+	    (info & KI_MIC)) {
+		sm->error = "replayed EAPOL-Key";
+		return WPA_ERR;
+	}
+
+	if ((info & KI_PAIRWISE) && !(info & KI_MIC)) {
+		/* Message 1: ANonce.  New SNonce, derive the PTK, answer with
+		 * message 2 carrying our RSN IE. */
+		cpy(sm->anonce, f + OFF_NONCE, 32);
+		if (!sm->have_snonce) {
+			rng(sm->snonce, 32);
+			sm->have_snonce = 1;
+		}
+		derive_ptk(sm);
+		*rlen = build(sm, f, 2 | KI_PAIRWISE | KI_MIC, sm->snonce,
+			      sm->ie, sm->ie_len, reply);
+		return WPA_REPLY;
+	}
+
+	if (!check_mic(sm, f, len)) {
+		sm->error = "EAPOL-Key MIC mismatch (wrong passphrase?)";
+		return WPA_ERR;
+	}
+
+	if (info & KI_PAIRWISE) {
+		/* Message 3: same ANonce, install, encrypted GTK. */
+		if (!(info & KI_INSTALL) || !(info & KI_ENC_DATA) ||
+		    cmp(f + OFF_NONCE, sm->anonce, 32) != 0) {
+			sm->error = "unexpected message 3";
+			return WPA_ERR;
+		}
+		n = decrypt_data(sm, f, dlen, plain);
+		if (n < 0 || parse_kde(sm, plain, (unsigned int)n, 1) < 0)
+			return WPA_ERR;
+		cpy(sm->gtk_rsc, f + OFF_RSC, 8);
+		cpy(sm->replay, f + OFF_REPLAY, 8);
+		sm->have_replay = 1;
+		sm->ptk_ok = 1;
+		*rlen = build(sm, f, 2 | KI_PAIRWISE | KI_MIC | KI_SECURE, 0,
+			      0, 0, reply);
+		return WPA_PTK;
+	}
+
+	/* Group key message 1 (rekey). */
+	if (!sm->ptk_ok || !(info & KI_ENC_DATA)) {
+		sm->error = "unexpected group key message";
+		return WPA_ERR;
+	}
+	n = decrypt_data(sm, f, dlen, plain);
+	if (n < 0 || parse_kde(sm, plain, (unsigned int)n, 0) < 0)
+		return WPA_ERR;
+	cpy(sm->gtk_rsc, f + OFF_RSC, 8);
+	cpy(sm->replay, f + OFF_REPLAY, 8);
+	sm->have_replay = 1;
+	*rlen = build(sm, f, 2 | KI_MIC | KI_SECURE, 0, 0, 0, reply);
+	return WPA_GTK;
+}

+ 54 - 0
wpa.h

@@ -0,0 +1,54 @@
+/* Minimal WPA2-PSK supplicant (IEEE 802.11i 4-way and group handshakes,
+ * key descriptor version 2: HMAC-SHA1-128 MIC + AES key wrap, CCMP only).
+ * Pure C, no OS calls: the ring-3 `wifi` command moves the EAPOL frames
+ * (SYS_WIFI_EAPOL_RX/TX) and installs the keys.  Host test: make test-wpa. */
+#ifndef WPA_H
+#define WPA_H
+
+#define WPA_NONE   0   /* frame ignored */
+#define WPA_REPLY  1   /* send `reply` */
+#define WPA_PTK    2   /* send `reply`, then install TK + GTK, authorize */
+#define WPA_GTK    3   /* send `reply`, then install the new GTK */
+#define WPA_ERR   -1   /* bad MIC / replay / malformed */
+
+struct wpa_sm {
+	unsigned char pmk[32];
+	unsigned char aa[6], spa[6];          /* AP and our MAC */
+	unsigned char anonce[32], snonce[32];
+	unsigned char ptk[48];                /* KCK | KEK | TK */
+	unsigned char replay[8];
+	int have_replay, have_snonce, ptk_ok;
+	unsigned char ie[64];                 /* our RSN IE (assoc request) */
+	unsigned int ie_len;
+	unsigned char ap_ie[64];              /* AP's RSN IE (beacon) */
+	unsigned int ap_ie_len;
+	unsigned char gtk[32];
+	unsigned int gtk_len;
+	int gtk_idx;
+	unsigned char gtk_rsc[8];
+	const char *error;
+};
+
+/* PMK = PBKDF2-HMAC-SHA1(passphrase, ssid, 4096, 32). */
+void wpa_pmk(const char *pass, const unsigned char *ssid, unsigned int ssid_len,
+	     unsigned char pmk[32]);
+
+/* Our RSN IE: version 1, CCMP group, CCMP pairwise, PSK AKM, caps 0. */
+unsigned int wpa_rsn_ie(unsigned char out[22]);
+
+void wpa_init(struct wpa_sm *sm, const unsigned char pmk[32],
+	      const unsigned char aa[6], const unsigned char spa[6],
+	      const unsigned char *ie, unsigned int ie_len,
+	      const unsigned char *ap_ie, unsigned int ap_ie_len);
+
+/* Process one EAPOL frame (starting at the EAPOL header).  `reply` must
+ * hold 256 bytes.  `rng` fills the SNonce. */
+int wpa_rx(struct wpa_sm *sm, const unsigned char *f, unsigned int len,
+	   unsigned char *reply, unsigned int *rlen,
+	   void (*rng)(unsigned char *out, unsigned int n));
+
+#define WPA_TK(sm)  ((sm)->ptk + 32)
+#define WPA_KCK(sm) ((sm)->ptk)
+#define WPA_KEK(sm) ((sm)->ptk + 16)
+
+#endif

+ 383 - 0
wpa_crypto.c

@@ -0,0 +1,383 @@
+/* WPA2-PSK crypto: see wpa_crypto.h.  Small and byte-oriented on purpose;
+ * the hot path (PBKDF2, 8192 SHA-1 blocks) still takes well under a
+ * second on the Braswell. */
+
+#include "wpa_crypto.h"
+
+static void cpy(unsigned char *d, const unsigned char *s, unsigned int n)
+{
+	while (n--)
+		*d++ = *s++;
+}
+
+/* ---- SHA-1 -------------------------------------------------------------- */
+struct sha1_ctx {
+	unsigned int h[5];
+	unsigned char buf[64];
+	unsigned int used;
+	unsigned long long total;
+};
+
+static unsigned int rol(unsigned int x, int n)
+{
+	return (x << n) | (x >> (32 - n));
+}
+
+static void sha1_block(unsigned int h[5], const unsigned char *p)
+{
+	unsigned int w[80], a, b, c, d, e, t, i;
+
+	for (i = 0; i < 16; i++)
+		w[i] = ((unsigned int)p[4 * i] << 24) | (p[4 * i + 1] << 16) |
+		       (p[4 * i + 2] << 8) | p[4 * i + 3];
+	for (; i < 80; i++)
+		w[i] = rol(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
+	a = h[0]; b = h[1]; c = h[2]; d = h[3]; e = h[4];
+	for (i = 0; i < 80; i++) {
+		unsigned int f, k;
+
+		if (i < 20) {
+			f = (b & c) | (~b & d);
+			k = 0x5a827999u;
+		} else if (i < 40) {
+			f = b ^ c ^ d;
+			k = 0x6ed9eba1u;
+		} else if (i < 60) {
+			f = (b & c) | (b & d) | (c & d);
+			k = 0x8f1bbcdcu;
+		} else {
+			f = b ^ c ^ d;
+			k = 0xca62c1d6u;
+		}
+		t = rol(a, 5) + f + e + k + w[i];
+		e = d; d = c; c = rol(b, 30); b = a; a = t;
+	}
+	h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e;
+}
+
+static void sha1_init(struct sha1_ctx *c)
+{
+	c->h[0] = 0x67452301u;
+	c->h[1] = 0xefcdab89u;
+	c->h[2] = 0x98badcfeu;
+	c->h[3] = 0x10325476u;
+	c->h[4] = 0xc3d2e1f0u;
+	c->used = 0;
+	c->total = 0;
+}
+
+static void sha1_update(struct sha1_ctx *c, const unsigned char *d,
+			unsigned int n)
+{
+	c->total += n;
+	while (n) {
+		unsigned int take = 64 - c->used;
+
+		if (take > n)
+			take = n;
+		cpy(c->buf + c->used, d, take);
+		c->used += take;
+		d += take;
+		n -= take;
+		if (c->used == 64) {
+			sha1_block(c->h, c->buf);
+			c->used = 0;
+		}
+	}
+}
+
+static void sha1_final(struct sha1_ctx *c, unsigned char out[20])
+{
+	unsigned long long bits = c->total * 8;
+	unsigned char pad = 0x80, z = 0, len[8];
+	unsigned int i;
+
+	sha1_update(c, &pad, 1);
+	while (c->used != 56)
+		sha1_update(c, &z, 1);
+	for (i = 0; i < 8; i++)
+		len[i] = (unsigned char)(bits >> (56 - 8 * i));
+	sha1_update(c, len, 8);
+	for (i = 0; i < 5; i++) {
+		out[4 * i] = c->h[i] >> 24;
+		out[4 * i + 1] = c->h[i] >> 16;
+		out[4 * i + 2] = c->h[i] >> 8;
+		out[4 * i + 3] = c->h[i];
+	}
+}
+
+void sha1(const unsigned char *d, unsigned int n, unsigned char out[20])
+{
+	struct sha1_ctx c;
+
+	sha1_init(&c);
+	sha1_update(&c, d, n);
+	sha1_final(&c, out);
+}
+
+void hmac_sha1_2(const unsigned char *key, unsigned int klen,
+		 const unsigned char *d1, unsigned int n1,
+		 const unsigned char *d2, unsigned int n2,
+		 unsigned char out[20])
+{
+	unsigned char k[64], pad[64], inner[20];
+	struct sha1_ctx c;
+	unsigned int i;
+
+	for (i = 0; i < 64; i++)
+		k[i] = 0;
+	if (klen > 64)
+		sha1(key, klen, k);
+	else
+		cpy(k, key, klen);
+	for (i = 0; i < 64; i++)
+		pad[i] = k[i] ^ 0x36;
+	sha1_init(&c);
+	sha1_update(&c, pad, 64);
+	sha1_update(&c, d1, n1);
+	if (n2)
+		sha1_update(&c, d2, n2);
+	sha1_final(&c, inner);
+	for (i = 0; i < 64; i++)
+		pad[i] = k[i] ^ 0x5c;
+	sha1_init(&c);
+	sha1_update(&c, pad, 64);
+	sha1_update(&c, inner, 20);
+	sha1_final(&c, out);
+}
+
+void hmac_sha1(const unsigned char *key, unsigned int klen,
+	       const unsigned char *d, unsigned int n, unsigned char out[20])
+{
+	hmac_sha1_2(key, klen, d, n, 0, 0, out);
+}
+
+void pbkdf2_sha1(const unsigned char *pass, unsigned int plen,
+		 const unsigned char *salt, unsigned int slen,
+		 unsigned int iterations, unsigned char *out, unsigned int olen)
+{
+	unsigned int blk = 1;
+
+	while (olen) {
+		unsigned char cnt[4], u[20], t[20];
+		unsigned int i, j, take = olen < 20 ? olen : 20;
+
+		cnt[0] = blk >> 24; cnt[1] = blk >> 16; cnt[2] = blk >> 8;
+		cnt[3] = blk;
+		hmac_sha1_2(pass, plen, salt, slen, cnt, 4, u);
+		cpy(t, u, 20);
+		for (i = 1; i < iterations; i++) {
+			hmac_sha1(pass, plen, u, 20, u);
+			for (j = 0; j < 20; j++)
+				t[j] ^= u[j];
+		}
+		cpy(out, t, take);
+		out += take;
+		olen -= take;
+		blk++;
+	}
+}
+
+void wpa_prf(const unsigned char *key, unsigned int klen, const char *label,
+	     const unsigned char *b, unsigned int blen,
+	     unsigned char *out, unsigned int olen)
+{
+	unsigned char msg[128 + 100], h[20];
+	unsigned int llen = 0, i, n;
+
+	while (label[llen])
+		llen++;
+	if (llen + 1 + blen + 1 > sizeof(msg))
+		return;
+	cpy(msg, (const unsigned char *)label, llen);
+	msg[llen] = 0;
+	cpy(msg + llen + 1, b, blen);
+	n = llen + 1 + blen;
+	for (i = 0; olen; i++) {
+		unsigned int take = olen < 20 ? olen : 20;
+
+		msg[n] = (unsigned char)i;
+		hmac_sha1(key, klen, msg, n + 1, h);
+		cpy(out, h, take);
+		out += take;
+		olen -= take;
+	}
+}
+
+/* ---- AES-128 ----------------------------------------------------------- */
+static const unsigned char sbox[256] = {
+	0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
+	0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
+	0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
+	0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
+	0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
+	0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
+	0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
+	0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
+	0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
+	0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
+	0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
+	0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
+	0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
+	0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
+	0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
+	0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16,
+};
+
+static unsigned char inv_sbox(unsigned char v)
+{
+	unsigned int i;
+
+	for (i = 0; i < 256; i++)
+		if (sbox[i] == v)
+			return (unsigned char)i;
+	return 0;
+}
+
+static unsigned char xt(unsigned char x)
+{
+	return (unsigned char)((x << 1) ^ ((x & 0x80) ? 0x1b : 0));
+}
+
+static unsigned char gmul(unsigned char a, unsigned char b)
+{
+	unsigned char r = 0;
+
+	while (b) {
+		if (b & 1)
+			r ^= a;
+		a = xt(a);
+		b >>= 1;
+	}
+	return r;
+}
+
+void aes128_setkey(unsigned int rk_words[44], const unsigned char key[16])
+{
+	unsigned char *rk = (unsigned char *)rk_words;
+	unsigned char rcon = 1;
+	unsigned int i;
+
+	cpy(rk, key, 16);
+	for (i = 16; i < 176; i += 4) {
+		unsigned char t[4];
+
+		cpy(t, rk + i - 4, 4);
+		if (i % 16 == 0) {
+			unsigned char u = t[0];
+
+			t[0] = sbox[t[1]] ^ rcon;
+			t[1] = sbox[t[2]];
+			t[2] = sbox[t[3]];
+			t[3] = sbox[u];
+			rcon = xt(rcon);
+		}
+		rk[i] = rk[i - 16] ^ t[0];
+		rk[i + 1] = rk[i - 15] ^ t[1];
+		rk[i + 2] = rk[i - 14] ^ t[2];
+		rk[i + 3] = rk[i - 13] ^ t[3];
+	}
+}
+
+static void add_round_key(unsigned char s[16], const unsigned char *rk)
+{
+	unsigned int i;
+
+	for (i = 0; i < 16; i++)
+		s[i] ^= rk[i];
+}
+
+void aes128_encrypt(const unsigned int rk_words[44], const unsigned char in[16],
+		    unsigned char out[16])
+{
+	const unsigned char *rk = (const unsigned char *)rk_words;
+	unsigned char s[16], t[16];
+	unsigned int r, i, c;
+
+	cpy(s, in, 16);
+	add_round_key(s, rk);
+	for (r = 1; r <= 10; r++) {
+		for (i = 0; i < 16; i++)                 /* sub + shift rows */
+			t[i] = sbox[s[(i + 4 * (i % 4)) % 16]];
+		if (r < 10) {
+			for (c = 0; c < 4; c++) {        /* mix columns */
+				unsigned char *col = t + 4 * c;
+				unsigned char a0 = col[0], a1 = col[1];
+				unsigned char a2 = col[2], a3 = col[3];
+
+				col[0] = xt(a0) ^ (xt(a1) ^ a1) ^ a2 ^ a3;
+				col[1] = a0 ^ xt(a1) ^ (xt(a2) ^ a2) ^ a3;
+				col[2] = a0 ^ a1 ^ xt(a2) ^ (xt(a3) ^ a3);
+				col[3] = (xt(a0) ^ a0) ^ a1 ^ a2 ^ xt(a3);
+			}
+		}
+		cpy(s, t, 16);
+		add_round_key(s, rk + 16 * r);
+	}
+	cpy(out, s, 16);
+}
+
+void aes128_decrypt(const unsigned int rk_words[44], const unsigned char in[16],
+		    unsigned char out[16])
+{
+	const unsigned char *rk = (const unsigned char *)rk_words;
+	unsigned char s[16], t[16];
+	unsigned int r, i, c;
+
+	cpy(s, in, 16);
+	add_round_key(s, rk + 160);
+	for (r = 9;; r--) {
+		for (i = 0; i < 16; i++)                 /* inv shift + inv sub */
+			t[(i + 4 * (i % 4)) % 16] = inv_sbox(s[i]);
+		add_round_key(t, rk + 16 * r);
+		if (r == 0) {
+			cpy(s, t, 16);
+			break;
+		}
+		for (c = 0; c < 4; c++) {                /* inv mix columns */
+			unsigned char *col = t + 4 * c;
+			unsigned char a0 = col[0], a1 = col[1];
+			unsigned char a2 = col[2], a3 = col[3];
+
+			col[0] = gmul(a0, 14) ^ gmul(a1, 11) ^ gmul(a2, 13) ^ gmul(a3, 9);
+			col[1] = gmul(a0, 9) ^ gmul(a1, 14) ^ gmul(a2, 11) ^ gmul(a3, 13);
+			col[2] = gmul(a0, 13) ^ gmul(a1, 9) ^ gmul(a2, 14) ^ gmul(a3, 11);
+			col[3] = gmul(a0, 11) ^ gmul(a1, 13) ^ gmul(a2, 9) ^ gmul(a3, 14);
+		}
+		cpy(s, t, 16);
+	}
+	cpy(out, s, 16);
+}
+
+int aes_unwrap(const unsigned char kek[16], const unsigned char *in,
+	       unsigned int n, unsigned char *out)
+{
+	unsigned int rk[44], blocks, i, j, k;
+	unsigned char a[8], b[16];
+
+	if (n < 24 || n % 8)
+		return -1;
+	blocks = n / 8 - 1;
+	aes128_setkey(rk, kek);
+	cpy(a, in, 8);
+	cpy(out, in + 8, n - 8);
+	for (j = 6; j-- > 0;) {
+		for (i = blocks; i >= 1; i--) {
+			unsigned int t = blocks * j + i;
+
+			cpy(b, a, 8);
+			b[7] ^= t;
+			b[6] ^= t >> 8;
+			b[5] ^= t >> 16;
+			b[4] ^= t >> 24;
+			cpy(b + 8, out + 8 * (i - 1), 8);
+			aes128_decrypt(rk, b, b);
+			cpy(a, b, 8);
+			cpy(out + 8 * (i - 1), b + 8, 8);
+		}
+	}
+	for (k = 0; k < 8; k++)
+		if (a[k] != 0xa6)
+			return -1;
+	return 0;
+}

+ 36 - 0
wpa_crypto.h

@@ -0,0 +1,36 @@
+/* WPA2-PSK crypto for the ring-3 supplicant (wpa.c): SHA-1, HMAC-SHA1,
+ * PBKDF2-HMAC-SHA1 (PMK), the 802.11i PRF (PTK), AES-128 and the RFC 3394
+ * key unwrap (GTK).  Pure freestanding C with host vectors (make test-wpa).
+ * CCMP itself runs in the WiFi firmware. */
+#ifndef WPA_CRYPTO_H
+#define WPA_CRYPTO_H
+
+#define SHA1_LEN 20
+
+void sha1(const unsigned char *d, unsigned int n, unsigned char out[20]);
+void hmac_sha1(const unsigned char *key, unsigned int klen,
+	       const unsigned char *d, unsigned int n, unsigned char out[20]);
+/* Two-part message (PRF and the EAPOL MIC use it to avoid a copy). */
+void hmac_sha1_2(const unsigned char *key, unsigned int klen,
+		 const unsigned char *d1, unsigned int n1,
+		 const unsigned char *d2, unsigned int n2,
+		 unsigned char out[20]);
+void pbkdf2_sha1(const unsigned char *pass, unsigned int plen,
+		 const unsigned char *salt, unsigned int slen,
+		 unsigned int iterations, unsigned char *out, unsigned int olen);
+/* PRF-n (IEEE 802.11-2016 12.7.1.2): HMAC-SHA1(K, A || 0 || B || i). */
+void wpa_prf(const unsigned char *key, unsigned int klen, const char *label,
+	     const unsigned char *b, unsigned int blen,
+	     unsigned char *out, unsigned int olen);
+
+void aes128_setkey(unsigned int rk[44], const unsigned char key[16]);
+void aes128_encrypt(const unsigned int rk[44], const unsigned char in[16],
+		    unsigned char out[16]);
+void aes128_decrypt(const unsigned int rk[44], const unsigned char in[16],
+		    unsigned char out[16]);
+/* RFC 3394 unwrap: `n` = wrapped length (multiple of 8, >= 24); writes
+ * n - 8 bytes.  0 on success, -1 when the integrity check fails. */
+int aes_unwrap(const unsigned char kek[16], const unsigned char *in,
+	       unsigned int n, unsigned char *out);
+
+#endif

+ 248 - 0
wpa_test.c

@@ -0,0 +1,248 @@
+/* Host tests for wpa_crypto.c and wpa.c (make test-wpa).
+ *
+ * Known-answer vectors: SHA-1 ("abc"), RFC 6070 PBKDF2, the IEEE 802.11
+ * PSK example (passphrase "password", SSID "IEEE"), the 802.11 PRF test
+ * vector, FIPS-197 AES-128 and RFC 3394 4.1.  Then a simulated
+ * authenticator runs a full 4-way handshake, a group rekey, a replay and a
+ * wrong-passphrase case through wpa_rx(). */
+
+#include <stdio.h>
+#include <string.h>
+#include "wpa.h"
+#include "wpa_crypto.h"
+
+static int fails;
+
+static void hex2bin(const char *h, unsigned char *out)
+{
+	while (h[0] && h[1]) {
+		unsigned int v;
+
+		sscanf(h, "%2x", &v);
+		*out++ = (unsigned char)v;
+		h += 2;
+	}
+}
+
+static void expect(const char *name, const unsigned char *got,
+		   const char *hex)
+{
+	unsigned char want[128];
+	unsigned int n = (unsigned int)strlen(hex) / 2;
+
+	hex2bin(hex, want);
+	if (memcmp(got, want, n) != 0) {
+		unsigned int i;
+
+		printf("FAIL %s\n  got  ", name);
+		for (i = 0; i < n; i++)
+			printf("%02x", got[i]);
+		printf("\n  want %s\n", hex);
+		fails++;
+	} else {
+		printf("ok   %s\n", name);
+	}
+}
+
+static void check(const char *name, int cond)
+{
+	printf("%s %s\n", cond ? "ok  " : "FAIL", name);
+	if (!cond)
+		fails++;
+}
+
+/* RFC 3394 wrap (authenticator side, test only). */
+static void aes_wrap(const unsigned char kek[16], const unsigned char *in,
+		     unsigned int n, unsigned char *out)
+{
+	unsigned int rk[44], blocks = n / 8, i, j;
+	unsigned char a[8], b[16];
+
+	aes128_setkey(rk, kek);
+	memset(a, 0xa6, 8);
+	memcpy(out + 8, in, n);
+	for (j = 0; j < 6; j++)
+		for (i = 1; i <= blocks; i++) {
+			unsigned int t = blocks * j + i;
+
+			memcpy(b, a, 8);
+			memcpy(b + 8, out + 8 * i, 8);
+			aes128_encrypt(rk, b, b);
+			memcpy(a, b, 8);
+			a[7] ^= t; a[6] ^= t >> 8; a[5] ^= t >> 16; a[4] ^= t >> 24;
+			memcpy(out + 8 * i, b + 8, 8);
+		}
+	memcpy(out, a, 8);
+}
+
+static void fixed_rng(unsigned char *out, unsigned int n)
+{
+	unsigned int i;
+
+	for (i = 0; i < n; i++)
+		out[i] = (unsigned char)(0x50 + i);
+}
+
+/* Authenticator-side EAPOL-Key builder. */
+static unsigned int ap_frame(unsigned char *f, unsigned int info,
+			     unsigned long long replay,
+			     const unsigned char *nonce, const unsigned char *rsc,
+			     const unsigned char *data, unsigned int dlen,
+			     const unsigned char *kck)
+{
+	unsigned int body = 95 + dlen, i;
+	unsigned char h[20];
+
+	memset(f, 0, 4 + body);
+	f[0] = 2; f[1] = 3; f[2] = body >> 8; f[3] = body;
+	f[4] = 2;
+	f[5] = info >> 8; f[6] = info;
+	f[8] = 16;
+	for (i = 0; i < 8; i++)
+		f[9 + i] = (unsigned char)(replay >> (56 - 8 * i));
+	if (nonce)
+		memcpy(f + 17, nonce, 32);
+	if (rsc)
+		memcpy(f + 65, rsc, 8);
+	f[97] = dlen >> 8; f[98] = dlen;
+	memcpy(f + 99, data, dlen);
+	if (kck) {
+		hmac_sha1(kck, 16, f, 4 + body, h);
+		memcpy(f + 81, h, 16);
+	}
+	return 4 + body;
+}
+
+int main(void)
+{
+	unsigned char out[128], key[16], pt[16], ct[24];
+	unsigned int rk[44], i;
+
+	/* ---- crypto known answers ---- */
+	sha1((const unsigned char *)"abc", 3, out);
+	expect("sha1(abc)", out, "a9993e364706816aba3e25717850c26c9cd0d89d");
+	pbkdf2_sha1((const unsigned char *)"password", 8,
+		    (const unsigned char *)"salt", 4, 4096, out, 20);
+	expect("pbkdf2 rfc6070 c=4096", out,
+	       "4b007901b765489abead49d926f721d065a429c1");
+	wpa_pmk("password", (const unsigned char *)"IEEE", 4, out);
+	expect("802.11 PSK->PMK", out,
+	       "f42c6fc52df0ebef9ebb4b90b38a5f902e83fe1b135a70e23aed762e9710a12e");
+	memset(key, 0x0b, 16);
+	{
+		unsigned char k20[20];
+
+		memset(k20, 0x0b, 20);
+		wpa_prf(k20, 20, "prefix", (const unsigned char *)"Hi There",
+			8, out, 64);
+	}
+	expect("802.11 PRF-512", out,
+	       "bcd4c650b30b9684951829e0d75f9d54b862175ed9f00606e17d8da35402ffee"
+	       "75df78c3d31e0f889f012120c0862beb67753e7439ae242edb8373698356cf5a");
+	for (i = 0; i < 16; i++)
+		key[i] = (unsigned char)i;
+	hex2bin("00112233445566778899aabbccddeeff", pt);
+	aes128_setkey(rk, key);
+	aes128_encrypt(rk, pt, out);
+	expect("aes128 fips-197", out, "69c4e0d86a7b0430d8cdb78070b4c55a");
+	aes128_decrypt(rk, out, out + 16);
+	expect("aes128 decrypt", out + 16, "00112233445566778899aabbccddeeff");
+	hex2bin("1fa68b0a8112b447aef34bd8fb5a7b829d3e862371d2cfe5", ct);
+	check("rfc3394 unwrap", aes_unwrap(key, ct, 24, out) == 0);
+	expect("rfc3394 plaintext", out, "00112233445566778899aabbccddeeff");
+	ct[3] ^= 1;
+	check("rfc3394 integrity", aes_unwrap(key, ct, 24, out) < 0);
+
+	/* ---- 4-way handshake against a simulated authenticator ---- */
+	{
+		struct wpa_sm sm;
+		unsigned char pmk[32], aa[6] = { 2, 0, 0, 0, 0, 1 };
+		unsigned char spa[6] = { 2, 0, 0, 0, 0, 2 }, anonce[32];
+		unsigned char ie[22], f[512], reply[256], kd[64], wrapped[72];
+		unsigned char gtk[16], rsc[8] = { 5, 0, 0, 0, 0, 0, 0, 0 };
+		unsigned int ielen = wpa_rsn_ie(ie), rlen, n, kdlen;
+		unsigned char h[20];
+		int r;
+
+		for (i = 0; i < 32; i++) {
+			pmk[i] = (unsigned char)i;
+			anonce[i] = (unsigned char)(0x10 + i);
+		}
+		for (i = 0; i < 16; i++)
+			gtk[i] = (unsigned char)(0xa0 + i);
+		wpa_init(&sm, pmk, aa, spa, ie, ielen, ie, ielen);
+
+		n = ap_frame(f, 0x008a, 1, anonce, 0, 0, 0, 0);
+		r = wpa_rx(&sm, f, n, reply, &rlen, fixed_rng);
+		check("msg1 -> reply", r == WPA_REPLY && rlen == 4 + 95 + ielen);
+		expect("PTK", sm.ptk,
+		       "f16138820d8dd0e1a17427b8ac7e4d27032f9e3f1f168fa6"
+		       "099a77850f77449c1a60803e872c30bf3bb0e01c597418ec");
+		check("msg2 key info 0x010a", reply[5] == 0x01 && reply[6] == 0x0a);
+		check("msg2 carries our RSN IE",
+		      memcmp(reply + 99, ie, ielen) == 0);
+		memcpy(out, reply + 81, 16);
+		memset(reply + 81, 0, 16);
+		hmac_sha1(WPA_KCK(&sm), 16, reply, rlen, h);
+		check("msg2 MIC", memcmp(out, h, 16) == 0);
+
+		/* msg 3: RSN IE + GTK KDE, padded and wrapped with the KEK. */
+		memcpy(kd, ie, ielen);
+		kdlen = ielen;
+		kd[kdlen++] = 0xdd; kd[kdlen++] = 22;
+		kd[kdlen++] = 0x00; kd[kdlen++] = 0x0f; kd[kdlen++] = 0xac;
+		kd[kdlen++] = 1; kd[kdlen++] = 1; kd[kdlen++] = 0;
+		memcpy(kd + kdlen, gtk, 16);
+		kdlen += 16;
+		kd[kdlen++] = 0xdd;                  /* padding: dd 00 ... */
+		while (kdlen % 8)
+			kd[kdlen++] = 0;
+		aes_wrap(WPA_KEK(&sm), kd, kdlen, wrapped);
+		n = ap_frame(f, 0x13ca, 2, anonce, rsc, wrapped, kdlen + 8,
+			     WPA_KCK(&sm));
+		r = wpa_rx(&sm, f, n, reply, &rlen, fixed_rng);
+		check("msg3 -> install", r == WPA_PTK);
+		check("GTK index 1", sm.gtk_idx == 1 && sm.gtk_len == 16 &&
+		      memcmp(sm.gtk, gtk, 16) == 0);
+		check("GTK RSC", sm.gtk_rsc[0] == 5);
+		check("msg4 key info 0x030a", reply[5] == 0x03 && reply[6] == 0x0a);
+		r = wpa_rx(&sm, f, n, reply, &rlen, fixed_rng);
+		check("replayed msg3 rejected", r == WPA_ERR);
+
+		/* group rekey: new GTK, key id 2 */
+		kdlen = 0;
+		kd[kdlen++] = 0xdd; kd[kdlen++] = 22;
+		kd[kdlen++] = 0x00; kd[kdlen++] = 0x0f; kd[kdlen++] = 0xac;
+		kd[kdlen++] = 1; kd[kdlen++] = 2; kd[kdlen++] = 0;
+		for (i = 0; i < 16; i++)
+			kd[kdlen++] = (unsigned char)(0xc0 + i);
+		kd[kdlen++] = 0xdd;
+		while (kdlen % 8)
+			kd[kdlen++] = 0;
+		aes_wrap(WPA_KEK(&sm), kd, kdlen, wrapped);
+		n = ap_frame(f, 0x1382, 3, 0, rsc, wrapped, kdlen + 8,
+			     WPA_KCK(&sm));
+		r = wpa_rx(&sm, f, n, reply, &rlen, fixed_rng);
+		check("group msg1 -> new GTK", r == WPA_GTK && sm.gtk_idx == 2 &&
+		      sm.gtk[0] == 0xc0);
+		check("group msg2 key info 0x0302",
+		      reply[5] == 0x03 && reply[6] == 0x02);
+
+		/* wrong passphrase: msg3 MIC computed with another KCK */
+		wpa_init(&sm, pmk, aa, spa, ie, ielen, ie, ielen);
+		n = ap_frame(f, 0x008a, 1, anonce, 0, 0, 0, 0);
+		wpa_rx(&sm, f, n, reply, &rlen, fixed_rng);
+		{
+			unsigned char bad[16];
+
+			memset(bad, 0x77, 16);
+			n = ap_frame(f, 0x13ca, 2, anonce, rsc, wrapped,
+				     kdlen + 8, bad);
+		}
+		check("bad MIC rejected", wpa_rx(&sm, f, n, reply, &rlen,
+						 fixed_rng) == WPA_ERR);
+	}
+
+	printf(fails ? "\n%d FAILED\n" : "\nall wpa tests passed\n", fails);
+	return fails ? 1 : 0;
+}

Некоторые файлы не были показаны из-за большого количества измененных файлов