diff --git a/FEATURES.md b/FEATURES.md index 1b8d9dfa9..4a9fe88a2 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -765,7 +765,6 @@ mistaken for GUI settings. | `IRIS_CHD_DIFF_DIR` | Redirect CHD diff sidecars; GUI App Store sets a writable container directory. | [src/chd_disk.rs](src/chd_disk.rs) | | `IRIS_CRASH_DIAG` | off disables Windows crash handler installation. | [src/crash_diag.rs](src/crash_diag.rs) | | `IRIS_CRASH_SELFTEST` | Standalone crash diagnostic self-test selector; deliberately crashes. | [src/main.rs](src/main.rs) | -| `IRIS_DISPLAY_VERIFY` | 1 checks the boards' "nothing changed" verdicts: a frame IMPACT or VPro would have left standing is composed anyway and compared with the one on screen; a difference is reported on stderr, with a count every 600 checks. For development; it composes every frame. | [src/display/verify.rs](src/display/verify.rs) | | `IRIS_ENTRY_PREAMBLE` | 0 turns off jitv2's interrupt check at an externally dispatched entry word (on by default; `j2 entrypre`). | [src/cpu/jitv2/mod.rs](src/cpu/jitv2/mod.rs) | | `IRIS_GPRCACHE` | Guest registers a JIT v2 function with a loop keeps in host registers, 0 to 31 (`j2 gprcache`; default 6, 10 on AArch64). | [src/cpu/jitv2/codegen.rs](src/cpu/jitv2/codegen.rs) | | `IRIS_GPRCACHE_EVERYWHERE` | Presence caches registers in functions without a loop too. For test runs: slower to compile, no faster to run. | [src/cpu/jitv2/codegen.rs](src/cpu/jitv2/codegen.rs) | diff --git a/HACKING.md b/HACKING.md index 7bef065ad..e8c96748f 100644 --- a/HACKING.md +++ b/HACKING.md @@ -104,7 +104,7 @@ section of [STORAGE.md](STORAGE.md) and the `block_node.rs` module docs: read them before writing a backend or changing a flush. `src/scsi_monitor.rs` implements the monitor's `scsi` and `cow` subcommands and the run-time disc changes once, over the bus a controller hands out through `ScsiTargets::scsi_bus`; chip-specific subcommands (`regs`; the -WD's `wdt`, `defer`) stay with the chip, and `DiscChanger` is +WD's `defer`) stay with the chip, and `DiscChanger` is implemented once for every `ScsiTargets`. Configuration is shared the same way: `scsi::attach_from_config` walks the SCSI `[[devices]]` entries for every machine, each at a slot in the slot list (`scsi0/t1`), and @@ -743,7 +743,7 @@ Rules for a board: double-buffered program costs one compose per swap, not one per retrace. A draw path that cannot name its planes or box must say "anything" (`Marks::mark_all`, or the board's plain written flag): a missing mark is - a stale picture. `IRIS_DISPLAY_VERIFY=1` checks the verdicts: frames a + a stale picture. `display verify on` checks the verdicts: frames a board would have left are composed anyway and compared. - The board does not present, write screenshots or count idle frames. The thread shows an unchanged frame again ten times a second for the status diff --git a/clanker/INDEX.md b/clanker/INDEX.md index 52f828630..fef7ca371 100644 --- a/clanker/INDEX.md +++ b/clanker/INDEX.md @@ -125,7 +125,7 @@ Non-graphics devices: MC/MEMCFG and RAM banks, HPC3, VDMA, EEPROMs and NVRAM, PS | [ip35-boot-window-memory-is-the-zero-holders.md](devices/ip35-boot-window-memory-is-the-zero-holders.md) | rule | Two-node IP35: memory behind the boot window at node field zero is the zero holder's for every node; keeping it on the reader gave node 1 its own RAM for 4 MiB of node 0 and corrupted IRIX (found by bisecting FC, JIT, graphics, second CPU, then diffing a piped disk region) | | [hub-second-processor-slice-runs-zeros.md](devices/hub-second-processor-slice-runs-zeros.md) | resolved | IP27: two slices on a Hub node shared their PROM cache-line stack and lost the PROM's pair liveness poll and flag-word handshake under host load (fixed: per-processor cached views, a PI hold bounded by the partner's retired cycles) | | [ip35-rendezvous-hold-must-stop-the-cpu-at-once.md](devices/ip35-rendezvous-hold-must-stop-the-cpu-at-once.md) | rule | A held CPU must retire nothing more; running out its batch let a Tezro PROM's PI1 pass a barrier alone and start the copied PROM early (measured on a fork's rendezvous) | -| [draw-marks-tell-the-display-what-shows.md](devices/draw-marks-tell-the-display-what-shows.md) | rule | IMPACT and VPro compose only when drawing landed in a buffer the screen shows: a draw marks its store, planes and box after its stores (`display::Marks`); a path that cannot must say "anything"; `IRIS_DISPLAY_VERIFY=1` checks the verdicts; measurements | +| [draw-marks-tell-the-display-what-shows.md](devices/draw-marks-tell-the-display-what-shows.md) | rule | IMPACT and VPro compose only when drawing landed in a buffer the screen shows: a draw marks its store, planes and box after its stores (`display::Marks`); a path that cannot must say "anything"; `display verify on` checks the verdicts; measurements | | [which-interrupt-is-the-irix-clock-tick.md](devices/which-interrupt-is-the-irix-clock-tick.md) | rule | IRIX's clock tick per machine: the 8254 timers 0+1 on Indy/Indigo2 (100 Hz + 1 kHz fast clock), CP0 Compare everywhere else (100 Hz; Octane mixes in fast clock and timeouts); how the programmed Compare rate is recovered when Count is zeroed each tick | | [pci-layer-design.md](devices/pci-layer-design.md) | design | The PCI layer: headers change only through the bus, byte orders are per-window values, `pci/` imports no card or SCSI; the stale-run and delivery-order hazards, the SeqCst handshake, and what the first attempt got wrong | | [onyx2-mediaio-rad1-is-not-the-octanes.md](devices/onyx2-mediaio-rad1-is-not-the-octanes.md) | rule | The Onyx2's MediaIO RAD1 (`Rad1::mediaio()`): revision 0x70 (7.0; 0xc0 panicked the kernel), 0x88/0x8c are not a mute (every other second was silent), its counter runs from reset | @@ -279,7 +279,7 @@ GR2 (XZ/Extreme): HQ2 HLE, GL state, FIN handshakes, the RE3 span JIT. Hardware | [DESIGN.md](gr2/DESIGN.md) | design | GR2 design | | [video-timing-from-vc1-tables.md](gr2/video-timing-from-vc1-tables.md) | rule | GR2 refresh rate: the VC1 frame and line-state table formats (units of five clocks), two known clocks; PROM-checked only. Also the O2's totals and dot clock | | [real-xz-comparison.md](gr2/real-xz-comparison.md) | open | Real Indy XZ vs emulated, same suites: fixed colour floor(v*256), quad fan, 4 GE; open EXP2 fog, local spot, X XYBitmap / 4-bit TrueColor / overlay XReadDisplay; glx-window-life kills Xsgi (piglit X restart hook); running on a real machine | -| [vdma-timeout-and-tracing.md](gr2/vdma-timeout-and-tracing.md) | rule | IRIX's VDMA wait is 500 000 DELAY(1) polls (a few hundred ms host); full GR2 tracing slows GEDMA DMA past it (VDMA TIMEOUT, board reset, kernel fault); measure untraced with `mc vdma on`; GIO32 path translates per page | +| [vdma-timeout-and-tracing.md](gr2/vdma-timeout-and-tracing.md) | rule | IRIX's VDMA wait is 500 000 DELAY(1) polls (a few hundred ms host); full GR2 tracing slows GEDMA DMA past it (VDMA TIMEOUT, board reset, kernel fault); measure untraced with `log mc on`; GIO32 path translates per page | | [bringup.md](gr2/bringup.md) | howto | GR2 bring-up: emulator-side gotchas | | [cx-save-must-wait-for-hq.md](gr2/cx-save-must-wait-for-hq.md) | rule | Context save: GEDMA reads must wait for the queued 0x1E1 | | [8-bit-blits-cost-the-sync-not-the-path.md](gr2/8-bit-blits-cost-the-sync-not-the-path.md) | measure | XZ 8-bit frames: XShm and glDrawPixels are the same GEDMA; per-frame sync is the cost; never use glPixelZoom | diff --git a/clanker/cpu/cpu-model-is-runtime-not-compile-time.md b/clanker/cpu/cpu-model-is-runtime-not-compile-time.md index d9440162e..1f9f0daa3 100644 --- a/clanker/cpu/cpu-model-is-runtime-not-compile-time.md +++ b/clanker/cpu/cpu-model-is-runtime-not-compile-time.md @@ -35,5 +35,5 @@ adds a stderr sink and turns on the named trace points. Devlog output requires a CLI's `env_logger` backend. Use the monitor instead (`Monitor listening on 127.0.0.1:8888`): `log scsi on`, -`scsi regs`, `scsi wdt`. `scsi regs` in particular is how the WD33C93A constants +`scsi regs`. `scsi regs` in particular is how the WD33C93A constants in `cpu-tests/harness/scsilog.c` were derived from the PROM's own driver. diff --git a/clanker/devices/draw-marks-tell-the-display-what-shows.md b/clanker/devices/draw-marks-tell-the-display-what-shows.md index f7161ca18..19d16882e 100644 --- a/clanker/devices/draw-marks-tell-the-display-what-shows.md +++ b/clanker/devices/draw-marks-tell-the-display-what-shows.md @@ -31,7 +31,7 @@ composed 550 to 600 frames of 606 to show 114 to 148 swaps. ## Checking it -`IRIS_DISPLAY_VERIFY=1` composes every frame a board would have left and +`display verify on` composes every frame a board would have left and compares (`src/display/verify.rs`). "missed" is a change with no mark for two frames running; "late" is one the next frame's verdict reported, which is a draw caught between its stores and its mark. diff --git a/clanker/gr2/vdma-timeout-and-tracing.md b/clanker/gr2/vdma-timeout-and-tracing.md index 0a8b082de..3448ed067 100644 --- a/clanker/gr2/vdma-timeout-and-tracing.md +++ b/clanker/gr2/vdma-timeout-and-tracing.md @@ -19,7 +19,7 @@ clear; our MC does not abort on that write, so the kernel waits for the transfer to finish before it reports. **Rule.** Treat a VDMA timeout seen only under tracing as a tracing -artefact first; reproduce untraced with `mc vdma on`, whose `VDMA end` lines +artefact first; reproduce untraced with `log mc on`, whose `VDMA end` lines give each transfer's host time. Keep the GIO32 path fast: it translates the memory side once per page (a per-byte walk took the DMA lock the CPU polls and read a PTE four times a word, ~0.75 us a word; now ~0.15 us). diff --git a/clanker/perf/window-presents-only-what-changed.md b/clanker/perf/window-presents-only-what-changed.md index baccb4383..ee48b2e0b 100644 --- a/clanker/perf/window-presents-only-what-changed.md +++ b/clanker/perf/window-presents-only-what-changed.md @@ -28,7 +28,7 @@ This is safe because every board that answers `Composed::Unchanged` leaves the screen's framebuffer alone: IMPACT's `Taken::None`, VPro's `reader::Composed::No`, the O2's `render_direct` with nothing written. A board that changes the picture and still answers `Unchanged` would show a -stale window; `IRIS_DISPLAY_VERIFY=1` is what catches that. +stale window; `display verify on` is what catches that. ## 2. The mip chain diff --git a/clanker/skills/irix-kernel-debug/SKILL.md b/clanker/skills/irix-kernel-debug/SKILL.md index bc00643c2..80424d531 100644 --- a/clanker/skills/irix-kernel-debug/SKILL.md +++ b/clanker/skills/irix-kernel-debug/SKILL.md @@ -56,7 +56,7 @@ Read `debug.md` for the commands; this skill is the workflow. Use the - Everything the kernel printed is kept in its console ring: `putbuf` reads it at any time, including after a hang. - The IRIS side has its own traces: `log scsi on` (`log scsi1` for the - second controller), `scsi wdt`, `pdma dump on`, `log net on` (most need `developer`). Run them at + second controller), `pdma dump on`, `log net on` (most need `developer`). Run them at the same time as the guest-side breakpoints so the two timelines can be matched. @@ -114,7 +114,7 @@ on each stage in order, continue, and check the state named: | Stage | Break on | Check | |---|---|---| | controller setup | `wd93_earlyinit`, `wd93edtinit` | reached at all; the controller's registers in `scsi regs` match what the driver just wrote | -| INQUIRY | `wd93_inq` | the command reaches the emulated target (`scsi wdt`), and the driver records success; after `finish`, the result | +| INQUIRY | `wd93_inq` | the command reaches the emulated target (`log scsi on`), and the driver records success; after `finish`, the result | | command completion | `wd93intr` | interrupts arrive and the driver reads the status the target sent | | device registration | `scsi_device_update`, `scsi_dev_add` | called for the target; this is what creates its hardware graph entries | | open | `dkscopen` | the disk open finds the inquiry data recorded earlier | diff --git a/debug.md b/debug.md index 896f849a0..f4ef68f1d 100644 --- a/debug.md +++ b/debug.md @@ -86,7 +86,7 @@ it forever. **[DEV]** below marks commands that need a `developer` build. Most are accepted in every build but do nothing without the feature; `si`, the CPU's -`trace start|stop|status`, `block`, `draw` and `jitcheck` (which also needs +`trace start|stop|status`, `draw` and `jitcheck` (which also needs `jitv2`) are not registered at all without it and answer "Unknown command". ## Command reference @@ -294,7 +294,6 @@ accesses with suspicion. |---|---| | `tlb dump` | All TLB entries (48 on R4400/R5000, 64 on R10000) | | `tlb trans [asid]` | Translate through the TLB, optionally with another ASID | -| `tlb debug ` | Log TLB operations **[DEV]** | | `l1i ` | L1 instruction cache | | `l1d ` | L1 data cache. For `check`, an address from `0x80000000` up is virtual, except one above 4 GB in the machine's memory, which is physical. `l1i` and `l2` read addresses the same way | | `l1d wb ` / `l1d pwb ` | Write cached L1D data back to RAM (virtual / physical range) | @@ -364,7 +363,6 @@ interpreter), `--features jitv2_smc_check` (writes onto executing pages), and | `scsi next ` | Move a disc to position 1 (next on eject) | | `scsi defer ` | Deferred SCSI status interrupts | | `scsi dayna` | DaynaPort MAC, addresses and counters (any controller) | -| `scsi wdt [N]` / `scsi wdt file ` | WD33C93A transaction ring: last `N` / all to a file **[DEV]** | | `scsi0 ...` / `scsi1 ...` | The same, for controller 0 / controller 1 (Indigo2 and O2) | | `scsi2 ...` / `cow2 ...` | The same, for the Fibre Channel adapter's loop (its disks are by loop ID); `scsi2 notes` lists what the driver did that the model does not decode | | `cow status` / `cow commit [id]` / `cow reset [id]` | Copy-on-write overlays (`cow1 ...` on a second controller) | @@ -373,12 +371,12 @@ interpreter), `--features jitv2_smc_check` (writes onto executing pages), and On the O2 the controllers are Adaptec 7880s: `scsi regs` shows that chip's interrupt status, queues and command totals, whether its worker thread is running (commands run on it, off the CPU's thread), any completions held -for a paused sequencer and NetBSD's doorbell, and `wdt` and `defer` +for a paused sequencer and NetBSD's doorbell, and `defer` are not there. Ids are per controller, as in the slots of the `[[devices]]` entries (`scsi1/t1` is id 1 on controller 1, so `scsi1 eject 1`). On the Octane the controllers are ISP1040s: `scsi notes` (`scsi1 notes`) -shows the command total and anything odd the driver did; `regs`, `wdt` +shows the command total and anything odd the driver did; `regs` and `defer` are not there. It also has `heart status` (interrupt bits, mask, counter, bank descriptors), `heart unsupported` (HEART registers touched but not modelled) and `ip30 memcfg|bridge|gfx|xbow|unmapped` @@ -391,7 +389,7 @@ On the Fuel the one controller is a two-channel ISP12160: `scsi` (or `scsi0`) and `cow` act on channel 0, `scsi1` and `cow1` on channel 1, and ids run 0 to 15 on each (`scsi1/t1` is id 1 on channel 1). `scsi notes` shows the whole chip's command total and anything odd the driver did, and -has no `scsi1` form; `regs`, `wdt` and `defer` are not there. The +has no `scsi1` form; `regs` and `defer` are not there. The Tezro's ISP12160 answers the same way. Queue position `[0]` is the mounted disc, `[1]` the next on eject. A disc @@ -427,7 +425,8 @@ in the `irix-gfx-loop` skill (`clanker/skills/irix-gfx-loop/SKILL.md`). | `rex SLOT ...`, `vc2 SLOT ...`, `xmap SLOT ...` and so on | With a second Newport head (a `newport` entry at `gio0`) each head answers the commands above after its slot: `rex gio0 status`, `vc2 gio0 status`. A bare command means the first head | | `disp status` / `disp debug ` | Display timing and framebuffer state | | `disp compositor ` | Switch between the GL and software compositor | -| `block debug ` | Block/span draw logging to `block.log` **[DEV]** | +| `display verify ` | IMPACT and VPro boards: compose the frames a board would have left standing and compare them with the one on screen; a difference is a change the board did not see, reported on stderr with a count every 600 checks. Slows the display | +| `log rex3 on` | In a developer build, each draw's mode, coordinates and colours, and the HOSTRW words that feed it **[DEV]** | | `draw debug ` | Draw a debug overlay on the framebuffer **[DEV]** | Build with `--features rex-dirty-upload` to make Newport framebuffer snapshot @@ -576,7 +575,6 @@ devices are [listed below](#sgi-o2-ip32). | `mc regs` | Memory Controller registers, including MEMCFG; CTRLD also lists its write count and last 16 values written | | `mc dma` | VDMA (graphics DMA) state | | `mc dma xlate [vaddr] [w]` | Walk the VDMA address translation for `vaddr` (default MEMADR) without side effects; `w` = the transfer writes memory | -| `mc vdma ` | VDMA trace to `vdma.log` | | `eeprom \|w >` | CPU/MC boot-configuration EEPROM (93C56; cache size etc.) | | `nveeprom \|w \|save [file]>` | Indigo2 NVRAM EEPROM (93CS56: PROM environment and MAC) | | `hpc3 status` | HPC3 state | @@ -638,7 +636,7 @@ in every build. |---|---| | `log status` | Each module's state | | `log ` | Enable / disable | -| `log file ` | Send a module's log to a file | +| `log file ` | Send those modules' log to a file instead of the monitor; one file at a time, shared by every module sent to it (`log all file off` closes it). The file is written out on `log status`, on stop, exit and panic, and when it closes; a killed process loses what was still buffered | `` is comma-separated globs over `module.event`, where a bare module is all its events, `all` is everything and a leading `-` removes: `heart`, @@ -655,10 +653,16 @@ alone is the module). The WD33C93A controllers and their DMA channels are per sl `odyssey`, `nvme` and the ISP1040 `scsi`, are selected whole whichever slot names them. A slot with nothing of its own takes its parent's, and one with nothing traceable is an error. +Messages a guest can trigger over and over that a user should always see (an +unmodelled register polled, a refused store, a bus error) are notices, not +trace points: they print on stderr in every build, the first four times per place +and register, then at each power of two with a count. + +`log mips.tlb on` prints each TLBR, TLBWI, TLBWR and TLBP **[DEV]**. `log mips.insn on` prints every instruction `run` and `step` execute (`log mips file ` writes them to a file instead) **[DEV]**. A device's trace is its module: `log ps2 on`, `log scsi on`, `log rtc on`. -`log net` traces packets, `log ioc` the 8254 timer, and `log phys` accesses +`log net` traces packets, `log ioc` the 8254 timer and the IOC3's unimplemented registers, and `log phys` accesses that reach the black hole or a bus-error region and, in a developer build, every physical bus access. The `hit` category of `l1i` and `l1d` also needs a developer build. @@ -678,10 +682,13 @@ configuration cycle on a PCI bus (MACE's, the Octane Bridge's) and whether a function answered it. `bridge` logs the Octane Bridge's register and translation-table accesses by name, and any transfer a PCI function started that reached no memory, and each interrupt pin's edges -and the HEART vector it sets or clears. `heart` logs HEART's register +and the HEART vector it sets or clears, and the interrupt packets and DMA it drops or +refuses. `heart` logs HEART's register accesses, one counter read in 256 with the host's clock, and every interrupt vector raised or lowered, and on the Octane every access nothing -answers. `o2audio` logs the O2's audio register accesses and codec writes. +answers. `o2audio` logs the O2's audio register accesses and codec writes. `mc` logs each VDMA +transfer (mode, block shape, the µTLB, each chunk, the host time it took) in every build, +and in a developer build the rest of the memory controller. Events: `pdma` — one per HPC3 channel, `hal0`..`hal7`, `scsi0`, `scsi1`, `enet0`, `enet1`; `mips` — `insn tlb mem fpu`; `l1i`/`l1d`/`l2c` — `hit miss op`; `nvme` — `state admin regs io` ([docs/nvme.md](docs/nvme.md#tracing)). @@ -717,7 +724,7 @@ its SCSI controllers answer to `scsi`/`cow` and `scsi1`/`cow1` as described unde | Command | Description | |---|---| -| `crime status` / `crime regs` / `crime irqlog [on\|off\|n]` / `crime touched` | CRIME interrupts, mask and memory banks / registers / the last *n* interrupt-register accesses (recorded only after `crime irqlog on`, which clears the old log; never in a `lightning` build) / registers the guest used (not kept in a `lightning` build) | +| `crime status` / `crime regs` / `crime touched` | CRIME interrupts, mask and memory banks / registers / registers the guest used (not kept in a `lightning` build). `crime trace FILE irq` records the interrupt-register accesses (needs `gputrace`, on with `developer`) | | `re status` / `re notes` | CRIME rendering engine state / notes on unusual commands | | `re trace [re,cpu,gbe,crime,irq\|all]` / `re trace off\|flush` | Annotated trace (`gputrace` builds). One trace shared by the O2's graphics blocks, also as `gbe trace` and `crime trace`: interface buffer entries with each primitive decoded (`re`), RE register reads (`cpu`), GBE accesses, shadow latches and timing interrupts (`gbe`), CRIME registers (`crime`). `irq` adds CRIME's interrupt registers, which `all` leaves out because IRIX writes the mask on every spl change | | `re rec ` / `re rec off` | Record the engine's writes, after every register as it stands, in the form the offline replay reads (`gputrace` builds). Memory the CPU wrote is not in it | @@ -744,7 +751,7 @@ its SCSI controllers answer to `scsi`/`cow` and `scsi1`/`cow1` as described unde | `o2 peek ADDR LEN PATH` | Physical memory to a file (up to 1 MB) | | `o2 scsi PATH` | The SCSI controllers' recent commands | | `o2 unmapped` | Bus accesses that reached no device (the first 64 distinct), with the PC that made each (not kept in a `lightning` build) | -| `o2 ps2log PATH` / `o2 crimelog PATH` | PS/2 traffic / CRIME interrupt-register accesses recorded since `crime irqlog on` | +| `o2 ps2log PATH` | PS/2 traffic | ## Recipes diff --git a/docs/graphics/newport.md b/docs/graphics/newport.md index 414ab2310..2c2586f07 100644 --- a/docs/graphics/newport.md +++ b/docs/graphics/newport.md @@ -221,7 +221,7 @@ The `rex` family: - `rex rec `, `rex rec mark|off` `rex trace` and `rex rec` need a build with the `gputrace` feature, which `developer` -turns on. A `developer` build also has `block debug` and `draw debug`. +turns on. A `developer` build also has `draw debug`, and `log rex3` logs each draw (what `block debug` wrote to `block.log`). The device commands: `vc2 status|ramdump`, `xmap status|dump`, `cmap status|dump`, `bt445 status|identity`, `disp status|debug|compositor`. diff --git a/docs/graphics/o2.md b/docs/graphics/o2.md index b268d46b1..f936bf92b 100644 --- a/docs/graphics/o2.md +++ b/docs/graphics/o2.md @@ -190,7 +190,7 @@ monitor's `o2 status` and `o2 pixel` call `render_screen` on demand. - `gbe status`, `gbe trace [re,cpu,gbe,crime,irq|all]`, `gbe trace off|flush` - `re status`, `re notes`, `re dither [on|off]`, `re trace [re,cpu,gbe,crime,irq|all]`, `re trace off|flush`, `re rec |off` -- `crime status`, `crime regs`, `crime irqlog [on|off|n]`, `crime touched`, +- `crime status`, `crime regs`, `crime touched`, `crime trace [...]`, `crime trace off|flush` The `o2` commands (`ip32_machine.rs`) are on the monitor. The graphics ones are diff --git a/iris-checks/tests/hot_paths.rs b/iris-checks/tests/hot_paths.rs index e0ca750d3..7e068d6f2 100644 --- a/iris-checks/tests/hot_paths.rs +++ b/iris-checks/tests/hot_paths.rs @@ -20,8 +20,8 @@ use std::sync::OnceLock; // the first two double as the control: if none shows a formatting call, the // disassembly cannot show them and a clean result means nothing. const CONTROL: &str = r"MipsExecutor.*::(report_[a-z_]*error|handle_exception)"; -const COLD: &str = r"::(report_[a-z_]*error|fault_note|post_refused_store|idle_profile_report|backtrace_from|jitv2_monitor_pfn|handle_exception|debug_|monitor_)"; -const FMT_CALL: &str = r"<(std::io::stdio::_e?print|.*::write_fmt|core::fmt::|alloc::fmt::format|<[ui](8|16|32|64|size)>::_fmt)"; +const COLD: &str = r"::(report_[a-z_]*error|fault_note|post_refused_store|idle_profile_report|backtrace_from|jitv2_monitor_pfn|handle_exception|breakpoint_hit_reason|debug_|monitor_)"; +const FMT_CALL: &str = r"<(std::io::stdio::_e?print|.*::write_fmt|core::fmt::|alloc::fmt::format|<[ui](8|16|32|64|size)>::_fmt|iris::devlog::notice_say)"; // A hit-path fetch must inline, so it has no symbol of its own. const OUT_OF_LINE_FETCH: &str = r"(CpuCache|ShadowCache|DecodeCache).*>::fetch$"; // #[inline(never)] in the source, so they exist whatever the inliner decides. @@ -70,6 +70,15 @@ fn load() -> Binary { funcs.sort_by_key(|f| f.0); funcs.dedup_by_key(|f| f.0); + // A call through a slot the loader fills (`call *slot(%rip)`) names its target in the slot's relocation. + let slots: std::collections::HashMap = elf + .dynamic_relocations() + .into_iter() + .flatten() + .filter(|(_, r)| matches!(r.flags(), object::RelocationFlags::Elf { r_type: object::elf::R_X86_64_RELATIVE })) + .map(|(at, r)| (at, r.addend() as u64)) + .collect(); + let mut calls = Vec::new(); for (addr, size, name, sec) in &funcs { if !name.contains("MipsExecutor") { @@ -79,12 +88,17 @@ fn load() -> Binary { let off = (addr - sec.address()) as usize; let code = &sec.data().unwrap()[off..off + *size as usize]; for ins in Decoder::with_ip(64, code, *addr, DecoderOptions::NONE) { - if !matches!(ins.mnemonic(), Mnemonic::Call | Mnemonic::Jmp) - || ins.op0_kind() != OpKind::NearBranch64 - { + if !matches!(ins.mnemonic(), Mnemonic::Call | Mnemonic::Jmp) { continue; } - let t = ins.near_branch_target(); + let t = match ins.op0_kind() { + OpKind::NearBranch64 => ins.near_branch_target(), + OpKind::Memory if ins.is_ip_rel_memory_operand() => match slots.get(&ins.ip_rel_memory_address()) { + Some(&t) => t, + None => continue, + }, + _ => continue, + }; let i = funcs.partition_point(|f| f.0 <= t); let Some(callee) = i.checked_sub(1).map(|i| &funcs[i]) else { continue }; let plus = if callee.0 == t { String::new() } else { format!("+{:#x}", t - callee.0) }; diff --git a/iris-gui/core/src/model/handle.rs b/iris-gui/core/src/model/handle.rs index eab90f748..f8f90638b 100644 --- a/iris-gui/core/src/model/handle.rs +++ b/iris-gui/core/src/model/handle.rs @@ -1129,6 +1129,7 @@ fn stop_machine_timed_keep(m: Box, abandoned: &Arc) let mut m = m; let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { m.stop(); + iris::devlog::DEVLOG.sync(); m })); // A stop given up on frees the library once it does finish (the @@ -1190,6 +1191,7 @@ fn stop_machine_timed(m: Box, abandoned: &Arc) -> R let mut m = m; let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { m.stop(); + iris::devlog::DEVLOG.sync(); drop(m); // Complete teardown before allowing a directory change. })); late_t.finished(); diff --git a/src/cpu/mips_exec.rs b/src/cpu/mips_exec.rs index 1ed1978f2..c9a8f7092 100644 --- a/src/cpu/mips_exec.rs +++ b/src/cpu/mips_exec.rs @@ -1339,8 +1339,6 @@ pub struct MipsExecutor { /// with `core.cur_code_pfn`, where this CPU reached `pcp`. #[cfg(feature = "jitv2")] pcp_uncached: bool, - /// Refused posted stores so far, so `post_refused_store` can log sparsely. - refused_stores: u64, /// `jitcheck`'s hardware-read fixup: `validate_jit_determinism`'s two /// passes run at genuinely different real wall-clock speed, so any /// device register whose value is driven by host time (e.g. the MC's @@ -2748,7 +2746,7 @@ impl MipsExecutor { #[allow(clippy::too_many_arguments)] fn report_bus_error(&self, op: BusErrorOp, size: usize, virt_addr: u64, phys_addr: u64, val: u64, mask: u64, status: u32) { match op { - BusErrorOp::Fetch => eprintln!("Bus error on instruction fetch: PC={:016x} PA={:08x} status={:08x}{}", virt_addr, phys_addr, status, self.fault_note(phys_addr, size)), + BusErrorOp::Fetch => crate::notice!(phys_addr >> 12, "Bus error on instruction fetch: PC={:016x} PA={:08x} status={:08x}{}", virt_addr, phys_addr, status, self.fault_note(phys_addr, size)), BusErrorOp::Read => { // jitcheck tag: which pass this read happened in, so a // divergence investigation can tell at a glance whether @@ -2766,10 +2764,10 @@ impl MipsExecutor { }; #[cfg(not(feature = "developer"))] let jitcheck_pass = ""; - eprintln!("Bus error on uncached read{}: PC={:016x} VA={:016x} PA={:016x} status={:08x}{}{}", size*8, self.core.pc, virt_addr, phys_addr, status, jitcheck_pass, self.fault_note(phys_addr, size)); + crate::notice!((self.core.pc, phys_addr >> 12), "Bus error on uncached read{}: PC={:016x} VA={:016x} PA={:016x} status={:08x}{}{}", size*8, self.core.pc, virt_addr, phys_addr, status, jitcheck_pass, self.fault_note(phys_addr, size)); } - BusErrorOp::Write => eprintln!("Bus error on uncached write{}: PC={:016x} VA={:016x} PA={:016x} val={:016x} status={:08x}{}", size*8, self.core.pc, virt_addr, phys_addr, val, status, self.fault_note(phys_addr, size)), - BusErrorOp::MaskedWrite => eprintln!("Bus error on uncached write64_masked: PC={:016x} VA={:016x} PA={:016x} val={:016x} mask={:016x} status={:08x}{}", self.core.pc, virt_addr, phys_addr, val, mask, status, self.fault_note(phys_addr, size)), + BusErrorOp::Write => crate::notice!((self.core.pc, phys_addr >> 12), "Bus error on uncached write{}: PC={:016x} VA={:016x} PA={:016x} val={:016x} status={:08x}{}", size*8, self.core.pc, virt_addr, phys_addr, val, status, self.fault_note(phys_addr, size)), + BusErrorOp::MaskedWrite => crate::notice!((self.core.pc, phys_addr >> 12), "Bus error on uncached write64_masked: PC={:016x} VA={:016x} PA={:016x} val={:016x} mask={:016x} status={:08x}{}", self.core.pc, virt_addr, phys_addr, val, mask, status, self.fault_note(phys_addr, size)), } } @@ -2788,12 +2786,8 @@ impl MipsExecutor { #[inline(never)] fn post_refused_store(&mut self, virt_addr: u64, phys_addr: u64, size: usize, val: u64, status: u32) { // The guest never learns a posted store failed, so a probe loop repeats it. - self.refused_stores += 1; - let n = self.refused_stores; - if n <= 4 || n.is_power_of_two() { - eprintln!("Unsupported uncached write{} (posted, completes, #{n}): PC={:016x} VA={:016x} PA={:016x} val={:016x} status={:08x}{}", - size * 8, self.core.pc, virt_addr, phys_addr, val, status, self.fault_note(phys_addr, size)); - } + crate::notice!((self.core.pc, phys_addr >> 12), "Unsupported uncached write{} (posted, completes): PC={:016x} VA={:016x} PA={:016x} val={:016x} status={:08x}{}", + size * 8, self.core.pc, virt_addr, phys_addr, val, status, self.fault_note(phys_addr, size)); } /// The bus the JIT reads code from and its compile pool is started on. @@ -3111,7 +3105,6 @@ impl MipsExecutor { jitv2_space: 0, #[cfg(feature = "jitv2")] pcp_uncached: false, - refused_stores: 0, #[cfg(feature = "developer")] hw_read_fixup_replay: None, #[cfg(feature = "developer")] diff --git a/src/cpu/mips_exec/monitor.rs b/src/cpu/mips_exec/monitor.rs index 8c197abc5..5348294d8 100644 --- a/src/cpu/mips_exec/monitor.rs +++ b/src/cpu/mips_exec/monitor.rs @@ -534,7 +534,7 @@ impl MipsCpu { ("bd".to_string(), "Alias for bp disable".to_string()), ("be".to_string(), "Alias for bp enable".to_string()), ("bb".to_string(), "Alias for bp delete".to_string()), - ("tlb".to_string(), "TLB commands: tlb dump | tlb trans [asid] | tlb debug [DEV]".to_string()), + ("tlb".to_string(), "TLB commands: tlb dump | tlb trans [asid]".to_string()), ("start".to_string(), "Start CPU execution thread".to_string()), ("stop".to_string(), "Stop CPU execution thread".to_string()), ("status".to_string(), "CPU running/stopped, PC, and why it last stopped (never blocks)".to_string()), @@ -1824,7 +1824,7 @@ impl MipsCpu { Err("ll stats requires --features llstats".to_string()) } "tlb" => { - if actual_args.is_empty() { return Err("Usage: tlb ...".to_string()); } + if actual_args.is_empty() { return Err("Usage: tlb ...".to_string()); } let exec = self.try_lock_executor()?; let tlb = &exec.tlb; diff --git a/src/crash_diag.rs b/src/crash_diag.rs index 9d638b82e..2886d0bef 100644 --- a/src/crash_diag.rs +++ b/src/crash_diag.rs @@ -128,6 +128,7 @@ fn install_panic_hook() { eprint!("{report}"); use std::io::Write; let _ = std::io::stderr().flush(); + crate::devlog::DEVLOG.try_sync(); IN_HOOK.store(false, Ordering::SeqCst); default_hook(info); diff --git a/src/dev/aic7880.rs b/src/dev/aic7880.rs index ae4d0144f..e7aaa8544 100644 --- a/src/dev/aic7880.rs +++ b/src/dev/aic7880.rs @@ -691,7 +691,7 @@ impl crate::scsi_monitor::ScsiTargets for Aic7880 { /// Controller 0 answers to `scsi`/`scsi0` and `cow`, controller 1 to `scsi1` /// and `cow1`. Only `scsi regs` is this chip's own; the rest is -/// `scsi_monitor`'s, so the WD33C93A's `wdt`, `defer` and `debug` are not here. +/// `scsi_monitor`'s, so the WD33C93A's `defer` and `debug` are not here. impl crate::traits::Device for Aic7880 { fn step(&self, _cycles: u64) {} diff --git a/src/dev/bridge.rs b/src/dev/bridge.rs index 1070cc4f7..036cd52f9 100644 --- a/src/dev/bridge.rs +++ b/src/dev/bridge.rs @@ -779,10 +779,10 @@ impl Bridge { match self.up.get(widget) { Some(h) if h.link_up() => { if !h.irq.packet(source, address, vector as u32, set) { - log::debug!("bridge: widget {widget} refused interrupt packet {address:#x} vector {vector}"); + crate::dlog!(LogModule::Bridge, "bridge: widget {widget} refused interrupt packet {address:#x} vector {vector}"); } } - _ => log::debug!("bridge: interrupt packet to widget {widget} dropped; no live link to a host"), + _ => crate::dlog!(LogModule::Bridge, "bridge: interrupt packet to widget {widget} dropped; no live link to a host"), } } ret @@ -967,7 +967,7 @@ impl Bridge { /// and released, not held until the link is re-established; what a core /// held in reset answers is not established. pub fn link_reset(&self) { - log::debug!("bridge: inbound link reset"); + crate::dlog!(LogModule::Bridge, "bridge: inbound link reset"); self.reset(); } @@ -1011,7 +1011,7 @@ impl Bridge { let host = st.r(reg::int_host(pin as u32)); if host == 0 && self.part == Part::Bridge { // An unprogrammed destination is an interrupt nobody routed. - log::debug!("bridge: interrupt pin {pin} changed with no destination programmed"); + crate::dlog!(LogModule::Bridge, "bridge: interrupt pin {pin} changed with no destination programmed"); return; } let dest = int_dest(st.r(reg::INT_DEST_UPPER), st.r(reg::INT_DEST_LOWER)); @@ -1025,8 +1025,8 @@ impl Bridge { crate::dlog!(LogModule::Bridge, "bridge: pin {pin} {} vector {vector} of widget {}", if set { "sets" } else { "clears" }, dest.widget); p.push(Packet { source: source(st), widget: dest.widget, address, vector, set }); } - Some(_) => log::debug!("bridge: interrupt packet to widget {} address {address:#x} vector {vector} is not one its host takes; dropped", dest.widget), - None => log::debug!("bridge: interrupt packet to widget {}, which is not a host; dropped", dest.widget), + Some(_) => crate::dlog!(LogModule::Bridge, "bridge: interrupt packet to widget {} address {address:#x} vector {vector} is not one its host takes; dropped", dest.widget), + None => crate::dlog!(LogModule::Bridge, "bridge: interrupt packet to widget {}, which is not a host; dropped", dest.widget), } } @@ -1039,7 +1039,7 @@ impl Bridge { Some(h) if h.host.accepts(dest.widget, dest.address, number) => { p.push(Packet { source: source(st), widget: dest.widget, address: dest.address, vector: number, set: true }) } - _ => log::debug!("bridge: error interrupt with no usable destination; dropped"), + _ => crate::dlog!(LogModule::Bridge, "bridge: error interrupt with no usable destination; dropped"), } } @@ -1086,7 +1086,7 @@ impl Bridge { /// faulting: a firmware self-test provokes one and fails on any /// synchronous exception. fn invalid_address(&self, st: &mut State, p: &mut Packets, off: u64, write: bool) { - log::debug!( + crate::dlog!(LogModule::Bridge, "bridge: {} of undefined register {off:#x}; flagging an invalid-address error", if write { "write" } else { "read" } ); @@ -1143,7 +1143,7 @@ impl Bridge { let base = off - SLOT_DATA; match info.access { Access::Ro | Access::Live => { - log::debug!("bridge: write of {val:#x} to read-only register {base:#x}"); + crate::dlog!(LogModule::Bridge, "bridge: write of {val:#x} to read-only register {base:#x}"); } Access::Wo => { if base == reg::INT_RESET { @@ -1205,7 +1205,7 @@ impl Bridge { }); // With the state lock dropped: the functions reset themselves. for pin in (0..4).filter(|pin| asserted >> pin & 1 != 0) { - log::warn!("bridge: Control drops reset pin {pin}: resetting PCI device {pin} (pin wiring is inferred)"); + crate::notice!(pin, "bridge: Control drops reset pin {pin}: resetting PCI device {pin} (pin wiring is inferred)"); self.bus.reset_device(pin); } ok @@ -1520,7 +1520,7 @@ impl Bridge { if addr >> 32 != 0 { let widget = ((addr >> 60) & 0xf) as u8; if widget == 0 { - log::debug!("bridge: 64-bit DMA names widget 0, which the crossbar cannot answer"); + crate::dlog!(LogModule::Bridge, "bridge: 64-bit DMA names widget 0, which the crossbar cannot answer"); return None; } return Some(Route::Host(addr & ((1 << 48) - 1), placement(addr & XBRIDGE_DMA64_SWAP != 0), widget)); @@ -1579,7 +1579,7 @@ impl Bridge { if addr >> 32 != 0 { let widget = ((addr >> 60) & 0xf) as u8; if widget == 0 { - log::debug!("bridge: 64-bit DMA names widget 0, which the crossbar cannot answer"); + crate::dlog!(LogModule::Bridge, "bridge: 64-bit DMA names widget 0, which the crossbar cannot answer"); return None; } return Some((addr & ((1 << 48) - 1), placement_for(DEV_SWAP_DIRECT), widget)); @@ -1587,7 +1587,7 @@ impl Bridge { let addr = addr as u32; // Local space never crosses the swapper. if addr < PCI_TRANSLATED { - log::debug!("bridge: DMA to PCI-local address {addr:#x} is not carried anywhere"); + crate::dlog!(LogModule::Bridge, "bridge: DMA to PCI-local address {addr:#x} is not carried anywhere"); return None; } let page_shift = if st.r(reg::CONTROL) & CONTROL_PAGE_16K != 0 { 14 } else { 12 }; @@ -1604,12 +1604,12 @@ impl Bridge { let index = ((addr - PCI_TRANSLATED) >> page_shift) as usize; if index >= ATE_ENTRIES { // External static RAM would supply the rest; this board has none. - log::debug!("bridge: DMA to {addr:#x} needs translation entry {index}, past the {ATE_ENTRIES} held"); + crate::dlog!(LogModule::Bridge, "bridge: DMA to {addr:#x} needs translation entry {index}, past the {ATE_ENTRIES} held"); return None; } let ate = st.ate[index]; if ate & ATE_VALID == 0 { - log::debug!("bridge: DMA to {addr:#x} uses translation entry {index}, which is not valid"); + crate::dlog!(LogModule::Bridge, "bridge: DMA to {addr:#x} uses translation entry {index}, which is not valid"); return None; } let widget = ((ate >> ATE_TARGET_WIDGET_SHIFT) & 0xf) as u8; @@ -1649,7 +1649,7 @@ impl Bridge { Some(Route::Host(xio, p, w)) => match self.up.get(w) { Some(h) if !h.link_up() => { // The Crossbow drops it; a dropped read is timed out. - log::debug!("bridge: transfer to widget {w}, whose link is down; dropped"); + crate::dlog!(LogModule::Bridge, "bridge: transfer to widget {w}, whose link is down; dropped"); dropped = true; false } @@ -1661,7 +1661,7 @@ impl Bridge { // Approximation: a transfer to a widget that is not a // host is dropped, not routed to a peer; no supported // guest is known to need peer DMA. - log::debug!("bridge: transfer to widget {w}, which is not a host; dropped"); + crate::dlog!(LogModule::Bridge, "bridge: transfer to widget {w}, which is not a host; dropped"); dropped = w == self.widget.load(Ordering::Acquire) || !(self.link_alive.read())(w); false } diff --git a/src/dev/crime.rs b/src/dev/crime.rs index 5cf5bf274..0fd810466 100644 --- a/src/dev/crime.rs +++ b/src/dev/crime.rs @@ -101,14 +101,6 @@ pub struct Crime { /// under this lock, so two threads cannot deliver it out of order. /// `regs` keeps no copy of INTSTAT, INTMASK or SOFTINT. int: Mutex, - /// The guest's last accesses to the interrupt registers (status, mask, - /// HARDINT, SOFTINT): `(write, offset, value)`, newest last, for the - /// `o2 crimelog` (chasing interrupt storms). - /// Off until the monitor's `crime irqlog on`, and not kept in a - /// `lightning` build: IRIX reads INTSTAT and writes INTMASK on every - /// interrupt and every spl change. - irqlog: Mutex>, - irqlog_on: AtomicBool, revision: std::sync::atomic::AtomicU64, /// The clock CRIME's free-running counter is derived from, so the PROM's /// delays take the time they ask for rather than a number of reads. @@ -141,8 +133,6 @@ impl Crime { trace: Mutex::new(Vec::new()), touched_bits: std::array::from_fn(|_| AtomicU64::new(0)), int: Mutex::new(IntState::default()), - irqlog: Mutex::new(std::collections::VecDeque::new()), - irqlog_on: AtomicBool::new(false), revision: std::sync::atomic::AtomicU64::new(CRIME_REV), ust, time_base: AtomicU64::new(0), @@ -244,40 +234,6 @@ impl Crime { self.trace.lock().unwrap().clone() } - #[inline] - fn log_irq(&self, write: bool, off: u32, val: u64) { - #[cfg(not(feature = "lightning"))] - if self.irqlog_on.load(Ordering::Relaxed) - && matches!(off, crime_reg::INTSTAT | crime_reg::INTMASK | crime_reg::HARDINT | crime_reg::SOFTINT) - { - let mut l = self.irqlog.lock().unwrap(); - if l.len() >= 8192 { - l.pop_front(); - } - l.push_back((write, off, val)); - } - #[cfg(feature = "lightning")] - let _ = (write, off, val); - } - - /// Start or stop recording interrupt-register accesses. Starting clears - /// what an earlier recording left. A `lightning` build records nothing. - pub fn set_irqlog(&self, on: bool) -> Result<(), String> { - if cfg!(feature = "lightning") { - return Err("crime: a lightning build does not record the interrupt log".into()); - } - if on { - self.irqlog.lock().unwrap().clear(); - } - self.irqlog_on.store(on, Ordering::Relaxed); - Ok(()) - } - - /// The interrupt-register log, one access per line, oldest first. - pub fn irqlog_text(&self) -> String { - self.irqlog.lock().unwrap().iter().map(|&(w, off, v)| format!("{} {:#04x} {:#018x}\n", if w { 'W' } else { 'R' }, off, v)).collect() - } - fn trace_category(off: u32) -> u32 { use crate::dev::o2gfx_trace::{TRACE_CRIME, TRACE_IRQ}; match off { @@ -288,7 +244,6 @@ impl Crime { pub(crate) fn load(&self, off: u32) -> u64 { let v = self.load_inner(off); - self.log_irq(false, off, v); if self.tr.on(Self::trace_category(off)) { self.tr.access(crate::dev::o2gfx_trace::Block::Crime, false, 64, off, v, off == crime_reg::TIME, false); } @@ -320,7 +275,6 @@ impl Crime { } fn store(&self, off: u32, val: u64) { - self.log_irq(true, off, val); if self.tr.on(Self::trace_category(off)) { self.tr.access(crate::dev::o2gfx_trace::Block::Crime, true, 64, off, val, false, false); } @@ -383,7 +337,7 @@ impl Device for Crime { fn is_running(&self) -> bool { true } fn register_commands(&self) -> Vec<(String, String)> { - vec![("crime".to_string(), "CRIME: crime status | crime regs | crime irqlog [on|off|n] | crime touched | crime trace [re,cpu,gbe,crime,irq|all] | crime trace off|flush".to_string())] + vec![("crime".to_string(), "CRIME: crime status | crime regs | crime touched | crime trace [re,cpu,gbe,crime,irq|all] | crime trace off|flush".to_string())] } fn execute_command(&self, cmd: &str, args: &[&str], mut w: Box) -> Result<(), String> { @@ -410,29 +364,13 @@ impl Device for Crime { } } } - "irqlog" if matches!(args.get(1).copied(), Some("on" | "off")) => { - let on = args[1] == "on"; - self.set_irqlog(on)?; - writeln!(w, " interrupt-register log {}", if on { "recording" } else { "stopped" }).ok(); - } - "irqlog" => { - if !self.irqlog_on.load(Ordering::Relaxed) { - writeln!(w, " (not recording; `crime irqlog on` starts)").ok(); - } - let n: usize = args.get(1).and_then(|v| v.parse().ok()).unwrap_or(32); - let log = self.irqlog_text(); - let lines: Vec<&str> = log.lines().collect(); - for l in &lines[lines.len().saturating_sub(n)..] { - writeln!(w, " {l}").ok(); - } - } "touched" => { for (off, write) in self.touched() { writeln!(w, " {off:#06x} {}", if write { "W" } else { "R" }).ok(); } } "trace" => return self.tr.command(&args[1..], &mut w), - _ => return Err("Usage: crime status | regs | irqlog [on|off|n] | touched | trace [re,cpu,gbe,crime,irq|all] | trace off|flush".to_string()), + _ => return Err("Usage: crime status | regs | touched | trace [re,cpu,gbe,crime,irq|all] | trace off|flush".to_string()), } Ok(()) } @@ -445,7 +383,6 @@ impl Resettable for Crime { self.regs.lock().unwrap().fill(0); self.change(|s| *s = IntState::default()); self.time_base.store(0, Ordering::Relaxed); - self.irqlog.lock().unwrap().clear(); } } diff --git a/src/dev/hpc3.rs b/src/dev/hpc3.rs index c7c0102ad..d8a5339fc 100644 --- a/src/dev/hpc3.rs +++ b/src/dev/hpc3.rs @@ -385,10 +385,6 @@ struct PdmaChannel { /// CPU reads of the CBP register: how often a driver polls the DMA /// position (a ring with no end-of-descriptor interrupts is refilled so). cbp_polls: u64, - /// The last CBP reads: (microseconds since the first, value, bytes the - /// device had read by then), for `pdma polls N`. - cbp_log: std::collections::VecDeque<(u64, u32, u64)>, - cbp_log_t0: Option, /// Device reads when the guest last read CBP, and when. reads_at_poll: u64, last_poll: Option, @@ -457,8 +453,6 @@ impl PdmaChannel { dev_reads: 0, dev_writes: 0, cbp_polls: 0, - cbp_log: std::collections::VecDeque::new(), - cbp_log_t0: None, reads_at_poll: 0, last_poll: None, width_16: false, @@ -946,10 +940,7 @@ impl PdmaChannelOps for PbusDmaOps { chan.cbp_polls += 1; chan.reads_at_poll = chan.dev_reads; chan.last_poll = Some(std::time::Instant::now()); - let t0 = *chan.cbp_log_t0.get_or_insert_with(std::time::Instant::now); - if chan.cbp_log.len() == 64 { chan.cbp_log.pop_front(); } - let entry = (t0.elapsed().as_micros() as u64, chan.cbp, chan.dev_reads * 4); - chan.cbp_log.push_back(entry); + if chan.log_active() { dlog_dev!(LogModule::Pdma, "PDMA[{}]: CBP read {:08x}, device has read {} bytes", chan.id, chan.cbp, chan.dev_reads * 4); } chan.cbp } HPC3_PDMA_NBDP => chan.nbdp, @@ -1624,15 +1615,6 @@ impl Device for Hpc3 { } return Ok(()); } - "polls" => { - let ch: usize = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(0); - let c = self.pdma_channels.get(ch).ok_or("pdma polls: no such channel")?.lock(); - writeln!(writer, "last CBP reads on channel {} (us, CBP, bytes read by the device):", ch).unwrap(); - for (t, v, b) in c.cbp_log.iter() { - writeln!(writer, " {:>12} {:08x} {}", t, v, b).unwrap(); - } - return Ok(()); - } "chain" => { let addr_str = args.get(1).ok_or_else(|| "Usage: pdma chain ".to_string())?; let mut addr = eval_const_expr(addr_str).map(|v| v as u32) diff --git a/src/dev/ioc3/mod.rs b/src/dev/ioc3/mod.rs index 0d736f2c1..38d391a57 100644 --- a/src/dev/ioc3/mod.rs +++ b/src/dev/ioc3/mod.rs @@ -265,12 +265,9 @@ const SSRAM_PARITY_ERROR: u32 = 0x0002_0000; /// MAC control bit 9: buffer RAM parity checking. const ENET_MCR_RAM_PARITY: u32 = 1 << 9; -/// Say once that a narrow access to a 32-bit block was refused. -fn narrow_once(a: u32, w: usize) { - static SAID: AtomicBool = AtomicBool::new(false); - if !SAID.swap(true, Ordering::Relaxed) { - log::warn!("ioc3: {w}-byte access at {a:#x} to a 32-bit register block refused (reads 0, writes dropped)"); - } +/// Say that a narrow access to a 32-bit block was refused. +fn narrow_refused(a: u32, w: usize) { + crate::notice!((), "ioc3: {w}-byte access at {a:#x} to a 32-bit register block refused (reads 0, writes dropped)"); } fn is_byte_wide(a: u32) -> bool { @@ -701,7 +698,7 @@ impl Shared { self.serial[p].as_ref().map_or(0, |s| s.read(off)) } _ => { - log::debug!("ioc3: read of unimplemented register {a:#x}"); + crate::dlog!(crate::devlog::LogModule::Ioc, "ioc3: read of unimplemented register {a:#x}"); 0 } } @@ -754,7 +751,7 @@ impl Shared { s.write(off, val); } } - _ => log::debug!("ioc3: write of {val:#x} to unimplemented register {a:#x}"), + _ => crate::dlog!(crate::devlog::LogModule::Ioc, "ioc3: write of {val:#x} to unimplemented register {a:#x}"), } } @@ -864,7 +861,7 @@ impl Shared { // refused, not widened to a lane. There is no bus error to return // from `bar_read`: it reads zero, and the write below is dropped. if w != 4 { - narrow_once(a, w); + narrow_refused(a, w); return 0; } if (reg::SSRAM..reg::SSRAM + reg::SSRAM_SIZE).contains(&a) { @@ -895,7 +892,7 @@ impl Shared { return; } if w != 4 || a & 3 != 0 { - narrow_once(a, w); + narrow_refused(a, w); return; } if (reg::SSRAM..reg::SSRAM + reg::SSRAM_SIZE).contains(&a) { diff --git a/src/dev/ioc3/parallel.rs b/src/dev/ioc3/parallel.rs index cb3c4aaa6..e5a0a2277 100644 --- a/src/dev/ioc3/parallel.rs +++ b/src/dev/ioc3/parallel.rs @@ -119,7 +119,7 @@ impl Parallel { continue; } if st.dma_control & PAR_DMA_FROM_PERIPHERAL != 0 { - log::debug!("ioc3: parallel context {i}: no peripheral to read from"); + crate::dlog!(crate::devlog::LogModule::Ioc, "ioc3: parallel context {i}: no peripheral to read from"); return; } let addr = ((st.addr_hi[i] as u64) << 32) | st.addr_lo[i] as u64; diff --git a/src/dev/mc.rs b/src/dev/mc.rs index 6df347b1d..977042864 100644 --- a/src/dev/mc.rs +++ b/src/dev/mc.rs @@ -103,10 +103,6 @@ pub struct MemoryController { memcfg_callback: Arc; 4]) + Send + Sync>>>, /// Channel to send async machine events (HardReset, PowerOff) to the machine thread. event_tx: Arc>, - /// Set when `mc vdma on` is active; gates the per-transfer logging in dma_worker. - vdma_debug: Arc, - /// Log file for VDMA transactions (set when vdma_debug is enabled). - vdma_log: Arc>>, /// Staging buffer for the batched VDMA paths (see `VDMA_CHUNK_QWORDS`). /// /// Allocated once and reused: the transfer path gathers into it and hands @@ -161,8 +157,6 @@ impl MemoryController { ram_sizes: Arc::new(ram_sizes), memcfg_callback: Arc::new(OnceLock::new()), event_tx: Arc::new(OnceLock::new()), - vdma_debug: Arc::new(AtomicBool::new(false)), - vdma_log: Arc::new(Mutex::new(None)), vdma_stage: Arc::new(Mutex::new( vec![0u64; crate::dev::mc_vdma::VDMA_CHUNK_QWORDS].into_boxed_slice())), } @@ -510,10 +504,6 @@ impl MemoryController { new_memcfg1, self.ram_sizes ); - eprintln!( - "MC: synthesized MEMCFG1 for extended RAM (banks {:?})", - self.ram_sizes - ); } changed } @@ -565,10 +555,6 @@ impl MemoryController { pub(crate) fn dma_running(&self) -> bool { self.running.load(Ordering::Relaxed) } - pub(crate) fn vdma_debug_enabled(&self) -> bool { self.vdma_debug.load(Ordering::Relaxed) } - - pub(crate) fn vdma_log(&self) -> &Mutex> { &self.vdma_log } - pub(crate) fn vdma_stage(&self) -> &Mutex> { &self.vdma_stage } pub fn register_locks(&self) { @@ -1099,7 +1085,7 @@ impl Device for MemoryController { fn register_commands(&self) -> Vec<(String, String)> { vec![ - ("mc".to_string(), "Memory Controller commands: mc dma, mc dma xlate [vaddr] [w], mc regs, mc vdma ".to_string()), + ("mc".to_string(), "Memory Controller commands: mc dma, mc dma xlate [vaddr] [w], mc regs".to_string()), ("eeprom".to_string(), "CPU/MC EEPROM commands (93C56 @ 0x1fa00030, CPU boot config incl. CACHSZ_REG @ word 0x11 — NOT the NVRAM/MAC chip, see `nveeprom`): eeprom dump | eeprom r | eeprom w ".to_string()), ] } @@ -1221,28 +1207,10 @@ impl Device for MemoryController { writeln!(writer, " SYS_SEMA : {}", s.sys_semaphore as u8).unwrap(); writeln!(writer, " LOCK_MEM : {:08x}", reg(REG_LOCK_MEMORY)).unwrap(); writeln!(writer, " EISA_LOCK : {:08x}", reg(REG_EISA_LOCK)).unwrap(); - } else if !args.is_empty() && args[0] == "vdma" { - let val = match args.get(1).map(|s| *s) { - Some("on") => true, - Some("off") => false, - _ => return Err("Usage: mc vdma ".to_string()), - }; - self.vdma_debug.store(val, Ordering::Relaxed); - let mut log = self.vdma_log.lock(); - if val { - match std::fs::File::create("vdma.log") { - Ok(f) => { *log = Some(f); writeln!(writer, "VDMA debug enabled, logging to vdma.log").unwrap(); } - Err(e) => { writeln!(writer, "VDMA debug enabled but failed to open log: {}", e).unwrap(); } - } - } else { - *log = None; - writeln!(writer, "VDMA debug disabled").unwrap(); - } } else { writeln!(writer, "MC Status: OK").unwrap(); writeln!(writer, " Usage: mc dma — show GIO DMA + µTLB status").unwrap(); writeln!(writer, " mc regs — show MC control registers").unwrap(); - writeln!(writer, " mc vdma — log VDMA transactions to vdma.log").unwrap(); } } "eeprom" => { diff --git a/src/dev/mc_vdma.rs b/src/dev/mc_vdma.rs index 59188e6a0..18e37ee8c 100644 --- a/src/dev/mc_vdma.rs +++ b/src/dev/mc_vdma.rs @@ -67,7 +67,7 @@ use std::sync::atomic::Ordering; use parking_lot::{Mutex, Condvar}; use std::io::Write as IoWrite; -use crate::devlog::LogModule; +use crate::devlog::{devlog_is_active, LogModule}; use crate::traits::BUS_BUSY; use crate::dev::mc::MemoryController; @@ -523,34 +523,30 @@ impl MemoryController { }; let phys = phys.as_ref(); - // Record the chosen path in vdma.log too — `mc vdma on` is the only - // diagnostic available in a lightning build (dlog_dev/developer is - // mutually exclusive with it), and "which engine ran this transfer" is - // the first thing worth knowing about a corrupted readback. - if self.vdma_debug_enabled() { - if let Some(f) = self.vdma_log().lock().as_mut() { - let path = if job.gio32 { - "GIO32 word" - } else if job.word_aligned && job.fill && job.to_host && !job.xlate { - "FILL" - } else if job.qword_flat() && !job.fill && !job.to_host { - "MEM->GIO qword" - } else if job.qword_flat() && !job.fill && job.to_host { - "GIO->MEM qword" - } else if job.line_bulk_ok() { - "PER-LINE bulk" - } else if job.word_aligned && !job.xlate { - "generic WORD" - } else { - "generic BYTE" - }; - let _ = writeln!(f, - " path={path} qword_flat={} flat_len={} (mem&7={} gio&7={} zoom={}/{} stride={} lw={} lc={} bc={})", - job.qword_flat(), job.flat_len(), - job.mem_vaddr & 7, job.gio_addr & 7, - job.zoom_count, job.line_zoom, job.stride, - job.line_width, job.line_count, job.byte_count); - } + // Which engine ran a transfer is the first thing to know about a + // corrupted readback. + if devlog_is_active(LogModule::Mc) { + let path = if job.gio32 { + "GIO32 word" + } else if job.word_aligned && job.fill && job.to_host && !job.xlate { + "FILL" + } else if job.qword_flat() && !job.fill && !job.to_host { + "MEM->GIO qword" + } else if job.qword_flat() && !job.fill && job.to_host { + "GIO->MEM qword" + } else if job.line_bulk_ok() { + "PER-LINE bulk" + } else if job.word_aligned && !job.xlate { + "generic WORD" + } else { + "generic BYTE" + }; + dlog!(LogModule::Mc, + " path={path} qword_flat={} flat_len={} (mem&7={} gio&7={} zoom={}/{} stride={} lw={} lc={} bc={})", + job.qword_flat(), job.flat_len(), + job.mem_vaddr & 7, job.gio_addr & 7, + job.zoom_count, job.line_zoom, job.stride, + job.line_width, job.line_count, job.byte_count); } if job.gio32 { @@ -683,13 +679,9 @@ impl MemoryController { mem_vaddr = mem_vaddr.wrapping_add(8); } - if self.vdma_debug_enabled() { - if let Some(f) = self.vdma_log().lock().as_mut() { - let _ = writeln!(f, - " write chunk: {} qwords first={:016x} last={:016x}", - chunk, stage[0], stage[chunk - 1]); - } - } + dlog!(LogModule::Mc, + " write chunk: {} qwords first={:016x} last={:016x}", + chunk, stage[0], stage[chunk - 1]); // Hand off the whole chunk. BUS_ERR means the device declined to // batch this address, so fall back to the scalar loop for it rather @@ -766,13 +758,9 @@ impl MemoryController { } } - if self.vdma_debug_enabled() { - if let Some(f) = self.vdma_log().lock().as_mut() { - let _ = writeln!(f, - " read chunk: {} qwords st={:#x} first={:016x} last={:016x}", - chunk, st, stage[0], stage[chunk - 1]); - } - } + dlog!(LogModule::Mc, + " read chunk: {} qwords st={:#x} first={:016x} last={:016x}", + chunk, st, stage[0], stage[chunk - 1]); // Drain: translate + write out. for &data in stage[..chunk].iter() { @@ -905,14 +893,10 @@ impl MemoryController { self.bulk_write_chunk(phys, job, &stage[..n]); } - if self.vdma_debug_enabled() { - if let Some(f) = self.vdma_log().lock().as_mut() { - let _ = writeln!(f, - " line chunk: {} lines x {} qwords = {} qwords ({})", - pending, qpl, n, - if job.to_host { "gio->mem" } else { "mem->gio" }); - } - } + dlog!(LogModule::Mc, + " line chunk: {} lines x {} qwords = {} qwords ({})", + pending, qpl, n, + if job.to_host { "gio->mem" } else { "mem->gio" }); pending = 0; chunk_mem = mem_vaddr; chunk_reps = reps_left; @@ -1238,10 +1222,10 @@ impl MemoryController { job.mem_vaddr, job.gio_addr, state.size, job.mode, job.to_host, job.fill, job.dir_up, job.xlate, job.word_aligned); - // Snapshot the µTLB while state is still locked, for the vdma_log page-table + // Snapshot the µTLB while state is still locked, for the page-table // dump below — translate_addr() re-reads this per-page during the transfer, // but the log only needs the entries valid at transfer start. - let tlb_snapshot = if self.vdma_debug_enabled() { + let tlb_snapshot = if devlog_is_active(LogModule::Mc) { Some((state.tlb_hi, state.tlb_lo)) } else { None @@ -1273,12 +1257,8 @@ impl MemoryController { let elapsed_us = (elapsed as f64 / freq as f64) * 1_000_000.0; dlog_dev!(LogModule::Mc, "MC: DMA Finished in {:.3} us ({} ticks)", elapsed_us, elapsed); - if self.vdma_debug_enabled() { - if let Some(f) = self.vdma_log().lock().as_mut() { - let _ = writeln!(f, "VDMA end: mem={:08x} fault={} {:.3}us", - result.mem_vaddr, result.exc, elapsed_us); - } - } + dlog!(LogModule::Mc, "VDMA end: mem={:08x} fault={} {:.3}us", + result.mem_vaddr, result.exc, elapsed_us); state = lock.lock(); state.memadr = result.mem_vaddr; @@ -1300,14 +1280,11 @@ impl MemoryController { } } - /// `mc vdma on` transfer header: mode, block shape and the µTLB as latched. + /// `log mc` transfer header: mode, block shape and the µTLB as latched. fn log_vdma_start(&self, job: &VdmaJob, tlb_hi: [u32; 4], tlb_lo: [u32; 4]) { - let mut guard = self.vdma_log().lock(); - let Some(f) = guard.as_mut() else { return; }; - let page_16k = (job.ctl & 0x2) != 0; let pte_8byte = (job.ctl & 0x1) != 0; - let _ = writeln!(f, + dlog!(LogModule::Mc, "VDMA start: dir={} mode={}{} mem={:08x} gio={:08x} xlate={} page={} pte={}B", if job.to_host { "gio->mem" } else { "mem->gio" }, if job.fill { "fill" } else { "copy" }, @@ -1315,17 +1292,17 @@ impl MemoryController { job.mem_vaddr, job.gio_addr, job.xlate, if page_16k { "16K" } else { "4K" }, if pte_8byte { 8 } else { 4 }); - let _ = writeln!(f, + dlog!(LogModule::Mc, " block: line_count={} line_width={:#x} line_zoom={} zoom_count={} byte_count={:#x} stride={}", job.line_count, job.line_width, job.line_zoom, job.zoom_count, job.byte_count, job.stride); if job.xlate { - let _ = writeln!(f, " uTLB:"); + dlog!(LogModule::Mc, " uTLB:"); for i in 0..4 { let hi = tlb_hi[i]; let lo = tlb_lo[i]; let valid = (lo & 2) != 0; let pte_base = (lo & 0x03ffffc0) << 6; - let _ = writeln!(f, " [{i}] vpnhi={:08x} valid={valid} pte_base={pte_base:08x}", + dlog!(LogModule::Mc, " [{i}] vpnhi={:08x} valid={valid} pte_base={pte_base:08x}", hi & 0xffc00000); } } @@ -1957,7 +1934,7 @@ mod line_bulk_tests_support { } /// Shapes the flat path rejects but the per-line path must handle. The - /// 164x239 entry is the real Start-menu blit from vdma.log. + /// 164x239 entry is the real Start-menu blit from a VDMA trace. fn shapes() -> Vec<(&'static str, VdmaJob)> { vec![ ("start-menu 164x239 stride=0", VdmaJob { diff --git a/src/dev/ng1/rex3.rs b/src/dev/ng1/rex3.rs index 75b1c5629..7a79c6fff 100644 --- a/src/dev/ng1/rex3.rs +++ b/src/dev/ng1/rex3.rs @@ -271,19 +271,10 @@ pub(crate) fn decode_dm1(v: u32) -> String { format!("{} {} host:{} cmp:{} logicop:{}{}", planes, depth, hdepth, dm.compare(), logicop, flags) } -/// Say what an access nothing handles, the first few times per register and kind, so a polled one -/// cannot flood stderr or hide a later one. +/// Say what an access nothing handles, per register and access kind, so a polled one cannot flood +/// stderr or hide a later one. fn unhandled(kind: &'static str, offset: u32, what: std::fmt::Arguments) { - static SEEN: std::sync::OnceLock>> = std::sync::OnceLock::new(); - if first_few(&mut SEEN.get_or_init(Default::default).lock(), kind, offset) { - eprintln!("REX3: unhandled {what}"); - } -} - -fn first_few(seen: &mut HashMap<(&'static str, u32), u32>, kind: &'static str, offset: u32) -> bool { - let n = seen.entry((kind, offset)).or_insert(0); - *n += 1; - *n <= 8 + crate::notice!((kind, offset), "REX3: unhandled {what}"); } pub(crate) fn rex3_reg_name(offset: u32) -> &'static str { @@ -1458,8 +1449,6 @@ pub struct Rex3 { #[cfg(all(test, feature = "gputrace"))] fence_observer: Mutex>>, #[cfg(feature = "developer")] - pub block_debug: Arc, - #[cfg(feature = "developer")] pub draw_debug: Arc, #[cfg(feature = "developer")] pub draw_ring: Arc>, @@ -1516,9 +1505,6 @@ pub struct Rex3 { /// The machine's status-bar inputs (heartbeat, cycle counter, ...), shared /// with every other board on it. pub status: Arc, - /// Optional log file for block/span draws (set when block_debug is enabled). - #[cfg(feature = "developer")] - block_log: Mutex>, /// What the bus and processor paths must report: `rec::TAP_REC` while a /// recording runs, `trace::TRACE_*` categories while a trace does. One /// relaxed load of zero is all either costs when off. @@ -1649,8 +1635,6 @@ impl Rex3 { #[cfg(all(test, feature = "gputrace"))] fence_observer: Mutex::new(None), #[cfg(feature = "developer")] - block_debug: Arc::new(AtomicBool::new(false)), - #[cfg(feature = "developer")] draw_debug: Arc::new(AtomicBool::new(false)), #[cfg(feature = "developer")] draw_ring: Arc::new(Mutex::new(DrawRingBuf::default())), @@ -1695,8 +1679,6 @@ impl Rex3 { #[cfg(feature = "rex-jit")] jit_last: std::cell::Cell::new((0, 0, 0, None)), status, - #[cfg(feature = "developer")] - block_log: Mutex::new(None), #[cfg(feature = "gputrace")] tap: AtomicU32::new(0), #[cfg(feature = "gputrace")] @@ -2394,7 +2376,7 @@ impl Rex3 { #[cfg(feature = "developer")] pub(crate) fn log_block(&self, ctx: &Rex3Context, opcode: u32) { - let need_block_log = self.block_log.lock().is_some(); + let need_block_log = devlog_is_active(LogModule::Rex3); let need_draw_ring = self.draw_debug_active(); if ctx.mid_primitive || (!need_block_log && !need_draw_ring) { return; } @@ -2431,73 +2413,71 @@ impl Rex3 { } else { (0, 0, 0, 0) }; if need_block_log { - if let Some(f) = self.block_log.lock().as_mut() { - let planes_str = match ctx.drawmode1.planes() { - DRAWMODE1_PLANES_RGB => "RGB", DRAWMODE1_PLANES_RGBA => "RGBA", - DRAWMODE1_PLANES_OLAY => "OLAY", DRAWMODE1_PLANES_PUP => "PUP", - DRAWMODE1_PLANES_CID => "CID", _ => "?" - }; - let bpp = match ctx.drawmode1.drawdepth() { - DRAWMODE1_DRAWDEPTH_4 => 4, - DRAWMODE1_DRAWDEPTH_8 => 8, - DRAWMODE1_DRAWDEPTH_12 => 12, - DRAWMODE1_DRAWDEPTH_24 => 24, - _ => 0, - }; - let opcode_str = match opcode { - DRAWMODE0_OPCODE_READ => "READ", - DRAWMODE0_OPCODE_DRAW => "DRAW", - DRAWMODE0_OPCODE_SCR2SCR => "SCR2SCR", - _ => "NOOP", - }; - let adrmode_str = match ctx.drawmode0.adrmode() { - 0=>"SPAN", 1=>"BLOCK", 2=>"I_LINE", 3=>"F_LINE", 4=>"A_LINE", _=>"?" - }; - let logicop_str = match ctx.drawmode1.logicop() { - 0=>"ZERO", 1=>"AND", 2=>"ANDR", 3=>"SRC", - 4=>"ANDI", 5=>"DST", 6=>"XOR", 7=>"OR", - 8=>"NOR", 9=>"XNOR",10=>"NDST",11=>"ORR", - 12=>"NSRC",13=>"ORI",14=>"NAND",15=>"ONE", _=>"?" - }; - let w = ((ctx.xend - ctx.xstart) >> 11).unsigned_abs() + 1; - let h = if is_span { 1 } else { ((ctx.yend - ctx.ystart) >> 11).unsigned_abs() + 1 }; - let colorhost = ctx.drawmode0.colorhost(); - let alphahost = ctx.drawmode0.alphahost(); - let cidmatch = (ctx.clipmode >> CLIPMODE_CIDMATCH_SHIFT) & 0xF; - let fastclear_active = ctx.drawmode1.fastclear() && cidmatch == 0xF; - let op_label = if fastclear_active { "FASTCLEAR" } else { opcode_str }; - let src_info = if is_scr2scr { - format!(" src=({},{})-({},{})", src_x0, src_y0, src_x1, src_y1) - } else { String::new() }; - let (log_x1, log_y1) = if is_span { (dst_x1, dst_y0) } else { (dst_x1, dst_y1) }; - let _ = writeln!(f, "{}: planes={} {} {}bpp logicop={} wrmask={:06x} colorhost={} alphahost={} dst=({},{})-({},{}) size={}x{}{}", - op_label, planes_str, adrmode_str, bpp, logicop_str, - ctx.wrmask, colorhost as u8, alphahost as u8, - dst_x0, dst_y0, log_x1, log_y1, w, h, src_info); - let _ = writeln!(f, " DM0={:08x} DM1={:08x}", ctx.drawmode0.0, ctx.drawmode1.0); - if fastclear_active { - let _ = writeln!(f, " colorvram={:08x} colorback={:08x}", ctx.colorvram, ctx.colorback); - } else { - let _ = writeln!(f, " color=(r:{:06x},g:{:05x},b:{:05x}) colori={:08x} colorback={:08x}", - ctx.colorred, ctx.colorgrn, ctx.colorblue, - ctx.get_colori(), ctx.colorback); - } - let _ = writeln!(f, " enzpat={} zpat={:08x} zpopaque={} enlspat={} lspat={:08x} lsopaque={} dblsrc={}", - ctx.drawmode0.enzpattern() as u8, ctx.zpattern, ctx.drawmode0.zpopaque() as u8, - ctx.drawmode0.enlspattern() as u8, ctx.lspattern, ctx.drawmode0.lsopaque() as u8, - ctx.drawmode1.dblsrc() as u8); - if colorhost || alphahost { - let hdepth = ctx.drawmode1.hostdepth(); - let double = ctx.drawmode1.rwdouble(); - let packed = ctx.drawmode1.rwpacked(); - let hbpp = match hdepth { 0=>4, 1=>8, 2=>12, 3=>32, _=>0 }; - let ppw = if packed { match hdepth { 0=>8, 1=>4, 2=>2, 3=>1, _=>1 } } else { 1 }; - let row_align = if double { ppw * 2 } else { ppw }; - let words_per_row = w.div_ceil(row_align) * (if double { 2 } else { 1 }); - let total_32b = words_per_row * h; - let _ = writeln!(f, " HOSTW: hbpp={} packed={} double={} ppw={} words_per_row={} expected_32b={} expected_64b={}", - hbpp, packed as u8, double as u8, ppw, words_per_row, total_32b, total_32b.div_ceil(2)); - } + let planes_str = match ctx.drawmode1.planes() { + DRAWMODE1_PLANES_RGB => "RGB", DRAWMODE1_PLANES_RGBA => "RGBA", + DRAWMODE1_PLANES_OLAY => "OLAY", DRAWMODE1_PLANES_PUP => "PUP", + DRAWMODE1_PLANES_CID => "CID", _ => "?" + }; + let bpp = match ctx.drawmode1.drawdepth() { + DRAWMODE1_DRAWDEPTH_4 => 4, + DRAWMODE1_DRAWDEPTH_8 => 8, + DRAWMODE1_DRAWDEPTH_12 => 12, + DRAWMODE1_DRAWDEPTH_24 => 24, + _ => 0, + }; + let opcode_str = match opcode { + DRAWMODE0_OPCODE_READ => "READ", + DRAWMODE0_OPCODE_DRAW => "DRAW", + DRAWMODE0_OPCODE_SCR2SCR => "SCR2SCR", + _ => "NOOP", + }; + let adrmode_str = match ctx.drawmode0.adrmode() { + 0=>"SPAN", 1=>"BLOCK", 2=>"I_LINE", 3=>"F_LINE", 4=>"A_LINE", _=>"?" + }; + let logicop_str = match ctx.drawmode1.logicop() { + 0=>"ZERO", 1=>"AND", 2=>"ANDR", 3=>"SRC", + 4=>"ANDI", 5=>"DST", 6=>"XOR", 7=>"OR", + 8=>"NOR", 9=>"XNOR",10=>"NDST",11=>"ORR", + 12=>"NSRC",13=>"ORI",14=>"NAND",15=>"ONE", _=>"?" + }; + let w = ((ctx.xend - ctx.xstart) >> 11).unsigned_abs() + 1; + let h = if is_span { 1 } else { ((ctx.yend - ctx.ystart) >> 11).unsigned_abs() + 1 }; + let colorhost = ctx.drawmode0.colorhost(); + let alphahost = ctx.drawmode0.alphahost(); + let cidmatch = (ctx.clipmode >> CLIPMODE_CIDMATCH_SHIFT) & 0xF; + let fastclear_active = ctx.drawmode1.fastclear() && cidmatch == 0xF; + let op_label = if fastclear_active { "FASTCLEAR" } else { opcode_str }; + let src_info = if is_scr2scr { + format!(" src=({},{})-({},{})", src_x0, src_y0, src_x1, src_y1) + } else { String::new() }; + let (log_x1, log_y1) = if is_span { (dst_x1, dst_y0) } else { (dst_x1, dst_y1) }; + dlog!(LogModule::Rex3, "{}: planes={} {} {}bpp logicop={} wrmask={:06x} colorhost={} alphahost={} dst=({},{})-({},{}) size={}x{}{}", + op_label, planes_str, adrmode_str, bpp, logicop_str, + ctx.wrmask, colorhost as u8, alphahost as u8, + dst_x0, dst_y0, log_x1, log_y1, w, h, src_info); + dlog!(LogModule::Rex3, " DM0={:08x} DM1={:08x}", ctx.drawmode0.0, ctx.drawmode1.0); + if fastclear_active { + dlog!(LogModule::Rex3, " colorvram={:08x} colorback={:08x}", ctx.colorvram, ctx.colorback); + } else { + dlog!(LogModule::Rex3, " color=(r:{:06x},g:{:05x},b:{:05x}) colori={:08x} colorback={:08x}", + ctx.colorred, ctx.colorgrn, ctx.colorblue, + ctx.get_colori(), ctx.colorback); + } + dlog!(LogModule::Rex3, " enzpat={} zpat={:08x} zpopaque={} enlspat={} lspat={:08x} lsopaque={} dblsrc={}", + ctx.drawmode0.enzpattern() as u8, ctx.zpattern, ctx.drawmode0.zpopaque() as u8, + ctx.drawmode0.enlspattern() as u8, ctx.lspattern, ctx.drawmode0.lsopaque() as u8, + ctx.drawmode1.dblsrc() as u8); + if colorhost || alphahost { + let hdepth = ctx.drawmode1.hostdepth(); + let double = ctx.drawmode1.rwdouble(); + let packed = ctx.drawmode1.rwpacked(); + let hbpp = match hdepth { 0=>4, 1=>8, 2=>12, 3=>32, _=>0 }; + let ppw = if packed { match hdepth { 0=>8, 1=>4, 2=>2, 3=>1, _=>1 } } else { 1 }; + let row_align = if double { ppw * 2 } else { ppw }; + let words_per_row = w.div_ceil(row_align) * (if double { 2 } else { 1 }); + let total_32b = words_per_row * h; + dlog!(LogModule::Rex3, " HOSTW: hbpp={} packed={} double={} ppw={} words_per_row={} expected_32b={} expected_64b={}", + hbpp, packed as u8, double as u8, ppw, words_per_row, total_32b, total_32b.div_ceil(2)); } } @@ -3966,10 +3946,7 @@ impl Rex3 { // entirely (`pending == None`). That is why the overlay showed // `0/4802` for a transfer that carried every word. The words // are counted in `execute_go` instead, once the record exists. - #[cfg(feature = "developer")] - if let Some(f) = self.block_log.lock().as_mut() { - let _ = writeln!(f, " HOSTRW batch write: {} qwords (asked {})", got, count); - } + dlog_dev!(LogModule::Rex3, " HOSTRW batch write: {} qwords (asked {})", got, count); } // Batched HOSTRW read: arm the cursor so the shader scatters its // output across host_buf instead of latching one word. @@ -3979,10 +3956,7 @@ impl Rex3 { ctx.host_cursor = 0; ctx.host_len = (val64 as u32).min(HOSTRW_BUF_QWORDS as u32); ctx.hostcnt = 0; - #[cfg(feature = "developer")] - if let Some(f) = self.block_log.lock().as_mut() { - let _ = writeln!(f, " HOSTRW batch read: {} qwords", ctx.host_len); - } + dlog_dev!(LogModule::Rex3, " HOSTRW batch read: {} qwords", ctx.host_len); } // HOSTRW: store data port value; reset shift so the draw picks up pixels from MSB. // The actual draw/read is triggered by execute_go() when entry.go is set. @@ -3992,10 +3966,7 @@ impl Rex3 { ctx.hostrw_set(val64); ctx.hostcnt = 0; self.note_hostrw_write(); - #[cfg(feature = "developer")] - if let Some(f) = self.block_log.lock().as_mut() { - let _ = writeln!(f, " HOSTRW64 {:016x}", val64); - } + dlog_dev!(LogModule::Rex3, " HOSTRW64 {:016x}", val64); } REX3_HOSTRW0 => { // 32-bit write to HOSTRW0: update high 32 bits [63:32]. @@ -4004,10 +3975,7 @@ impl Rex3 { ctx.hostrw_set(new_val); ctx.hostcnt = 0; self.note_hostrw_write(); - #[cfg(feature = "developer")] - if let Some(f) = self.block_log.lock().as_mut() { - let _ = writeln!(f, " HOSTRW0 {:08x} -> {:016x}", val64 as u32, new_val); - } + dlog_dev!(LogModule::Rex3, " HOSTRW0 {:08x} -> {:016x}", val64 as u32, new_val); } REX3_HOSTRW1 => { // 32-bit write to HOSTRW1: update low 32 bits [31:0]. @@ -4016,10 +3984,7 @@ impl Rex3 { ctx.hostrw_set(new_val); ctx.hostcnt = 0; self.note_hostrw_write(); - #[cfg(feature = "developer")] - if let Some(f) = self.block_log.lock().as_mut() { - let _ = writeln!(f, " HOSTRW1 {:08x} -> {:016x}", val64 as u32, new_val); - } + dlog_dev!(LogModule::Rex3, " HOSTRW1 {:08x} -> {:016x}", val64 as u32, new_val); } REX3_DRAWMODE1 => ctx.drawmode1 = DrawMode1(val), REX3_DRAWMODE0 => ctx.drawmode0 = DrawMode0(val), @@ -4461,7 +4426,6 @@ impl Device for Rex3 { ]; #[cfg(feature = "developer")] cmds.extend([ - ("block".to_string(), "Block draw logging: block debug [DEV]".to_string()), ("draw".to_string(), "Draw debug overlay: draw debug [DEV]".to_string()), ]); cmds @@ -4867,21 +4831,6 @@ impl Device for Rex3 { }; match cmd { - #[cfg(feature = "developer")] - "block" => { - self.block_debug.store(val, Ordering::Relaxed); - let mut log = self.block_log.lock(); - if val { - match std::fs::File::create("block.log") { - Ok(f) => { *log = Some(f); writeln!(writer, "Block debug enabled, logging to block.log").unwrap(); } - Err(e) => { writeln!(writer, "Block debug enabled but failed to open log: {}", e).unwrap(); } - } - } else { - *log = None; - writeln!(writer, "Block debug disabled").unwrap(); - } - return Ok(()); - } #[cfg(feature = "developer")] "draw" => { self.ensure_cpu_overlay_available(val, "draw debug overlay")?; @@ -5105,11 +5054,9 @@ impl Rex3 { if reg_offset == REX3_HOSTRW0 || reg_offset == REX3_HOSTRW1 { self.note_hostrw_read(); #[cfg(feature = "developer")] - if let Some(f) = self.block_log.lock().as_mut() { - if result.is_ok() { - let _ = writeln!(f, " {} read -> {:08x}{}", - rex3_reg_name(reg_offset), result.data, if is_go { " (GO)" } else { "" }); - } + if result.is_ok() { + dlog_dev!(LogModule::Rex3, " {} read -> {:08x}{}", + rex3_reg_name(reg_offset), result.data, if is_go { " (GO)" } else { "" }); } } else if is_go { // Any other register read with the GO bit also pushes a PURE_GO (see below), @@ -5118,10 +5065,7 @@ impl Rex3 { // count that comes up short of expected_64b/expected_words can be traced to // a non-HOSTRW GO-read stealing one of the PURE_GO slots, instead of looking // like a dropped/missing pixel word. - #[cfg(feature = "developer")] - if let Some(f) = self.block_log.lock().as_mut() { - let _ = writeln!(f, " {} read (GO, non-HOSTRW)", rex3_reg_name(reg_offset)); - } + dlog_dev!(LogModule::Rex3, " {} read (GO, non-HOSTRW)", rex3_reg_name(reg_offset)); } // Blocking push, deliberately: `result` is already computed above and a @@ -5274,10 +5218,7 @@ impl Rex3 { } let val = unsafe { (*self.context.get()).hostrw_get() }; self.note_hostrw_read(); - #[cfg(feature = "developer")] - if let Some(f) = self.block_log.lock().as_mut() { - let _ = writeln!(f, " HOSTRW0_64 read -> {:016x}{}", val, if is_go64r { " (GO)" } else { "" }); - } + dlog_dev!(LogModule::Rex3, " HOSTRW0_64 read -> {:016x}{}", val, if is_go64r { " (GO)" } else { "" }); if is_go64r { // Enqueue a pure-go entry: no register update, just trigger next pixel batch. self.gfifo_push(GFIFO_PURE_GO, 0); @@ -5326,10 +5267,7 @@ impl Rex3 { let val = unsafe { (*self.context.get()).hostrw_get() }; self.note_hostrw_read(); - #[cfg(feature = "developer")] - if let Some(f) = self.block_log.lock().as_mut() { - let _ = writeln!(f, " HOSTRW0_64 dma_read: before={:016x} after={:016x} (primed)", before, val); - } + dlog_dev!(LogModule::Rex3, " HOSTRW0_64 dma_read: before={:016x} after={:016x} (primed)", before, val); BusRead64::ok(val) } diff --git a/src/dev/ng1/rex3_generic.rs b/src/dev/ng1/rex3_generic.rs index 18f3723ec..e7cbf62ac 100644 --- a/src/dev/ng1/rex3_generic.rs +++ b/src/dev/ng1/rex3_generic.rs @@ -1527,7 +1527,7 @@ pub fn draw_block_g(fb: &Framebuffers, ctx: &mut Rex3Context, m: &M) { // which already clears mid_primitive here. Leaving this true (as // before) permanently wedged log_block()'s "primitive start" guard // after the first non-stopony block ever ran, hiding every - // subsequent block/READ/DRAW header from block.log. + // subsequent block/READ/DRAW header from the block trace. ctx.mid_primitive = false; break; } diff --git a/src/dev/ng1/rex3_tests.rs b/src/dev/ng1/rex3_tests.rs index d71e02cad..39c4c34e4 100644 --- a/src/dev/ng1/rex3_tests.rs +++ b/src/dev/ng1/rex3_tests.rs @@ -8050,7 +8050,7 @@ fn test_hostw_batch_paints_every_row_of_a_multirow_block() { "last row is blank: the batch was dropped before finishing"); } -/// The real icon-upload shape from `vdma.log`: 98 x 98 RGB24, 49 64-bit words +/// The real icon-upload shape from a VDMA trace: 98 x 98 RGB24, 49 64-bit words /// per row, 4802 words in one batch. /// /// Drives the batch against the CPU's one-word-per-GO feed, which is the @@ -10003,12 +10003,3 @@ fn rexget_clears_the_sign_extension() { // Writing then reading a negative coordinate leaves its 23-bit form. assert_eq!((-0x80i32 as u32).rexset(9, 7).rexget(9, 7), 0x007F_FF80); } - -#[test] -fn an_unhandled_register_is_reported_a_few_times_and_the_next_one_still_is() { - let mut seen = std::collections::HashMap::new(); - let polled: Vec = (0..10).map(|_| super::first_few(&mut seen, "read32", 0x1000)).collect(); - assert_eq!(polled.iter().filter(|&&p| p).count(), 8); - assert!(super::first_few(&mut seen, "read32", 0x1004)); - assert!(super::first_few(&mut seen, "write", 0x1000)); -} diff --git a/src/dev/nvme/tests.rs b/src/dev/nvme/tests.rs index 04f5b55d5..e3d7bad58 100644 --- a/src/dev/nvme/tests.rs +++ b/src/dev/nvme/tests.rs @@ -334,7 +334,7 @@ fn a_failed_enable_is_counted_with_its_reason_across_the_reset() { fn the_trace_records_cc_writes_ready_and_commands() { use crate::devlog::devlog; let path = std::env::temp_dir().join(format!("iris-nvme-trace-{}", std::process::id())); - devlog().set_file(LogModule::Nvme, path.to_str().unwrap()).unwrap(); + devlog().set_file(&[LogModule::Nvme], path.to_str().unwrap()).unwrap(); devlog().select("nvme.state,nvme.admin", true).unwrap(); let mut r = Rig::new(); r.enable(); diff --git a/src/dev/vino.rs b/src/dev/vino.rs index d8521fb35..86778ec64 100644 --- a/src/dev/vino.rs +++ b/src/dev/vino.rs @@ -529,7 +529,7 @@ impl Vino { for i in 0..4usize { let word_addr = addr.wrapping_add((i as u32) * 4); let word = { let _r = mem.read32(word_addr as u64); if _r.is_ok() { _r.data } else { - eprintln!("VINO: descriptor_fetch read error at {:#010x}", word_addr); + crate::notice!(word_addr, "VINO: descriptor_fetch read error at {:#010x}", word_addr); 0 } }; @@ -1013,7 +1013,7 @@ impl Vino { reg::I2C_CONTROL => st.i2c_ctrl, reg::I2C_DATA => st.i2c_data, _ => { - eprintln!("VINO: unknown read at offset {:#06x}", offset); + crate::notice!(offset, "VINO: unknown read at offset {:#06x}", offset); 0 } } @@ -1067,7 +1067,7 @@ impl Vino { reg::CH_FIFO_READ => chan.fifo_gio_ptr, reg::CH_FIFO_WRITE => chan.fifo_video_ptr, _ => { - eprintln!("VINO: unknown channel read at ch_off {:#06x}", off); + crate::notice!(off, "VINO: unknown channel read at ch_off {:#06x}", off); 0 } } @@ -1174,7 +1174,7 @@ impl Vino { } } _ => { - eprintln!("VINO: unknown write at offset {:#06x} = {:#010x}", offset, val); + crate::notice!(offset, "VINO: unknown write at offset {:#06x} = {:#010x}", offset, val); } } } @@ -1219,7 +1219,7 @@ impl Vino { reg::CH_FIFO_READ => { /* read-only, ignore */ } reg::CH_FIFO_WRITE => { /* read-only, ignore */ } _ => { - eprintln!("VINO: unknown channel write at ch_off {:#06x} = {:#010x}", off, val); + crate::notice!(off, "VINO: unknown channel write at ch_off {:#06x} = {:#010x}", off, val); } } } diff --git a/src/dev/wd33c93a.rs b/src/dev/wd33c93a.rs index a9f2f5024..d125fda33 100644 --- a/src/dev/wd33c93a.rs +++ b/src/dev/wd33c93a.rs @@ -74,57 +74,6 @@ impl ArmWaits { } } -// Ring-buffer trace of WD33C93 register accesses with consecutive-dedup, so -// long polling loops compress to one "(x N)" line and the ring covers a much -// wider window of activity. -// Only compiled and active under --features developer. -#[cfg(feature = "developer")] -pub static WDT_SEQ: AtomicU64 = AtomicU64::new(0); -#[cfg(feature = "developer")] -pub struct WdtRing { - entries: VecDeque<(u64, String, u64)>, // (first_seq, message, repeat_count) -} -#[cfg(feature = "developer")] -pub static WDT_RING: parking_lot::Mutex = parking_lot::Mutex::new(WdtRing { entries: VecDeque::new() }); -#[cfg(feature = "developer")] -const WDT_RING_CAP: usize = 4000; - -#[cfg(feature = "developer")] -pub fn wdt_log(args: std::fmt::Arguments<'_>) { - let n = WDT_SEQ.fetch_add(1, Ordering::Relaxed); - let msg = format!("{}", args); - let mut ring = WDT_RING.lock(); - if let Some(last) = ring.entries.back_mut() { - if last.1 == msg { - last.2 += 1; - return; - } - } - if ring.entries.len() >= WDT_RING_CAP { ring.entries.pop_front(); } - ring.entries.push_back((n, msg, 1)); -} - -#[cfg(feature = "developer")] -pub fn wdt_dump_tail() { - let ring = WDT_RING.lock(); - for (seq, msg, cnt) in ring.entries.iter() { - if *cnt == 1 { - eprintln!("WDT {:8} {}", seq, msg); - } else { - eprintln!("WDT {:8} {} (x{})", seq, msg, cnt); - } - } - eprintln!("WDT_DUMP_END (total_seen={})", WDT_SEQ.load(Ordering::Relaxed)); -} - -/// Log a WDT entry — no-op when developer feature is disabled. -macro_rules! wdt { - ($($arg:tt)*) => { - #[cfg(feature = "developer")] - wdt_log(format_args!($($arg)*)); - }; -} - // Indirect Register Addresses (accessed via AR) pub mod regs { pub const OWN_ID: u8 = 0x00; @@ -526,8 +475,6 @@ impl Wd33c93a { if ar == regs::DATA { let val = state.fifo.pop_front().unwrap_or(0); - wdt!("R FIFO -> {:02x} (fifo_remaining={})", - val, state.fifo.len()); dlog!(state.log_module(), "WD33C93A({}): Read FIFO -> {:02x}", state.id, val); // DBR-based PIO delivery: when DBR was set (data/status/msg byte ready), @@ -547,17 +494,17 @@ impl Wd33c93a { match cmd_phase { command_phase::TRANSFER_COUNT => { state.regs[regs::TARGET_LUN as usize] = state.pending_status; - wdt!("PIO_INT TRANSFER_COUNT→RECEIVE_STATUS phase={:02x}", cmd_phase); + dlog_dev!(state.log_module(), "PIO_INT TRANSFER_COUNT→RECEIVE_STATUS phase={:02x}", cmd_phase); state.queue_interrupt(Some(command_phase::RECEIVE_STATUS), scsi_status::TRANSFER_STATUS_IN); fire_irq = true; } command_phase::RECEIVE_STATUS => { - wdt!("PIO_INT RECEIVE_STATUS→STATUS_RECEIVED phase={:02x}", cmd_phase); + dlog_dev!(state.log_module(), "PIO_INT RECEIVE_STATUS→STATUS_RECEIVED phase={:02x}", cmd_phase); state.queue_interrupt(Some(command_phase::STATUS_RECEIVED), scsi_status::TRANSFER_MSG_IN); fire_irq = true; } command_phase::STATUS_RECEIVED => { - wdt!("PIO_INT STATUS_RECEIVED→COMPLETE_MSG phase={:02x}", cmd_phase); + dlog_dev!(state.log_module(), "PIO_INT STATUS_RECEIVED→COMPLETE_MSG phase={:02x}", cmd_phase); state.queue_interrupt(Some(command_phase::COMPLETE_MSG), scsi_status::DISCONNECT); fire_irq = true; } @@ -600,12 +547,6 @@ impl Wd33c93a { state.update_irq(); } - wdt!("R REG[{:02x}] -> {:02x} (phase={:02x} stat={:02x} asr={:02x})", - ar, val, - state.regs[regs::COMMAND_PHASE as usize], - state.regs[regs::SCSI_STATUS as usize], - state.asr); - // Auto-increment for registers except COMMAND (0x18), DATA (0x19), AUX_STATUS (0x1F) if ar != regs::COMMAND && ar != regs::AUX_STATUS_DIRECT { state.ar = (ar + 1) & 0x1F; @@ -640,7 +581,6 @@ impl Wd33c93a { if addr == 0 { // Write AR (Address Register) state.ar = val & 0x1F; - wdt!("W AR <- {:02x}", val); dlog!(state.log_module(), "WD33C93A({}): Write AR <- {:02x}", state.id, val); state.last_read_asr = None; state.last_read_reg = None; @@ -649,16 +589,6 @@ impl Wd33c93a { // Write register pointed to by AR let ar = state.ar & 0x1F; - { - let label = match ar { - regs::DATA => "DATA", - regs::COMMAND => "COMMAND", - regs::AUX_STATUS_DIRECT => "ASR_DIR", - _ => "REG", - }; - wdt!("W {}[{:02x}] <- {:02x} (phase={:02x})", - label, ar, val, state.regs[regs::COMMAND_PHASE as usize]); - } dlog!(state.log_module(), "WD33C93A({}): Write Reg {:02x} <- {:02x}", state.id, ar, val); state.last_read_asr = None; state.last_read_reg = None; @@ -854,7 +784,7 @@ impl Device for Wd33c93a { fn register_commands(&self) -> Vec<(String, String)> { vec![ - ("scsi".to_string(), "SCSI: scsi regs | scsi status | scsi armwait [reset] | scsi dayna | scsi wdt [N] | scsi wdt file | scsi eject | scsi add | scsi list | scsi del | scsi next | scsi defer ".to_string()), + ("scsi".to_string(), "SCSI: scsi regs | scsi status | scsi armwait [reset] | scsi dayna | scsi eject | scsi add | scsi list | scsi del | scsi next | scsi defer ".to_string()), ("cow".to_string(), "COW overlay: cow status | cow commit [id] | cow reset [id]".to_string()), ] } @@ -873,45 +803,6 @@ impl Device for Wd33c93a { ARM_WAITS.report(&mut *writer); return Ok(()); } - Some("wdt") => { - #[cfg(feature = "developer")] { - // "scsi wdt [N]" — dump last N entries to console - // "scsi wdt file " — dump entire ring to file - let file_mode = args.get(1).copied() == Some("file"); - if file_mode { - let path = args.get(2).ok_or_else(|| "Usage: scsi wdt file ".to_string())?; - let mut f = std::fs::File::create(path) - .map_err(|e| format!("Cannot create {}: {}", path, e))?; - let ring = WDT_RING.lock(); - for (seq, msg, cnt) in ring.entries.iter() { - if *cnt == 1 { - writeln!(f, "WDT {:8} {}", seq, msg).unwrap(); - } else { - writeln!(f, "WDT {:8} {} (x{})", seq, msg, cnt).unwrap(); - } - } - writeln!(f, "WDT_DUMP_END (total_seen={})", WDT_SEQ.load(Ordering::Relaxed)).unwrap(); - drop(ring); - writeln!(writer, "WDT ring written to {}", path).unwrap(); - } else { - let n: Option = args.get(1).and_then(|s| s.parse().ok()); - let ring = WDT_RING.lock(); - let entries = &ring.entries; - let skip = n.map(|n| entries.len().saturating_sub(n)).unwrap_or(0); - for (seq, msg, cnt) in entries.iter().skip(skip) { - if *cnt == 1 { - writeln!(writer, "WDT {:8} {}", seq, msg).unwrap(); - } else { - writeln!(writer, "WDT {:8} {} (x{})", seq, msg, cnt).unwrap(); - } - } - writeln!(writer, "(total_seen={})", WDT_SEQ.load(Ordering::Relaxed)).unwrap(); - } - } - #[cfg(not(feature = "developer"))] - writeln!(writer, "WDT ring not available (build with --features developer)").unwrap(); - return Ok(()); - } Some("regs") => { let state = self.state.lock(); let r = &state.regs; @@ -969,7 +860,7 @@ impl Device for Wd33c93a { writeln!(writer, "SCSI deferred interrupts {}", if val { "enabled" } else { "disabled" }).unwrap(); return Ok(()); } - _ => return Err(format!("Usage: {} | scsi regs | scsi wdt [N] | scsi defer ", crate::scsi_monitor::SCSI_USAGE)), + _ => return Err(format!("Usage: {} | scsi regs | scsi defer ", crate::scsi_monitor::SCSI_USAGE)), } } if cmd == "cow" { @@ -1093,10 +984,6 @@ impl Wd33c93aState { self.last_read_asr = Some(val); } self.last_read_reg = None; - wdt!("R ASR -> {:02x} (phase={:02x} stat={:02x})", - val, - self.regs[regs::COMMAND_PHASE as usize], - self.regs[regs::SCSI_STATUS as usize]); val } @@ -1112,7 +999,7 @@ impl Wd33c93aState { self.asr = val; let new_int = self.asr & asr::INT; if new_int != old_int { - wdt!("INT_LINE {} (asr={:02x})", + dlog_dev!(self.log_module(), "INT_LINE {} (asr={:02x})", if new_int != 0 { "ASSERT" } else { "DEASSERT" }, self.asr); if let Some(irq) = &self.irq { irq.set(new_int != 0); } } @@ -1139,7 +1026,7 @@ impl Wd33c93aState { // update_irq, giving wd33c93_loop time to exit before INT fires. self.update_asr(asr::CIP | asr::DBR, asr::INT); crate::pf_instant!(crate::perfetto::events::SCSI_INT, status); - wdt!("QUEUE_IRQ phase={:02x} stat={:02x} deferred={} (fifo_remaining={})", + dlog_dev!(self.log_module(), "QUEUE_IRQ phase={:02x} stat={:02x} deferred={} (fifo_remaining={})", self.regs[regs::COMMAND_PHASE as usize], status, deferred, self.irq_fifo.len()); true } else { @@ -1243,7 +1130,7 @@ impl Wd33c93aState { && self.xfer_data.is_empty() { dlog!(self.log_module(), "WD33C93A({}): SELECT_ATN_XFER conclude (PH_DATA=0x46)", self.id); - wdt!("CONCLUDE tgt={} status={:02x} pending_data={} xfer_data={} phase={:02x}", self.target_id, self.pending_status, self.pending_data.len(), self.xfer_data.len(), self.regs[regs::COMMAND_PHASE as usize]); + dlog_dev!(self.log_module(), "CONCLUDE tgt={} status={:02x} pending_data={} xfer_data={} phase={:02x}", self.target_id, self.pending_status, self.pending_data.len(), self.xfer_data.len(), self.regs[regs::COMMAND_PHASE as usize]); self.regs[regs::TARGET_LUN as usize] = self.pending_status; self.queue_interrupt(Some(command_phase::COMPLETE_MSG), scsi_status::SELECT_TRANSFER_SUCCESS); return; @@ -1294,7 +1181,7 @@ impl Wd33c93aState { } } // Transfer complete — raise final completion interrupt - wdt!("CONCLUDE tgt={} status={:02x} (resume path)", self.target_id, self.pending_status); + dlog_dev!(self.log_module(), "CONCLUDE tgt={} status={:02x} (resume path)", self.target_id, self.pending_status); self.regs[regs::TARGET_LUN as usize] = self.pending_status; self.queue_interrupt(Some(command_phase::COMPLETE_MSG), scsi_status::SELECT_TRANSFER_SUCCESS); return; @@ -1302,7 +1189,7 @@ impl Wd33c93aState { if !self.bus.has_target(self.target_id as u8) { dlog!(self.log_module(), "WD33C93A({}): No device at target {}, timing out", self.id, self.target_id); - wdt!("SEL_TIMEO tgt={} cmd={:02x} asr={:02x}", self.target_id, cmd, self.asr); + dlog_dev!(self.log_module(), "SEL_TIMEO tgt={} cmd={:02x} asr={:02x}", self.target_id, cmd, self.asr); // First interrupt (0x42): consumed by selectbus's SBIC_WAIT(INT) poll. // Second interrupt (0x41 DISC): consumed by wd33c93_poll's wd33c93_loop // call, which handles DISC via nextstate → scsidone → ITSDONE set. @@ -1349,7 +1236,7 @@ impl Wd33c93aState { // SELECT (no ATN) goes straight to CMD phase in one interrupt. if cmd == cmd::SELECT_ATN { dlog!(self.log_module(), "WD33C93A({}): SELECT_ATN → 0x11 then 0x8E", self.id); - wdt!("SEL_ATN tgt={}", self.target_id); + dlog_dev!(self.log_module(), "SEL_ATN tgt={}", self.target_id); self.queue_interrupt(Some(command_phase::SELECTED), scsi_status::SELECT_SUCCESS); self.queue_interrupt(None, scsi_status::REQ_SEND_MSG_OUT); } else { @@ -1431,12 +1318,12 @@ impl Wd33c93aState { command_phase::TRANSFER_COUNT => { if !self.pending_data.is_empty() { let data = std::mem::take(&mut self.pending_data); - wdt!("CONSUME tgt={} pending_data=0x{:x} bytes CTRL={:02x} use_dma={} phase={:02x}", self.target_id, data.len(), self.regs[regs::CONTROL as usize], self.use_dma(), self.regs[regs::COMMAND_PHASE as usize]); + dlog_dev!(self.log_module(), "CONSUME tgt={} pending_data=0x{:x} bytes CTRL={:02x} use_dma={} phase={:02x}", self.target_id, data.len(), self.regs[regs::CONTROL as usize], self.use_dma(), self.regs[regs::COMMAND_PHASE as usize]); if self.use_dma() { // DMA path: CONTROL register now valid, driver has set up DMA. dlog!(self.log_module(), "WD33C93A({}): XFER_INFO DATA_IN DMA, {} bytes", self.id, data.len()); if !self.send_data_chunked(data, 0, dma) { - eprintln!("WD33C93A: send_data_chunked paused"); + crate::notice!((), "WD33C93A: send_data_chunked paused"); return; // paused mid-chunk, interrupt already raised } self.regs[regs::TARGET_LUN as usize] = self.pending_status; @@ -1708,12 +1595,12 @@ impl Wd33c93aState { self.pending_status = response.status; self.pending_msg = 0x00; if !self.pending_data.is_empty() { - eprintln!("WD33C93A: WARNING pending_data not empty ({} bytes) when staging new response!", self.pending_data.len()); + crate::notice!((), "WD33C93A: WARNING pending_data not empty ({} bytes) when staging new response!", self.pending_data.len()); } self.pending_data = response.data; self.set_transfer_count(self.pending_data.len() as u32); dlog!(self.log_module(), "WD33C93A({}): DATA_IN 0x{:x} bytes staged, raising TRANSFER_DATA_IN", self.id, self.pending_data.len()); - wdt!("STAGE tgt={} pending_data=0x{:x} bytes tc=0x{:x}", self.target_id, self.pending_data.len(), self.get_transfer_count()); + dlog_dev!(self.log_module(), "STAGE tgt={} pending_data=0x{:x} bytes tc=0x{:x}", self.target_id, self.pending_data.len(), self.get_transfer_count()); self.queue_interrupt(Some(command_phase::TRANSFER_COUNT), scsi_status::TRANSFER_DATA_IN); return; } @@ -1728,13 +1615,13 @@ impl Wd33c93aState { if auto_mode { // IRIX/PROM: auto mode expects S_XFERRED (0x16) directly after completion. - wdt!("CONCLUDE tgt={} status={:02x} (auto) phase={:02x}", self.target_id, self.pending_status, self.regs[regs::COMMAND_PHASE as usize]); + dlog_dev!(self.log_module(), "CONCLUDE tgt={} status={:02x} (auto) phase={:02x}", self.target_id, self.pending_status, self.regs[regs::COMMAND_PHASE as usize]); self.regs[regs::TARGET_LUN as usize] = self.pending_status; self.queue_interrupt(Some(command_phase::COMPLETE_MSG), scsi_status::SELECT_TRANSFER_SUCCESS); } else { // NetBSD/OpenBSD manual mode: signal STATUS phase; driver's nextstate STATUS case // calls xferdone() which then issues SELECT_ATN_XFER(cmd_phase=0x46) → our conclude. - wdt!("STATUS_IN tgt={} status={:02x} phase={:02x}", self.target_id, self.pending_status, self.regs[regs::COMMAND_PHASE as usize]); + dlog_dev!(self.log_module(), "STATUS_IN tgt={} status={:02x} phase={:02x}", self.target_id, self.pending_status, self.regs[regs::COMMAND_PHASE as usize]); self.regs[regs::TARGET_LUN as usize] = self.pending_status; // deferred=true: worker clears CIP and spins 10000 cycles before asserting INT, // giving wd33c93_loop time to exit before STATUS_IN fires. @@ -1758,7 +1645,7 @@ impl Wd33c93aState { /// UNEXPECTED_RECV_DATA interrupt so IRIX's unex_info() can re-arm for the next chunk. fn send_data_chunked(&mut self, data: Vec, offset: usize, dma: Option<&dyn DmaClient>) -> bool { dlog!(self.log_module(), "WD33C93A({}): Sending 0x{:x} bytes via DMA (offset=0x{:x})", self.id, data.len() - offset, offset); - wdt!("DMA_OUT start: 0x{:x} bytes (offset=0x{:x})", data.len() - offset, offset); + dlog_dev!(self.log_module(), "DMA_OUT start: 0x{:x} bytes (offset=0x{:x})", data.len() - offset, offset); if let Some(dma_dev) = dma { let total = data.len(); let last_idx = total.saturating_sub(1); @@ -1803,13 +1690,13 @@ impl Wd33c93aState { self.xfer_data = data; self.xfer_offset = i; self.xfer_direction_in = true; - wdt!("DMA_OUT pause: EOX={} refused={} at offset=0x{:x}", st.eox(), st.refused(), i); + dlog_dev!(self.log_module(), "DMA_OUT pause: EOX={} refused={} at offset=0x{:x}", st.eox(), st.refused(), i); self.queue_interrupt(Some(command_phase::TRANSFER_COUNT), scsi_status::UNEXPECTED_SEND_DATA); return false; } } } - wdt!("DMA_OUT done"); + dlog_dev!(self.log_module(), "DMA_OUT done"); true } @@ -1823,7 +1710,7 @@ impl Wd33c93aState { fn receive_data_chunked_from(&mut self, total: usize, mut data: Vec, dma: Option<&dyn DmaClient>) -> Option> { dlog!(self.log_module(), "WD33C93A({}): Receiving 0x{:x} bytes via DMA (have=0x{:x})", self.id, total - data.len(), data.len()); - wdt!("DMA_IN start: 0x{:x} bytes (have=0x{:x})", total - data.len(), data.len()); + dlog_dev!(self.log_module(), "DMA_IN start: 0x{:x} bytes (have=0x{:x})", total - data.len(), data.len()); if let Some(dma_dev) = dma { while data.len() < total { match dma_dev.read() { @@ -1836,7 +1723,7 @@ impl Wd33c93aState { let pause = st.eox() && data.len() < total; if pause { dlog!(self.log_module(), "WD33C93A({}): EOX at offset=0x{:x}, remaining=0x{:x} — pausing", self.id, data.len(), total - data.len()); - wdt!("DMA_IN pause(EOX): at offset=0x{:x} remaining=0x{:x}", data.len(), total - data.len()); + dlog_dev!(self.log_module(), "DMA_IN pause(EOX): at offset=0x{:x} remaining=0x{:x}", data.len(), total - data.len()); self.xfer_data = data; self.xfer_offset = total; // store total as sentinel; xfer_data.len() is progress self.xfer_direction_in = false; @@ -1852,7 +1739,7 @@ impl Wd33c93aState { // (NetBSD: SET_SBIC_cmd then sc_dmago on same CPU thread). // Wait up to 100ms for the CPU thread to call dmago, woken // by the arming itself (see send_data_chunked). - wdt!("DMA_IN wait: channel not yet active"); + dlog_dev!(self.log_module(), "DMA_IN wait: channel not yet active"); let start = std::time::Instant::now(); let deadline = start + std::time::Duration::from_millis(100); let mut got = false; @@ -1875,7 +1762,7 @@ impl Wd33c93aState { self.decrement_transfer_count(); let pause = st.eox() && data.len() < total; if pause { - wdt!("DMA_IN pause(EOX after wait): offset=0x{:x}", data.len()); + dlog_dev!(self.log_module(), "DMA_IN pause(EOX after wait): offset=0x{:x}", data.len()); self.xfer_data = data; self.xfer_offset = total; self.xfer_direction_in = false; @@ -1889,14 +1776,14 @@ impl Wd33c93aState { if !got { ARM_WAITS.record(polls, start.elapsed(), false); dlog!(self.log_module(), "WD33C93A({}): DMA channel still not active after 100ms — giving up", self.id); - wdt!("DMA_IN wait TIMEOUT: channel never became active"); + dlog_dev!(self.log_module(), "DMA_IN wait TIMEOUT: channel never became active"); break; } // Successfully got first byte — continue outer loop } else { // Mid-transfer: chain exhausted early — pause for IRIX resume dlog!(self.log_module(), "WD33C93A({}): EOX at offset=0x{:x}, remaining=0x{:x} — pausing", self.id, data.len(), remaining); - wdt!("DMA_IN pause(inactive mid-xfer): offset=0x{:x} remaining=0x{:x}", data.len(), remaining); + dlog_dev!(self.log_module(), "DMA_IN pause(inactive mid-xfer): offset=0x{:x} remaining=0x{:x}", data.len(), remaining); self.xfer_data = data; self.xfer_offset = total; self.xfer_direction_in = false; @@ -1914,7 +1801,7 @@ impl Wd33c93aState { data.push(self.fifo.pop_front().unwrap_or(0)); } } - wdt!("DMA_IN done: 0x{:x} bytes", total); + dlog_dev!(self.log_module(), "DMA_IN done: 0x{:x} bytes", total); Some(data) } diff --git a/src/devlog.rs b/src/devlog.rs index 7c181e708..f3ff9a2ae 100644 --- a/src/devlog.rs +++ b/src/devlog.rs @@ -1,11 +1,13 @@ +use std::collections::{hash_map::DefaultHasher, HashMap}; use std::fmt; -use std::fs::File; -use std::io::{BufWriter, Write}; +use std::hash::{BuildHasher, BuildHasherDefault}; +use std::io::Write; use std::sync::Arc; -use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use parking_lot::Mutex; use crate::config::MachineConfig; use crate::topology::{DevicePlacement, SlotPoints}; +use crate::trace_writer::TraceWriter; use crate::traits::Device; /// The bit of event `name` in a module's `EVENTS` table; a name the table lacks fails the build. @@ -23,19 +25,19 @@ pub const fn event(names: &[&str], name: &str) -> u32 { panic!("no such event") } -/// One module's trace state: a bit per named event (all clear is off) and its file sink. +/// One module's trace state: a bit per named event (all clear is off) and whether its lines go to the file. struct Point { name: &'static str, events: &'static [&'static str], /// Every site is `dlog_dev!`, so nothing prints without `--features developer`. dev: bool, on: AtomicU32, - file: Mutex)>>, + to_file: AtomicBool, } impl Point { const fn new(name: &'static str, events: &'static [&'static str], dev: bool) -> Self { - Self { name, events, dev, on: AtomicU32::new(0), file: Mutex::new(None) } + Self { name, events, dev, on: AtomicU32::new(0), to_file: AtomicBool::new(false) } } } @@ -260,9 +262,11 @@ pub struct DevLog { /// All currently connected monitor clients (and any host sinks like stderr). /// Entries are pruned on write error. writers: Mutex>, + /// The file the modules `log POINTS file PATH` named write to. + file: Mutex>, } -pub static DEVLOG: DevLog = DevLog { writers: Mutex::new(Vec::new()) }; +pub static DEVLOG: DevLog = DevLog { writers: Mutex::new(Vec::new()), file: Mutex::new(None) }; pub fn devlog() -> &'static DevLog { &DEVLOG } @@ -321,16 +325,34 @@ impl DevLog { if !writers.iter().any(|w| Arc::ptr_eq(w, sink)) { writers.push(sink.clone()); } } - /// Open a file sink for a module. - pub fn set_file(&self, m: LogModule, path: &str) -> Result<(), String> { - let file = File::create(path).map_err(|e| format!("Cannot open {}: {}", path, e))?; - *m.point().file.lock() = Some((path.to_string(), BufWriter::new(file))); + /// Send the modules' lines to the file at `path` instead of the monitor. One file at a time. + pub fn set_file(&self, mods: &[LogModule], path: &str) -> Result<(), String> { + let mut file = self.file.lock(); + match &*file { + Some(f) if f.path != path => return Err(format!("log file is {}; `log all file off` first", f.path)), + Some(_) => {} + None => *file = Some(TraceWriter::create(path).map_err(|e| format!("Cannot open {path}: {e}"))?), + } + for m in mods { m.point().to_file.store(true, Ordering::Relaxed); } Ok(()) } - /// Close a module's file sink (output reverts to monitor broadcast). + /// Return a module's lines to the monitor; the file closes with its last module. pub fn clear_file(&self, m: LogModule) { - *m.point().file.lock() = None; + m.point().to_file.store(false, Ordering::Relaxed); + if !LogModule::ALL.iter().any(|m| m.point().to_file.load(Ordering::Relaxed)) { + *self.file.lock() = None; + } + } + + /// Wait until every line written so far is in the file. + pub fn sync(&self) { + if let Some(f) = &mut *self.file.lock() { f.sync(); } + } + + /// `sync` for a panic hook: skipped when the panic came from inside a write. + pub fn try_sync(&self) { + if let Some(f) = self.file.try_lock().as_deref_mut().and_then(Option::as_mut) { f.sync(); } } /// Write a log message unconditionally — bypasses the module enabled flag. @@ -350,14 +372,14 @@ impl DevLog { #[cold] #[inline(never)] pub fn write(&self, m: LogModule, args: fmt::Arguments) { - let msg = fmt::format(args); - - // File sink takes priority — write there and return. - if let Some((_, f)) = &mut *m.point().file.lock() { - let _ = writeln!(f, "[{}] {}", m.name(), msg); - let _ = f.flush(); - return; + // The file takes priority over the monitor. + if m.point().to_file.load(Ordering::Relaxed) { + if let Some(f) = &mut *self.file.lock() { + f.line(format_args!("[{}] {}", m.name(), args)); + return; + } } + let msg = fmt::format(args); // Broadcast to all connected monitor clients; prune dead connections. self.writers.lock().retain(|w| { @@ -413,6 +435,38 @@ macro_rules! dlog_unconditional { }; } +/// How many times each (call site, key) has said its notice. +static NOTICES: Mutex>> = + Mutex::new(HashMap::with_hasher(BuildHasherDefault::new())); + +/// The count of this notice at `site` and `key`, if it is due: the first four, then each power of two. +pub fn notice_due(site: (&'static str, u32), key: impl std::hash::Hash) -> Option { + let key = BuildHasherDefault::::default().hash_one(key); + let mut seen = NOTICES.lock(); + if seen.len() >= 4096 { seen.clear(); } + let n = seen.entry((site.0, site.1, key)).or_insert(0); + *n += 1; + (*n <= 4 || n.is_power_of_two()).then_some(*n) +} + +/// Say a notice on stderr, with its count once it repeats. +#[cold] +#[inline(never)] +pub fn notice_say(args: fmt::Arguments, n: u64) { + if n > 1 { eprintln!("{args} (#{n})") } else { eprintln!("{args}") } +} + +/// Say on stderr, in every build, a message a guest can trigger repeatedly: the first four times per +/// call site and `key` (`()` for a site with one thing to say), then at each power of two. +#[macro_export] +macro_rules! notice { + ($key:expr, $($arg:tt)*) => { + if let Some(n) = $crate::devlog::notice_due((file!(), line!()), $key) { + $crate::devlog::notice_say(format_args!($($arg)*), n); + } + }; +} + /// Hot-path log. Compiles to nothing in non-developer (release) builds. #[macro_export] macro_rules! dlog_dev { @@ -447,19 +501,22 @@ impl Device for LogDevice { \x20 a slot (scsi0/t1, xio15/pci0/2) selects its devices' modules; shared ones whole\n\ \x20 modules: {}{}\n\ \x20 [DEV] = some of a module's messages appear only in a --features developer build", modules.join(" "), events), - )] + ), ("display".to_string(), "display verify (compose the frames a board would skip and compare them; slows the display)".to_string())] } fn execute_command(&self, cmd: &str, args: &[&str], mut writer: Box) -> Result<(), String> { + if cmd == "display" { return crate::display::verify::command(args); } if cmd != "log" { return Err(format!("Unknown command: {}", cmd)); } let arg0 = args.get(0).copied().unwrap_or(""); let dl = &DEVLOG; if arg0 == "status" { + dl.sync(); // the file lags until written out; status is where a user looks + let file = dl.file.lock().as_ref().map(|f| f.path.clone()).unwrap_or_default(); writeln!(writer, "{:<8} {:<24} file", "module", "events").map_err(|e| e.to_string())?; writeln!(writer, "{}", "-".repeat(60)).map_err(|e| e.to_string())?; for &m in LogModule::ALL { - let path = m.point().file.lock().as_ref().map(|(p, _)| p.clone()).unwrap_or_default(); + let path = if m.point().to_file.load(Ordering::Relaxed) { &file[..] } else { "" }; writeln!(writer, "{:<8} {:<24} {}", m.name(), m.describe(devlog_mask(m)), path) .map_err(|e| e.to_string())?; } @@ -475,10 +532,9 @@ impl Device for LogDevice { for (m, _) in parse(arg0)? { dl.clear_file(m); } } "file" => { - if parse(arg0)?.len() != 1 { - return Err("log file takes one module".to_string()); - } - for m in dl.select(arg0, true)? { dl.set_file(m, arg2)?; } + let mods: Vec<_> = parse(arg0)?.into_iter().map(|(m, _)| m).collect(); + dl.set_file(&mods, arg2)?; + dl.select(arg0, true)?; } _ => return Err("Usage: log > | log status".to_string()), } @@ -609,7 +665,7 @@ mod tests { /// `log ... on` with no monitor client (a `[debug] startup` command) reaches stderr, as `--log` does. #[test] fn log_on_with_no_sink_adds_stderr() { - let dl = DevLog { writers: Mutex::new(Vec::new()) }; + let dl = DevLog { writers: Mutex::new(Vec::new()), file: Mutex::new(None) }; dl.enable("heart").unwrap(); dl.add_stderr(); assert_eq!(dl.writers.lock().len(), 1); @@ -647,11 +703,29 @@ mod tests { assert!(bad.is_empty(), "{bad:#?}"); } - /// One file cannot take two modules: their writers would overwrite each other. + /// A notice is said the first four times, then at powers of two, and a different key starts over. + #[test] + fn a_notice_is_said_a_few_times_and_the_next_key_still_is() { + let said: Vec = (0..10).filter_map(|_| notice_due(("test", 1), ("read32", 0x1000u32))).collect(); + assert_eq!(said, [1, 2, 3, 4, 8]); + assert_eq!(notice_due(("test", 1), ("read32", 0x1004u32)), Some(1)); + } + + /// Two modules share one file, in order; an idle tail reaches it on `sync`, and a second path is refused. #[test] - fn a_file_takes_one_module() { - let r = LogDevice.execute_command("log", &["net,heart", "file", "/nonexistent/x"], Box::new(std::io::sink())); - assert!(r.unwrap_err().contains("one module")); + fn modules_share_one_file() { + let path = std::env::temp_dir().join(format!("devlog_{}.txt", std::process::id())); + let path = path.to_str().unwrap(); + let dl = DevLog { writers: Mutex::new(Vec::new()), file: Mutex::new(None) }; + dl.set_file(&[LogModule::Net, LogModule::Seeq], path).unwrap(); + dl.write(LogModule::Net, format_args!("a")); + dl.write(LogModule::Seeq, format_args!("b")); + assert!(dl.set_file(&[LogModule::Net], "/nonexistent/x").unwrap_err().starts_with("log file is ")); + dl.sync(); + assert_eq!(std::fs::read_to_string(path).unwrap(), "[net] a\n[seeq] b\n"); + dl.clear_file(LogModule::Net); + dl.clear_file(LogModule::Seeq); + let _ = std::fs::remove_file(path); } /// A monitor connection's log sink holds a handle on its socket. One left diff --git a/src/disp.rs b/src/disp.rs index c6f0ecac6..97d81894c 100644 --- a/src/disp.rs +++ b/src/disp.rs @@ -301,8 +301,8 @@ impl Rex3Screen { Some(gap) if cursor_on && self.cursor_gap_warned != Some(gap) => { self.cursor_gap_warned = Some(gap); match gap { - Some(d) => println!("Rex3: WARNING: hpos_to_visible={d} is out of the cursor adjustment's range, using 11"), - None => println!("Rex3: WARNING: HPOS leading edge not found in the video table, using cursor_x_adjust=11"), + Some(d) => eprintln!("Rex3: WARNING: hpos_to_visible={d} is out of the cursor adjustment's range, using 11"), + None => eprintln!("Rex3: WARNING: HPOS leading edge not found in the video table, using cursor_x_adjust=11"), } } None => self.cursor_gap_warned = None, diff --git a/src/display/verify.rs b/src/display/verify.rs index 03a19d4e1..a7652fd91 100644 --- a/src/display/verify.rs +++ b/src/display/verify.rs @@ -1,5 +1,5 @@ //! A check of the boards' "nothing changed" verdicts, for development: -//! with `IRIS_DISPLAY_VERIFY=1` a frame a board would have left standing is +//! with `display verify on` a frame a board would have left standing is //! composed anyway and compared with the one on screen. A difference is a //! change the board did not see. //! @@ -8,11 +8,23 @@ //! One the next verdict still does not report is missed. use crate::disp::{Rex3Screen, FB_STRIDE}; +use std::sync::atomic::{AtomicBool, Ordering}; -/// Whether verdicts are checked (`IRIS_DISPLAY_VERIFY` set and not 0). +static ON: AtomicBool = AtomicBool::new(false); + +/// Whether verdicts are checked (`display verify on`). pub fn on() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("IRIS_DISPLAY_VERIFY").is_ok_and(|v| v != "0" && !v.is_empty())) + ON.load(Ordering::Relaxed) +} + +/// The monitor's `display verify on|off`. +pub fn command(args: &[&str]) -> Result<(), String> { + match args { + ["verify", "on"] => ON.store(true, Ordering::Relaxed), + ["verify", "off"] => ON.store(false, Ordering::Relaxed), + _ => return Err("Usage: display verify ".to_string()), + } + Ok(()) } /// One head's check. diff --git a/src/ip32/tests.rs b/src/ip32/tests.rs index 73558541f..a39833415 100644 --- a/src/ip32/tests.rs +++ b/src/ip32/tests.rs @@ -289,23 +289,6 @@ fn the_time_counter_runs_at_66_67_mhz() { assert_eq!(c.read64((CRIME_BASE + crime_reg::TIME) as u64).data, 200_000, "3 ms of a 66.67 MHz clock"); } -#[test] -#[cfg(not(feature = "lightning"))] -fn the_interrupt_log_records_only_while_on() { - let c = Crime::new(std::sync::Arc::new(MaceUst::new(crate::clock::Clock::stepped()))); - let mask = (CRIME_BASE + crime_reg::INTMASK) as u64; - c.write64(mask, 1); - assert_eq!(c.irqlog_text(), "", "off until asked for"); - c.set_irqlog(true).unwrap(); - // A 32-bit store merges into the register without reading it as the - // guest: one write, no read. - c.write32(mask + 4, 2); - assert_eq!(c.irqlog_text(), format!("W {:#04x} 0x0000000000000002\n", crime_reg::INTMASK)); - c.set_irqlog(false).unwrap(); - let _ = c.read64(mask); - assert_eq!(c.irqlog_text().lines().count(), 1, "stopped"); -} - #[test] #[cfg(not(feature = "lightning"))] fn every_touched_register_is_recorded_once_per_direction() { diff --git a/src/ip32_machine.rs b/src/ip32_machine.rs index 04fa261e3..7611e86a3 100644 --- a/src/ip32_machine.rs +++ b/src/ip32_machine.rs @@ -1002,7 +1002,7 @@ impl Device for O2Control { fn register_commands(&self) -> Vec<(String, String)> { vec![("o2".to_string(), "O2 diagnostics: o2 status | pixel X Y | pc | regs | peek ADDR LEN PATH | \ - scsi PATH | unmapped | ps2log PATH | crimelog PATH".to_string())] + scsi PATH | unmapped | ps2log PATH".to_string())] } fn execute_command(&self, cmd: &str, args: &[&str], mut w: Box) -> Result<(), String> { @@ -1024,12 +1024,6 @@ fn control_command(bus: &Ip32Bus, cmd: &str, arg: &str, rgba: &mut [u8]) -> Stri LAST_PC.load(Ordering::Relaxed), BATCHES.load(Ordering::Relaxed) ), - // `crimelog PATH`: the guest's recent CRIME interrupt-register - // accesses, oldest first. - "crimelog" => match std::fs::write(arg.trim(), bus.crime.regs.irqlog_text()) { - Ok(()) => "ok".into(), - Err(e) => format!("err {e}"), - }, "regs" => { let r: Vec = LAST_REGS.iter().map(|v| v.load(Ordering::Relaxed)).collect(); let mut s = format!("ok pc 0x{:08x}", LAST_PC.load(Ordering::Relaxed)); diff --git a/src/scsi.rs b/src/scsi.rs index b45f3a7ae..fcb43513e 100644 --- a/src/scsi.rs +++ b/src/scsi.rs @@ -1290,7 +1290,7 @@ impl ScsiTarget for ScsiDevice { scsi_cmd::SGI_EJECT => self.exec_sgi_eject(&req.cdb)?, scsi_cmd::SGI_HD2CDROM => self.exec_sgi_hd2cdrom(&req.cdb)?, _ => { - eprintln!("SCSI: Unimplemented command {:02x} cdb={:02x?}", req.cdb[0], &req.cdb); + crate::notice!(req.cdb[0], "SCSI: Unimplemented command {:02x} cdb={:02x?}", req.cdb[0], &req.cdb); self.check_condition(0x05, 0x20, 0x00) // Illegal Request: Invalid Command Operation Code } }; diff --git a/src/scsi_monitor.rs b/src/scsi_monitor.rs index 9c0a3ba79..ff26310a8 100644 --- a/src/scsi_monitor.rs +++ b/src/scsi_monitor.rs @@ -8,7 +8,7 @@ //! `scsi dayna`, the changer subcommands (`eject`, `add`, `list`, `del`, //! `next`), the whole of `cow`, and the [`crate::workstation::DiscChanger`] //! operations the window, the CI socket and iris-gui use. What is one chip's -//! alone (`scsi regs`, the WD's `wdt`, `defer` and `debug`) stays with the +//! alone (`scsi regs`, the WD's `defer` and `debug`) stays with the //! chip, which tries [`scsi_subcommand`] first and handles the rest itself. use std::io::Write; diff --git a/src/workstation.rs b/src/workstation.rs index 35a5f19c4..76aa6f81f 100644 --- a/src/workstation.rs +++ b/src/workstation.rs @@ -577,6 +577,7 @@ pub type MachineSlot = Arc>; /// fatal, since the process is going away either way. pub fn stop_and_flush(machine: &mut dyn Workstation, at: &str) -> Flushed { stop_flushing(machine, |m| m.stop(), |m| m.flush_disks(), at); + crate::devlog::DEVLOG.sync(); Flushed(()) } @@ -882,6 +883,7 @@ pub fn exit_process(at: &str, code: i32, stop_and_flush: impl FnOnce() -> Flushe crate::console_edit::restore_terminal(); } let Flushed(()) = stop_and_flush(); + crate::devlog::DEVLOG.sync(); if !exiting { eprintln!("iris: exit at {at} suppressed (IRIS_NO_EXIT_ON_POWEROFF)"); #[cfg(test)]