Compare commits

...
124 Commits
Author SHA1 Message Date
joevt 7503941f23 display_sdl: Replace comma with semi-colons. 2026-11-26 10:22:20 -07:00
joevt 293bb0018b mpc106: Different slots for different machines. 2026-11-26 08:36:55 -07:00
joevt ba62201573 videoctrl: Init refresh_rate. 2026-11-23 08:12:24 -07:00
joevt 94ffe31dda videoctrl: pixel_clock should be double.
So that it can represent pixel clocks exactly above 16.777216 MHz.
2026-11-23 08:12:21 -07:00
dingusdev d0fb711842 Slight update on AI rules 2026-11-10 00:09:51 +00:00
Maxim Poliakovski 090e852ecc dec21154: use constants for PCI class ID and revision. 2026-11-05 23:43:07 +01:00
Maxim Poliakovski b9d3456c44 mpc106: use named constants for PCI class ID and revision. 2026-11-04 16:57:33 +01:00
Maxim Poliakovski 7384b16548 PCI class ID for MacIO ASICs is now a named constant. 2026-11-04 16:21:15 +01:00
Maxim Poliakovski 8f6c4423e7 Move common PCI definitions to pcidefs.h 2026-11-03 15:25:56 +01:00
Mihai Parparita a0cc486580 mpc106: remove duplicated properties
`pci_J12` causes a duplicated property warning, and makes the
`AtiMach64Gx` default value from machineyosemite.cpp not work. Since
it's a Yosemite-only slot, it seems reasonable for only the machine
to define.

Also removes the similarly duplicted `pci_GPU` property, which had
already been commented out in 40c82785c9.
2026-11-01 19:21:23 -07:00
joevt 810c3f9dd3 platinum: Write protect read-only bits. 2026-10-31 19:56:07 -07:00
joevt 3ad54485ff platinum: Default gfxmem_size to 4 MB.
So we can get all the graphics modes without adding to the command line.

We don't default to max RAM because adding RAM doesn't add more
capabilities and the top end is much greater than with VRAM.
2026-10-31 18:59:27 -07:00
joevt 64d4654e2e platinum: Add comment for cpu_id calculation. 2026-10-31 18:55:31 -07:00
joevt f22a333ae7 platinum: Fix address in unmapped log message.
offset is relative to VRAM_REGION_BASE, not whatever is in fb_addr.
2026-10-31 16:33:46 -07:00
joevt fd1b1bb8f1 control: Update display only if base changes. 2026-10-30 21:05:15 -07:00
joevt dd5ecee284 control: Fix indent. 2026-10-30 18:24:29 -07:00
joevt f084bae478 control: Remove extra spaces. 2026-10-30 18:24:21 -07:00
joevt beaae745bb ppcmmu: Add size to MapDmaResult.
A DMA range might span more than one region. Return info for the first
region only.
2026-10-25 15:33:50 -07:00
joevt 1b63628e58 ppcopcodes: Overflow optional operation omit. 2026-10-23 17:27:09 -07:00
joevt 7a13951400 psx: Initialize class fields.
Use values from the PSX ERS document instead of leaving them random.
2026-10-21 20:26:27 -07:00
joevt 94e7bbd14a platinum: Update display only if base changes.
Corum III in BeOS sets base address often.
2026-10-20 06:17:31 -07:00
joevt 5ad23f5f88 valkyrie: Add missing display modes. 2026-10-19 07:01:34 -07:00
joevt cd2e0ad7da valkyrie: Fix display mode change detection.
The mode should change even if the display disable flag doesn't change.
2026-10-19 07:01:06 -07:00
joevt 8e03b1c52a ppcexec: Add EAR register for disassembly.
BeOS uses the EAR register. This name map is used when listing the
values of input and output registers in disassembly.
2026-10-19 06:56:12 -07:00
joevt 8cab662f6e ppcexec: Use get_virt_time_ns exclusively. 2026-10-19 06:17:30 -07:00
joevt 8dff8a4238 ppcexec: Add comment for Open Firmware illegal op. 2026-10-19 06:16:44 -07:00
Mihai Parparita 904c1b177e benchmark: Add an FPU-focused benchmark
Complement bench1's integer workload with a replay through the real FPU
opcode dispatcher. The 512 instruction and register snapshots are based
on observed FPU operations while running GLTeapot on BeOS PR1.

Report median host time per instruction and provide a checksum mode for
checking that different implementations produce the same results,
without guest boot, display updates, or timer overhead.
2026-10-16 18:13:30 -07:00
Mihai Parparita a188a15bf6 ppc: Reduce floating-point exception handling overhead
Combine the host exception checks and only clear exceptions when needed.
On Apple ARM64, use ACLE intrinsics to read and update FPSR directly,
preserving unrelated status bits. Skip these checks when FE_ALL_EXCEPT
is zero.

On an M2 Max, the FPU replay benchmark drops from 32.6 ns/instruction to
21.3 ns with combined checks and 17.9 ns with the ARM64 helpers, giving
roughly 1.5x and 1.8x throughput respectively.
2026-10-16 18:13:30 -07:00
joevt 6d8ce06052 macio: Interrupt when event gets set.
First, fix when event gets set. Previously, for emulated mode, event was
always set even if the irq_line_state is unchanged. Now, the event gets
set only when the level transitions.

For native mode, event is set only when level transitions from 0 to 1.
This remains correct behavior.

Second, call signal_cpu_int only if event changed. Previously, it was
always called even if irq_lane_state or int_event are unchanged.
2026-10-15 18:33:00 -07:00
joevt fc0d722df0 macio: Fix MIO_OHARE_ID comments.
Because this is the name of the enum.
2026-10-15 18:27:24 -07:00
joevt b6dbbe2685 macio: Clarify ack_int_common comments. 2026-10-15 07:05:03 -07:00
joevt 3430e108bd videoctrl: VBL deassert relative to assert time.
The de-assert time should be relative to expected assert time to ensure
that it occurs before next assert time.
2026-10-15 06:26:21 -07:00
joevt 5b3e4f6552 videoctrl: Add missing this. 2026-10-15 06:23:04 -07:00
Mihai Parparita 357b838ac7 macio: Keep interrupt events and CPU IRQ state consistent
Apply the Grand Central fixes from dingusdev/dingusppc#240 to O'Hare,
Heathrow, and Paddington; the Heathrow ERS shows that it expects to
have the same behavior:
- Reevaluate the CPU interrupt when either mask changes, releasing it
  if no pending events remain enabled in either bank (section 7.1).
- Keep events latched until software writes InterruptClear, even if a
  device deasserts its interrupt line or repeats an assertion (sections
  7.2.1 and 7.2.5).
- Replace writable InterruptMask2 bits instead of ORing them, allowing
  sources to be disabled while preserving the read-only IntMode bit
  (section 7.2.6).
2026-10-14 17:43:14 -07:00
Mihai Parparita 049f8b68c5 machines: repeat 4 MB ROM in 16 MB mapped space
Per the Hammerhead ERS the ROM region is 0xFF000000-0xFFFFFFFF. We were
only mapping the ROM at the uppermost 4 MB of that (0xFFC00000). The fact
that copies are returned at other addresses in that range is not
explicitly stated in the ERS, but it does appear to be emprically true.
It's also corroborated by the 9600 wiring diagram, which shows only enough
address bits for 4MB being used for the ROM.

Also does the same fix for Platinum/7200, which has the same mapping and
address bits, and adds some notes about this to the documentation.

Fixes SheepShaver in BeOS guests, which was using 0xFF000000 to get at
the hardware ROM (see https://github.com/cebix/macemu/blob/96e512bd6376e78a2869f16dcc8a9028bce5ee72/BasiliskII/src/BeOS/SheepDriver/sheep_driver.c#L454).
2026-10-14 15:46:43 -07:00
Mihai Parparita 45a4965cd5 grandcentral: Keep interrupt events and CPU IRQ state consistent
Two correctness fixes, based on the Grand Central ERS:
- Reevaluate the CPU interrupt when the mask changes, releasing it if
  no pending events remain enabled (section 6.1).
- Keep events latched until software writes InterruptClear, even if a
  device deasserts its interrupt line or repeats an assertion (section
  6.2.1).

This fixes occasional freezes on BeOS (especially in realtime mode).
Previously, the CPU interrupt could remain asserted with no enabled
events, trapping BeOS in its interrupt handler.
2026-10-14 15:32:24 -07:00
4e254fc972 viacuda: Keep timer 2 rollover and interrupt timing in sync
T2 readback wrapped after N+1 clocks, but its interrupt was scheduled
for N+3. Mac OS Microseconds could see a wrapped counter with no pending
interrupt, then clear the newly asserted interrupt by reading T2CL. The
one-shot timer would never be serviced or rearmed.

Abuse paces its intro text by repeatedly calling Microseconds until 150
ms have elapsed. This tight polling loop exposes the race. Once the
interrupt is lost, the OS stops accumulating elapsed timer periods,
while the hardware counter keeps wrapping. Microseconds then cycles
within a roughly 84 ms window instead of advancing monotonically, so the
150 ms wait can no longer complete normally. The guest keeps running,
but the text's pacing loop effectively stalls, accounting for the
reported frozen or extremely slow scrolling.

Use a shared time origin for counter readback and the N+1.5-clock
interrupt, including the initial half-clock delay. Before reading T2 or
IFR, also assert any overdue interrupt and cancel its queued callback,
so realtime reads and acknowledgments don't depend on timer polling.

Verified native Abuse intro and gameplay, native and Emscripten builds,
and 84 timer checks covering rollover, acknowledgment and overdue reads.

Co-Authored-By: joevt <[email protected]>
Co-Authored-By: Mihai Parparita <[email protected]>
2026-10-13 21:41:03 -07:00
Mihai Parparita 21c6a80e2c timermanager: Preserve phase when rescheduling overdue timers
We would reschedule timers based on their interval and the current time, which
would cause timers with the same interval to get aligned. This may be not be
desired (if a subsystem has two intentionally out-of-phase timers), so we
instead advance the timer based on its previously scheduled time and multiples
of the interval.

Not strictly necessary for the codebase as it stands today (we no longer use
two cyclic intervals for the VBL interval) but it still seems like a worthwhile
correctness improvement, if we decide to reintroduce that approach.
2026-10-13 19:17:31 -07:00
Mihai Parparita 0ea30ac041 videoctrl: Avoid two cyclic timers for VBL interval
We were relying on two separate cyclic timers for the VBL interval, but
in realtime mode we may end up falling behind in timer execution, and the exact
phase may not be preserved. In the worst case they would end up exactly aligned,
and the VBL interval would be effectively lost (the guest polls for the VBL bit
and would never see it)

Switch to only one cyclic timer, which repeatedly sets a one-shot timer for
the VBL end.
2026-10-13 19:17:31 -07:00
joevt 98421734de viacuda: Remove clock drift from T1 rearm.
Use the expected end time as the start time for the next iteration
rather than using the current time. This removes accumulative lag that
process_events might introduce.
2026-10-13 06:20:32 -07:00
joevt e52317c8b5 ppcopcodes: Reduce rA != 0 checks.
By separating (rA != 0) handling from (rA == 0 && is_601) handling.
2026-10-13 06:20:24 -07:00
Mihai Parparita 2a83f5bddc Create empty CD-ROM drives for SCSI-based machines
We only created SCSI CD-ROM drives when an image was supplied at
startup, so later insertion requests had no drive to go to. The
Beige G3 already worked because its ATAPI drive is always created.

Extend the ATAPI approach (where a `cdr_config` property defines the bus
where a CD-ROM drive should be attached) for SCSI-based machines too.
Use it to define default drive on the appropriate bus for PDM, TNT,
Catalyst, Alchemy, Gazelle, and Pippin. Supplying images at startup still
uses the existing drive allocation behavior.
2026-10-11 15:44:22 -07:00
Mihai Parparita 716254c37c Handle CD-ROM commands when no media is present
The 7300 ROM tries to read from an empty CD-ROM drive during boot.
We would try to transfer data from an unallocated buffer and crash.

Return NOT READY / MEDIUM NOT PRESENT for reads, capacity requests,
and TOC requests. Also covers the separate ATAPI READ CD path. This
matches the behavior described in ATAPI 2.6 section 8.5 and the
per-command error tables:
https://www.grix.it/UserFiles/marco.c/INF-8020.pdf
2026-10-11 15:44:22 -07:00
Mihai Parparita 325cc8ac9f ppcopcodes: Reuse operand decode helpers
Use existing helpers for more instructions instructions (twi, mtsr,
mtmsr, etc.). Prompted by the recent fix for tw - these were all correct
already, but might as well make things more uniform.
2026-10-11 15:32:26 -07:00
Mihai Parparita 5cb6d66f18 ppc: Fix reversed operands in tw opcode implementation
The manual decode swapped rA and rB. Fix thix by using the standard
`ppc_grab_regsab` decode helper.

Fixes Macintosh Common Lisp 4.2 hanging at startup (with 7.5.5 booting
using the 7500 ROM).
2026-10-11 15:32:26 -07:00
Mihai Parparita 6f87662a1d ppcexec: Avoid excessive timer polling in realtime mode
When the interpreter can run faster than realtime (depends on the
host system's performance), we would end up checking timer more
frequently.

This is because the `max_cycles` value returned by `process_events()`
was based on the absolute timer deadline converted to instruction
counts. Once `g_icycles` got ahead of that value, we would check timers
after every instruction.

Instead, use the time remaining until the next timer to schedule an
instruction batch relative to `g_icycles`, capped using the existing
500us polling interval.
2026-10-09 19:10:36 -07:00
Mihai Parparita 62793bb935 ppc: make illegal instructions more obvious
Log a warning whenever an illegal opcode exception is being raised,
since it's usually a clue that we have a correctness bug.

Just a warning (as opposed to an error) because the guest OS may handle
the exception and continue execution.
2026-10-09 19:10:02 -07:00
Mihai Parparita 4ed0282ef3 ppc: allow rA=0 for 601 integer store-update instructions
Normally rA (where the effective address is stored) cannot be 0, but the
MPC601 user manual explicitly says that it's allowed for POWER
compatibility (the update is skipped in that case).

Fixes mouse movement in Barrack under on the 6100, which would previously
stop executing because of an illegal opcode exeception being raised
(and unhandled).
2026-10-09 19:10:02 -07:00
joevt 47a9ccd73b ppcopcodes: Add parenthesis in conditional.
Makes the statement look nicer - symmetry!
2026-10-08 20:26:42 -07:00
joevt 96393c63d0 ppcopcodes: Don't redefine ppc_result_a.
It is defined by the ppc_grab_* macro.
2026-10-08 20:21:44 -07:00
Mihai Parparita a811ff8aa3 ppcexec: Use recommended Apple API for getting the realtime clock
The documentation for `mach_absolute_time` recommends replacing it with
`clock_gettime_nsec_np(CLOCK_UPTIME_RAW)`. The latter is also slightly
simpler to use (no need for initialization and a conversion step).
2026-10-08 17:57:13 -07:00
Mihai Parparita 8851daadc9 hostevents_sdl: prevent realtime toggle keyboard shortcut from reaching the guest
Matches the behavior of other internal keyboard shortcuts.
2026-10-08 17:56:05 -07:00
Mihai Parparita 90debefc2a main: allow realtime mode to be enabled at startup
Adds a --realtime CLI flag to enable realtime mode immediately at
startup.

Also tweaks documentation to mention the Control-Alt-R realtime toggle
and the relationship between the realtime mode and deterministic mode.
2026-10-08 17:56:05 -07:00
joevt 74c60fcd57 ppcopcodes: Carry calculation conditional cut. 2026-10-07 06:22:28 -07:00
joevt 8652a5b8c4 ppcopcodes: Remove blank line. 2026-10-07 06:22:01 -07:00
joevt 25eac76d26 ppcopcodes: Rename grab_ca or grab_xer to xer_ca. 2026-10-07 06:21:53 -07:00
Mihai Parparita 315e3d9f2a timermanager: Make shared TimerInfo structs safer to use
With the shared `TimerInfo` structs refactor from 529fff7d, it's easier
to accidentally enqueue the same timer multiple twice. Help the the
programmer out by logging an error if the timer is already `active` when
adding it. To also reduce the boilerplate, one-shot timers and and
cancellation automatically clear the flag.

The error could be upgraded to a CHECK_F once we're more confident that
we've fixed all of the callsites.
2026-10-06 19:08:45 -07:00
Mihai Parparita 5f111d0929 soundserver_cubeb: Avoid enqueueing the deterministic poll timer twice
Solarian II repeatedly restarts sound DMA without the stream being
closed, and thus we would end up in `SoundServer::start_out_stream`
without going through `close_out_stream`. The `add_cyclic_timer` did
call did not check if the timer was already active, and we would end up
with a duplicate entry in the timer queue, which slowdowns and other
incorrect behavior.

Fixed by checking the `active` flag, like all of the other callsites.
2026-10-06 19:08:45 -07:00
Mihai Parparita 3f070249f2 control: suppress MON_SENSE logspam during startup
When the Displays Enabler extension would load under Mac OS 7.6.1 and
the 7300 ROM, there would be several hundred ERROR level lines about
MON_SENSE register writes with unexpected values (more than 5 bits set).

These were actually harmless (they had the read-only sense input bits
6-8), tweak the mask so that they remain at level 9.
2026-10-01 18:10:00 -07:00
Mihai Parparita 13e02f7978 control: skip no-op display updates
Makes both flavors of Control enable the `draw_fb_is_dynamic` optimization,
which lets us skip SDL screen update when the the framebuffer content
has not changed.

Improve BeOS PR1 booting on the 7300 from 15.8-46s to 13.9-14.2. The
variability appears to be due to time spent in `SDL_RenderPresent`,
per https://developer.apple.com/documentation/metal/onscreen-presentation
this may block on macOS (with the Metal backend) until the next display
refresh, and we were generating a lot more frames to present before.

Also improves smoothness of the BeOS GL Teapot demo (the displayed
framerate does not change since the timer is driven by instruction
cycles, which don't change).
2026-10-01 06:25:55 -07:00
joevt 317a34a761 swim3: Add reading of Read Mode register.
This is documented in the SWIM3 ERS as:
2026-09-30 21:19:54 -07:00
dingusdev 72a33a1b8a Version 1.04c Prep 2026-09-30 18:18:04 -07:00
Mihai Parparita ab5699d7f9 control: handle reads and writes from the little-endian aperture
BeOS DR8.2 and DR8.3 use this - not handling it was causing graphical
corruption during boot.

We do the operation as usual in big endian mode (which handles the bank
logic) and then byte-swap the results. Note that the byte swapping
depends on the bit width, not the payload length (patent US5640545A
is presumed to describe some of the logic)
2026-09-30 17:03:16 -07:00
Mihai Parparita 387686aaee viacuda: Allow a specific RTC time to be set
Makes it possible to run time-limited OS versions like BeOS DR8.2
(which does not work after 1997-04-01).

This is now also used for deterministic mode (which had already been
hardcoding a 2001-03-24 RTC time).

Also document both flags in the manual.
2026-09-30 16:57:54 -07:00
Mihai Parparita 21c6e24c7c display: Refresh display when RAMDAC pixel width changes
When changing the bit depth, there are two display attributes that change: the
frame buffer pitch and the pixel width.

Mac OS (7.6.1) and BeOS (R3) do those updates in different order: Mac OS updates
the pixel width first, then the frame buffer pitch; BeOS does the opposite.

For Control and Platinum video, those are handled in separate components
(`ControlVideo`/`PlatinumCtrl` vs. `AppleRamdac`), and only the former had the
ability to trigger display configuration updates (which determines the
`convert_fb_cb` function that is selected). BeOS would thus be left with a stale
value, leading to display corruption.

To fix this, add a pixel width update callback (similar to the hardware cursor
change one) and use it to trigger a display configuration update from the
`AppleRamdac` side.
2026-09-28 06:22:03 -07:00
joevt 4d42720af9 adbkeyboard: Fix get_register_3.
The format of register 3 is incorrect. Use the adbdevice implementation.
2026-09-27 15:54:23 -07:00
joevt bf28e376ce adbdevice: Remove set_register_3 duplicate code. 2026-09-27 15:53:05 -07:00
joevt 8413e9245a dbdma: Add missing this. 2026-09-27 09:34:50 -07:00
joevt 019a15e6eb dbdma: Remove extra spaces. 2026-09-27 09:28:15 -07:00
Mihai Parparita 5b292af4d7 adbkeyboard: Improve register 2 emulation
We were defaulting the contents of register 2 to zeros, but that
actually means an active state (modifier key is being held down and/or
an LED is on, see Table 8-11 in "Guide to Macintosh Family Hardware
(2nd Edition, 1990)"). We should default to 1, and also actually track
and report modifier key state.

This affected the BeOS boot chooser - it gets modifiers from
register 2, and the 0 value made it think that all modifiers were being
held. In turn that would make it bring up the "choose device" screen,
instead of automatically continuing with the previously-selected one.

Classic Mac OS was not affected (e.g. for hold down shift to disable
extensions) because it consumes key updates from register 0 and
maintains its own modifier state.
2026-09-26 15:12:11 -07:00
joevt 74c388c6ec atabasedevice: Queue single read data interrupt. 2026-09-26 08:59:00 -07:00
joevt 0c05d4ff9f ppcopcodes: Add emulation of THRMn registers.
Required for booting Mac OS 9.2.2 on iMac.
2026-09-25 20:31:30 -07:00
joevt 529fff7d4d timermanager: Pre-allocate TimerInfo.
Remove std::shared_ptr allocation/deallocation of TimerInfo structs.
2026-09-25 20:12:05 -07:00
joevt 3d5e2442d3 timermanager: Return next_ns from process_timers.
The point of this change is that g_icycles might not always be the
current time. For example, when g_realtime is true.

process_timers now returns the next time a timer needs to be processed.
Don't subtract time_now, because for realtime mode, the time has changed
since time_now was captured, especially for timers that take a long time
to process.

When there's no timer pending, process_events will return a time of now
+ 0.5 ms for when process_timers should be called again.
2026-09-23 07:06:26 -07:00
joevt 14bae3d789 timermanager: Add time parameters to callback. 2026-09-23 07:04:04 -07:00
joevt ab874a0da9 ppcexceptions: Remove duplicate exception handling code. 2026-09-22 20:29:12 -07:00
joevt ba4a5c7c44 ppcemu: Define more PPC exceptions. 2026-09-22 20:26:38 -07:00
joevt e729b989bb ppcemu: Specify PPC exception values. 2026-09-22 20:26:10 -07:00
joevt 320688dee7 ppcmmu: Fix spelling. 2026-09-22 20:19:00 -07:00
Mihai Parparita 1a0439a871 ppcmmu: Flush all PAT-derived TLB entries for the tlbie instruction
This fixes booting Mac OS 8.6 hanging at the Happy Mac on the iMac G3.
During boot, as part of installing the nanokernel, the OS attempts to do
a full TLB flush via a series of `tlbie` instructions. We were trying to
respect the effective address that's specified in the instruction, but
the semantics of how it should be interpreted are different on the 750
CPU - the [user manual](https://www.nxp.com/docs/en/reference-manual/MPC750UM.pdf)
says:

> The `tlbie` instruction invalidates all TLB entries indexed by the EA,
> and operates on both the instruction and data TLBs simultaneously
> invalidating four TLB entries. The index corresponds to bits 14-19 of the EA.

We were not respecting the bits 14-19 part (`TLB_VPS_MASK` matched bits
4-19), and thus not matching all expected entries. The stale entries
would remain, leading to unexpected behavior.

Rather than trying to more precisely model the 750 behavior, we instead
flush all PAT-derived TLB entries. This matches QEMU's approach (see
qemu/qemu@3dcfb74fd4) and is allowed by
[the PowerPC specification](http://refspecs.linux-foundation.org/PPC_hrm.2005mar31.pdf):

> For example, the tlbie instruction may be implemented to purge all TLB
> entries in a congruence class (that is, all TLB entries indexed by the
> specified effective address which can include corresponding entries in
> data and instruction TLBs) **or the entire TLB**.

As of #219 a full flush is not that expensive, thus this does not
materially affect performance. The goal of the guest OS is a full TLB
flush anyway (hence the sweep of `tlbie` instructions), so we don't end
up doing too many extra lookups after they're done.

For #184
2026-09-16 18:33:16 -07:00
dingusdev 453f2a4a5b MESH: Add missing IRQ update when writing to IntMask 2026-09-13 22:21:26 -07:00
dingusdev 6cb2dc51fe Add missing reset values for MESH 2026-09-13 22:20:44 -07:00
joevt cf951f6900 sc53c94: Allow CLEAR_FIFO after RESET_DEVICE part 3. 2026-09-08 07:10:01 -07:00
dingusdev 796ce78e54 Move Burgundy namespaces to the header 2026-09-07 22:46:37 -07:00
joevt 54c5501e22 burgundy: Add a mic and headphones.
To make sure we get stereo input and output capability.
2026-09-07 22:41:38 -07:00
joevt 1ad1ab29b1 burgundy: Define all bits of the main registers.
Move register definition from .h to .cpp
2026-09-07 22:41:00 -07:00
joevt d2065c8d80 burgundy: Set ID and Vendor registers.
Necessary for classic Mac OS. These are from real B&W G3.
2026-09-07 22:38:44 -07:00
joevt aa5ad2fad9 burgundy: Range check register address. 2026-09-07 22:38:23 -07:00
joevt 4666994a8b burgundy: Increase first_valid time.
Measured ≈22.6 µs on a real B&W G3.
2026-09-07 22:34:57 -07:00
joevt 14cd5559f5 burgundy: Change first_valid to bool. 2026-09-07 22:29:11 -07:00
joevt 932739095a burgundy: Remove extra byte swap. 2026-09-07 22:27:31 -07:00
joevt 28796e3bda burgundy: Remove extra spaces. 2026-09-07 22:27:18 -07:00
joevt 20a22a86e1 sc53c94: Remove extra spaces. 2026-09-07 22:26:44 -07:00
dingusdevandjoevt 5ff0789e75 sc53c94: Allow CLEAR_FIFO after RESET_DEVICE part 2.
Co-Authored-By: joevt <[email protected]>
2026-09-07 22:25:24 -07:00
joevt 8b983ea103 sc53c94: Update IRQ after RESET_DEVICE.
Everywhere that int_status is changed, update_irq must be called to
update irq and status.
2026-09-05 07:57:03 -07:00
joevt 409ec7015e sc53c94: Allow CLEAR_FIFO after RESET_DEVICE.
For Open Firmware reset-scsi compatibility.
2026-09-05 07:56:50 -07:00
joevt e1e324b5d8 maciotwo: Apply mask when reading int events.
The event is still pending even if masked. It will cause an interrupt
when it is unmasked unless it is cleared. Tested on real B&W G3.
2026-09-03 07:37:00 -07:00
joevt c8a9fb91c5 grandcentral: Apply mask when reading int events.
The event is still pending even if masked. It will cause an interrupt
when it is unmasked unless it is cleared. Tested on real Power Mac 8600.
2026-09-03 07:36:39 -07:00
joevt b670fab0f3 grandcentral: Always set DMA interrupt 11.
This interrupt is reserved and is therefore always set.
Tested on a real Power Mac 8600.
2026-09-03 07:36:30 -07:00
Mihai Parparita 21a6b16102 cdrom: Support inserting and ejecting media
Let empty CD-ROM drives accept image insertion events and report the
change to the guest. Guest eject requests now detach the backing image,
and insertion is rejected while media is still present.

SDL handles dropped files through the shared event path. The macOS
bundle also registers ISO and Toast images for app-icon drops.
2026-09-01 06:47:03 -07:00
Mihai Parparita 8101c11ed8 scsi: Delegate medium ejection to devices
Keep START STOP UNIT decoding in ScsiBlockCmds while letting devices
override only the eject action. The default behavior is unchanged.
2026-09-01 06:47:03 -07:00
Mihai Parparita 8bb9037c21 blockstorage: Add image attach and detach helpers
Make backing-image lifetime explicit and reset generic transfer state
when an image is detached. Keep device-specific media behavior in callers.
2026-09-01 06:47:03 -07:00
Mihai Parparita f69d14063c scsi: Name START STOP UNIT flags 2026-09-01 06:47:03 -07:00
joevt a3ac1f4ec0 awacs: Remove blank line. 2026-08-29 07:56:44 -07:00
joevt 86cd4f0712 awacs: Remove extra spaces. 2026-08-29 07:56:37 -07:00
joevt 885be6ae56 atirage: Consolidate ATI_CRTC_INT_CNTL handling. 2026-08-29 07:05:43 -07:00
Mihai Parparita 50950fcfef imgfile: Keep the current image if opening another fails
Create the replacement backend before swapping it in. This lets callers
try a new image without losing the one that is already open.
2026-08-23 17:57:00 -07:00
joevt 583137f327 dbdma: Remove unused callbacks. 2026-08-23 16:29:03 -07:00
Mihai Parparita 4d3cd65429 dma: Remove the old pull/push completion API
b63b6583 removed the old ESCC DMA implementation, taking the last users
of end_pull_data(), end_push_data(), and get_push_data_remaining() with
it. 9fb34efc later removed the last get_pull_data_remaining() call from
the sound server.

Nothing has called these hooks since. Remove them from DmaOutChannel,
DmaInChannel, and DMAChannel instead of carrying dead completion paths
alongside the DMA interfaces that are still in use.
2026-08-21 22:51:37 -07:00
Mihai Parparita a35736dda3 dbdma: Interpret command lists until STOP
With #214 we started to advertise the IDE DMA support from #192 to
guests. That appeared to break booting Mac OS 8.x, at least on the Beige
G3: the startup disk was not even detected.

Mac OS 8.1 sets up an IDE DMA read as INPUT_MORE, then a NOP with its i
field set to always, then STOP, which clears the channel's ACTIVE bit.
The emulated transfer completion path interpreted only one following
descriptor, so it stopped at NOP. NOP raised the interrupt, but STOP was
never reached and the channel stayed active. The Mac OS X driver is more
tolerant of this, which is why it was not an issue there.

The DBDMA Specification, section 1.4, says: "The target fetches command
entries and performs the command-entry-specified data-transfer operation,
processing command entries until a STOP entry is reached". Keep
interpreting ready commands until a transfer blocks or the channel stops,
as start() and resume() already did. This is closer to the hardware
behavior, and empirically lets Mac OS 8.1 boot again.
2026-08-21 22:51:37 -07:00
Mihai Parparita dced15e63d ppc: Ignore unchanged BAT register writes
Avoids unncessary TLB invalidations.
2026-08-20 22:54:26 -07:00
Mihai Parparita 13ccd42e16 ppcmmu: Track translated entries for invalidation
XNU frequently changes BAT and PAT mappings for physical-memory access.
Each  resulting context synchronization can walk tens of thousands of TLB
entries, which consumes a lot of time.

Record the instruction and data TLB slots populated by BAT or PAT and
invalidate only those slots. Pending invalidations are coalesced by source,
and BAT updates cover PAT-derived entries because a new BAT can shadow a page
mapping.

Saves another 0.7 secondss in the time it takes to boot Mac OS X 10.3 to
the WindowServer (compared to the generational PAT invalidation).
2026-08-20 22:54:26 -07:00
Mihai Parparita 855f43c2eb ppcmmu: Revert generational PAT invalidation
PAT generation counters make invalidation constant-time by adding a
generation check to every TLB lookup, but they added a per-access overhead
to compare generation counters. I am swithcing to an alternate approach
(explicitly tracking populated entries, which can also be used for
BAT-derived entries), and am removing this first to make that diff
easier to read.

This logically reverts the work from #199 (the TLB helper refactoring
from #203 prevents a mechanical revert).
2026-08-20 22:54:26 -07:00
Maxim Poliakovski 5f6f3624e1 ppcdechelpers.h: split operand decoding and value loading.
Also remove duplicated code wherever possible.
2026-08-18 16:25:03 +02:00
joevt c8185d0431 scsiphysdevice: Fix spelling. 2026-08-18 06:55:45 -07:00
joevt f547057bb6 ppcdisasm: Fix rlwimi input register list.
The destination register is also an input since only some bits are
modified.
2026-08-18 06:55:11 -07:00
probonopd 6fc87fb982 input: add --swap-command-option to swap the Command and Option keys 2026-08-17 20:32:56 -07:00
Maxim Poliakovski d5f16cf4b6 Rename ppcmacros.h to ppcdechelpers.h & cleanup formatting. 2026-08-17 14:11:55 +02:00
probonopd 57eb29e26c soundserver: drain guest sound DMA via cyclic timer when host stream fails to start
If the host audio stream cannot be started (e.g. no working output device),
the guest sound DMA never advances because the cubeb callback that pulls
data is never invoked. The guest sound driver then stalls forever waiting
for DMA interrupts and the system hangs during boot. Fall back to draining
the DMA via a cyclic timer, as is already done in deterministic mode, so
the guest sees DMA progress even though there is no audible output.
2026-08-16 18:28:41 -07:00
probonopd ed85c82556 viacuda: accept TIMER_TICKLE and SET_POWER_MESSAGES pseudo commands
Log both commands at INFO instead of WARNING. Track the shutdown watchdog
count from TIMER_TICKLE and never act on expiry so the guest cannot be
powered off spuriously when it stops tickling.
2026-08-16 18:28:07 -07:00
Mihai Parparita bd7e3b264b ata: Advertise multiword DMA support
Followup to #192. That implemented DMA support, but did not advertise
it via the IDENTIFY command. While the 10.0 public beta used it
unconditionally, later releases will only use it if the hardware
reports the MWDMA bit.

Takes booting 10.3 (to WindowServer startup) from ~60 seconds to ~47 seconds on my machine.
2026-08-16 14:34:31 -07:00
Mihai Parparita 246bb00ea6 main: Guard deterministic PC logging during transitions
I happened to get a crash when running with deterministic mode because
an exception occurred right when when the periodic logging timer fired,
and the PC address not valid under the new mapping.
2026-08-16 14:11:00 -07:00
Mihai Parparita f6f8d28001 sdl: allow screensaver
SDL defaults to disabling the screensaver, which on macOS hosts also
means that the display or machine will not sleep. This is appropriate
for games, but not for a regular windowed application like DingusPPC (if
a session is left running in the background).
2026-08-15 14:43:38 -07:00
Mihai Parparita 253844cec5 ppcmmu: Add helpers for repeated TLB operations
Helps a bit with some of the code duplication introduced in #203.
2026-08-14 19:26:02 -07:00
110 changed files with 3722 additions and 1499 deletions

No files matched your search

+29 -24
View File
@@ -183,13 +183,20 @@ if (APPLE)
set_target_properties(dingusppc PROPERTIES
MACOSX_BUNDLE_GUI_IDENTIFIER "${BUNDLE_ID}"
MACOSX_BUNDLE_BUNDLE_NAME "DingusPPC"
MACOSX_BUNDLE_BUNDLE_VERSION "alpha 1.0.4b"
MACOSX_BUNDLE_SHORT_VERSION_STRING "a1.0.4b"
MACOSX_BUNDLE_BUNDLE_VERSION "alpha 1.0.4c"
MACOSX_BUNDLE_SHORT_VERSION_STRING "a1.0.4c"
MACOSX_BUNDLE_EXECUTABLE_NAME "DingusPPC"
# Placeholder for the icon file:
# MACOSX_BUNDLE_ICON_FILE "icon.icns"
)
if (NOT IOS)
set_target_properties(dingusppc PROPERTIES
MACOSX_BUNDLE_INFO_PLIST "${PROJECT_SOURCE_DIR}/cmake/DingusPPCInfo.plist.in"
XCODE_ATTRIBUTE_PRODUCT_BUNDLE_IDENTIFIER "${BUNDLE_ID}"
)
endif()
find_library(COCOA_LIBRARY Cocoa)
find_library(IOKIT_LIBRARY IOKit)
find_library(COREAUDIO_LIBRARY CoreAudio)
@@ -258,28 +265,26 @@ if (DPPC_BUILD_PPC_TESTS)
endif()
if (DPPC_BUILD_BENCHMARKS)
add_compile_options("-DPPC_BENCHMARKS")
file(GLOB BENCH_SOURCES "${PROJECT_SOURCE_DIR}/benchmark/*.cpp"
"${PROJECT_SOURCE_DIR}/cpu/ppc/*.cpp"
"${PROJECT_SOURCE_DIR}/cpu/ppc/*.h"
)
add_executable(bench1 ${BENCH_SOURCES} $<TARGET_OBJECTS:core>
# $<TARGET_OBJECTS:cpu_ppc>
$<TARGET_OBJECTS:debugger>
$<TARGET_OBJECTS:devices>
$<TARGET_OBJECTS:machines>
$<TARGET_OBJECTS:utils>
$<TARGET_OBJECTS:loguru>)
target_link_libraries(bench1 PRIVATE cubeb SDL2::SDL2 ${CMAKE_DL_LIBS}
${CMAKE_THREAD_LIBS_INIT})
if (WIN32)
target_compile_definitions(bench1 PRIVATE SDL_MAIN_HANDLED)
endif()
if (DPPC_68K_DEBUGGER)
target_link_libraries(bench1 PRIVATE capstone)
endif()
file(GLOB BENCH_CPU_SOURCES "${PROJECT_SOURCE_DIR}/cpu/ppc/*.cpp"
"${PROJECT_SOURCE_DIR}/cpu/ppc/*.h")
foreach(BENCHMARK bench1 bench2)
add_executable(${BENCHMARK} "benchmark/${BENCHMARK}.cpp" ${BENCH_CPU_SOURCES}
$<TARGET_OBJECTS:core>
$<TARGET_OBJECTS:debugger>
$<TARGET_OBJECTS:devices>
$<TARGET_OBJECTS:machines>
$<TARGET_OBJECTS:utils>
$<TARGET_OBJECTS:loguru>)
target_compile_definitions(${BENCHMARK} PRIVATE PPC_BENCHMARKS)
target_link_libraries(${BENCHMARK} PRIVATE cubeb SDL2::SDL2 ${CMAKE_DL_LIBS}
${CMAKE_THREAD_LIBS_INIT})
if (WIN32)
target_compile_definitions(${BENCHMARK} PRIVATE SDL_MAIN_HANDLED)
endif()
if (DPPC_68K_DEBUGGER)
target_link_libraries(${BENCHMARK} PRIVATE capstone)
endif()
endforeach()
endif()
if (DPPC_BUILD_PPC_TESTS)
+5
View File
@@ -4,7 +4,12 @@ General
* Test your contributions to assure they do not break existing functionality.
* Commits to the repo should be done by portions; that is, by individual functionalities of the program.
* Don't use any disrespectful language.
AI Usage
=======
* Do not use artificial intelligence to make contributions. This is due to authorship issues and licensing issues regarding AI usage.
* Do not use artificial intelligence to write up issues or pull requests.
Code
=======
+2
View File
@@ -31,6 +31,7 @@
- lefp
- mathstuf
- mrpapersonic
- probonopd
- Randrianasulu
- roytam1
- sdkmap
@@ -58,6 +59,7 @@
- Blitter.net
- Emaculation
- GitHub
- pagetable.com
- PenguinPPC
- VirtuallyFun
- The makers of Loguru, SDL2, Capstone, and CLI11
+119
View File
@@ -0,0 +1,119 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team
(See CREDITS.MD for more details)
(You may also contact divingkxt or powermax2286 on Discord)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
// Replay floating-point instructions and input registers captured while BeOS
// PR1 GLTeapot renders. This measures the real opcode dispatcher and handlers,
// including FPSCR maintenance, without guest boot, display, or timer overhead.
#include <cpu/ppc/ppcemu.h>
#include <thirdparty/loguru/loguru.hpp>
#include <algorithm>
#include <cfenv>
#include <chrono>
#include <cinttypes>
#include <cstdio>
#include <cstring>
#include <vector>
#include "bench2_data.h"
#if defined(PPC_BENCHMARKS)
void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
power_off(po_benchmark_exception);
}
#endif
static void replay_sample(const FpuSample& sample) {
if ((ppc_state.fpscr ^ sample.fpscr) & FPSCR::RN_MASK)
set_host_rounding_mode(sample.fpscr & FPSCR::RN_MASK);
ppc_state.fpscr = sample.fpscr;
ppc_state.cr = sample.cr;
ppc_state.fpr[(sample.opcode >> 21) & 31].int64_r = sample.d;
ppc_state.fpr[(sample.opcode >> 16) & 31].int64_r = sample.a;
ppc_state.fpr[(sample.opcode >> 11) & 31].int64_r = sample.b;
ppc_state.fpr[(sample.opcode >> 6) & 31].int64_r = sample.c;
ppc_main_opcode(ppc_opcode_grabber, sample.opcode);
}
static uint64_t check_replay() {
uint64_t hash = 1469598103934665603ULL;
auto mix = [&hash](uint64_t value) { hash = (hash ^ value) * 1099511628211ULL; };
std::feclearexcept(FE_ALL_EXCEPT);
for (const auto& sample : fpu_samples) {
replay_sample(sample);
mix(ppc_state.fpr[(sample.opcode >> 21) & 31].int64_r);
mix(ppc_state.fpscr);
mix(ppc_state.cr);
}
return hash;
}
int main(int argc, char** argv) {
if (argc > 2 || (argc == 2 && std::strcmp(argv[1], "--check"))) {
fprintf(stderr, "Usage: %s [--check]\n", argv[0]);
return 2;
}
loguru::g_stderr_verbosity = loguru::Verbosity_ERROR;
is_601 = false;
initialize_ppc_opcode_table();
ppc_msr_did_change(ppc_state.msr, MSR::ME | MSR::IP | MSR::FP, false);
set_host_rounding_mode(0);
power_on = true;
const uint64_t expected = check_replay();
constexpr size_t sample_count = sizeof(fpu_samples) / sizeof(fpu_samples[0]);
printf("GLTeapot FPU replay: %zu samples, checksum %016" PRIx64 "\n", sample_count, expected);
if (!power_on)
return 1;
if (argc == 2 && !std::strcmp(argv[1], "--check"))
return 0;
constexpr unsigned passes = 10000;
constexpr unsigned trials = 9;
// Warm the dispatcher, handlers and captured input data.
for (unsigned pass = 0; pass < 100; pass++)
for (const auto& sample : fpu_samples)
replay_sample(sample);
std::vector<double> times;
for (unsigned trial = 0; trial < trials; trial++) {
std::feclearexcept(FE_ALL_EXCEPT);
auto start = std::chrono::steady_clock::now();
for (unsigned pass = 0; pass < passes; pass++)
for (const auto& sample : fpu_samples)
replay_sample(sample);
auto end = std::chrono::steady_clock::now();
if (!power_on || check_replay() != expected) {
fprintf(stderr, "FPU replay changed its result during timing\n");
return 1;
}
double ns = std::chrono::duration<double, std::nano>(end - start).count() /
(uint64_t(passes) * sample_count);
times.push_back(ns);
printf("Trial %u: %.3f ns/FPU instruction, %.3f million FPU instructions/s\n",
trial + 1, ns, 1000.0 / ns);
}
std::sort(times.begin(), times.end());
double median = times[times.size() / 2];
printf("Median: %.3f ns/FPU instruction, %.3f million FPU instructions/s\n",
median, 1000.0 / median);
return 0;
}
File diff suppressed because it is too large. Load diff
+70
View File
@@ -0,0 +1,70 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key>
<string>CD-ROM image</string>
<key>CFBundleTypeRole</key>
<string>Viewer</string>
<key>LSHandlerRank</key>
<string>Alternate</string>
<key>LSItemContentTypes</key>
<array>
<string>public.iso-image</string>
<string>com.roxio.disk-image-toast</string>
</array>
</dict>
</array>
<key>CFBundleExecutable</key>
<string>${MACOSX_BUNDLE_EXECUTABLE_NAME}</string>
<key>CFBundleGetInfoString</key>
<string>${MACOSX_BUNDLE_INFO_STRING}</string>
<key>CFBundleIconFile</key>
<string>${MACOSX_BUNDLE_ICON_FILE}</string>
<key>CFBundleIdentifier</key>
<string>${MACOSX_BUNDLE_GUI_IDENTIFIER}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleLongVersionString</key>
<string>${MACOSX_BUNDLE_LONG_VERSION_STRING}</string>
<key>CFBundleName</key>
<string>${MACOSX_BUNDLE_BUNDLE_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>${MACOSX_BUNDLE_SHORT_VERSION_STRING}</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>${MACOSX_BUNDLE_BUNDLE_VERSION}</string>
<key>CSResourcesFileMapped</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>${MACOSX_BUNDLE_COPYRIGHT}</string>
<key>UTImportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>public.disk-image</string>
</array>
<key>UTTypeDescription</key>
<string>Toast disk image</string>
<key>UTTypeIdentifier</key>
<string>com.roxio.disk-image-toast</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>toast</string>
</array>
</dict>
</dict>
</array>
</dict>
</plist>
+25
View File
@@ -25,6 +25,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <core/coresignal.h>
#include <cinttypes>
#include <string>
class WindowEvent {
public:
@@ -119,6 +120,20 @@ public:
uint8_t button;
};
enum class CdromInsertionResult {
SUCCESS,
NO_DRIVE,
MEDIA_PRESENT,
IMAGE_OPEN_FAILED,
};
class CdromImageEvent {
public:
std::string image_path;
CdromInsertionResult result = CdromInsertionResult::NO_DRIVE;
bool handled = false;
};
class EventManager {
public:
static EventManager* get_instance() {
@@ -131,6 +146,9 @@ public:
void poll_events();
void set_keyboard_locale(uint32_t keyboard_id);
void post_keyboard_state_events();
void post_cdrom_event(CdromImageEvent& event) {
_cdrom_signal.emit(event);
}
template <typename T>
void add_window_handler(T *inst, void (T::*func)(const WindowEvent&)) {
@@ -152,6 +170,11 @@ public:
_gamepad_signal.connect_method(inst, func);
}
template <typename T>
void add_cdrom_handler(T* inst, void (T::*func)(CdromImageEvent&)) {
_cdrom_signal.connect_method(inst, func);
}
template <typename T>
void add_post_handler(T *inst, void (T::*func)()) {
_post_signal.connect_method(inst, func);
@@ -162,6 +185,7 @@ public:
_mouse_signal.disconnect_all();
_keyboard_signal.disconnect_all();
_gamepad_signal.disconnect_all();
_cdrom_signal.disconnect_all();
_post_signal.disconnect_all();
}
@@ -179,6 +203,7 @@ private:
CoreSignal<const MouseEvent&> _mouse_signal;
CoreSignal<const KeyboardEvent&> _keyboard_signal;
CoreSignal<const GamepadEvent&> _gamepad_signal;
CoreSignal<CdromImageEvent&> _cdrom_signal;
CoreSignal<> _post_signal;
uint64_t events_captured = 0;
+49 -5
View File
@@ -32,6 +32,20 @@ static int get_sdl_event_key_code(const SDL_KeyboardEvent& event, uint32_t kbd_l
constexpr int KMOD_ALL = KMOD_LSHIFT | KMOD_RSHIFT | KMOD_LCTRL | KMOD_RCTRL | KMOD_LALT | KMOD_RALT | KMOD_LGUI | KMOD_RGUI;
bool g_swap_command_option = false;
static AdbKey swap_command_option(AdbKey key)
{
if (!g_swap_command_option)
return key;
switch (key) {
case AdbKey_Option: return AdbKey_Command;
case AdbKey_RightOption: return AdbKey_Command;
case AdbKey_Command: return AdbKey_Option;
default: return key;
}
}
void EventManager::set_keyboard_locale(uint32_t keyboard_id) {
this->kbd_locale = keyboard_id;
}
@@ -151,6 +165,7 @@ void EventManager::poll_events() {
bool g_realtime_status = toggle_g_realtime();
LOG_F(INFO, "g_realtime: %s", g_realtime_status ? "enabled" : "disabled");
}
return;
}
// Control-L: log toggle
@@ -308,6 +323,35 @@ void EventManager::poll_events() {
}
break;
case SDL_DROPFILE: {
const char* path = event.drop.file;
// TODO: Distinguish CD-ROM and floppy images once dynamic
// floppy insertion is supported.
CdromImageEvent cdrom_event{};
cdrom_event.image_path = path;
this->post_cdrom_event(cdrom_event);
switch (cdrom_event.result) {
case CdromInsertionResult::SUCCESS:
LOG_F(INFO, "Inserted CD-ROM image: %s", path);
break;
case CdromInsertionResult::NO_DRIVE:
LOG_F(ERROR, "Cannot insert CD-ROM image; no CD-ROM drive is available: %s",
path);
break;
case CdromInsertionResult::MEDIA_PRESENT:
LOG_F(ERROR, "Cannot insert CD-ROM image; eject the current media first: %s",
path);
break;
case CdromInsertionResult::IMAGE_OPEN_FAILED:
LOG_F(ERROR, "Cannot insert CD-ROM image: %s", path);
break;
}
SDL_free(event.drop.file);
}
break;
default:
unhandled_events++;
}
@@ -358,7 +402,7 @@ void EventManager::post_keyboard_state_events() {
continue;
LOG_F(INFO, " Modifier: %s", SDL_GetScancodeName(mod->scancode));
count++;
ke.key = mod->adbkey;
ke.key = swap_command_option(mod->adbkey);
ke.flags = KEYBOARD_EVENT_DOWN;
this->_keyboard_signal.emit(ke);
}
@@ -483,10 +527,10 @@ static int get_sdl_event_key_code(const SDL_KeyboardEvent &event, uint32_t kbd_l
case SDLK_RCTRL: return AdbKey_RightControl;
case SDLK_LSHIFT: return AdbKey_Shift;
case SDLK_RSHIFT: return AdbKey_RightShift;
case SDLK_LALT: return AdbKey_Option;
case SDLK_RALT: return AdbKey_RightOption;
case SDLK_LGUI: return AdbKey_Command;
case SDLK_RGUI: return AdbKey_Command;
case SDLK_LALT: return swap_command_option(AdbKey_Option);
case SDLK_RALT: return swap_command_option(AdbKey_RightOption);
case SDLK_LGUI: return swap_command_option(AdbKey_Command);
case SDLK_RGUI: return swap_command_option(AdbKey_Command);
case SDLK_MENU: return AdbKey_Grave;
case SDLK_CAPSLOCK: return AdbKey_CapsLock;
+38 -30
View File
@@ -30,51 +30,49 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
TimerManager* TimerManager::timer_manager;
uint32_t TimerManager::add_absolute_timer(uint64_t timeout_ns, uint64_t interval, timer_cb cb)
void TimerManager::add_absolute_timer(TimerInfo &ti, uint64_t timeout_ns, uint64_t interval, timer_cb cb)
{
TimerInfo* ti = new TimerInfo;
if (ti.active)
LOG_F(ERROR, "Timer %p is already active; cancel it before rescheduling", (void*)&ti);
ti->id = ++this->id;
ti->timeout_ns = timeout_ns;
ti->interval_ns = interval;
ti->cb = cb;
std::shared_ptr<TimerInfo> timer_desc(ti);
ti.timeout_ns = timeout_ns;
ti.interval_ns = interval;
ti.active = true;
ti.cb = cb;
// add new timer to the timer queue
this->timer_queue.push(timer_desc);
this->timer_queue.push(&ti);
// notify listeners about changes in the timer queue
if (!this->cb_active) {
this->notify_timer_changes();
}
return ti->id;
}
uint32_t TimerManager::add_oneshot_timer(uint64_t timeout, timer_cb cb)
void TimerManager::add_oneshot_timer(TimerInfo &ti, uint64_t timeout, timer_cb cb)
{
return TimerManager::add_absolute_timer(this->get_time_now() + timeout, 0, cb);
TimerManager::add_absolute_timer(ti, this->get_time_now() + timeout, 0, cb);
}
uint32_t TimerManager::add_immediate_timer(timer_cb cb)
void TimerManager::add_immediate_timer(TimerInfo &ti, timer_cb cb)
{
return TimerManager::add_absolute_timer(0, 0, cb);
TimerManager::add_absolute_timer(ti, 0, 0, cb);
}
uint32_t TimerManager::add_cyclic_timer(uint64_t interval, uint64_t delay, timer_cb cb)
void TimerManager::add_cyclic_timer(TimerInfo &ti, uint64_t interval, uint64_t delay, timer_cb cb)
{
return TimerManager::add_absolute_timer(this->get_time_now() + delay, interval, cb);
TimerManager::add_absolute_timer(ti, this->get_time_now() + delay, interval, cb);
}
uint32_t TimerManager::add_cyclic_timer(uint64_t interval, timer_cb cb)
void TimerManager::add_cyclic_timer(TimerInfo &ti, uint64_t interval, timer_cb cb)
{
return this->add_cyclic_timer(interval, interval, cb);
this->add_cyclic_timer(ti, interval, interval, cb);
}
void TimerManager::cancel_timer(uint32_t id)
void TimerManager::cancel_timer(TimerInfo &ti)
{
this->timer_queue.remove_by_id(id);
this->timer_queue.remove_by_id(&ti);
ti.active = false;
if (!this->cb_active) {
this->notify_timer_changes();
}
@@ -82,7 +80,7 @@ void TimerManager::cancel_timer(uint32_t id)
uint64_t TimerManager::process_timers()
{
std::shared_ptr<TimerInfo> cur_timer;
TimerInfo *cur_timer;
uint64_t time_now = get_time_now();
{ // mtx scope
@@ -95,7 +93,7 @@ uint64_t TimerManager::process_timers()
cur_timer = this->timer_queue.top();
} // ] mtx scope
while (cur_timer->timeout_ns <= time_now) {
this->timer_queue.remove_by_id(cur_timer->id);
this->timer_queue.remove_by_id(cur_timer);
uint64_t timeout_ns = cur_timer->timeout_ns;
timer_cb cb = cur_timer->cb;
@@ -103,16 +101,25 @@ uint64_t TimerManager::process_timers()
if (cur_timer->interval_ns) {
std::lock_guard<std::recursive_mutex> lk(this->timer_queue.get_mtx());
uint64_t timeout_ns_new = timeout_ns + cur_timer->interval_ns;
if (timeout_ns_new <= time_now)
timeout_ns_new = time_now + cur_timer->interval_ns;
if (timeout_ns_new <= time_now) {
// Skip missed periods without changing the timer's phase.
// Rebasing deadlines on time_now would align timers that
// have the same period.
const uint64_t periods_to_skip =
((time_now - timeout_ns_new) / cur_timer->interval_ns) + 1;
timeout_ns_new += periods_to_skip * cur_timer->interval_ns;
}
cur_timer->timeout_ns = timeout_ns_new;
this->timer_queue.push(cur_timer);
} else {
// One-shot callbacks may immediately reuse their TimerInfo.
cur_timer->active = false;
}
this->cb_active = true;
// invoke timer callback
cb();
cb(time_now, timeout_ns);
this->cb_active = false;
@@ -127,16 +134,17 @@ uint64_t TimerManager::process_timers()
} // ] mtx scope
}
// return time slice in nanoseconds until next timer's expiry
return cur_timer->timeout_ns - time_now;
// return next timer's expiry
return cur_timer->timeout_ns;
}
void TimerManager::cancel_all_timers()
{
std::shared_ptr<TimerInfo> cur_timer;
TimerInfo *cur_timer;
while (!this->timer_queue.empty()) {
cur_timer = this->timer_queue.top();
LOG_F(WARNING, "Canceling timer id:%u ns:%llu", cur_timer->id, cur_timer->timeout_ns);
LOG_F(WARNING, "Canceling timer id:%llu ns:%llu", uint64_t(cur_timer), cur_timer->timeout_ns);
this->timer_queue.pop();
cur_timer->active = false;
}
}
+18 -18
View File
@@ -40,7 +40,7 @@ constexpr auto ONE_BILLION_NS = 1000000000;
#define USECS_TO_NSECS(us) (us) * NS_PER_USEC
#define MSECS_TO_NSECS(ms) (ms) * NS_PER_MSEC
typedef std::function<void()> timer_cb;
typedef std::function<void(uint64_t timeout_ns, uint64_t time_now)> timer_cb;
typedef std::function<void()> notify_changes_cb;
/** Extend std::priority_queue as suggested here:
@@ -50,17 +50,17 @@ typedef std::function<void()> notify_changes_cb;
template <typename T, class Container = std::vector<T>, class Compare = std::less<typename Container::value_type>>
class my_priority_queue : public std::priority_queue<T, Container, Compare> {
public:
bool remove_by_id(const uint32_t id){
bool remove_by_id(T id){
std::lock_guard<std::recursive_mutex> lk(mtx);
if (this->empty())
return false;
auto el = this->top();
if (el->id == id) {
if (el == id) {
std::priority_queue<T, Container, Compare>::pop();
return true;
}
auto it = std::find_if(
this->c.begin(), this->c.end(), [id](const T& el) { return el->id == id; });
this->c.begin(), this->c.end(), [id](const T& el) { return el == id; });
if (it != this->c.end()) {
this->c.erase(it);
std::make_heap(this->c.begin(), this->c.end(), this->comp);
@@ -93,18 +93,18 @@ private:
};
typedef struct TimerInfo {
uint32_t id;
uint64_t timeout_ns; // timer expiry
uint64_t interval_ns; // 0 for one-shot timers
bool active = false; // maintained by TimerManager while queued
timer_cb cb; // timer callback
} TimerInfo;
// Custom comparator for sorting our timer queue in ascending order
class MyGtComparator {
public:
bool operator()(const std::shared_ptr<TimerInfo>& l, const std::shared_ptr<TimerInfo>& r) const {
return l.get()->timeout_ns > r.get()->timeout_ns ||
(l.get()->timeout_ns == r.get()->timeout_ns && l.get()->id > r.get()->id);
bool operator()(const TimerInfo *l, const TimerInfo *r) const {
return l->timeout_ns > r->timeout_ns ||
(l->timeout_ns == r->timeout_ns && l > r);
}
};
@@ -130,13 +130,15 @@ public:
// return current virtual time in nanoseconds
uint64_t current_time_ns() const { return get_time_now(); }
// creating and cancelling timers
uint32_t add_absolute_timer(uint64_t timeout_ns, uint64_t interval, timer_cb cb);
uint32_t add_oneshot_timer(uint64_t timeout, timer_cb cb);
uint32_t add_immediate_timer(timer_cb cb);
uint32_t add_cyclic_timer(uint64_t interval, timer_cb cb);
uint32_t add_cyclic_timer(uint64_t interval, uint64_t delay, timer_cb cb);
void cancel_timer(uint32_t id);
// Adding requires an inactive timer; cancel before rescheduling.
// One-shot timers become inactive before their callback runs.
// Cyclic timers remain active until canceled, including during callbacks.
void add_absolute_timer(TimerInfo &ti, uint64_t timeout_ns, uint64_t interval, timer_cb cb);
void add_oneshot_timer(TimerInfo &ti, uint64_t timeout, timer_cb cb);
void add_immediate_timer(TimerInfo &ti, timer_cb cb);
void add_cyclic_timer(TimerInfo &ti, uint64_t interval, timer_cb cb);
void add_cyclic_timer(TimerInfo &ti, uint64_t interval, uint64_t delay, timer_cb cb);
void cancel_timer(TimerInfo &ti);
void cancel_all_timers();
uint64_t process_timers();
@@ -146,13 +148,11 @@ private:
TimerManager(){} // private constructor to implement a singleton
// timer queue
my_priority_queue<std::shared_ptr<TimerInfo>, std::vector<std::shared_ptr<TimerInfo>>, MyGtComparator> timer_queue;
my_priority_queue<TimerInfo*, std::vector<TimerInfo*>, MyGtComparator> timer_queue;
std::function<uint64_t()> get_time_now;
std::function<void()> notify_timer_changes;
std::atomic<uint32_t> id{0};
// FIXME: Do we need this? It gets written in main thread and read in audio thread.
bool cb_active = false; // true if a timer callback is executing
};
+4 -3
View File
@@ -23,9 +23,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
// Any shared opcodes are in ppcopcodes.cpp
#include <core/bitops.h>
#include "ppcemu.h"
#include "ppcmacros.h"
#include "ppcmmu.h"
#include <cpu/ppc/ppcdechelpers.h>
#include <cpu/ppc/ppcemu.h>
#include <cpu/ppc/ppcmmu.h>
#include <stdint.h>
/** mask generator for rotate and shift instructions (§ 4.2.1.4 PowerpC PEM) */
+215
View File
@@ -0,0 +1,215 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team
(See CREDITS.MD for more details)
(You may also contact divingkxt or powermax2286 on Discord)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef PPC_DECODE_HELPERS_H
#define PPC_DECODE_HELPERS_H
#include <cinttypes>
// ============== Helpers for extracting operands from opcodes ================
#define decode_ops_sa(opcode) \
int reg_s = (opcode >> 21) & 0x1F; \
int reg_a = (opcode >> 16) & 0x1F;
#define decode_ops_da(opcode) \
int reg_d = (opcode >> 21) & 0x1F; \
int reg_a = (opcode >> 16) & 0x1F;
#define decode_ops_sab(opcode) \
decode_ops_sa(opcode); \
int reg_b = (opcode >> 11) & 0x1F;
#define decode_ops_dab(opcode) \
decode_ops_da(opcode); \
int reg_b = (opcode >> 11) & 0x1F;
#define decode_ops_dasimm(opcode) \
decode_ops_da(opcode); \
int32_t simm = int32_t(int16_t(opcode));
#define decode_ops_sauimm(opcode) \
decode_ops_sa(opcode); \
uint32_t uimm = uint16_t(opcode);
#define decode_ops_dauimm(opcode) \
decode_ops_da(opcode); \
uint32_t uimm = uint16_t(opcode);
// ================= Helpers for the original interpreter =====================
// The helpers below do the same work as those above but also pre-load some
// register values and place them into local variables.
// That significantly reduces interpreter code.
#define ppc_grab_regsdasimm(opcode) \
decode_ops_dasimm(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsdauimm(opcode) \
decode_ops_dauimm(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsasimm(opcode) \
int reg_a = (opcode >> 16) & 0x1F; \
int32_t simm = int32_t(int16_t(opcode)); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssauimm(opcode) \
decode_ops_sauimm(opcode); \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_crfd_regsauimm(opcode) \
int crf_d = (opcode >> 21) & 0x1C; \
int reg_a = (opcode >> 16) & 0x1F; \
uint32_t uimm = uint16_t(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_da(opcode) \
decode_ops_da(opcode)
#define ppc_grab_dab(opcode) \
decode_ops_dab(opcode)
#define ppc_grab_s(opcode) \
int reg_s = (opcode >> 21) & 0x1F; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s];
#define ppc_grab_regsdab(opcode) \
decode_ops_dab(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regssab(opcode) \
decode_ops_sab(opcode); \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regssab_stswx(opcode) \
decode_ops_sab(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regsab(opcode) \
int reg_a = (opcode >> 16) & 0x1F; \
int reg_b = (opcode >> 11) & 0x1F; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regssa(opcode) \
decode_ops_sa(opcode); \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssa_stmw(opcode) \
decode_ops_sa(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssash(opcode) \
decode_ops_sa(opcode); \
unsigned rot_sh = (opcode >> 11) & 0x1F; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssash_stswi(opcode) \
decode_ops_sa(opcode); \
unsigned rot_sh = (opcode >> 11) & 0x1F; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssb(opcode) \
int reg_s = (opcode >> 21) & 0x1F; \
int reg_b = (opcode >> 11) & 0x1F; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regsda(opcode) \
decode_ops_da(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsdb(opcode) \
int reg_d = (opcode >> 21) & 0x1F; \
uint32_t reg_b = (opcode >> 11) & 0x1F; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regsfpdb(opcode) \
int reg_d = (opcode >> 21) & 0x1F; \
int reg_b = (opcode >> 11) & 0x1F;
#define ppc_grab_regsfpdiab(opcode) \
decode_ops_dab(opcode); \
uint32_t val_reg_a = ppc_state.gpr[reg_a]; \
uint32_t val_reg_b = ppc_state.gpr[reg_b];
#define ppc_grab_regsfpdia(opcode) \
decode_ops_da(opcode); \
uint32_t val_reg_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsfpsia(opcode) \
decode_ops_sa(opcode); \
uint32_t val_reg_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsfpsiab(opcode) \
decode_ops_sab(opcode); \
uint32_t val_reg_a = ppc_state.gpr[reg_a]; \
uint32_t val_reg_b = ppc_state.gpr[reg_b];
#define ppc_grab_regsfpsab(opcode) \
int reg_a = (opcode >> 16) & 0x1F; \
int reg_b = (opcode >> 11) & 0x1F; \
int crf_d = (opcode >> 21) & 0x1C; \
double db_test_a = GET_FPR(reg_a); \
double db_test_b = GET_FPR(reg_b);
#define ppc_grab_regsfpdab(opcode) \
decode_ops_dab(opcode); \
double val_reg_a = GET_FPR(reg_a); \
double val_reg_b = GET_FPR(reg_b);
#define ppc_grab_regsfpdac(opcode) \
decode_ops_da(opcode); \
int reg_c = (opcode >> 6) & 0x1F; \
double val_reg_a = GET_FPR(reg_a); \
double val_reg_c = GET_FPR(reg_c);
#define ppc_grab_regsfpdabc(opcode) \
decode_ops_dab(opcode); \
int reg_c = (opcode >> 6) & 0x1F; \
double val_reg_a = GET_FPR(reg_a); \
double val_reg_b = GET_FPR(reg_b); \
double val_reg_c = GET_FPR(reg_c);
#define ppc_store_iresult_reg(reg, ppc_result) \
ppc_state.gpr[reg] = ppc_result
#define ppc_store_fpresult_int(reg, ppc_result64_d) \
ppc_state.fpr[(reg)].int64_r = ppc_result64_d
#define ppc_store_fpresult_flt(reg, ppc_dblresult64_d) \
ppc_state.fpr[(reg)].dbl64_r = ppc_dblresult64_d
#define GET_FPR(reg) \
ppc_state.fpr[(reg)].dbl64_r
#define FPR_INT(reg) \
ppc_state.fpr[reg].int64_r
#endif // PPC_DECODE_HELPERS_H
+8 -1
View File
@@ -392,6 +392,13 @@ void fmt_rotateop(PPCDisasmContext* ctx, const char* opc, int dst, int src, int
}
}
void fmt_rotateinsert(PPCDisasmContext* ctx, const char* opc, int dst, int src, int sh, int mb, int me) {
ctx->instr_str = my_sprintf("%-7s r%d, r%d, %d, %d, %d", opc, dst, src, sh, mb, me);
add_reg_in(ctx, "r%d", dst);
add_reg_in(ctx, "r%d", src);
add_reg_out(ctx, "r%d", dst);
}
/* Opcodes */
void opc_illegal(PPCDisasmContext* ctx) {
@@ -522,7 +529,7 @@ void opc_rlwimi(PPCDisasmContext* ctx) {
add_reg_out(ctx, "cr");
}
fmt_rotateop(ctx, opcode, ra, rs, sh, mb, me, true);
fmt_rotateinsert(ctx, opcode, ra, rs, sh, mb, me);
}
void opc_rlwinm(PPCDisasmContext* ctx) {
+22 -12
View File
@@ -126,6 +126,9 @@ enum SPR : int {
SDA = 959,
HID0 = 1008,
HID1 = 1009,
THRM1 = 1020,
THRM2 = 1021,
THRM3 = 1022,
};
/** symbolic names for common PPC processors */
@@ -321,17 +324,22 @@ enum FPOP : int {
/** PowerPC exception types. */
enum class Except_Type {
EXC_SYSTEM_RESET = 1,
EXC_MACHINE_CHECK,
EXC_DSI,
EXC_ISI,
EXC_EXT_INT,
EXC_ALIGNMENT,
EXC_PROGRAM,
EXC_NO_FPU,
EXC_DECR,
EXC_SYSCALL = 12,
EXC_TRACE = 13
EXC_SYSTEM_RESET = 0x01,
EXC_MACHINE_CHECK = 0x02,
EXC_DSI = 0x03,
EXC_ISI = 0x04,
EXC_EXT_INT = 0x05,
EXC_ALIGNMENT = 0x06,
EXC_PROGRAM = 0x07,
EXC_NO_FPU = 0x08,
EXC_DECR = 0x09,
EXC_SYSCALL = 0x0C,
EXC_TRACE = 0x0D,
EXC_FP_ASSIST = 0x0E,
EXC_PERF_MON_INT = 0x0F,
EXC_INST_ADDR_BP = 0x13,
EXC_SYS_MGMT_INT = 0x14,
EXC_THRM_MGMT_INT = 0x17,
};
/** Program Exception subclasses. */
@@ -373,6 +381,7 @@ void p_power_off(const char* file, int line, Po_Cause new_reason);
extern bool int_pin;
extern bool dec_exception_pending;
extern bool thrm_exception_pending;
extern bool is_601; // For PowerPC 601 Emulation
extern bool include_601; // For non-PowerPC 601 emulation with 601 extras
@@ -725,7 +734,8 @@ extern int increment_icnt_factor();
extern int decrement_icnt_factor();
extern int get_icnt_factor();
/* toggle_g_realtime */
/* realtime clock control */
extern bool g_realtime;
extern bool toggle_g_realtime();
/* force_cycle_counter_reload */
+15 -37
View File
@@ -39,8 +39,11 @@ void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
switch (exception_type) {
case Except_Type::EXC_SYSTEM_RESET:
case Except_Type::EXC_DSI:
case Except_Type::EXC_ALIGNMENT:
case Except_Type::EXC_PROGRAM:
case Except_Type::EXC_NO_FPU:
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0100;
break;
case Except_Type::EXC_MACHINE_CHECK:
@@ -48,12 +51,6 @@ void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
/* TODO: handle internal checkstop */
}
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0200;
break;
case Except_Type::EXC_DSI:
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0300;
break;
case Except_Type::EXC_ISI:
@@ -62,56 +59,28 @@ void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
} else {
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFCUL;
}
ppc_next_instruction_address = 0x0400;
break;
case Except_Type::EXC_EXT_INT:
if (exec_flags & ~EXEF_OPC_DECODER) {
ppc_state.spr[SPR::SRR0] = ppc_next_instruction_address;
} else {
ppc_state.spr[SPR::SRR0] = (ppc_state.pc & 0xFFFFFFFCUL) + 4;
}
ppc_next_instruction_address = 0x0500;
break;
case Except_Type::EXC_ALIGNMENT:
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0600;
break;
case Except_Type::EXC_PROGRAM:
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0700;
break;
case Except_Type::EXC_NO_FPU:
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0800;
break;
case Except_Type::EXC_DECR:
case Except_Type::EXC_THRM_MGMT_INT:
if (exec_flags & ~EXEF_OPC_DECODER) {
ppc_state.spr[SPR::SRR0] = ppc_next_instruction_address;
} else {
ppc_state.spr[SPR::SRR0] = (ppc_state.pc & 0xFFFFFFFCUL) + 4;
}
ppc_next_instruction_address = 0x0900;
break;
case Except_Type::EXC_SYSCALL:
ppc_state.spr[SPR::SRR0] = (ppc_state.pc & 0xFFFFFFFC) + 4;
ppc_next_instruction_address = 0x0C00;
break;
case Except_Type::EXC_TRACE:
ppc_state.spr[SPR::SRR0] = (ppc_state.pc & 0xFFFFFFFC) + 4;
ppc_next_instruction_address = 0x0D00;
break;
default:
ABORT_F("Unknown exception occurred: %X\n", (unsigned)exception_type);
break;
}
ppc_next_instruction_address = uint32_t(exception_type) << 8;
ppc_state.spr[SPR::SRR1] = (ppc_state.msr & 0x0000FF73) | srr1_bits;
uint32_t old_msr_val = ppc_state.msr;
@@ -202,6 +171,15 @@ void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
case Except_Type::EXC_TRACE:
exc_descriptor = "Trace exception occurred";
break;
case Except_Type::EXC_THRM_MGMT_INT:
exc_descriptor = "Thermal management interrupt exception occurred";
break;
default:
char buffer[100];
snprintf(buffer, sizeof(buffer), "Exception 0x%X occurred", int(exception_type));
exc_descriptor = buffer;
}
throw std::invalid_argument(exc_descriptor);
+42 -25
View File
@@ -36,19 +36,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <string>
#ifdef __APPLE__
#include <mach/mach_time.h>
#undef EXC_SYSCALL
static struct mach_timebase_info timebase_info;
static uint64_t
ConvertHostTimeToNanos2(uint64_t host_time)
{
if (timebase_info.numer == timebase_info.denom)
return host_time;
long double answer = host_time;
answer *= timebase_info.numer;
answer /= timebase_info.denom;
return (uint64_t)answer;
}
#include <ctime>
#endif
using namespace std;
@@ -128,6 +116,7 @@ unsigned exec_flags; // execution control flags
volatile bool exec_timer;
bool int_pin = false; // interrupt request pin state: true - asserted
bool dec_exception_pending = false;
bool thrm_exception_pending = false;
/* variables related to virtual time */
bool g_realtime = false;
@@ -286,6 +275,18 @@ PPCOpcode* ppc_opcode_grabber = OpcodeGrabberNoFPU;
/** Exception helpers. */
void ppc_illegalop(uint32_t opcode) {
// Zero values are used as sentinels in the TNT ROM and are thus somewhat
// common, don't log them.
// Example: ciexit in Old World Open Firmware uses opcode 0.
if (opcode) {
PPCDisasmContext ctx;
ctx.instr_code = opcode;
ctx.instr_addr = 0;
ctx.simplified = false;
auto op_name = disassemble_single(&ctx);
LOG_F(WARNING, "Illegal opcode exception raised for 0x%08x (decoded as %s). The PC was 0x%08x.", opcode, op_name.c_str(), ppc_state.pc);
}
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
@@ -344,7 +345,7 @@ void ppc_main_opcode(PPCOpcode *opcodeGrabber, uint32_t opcode)
static long long cpu_now_ns() {
#ifdef __APPLE__
return ConvertHostTimeToNanos2(mach_absolute_time());
return clock_gettime_nsec_np(CLOCK_UPTIME_RAW);
#else
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch()).count();
@@ -375,16 +376,34 @@ void set_virt_time_ns(uint64_t time_now)
LOG_F(INFO, "time before: %lld after: %lld change: %lld", time_now, time_new, time_new - time_now);
}
static constexpr uint64_t TIMER_POLL_INTERVAL_NS = 500'000;
static uint64_t process_events()
{
exec_timer = false;
uint64_t slice_ns = TimerManager::get_instance()->process_timers();
if (slice_ns == 0) {
// execute 25.000 cycles
// if there are no pending timers
return g_icycles + 25000;
uint64_t next_ns = TimerManager::get_instance()->process_timers();
if (g_realtime) {
uint64_t time_now = get_virt_time_ns();
uint64_t delay_ns;
if (next_ns) {
delay_ns = next_ns > time_now ? next_ns - time_now : 0;
} else {
delay_ns = TIMER_POLL_INTERVAL_NS;
}
// Host time and the instruction counter advance independently. Schedule
// a relative instruction batch, capped so long deadlines still poll.
// Comparing an absolute wall-time deadline with g_icycles can otherwise
// make a fast interpreter process timers after every instruction.
return g_icycles + (std::min(delay_ns, TIMER_POLL_INTERVAL_NS) >> icnt_factor) + 1;
}
return g_icycles + (slice_ns >> icnt_factor) + 1;
return (
(
next_ns ?
next_ns
:
get_virt_time_ns() + TIMER_POLL_INTERVAL_NS
) >> icnt_factor
) + 1;
}
static void force_cycle_counter_reload()
@@ -1033,9 +1052,6 @@ void ppc_cpu_init(MemCtrlBase* mem_ctrl, uint32_t cpu_version, bool do_include_6
TimerManager::get_instance()->set_notify_changes_cb(&force_cycle_counter_reload);
// initialize time base facility
#ifdef __APPLE__
mach_timebase_info(&timebase_info);
#endif
g_nanoseconds_base = cpu_now_ns();
g_icycles = 0;
@@ -1108,13 +1124,14 @@ static map<string, int> SPRName2Num = {
{"DBAT2L", 541}, {"DBAT3U", 542}, {"DBAT3L", 543},
{"HID0", SPR::HID0}, {"HID1", SPR::HID1}, {"IABR", 1010},
{"DABR", 1013}, {"L2CR", 1017}, {"ICTC", 1019},
{"THRM1", 1020}, {"THRM2", 1021}, {"THRM3", 1022},
{"THRM1", SPR::THRM1}, {"THRM2", SPR::THRM2}, {"THRM3", SPR::THRM3},
{"PIR", 1023}, {"TBL", SPR::TBL_S}, {"TBU", SPR::TBU_S},
{"SDR1", SPR::SDR1}, {"MQ", SPR::MQ}, {"RTCU", SPR::RTCU_S},
{"RTCL", SPR::RTCL_S}, {"DSISR", SPR::DSISR}, {"DAR", SPR::DAR},
{"MMCR0", SPR::MMCR0}, {"PMC1", SPR::PMC1}, {"PMC2", SPR::PMC2},
{"SDA", SPR::SDA}, {"SIA", SPR::SIA}, {"MMCR1", SPR::MMCR1},
{"PMC3", SPR::PMC3}, {"PMC4", SPR::PMC4},
{"PMC3", SPR::PMC3}, {"PMC4", SPR::PMC4}, {"EAR", SPR::EAR},
// get value from supervisor index same as we do for SPR268 and SPR269
{"TBL_U", SPR::TBL_S}, {"TBU_U", SPR::TBU_S},
};
+45 -20
View File
@@ -21,14 +21,19 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
// The floating point opcodes for the processor - ppcfpopcodes.cpp
#include "ppcemu.h"
#include "ppcmacros.h"
#include "ppcmmu.h"
#include <stdlib.h>
#include <cpu/ppc/ppcdechelpers.h>
#include <cpu/ppc/ppcemu.h>
#include <cpu/ppc/ppcmmu.h>
#include <cfenv>
#include <cfloat>
#include <cinttypes>
#include <cmath>
#include <cfloat>
#include <stdlib.h>
#if defined(__APPLE__) && defined(__aarch64__)
#include <arm_acle.h>
#endif
inline static void ppc_update_cr1() {
// copy FPSCR[FX|FEX|VX|OX] to CR1
@@ -116,6 +121,26 @@ static double set_endresult_nan() {
return std::numeric_limits<double>::quiet_NaN();
}
#if FE_ALL_EXCEPT
static int test_and_clear_fp_exceptions() {
#if defined(__APPLE__) && defined(__aarch64__)
// Darwin's FE_* masks match the ARM64 FPSR exception bits. Preserve
// other status bits and avoid a second register read when clearing.
uint64_t fpsr = __arm_rsr64("fpsr");
int exceptions = fpsr & FE_ALL_EXCEPT;
if (exceptions) {
fpsr &= ~uint64_t(FE_ALL_EXCEPT);
__arm_wsr64("fpsr", fpsr);
}
#else
int exceptions = std::fetestexcept(FE_ALL_EXCEPT);
if (exceptions)
std::feclearexcept(FE_ALL_EXCEPT);
#endif
return exceptions;
}
#endif
static void fpresult_update(double set_result) {
if (std::isnan(set_result)) {
ppc_state.fpscr |= FPCC_FUNAN | FPRCD;
@@ -127,18 +152,18 @@ static void fpresult_update(double set_result) {
} else {
ppc_state.fpscr |= FPCC_ZERO;
}
if (std::fetestexcept(FE_OVERFLOW)) {
#if FE_ALL_EXCEPT
int exceptions = test_and_clear_fp_exceptions();
if (exceptions & FE_OVERFLOW) {
ppc_state.fpscr |= (OX + FX);
}
if (std::fetestexcept(FE_UNDERFLOW)) {
if (exceptions & FE_UNDERFLOW) {
ppc_state.fpscr |= (UX + FX);
}
if (std::fetestexcept(FE_DIVBYZERO)) {
if (exceptions & FE_DIVBYZERO) {
ppc_state.fpscr |= (ZX + FX);
}
std::feclearexcept(FE_ALL_EXCEPT);
#endif
if (std::isinf(set_result))
ppc_state.fpscr |= FPCC_FUNAN;
@@ -420,7 +445,7 @@ void dppc_interpreter::ppc_fnmadd(uint32_t opcode) {
if (snan_single_check(reg_a) || snan_single_check(reg_b) || snan_single_check(reg_c)) {
uint64_t qnan = 0x7FFC000000000000;
ppc_store_fpresult_int(reg_d, qnan);
}
}
else {
ppc_store_fpresult_flt(reg_d, ppc_dblresult64_d);
}
@@ -1024,7 +1049,7 @@ void dppc_interpreter::ppc_lfsu(uint32_t opcode) {
ppc_store_iresult_reg(reg_a, ea);
}
else {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
}
}
@@ -1045,7 +1070,7 @@ void dppc_interpreter::ppc_lfsux(uint32_t opcode) {
ppc_store_iresult_reg(reg_a, ea);
}
else {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
return;
}
}
@@ -1069,7 +1094,7 @@ void dppc_interpreter::ppc_lfdu(uint32_t opcode) {
ppc_store_iresult_reg(reg_a, ea);
}
else {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
}
}
@@ -1090,7 +1115,7 @@ void dppc_interpreter::ppc_lfdux(uint32_t opcode) {
ppc_store_iresult_reg(reg_a, ea);
}
else {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
}
}
@@ -1113,7 +1138,7 @@ void dppc_interpreter::ppc_stfsu(uint32_t opcode) {
ppc_store_iresult_reg(reg_a, ea);
}
else {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
}
}
@@ -1134,7 +1159,7 @@ void dppc_interpreter::ppc_stfsux(uint32_t opcode) {
ppc_store_iresult_reg(reg_a, ea);
}
else {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
}
}
@@ -1155,7 +1180,7 @@ void dppc_interpreter::ppc_stfdu(uint32_t opcode) {
ppc_store_iresult_reg(reg_a, ea);
}
else {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
}
}
@@ -1174,7 +1199,7 @@ void dppc_interpreter::ppc_stfdux(uint32_t opcode) {
ppc_store_iresult_reg(reg_a, ea);
}
else {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
}
}
-213
View File
@@ -1,213 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team
(See CREDITS.MD for more details)
(You may also contact divingkxt or powermax2286 on Discord)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef PPC_MACROS_H
#define PPC_MACROS_H
#include <cinttypes>
#define ppc_grab_regsdasimm(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int32_t simm = int32_t(int16_t(opcode)); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsdauimm(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
uint32_t uimm = uint16_t(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsasimm(opcode) \
int reg_a = (opcode >> 16) & 31; \
int32_t simm = int32_t(int16_t(opcode)); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssauimm(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
uint32_t uimm = uint16_t(opcode); \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_crfd_regsauimm(opcode) \
int crf_d = (opcode >> 21) & 0x1C; \
int reg_a = (opcode >> 16) & 31; \
uint32_t uimm = uint16_t(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_da(opcode)\
int reg_d = (opcode >> 21) & 31;\
int reg_a = (opcode >> 16) & 31;\
#define ppc_grab_dab(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31;
#define ppc_grab_s(opcode) \
int reg_s = (opcode >> 21) & 31; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s];
#define ppc_grab_regsdab(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regssab(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b]; \
#define ppc_grab_regssab_stswx(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regsab(opcode) \
int reg_a = (opcode >> 16) & 31;\
int reg_b = (opcode >> 11) & 31;\
uint32_t ppc_result_a = ppc_state.gpr[reg_a];\
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regssa(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssa_stmw(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssash(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
unsigned rot_sh = (opcode >> 11) & 31; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssash_stswi(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
unsigned rot_sh = (opcode >> 11) & 31; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssb(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_b = (opcode >> 11) & 31; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b]; \
#define ppc_grab_regsda(opcode) \
int reg_d = (opcode >> 21) & 31; \
uint32_t reg_a = (opcode >> 16) & 31; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsdb(opcode) \
int reg_d = (opcode >> 21) & 31; \
uint32_t reg_b = (opcode >> 11) & 31; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_store_iresult_reg(reg, ppc_result)\
ppc_state.gpr[reg] = ppc_result
#define ppc_store_fpresult_int(reg, ppc_result64_d)\
ppc_state.fpr[(reg)].int64_r = ppc_result64_d
#define ppc_store_fpresult_flt(reg, ppc_dblresult64_d)\
ppc_state.fpr[(reg)].dbl64_r = ppc_dblresult64_d
#define ppc_grab_regsfpdb(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_b = (opcode >> 11) & 31;
#define GET_FPR(reg) \
ppc_state.fpr[(reg)].dbl64_r
#define FPR_INT(reg) \
ppc_state.fpr[reg].int64_r
#define ppc_grab_regsfpdiab(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
uint32_t val_reg_a = ppc_state.gpr[reg_a]; \
uint32_t val_reg_b = ppc_state.gpr[reg_b];
#define ppc_grab_regsfpdia(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
uint32_t val_reg_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsfpsia(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
uint32_t val_reg_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsfpsiab(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
uint32_t val_reg_a = ppc_state.gpr[reg_a]; \
uint32_t val_reg_b = ppc_state.gpr[reg_b];
#define ppc_grab_regsfpsab(opcode) \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
int crf_d = (opcode >> 21) & 0x1C; \
double db_test_a = GET_FPR(reg_a); \
double db_test_b = GET_FPR(reg_b);
#define ppc_grab_regsfpdab(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
double val_reg_a = GET_FPR(reg_a); \
double val_reg_b = GET_FPR(reg_b);
#define ppc_grab_regsfpdac(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_c = (opcode >> 6) & 31; \
double val_reg_a = GET_FPR(reg_a); \
double val_reg_c = GET_FPR(reg_c);
#define ppc_grab_regsfpdabc(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
int reg_c = (opcode >> 6) & 31; \
double val_reg_a = GET_FPR(reg_a); \
double val_reg_b = GET_FPR(reg_b); \
double val_reg_c = GET_FPR(reg_c);
#endif // PPC_MACROS_H
+276 -307
View File
@@ -31,6 +31,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cinttypes>
#include <loguru.hpp>
#include <stdexcept>
#include <vector>
//#define MMU_PROFILING // uncomment this to enable MMU profiling
//#define TLB_PROFILING // uncomment this to enable SoftTLB profiling
@@ -56,6 +57,7 @@ uint64_t iomem_writes_total = 0; // counts I/O memory writes
uint64_t exec_reads_total = 0; // counts reads from executable memory
uint64_t bat_transl_total = 0; // counts BAT translations
uint64_t ptab_transl_total = 0; // counts page table translations
uint64_t pat_flushes_total = 0; // counts full page-translation TLB flushes
uint64_t unaligned_reads = 0; // counts unaligned reads
uint64_t unaligned_writes = 0; // counts unaligned writes
uint64_t unaligned_crossp_r = 0; // counts unaligned crosspage reads
@@ -376,7 +378,9 @@ static PATResult page_address_translation(uint32_t la, bool is_instr_fetch,
};
}
MapDmaResult mmu_map_dma_mem(uint32_t addr, uint32_t size, bool allow_mmio, bool is_dbg) {
MapDmaResult mmu_map_dma_mem(uint32_t addr, uint32_t size,
bool allow_mmio, bool allow_partial, bool is_dbg)
{
MMIODevice *devobj = nullptr;
uint8_t *host_va = nullptr;
uint32_t dev_base = 0;
@@ -430,10 +434,18 @@ MapDmaResult mmu_map_dma_mem(uint32_t addr, uint32_t size, bool allow_mmio, bool
addr, addr + size - 1
);
} else {
if (is_dbg) goto fail;
ABORT_F("SOS: DMA access to unmapped physical memory 0x%08X..0x%08X because size extends outside region!",
addr, addr + size - 1
);
if (allow_partial) {
if (!is_dbg)
LOG_F(INFO, "DMA access to physical memory 0x%08X..0x%08X spans regions!",
addr, addr + size - 1
);
size = cur_dma_rgn->end - addr + 1;
} else {
if (is_dbg) goto fail;
ABORT_F("DMA access to physical memory 0x%08X..0x%08X spans regions!",
addr, addr + size - 1
);
}
}
}
@@ -453,15 +465,23 @@ MapDmaResult mmu_map_dma_mem(uint32_t addr, uint32_t size, bool allow_mmio, bool
is_writable = true; // all MMIO devices must provide a write method
}
return MapDmaResult{cur_dma_rgn->type, is_writable, host_va, devobj, dev_base};
return MapDmaResult{
.type = cur_dma_rgn->type,
.size = size,
.is_writable = is_writable,
.host_va = host_va,
.dev_obj = devobj,
.dev_base = dev_base,
};
fail:
return MapDmaResult{RT_NONE, false, nullptr, nullptr, 0};
return MapDmaResult{
.type = RT_NONE
};
}
constexpr uint32_t TLB_SIZE = 4096;
constexpr uint32_t TLB2_WAYS = 4;
constexpr uint32_t TLB_INVALID_TAG = 0xFFFFFFFF;
constexpr uint32_t TLB_VPS_MASK = 0x0FFFF000; // mask for TLB invalidation
enum TLBFlags : uint16_t {
PAGE_MEM = 1 << 0, // memory page backed by host memory
@@ -471,15 +491,14 @@ enum TLBFlags : uint16_t {
TLBE_FROM_PAT = 1 << 4, // TLB entry has been translated with PAT
PAGE_WRITABLE = 1 << 5, // page is writable
PTE_SET_C = 1 << 6, // tells if C bit of the PTE needs to be updated
TLBE_CTX_TRACKED = 1 << 7, // entry pointer is in gTrackedIEntries or gTrackedDEntries
};
// PAT context changes are frequent, so implicitly invalidate PAT-derived
// entries via a generation counter (instead of walking the TLB array and
// clearing every time).
static uint32_t gTLBPatGeneration = 0;
constexpr uint16_t TLBE_FROM_TRANSLATION =
TLBFlags::TLBE_FROM_BAT | TLBFlags::TLBE_FROM_PAT;
typedef struct TLBEntry {
uint32_t tag; // use is_invalid() or matches_tag() for validity checks
uint32_t tag;
uint16_t flags;
uint16_t lru_bits;
union {
@@ -493,23 +512,100 @@ typedef struct TLBEntry {
};
};
uint32_t phys_tag;
uint32_t pat_generation;
bool is_invalid() const
{
return tag == TLB_INVALID_TAG ||
((flags & TLBFlags::TLBE_FROM_PAT) &&
pat_generation != gTLBPatGeneration);
}
bool matches_tag(uint32_t tag_in) const
{
return tag == tag_in &&
(!(flags & TLBFlags::TLBE_FROM_PAT) ||
pat_generation == gTLBPatGeneration);
}
uint32_t reserved;
} TLBEntry;
// Track slots populated by either page or block address translation. Context
// changes can then invalidate only populated slots without adding a generation
// check to every TLB lookup.
static std::vector<TLBEntry *> gTrackedIEntries;
static std::vector<TLBEntry *> gTrackedDEntries;
// TLBE_FROM_* sources awaiting invalidation at the next context sync.
static uint16_t gPendingIInvalidationSources = 0;
static uint16_t gPendingDInvalidationSources = 0;
template <const TLBType tlb_type>
static void track_translated_entry(TLBEntry *tlb_entry)
{
if (!(tlb_entry->flags & TLBE_FROM_TRANSLATION) ||
(tlb_entry->flags & TLBFlags::TLBE_CTX_TRACKED))
return;
tlb_entry->flags |= TLBFlags::TLBE_CTX_TRACKED;
if (tlb_type == TLBType::ITLB)
gTrackedIEntries.push_back(tlb_entry);
else
gTrackedDEntries.push_back(tlb_entry);
}
static void tlb_invalidate_tracked_entries(std::vector<TLBEntry *> &tracked_entries,
uint16_t sources)
{
size_t retained_count = 0;
for (TLBEntry *tlb_entry : tracked_entries) {
uint16_t source = tlb_entry->flags & TLBE_FROM_TRANSLATION;
if (source & sources) {
tlb_entry->tag = TLB_INVALID_TAG;
tlb_entry->flags &= ~TLBFlags::TLBE_CTX_TRACKED;
} else if (source) {
tracked_entries[retained_count++] = tlb_entry;
} else {
tlb_entry->flags &= ~TLBFlags::TLBE_CTX_TRACKED;
}
}
tracked_entries.resize(retained_count);
}
template <const TLBType tlb_type>
static void tlb_invalidate_tracked_entries()
{
uint16_t *pending_sources;
std::vector<TLBEntry *> *tracked_entries;
if (tlb_type == TLBType::ITLB) {
pending_sources = &gPendingIInvalidationSources;
tracked_entries = &gTrackedIEntries;
} else {
pending_sources = &gPendingDInvalidationSources;
tracked_entries = &gTrackedDEntries;
}
if (!*pending_sources)
return;
tlb_invalidate_tracked_entries(*tracked_entries, *pending_sources);
*pending_sources = 0;
}
static void schedule_tlb_invalidation(TLBType tlb_type, uint16_t sources_to_invalidate)
{
uint16_t *pending_sources;
if (tlb_type == TLBType::ITLB)
pending_sources = &gPendingIInvalidationSources;
else
pending_sources = &gPendingDInvalidationSources;
if (!*pending_sources) {
if (tlb_type == TLBType::ITLB)
add_ctx_sync_action(&tlb_invalidate_tracked_entries<TLBType::ITLB>);
else
add_ctx_sync_action(&tlb_invalidate_tracked_entries<TLBType::DTLB>);
}
*pending_sources |= sources_to_invalidate;
}
template <const TLBType tlb_type>
static void promote_tlb_entry(TLBEntry *tlb1_entry, const TLBEntry *tlb2_entry)
{
uint16_t tracked = tlb1_entry->flags & TLBFlags::TLBE_CTX_TRACKED;
*tlb1_entry = *tlb2_entry;
tlb1_entry->flags &= ~TLBFlags::TLBE_CTX_TRACKED;
tlb1_entry->flags |= tracked;
track_translated_entry<tlb_type>(tlb1_entry);
}
// primary ITLB for all MMU modes
static std::array<TLBEntry, TLB_SIZE> itlb1_mode1;
static std::array<TLBEntry, TLB_SIZE> itlb1_mode2;
@@ -595,6 +691,27 @@ void mmu_change_mode()
}
}
template <uint32_t way>
static inline void tlb2_touch_way(TLBEntry *tlb_entry)
{
static_assert(way < TLB2_WAYS);
// Each pair is one branch of the four-way tree-based LRU. Mark the
// selected way as most recently used, its sibling as the next replacement
// candidate, and the other pair as less recently used.
if constexpr (way < 2) {
tlb_entry[0].lru_bits = way == 0 ? 0x3 : 0x2;
tlb_entry[1].lru_bits = way == 1 ? 0x3 : 0x2;
tlb_entry[2].lru_bits &= 0x1;
tlb_entry[3].lru_bits &= 0x1;
} else {
tlb_entry[0].lru_bits &= 0x1;
tlb_entry[1].lru_bits &= 0x1;
tlb_entry[2].lru_bits = way == 2 ? 0x3 : 0x2;
tlb_entry[3].lru_bits = way == 3 ? 0x3 : 0x2;
}
}
template <const TLBType tlb_type>
static TLBEntry* tlb2_target_entry(uint32_t gp_va)
{
@@ -607,65 +724,33 @@ static TLBEntry* tlb2_target_entry(uint32_t gp_va)
}
// select the target from invalid blocks first
if (tlb_entry[0].is_invalid()) {
// update LRU bits
tlb_entry[0].lru_bits = 0x3;
tlb_entry[1].lru_bits = 0x2;
tlb_entry[2].lru_bits &= 0x1;
tlb_entry[3].lru_bits &= 0x1;
if (tlb_entry[0].tag == TLB_INVALID_TAG) {
tlb2_touch_way<0>(tlb_entry);
return tlb_entry;
} else if (tlb_entry[1].is_invalid()) {
// update LRU bits
tlb_entry[0].lru_bits = 0x2;
tlb_entry[1].lru_bits = 0x3;
tlb_entry[2].lru_bits &= 0x1;
tlb_entry[3].lru_bits &= 0x1;
} else if (tlb_entry[1].tag == TLB_INVALID_TAG) {
tlb2_touch_way<1>(tlb_entry);
return &tlb_entry[1];
} else if (tlb_entry[2].is_invalid()) {
// update LRU bits
tlb_entry[0].lru_bits &= 0x1;
tlb_entry[1].lru_bits &= 0x1;
tlb_entry[2].lru_bits = 0x3;
tlb_entry[3].lru_bits = 0x2;
} else if (tlb_entry[2].tag == TLB_INVALID_TAG) {
tlb2_touch_way<2>(tlb_entry);
return &tlb_entry[2];
} else if (tlb_entry[3].is_invalid()) {
// update LRU bits
tlb_entry[0].lru_bits &= 0x1;
tlb_entry[1].lru_bits &= 0x1;
tlb_entry[2].lru_bits = 0x2;
tlb_entry[3].lru_bits = 0x3;
} else if (tlb_entry[3].tag == TLB_INVALID_TAG) {
tlb2_touch_way<3>(tlb_entry);
return &tlb_entry[3];
} else { // no free entries, replace an existing one according with the hLRU policy
#ifdef TLB_PROFILING
num_entry_replacements++;
#endif
if (tlb_entry[0].lru_bits == 0) {
// update LRU bits
tlb_entry[0].lru_bits = 0x3;
tlb_entry[1].lru_bits = 0x2;
tlb_entry[2].lru_bits &= 0x1;
tlb_entry[3].lru_bits &= 0x1;
tlb2_touch_way<0>(tlb_entry);
return tlb_entry;
} else if (tlb_entry[1].lru_bits == 0) {
// update LRU bits
tlb_entry[0].lru_bits = 0x2;
tlb_entry[1].lru_bits = 0x3;
tlb_entry[2].lru_bits &= 0x1;
tlb_entry[3].lru_bits &= 0x1;
tlb2_touch_way<1>(tlb_entry);
return &tlb_entry[1];
} else if (tlb_entry[2].lru_bits == 0) {
// update LRU bits
tlb_entry[0].lru_bits &= 0x1;
tlb_entry[1].lru_bits &= 0x1;
tlb_entry[2].lru_bits = 0x3;
tlb_entry[3].lru_bits = 0x2;
tlb2_touch_way<2>(tlb_entry);
return &tlb_entry[2];
} else {
// update LRU bits
tlb_entry[0].lru_bits &= 0x1;
tlb_entry[1].lru_bits &= 0x1;
tlb_entry[2].lru_bits = 0x2;
tlb_entry[3].lru_bits = 0x3;
tlb2_touch_way<3>(tlb_entry);
return &tlb_entry[3];
}
}
@@ -714,11 +799,12 @@ static TLBEntry* itlb2_refill(uint32_t guest_va)
const uint32_t tag = guest_va & ~0xFFFUL;
tlb_entry = tlb2_target_entry<TLBType::ITLB>(tag);
tlb_entry->tag = tag;
tlb_entry->flags = flags | TLBFlags::PAGE_MEM;
tlb_entry->flags = flags | TLBFlags::PAGE_MEM |
(tlb_entry->flags & TLBFlags::TLBE_CTX_TRACKED);
tlb_entry->host_va_offs_r = (int64_t)rgn_desc->mem_ptr - guest_va +
(phys_addr - rgn_desc->start);
tlb_entry->phys_tag = phys_addr & ~0xFFFUL;
tlb_entry->pat_generation = gTLBPatGeneration;
track_translated_entry<TLBType::ITLB>(tlb_entry);
} else {
ABORT_F("Instruction fetch from unmapped memory at 0x%08X!\n", phys_addr);
}
@@ -787,14 +873,16 @@ static TLBEntry* dtlb2_refill(uint32_t guest_va, int is_write, bool is_dbg = fal
tlb_entry = tlb2_target_entry<TLBType::DTLB>(tag);
tlb_entry->tag = tag;
if (rgn_desc->type & RT_MMIO) { // MMIO region
tlb_entry->flags = flags | TLBFlags::PAGE_IO;
tlb_entry->flags = flags | TLBFlags::PAGE_IO |
(tlb_entry->flags & TLBFlags::TLBE_CTX_TRACKED);
tlb_entry->rgn_desc = rgn_desc;
tlb_entry->dev_base_va = guest_va - (phys_addr - rgn_desc->start);
} else { // memory region backed by host memory
tlb_entry->flags = flags | TLBFlags::PAGE_MEM;
tlb_entry->flags = flags | TLBFlags::PAGE_MEM |
(tlb_entry->flags & TLBFlags::TLBE_CTX_TRACKED);
tlb_entry->host_va_offs_r = (int64_t)rgn_desc->mem_ptr - guest_va +
(phys_addr - rgn_desc->start);
if (rgn_desc->type == RT_ROM) {
if (rgn_desc->type & RT_ROM) {
// redirect writes to the dummy page for ROM regions
tlb_entry->host_va_offs_w = (int64_t)&dummy_page - tag;
} else {
@@ -802,7 +890,7 @@ static TLBEntry* dtlb2_refill(uint32_t guest_va, int is_write, bool is_dbg = fal
}
}
tlb_entry->phys_tag = phys_addr & ~0xFFFUL;
tlb_entry->pat_generation = gTLBPatGeneration;
track_translated_entry<TLBType::DTLB>(tlb_entry);
return tlb_entry;
} else {
if (!is_dbg) {
@@ -831,32 +919,16 @@ static inline TLBEntry* lookup_secondary_tlb(uint32_t guest_va, uint32_t tag) {
tlb_entry = &pCurDTLB2[((guest_va >> PPC_PAGE_SIZE_BITS) & tlb_size_mask) * TLB2_WAYS];
}
if (tlb_entry[0].matches_tag(tag)) {
// update LRU bits
tlb_entry[0].lru_bits = 0x3;
tlb_entry[1].lru_bits = 0x2;
tlb_entry[2].lru_bits &= 0x1;
tlb_entry[3].lru_bits &= 0x1;
} else if (tlb_entry[1].matches_tag(tag)) {
// update LRU bits
tlb_entry[0].lru_bits = 0x2;
tlb_entry[1].lru_bits = 0x3;
tlb_entry[2].lru_bits &= 0x1;
tlb_entry[3].lru_bits &= 0x1;
if (tlb_entry[0].tag == tag) {
tlb2_touch_way<0>(tlb_entry);
} else if (tlb_entry[1].tag == tag) {
tlb2_touch_way<1>(tlb_entry);
tlb_entry = &tlb_entry[1];
} else if (tlb_entry[2].matches_tag(tag)) {
// update LRU bits
tlb_entry[0].lru_bits &= 0x1;
tlb_entry[1].lru_bits &= 0x1;
tlb_entry[2].lru_bits = 0x3;
tlb_entry[3].lru_bits = 0x2;
} else if (tlb_entry[2].tag == tag) {
tlb2_touch_way<2>(tlb_entry);
tlb_entry = &tlb_entry[2];
} else if (tlb_entry[3].matches_tag(tag)) {
// update LRU bits
tlb_entry[0].lru_bits &= 0x1;
tlb_entry[1].lru_bits &= 0x1;
tlb_entry[2].lru_bits = 0x2;
tlb_entry[3].lru_bits = 0x3;
} else if (tlb_entry[3].tag == tag) {
tlb2_touch_way<3>(tlb_entry);
tlb_entry = &tlb_entry[3];
} else {
return nullptr;
@@ -864,20 +936,59 @@ static inline TLBEntry* lookup_secondary_tlb(uint32_t guest_va, uint32_t tag) {
return tlb_entry;
}
struct TLBLookupResult {
TLBEntry *primary_entry;
TLBEntry *matched_entry; // nullptr if both TLBs missed
bool primary_hit;
};
template <const TLBType tlb_type>
static inline TLBLookupResult lookup_tlb(uint32_t guest_va, uint32_t tag)
{
TLBEntry *primary_entry;
if constexpr (tlb_type == TLBType::ITLB) {
primary_entry = &pCurITLB1[(guest_va >> PPC_PAGE_SIZE_BITS) & tlb_size_mask];
} else {
primary_entry = &pCurDTLB1[(guest_va >> PPC_PAGE_SIZE_BITS) & tlb_size_mask];
}
if (primary_entry->tag == tag) {
return TLBLookupResult{primary_entry, primary_entry, true};
}
return TLBLookupResult{
primary_entry,
lookup_secondary_tlb<tlb_type>(guest_va, tag),
false
};
}
// Returns true when the PTE.C bit was updated. Callers writing through a
// primary entry use this to mirror the update into the secondary TLB.
static inline bool prepare_dtlb_write(TLBEntry *tlb_entry, uint32_t guest_va)
{
if (!(tlb_entry->flags & TLBFlags::PAGE_WRITABLE)) {
ppc_state.spr[SPR::DSISR] = 0x08000000 | (1 << 25);
ppc_state.spr[SPR::DAR] = guest_va;
mmu_exception_handler(Except_Type::EXC_DSI, 0);
}
if (tlb_entry->flags & TLBFlags::PTE_SET_C) {
return false;
}
// Perform full page address translation to update the PTE.C bit.
page_address_translation(guest_va, false, !!(ppc_state.msr & MSR::PR), true);
tlb_entry->flags |= TLBFlags::PTE_SET_C;
return true;
}
void mmu_dcbz(uint32_t opcode, uint32_t guest_va)
{
const uint32_t tag = guest_va & ~0xFFFUL;
// look up guest virtual address in the primary TLB
TLBEntry *tlb_entry = &pCurDTLB1[(guest_va >> PPC_PAGE_SIZE_BITS) & tlb_size_mask];
if (!tlb_entry->matches_tag(tag)) {
// primary TLB miss -> look up address in the secondary TLB
tlb_entry = lookup_secondary_tlb<TLBType::DTLB>(guest_va, tag);
if (tlb_entry == nullptr) {
// secondary TLB miss ->
// perform full address translation and refill the secondary TLB
tlb_entry = dtlb2_refill(guest_va, 1);
}
TLBEntry *tlb_entry = lookup_tlb<TLBType::DTLB>(guest_va, tag).matched_entry;
if (tlb_entry == nullptr) {
// perform full address translation and refill the secondary TLB
tlb_entry = dtlb2_refill(guest_va, 1);
}
// Check if this was in a MMIO region, in which case we avoid doing the
@@ -887,15 +998,7 @@ void mmu_dcbz(uint32_t opcode, uint32_t guest_va)
if (tlb_entry->flags & TLBFlags::PAGE_IO) {
// Still do the same checks that mmu_write_vmem would have done to
// disallow writes to read-only regions.
if (!(tlb_entry->flags & TLBFlags::PAGE_WRITABLE)) {
ppc_state.spr[SPR::DSISR] = 0x08000000 | (1 << 25);
ppc_state.spr[SPR::DAR] = guest_va;
mmu_exception_handler(Except_Type::EXC_DSI, 0);
}
if (!(tlb_entry->flags & TLBFlags::PTE_SET_C)) {
page_address_translation(guest_va, false, !!(ppc_state.msr & MSR::PR), true);
tlb_entry->flags |= TLBFlags::PTE_SET_C;
}
prepare_dtlb_write(tlb_entry, guest_va);
return;
}
@@ -924,16 +1027,15 @@ uint8_t *mmu_translate_imem(uint32_t vaddr, uint32_t *paddr)
const uint32_t tag = vaddr & ~0xFFFUL;
// look up guest virtual address in the primary ITLB
tlb1_entry = &pCurITLB1[(vaddr >> PPC_PAGE_SIZE_BITS) & tlb_size_mask];
if (tlb1_entry->matches_tag(tag)) { // primary ITLB hit -> fast path
TLBLookupResult tlb_lookup = lookup_tlb<TLBType::ITLB>(vaddr, tag);
tlb1_entry = tlb_lookup.primary_entry;
if (tlb_lookup.primary_hit) { // primary ITLB hit -> fast path
#ifdef TLB_PROFILING
num_primary_itlb_hits++;
#endif
host_va = (uint8_t *)(tlb1_entry->host_va_offs_r + vaddr);
} else {
// primary ITLB miss -> look up address in the secondary ITLB
tlb2_entry = lookup_secondary_tlb<TLBType::ITLB>(vaddr, tag);
tlb2_entry = tlb_lookup.matched_entry;
if (tlb2_entry == nullptr) {
#ifdef TLB_PROFILING
num_itlb_refills++;
@@ -948,11 +1050,7 @@ uint8_t *mmu_translate_imem(uint32_t vaddr, uint32_t *paddr)
}
#endif
// refill the primary ITLB
tlb1_entry->tag = tag;
tlb1_entry->flags = tlb2_entry->flags;
tlb1_entry->host_va_offs_r = tlb2_entry->host_va_offs_r;
tlb1_entry->phys_tag = tlb2_entry->phys_tag;
tlb1_entry->pat_generation = tlb2_entry->pat_generation;
promote_tlb_entry<TLBType::ITLB>(tlb1_entry, tlb2_entry);
host_va = (uint8_t *)(tlb1_entry->host_va_offs_r + vaddr);
}
@@ -962,114 +1060,14 @@ uint8_t *mmu_translate_imem(uint32_t vaddr, uint32_t *paddr)
return host_va;
}
static void tlb_flush_primary_entry(std::array<TLBEntry, TLB_SIZE> &tlb1, uint32_t tag)
void tlb_flush_all_pat()
{
TLBEntry *tlb_entry = &tlb1[(tag >> PPC_PAGE_SIZE_BITS) & tlb_size_mask];
if (tlb_entry->tag != TLB_INVALID_TAG && (tlb_entry->tag & TLB_VPS_MASK) == tag) {
tlb_entry->tag = TLB_INVALID_TAG;
//LOG_F(INFO, "Invalidated primary TLB entry at 0x%X", tag);
}
}
#ifdef MMU_PROFILING
pat_flushes_total++;
#endif
static void tlb_flush_secondary_entry(std::array<TLBEntry, TLB_SIZE*TLB2_WAYS> &tlb2, uint32_t tag)
{
TLBEntry *tlb_entry = &tlb2[((tag >> PPC_PAGE_SIZE_BITS) & tlb_size_mask) * TLB2_WAYS];
for (int i = 0; i < TLB2_WAYS; i++) {
if (tlb_entry[i].tag != TLB_INVALID_TAG && (tlb_entry[i].tag & TLB_VPS_MASK) == tag) {
tlb_entry[i].tag = TLB_INVALID_TAG;
//LOG_F(INFO, "Invalidated secondary TLB entry at 0x%X", tag);
}
}
}
void tlb_flush_entry(uint32_t ea)
{
const uint32_t tag = ea & TLB_VPS_MASK;
tlb_flush_primary_entry(itlb1_mode1, tag);
tlb_flush_secondary_entry(itlb2_mode1, tag);
tlb_flush_primary_entry(itlb1_mode2, tag);
tlb_flush_secondary_entry(itlb2_mode2, tag);
tlb_flush_primary_entry(itlb1_mode3, tag);
tlb_flush_secondary_entry(itlb2_mode3, tag);
tlb_flush_primary_entry(dtlb1_mode1, tag);
tlb_flush_secondary_entry(dtlb2_mode1, tag);
tlb_flush_primary_entry(dtlb1_mode2, tag);
tlb_flush_secondary_entry(dtlb2_mode2, tag);
tlb_flush_primary_entry(dtlb1_mode3, tag);
tlb_flush_secondary_entry(dtlb2_mode3, tag);
}
template <std::size_t N>
static void tlb_flush_entries(std::array<TLBEntry, N> &tlb, TLBFlags type) {
for (auto &tlb_el : tlb) {
if (tlb_el.tag != TLB_INVALID_TAG && tlb_el.flags & type) {
tlb_el.tag = TLB_INVALID_TAG;
}
}
}
template <const TLBType tlb_type>
void tlb_flush_entries(TLBFlags type)
{
// Mode 1 is real addressing and thus can't contain any PAT entries by definition.
bool flush_mode1 = type != TLBE_FROM_PAT;
if (tlb_type == TLBType::ITLB) {
if (flush_mode1) {
tlb_flush_entries(itlb1_mode1, type);
}
tlb_flush_entries(itlb1_mode2, type);
tlb_flush_entries(itlb1_mode3, type);
if (flush_mode1) {
tlb_flush_entries(itlb2_mode1, type);
}
tlb_flush_entries(itlb2_mode2, type);
tlb_flush_entries(itlb2_mode3, type);
} else {
if (flush_mode1) {
tlb_flush_entries(dtlb1_mode1, type);
}
tlb_flush_entries(dtlb1_mode2, type);
tlb_flush_entries(dtlb1_mode3, type);
if (flush_mode1) {
tlb_flush_entries(dtlb2_mode1, type);
}
tlb_flush_entries(dtlb2_mode2, type);
tlb_flush_entries(dtlb2_mode3, type);
}
}
static bool gTLBFlushIBatEntries = false;
static bool gTLBFlushDBatEntries = false;
static bool gTLBInvalidatePatEntries = false;
template <const TLBType tlb_type>
void tlb_flush_bat_entries()
{
if (tlb_type == TLBType::ITLB) {
if (!gTLBFlushIBatEntries)
return;
tlb_flush_entries<TLBType::ITLB>(TLBE_FROM_BAT);
gTLBFlushIBatEntries = false;
} else {
if (!gTLBFlushDBatEntries)
return;
tlb_flush_entries<TLBType::DTLB>(TLBE_FROM_BAT);
gTLBFlushDBatEntries = false;
}
}
static void tlb_invalidate_pat_entries()
{
if (!gTLBInvalidatePatEntries)
return;
gTLBPatGeneration++;
if (gTLBPatGeneration == 0) { // Do a full flush when the counter wraps around
tlb_flush_entries<TLBType::ITLB>(TLBE_FROM_PAT);
tlb_flush_entries<TLBType::DTLB>(TLBE_FROM_PAT);
}
gTLBInvalidatePatEntries = false;
tlb_invalidate_tracked_entries(gTrackedIEntries, TLBE_FROM_PAT);
tlb_invalidate_tracked_entries(gTrackedDEntries, TLBE_FROM_PAT);
}
static void mpc601_bat_update(uint32_t bat_reg)
@@ -1097,26 +1095,19 @@ static void mpc601_bat_update(uint32_t bat_reg)
// copy IBAT entry to DBAT entry
*dbat_entry = *ibat_entry;
} else {
// disable the corresponding BAT paars
// disable the corresponding BAT pairs
ibat_entry->valid = false;
dbat_entry->valid = false;
}
// MPC601 has unified BATs so we're going to flush both ITLB and DTLB
if (!gTLBFlushIBatEntries) {
gTLBFlushIBatEntries = true;
add_ctx_sync_action(&tlb_flush_bat_entries<TLBType::ITLB>);
}
if (!gTLBFlushDBatEntries) {
gTLBFlushDBatEntries = true;
add_ctx_sync_action(&tlb_flush_bat_entries<TLBType::DTLB>);
}
mmu_pat_ctx_changed();
// MPC601 has unified BATs, so they affect both translation contexts.
schedule_tlb_invalidation(TLBType::ITLB, TLBE_FROM_TRANSLATION);
schedule_tlb_invalidation(TLBType::DTLB, TLBE_FROM_TRANSLATION);
}
static void mpc601_dbat_update(uint32_t /*bat_reg*/)
{
// ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
// ppc_illegalop(opcode);
}
static void ppc_ibat_update(uint32_t bat_reg)
@@ -1137,11 +1128,8 @@ static void ppc_ibat_update(uint32_t bat_reg)
bat_entry->phys_hi = ppc_state.spr[upper_reg_num + 1] & hi_mask;
bat_entry->bepi = ppc_state.spr[upper_reg_num] & hi_mask;
if (!gTLBFlushIBatEntries) {
gTLBFlushIBatEntries = true;
add_ctx_sync_action(&tlb_flush_bat_entries<TLBType::ITLB>);
}
mmu_pat_ctx_changed();
// A new IBAT can shadow an existing page translation.
schedule_tlb_invalidation(TLBType::ITLB, TLBE_FROM_TRANSLATION);
}
static void ppc_dbat_update(uint32_t bat_reg)
@@ -1162,21 +1150,16 @@ static void ppc_dbat_update(uint32_t bat_reg)
bat_entry->phys_hi = ppc_state.spr[upper_reg_num + 1] & hi_mask;
bat_entry->bepi = ppc_state.spr[upper_reg_num] & hi_mask;
if (!gTLBFlushDBatEntries) {
gTLBFlushDBatEntries = true;
add_ctx_sync_action(&tlb_flush_bat_entries<TLBType::DTLB>);
}
mmu_pat_ctx_changed();
// A new DBAT can shadow an existing page translation.
schedule_tlb_invalidation(TLBType::DTLB, TLBE_FROM_TRANSLATION);
}
void mmu_pat_ctx_changed()
{
// Page address translation context changed so invalidate all PAT entries
// from both ITLB and DTLB.
if (!gTLBInvalidatePatEntries) {
gTLBInvalidatePatEntries = true;
add_ctx_sync_action(&tlb_invalidate_pat_entries);
}
schedule_tlb_invalidation(TLBType::ITLB, TLBFlags::TLBE_FROM_PAT);
schedule_tlb_invalidation(TLBType::DTLB, TLBFlags::TLBE_FROM_PAT);
}
#if SUPPORTS_PPC_LITTLE_ENDIAN_MODE
@@ -1221,12 +1204,13 @@ inline T mmu_read_vmem(uint32_t opcode, uint32_t guest_va)
const uint32_t tag = guest_va & ~0xFFFUL;
// look up guest virtual address in the primary TLB
// look up guest virtual address in the primary and secondary TLBs
#if SUPPORTS_MEMORY_CTRL_ENDIAN_MODE
bool needs_swap = false;
#endif
tlb1_entry = &pCurDTLB1[(guest_va >> PPC_PAGE_SIZE_BITS) & tlb_size_mask];
if (tlb1_entry->matches_tag(tag)) { // primary TLB hit -> fast path
TLBLookupResult tlb_lookup = lookup_tlb<TLBType::DTLB>(guest_va, tag);
tlb1_entry = tlb_lookup.primary_entry;
if (tlb_lookup.primary_hit) { // primary TLB hit -> fast path
#ifdef TLB_PROFILING
num_primary_dtlb_hits++;
#endif
@@ -1241,8 +1225,7 @@ inline T mmu_read_vmem(uint32_t opcode, uint32_t guest_va)
host_va = (uint8_t *)(tlb1_entry->host_va_offs_r + guest_va);
} else {
// primary TLB miss -> look up address in the secondary TLB
tlb2_entry = lookup_secondary_tlb<TLBType::DTLB>(guest_va, tag);
tlb2_entry = tlb_lookup.matched_entry;
if (tlb2_entry == nullptr) {
#ifdef TLB_PROFILING
num_dtlb_refills++;
@@ -1262,7 +1245,7 @@ inline T mmu_read_vmem(uint32_t opcode, uint32_t guest_va)
if (tlb2_entry->flags & TLBFlags::PAGE_MEM) { // is it a real memory region?
// refill the primary TLB
*tlb1_entry = *tlb2_entry;
promote_tlb_entry<TLBType::DTLB>(tlb1_entry, tlb2_entry);
#if SUPPORTS_MEMORY_CTRL_ENDIAN_MODE
needs_swap = mem_ctrl_instance->needs_swap_endian(false);
@@ -1392,25 +1375,17 @@ inline void mmu_write_vmem(uint32_t opcode, uint32_t guest_va, T value)
const uint32_t tag = guest_va & ~0xFFFUL;
// look up guest virtual address in the primary TLB
// look up guest virtual address in the primary and secondary TLBs
#if SUPPORTS_MEMORY_CTRL_ENDIAN_MODE
bool needs_swap = false;
#endif
tlb1_entry = &pCurDTLB1[(guest_va >> PPC_PAGE_SIZE_BITS) & tlb_size_mask];
if (tlb1_entry->matches_tag(tag)) { // primary TLB hit -> fast path
TLBLookupResult tlb_lookup = lookup_tlb<TLBType::DTLB>(guest_va, tag);
tlb1_entry = tlb_lookup.primary_entry;
if (tlb_lookup.primary_hit) { // primary TLB hit -> fast path
#ifdef TLB_PROFILING
num_primary_dtlb_hits++;
#endif
if (!(tlb1_entry->flags & TLBFlags::PAGE_WRITABLE)) {
ppc_state.spr[SPR::DSISR] = 0x08000000 | (1 << 25);
ppc_state.spr[SPR::DAR] = guest_va;
mmu_exception_handler(Except_Type::EXC_DSI, 0);
}
if (!(tlb1_entry->flags & TLBFlags::PTE_SET_C)) {
// perform full page address translation to update PTE.C bit
page_address_translation(guest_va, false, !!(ppc_state.msr & MSR::PR), true);
tlb1_entry->flags |= TLBFlags::PTE_SET_C;
if (prepare_dtlb_write(tlb1_entry, guest_va)) {
// don't forget to update the secondary TLB as well
tlb2_entry = lookup_secondary_tlb<TLBType::DTLB>(guest_va, tag);
if (tlb2_entry != nullptr) {
@@ -1426,8 +1401,7 @@ inline void mmu_write_vmem(uint32_t opcode, uint32_t guest_va, T value)
#endif
host_va = (uint8_t *)(tlb1_entry->host_va_offs_w + guest_va);
} else {
// primary TLB miss -> look up address in the secondary TLB
tlb2_entry = lookup_secondary_tlb<TLBType::DTLB>(guest_va, tag);
tlb2_entry = tlb_lookup.matched_entry;
if (tlb2_entry == nullptr) {
#ifdef TLB_PROFILING
num_dtlb_refills++;
@@ -1444,22 +1418,11 @@ inline void mmu_write_vmem(uint32_t opcode, uint32_t guest_va, T value)
num_secondary_dtlb_hits++;
}
#endif
if (!(tlb2_entry->flags & TLBFlags::PAGE_WRITABLE)) {
ppc_state.spr[SPR::DSISR] = 0x08000000 | (1 << 25);
ppc_state.spr[SPR::DAR] = guest_va;
mmu_exception_handler(Except_Type::EXC_DSI, 0);
}
if (!(tlb2_entry->flags & TLBFlags::PTE_SET_C)) {
// perform full page address translation to update PTE.C bit
page_address_translation(guest_va, false, !!(ppc_state.msr & MSR::PR), true);
tlb2_entry->flags |= TLBFlags::PTE_SET_C;
}
prepare_dtlb_write(tlb2_entry, guest_va);
if (tlb2_entry->flags & TLBFlags::PAGE_MEM) { // is it a real memory region?
// refill the primary TLB
*tlb1_entry = *tlb2_entry;
promote_tlb_entry<TLBType::DTLB>(tlb1_entry, tlb2_entry);
#if SUPPORTS_MEMORY_CTRL_ENDIAN_MODE
needs_swap = mem_ctrl_instance->needs_swap_endian(false);
@@ -1773,6 +1736,10 @@ public:
.format = ProfileVarFmt::DEC,
.value = ptab_transl_total});
vars.push_back({.name = "Full PAT TLB Flushes Total",
.format = ProfileVarFmt::DEC,
.value = pat_flushes_total});
vars.push_back({.name = "Unaligned Reads Total",
.format = ProfileVarFmt::DEC,
.value = unaligned_reads});
@@ -1798,6 +1765,7 @@ public:
exec_reads_total = 0;
bat_transl_total = 0;
ptab_transl_total = 0;
pat_flushes_total = 0;
unaligned_reads = 0;
unaligned_writes = 0;
unaligned_crossp_r = 0;
@@ -1967,13 +1935,12 @@ bool mmu_translate_dbg(uint32_t guest_va, uint32_t &guest_pa) {
const uint32_t tag = guest_va & ~0xFFFUL;
// look up guest virtual address in the primary TLB
tlb1_entry = &pCurDTLB1[(guest_va >> PPC_PAGE_SIZE_BITS) & tlb_size_mask];
TLBLookupResult tlb_lookup = lookup_tlb<TLBType::DTLB>(guest_va, tag);
tlb1_entry = tlb_lookup.primary_entry;
do {
if (!tlb1_entry->matches_tag(tag)) {
// primary TLB miss -> look up address in the secondary TLB
tlb2_entry = lookup_secondary_tlb<TLBType::DTLB>(guest_va, tag);
if (!tlb_lookup.primary_hit) {
tlb2_entry = tlb_lookup.matched_entry;
if (tlb2_entry == nullptr) {
// secondary TLB miss ->
// perform full address translation and refill the secondary TLB
@@ -1986,7 +1953,7 @@ bool mmu_translate_dbg(uint32_t guest_va, uint32_t &guest_pa) {
if (tlb2_entry->flags & TLBFlags::PAGE_MEM) { // is it a real memory region?
// refill the primary TLB
*tlb1_entry = *tlb2_entry;
promote_tlb_entry<TLBType::DTLB>(tlb1_entry, tlb2_entry);
}
else {
tlb1_entry = tlb2_entry;
@@ -2022,14 +1989,16 @@ static void invalidate_tlb_entries(std::array<TLBEntry, N> &tlb) {
tlb_el.host_va_offs_r = 0;
tlb_el.host_va_offs_w = 0;
tlb_el.phys_tag = 0;
tlb_el.pat_generation = 0;
tlb_el.reserved = 0;
}
}
void ppc_mmu_init()
{
gTLBPatGeneration = 0;
gTLBInvalidatePatEntries = false;
gPendingIInvalidationSources = 0;
gPendingDInvalidationSources = 0;
gTrackedIEntries.clear();
gTrackedDEntries.clear();
last_ptab_area = {0xFFFFFFFF, 0xFFFFFFFF, 0, 0, nullptr, nullptr};
+4 -2
View File
@@ -71,6 +71,7 @@ typedef struct PATResult {
/** DMA memory mapping result. */
typedef struct MapDmaResult {
uint32_t type;
uint32_t size;
bool is_writable;
// for memory regions
uint8_t* host_va;
@@ -89,11 +90,12 @@ extern std::function<void(uint32_t bat_reg)> dbat_update;
extern PPC_BAT_entry ibat_array[4];
extern PPC_BAT_entry dbat_array[4];
extern MapDmaResult mmu_map_dma_mem(uint32_t addr, uint32_t size, bool allow_mmio = false, bool is_dbg = false);
extern MapDmaResult mmu_map_dma_mem(uint32_t addr, uint32_t size,
bool allow_mmio = false, bool allow_partial = false, bool is_dbg = false);
extern void mmu_change_mode(void);
extern void mmu_pat_ctx_changed();
extern void tlb_flush_entry(uint32_t ea);
extern void tlb_flush_all_pat();
extern void mmu_dcbz(uint32_t opcode, uint32_t guest_va);
extern uint64_t mem_read_dbg(uint32_t virt_addr, uint32_t size);
+202 -150
View File
@@ -24,12 +24,16 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <core/bitops.h>
#include <core/timermanager.h>
#include <core/mathutils.h>
#include "ppcemu.h"
#include "ppcmacros.h"
#include "ppcmmu.h"
#include <cpu/ppc/ppcdechelpers.h>
#include <cpu/ppc/ppcemu.h>
#include <cpu/ppc/ppcmmu.h>
#include <cinttypes>
#include <vector>
static int junction_temperature = 24;
static TimerInfo thermal_timer;
//Extract the registers desired and the values of the registers.
// Affects CR Field 0 - For integer operations
@@ -48,30 +52,14 @@ void ppc_changecrf0(uint32_t set_result) {
}
// Affects the XER register's Carry Bit
inline static void ppc_carry(uint32_t a, uint32_t b) {
if (b < a) {
ppc_state.spr[SPR::XER] |= XER::CA;
} else {
ppc_state.spr[SPR::XER] &= ~XER::CA;
}
}
inline static void ppc_carry_sub(uint32_t a, uint32_t b) {
if (b >= a) {
ppc_state.spr[SPR::XER] |= XER::CA;
} else {
ppc_state.spr[SPR::XER] &= ~XER::CA;
}
inline static void ppc_carry(uint64_t ppc_result_l) {
ppc_state.spr[SPR::XER] = (ppc_state.spr[SPR::XER] & ~XER::CA) | ((ppc_result_l >> (32 - 29)) & XER::CA);
}
// Affects the XER register's SO and OV Bits
inline static void ppc_setsoov(uint32_t a, uint32_t b, uint32_t d) {
if (int32_t((a ^ b) & (a ^ d)) < 0) {
ppc_state.spr[SPR::XER] |= XER::SO | XER::OV;
} else {
ppc_state.spr[SPR::XER] &= ~XER::OV;
}
ppc_state.spr[SPR::XER] = (ppc_state.spr[SPR::XER] & ~XER::OV) |
((int32_t((a ^ b) & (a ^ d)) < 0) ? (XER::SO | XER::OV) : 0);
}
typedef std::function<void()> CtxSyncCallback;
@@ -111,8 +99,9 @@ template void dppc_interpreter::ppc_addi<SHFT1>(uint32_t opcode);
template <field_rc rec>
void dppc_interpreter::ppc_addic(uint32_t opcode) {
ppc_grab_regsdasimm(opcode);
uint32_t ppc_result_d = (ppc_result_a + simm);
ppc_carry(ppc_result_a, ppc_result_d);
uint64_t ppc_result_l = uint64_t(ppc_result_a) + uint32_t(simm);
uint32_t ppc_result_d = uint32_t(ppc_result_l);
ppc_carry(ppc_result_l);
if (rec)
ppc_changecrf0(ppc_result_d);
ppc_store_iresult_reg(reg_d, ppc_result_d);
@@ -124,10 +113,10 @@ template void dppc_interpreter::ppc_addic<RC1>(uint32_t opcode);
template <field_carry carry, field_rc rec, field_ov ov>
void dppc_interpreter::ppc_add(uint32_t opcode) {
ppc_grab_regsdab(opcode);
uint32_t ppc_result_d = ppc_result_a + ppc_result_b;
uint64_t ppc_result_l = uint64_t(ppc_result_a) + ppc_result_b;
uint32_t ppc_result_d = uint32_t(ppc_result_l);
if (carry)
ppc_carry(ppc_result_a, ppc_result_d);
ppc_carry(ppc_result_l);
if (ov)
ppc_setsoov(ppc_result_a, ~ppc_result_b, ppc_result_d);
if (rec)
@@ -148,14 +137,9 @@ template <field_rc rec, field_ov ov>
void dppc_interpreter::ppc_adde(uint32_t opcode) {
ppc_grab_regsdab(opcode);
uint32_t xer_ca = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint32_t ppc_result_d = ppc_result_a + ppc_result_b + xer_ca;
if ((ppc_result_d < ppc_result_a) || (xer_ca && (ppc_result_d == ppc_result_a))) {
ppc_state.spr[SPR::XER] |= XER::CA;
} else {
ppc_state.spr[SPR::XER] &= ~XER::CA;
}
uint64_t ppc_result_l = uint64_t(ppc_result_a) + ppc_result_b + xer_ca;
uint32_t ppc_result_d = uint32_t(ppc_result_l);
ppc_carry(ppc_result_l);
if (ov)
ppc_setsoov(ppc_result_a, ~ppc_result_b, ppc_result_d);
if (rec)
@@ -173,14 +157,9 @@ template <field_rc rec, field_ov ov>
void dppc_interpreter::ppc_addme(uint32_t opcode) {
ppc_grab_regsda(opcode);
uint32_t xer_ca = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint32_t ppc_result_d = ppc_result_a + xer_ca - 1;
if (((xer_ca - 1) < 0xFFFFFFFFUL) || (ppc_result_d < ppc_result_a)) {
ppc_state.spr[SPR::XER] |= XER::CA;
} else {
ppc_state.spr[SPR::XER] &= ~XER::CA;
}
uint64_t ppc_result_l = uint64_t(ppc_result_a) + xer_ca + uint32_t(-1);
uint32_t ppc_result_d = uint32_t(ppc_result_l);
ppc_carry(ppc_result_l);
if (ov)
ppc_setsoov(ppc_result_a, 0, ppc_result_d);
if (rec)
@@ -197,15 +176,10 @@ template void dppc_interpreter::ppc_addme<RC1, OV1>(uint32_t opcode);
template <field_rc rec, field_ov ov>
void dppc_interpreter::ppc_addze(uint32_t opcode) {
ppc_grab_regsda(opcode);
uint32_t grab_xer = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint32_t ppc_result_d = ppc_result_a + grab_xer;
if (ppc_result_d < ppc_result_a) {
ppc_state.spr[SPR::XER] |= XER::CA;
} else {
ppc_state.spr[SPR::XER] &= ~XER::CA;
}
uint32_t xer_ca = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint64_t ppc_result_l = uint64_t(ppc_result_a) + xer_ca;
uint32_t ppc_result_d = uint32_t(ppc_result_l);
ppc_carry(ppc_result_l);
if (ov)
ppc_setsoov(ppc_result_a, 0xFFFFFFFFUL, ppc_result_d);
if (rec)
@@ -221,21 +195,19 @@ template void dppc_interpreter::ppc_addze<RC1, OV1>(uint32_t opcode);
void dppc_interpreter::ppc_subfic(uint32_t opcode) {
ppc_grab_regsdasimm(opcode);
uint32_t ppc_result_d = simm - ppc_result_a;
if (simm == -1)
ppc_state.spr[SPR::XER] |= XER::CA;
else
ppc_carry(~ppc_result_a, ppc_result_d);
uint64_t ppc_result_l = uint64_t(uint32_t(~ppc_result_a)) + uint32_t(simm) + 1;
uint32_t ppc_result_d = uint32_t(ppc_result_l);
ppc_carry(ppc_result_l);
ppc_store_iresult_reg(reg_d, ppc_result_d);
}
template <field_carry carry, field_rc rec, field_ov ov>
void dppc_interpreter::ppc_subf(uint32_t opcode) {
ppc_grab_regsdab(opcode);
uint32_t ppc_result_d = ppc_result_b - ppc_result_a;
uint64_t ppc_result_l = uint64_t(uint32_t(~ppc_result_a)) + ppc_result_b + 1;
uint32_t ppc_result_d = uint32_t(ppc_result_l);
if (carry)
ppc_carry_sub(ppc_result_a, ppc_result_b);
ppc_carry(ppc_result_l);
if (ov)
ppc_setsoov(ppc_result_b, ppc_result_a, ppc_result_d);
if (rec)
@@ -256,13 +228,10 @@ template void dppc_interpreter::ppc_subf<CARRY1, RC1, OV1>(uint32_t opcode);
template <field_rc rec, field_ov ov>
void dppc_interpreter::ppc_subfe(uint32_t opcode) {
ppc_grab_regsdab(opcode);
uint32_t grab_ca = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint32_t ppc_result_d = ~ppc_result_a + ppc_result_b + grab_ca;
if (grab_ca && ppc_result_b == 0xFFFFFFFFUL)
ppc_state.spr[SPR::XER] |= XER::CA;
else
ppc_carry(~ppc_result_a, ppc_result_d);
uint32_t xer_ca = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint64_t ppc_result_l = uint64_t(uint32_t(~ppc_result_a)) + ppc_result_b + xer_ca;
uint32_t ppc_result_d = uint32_t(ppc_result_l);
ppc_carry(ppc_result_l);
if (ov)
ppc_setsoov(ppc_result_b, ppc_result_a, ppc_result_d);
if (rec)
@@ -279,14 +248,10 @@ template void dppc_interpreter::ppc_subfe<RC1, OV1>(uint32_t opcode);
template <field_rc rec, field_ov ov>
void dppc_interpreter::ppc_subfme(uint32_t opcode) {
ppc_grab_regsda(opcode);
uint32_t grab_ca = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint32_t ppc_result_d = ~ppc_result_a + grab_ca - 1;
if (ppc_result_a == 0xFFFFFFFFUL && !grab_ca)
ppc_state.spr[SPR::XER] &= ~XER::CA;
else
ppc_state.spr[SPR::XER] |= XER::CA;
uint32_t xer_ca = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint64_t ppc_result_l = uint64_t(uint32_t(~ppc_result_a)) + xer_ca + uint32_t(-1);
uint32_t ppc_result_d = uint32_t(ppc_result_l);
ppc_carry(ppc_result_l);
if (ov) {
if (ppc_result_d == ppc_result_a && int32_t(ppc_result_d) > 0)
ppc_state.spr[SPR::XER] |= XER::SO | XER::OV;
@@ -308,14 +273,10 @@ template void dppc_interpreter::ppc_subfme<RC1, OV1>(uint32_t opcode);
template <field_rc rec, field_ov ov>
void dppc_interpreter::ppc_subfze(uint32_t opcode) {
ppc_grab_regsda(opcode);
uint32_t grab_ca = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint32_t ppc_result_d = ~ppc_result_a + grab_ca;
if (!ppc_result_d && grab_ca) // special case: ppc_result_d = 0 and CA=1
ppc_state.spr[SPR::XER] |= XER::CA;
else
ppc_state.spr[SPR::XER] &= ~XER::CA;
uint32_t xer_ca = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint64_t ppc_result_l = uint64_t(uint32_t(~ppc_result_a)) + xer_ca;
uint32_t ppc_result_d = uint32_t(ppc_result_l);
ppc_carry(ppc_result_l);
if (ov) {
if (ppc_result_d && ppc_result_d == ppc_result_a)
ppc_state.spr[SPR::XER] |= XER::SO | XER::OV;
@@ -732,10 +693,10 @@ void dppc_interpreter::ppc_mtsr(uint32_t opcode) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::NOT_ALLOWED);
return;
}
int reg_s = (opcode >> 21) & 0x1F;
ppc_grab_s(opcode);
uint32_t grab_sr = (opcode >> 16) & 0x0F;
if (ppc_state.sr[grab_sr] != ppc_state.gpr[reg_s]) {
ppc_state.sr[grab_sr] = ppc_state.gpr[reg_s];
if (ppc_state.sr[grab_sr] != ppc_result_d) {
ppc_state.sr[grab_sr] = ppc_result_d;
mmu_pat_ctx_changed();
}
}
@@ -802,9 +763,9 @@ void dppc_interpreter::ppc_mtmsr(uint32_t opcode) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::NOT_ALLOWED);
return;
}
uint32_t reg_s = (opcode >> 21) & 0x1F;
ppc_grab_s(opcode);
uint32_t old_msr_val = ppc_state.msr;
uint32_t new_msr_val = ppc_state.gpr[reg_s];
uint32_t new_msr_val = ppc_result_d;
if (!is_601) {
ppc_change_endian((new_msr_val & MSR::LE) != 0);
}
@@ -819,6 +780,9 @@ void dppc_interpreter::ppc_mtmsr(uint32_t opcode) {
dec_exception_pending = false;
//LOG_F(WARNING, "MTMSR: decrementer exception triggered");
ppc_exception_handler(Except_Type::EXC_DECR, 0);
} else if ((ppc_state.msr & MSR::EE) && thrm_exception_pending) {
thrm_exception_pending = false;
ppc_exception_handler(Except_Type::EXC_THRM_MGMT_INT, 0);
} else if (ppc_state.msr & MSR::POW) [[unlikely]] {
bool enter_sleep = false;
@@ -908,11 +872,11 @@ static void update_timebase(uint64_t mask, uint64_t new_val)
tbr_wr_timestamp = get_virt_time_ns();
}
static uint32_t decrementer_timer_id = 0;
static TimerInfo decrementer_timer;
static void update_decrementer(bool update_time_stamp, uint32_t oldval, uint32_t newval);
static void trigger_decrementer_exception() {
static void trigger_decrementer_exception(uint64_t = 0, uint64_t = 0) {
if (ppc_state.msr & MSR::EE) {
dec_exception_pending = false;
//LOG_F(WARNING, "decrementer exception triggered");
@@ -924,8 +888,7 @@ static void trigger_decrementer_exception() {
}
}
static void trigger_timed_decrementer_exception() {
decrementer_timer_id = 0;
static void trigger_timed_decrementer_exception(uint64_t, uint64_t) {
uint32_t new_val = calc_dec_value();
if (new_val >= 0 && new_val != uint32_t(-1)) {
new_val = -1;
@@ -934,8 +897,7 @@ static void trigger_timed_decrementer_exception() {
trigger_decrementer_exception();
}
static void trigger_immediate_decrementer_exception() {
decrementer_timer_id = 0;
static void trigger_immediate_decrementer_exception(uint64_t, uint64_t) {
update_decrementer(false, ppc_state.spr[SPR::DEC_S], ppc_state.spr[SPR::DEC_S]);
trigger_decrementer_exception();
}
@@ -948,12 +910,12 @@ static void update_decrementer(bool update_time_stamp, uint32_t oldval, uint32_t
dec_exception_pending = false;
if (decrementer_timer_id) {
TimerManager::get_instance()->cancel_timer(decrementer_timer_id);
if (decrementer_timer.active) {
TimerManager::get_instance()->cancel_timer(decrementer_timer);
}
if (bit_changed(oldval, newval, 31) && bit_set(newval, 31)) {
decrementer_timer_id = TimerManager::get_instance()->add_immediate_timer(
TimerManager::get_instance()->add_immediate_timer(decrementer_timer,
trigger_immediate_decrementer_exception
);
return;
@@ -973,12 +935,53 @@ static void update_decrementer(bool update_time_stamp, uint32_t oldval, uint32_t
uint32_t time_out_lo;
_u32xu64(newval, tbr_period_ns, time_out, time_out_lo);
//LOG_F(WARNING, "new decrementer value: 0x%08X, interrupt after %llu ns", newval, time_out);
decrementer_timer_id = TimerManager::get_instance()->add_oneshot_timer(
TimerManager::get_instance()->add_oneshot_timer(decrementer_timer,
time_out,
trigger_timed_decrementer_exception
);
}
static void update_thermal(uint64_t, uint64_t) {
uint32_t val = ppc_state.spr[SPR::THRM3];
auto sampled_interval_timer_value = (val >> 1) & 0x1FFF;
auto enabled = val & 1;
bool interrupt = false;
for (int the_reg = 0; the_reg < 2; the_reg++) {
val = ppc_state.spr[SPR::THRM1 + the_reg];
uint32_t t_interrupt; // = (val >> 31) & 1;
uint32_t t_int_valid; // = (val >> 30) & 1;
uint32_t threshold = (val >> 23) & 0x7F;
uint32_t t_int_direction = (val >> 2) & 1;
uint32_t t_int_enable = (val >> 1) & 1;
uint32_t valid = (val >> 0) & 1;
if (!valid) {
t_interrupt = 0;
t_int_valid = 0;
} else {
t_interrupt = t_int_direction ?
junction_temperature < threshold
:
junction_temperature > threshold;
t_int_valid = 1;
interrupt |= t_int_enable && t_interrupt;
}
ppc_state.spr[SPR::THRM1 + the_reg] = (t_interrupt << 31) | (t_int_valid << 30) | (val & 0x3FFFFFFF);
}
if (interrupt && enabled) {
if (ppc_state.msr & MSR::EE) {
thrm_exception_pending = false;
ppc_exception_handler(Except_Type::EXC_THRM_MGMT_INT, 0);
}
else {
thrm_exception_pending = true;
}
}
}
void dppc_interpreter::ppc_mfspr(uint32_t opcode) {
ppc_grab_dab(opcode);
uint32_t ref_spr = (reg_b << 5) | reg_a;
@@ -996,14 +999,14 @@ void dppc_interpreter::ppc_mfspr(uint32_t opcode) {
switch (ref_spr) {
case SPR::MQ:
if (!(is_601 || include_601)) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
return;
}
ppc_state.gpr[reg_d] = ppc_state.spr[ref_spr];
break;
case SPR::RTCL_U:
if (!is_601) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
return;
}
calc_rtcl_value();
@@ -1013,7 +1016,7 @@ void dppc_interpreter::ppc_mfspr(uint32_t opcode) {
break;
case SPR::RTCU_U:
if (!is_601) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
return;
}
calc_rtcl_value();
@@ -1023,7 +1026,7 @@ void dppc_interpreter::ppc_mfspr(uint32_t opcode) {
break;
case SPR::DEC_U:
if (!is_601) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
return;
}
// fallthrough
@@ -1051,6 +1054,15 @@ void dppc_interpreter::ppc_mfspr(uint32_t opcode) {
ppc_state.spr[TBL_S] = uint32_t(tbr_value);
break;
}
case SPR::THRM1:
case SPR::THRM2: {
uint32_t val = ppc_state.spr[ref_spr];
ppc_state.gpr[reg_d] = val;
break;
}
case SPR::THRM3:
ppc_state.gpr[reg_d] = ppc_state.spr[ref_spr];
break;
default:
// FIXME: Unknown SPR should be noop or illegal instruction.
ppc_state.gpr[reg_d] = ppc_state.spr[ref_spr];
@@ -1078,13 +1090,13 @@ void dppc_interpreter::ppc_mtspr(uint32_t opcode) {
if (is_601 || include_601)
ppc_state.spr[ref_spr] = val;
else
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
break;
case SPR::RTCL_U:
case SPR::RTCU_U:
case SPR::DEC_U:
if (!is_601) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
}
break;
case SPR::XER:
@@ -1132,8 +1144,10 @@ void dppc_interpreter::ppc_mtspr(uint32_t opcode) {
case 533:
case 534:
case 535:
ppc_state.spr[ref_spr] = val;
ibat_update(ref_spr);
if (ppc_state.spr[ref_spr] != val) {
ppc_state.spr[ref_spr] = val;
ibat_update(ref_spr);
}
break;
case 536:
case 537:
@@ -1143,8 +1157,10 @@ void dppc_interpreter::ppc_mtspr(uint32_t opcode) {
case 541:
case 542:
case 543:
ppc_state.spr[ref_spr] = val;
dbat_update(ref_spr);
if (ppc_state.spr[ref_spr] != val) {
ppc_state.spr[ref_spr] = val;
dbat_update(ref_spr);
}
break;
case SPR::HID0:
ppc_state.spr[ref_spr] = val;
@@ -1152,6 +1168,25 @@ void dppc_interpreter::ppc_mtspr(uint32_t opcode) {
ppc_change_endian((val & 0x10000000) != 0);
}
break;
case SPR::THRM1:
case SPR::THRM2: {
ppc_state.spr[ref_spr] = val & 0x3F800007;
if (thermal_timer.active)
TimerManager::get_instance()->cancel_timer(thermal_timer);
TimerManager::get_instance()->add_oneshot_timer(thermal_timer, USECS_TO_NSECS(20), update_thermal);
break;
}
case SPR::THRM3: {
ppc_state.spr[ref_spr] = val & 0x00003FFF;
ppc_state.spr[SPR::THRM1] &= ~(3<<30);
ppc_state.spr[SPR::THRM2] &= ~(3<<30);
if (thermal_timer.active)
TimerManager::get_instance()->cancel_timer(thermal_timer);
TimerManager::get_instance()->add_oneshot_timer(thermal_timer, USECS_TO_NSECS(20), update_thermal);
break;
}
default:
// FIXME: Unknown SPR should be noop or illegal instruction.
ppc_state.spr[ref_spr] = val;
@@ -1176,7 +1211,7 @@ void dppc_interpreter::ppc_mftb(uint32_t opcode) {
ppc_state.spr[TBL_S] = uint32_t(tbr_value);
break;
default:
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
}
}
@@ -1513,14 +1548,18 @@ void dppc_interpreter::ppc_rfi(uint32_t opcode) {
ppc_msr_did_change(ppc_state.msr, new_msr_val);
// setting MSR[EE] may enable pending exceptions
if ((ppc_state.msr & MSR::EE) && (int_pin || dec_exception_pending)) {
if ((ppc_state.msr & MSR::EE) && (int_pin || dec_exception_pending || thrm_exception_pending)) {
uint32_t save_srr0 = ppc_state.spr[SPR::SRR0] & ~3UL;
if (int_pin) // check for pending external exceptions (higher priority)
ppc_exception_handler(Except_Type::EXC_EXT_INT, 0);
else {
else if (dec_exception_pending) {
dec_exception_pending = false;
ppc_exception_handler(Except_Type::EXC_DECR, 0);
}
else if (thrm_exception_pending) {
thrm_exception_pending = false;
ppc_exception_handler(Except_Type::EXC_THRM_MGMT_INT, 0);
}
ppc_state.spr[SPR::SRR0] = save_srr0;
return;
}
@@ -1540,27 +1579,25 @@ void dppc_interpreter::ppc_sc(uint32_t opcode) {
}
void dppc_interpreter::ppc_tw(uint32_t opcode) {
uint32_t reg_a = (opcode >> 11) & 0x1F;
uint32_t reg_b = (opcode >> 16) & 0x1F;
ppc_grab_regsab(opcode);
uint32_t ppc_to = (opcode >> 21) & 0x1F;
if (((int32_t(ppc_state.gpr[reg_a]) < int32_t(ppc_state.gpr[reg_b])) && (ppc_to & 0x10)) ||
((int32_t(ppc_state.gpr[reg_a]) > int32_t(ppc_state.gpr[reg_b])) && (ppc_to & 0x08)) ||
((int32_t(ppc_state.gpr[reg_a]) == int32_t(ppc_state.gpr[reg_b])) && (ppc_to & 0x04)) ||
((ppc_state.gpr[reg_a] < ppc_state.gpr[reg_b]) && (ppc_to & 0x02)) ||
((ppc_state.gpr[reg_a] > ppc_state.gpr[reg_b]) && (ppc_to & 0x01))) {
if (((int32_t(ppc_result_a) < int32_t(ppc_result_b)) && (ppc_to & 0x10)) ||
((int32_t(ppc_result_a) > int32_t(ppc_result_b)) && (ppc_to & 0x08)) ||
((int32_t(ppc_result_a) == int32_t(ppc_result_b)) && (ppc_to & 0x04)) ||
((ppc_result_a < ppc_result_b) && (ppc_to & 0x02)) ||
((ppc_result_a > ppc_result_b) && (ppc_to & 0x01))) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::TRAP);
}
}
void dppc_interpreter::ppc_twi(uint32_t opcode) {
int32_t simm = int32_t(int16_t(opcode));
uint32_t reg_a = (opcode >> 16) & 0x1F;
ppc_grab_regsasimm(opcode);
uint32_t ppc_to = (opcode >> 21) & 0x1F;
if (((int32_t(ppc_state.gpr[reg_a]) < simm) && (ppc_to & 0x10)) ||
((int32_t(ppc_state.gpr[reg_a]) > simm) && (ppc_to & 0x08)) ||
((int32_t(ppc_state.gpr[reg_a]) == simm) && (ppc_to & 0x04)) ||
(ppc_state.gpr[reg_a] < uint32_t(simm) && (ppc_to & 0x02)) ||
(ppc_state.gpr[reg_a] > uint32_t(simm) && (ppc_to & 0x01))) {
if (((int32_t(ppc_result_a) < simm) && (ppc_to & 0x10)) ||
((int32_t(ppc_result_a) > simm) && (ppc_to & 0x08)) ||
((int32_t(ppc_result_a) == simm) && (ppc_to & 0x04)) ||
(ppc_result_a < uint32_t(simm) && (ppc_to & 0x02)) ||
(ppc_result_a > uint32_t(simm) && (ppc_to & 0x01))) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::TRAP);
}
}
@@ -1659,13 +1696,17 @@ void dppc_interpreter::ppc_stu(uint32_t opcode) {
ppc_grab_regssa(opcode);
if (reg_a != 0) {
uint32_t ea = int32_t(int16_t(opcode));
ea += ppc_result_a;
uint32_t ea = ppc_result_a + int32_t(int16_t(opcode));
mmu_write_vmem<T>(opcode, ea, ppc_result_d);
ppc_state.gpr[reg_a] = ea;
}
else if (is_601) {
// MPC601 permits RA=0 for POWER compatibility and suppresses the update.
uint32_t ea = int32_t(int16_t(opcode));
mmu_write_vmem<T>(opcode, ea, ppc_result_d);
}
else {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
}
}
@@ -1686,8 +1727,13 @@ void dppc_interpreter::ppc_stux(uint32_t opcode) {
mmu_write_vmem<T>(opcode, ea, ppc_result_d);
ppc_state.gpr[reg_a] = ea;
}
else if (is_601) {
// MPC601 permits RA=0 for POWER compatibility and suppresses the update.
uint32_t ea = ppc_result_b;
mmu_write_vmem<T>(opcode, ea, ppc_result_d);
}
else {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
}
}
@@ -1754,8 +1800,8 @@ void dppc_interpreter::ppc_lz(uint32_t opcode) {
#ifdef CPU_PROFILING
num_int_loads++;
#endif
ppc_grab_regsda(opcode);
uint32_t ea = int32_t(int16_t(opcode));
ppc_grab_regsdasimm(opcode);
uint32_t ea = simm;
ea += reg_a ? ppc_result_a : 0;
uint32_t ppc_result_d = mmu_read_vmem<T>(opcode, ea);
ppc_store_iresult_reg(reg_d, ppc_result_d);
@@ -1770,16 +1816,16 @@ void dppc_interpreter::ppc_lzu(uint32_t opcode) {
#ifdef CPU_PROFILING
num_int_loads++;
#endif
ppc_grab_regsda(opcode);
uint32_t ea = int32_t(int16_t(opcode));
if ((reg_a != reg_d) && reg_a != 0) {
ppc_grab_regsdasimm(opcode);
uint32_t ea = simm;
if ((reg_a != reg_d) && (reg_a != 0)) {
ea += ppc_result_a;
uint32_t ppc_result_d = mmu_read_vmem<T>(opcode, ea);
ppc_store_iresult_reg(reg_d, ppc_result_d);
uint32_t ppc_result_a = ea;
ppc_result_a = ea;
ppc_store_iresult_reg(reg_a, ppc_result_a);
} else {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
}
}
@@ -1815,7 +1861,7 @@ void dppc_interpreter::ppc_lzux(uint32_t opcode) {
ppc_result_a = ea;
ppc_store_iresult_reg(reg_a, ppc_result_a);
} else {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
}
}
@@ -1827,8 +1873,8 @@ void dppc_interpreter::ppc_lha(uint32_t opcode) {
#ifdef CPU_PROFILING
num_int_loads++;
#endif
ppc_grab_regsda(opcode);
uint32_t ea = int32_t(int16_t(opcode));
ppc_grab_regsdasimm(opcode);
uint32_t ea = simm;
ea += (reg_a ? ppc_result_a : 0);
int16_t val = mmu_read_vmem<uint16_t>(opcode, ea);
ppc_store_iresult_reg(reg_d, int32_t(val));
@@ -1838,16 +1884,16 @@ void dppc_interpreter::ppc_lhau(uint32_t opcode) {
#ifdef CPU_PROFILING
num_int_loads++;
#endif
ppc_grab_regsda(opcode);
ppc_grab_regsdasimm(opcode);
if ((reg_a != reg_d) && reg_a != 0) {
uint32_t ea = int32_t(int16_t(opcode));
uint32_t ea = simm;
ea += ppc_result_a;
int16_t val = mmu_read_vmem<uint16_t>(opcode, ea);
ppc_store_iresult_reg(reg_d, int32_t(val));
uint32_t ppc_result_a = ea;
ppc_result_a = ea;
ppc_store_iresult_reg(reg_a, ppc_result_a);
} else {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
}
}
@@ -1860,11 +1906,11 @@ void dppc_interpreter::ppc_lhaux(uint32_t opcode) {
uint32_t ea = ppc_result_a + ppc_result_b;
int16_t val = mmu_read_vmem<uint16_t>(opcode, ea);
ppc_store_iresult_reg(reg_d, int32_t(val));
uint32_t ppc_result_a = ea;
ppc_result_a = ea;
ppc_store_iresult_reg(reg_a, ppc_result_a);
}
else {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
}
}
@@ -1914,8 +1960,8 @@ void dppc_interpreter::ppc_lmw(uint32_t opcode) {
#ifdef CPU_PROFILING
num_int_loads++;
#endif
ppc_grab_regsda(opcode);
uint32_t ea = int32_t(int16_t(opcode));
ppc_grab_regsdasimm(opcode);
uint32_t ea = simm;
ea += (reg_a ? ppc_result_a : 0);
// How many words to load in memory - using a do-while for this
do {
@@ -1972,7 +2018,7 @@ void dppc_interpreter::ppc_lswx(uint32_t opcode) {
if ((reg_d == 0 && reg_a == 0) || (reg_d == reg_a) || (reg_d == reg_b)) {
// UNTESTED! Does invalid form really cause exception?
// G4 doesn't do exception
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
ppc_illegalop(opcode);
}
*/
@@ -2125,7 +2171,13 @@ void dppc_interpreter::ppc_tlbie(uint32_t opcode) {
return;
}
tlb_flush_entry(ppc_state.gpr[(opcode >> 11) & 0x1F]);
// Ideally we would get the effective address via ppc_state.gpr[(opcode >> 11) & 0x1F]
// and use that to identify entries to flush. But that is CPU-dependent (e.g.
// on the 750 only bits 14-19 are used to find matching entries) and does not
// map cleanly to the layout of our virtual TLB. The PowerPC specification
// allows an implementation to be more lax and flush the entire TLB, so we
// do that instead.
tlb_flush_all_pat();
}
void dppc_interpreter::ppc_tlbia(uint32_t opcode) {
+2 -1
View File
@@ -1167,7 +1167,8 @@ void DppcDebugger::enter_debugger() {
cout << exc.what() << endl;
continue;
}
TimerManager::get_instance()->add_oneshot_timer(0, [irq_bit](){
static TimerInfo viaint_timer;
TimerManager::get_instance()->add_oneshot_timer(viaint_timer, 0, [irq_bit](uint64_t, uint64_t){
ViaCuda* via_obj = dynamic_cast<ViaCuda*>(gMachineObj->get_comp_by_name("ViaCuda"));
via_obj->assert_int(irq_bit);
});
-3
View File
@@ -77,9 +77,6 @@ bool AdbAppleJack::get_register_0() {
}
void AdbAppleJack::set_register_3() {
if (this->host_obj->get_input_count() < 2) // ensure we got enough data
return;
const uint8_t* in_data = this->host_obj->get_input_buf();
switch (in_data[1]) {
+22 -1
View File
@@ -21,6 +21,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file Base class for Apple Desktop Bus devices. */
#include <loguru.hpp>
#include <core/timermanager.h>
#include <devices/common/adb/adbdevice.h>
#include <devices/common/adb/adbbus.h>
@@ -92,7 +93,8 @@ void AdbDevice::listen(const uint8_t dev_addr, const uint8_t reg_num) {
this->set_register_2();
break;
case 3:
this->set_register_3();
if (this->host_obj->get_input_count() >= 2) // ensure we got enough data
this->set_register_3();
break;
}
}
@@ -107,6 +109,25 @@ bool AdbDevice::get_register_3() {
return true;
}
void AdbDevice::set_register_3() {
const uint8_t* in_data = this->host_obj->get_input_buf();
uint8_t new_addr = in_data[0] & 0xF;
switch (in_data[1]) {
case 0:
this->my_addr = new_addr;
this->srq_flag = !!(in_data[0] & 0x20);
break;
case 0xFE: // move to a new address if there was no collision
if (!this->got_collision) {
this->my_addr = new_addr;
}
break;
default:
LOG_F(WARNING, "ADB Device: unknown handler ID = 0x%X", in_data[1]);
}
}
uint8_t AdbDevice::gen_random_address() {
return TimerManager::get_instance()->current_time_ns() & 0xF;
}
+1 -1
View File
@@ -64,7 +64,7 @@ protected:
virtual void set_register_0() {}
virtual void set_register_1() {}
virtual void set_register_2() {}
virtual void set_register_3() {}
virtual void set_register_3();
uint8_t exc_event_flag = 0;
uint8_t srq_flag = 0;
+32 -26
View File
@@ -34,6 +34,7 @@ AdbKeyboard::AdbKeyboard(std::string name) : AdbDevice(name) {
}
void AdbKeyboard::event_handler(const KeyboardEvent& event) {
this->keys_down.set(event.key, !(event.flags & KEYBOARD_EVENT_UP));
this->pending_events.push_back(std::make_unique<KeyboardEvent>(event));
if (this->pending_events.size() == 1) {
@@ -46,8 +47,9 @@ void AdbKeyboard::reset() {
this->dev_handler_id = 2; // Extended ADB keyboard
this->exc_event_flag = 1;
this->srq_flag = 0; // don't process keyboard service requests yet
this->led_state = 0; // LEDs off
this->led_state = 7; // LEDs off (active low)
this->pending_events.clear();
this->keys_down.reset();
}
bool AdbKeyboard::get_register_0() {
@@ -92,9 +94,35 @@ uint8_t AdbKeyboard::consume_pending_event() {
}
bool AdbKeyboard::get_register_2() {
// Register 2 reflects the current modifier keys, and a zero value means
// that the key is held down.
static const struct {
uint8_t key;
uint8_t bit;
} reg2_keys[] = {
{ AdbKey_Delete, 14 },
{ AdbKey_CapsLock, 13 },
{ AdbKey_Power, 12 },
{ AdbKey_Control, 11 },
{ AdbKey_RightControl, 11 },
{ AdbKey_Shift, 10 },
{ AdbKey_RightShift, 10 },
{ AdbKey_Option, 9 },
{ AdbKey_RightOption, 9 },
{ AdbKey_Command, 8 },
{ AdbKey_KeypadClear, 7 },
{ AdbKey_F14, 6 }, // Scroll Lock
};
uint16_t reg2 = 0xFFF8 | this->led_state;
for (const auto& key : reg2_keys) {
if (this->keys_down[key.key])
reg2 &= ~(1 << key.bit);
}
uint8_t* out_buf = this->host_obj->get_output_buf();
out_buf[0] = 0;
out_buf[1] = this->led_state & 0x07;
out_buf[0] = reg2 >> 8;
out_buf[1] = reg2 & 0xFF;
this->host_obj->set_output_count(2);
return true;
}
@@ -108,40 +136,18 @@ void AdbKeyboard::set_register_2() {
this->led_state = in_data[1] & 0x07;
}
bool AdbKeyboard::get_register_3() {
uint8_t* out_buf = this->host_obj->get_output_buf();
out_buf[0] = (this->my_addr << 4) | (1 << 1) | 1; // Address + SRQ Enable + Exc Event
out_buf[1] = this->dev_handler_id;
this->host_obj->set_output_count(2);
return true;
}
void AdbKeyboard::set_register_3() {
if (this->host_obj->get_input_count() < 2) // ensure we got enough data
return;
const uint8_t* in_data = this->host_obj->get_input_buf();
switch (in_data[1]) {
case 0:
this->my_addr = in_data[0] & 0xF;
this->srq_flag = !!(in_data[0] & 0x20);
break;
case 1:
case 2:
this->dev_handler_id = in_data[1];
break;
case 3: // extended keyboard protocol isn't supported yet
break;
case 0xFE: // move to a new address if there was no collision
if (!this->got_collision) {
this->my_addr = in_data[0] & 0xF;
}
break;
default:
LOG_F(WARNING, "%s: unknown handler ID = 0x%X", this->name.c_str(), in_data[1]);
this->AdbDevice::set_register_3();
}
}
+3 -1
View File
@@ -27,6 +27,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <devices/common/adb/adbdevice.h>
#include <devices/common/hwcomponent.h>
#include <bitset>
#include <deque>
#include <memory>
#include <string>
@@ -47,13 +48,13 @@ public:
bool get_register_0() override;
bool get_register_2() override;
bool get_register_3() override;
void set_register_2() override;
void set_register_3() override;
private:
std::deque<std::unique_ptr<KeyboardEvent>> pending_events;
std::bitset<128> keys_down;
uint8_t consume_pending_event();
};
@@ -129,6 +130,7 @@ enum AdbKey {
AdbKey_Option = 0x3a,
AdbKey_Command = 0x37,
AdbKey_CapsLock = 0x39,
AdbKey_Power = 0x7f,
AdbKey_RightControl = 0x7d,
AdbKey_RightShift = 0x7b,
+1 -13
View File
@@ -142,28 +142,16 @@ bool AdbMouse::get_register_1() {
}
void AdbMouse::set_register_3() {
if (this->host_obj->get_input_count() < 2) // ensure we got enough data
return;
const uint8_t* in_data = this->host_obj->get_input_buf();
switch (in_data[1]) {
case 0:
this->my_addr = in_data[0] & 0xF;
this->srq_flag = !!(in_data[0] & 0x20);
break;
case 1:
case 2:
case 4: // switch over to extended mouse protocol
this->dev_handler_id = in_data[1];
break;
case 0xFE: // move to a new address if there was no collision
if (!this->got_collision) {
this->my_addr = in_data[0] & 0xF;
}
break;
default:
LOG_F(WARNING, "%s: unknown handler ID = 0x%X", this->name.c_str(), in_data[1]);
this->AdbDevice::set_register_3();
}
}
+28 -11
View File
@@ -77,8 +77,13 @@ uint16_t AtaBaseDevice::read(const uint8_t reg_addr) {
this->r_status &= ~DRQ;
} else {
this->chunk_cnt = std::min(this->xfer_cnt, this->chunk_size);
TimerManager::get_instance()->add_oneshot_timer(
USECS_TO_NSECS(100), [this]() { this->update_intrq(1); });
if (!this->read_data_timer.active) {
TimerManager::get_instance()->add_oneshot_timer(this->read_data_timer,
USECS_TO_NSECS(100), [this](uint64_t, uint64_t) {
this->update_intrq(1);
}
);
}
}
}
return ret_data;
@@ -121,17 +126,25 @@ void AtaBaseDevice::write(const uint8_t reg_addr, const uint16_t value) {
this->xfer_cnt = 0;
this->r_status &= ~DRQ;
//LOG_F(INFO, "%s: write complete", name.c_str());
TimerManager::get_instance()->add_oneshot_timer(USECS_TO_NSECS(100), [this]() {
this->r_status &= ~BSY;
this->update_intrq(1);
});
if (this->write_done_timer.active)
LOG_F(ERROR, "%s: write_done_timer is already active", this->get_name().c_str());
TimerManager::get_instance()->add_oneshot_timer(write_done_timer,
USECS_TO_NSECS(100), [this](uint64_t, uint64_t) {
this->r_status &= ~BSY;
this->update_intrq(1);
}
);
} else {
this->cur_data_ptr = this->data_ptr;
this->chunk_cnt = std::min(this->xfer_cnt, this->chunk_size);
//LOG_F(INFO, "%s: write needs more data (left: 0x%x)", name.c_str(), xfer_cnt);
TimerManager::get_instance()->add_oneshot_timer(USECS_TO_NSECS(100), [this]() {
this->signal_data_ready();
});
if (this->write_more_timer.active)
LOG_F(ERROR, "%s: write_more_timer is already active", this->get_name().c_str());
TimerManager::get_instance()->add_oneshot_timer(this->write_more_timer,
USECS_TO_NSECS(100), [this](uint64_t, uint64_t) {
this->signal_data_ready();
}
);
}
}
}
@@ -213,7 +226,9 @@ int AtaBaseDevice::pull_data(uint8_t *buf, int len) {
if (!this->xfer_cnt) {
this->is_dma_xfer = false;
this->data_ptr = nullptr;
TimerManager::get_instance()->add_oneshot_timer(500, [this]() {
if (this->dma_pull_timer.active)
LOG_F(ERROR, "%s: dma_pull_timer is already active", this->get_name().c_str());
TimerManager::get_instance()->add_oneshot_timer(dma_pull_timer, 500, [this](uint64_t, uint64_t) {
this->r_status &= ~(BSY | DRQ);
this->update_intrq(1);
});
@@ -240,7 +255,9 @@ int AtaBaseDevice::push_data(uint8_t *buf, int len) {
this->is_dma_xfer = false;
this->data_ptr = nullptr;
this->cur_data_ptr = nullptr;
TimerManager::get_instance()->add_oneshot_timer(500, [this]() {
if (this->dma_push_timer.active)
LOG_F(ERROR, "%s: dma_push_timer is already active", this->get_name().c_str());
TimerManager::get_instance()->add_oneshot_timer(dma_push_timer, 500, [this](uint64_t, uint64_t) {
this->r_status &= ~(BSY | DRQ);
this->update_intrq(1);
});
+7
View File
@@ -25,6 +25,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#define ATA_BASE_DEVICE_H
#include <core/endianswap.h>
#include <core/timermanager.h>
#include <devices/common/ata/atadefs.h>
#include <devices/common/hwcomponent.h>
@@ -108,6 +109,12 @@ protected:
bool is_dma_xfer = false;
std::function<void()> post_xfer_action = nullptr;
TimerInfo read_data_timer;
TimerInfo write_done_timer;
TimerInfo write_more_timer;
TimerInfo dma_pull_timer;
TimerInfo dma_push_timer;
};
#endif // ATA_BASE_DEVICE_H
+5 -3
View File
@@ -289,7 +289,7 @@ void AtaHardDisk::prepare_identify_info() {
std::memset(this->data_buf, 0, sizeof(this->data_buf));
WRITE_WORD_LE_A(&buf_ptr[ 0], 0x0040); // ATA device, non-removable media, non-removable drive
WRITE_WORD_LE_A(&buf_ptr[49], 0x0200); // report LBA support
WRITE_WORD_LE_A(&buf_ptr[49], 0x0300); // report DMA and LBA support
// Maximum number of logical sectors per data block that the device supports
// for READ_MULTIPLE/WRITE_MULTIPLE commands.
@@ -307,8 +307,8 @@ void AtaHardDisk::prepare_identify_info() {
WRITE_WORD_LE_A(&buf_ptr[51], 0x0200); // max. PIO mode for a basic device
// report validity for the advanced PIO and MWDMA fields
//WRITE_WORD_LE_A(&buf_ptr[53], 0x0003);
// report validity for the MWDMA fields
WRITE_WORD_LE_A(&buf_ptr[53], 0x0002);
WRITE_DWORD_LE_A(&buf_ptr[57], this->total_sectors);
@@ -316,6 +316,8 @@ void AtaHardDisk::prepare_identify_info() {
WRITE_DWORD_LE_A(&buf_ptr[60], this->total_sectors);
WRITE_WORD_LE_A(&buf_ptr[63], ((1 << this->cur_dma_mode) << 8) | 7);
WRITE_WORD_LE_A(&buf_ptr[65], 120); // minimum MWDMA cycle time (ns)
WRITE_WORD_LE_A(&buf_ptr[66], 120); // recommended MWDMA cycle time (ns)
}
uint64_t AtaHardDisk::get_lba() {
+3
View File
@@ -24,6 +24,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef ATA_HARD_DISK_H
#define ATA_HARD_DISK_H
#include <core/timermanager.h>
#include <devices/common/ata/atabasedevice.h>
#include <utils/imgfile.h>
@@ -74,6 +75,8 @@ private:
uint8_t cur_dma_mode = 2; // current multi-word DMA mode
char * buffer = new char[1 <<17];
TimerInfo signal_ready_timer;
};
#endif // ATA_HARD_DISK_H
+13 -1
View File
@@ -67,11 +67,17 @@ int AtapiCdrom::device_postinit() {
parse_device_path(cdr_config, bus_id, dev_num);
auto bus_obj = dynamic_cast<IdeChannel*>(gMachineObj->get_comp_by_name(bus_id));
if (!bus_obj) {
LOG_F(ERROR, "%s: cdr_config device path %s does not specify a known IDE bus",
this->name.c_str(), cdr_config.c_str());
return -1;
}
bus_obj->register_device(dev_num, this);
std::string cdr_image_path = GET_STR_PROP("cdr_img");
if (!cdr_image_path.empty()) {
this->insert_image(cdr_image_path);
if (!this->insert_image(cdr_image_path))
return -1;
}
return 0;
@@ -99,6 +105,12 @@ void AtapiCdrom::perform_packet_command() {
switch (this->cmd_pkt[0]) {
case ScsiCommand::READ_CD:
{
// READ_CD currently bypasses the shared CD-ROM command dispatcher.
if (!this->ready_for_command()) {
this->present_status();
break;
}
lba = READ_DWORD_BE_U(&this->cmd_pkt[2]);
xfer_len = (this->cmd_pkt[6] << 16) | READ_WORD_BE_U(&this->cmd_pkt[7]);
if (this->cmd_pkt[9] == 0 && (this->cmd_pkt[10] & 7) == 0) {
+1 -1
View File
@@ -38,7 +38,7 @@ public:
return std::unique_ptr<AtapiCdrom>(new AtapiCdrom("ATAPI-CDROM"));
}
bool is_device_ready() override { return this->is_ready; }
bool is_device_ready() override { return this->medium_present(); }
uint8_t not_ready_reason() override { return ScsiError::MEDIUM_NOT_PRESENT; }
int device_postinit() override;
+3 -1
View File
@@ -91,7 +91,9 @@ int IdeChannel::xfer_to(DmaChannel *ch_obj, uint8_t *buf, int len) {
}
void IdeChannel::assert_dmareq(uint64_t delay) {
TimerManager::get_instance()->add_oneshot_timer(delay, [this]() {
if (this->dmareq_timer.active)
LOG_F(WARNING, "%s: dmareq_timer is already active", this->get_name().c_str());
TimerManager::get_instance()->add_oneshot_timer(this->dmareq_timer, delay, [this](uint64_t, uint64_t) {
//LOG_F(INFO, "%s: DMAREQ asserted", this->name.c_str());
this->channel_obj->xfer_retry();
});
+3
View File
@@ -24,6 +24,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef IDE_CHANNEL_H
#define IDE_CHANNEL_H
#include <core/timermanager.h>
#include <devices/common/ata/atadefs.h>
#include <devices/common/dmacore.h>
#include <devices/common/hwcomponent.h>
@@ -74,6 +75,8 @@ private:
AtaInterface* devices[2];
std::unique_ptr<AtaInterface> device_stub;
TimerInfo dmareq_timer;
};
/** This class models an IDE channel specific to MacIO ASICs. */
+23 -75
View File
@@ -40,12 +40,6 @@ void DMAChannel::set_callbacks(DbdmaCallback start_cb, DbdmaCallback stop_cb) {
this->stop_cb = stop_cb;
}
void DMAChannel::set_data_callbacks(DbdmaCallback in_cb, DbdmaCallback out_cb, DbdmaCallback flush_cb) {
this->in_cb = in_cb;
this->out_cb = out_cb;
this->flush_cb = flush_cb;
}
/* Load DMACmd from physical memory. */
DMACmd* DMAChannel::fetch_cmd(uint32_t cmd_addr, DMACmd* p_cmd, bool *is_writable) {
MapDmaResult res = mmu_map_dma_mem(cmd_addr, 16, false);
@@ -100,14 +94,10 @@ void DMAChannel::interpret_cmd() {
case DBDMA_Cmd::OUTPUT_MORE:
case DBDMA_Cmd::OUTPUT_LAST:
this->xfer_to_device();
if (this->out_cb)
this->out_cb();
break;
case DBDMA_Cmd::INPUT_MORE:
case DBDMA_Cmd::INPUT_LAST:
this->xfer_from_device();
if (this->in_cb)
this->in_cb();
break;
}
} else {
@@ -145,6 +135,15 @@ void DMAChannel::interpret_cmd() {
}
}
void DMAChannel::interpret_until_blocked() {
// Execute ready commands until a transfer is queued or the channel becomes idle/dead.
while (this->is_active()) {
this->interpret_cmd();
if (this->cmd_in_progress)
break;
}
}
void DMAChannel::update_cmd() {
if (this->cur_is_writable) {
if (this->cur_cmd < DBDMA_Cmd::STOP)
@@ -291,10 +290,12 @@ void DMAChannel::update_irq(uint8_t cmd_bits) {
}
}
if (cond) {
if (int_ctrl) {
TimerManager::get_instance()->add_immediate_timer([this] {
this->int_ctrl->ack_dma_int(this->irq_id, 1);
});
if (this->int_ctrl) {
if (!this->interrupt_timer.active) {
TimerManager::get_instance()->add_immediate_timer(this->interrupt_timer, [this](uint64_t, uint64_t) {
this->int_ctrl->ack_dma_int(this->irq_id, 1);
});
}
} else
LOG_F(ERROR, "%s Interrupt ignored", this->get_name().c_str());
}
@@ -343,7 +344,7 @@ void DMAChannel::reg_write(uint32_t offset, uint32_t value, int size) {
this->get_name().c_str());
}
value = BYTESWAP_32(value);
value = BYTESWAP_32(value);
switch (offset) {
case DMAReg::CH_CTRL:
@@ -370,8 +371,6 @@ void DMAChannel::reg_write(uint32_t offset, uint32_t value, int size) {
this->ch_stat |= CH_STAT_FLUSH;
if (this->dev_obj != nullptr)
this->dev_obj->notify(this, DMA_MSG_FLUSH);
if (this->flush_cb)
this->flush_cb();
this->update_cmd();
}
}
@@ -471,7 +470,7 @@ void DMAChannel::xfer_from_device() {
this->get_name().c_str());
}
this->interpret_cmd();
this->interpret_until_blocked();
}
void DMAChannel::xfer_to_device() {
@@ -488,7 +487,7 @@ void DMAChannel::xfer_to_device() {
this->finish_cmd();
}
this->interpret_cmd();
this->interpret_until_blocked();
}
void DMAChannel::xfer_retry() {
@@ -521,9 +520,7 @@ DmaPullResult DMAChannel::pull_data(uint32_t req_len, uint32_t *avail_len, uint8
}
// interpret DBDMA program until we get data or become idle
while ((this->ch_stat & CH_STAT_ACTIVE) && !this->queue_len) {
this->interpret_cmd();
}
this->interpret_until_blocked();
// dequeue data if any
if (this->queue_len) {
@@ -556,9 +553,7 @@ DmaPushResult DMAChannel::push_data(const char* src_ptr, int len) {
}
// interpret DBDMA program until we get buffer to fill in or become idle
while ((this->ch_stat & CH_STAT_ACTIVE) && !this->queue_len) {
this->interpret_cmd();
}
this->interpret_until_blocked();
if (this->queue_len) {
len = std::min((int)this->queue_len, len);
@@ -570,47 +565,12 @@ DmaPushResult DMAChannel::push_data(const char* src_ptr, int len) {
// proceed with the DBDMA program if the buffer became exhausted
if (!this->queue_len) {
this->interpret_cmd();
this->interpret_until_blocked();
}
return DmaPushResult::PushedData;
}
void DMAChannel::end_pull_data() {
if (!this->is_active()) {
// dead or idle channel? -> no more data
LOG_F(WARNING, "%s: Ending Dead/idle channel -> no more data",
this->get_name().c_str());
return;
}
if (this->queue_len) {
this->queue_len = 0;
} else {
this->ch_stat &= ~CH_STAT_FLUSH;
}
// proceed with the DBDMA program
this->interpret_cmd();
}
void DMAChannel::end_push_data() {
if (!this->is_active()) {
LOG_F(WARNING, "%s: Attempt to end push data to dead/idle channel",
this->get_name().c_str());
return;
}
if (this->queue_len) {
this->queue_len = 0;
} else {
this->ch_stat &= ~CH_STAT_FLUSH;
}
// proceed with the DBDMA program
this->interpret_cmd();
}
bool DMAChannel::is_out_active() {
return this->is_active();
}
@@ -646,13 +606,7 @@ void DMAChannel::start() {
if (this->start_cb)
this->start_cb();
// some DBDMA programs contain commands that don't transfer data
// between a device and memory (LOAD_QUAD, STORE_QUAD, NOP and STOP).
// We thus interprete the DBDMA program until a data transfer between
// a device and memory is queued or the channel becomes idle/dead.
while (!this->cmd_in_progress && this->is_active()) {
this->interpret_cmd();
}
this->interpret_until_blocked();
}
void DMAChannel::resume() {
@@ -664,13 +618,7 @@ void DMAChannel::resume() {
LOG_F(INFO, "%s: Resuming DMA channel", this->get_name().c_str());
// some DBDMA programs contain commands that don't transfer data
// between a device and memory (LOAD_QUAD, STORE_QUAD, NOP and STOP).
// We thus interprete the DBDMA program until a data transfer between
// a device and memory is queued or the channel becomes idle/dead.
while (!this->cmd_in_progress && this->is_active()) {
this->interpret_cmd();
}
this->interpret_until_blocked();
}
void DMAChannel::abort() {
+3 -8
View File
@@ -29,6 +29,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef DB_DMA_H
#define DB_DMA_H
#include <core/timermanager.h>
#include <devices/common/dmacore.h>
#include <cinttypes>
@@ -109,7 +110,6 @@ public:
~DMAChannel() = default;
void set_callbacks(DbdmaCallback start_cb, DbdmaCallback stop_cb);
void set_data_callbacks(DbdmaCallback in_cb, DbdmaCallback out_cb, DbdmaCallback flush_cb);
uint32_t reg_read(uint32_t offset, int size);
void reg_write(uint32_t offset, uint32_t value, int size);
@@ -125,10 +125,6 @@ public:
bool is_in_active() override;
DmaPullResult pull_data(uint32_t req_len, uint32_t *avail_len, uint8_t **p_data) override;
DmaPushResult push_data(const char* src_ptr, int len) override;
int get_pull_data_remaining() override { return this->queue_len; }
int get_push_data_remaining() override { return this->queue_len; }
void end_pull_data() override;
void end_push_data() override;
bool dma_is_ready() override;
void xfer_retry() override;
@@ -141,6 +137,7 @@ public:
protected:
DMACmd* fetch_cmd(uint32_t cmd_addr, DMACmd* p_cmd, bool *is_writable);
void interpret_cmd(void);
void interpret_until_blocked();
void update_cmd();
void finish_cmd();
void xfer_quad(bool is_store);
@@ -158,9 +155,6 @@ protected:
private:
std::function<void(void)> start_cb = nullptr; // DMA channel start callback
std::function<void(void)> stop_cb = nullptr; // DMA channel stop callback
std::function<void(void)> in_cb = nullptr; // DMA channel in callback
std::function<void(void)> out_cb = nullptr; // DMA channel out callback
std::function<void(void)> flush_cb = nullptr; // DMA channel flush callback
uint16_t ch_stat = 0;
uint32_t cmd_ptr = 0;
@@ -180,6 +174,7 @@ private:
// Interrupt related stuff
InterruptCtrl* int_ctrl = nullptr;
uint64_t irq_id = 0;
TimerInfo interrupt_timer;
};
#endif // DB_DMA_H
-4
View File
@@ -45,8 +45,6 @@ public:
virtual bool is_out_active() { return true; }
virtual DmaPullResult pull_data(uint32_t req_len, uint32_t *avail_len,
uint8_t **p_data) = 0;
virtual int get_pull_data_remaining() { return 1; }
virtual void end_pull_data() {}
std::string get_name(void) { return this->name; }
@@ -60,8 +58,6 @@ public:
virtual bool is_in_active() { return true; }
virtual DmaPushResult push_data(const char* src_ptr, int len) = 0;
virtual int get_push_data_remaining() { return 1; }
virtual void end_push_data() {}
std::string get_name(void) { return this->name; }
+3 -1
View File
@@ -32,6 +32,8 @@ enum YosemiteGpioMask: uint8_t {
GPIO_FWDET = 2, // FireWire detect
};
constexpr uint32_t my_rev_id = 2;
DecPciBridge::DecPciBridge(std::string name) : PCIBridge(name)
{
supports_types(HWCompType::PCI_HOST | HWCompType::PCI_DEV);
@@ -39,7 +41,7 @@ DecPciBridge::DecPciBridge(std::string name) : PCIBridge(name)
// initialize PCI config header
this->vendor_id = PCI_VENDOR_DEC;
this->device_id = 0x0026;
this->class_rev = 0x06040002;
this->class_rev = DEVTYPE_PCI2PCI_BRIDGE | my_rev_id;
this->cache_ln_sz = 0;
this->command = 0;
this->status = 0x2B0;
+1 -10
View File
@@ -23,6 +23,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#define PCI_BASE_H
#include <devices/common/mmiodevice.h>
#include <devices/common/pci/pcidefs.h>
#include <devices/common/pci/pcihost.h>
#include <cinttypes>
@@ -52,16 +53,6 @@ enum {
// Int_Pin and Int_Line registers (type 0, 1, and 2)
};
/** PCI Vendor IDs for devices used in Power Macintosh computers. */
enum {
PCI_VENDOR_ATI = 0x1002,
PCI_VENDOR_DEC = 0x1011,
PCI_VENDOR_MOTOROLA = 0x1057,
PCI_VENDOR_APPLE = 0x106B,
PCI_VENDOR_SILICON_IMAGE = 0x1095,
PCI_VENDOR_NVIDIA = 0x10DE,
};
/** PCI BAR types */
enum PCIBarType : uint32_t {
Unused = 0,
+72
View File
@@ -0,0 +1,72 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team
(See CREDITS.MD for more details)
(You may also contact divingkxt or powermax2286 on Discord)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef PCI_DEFS_H
#define PCI_DEFS_H
#include <cinttypes>
/** PCI device class/subclass/programming interface definitions. */
enum : uint8_t {
DEVCLASS_UNCLASSIFIED = 0x00, // unclassified/legacy devices
DEVCLASS_MASS_STORAGE_CTRL = 0x01, // mass storage controllers
SUBCLASS_IDE_CTRL = 0x01, // IDE controller
PROGIF_BUS_MASTER = 0x80, // bus master (DMA) capable
DEVCLASS_DISPLAY_CTRL = 0x03, // display controllers
SUBCLASS_VGA_COMPAT = 0x00, // VGA-compatible display controller
SUBCLASS_NON_VGA = 0x80, // non-VGA display controller
DEVCLASS_BRIDGE_DEVICE = 0x06, // various bridge devices
SUBCLASS_HOST_BRIDGE = 0x00, // host-to-PCI bridge
SUBCLASS_PCI2PCI_BRIDGE = 0x04, // PCI-to-PCI bridge
DEVCLASS_SERIAL_BUS_CTRL = 0x0C, // serial bus controllers
SUBCLASS_USB_CTRL = 0x03, // Universal serial bus (USB) controller
PROGIF_OHCI = 0x10, // conforms to the OpenHCI specification
DEVCLASS_UNASSIGNED = 0xFF
};
/** Some common PCI device type definitions. */
enum : uint32_t {
DEVTYPE_HOST2PCI_BRIDGE = (DEVCLASS_BRIDGE_DEVICE << 24) |
(SUBCLASS_HOST_BRIDGE << 16),
DEVTYPE_PCI2PCI_BRIDGE = (DEVCLASS_BRIDGE_DEVICE << 24) |
(SUBCLASS_PCI2PCI_BRIDGE << 16),
DEVTYPE_VGA_COMPAT_VIDCTRL = (DEVCLASS_DISPLAY_CTRL << 24) |
(SUBCLASS_VGA_COMPAT << 16),
DEVTYPE_IDE_CTRL_BUS_MASTER = (DEVCLASS_MASS_STORAGE_CTRL << 24) |
(SUBCLASS_IDE_CTRL << 16) | (PROGIF_BUS_MASTER << 8),
DEVTYPE_USB_OHCI_CTRL = (DEVCLASS_SERIAL_BUS_CTRL << 24) |
(SUBCLASS_USB_CTRL << 16) | (PROGIF_OHCI << 8),
};
/** PCI Vendor IDs for devices used in Power Macintosh computers. */
enum : uint16_t {
PCI_VENDOR_ATI = 0x1002,
PCI_VENDOR_DEC = 0x1011,
PCI_VENDOR_OPTi = 0x1045,
PCI_VENDOR_TI = 0x104C, // common abbreviation for Texas Instruments
PCI_VENDOR_MOTOROLA = 0x1057,
PCI_VENDOR_APPLE = 0x106B,
PCI_VENDOR_SILICON_IMAGE = 0x1095,
PCI_VENDOR_NVIDIA = 0x10DE,
PCI_VENDOR_IXMICRO = 0x10E0, // also known as Integrated Micro Solutions
};
#endif // PCI_DEFS_H
+7
View File
@@ -51,10 +51,16 @@ int MeshController::device_postinit() {
void MeshController::reset(bool is_hard_reset) {
this->cur_cmd = SeqCmd::NoOperation;
this->fifo_pos = 0;
this->to_xfer = 0;
this->int_stat = 0;
this->int_mask = 0;
this->exception = 0;
this->xfer_count = 0;
this->src_id = 7;
this->check_parity = true;
this->cur_state = Scsi_Bus_Controller::SeqState::BUS_FREE;
update_irq();
if (is_hard_reset) {
this->bus_stat = 0;
@@ -123,6 +129,7 @@ void MeshController::write(uint8_t reg_offset, uint8_t value) {
break;
case MeshReg::IntMask:
this->int_mask = value;
update_irq();
break;
case MeshReg::Interrupt:
this->int_stat &= ~(value & INT_MASK); // clear requested interrupt bits
+15 -19
View File
@@ -78,7 +78,7 @@ void Sc53C94::reset_device()
this->cur_step = 0;
this->seq_step = 0;
this->status &= STAT_PHASE_MASK; // reset doesn't affect bus phase bits
this->status &= STAT_PHASE_MASK; // reset doesn't affect bus phase bits
this->int_status = 0;
}
@@ -252,7 +252,7 @@ void Sc53C94::pseudo_dma_write(uint16_t data) {
void Sc53C94::update_command_reg(uint8_t cmd)
{
if (this->on_reset && (cmd & CMD_OPCODE) != CMD_NOP) {
if (this->on_reset && (cmd & CMD_OPCODE) != CMD_NOP && (cmd & CMD_OPCODE) != CMD_CLEAR_FIFO) {
LOG_F(WARNING, "%s: command register blocked after RESET!", this->name.c_str());
return;
}
@@ -306,6 +306,7 @@ void Sc53C94::exec_command()
exec_next_command();
break;
case CMD_CLEAR_FIFO:
this->on_reset = false; // unblock the command register
this->data_fifo_pos = 0; // set the bottom of the data FIFO to zero
this->data_fifo[0] = 0;
exec_next_command();
@@ -313,20 +314,19 @@ void Sc53C94::exec_command()
case CMD_RESET_DEVICE:
reset_device();
this->on_reset = true; // block the command register
this->update_irq();
return;
case CMD_RESET_BUS:
LOG_F(INFO, "%s: resetting SCSI bus...", this->name.c_str());
// assert RST line
this->bus_obj->assert_ctrl_line(this->my_bus_id, SCSI_CTRL_RST);
// release RST line after 25 us
if (my_timer_id) {
TimerManager::get_instance()->cancel_timer(this->my_timer_id);
my_timer_id = 0;
if (my_timer.active) {
TimerManager::get_instance()->cancel_timer(this->my_timer);
}
my_timer_id = TimerManager::get_instance()->add_oneshot_timer(
TimerManager::get_instance()->add_oneshot_timer(my_timer,
USECS_TO_NSECS(25),
[this]() {
my_timer_id = 0;
[this](uint64_t, uint64_t) {
this->bus_obj->release_ctrl_line(this->my_bus_id, SCSI_CTRL_RST);
});
if (!(config1 & CFG1_DISR)) {
@@ -475,25 +475,22 @@ uint8_t Sc53C94::fifo_pop()
void Sc53C94::seq_defer_state(uint64_t delay_ns)
{
if (this->seq_timer_id) {
TimerManager::get_instance()->cancel_timer(this->seq_timer_id);
this->seq_timer_id = 0;
if (this->seq_timer.active) {
TimerManager::get_instance()->cancel_timer(this->seq_timer);
}
if (delay_ns) {
this->seq_timer_id = TimerManager::get_instance()->add_oneshot_timer(
TimerManager::get_instance()->add_oneshot_timer(this->seq_timer,
delay_ns,
[this]() {
[this](uint64_t, uint64_t) {
// re-enter the sequencer with the state specified in next_state
this->seq_timer_id = 0;
this->cur_state = this->next_state;
this->sequencer();
});
} else {
this->seq_timer_id = TimerManager::get_instance()->add_immediate_timer(
[this]() {
TimerManager::get_instance()->add_immediate_timer(this->seq_timer,
[this](uint64_t, uint64_t) {
// re-enter the sequencer with the state specified in next_state
this->seq_timer_id = 0;
this->cur_state = this->next_state;
this->sequencer();
});
@@ -708,8 +705,7 @@ void Sc53C94::notify(ScsiNotification notif_type, int param)
case ScsiNotification::CONFIRM_SEL:
if (this->target_id == param) {
// cancel selection timeout timer
TimerManager::get_instance()->cancel_timer(this->seq_timer_id);
this->seq_timer_id = 0;
TimerManager::get_instance()->cancel_timer(this->seq_timer);
this->cur_state = SeqState::SEL_END;
this->sequencer();
} else {
+3 -2
View File
@@ -29,6 +29,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef SC_53C94_H
#define SC_53C94_H
#include <core/timermanager.h>
#include <devices/common/scsi/scsi.h>
#include <devices/common/dbdma.h>
@@ -250,7 +251,7 @@ protected:
private:
uint8_t chip_id = 0;
uint8_t my_bus_id = 0;
uint32_t my_timer_id = 0;
TimerInfo my_timer;
uint8_t cmd_fifo[2];
uint8_t data_fifo[DATA_FIFO_MAX];
@@ -278,7 +279,7 @@ private:
uint8_t phase_latch = 0;
// sequencer state
uint32_t seq_timer_id = 0;
TimerInfo seq_timer;
uint32_t cur_state = 0;
uint32_t next_state = 0;
SeqDesc* cmd_steps = nullptr;
+13
View File
@@ -24,6 +24,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef SCSI_H
#define SCSI_H
#include <core/timermanager.h>
#include <devices/common/hwcomponent.h>
#include <devices/common/scsi/scsiphysinterface.h>
@@ -175,6 +176,14 @@ enum ScsiCommand : uint8_t {
READ_CD = 0xBE,
};
/** START STOP UNIT command flags in CDB byte 4. */
namespace ScsiStartStopUnit {
enum : uint8_t {
START = 1 << 0,
LOAD_EJECT = 1 << 1,
};
}
enum ScsiSense : uint8_t {
NO_SENSE = 0x0,
RECOVERED = 0x1,
@@ -200,8 +209,10 @@ enum ScsiError : uint8_t {
INVALID_CDB = 0x24,
INVALID_LUN = 0x25,
WRITE_PROTECT = 0x27,
MEDIUM_CHANGED = 0x28,
SAVING_NOT_SUPPORTED = 0x39,
MEDIUM_NOT_PRESENT = 0x3A,
REMOVAL_PREVENTED = 0x53,
};
/** SCSI device types used in INQUIRY. */
@@ -359,6 +370,8 @@ protected:
more_data_cb_t read_more_data = {};
more_data_cb_t write_more_data = {};
TimerInfo bus_settle_timer;
};
/** This class provides a higher level abstraction for the SCSI bus. */
+13 -5
View File
@@ -79,6 +79,11 @@ void ScsiBlockCmds::init_block_device(uint8_t medium_type, uint8_t dev_flags,
}
void ScsiBlockCmds::process_command() {
if (!this->ready_for_command()) {
phy_impl->switch_phase(ScsiPhase::STATUS);
return;
}
int next_phase;
// use non-disk buffer by default
@@ -179,17 +184,20 @@ int ScsiBlockCmds::write() {
}
int ScsiBlockCmds::start_stop_unit() {
if (this->cdb_ptr[4] & 1) {
if (this->cdb_ptr[4] & 2)
if (this->cdb_ptr[4] & ScsiStartStopUnit::START) {
if (this->cdb_ptr[4] & ScsiStartStopUnit::LOAD_EJECT)
LOG_F(INFO, "START_STOP_UNIT: medium load requested");
} else {
if (this->cdb_ptr[4] & 2) {
LOG_F(INFO, "START_STOP_UNIT: medium eject requested");
}
if (this->cdb_ptr[4] & ScsiStartStopUnit::LOAD_EJECT)
this->eject_medium();
}
return ScsiPhase::STATUS;
}
void ScsiBlockCmds::eject_medium() {
LOG_F(INFO, "START_STOP_UNIT: medium eject requested");
}
int ScsiBlockCmds::read_capacity() {
uint32_t lba = this->get_lba();
+1
View File
@@ -63,6 +63,7 @@ public:
protected:
virtual void process_command() override;
virtual void eject_medium();
uint32_t get_lba();
+55 -17
View File
@@ -31,6 +31,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cinttypes>
#include <sstream>
#include <vector>
ScsiBus::ScsiBus(const std::string name)
{
@@ -338,28 +339,65 @@ void ScsiBus::attach_scsi_devices(const std::string bus_suffix)
}
}
int default_cdrom_id = -1;
std::string cdr_config = GET_STR_PROP("cdr_config");
if (!cdr_config.empty()) {
std::string bus_id;
uint32_t dev_num;
parse_device_path(cdr_config, bus_id, dev_num);
// Only consume SCSI paths; other buses handle their own CD-ROM configuration.
if (bus_id.starts_with("Scsi")) {
auto bus_obj = dynamic_cast<ScsiBus*>(gMachineObj->get_comp_by_name_optional(bus_id));
if (!bus_obj)
ABORT_F("cdr_config device path %s does not specify a known SCSI bus", cdr_config.c_str());
if (dev_num >= SCSI_MAX_DEVS)
ABORT_F("Invalid SCSI ID in cdr_config device path %s", cdr_config.c_str());
if (bus_obj == this) {
if (this->devices[dev_num])
ABORT_F("%s: cdr_config SCSI ID %u is already occupied", bus_id.c_str(), dev_num);
default_cdrom_id = dev_num;
}
}
}
image_path = GET_STR_PROP("cdr_img" + bus_suffix);
std::vector<std::string> cdrom_paths;
if (!image_path.empty()) {
std::istringstream image_stream(image_path);
while (std::getline(image_stream, path, ':')) {
// do two passes because we start at ID 3.
// Keep empty entries, including the last one, as empty CD-ROM drives.
size_t start = 0;
size_t end;
do {
end = image_path.find(':', start);
cdrom_paths.push_back(image_path.substr(start, end - start));
start = end + 1;
} while (end != std::string::npos);
} else if (default_cdrom_id >= 0) {
cdrom_paths.push_back("");
}
for (const auto& path : cdrom_paths) {
if (default_cdrom_id >= 0) {
scsi_id = default_cdrom_id;
default_cdrom_id = -1;
} else {
// do two passes because we start at ID 3.
for (scsi_id = 3; scsi_id < SCSI_MAX_DEVS * 2 &&
this->devices[scsi_id % SCSI_MAX_DEVS]; scsi_id++) {}
}
if (scsi_id < SCSI_MAX_DEVS * 2) {
scsi_id = scsi_id % SCSI_MAX_DEVS;
std::string scsi_device_name = "ScsiCdrom" + bus_suffix + "," +
std::to_string(scsi_id);
ScsiCdrom *scsi_device = new ScsiCdrom(scsi_device_name, scsi_id);
gMachineObj->add_device(scsi_device_name,
std::unique_ptr<ScsiCdrom>(scsi_device));
this->register_device(scsi_id, scsi_device);
scsi_device->insert_image(path);
}
else {
LOG_F(ERROR, "%s: Too many devices. CD-ROM \"%s\" was not added.",
this->get_name().c_str(), path.c_str());
}
if (scsi_id < SCSI_MAX_DEVS * 2) {
scsi_id = scsi_id % SCSI_MAX_DEVS;
std::string scsi_device_name = "ScsiCdrom" + bus_suffix + "," +
std::to_string(scsi_id);
ScsiCdrom *scsi_device = new ScsiCdrom(scsi_device_name, scsi_id);
gMachineObj->add_device(scsi_device_name,
std::unique_ptr<ScsiCdrom>(scsi_device));
this->register_device(scsi_id, scsi_device);
if (!path.empty() && !scsi_device->insert_image(path))
ABORT_F("Could not insert CD-ROM image, %s", path.c_str());
}
else {
LOG_F(ERROR, "%s: Too many devices. CD-ROM \"%s\" was not added.",
this->get_name().c_str(), path.c_str());
}
}
}
+6 -4
View File
@@ -31,9 +31,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
using namespace Scsi_Bus_Controller;
void ScsiBusController::seq_defer_state(uint64_t delay_ns) {
seq_timer_id = TimerManager::get_instance()->add_oneshot_timer(
if (this->seq_timer.active) {
TimerManager::get_instance()->cancel_timer(this->seq_timer);
}
TimerManager::get_instance()->add_oneshot_timer(this->seq_timer,
delay_ns,
[this]() {
[this](uint64_t, uint64_t) {
// re-enter the sequencer with the state specified in next_state
this->cur_state = this->next_state;
this->sequencer();
@@ -170,8 +173,7 @@ void ScsiBusController::notify(ScsiNotification notif_type, int param) {
case ScsiNotification::CONFIRM_SEL:
if (this->dst_id == param) {
// cancel selection timeout timer
TimerManager::get_instance()->cancel_timer(this->seq_timer_id);
seq_timer_id = 0;
TimerManager::get_instance()->cancel_timer(this->seq_timer);
this->cur_state = SeqState::SEL_END;
this->sequencer();
} else {
+2 -1
View File
@@ -24,6 +24,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef SCSI_BUS_CTRL_H
#define SCSI_BUS_CTRL_H
#include <core/timermanager.h>
#include <devices/common/dmacore.h>
#include <devices/common/hwinterrupt.h>
#include <devices/common/scsi/scsi.h>
@@ -104,7 +105,7 @@ protected:
uint8_t data_fifo[DATA_FIFO_DEPTH] = {};
// Sequencer state
uint32_t seq_timer_id = 0;
TimerInfo seq_timer;
uint32_t cur_state = Scsi_Bus_Controller::SeqState::IDLE;
uint32_t next_state = Scsi_Bus_Controller::SeqState::IDLE;
int cur_bus_phase = 0;
+2 -1
View File
@@ -43,7 +43,8 @@ public:
}
protected:
bool is_device_ready() override { return this->is_ready; }
bool is_device_ready() override { return this->medium_present(); }
uint8_t not_ready_reason() override { return ScsiError::MEDIUM_NOT_PRESENT; }
void mode_select_6(uint8_t param_len);
+29
View File
@@ -42,6 +42,11 @@ ScsiCdromCmds::ScsiCdromCmds() {
}
void ScsiCdromCmds::process_command() {
if (!this->ready_for_command()) {
phy_impl->switch_phase(ScsiPhase::STATUS);
return;
}
int next_phase;
// use non-disk buffer by default
@@ -62,6 +67,30 @@ void ScsiCdromCmds::process_command() {
phy_impl->switch_phase(next_phase);
}
int ScsiCdromCmds::test_unit_ready() {
if (this->consume_media_change()) {
this->sense_key = ScsiSense::UNIT_ATTENTION;
this->asc = ScsiError::MEDIUM_CHANGED;
this->ascq = 0;
phy_impl->set_status(ScsiStatus::CHECK_CONDITION, this->sense_key);
return ScsiPhase::STATUS;
}
return ScsiCommonCmds::test_unit_ready();
}
void ScsiCdromCmds::eject_medium() {
if (this->drive_locked) {
LOG_F(INFO, "START_STOP_UNIT: medium eject prevented");
this->field_ptr_valid = false;
this->bit_ptr_valid = false;
this->illegal_request(ScsiError::REMOVAL_PREVENTED, 2, false);
} else {
LOG_F(INFO, "START_STOP_UNIT: medium eject requested");
this->eject_image();
}
}
int ScsiCdromCmds:: read_toc() {
uint8_t start_track, session_num;
int tot_tracks, resp_len = 0;
+2
View File
@@ -35,6 +35,8 @@ public:
protected:
virtual void process_command() override;
int test_unit_ready() override;
void eject_medium() override;
int get_apple_page_49(uint8_t subpage, uint8_t ctrl,
uint8_t *out_ptr, int avail_len);
+19 -2
View File
@@ -109,16 +109,33 @@ int ScsiCommonCmds::verify_cdb() {
}
int ScsiCommonCmds::test_unit_ready() {
// Assume that LUN is okay and the status has been set to GOOD
this->ready_for_command(true);
return ScsiPhase::STATUS;
}
bool ScsiCommonCmds::ready_for_command(bool force_check) {
// TUR forces a check from its handler; dispatch lets it and media-independent
// commands through to ScsiCommonCmds.
if (!force_check) {
switch (this->cdb_ptr[0]) {
case ScsiCommand::INQUIRY:
case ScsiCommand::REQ_SENSE:
case ScsiCommand::TEST_UNIT_READY:
case ScsiCommand::MODE_SENSE_6:
case ScsiCommand::MODE_SENSE_10:
return true;
}
}
if (!phy_impl->is_device_ready()) {
this->sense_key = ScsiSense::NOT_READY;
this->asc = phy_impl->not_ready_reason();
this->ascq = 0;
phy_impl->set_status(ScsiStatus::CHECK_CONDITION, this->sense_key);
return false;
}
return ScsiPhase::STATUS;
return true;
}
int ScsiCommonCmds::inquiry() {
+2
View File
@@ -98,6 +98,8 @@ protected:
virtual void invalid_command();
virtual void illegal_request(uint8_t asc, uint8_t ascq, bool is_cdb = true);
bool ready_for_command(bool force_check = false);
int get_one_page(uint8_t ctrl, uint8_t page, uint8_t subpage, uint8_t* out_ptr,
int avail_len);
+4 -2
View File
@@ -56,7 +56,7 @@ ScsiHardDisk::ScsiHardDisk(std::string name, int my_id) : ScsiPhysDevice(name, m
}
void ScsiHardDisk::insert_image(std::string filename) {
if (this->set_host_file(filename) < 0)
if (!this->attach_image(filename))
ABORT_F("%s: could not open image file %s", this->name.c_str(), filename.c_str());
this->is_writeable = true;
@@ -177,7 +177,9 @@ void ScsiHardDisk::format() {
if (this->cmd_buf[1] & 0x10)
ABORT_F("%s: defect list isn't supported yet", this->name.c_str());
TimerManager::get_instance()->add_oneshot_timer(NS_PER_SEC, [this]() {
if (this->phase_switch_timer.active)
LOG_F(WARNING, "%s: phase_switch_timer is already active", this->get_name().c_str());
TimerManager::get_instance()->add_oneshot_timer(this->phase_switch_timer, NS_PER_SEC, [this](uint64_t, uint64_t) {
this->switch_phase(ScsiPhase::STATUS);
});
}
+3 -1
View File
@@ -24,6 +24,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef SCSI_HD_H
#define SCSI_HD_H
#include <core/timermanager.h>
#include <devices/common/scsi/scsi.h>
#include <devices/common/scsi/scsiblockcmds.h>
#include <devices/storage/blockstoragedevice.h>
@@ -40,7 +41,7 @@ public:
void process_command() override;
protected:
bool is_device_ready() override { return this->is_ready; }
bool is_device_ready() override { return this->image_attached(); }
void mode_select_6(uint8_t param_len);
@@ -55,6 +56,7 @@ protected:
private:
uint8_t data_buf[2048] = {};
TimerInfo phase_switch_timer;
};
#endif // SCSI_HD_H
+5 -3
View File
@@ -31,15 +31,17 @@ void ScsiPhysDevice::notify(ScsiNotification notif_type, int param)
if (notif_type == ScsiNotification::BUS_PHASE_CHANGE) {
switch (param) {
case ScsiPhase::RESET:
LOG_F(9, "device %d: bus reset aknowledged", this->scsi_id);
LOG_F(9, "device %d: bus reset acknowledged", this->scsi_id);
break;
case ScsiPhase::SELECTION:
// check if something tries to select us
if (this->bus_obj->get_data_lines() & (1 << scsi_id)) {
LOG_F(9, "device %d selected", this->scsi_id);
TimerManager::get_instance()->add_oneshot_timer(
if (this->bus_settle_timer.active)
LOG_F(ERROR, "%s: bus_settle_timer already active", this->get_name().c_str());
TimerManager::get_instance()->add_oneshot_timer(bus_settle_timer,
BUS_SETTLE_DELAY,
[this]() {
[this](uint64_t, uint64_t) {
// don't confirm selection if BSY or I/O are asserted
if (this->bus_obj->test_ctrl_lines(SCSI_CTRL_BSY | SCSI_CTRL_IO))
return;
+96 -66
View File
@@ -36,11 +36,15 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <machines/machinebase.h>
#include <cinttypes>
#include <optional>
#include <string>
#include <vector>
using namespace std;
static std::optional<uint32_t> rtc_start_time;
static std::chrono::steady_clock::time_point rtc_start_host_time;
ViaCuda::ViaCuda() : I2CBus() {
this->name = "ViaCuda";
@@ -99,21 +103,17 @@ ViaCuda::ViaCuda() : I2CBus() {
ViaCuda::~ViaCuda()
{
if (this->sr_timer_id) {
TimerManager::get_instance()->cancel_timer(this->sr_timer_id);
this->sr_timer_id = 0;
if (this->sr_timer.active) {
TimerManager::get_instance()->cancel_timer(this->sr_timer);
}
if (this->t1_timer_id) {
TimerManager::get_instance()->cancel_timer(this->t1_timer_id);
this->t1_timer_id = 0;
if (this->t1_timer.active) {
TimerManager::get_instance()->cancel_timer(this->t1_timer);
}
if (this->t2_timer_id) {
TimerManager::get_instance()->cancel_timer(this->t2_timer_id);
this->t2_timer_id = 0;
if (this->t2_timer.active) {
TimerManager::get_instance()->cancel_timer(this->t2_timer);
}
if (this->treq_timer_id) {
TimerManager::get_instance()->cancel_timer(this->treq_timer_id);
this->treq_timer_id = 0;
if (this->treq_timer.active) {
TimerManager::get_instance()->cancel_timer(this->treq_timer);
}
}
@@ -160,10 +160,12 @@ uint8_t ViaCuda::read(int reg) {
case VIA_T1LH:
return this->via_t1lh;
case VIA_T2CL:
this->check_t2();
this->_via_ifr &= ~VIA_IF_T2;
update_irq();
return this->calc_counter_val(this->t2_counter, this->t2_start_time) & 0xFFU;
case VIA_T2CH:
this->check_t2();
return this->calc_counter_val(this->t2_counter, this->t2_start_time) >> 8;
case VIA_SR:
value = this->via_sr;
@@ -175,6 +177,7 @@ uint8_t ViaCuda::read(int reg) {
case VIA_PCR:
return this->via_pcr;
case VIA_IFR:
this->check_t2();
return this->_via_ifr;
case VIA_IER:
return (this->_via_ier | 0x80); // bit 7 always reads as "1"
@@ -210,9 +213,8 @@ void ViaCuda::write(int reg, uint8_t value) {
break;
case VIA_T1CH:
// cancel active T1 timer task
if (this->t1_timer_id) {
TimerManager::get_instance()->cancel_timer(this->t1_timer_id);
this->t1_timer_id = 0;
if (this->t1_timer.active) {
TimerManager::get_instance()->cancel_timer(this->t1_timer);
}
// clear T1 flag in IFR
this->_via_ifr &= ~VIA_IF_T1;
@@ -221,7 +223,7 @@ void ViaCuda::write(int reg, uint8_t value) {
this->via_t1lh = value;
// load the T1 counter from the corresponding latches
this->t1_counter = (this->via_t1lh << 8) | this->via_t1ll;
this->activate_t1();
this->activate_t1(TimerManager::get_instance()->current_time_ns());
break;
case VIA_T1LL:
this->via_t1ll = value;
@@ -237,26 +239,15 @@ void ViaCuda::write(int reg, uint8_t value) {
break;
case VIA_T2CH:
// cancel active T2 timer task
if (this->t2_timer_id) {
TimerManager::get_instance()->cancel_timer(this->t2_timer_id);
this->t2_timer_id = 0;
if (this->t2_timer.active) {
TimerManager::get_instance()->cancel_timer(this->t2_timer);
}
// clear T2 flag in IFR
this->_via_ifr &= ~VIA_IF_T2;
update_irq();
// load initial value into counter 2
this->t2_counter = (value << 8) | this->via_t2ll;
// TODO: delay for one phase 2 clock
// sample current vCPU time and remember it
this->t2_start_time = TimerManager::get_instance()->current_time_ns();
// set up timeout timer for T2
this->t2_timer_id = TimerManager::get_instance()->add_oneshot_timer(
(this->via_clk_dur * (this->t2_counter + 3) + (uint64_t(1) << 36)) >> 37,
[this]() {
this->t2_timer_id = 0;
this->assert_t2_int();
}
);
this->activate_t2(TimerManager::get_instance()->current_time_ns());
break;
case VIA_SR:
this->via_sr = value;
@@ -293,30 +284,58 @@ uint16_t ViaCuda::calc_counter_val(const uint16_t last_val, const uint64_t &star
{
// calculate current counter value based on elapsed time and timer frequency
uint64_t cur_time = TimerManager::get_instance()->current_time_ns();
// The loaded value remains visible during the initial half-clock delay.
if (cur_time <= start_time)
return last_val;
uint64_t diff_hi;
uint32_t diff_lo;
_u32xu64(this->via_clk_freq, cur_time - start_time, diff_hi, diff_lo);
return last_val - (diff_hi >> 10);
}
void ViaCuda::activate_t1() {
void ViaCuda::activate_t1(uint64_t start_time) {
// TODO: delay for one phase 2 clock
// sample current vCPU time and remember it
this->t1_start_time = TimerManager::get_instance()->current_time_ns();
this->t1_start_time = start_time;
uint64_t timeout = start_time +
((this->via_clk_dur * (this->t1_counter + 3) + (uint64_t(1) << 36)) >> 37);
// set up timout timer for T1
this->t1_timer_id = TimerManager::get_instance()->add_oneshot_timer(
(this->via_clk_dur * (this->t1_counter + 3) + (uint64_t(1) << 36)) >> 37,
[this]() {
TimerManager::get_instance()->add_absolute_timer(this->t1_timer,
timeout, 0,
[this](uint64_t timeout_ns, uint64_t /*time_now*/) {
// reload the T1 counter from the corresponding latches
this->t1_counter = (this->via_t1lh << 8) | this->via_t1ll;
this->t1_timer_id = 0;
this->assert_t1_int();
if (this->via_acr & 0x40)
this->activate_t1();
this->activate_t1(timeout_ns);
}
);
}
void ViaCuda::activate_t2(uint64_t start_time) {
// T2's one-shot interrupt occurs N + 1.5 VIA clocks after loading N.
// Timer begins counting after 0.5 VIA clocks
start_time += (this->via_clk_dur + (uint64_t(1) << 37)) >> 38;
this->t2_start_time = start_time;
// Timer ends N + 1 VIA clocks after start time.
uint64_t timeout = start_time +
((this->via_clk_dur * (this->t2_counter + 1) + (uint64_t(1) << 36)) >> 37);
TimerManager::get_instance()->add_absolute_timer(
this->t2_timer, timeout, 0, [this](uint64_t, uint64_t) { this->assert_t2_int(); });
}
void ViaCuda::check_t2() {
// The process_events is where assert_t2_int is supposed to happen,
// but if a register read doesn't see that an interrupt happened
// when the counter wraps, then Microseconds in classic Mac OS will
// fail, so we call assert_t2_int here which sets the IFR register
// makes the interrupt happen as soon as possible.
auto tm = TimerManager::get_instance();
if (this->t2_timer.active && tm->current_time_ns() >= this->t2_timer.timeout_ns) {
tm->cancel_timer(this->t2_timer);
this->assert_t2_int();
}
}
void ViaCuda::print_enabled_ints() {
const char* via_int_src[] = {"CA2", "CA1", "SR", "CB2", "CB1", "T2", "T1"};
@@ -382,14 +401,12 @@ void ViaCuda::assert_ctrl_line(ViaLine line)
}
void ViaCuda::schedule_sr_int(uint64_t timeout_ns) {
if (this->sr_timer_id) {
TimerManager::get_instance()->cancel_timer(this->sr_timer_id);
this->sr_timer_id = 0;
if (this->sr_timer.active) {
TimerManager::get_instance()->cancel_timer(this->sr_timer);
}
this->sr_timer_id = TimerManager::get_instance()->add_oneshot_timer(
TimerManager::get_instance()->add_oneshot_timer(this->sr_timer,
timeout_ns,
[this]() {
this->sr_timer_id = 0;
[this](uint64_t, uint64_t) {
this->assert_sr_int();
}
);
@@ -420,12 +437,13 @@ void ViaCuda::write(uint8_t new_state) {
process_packet();
// start response transaction
this->treq_timer_id = TimerManager::get_instance()->add_oneshot_timer(
if (this->treq_timer.active)
LOG_F(ERROR, "Cuda: treq_timer is already active");
TimerManager::get_instance()->add_oneshot_timer(this->treq_timer,
USECS_TO_NSECS(13), // delay TREQ assertion for New World
[this]() {
[this](uint64_t, uint64_t) {
this->via_portb &= ~CUDA_TREQ; // assert TREQ
this->treq = 0;
this->treq_timer_id = 0;
});
}
@@ -618,7 +636,7 @@ void ViaCuda::autopoll_handler() {
// Don't send one-second packets if a command response is pending.
// Unlike autopoll, time packets are not urgent enough to preempt.
if (!this->treq || this->treq_timer_id || this->sr_timer_id) {
if (!this->treq || this->treq_timer.active || this->sr_timer.active) {
// ERS: track missed ticks for mode $02/$03 fallback
if (this_time != this->last_time)
this->one_sec_missed = true;
@@ -790,7 +808,8 @@ void ViaCuda::pseudo_command() {
response_header(CUDA_PKT_PSEUDO, 0);
break;
case CUDA_SET_POWER_MESSAGES:
LOG_F(WARNING, "Cuda: unsupported pseudo command 0x%X SET_POWER_MESSAGES", cmd);
this->power_messages_enabled = !!this->in_buf[2];
LOG_F(INFO, "Cuda: power messages %s", this->power_messages_enabled ? "enabled" : "disabled");
response_header(CUDA_PKT_PSEUDO, 0);
break;
case CUDA_READ_WRITE_I2C:
@@ -798,7 +817,18 @@ void ViaCuda::pseudo_command() {
i2c_simple_transaction(this->in_buf[2], &this->in_buf[3], this->in_count - 3);
break;
case CUDA_TIMER_TICKLE:
LOG_F(WARNING, "Cuda: unsupported pseudo command 0x%X TIMER_TICKLE - Byte Sent: 0x%02x", cmd, this->in_buf[2]);
// The guest re-arms the Cuda shutdown watchdog on every tickle; the
// firmware counts it down at 16 counts/sec and powers the machine off
// when it reaches zero. We track the count so an arm value change is
// visible in the log, but never act on expiry to avoid spurious
// power-offs if the guest stops tickling.
if (this->tickle_value != this->in_buf[2]) {
this->tickle_value = this->in_buf[2];
LOG_F(INFO, "Cuda: timer tickle set to %d counts (%.1f s)", this->tickle_value,
(double)this->tickle_value / 16.0);
} else {
LOG_F(9, "Cuda: timer tickle");
}
response_header(CUDA_PKT_PSEUDO, 0);
break;
case CUDA_COMB_FMT_I2C:
@@ -846,24 +876,24 @@ void ViaCuda::pseudo_command() {
}
}
void ViaCuda::set_start_time(std::chrono::local_seconds start_time)
{
// The Macintosh RTC counts local calendar seconds since January 1, 1904.
auto mac_epoch = std::chrono::local_days{std::chrono::year{1904}/1/1};
rtc_start_time = uint32_t((start_time - mac_epoch).count());
rtc_start_host_time = std::chrono::steady_clock::now();
}
uint32_t ViaCuda::calc_real_time() {
std::chrono::time_point<std::chrono::system_clock> end;
if (is_deterministic) {
// March 24, 2001 was the public release date of Mac OS X.
std::tm tm = {
.tm_sec = 0,
.tm_min = 0,
.tm_hour = 12,
.tm_mday = 24,
.tm_mon = 3 - 1,
.tm_year = 2001 - 1900,
.tm_isdst = 0
};
end = std::chrono::system_clock::from_time_t(std::mktime(&tm));
} else {
end = std::chrono::system_clock::now();
if (rtc_start_time) {
// We still want to advance time in deterministic mode, but tie it to
// virtual time so that it's reproducible.
uint64_t elapsed_seconds = is_deterministic ? get_virt_time_ns() / NS_PER_SEC :
std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::steady_clock::now() - rtc_start_host_time).count();
return uint32_t(*rtc_start_time + elapsed_seconds);
}
auto elapsed_systemclock = end - this->mac_epoch;
auto elapsed_systemclock = std::chrono::system_clock::now() - this->mac_epoch;
auto elapsed_seconds = std::chrono::duration_cast<std::chrono::seconds>(elapsed_systemclock);
return uint32_t(elapsed_seconds.count());
}
+16 -7
View File
@@ -42,6 +42,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef VIACUDA_H
#define VIACUDA_H
#include <core/timermanager.h>
#include <devices/common/i2c/i2c.h>
#include <devices/common/nvram.h>
@@ -172,6 +173,10 @@ public:
return std::unique_ptr<ViaCuda>(new ViaCuda());
}
// Configure the initial RTC from a fixed time. If not set the current
// wall time is used.
static void set_start_time(std::chrono::local_seconds start_time);
// HWComponent methods
int device_postinit();
@@ -198,20 +203,20 @@ private:
uint32_t via_clk_freq; // 0.00078336 VIA clock periods per ns; 0 integer bits, 42 fraction bits (first 10 are implicit zeros)
// VIA internal state
uint32_t sr_timer_id = 0;
TimerInfo sr_timer;
uint8_t last_orb = 0; // last value written to the ORB register.
// timer 1 state
uint8_t via_t1ll; // low-order latch
uint8_t via_t1lh; // high-order latch
uint16_t t1_counter; // internal counter
uint32_t t1_timer_id = 0;
TimerInfo t1_timer;
uint64_t t1_start_time = 0;
// timer 2 state
uint8_t via_t2ll; // low-order latch (write-only)
uint16_t t2_counter; // internal counter
uint32_t t2_timer_id = 0;
TimerInfo t2_timer;
uint64_t t2_start_time = 0;
// VIA interrupt related stuff
@@ -225,7 +230,7 @@ private:
uint8_t old_byteack;
uint8_t treq;
bool is_sync_state = false;
uint32_t treq_timer_id = 0;
TimerInfo treq_timer;
uint8_t in_buf[CUDA_IN_BUF_SIZE];
int32_t in_count;
int max_in_count = 0;
@@ -239,8 +244,10 @@ private:
uint8_t one_sec_mode = 0;
bool one_sec_first_pkt = true; // ERS: first one-sec pkt always mode $01
bool one_sec_missed = false; // ERS: missed pkt -> fallback to mode $01
bool file_server = false;
bool mono_stable = false;
bool file_server = false;
bool mono_stable = false;
bool power_messages_enabled = false;
uint8_t tickle_value = 0; // last shutdown watchdog count from the guest
uint8_t ipl_level = 0;
uint16_t device_mask = 0;
@@ -266,7 +273,9 @@ private:
void assert_t2_int();
void schedule_sr_int(uint64_t timeout_ns);
uint16_t calc_counter_val(const uint16_t last_val, const uint64_t &start_time);
void activate_t1();
void activate_t1(uint64_t start_time);
void activate_t2(uint64_t start_time);
void check_t2();
// CUDA methods
void cuda_init();
+27 -28
View File
@@ -70,17 +70,14 @@ void Swim3Ctrl::reset()
this->timer_val = 0;
this->phase_lines = 0;
if (this->one_us_timer_id) {
TimerManager::get_instance()->cancel_timer(this->one_us_timer_id);
this->one_us_timer_id = 0;
if (this->one_us_timer.active) {
TimerManager::get_instance()->cancel_timer(this->one_us_timer);
}
if (this->step_timer_id) {
TimerManager::get_instance()->cancel_timer(this->step_timer_id);
this->step_timer_id = 0;
if (this->step_timer.active) {
TimerManager::get_instance()->cancel_timer(this->step_timer);
}
if (this->access_timer_id) {
TimerManager::get_instance()->cancel_timer(this->access_timer_id);
this->access_timer_id = 0;
if (this->access_timer.active) {
TimerManager::get_instance()->cancel_timer(this->access_timer);
}
}
@@ -115,6 +112,8 @@ uint8_t Swim3Ctrl::read(uint8_t reg_offset)
return this->phase_lines;
case Swim3Reg::Setup:
return this->setup_reg;
case Swim3Reg::Status_Mode0:
return this->mode_reg;
case Swim3Reg::Handshake_Mode1:
if (this->mode_reg & SWIM3_DRIVE_1) { // internal drive?
status_addr = ((this->mode_reg & SWIM3_HEAD_SELECT) >> 2) | (this->phase_lines & 7);
@@ -237,7 +236,7 @@ void Swim3Ctrl::do_step()
// instruct the drive to perform single step in current direction
this->int_drive->command(MacSuperdrive::CommandAddr::Do_Step, 0);
if (--this->step_count == 0) {
if (this->step_timer_id) {
if (this->step_timer.active) {
this->stop_stepping();
}
this->int_flags |= INT_STEP_DONE;
@@ -253,12 +252,12 @@ void Swim3Ctrl::start_stepping()
return;
}
if (this->mode_reg & SWIM3_GO_STEP || this->step_timer_id) {
if (this->mode_reg & SWIM3_GO_STEP || this->step_timer.active) {
LOG_F(ERROR, "SWIM3: another stepping action is running!");
return;
}
if (this->mode_reg & SWIM3_GO || this->access_timer_id) {
if (this->mode_reg & SWIM3_GO || this->access_timer.active) {
LOG_F(ERROR, "SWIM3: stepping attempt while disk access is in progress!");
return;
}
@@ -273,9 +272,9 @@ void Swim3Ctrl::start_stepping()
// step count > 1 requires periodic task
if (this->step_count > 1) {
this->step_timer_id = TimerManager::get_instance()->add_cyclic_timer(
TimerManager::get_instance()->add_cyclic_timer(this->step_timer,
USECS_TO_NSECS(80),
[this]() {
[this](uint64_t, uint64_t) {
this->do_step();
}
);
@@ -288,21 +287,20 @@ void Swim3Ctrl::start_stepping()
void Swim3Ctrl::stop_stepping()
{
// cancel stepping task
if (this->step_timer_id) {
TimerManager::get_instance()->cancel_timer(this->step_timer_id);
this->step_timer_id = 0;
if (this->step_timer.active) {
TimerManager::get_instance()->cancel_timer(this->step_timer);
}
this->step_count = 0; // not sure this one is required
}
void Swim3Ctrl::start_disk_access()
{
if (this->mode_reg & SWIM3_GO || this->access_timer_id) {
if (this->mode_reg & SWIM3_GO || this->access_timer.active) {
LOG_F(ERROR, "SWIM3: another disk access is running!");
return;
}
if (this->mode_reg & SWIM3_GO_STEP || this->step_timer_id) {
if (this->mode_reg & SWIM3_GO_STEP || this->step_timer.active) {
LOG_F(ERROR, "SWIM3: disk access attempt while stepping is in progress!");
return;
}
@@ -317,9 +315,9 @@ void Swim3Ctrl::start_disk_access()
this->target_sect = this->first_sec;
this->access_timer_id = TimerManager::get_instance()->add_oneshot_timer(
TimerManager::get_instance()->add_oneshot_timer(this->access_timer,
this->int_drive->sync_to_disk(),
[this]() {
[this](uint64_t, uint64_t) {
this->cur_state = SWIM3_ADDR_MARK_SEARCH;
this->disk_access();
}
@@ -369,9 +367,9 @@ void Swim3Ctrl::disk_access()
return;
}
this->access_timer_id = TimerManager::get_instance()->add_oneshot_timer(
TimerManager::get_instance()->add_oneshot_timer(this->access_timer,
delay,
[this]() {
[this](uint64_t, uint64_t) {
this->disk_access();
}
);
@@ -380,9 +378,8 @@ void Swim3Ctrl::disk_access()
void Swim3Ctrl::stop_disk_access()
{
// cancel disk access timer
if (this->access_timer_id) {
TimerManager::get_instance()->cancel_timer(this->access_timer_id);
this->access_timer_id = 0;
if (this->access_timer.active) {
TimerManager::get_instance()->cancel_timer(this->access_timer);
}
}
@@ -399,9 +396,11 @@ void Swim3Ctrl::init_timer(const uint8_t start_val)
this->one_us_timer_start = TimerManager::get_instance()->current_time_ns();
this->one_us_timer_id = TimerManager::get_instance()->add_oneshot_timer(
if( this->one_us_timer.active)
LOG_F(ERROR, "SWIM3: one_us_timer is already active");
TimerManager::get_instance()->add_oneshot_timer(this->one_us_timer,
uint32_t(this->timer_val) * NS_PER_USEC,
[this]() {
[this](uint64_t, uint64_t) {
this->timer_val = 0;
this->int_flags |= INT_TIMER_DONE;
update_irq();
+3 -3
View File
@@ -140,9 +140,9 @@ private:
uint8_t rd_line;
int cur_state;
int one_us_timer_id = 0;
int step_timer_id = 0;
int access_timer_id = 0;
TimerInfo one_us_timer;
TimerInfo step_timer;
TimerInfo access_timer;
uint64_t one_us_timer_start = 0;
+42 -27
View File
@@ -96,9 +96,8 @@ AMIC::AMIC() : MMIODevice()
AMIC::~AMIC()
{
if (this->pseudo_vbl_tid) {
TimerManager::get_instance()->cancel_timer(this->pseudo_vbl_tid);
this->pseudo_vbl_tid = 0;
if (this->pseudo_vbl_timer.active) {
TimerManager::get_instance()->cancel_timer(this->pseudo_vbl_timer);
}
}
@@ -113,9 +112,9 @@ int AMIC::device_postinit()
}
// AMIC drives the VIA CA1 internally to generate 60.15 Hz interrupts
this->pseudo_vbl_tid = TimerManager::get_instance()->add_cyclic_timer(
TimerManager::get_instance()->add_cyclic_timer(pseudo_vbl_timer,
static_cast<uint64_t>((1.0f/60.15) * NS_PER_SEC + 0.5f),
[this]() {
[this](uint64_t, uint64_t) {
this->viacuda->assert_ctrl_line(ViaLine::CA1);
});
@@ -635,7 +634,9 @@ void AmicSndOutDma::update_irq() {
uint8_t new_level = !!((this->dma_out_ctrl >> 4) & this->dma_out_ctrl);
if (new_level != this->irq_level) {
this->irq_level = new_level;
TimerManager::get_instance()->add_immediate_timer([this] {
if (this->interrupt_timer.active)
LOG_F(ERROR, "AMIC: interrupt_timer is already active");
TimerManager::get_instance()->add_immediate_timer(interrupt_timer, [this](uint64_t, uint64_t) {
this->int_ctrl->ack_dma_int(this->snd_dma_irq_id, this->irq_level);
});
}
@@ -687,10 +688,10 @@ DmaPullResult AmicSndOutDma::pull_data(uint32_t req_len, uint32_t *avail_len,
MapDmaResult res = mmu_map_dma_mem(
(this->snd_buf_num ? this->out_buf1 : this->out_buf0) + this->cur_buf_pos,
len, false);
len, false, true);
*p_data = res.host_va;
this->cur_buf_pos += len;
*avail_len = len;
this->cur_buf_pos += res.size;
*avail_len = res.size;
return DmaPullResult::MoreData;
}
@@ -723,15 +724,19 @@ DmaPushResult AmicFloppyDma::push_data(const char* src_ptr, int len)
{
len = std::min((int)this->byte_count, len);
MapDmaResult res = mmu_map_dma_mem(this->addr_ptr, len, false);
uint8_t *p_data = res.host_va;
if (!res.is_writable) {
ABORT_F("AMIC: attempting DMA write to read-only memory");
}
std::memcpy(p_data, src_ptr, len);
do {
MapDmaResult res = mmu_map_dma_mem(this->addr_ptr, len, false, true);
uint8_t *p_data = res.host_va;
if (!res.is_writable) {
ABORT_F("AMIC: attempting DMA write to read-only memory");
}
std::memcpy(p_data, src_ptr, res.size);
this->addr_ptr += len;
this->byte_count -= len;
this->addr_ptr += res.size;
this->byte_count -= res.size;
src_ptr += res.size;
len -= res.size;
} while (len > 0);
if (!this->byte_count) {
LOG_F(WARNING, "AMIC: DMA interrupts not implemented yet");
}
@@ -782,12 +787,17 @@ void AmicScsiDma::xfer_from_device() {
uint32_t len = this->dev_obj->tell_xfer_size(this);
MapDmaResult res = mmu_map_dma_mem(this->addr_ptr, len, false);
do {
MapDmaResult res = mmu_map_dma_mem(this->addr_ptr, len, false, true);
int got_bytes = this->dev_obj->xfer_from(this, res.host_va, len);
if (got_bytes > 0) {
this->addr_ptr += got_bytes;
}
int got_bytes = this->dev_obj->xfer_from(this, res.host_va, res.size);
if (got_bytes > 0) {
this->addr_ptr += got_bytes;
}
if (got_bytes < res.size)
break;
len -= res.size;
} while (len > 0);
}
void AmicScsiDma::xfer_to_device() {
@@ -798,12 +808,17 @@ void AmicScsiDma::xfer_to_device() {
uint32_t len = this->dev_obj->tell_xfer_size(this);
MapDmaResult res = mmu_map_dma_mem(this->addr_ptr, len, false);
do {
MapDmaResult res = mmu_map_dma_mem(this->addr_ptr, len, false, true);
int got_bytes = this->dev_obj->xfer_to(this, res.host_va, len);
if (got_bytes > 0) {
this->addr_ptr += got_bytes;
}
int got_bytes = this->dev_obj->xfer_to(this, res.host_va, res.size);
if (got_bytes > 0) {
this->addr_ptr += got_bytes;
}
if (got_bytes < res.size)
break;
len -= res.size;
} while (len > 0);
}
void AmicScsiDma::xfer_retry() {
+3 -1
View File
@@ -24,6 +24,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef AMIC_H
#define AMIC_H
#include <core/timermanager.h>
#include <devices/common/dmacore.h>
#include <devices/common/hwinterrupt.h>
#include <devices/common/mmiodevice.h>
@@ -133,6 +134,7 @@ private:
InterruptCtrl *int_ctrl = nullptr;
uint64_t snd_dma_irq_id = 0;
uint8_t irq_level = 0;
TimerInfo interrupt_timer;
};
/** AMIC-specific floppy DMA implementation. */
@@ -411,7 +413,7 @@ private:
uint8_t via2_slot_ifr = 0x7F; // reverse logic
uint8_t via2_slot_irq = 0; // normal logic
uint32_t pseudo_vbl_tid = 0; // ID for the pseudo-VBL timer
TimerInfo pseudo_vbl_timer; // the pseudo-VBL timer
// AMIC subdevice instances
Sc53C94* scsi;
+20 -13
View File
@@ -41,13 +41,14 @@ NvramDev::NvramDev(NvramAddrHiDev *addr_hi) {
GrandCentral::GrandCentral() : PCIDevice("mac-io_grandcentral"), InterruptCtrl()
{
supports_types(HWCompType::IOBUS_HOST | HWCompType::MMIO_DEV | HWCompType::PCI_DEV | HWCompType::INT_CTRL);
supports_types(HWCompType::IOBUS_HOST | HWCompType::MMIO_DEV |
HWCompType::PCI_DEV | HWCompType::INT_CTRL);
// populate my PCI config header
this->vendor_id = PCI_VENDOR_APPLE;
this->device_id = MIO_DEV_ID_GRANDCENTRAL;
this->status = 0x0200; // 9:DEVSEL
this->class_rev = 0xFF000002;
this->class_rev = MACIO_DEVCLASS_ID | 2; // hardcoded revision = 2
this->cache_ln_sz = 8;
this->setup_bars({{0, 0xFFFE0000UL}}); // declare 128Kb of memory-mapped I/O space
@@ -295,7 +296,7 @@ uint32_t GrandCentral::read(uint32_t rgn_start, uint32_t offset, int size)
} else { // Interrupt related registers
switch (offset) {
case MIO_INT_EVENTS1:
return BYTESWAP_32(this->int_events);
return BYTESWAP_32(this->int_events & this->int_mask);
case MIO_INT_MASK1:
return BYTESWAP_32(this->int_mask);
case MIO_INT_CLEAR1:
@@ -303,7 +304,7 @@ uint32_t GrandCentral::read(uint32_t rgn_start, uint32_t offset, int size)
// so we return zero here as real HW does
return 0;
case MIO_INT_LEVELS1:
return BYTESWAP_32(this->int_levels);
return BYTESWAP_32(this->int_levels | (1<<0x0B));
}
}
@@ -433,6 +434,7 @@ void GrandCentral::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
switch (offset) {
case MIO_INT_MASK1:
this->int_mask = BYTESWAP_32(value);
this->clear_cpu_int();
this->signal_cpu_int();
break;
case MIO_INT_CLEAR1:
@@ -523,15 +525,11 @@ uint64_t GrandCentral::register_dma_int(IntSrc src_id) {
}
void GrandCentral::ack_int_common(uint64_t irq_id, uint8_t irq_line_state) {
// native mode: set IRQ bits in int_events on a 0-to-1 transition
// emulated mode: set IRQ bits in int_events on all transitions
// MACIO_INT_MODE is 0: native mode: set IRQ bits in int_events on a 0-to-1 transition
// MACIO_INT_MODE is 1: emulated mode: set IRQ bits in int_events on all transitions
if ((this->int_mask & MACIO_INT_MODE) ||
(irq_line_state && !(this->int_levels & irq_id))) {
this->int_events |= (uint32_t)irq_id;
} else {
this->int_events &= ~(uint32_t)irq_id;
}
uint32_t old_levels = this->int_levels;
uint32_t old_events = this->int_events;
// update IRQ line state
if (irq_line_state) {
@@ -540,7 +538,16 @@ void GrandCentral::ack_int_common(uint64_t irq_id, uint8_t irq_line_state) {
this->int_levels &= ~(uint32_t)irq_id;
}
this->signal_cpu_int();
if (
irq_line_state != !!(old_levels & irq_id)
&& (irq_line_state || (this->int_mask & MACIO_INT_MODE))
) {
this->int_events |= (uint32_t)irq_id;
// Events remain latched until software writes InterruptClear.
if (old_events != this->int_events) {
this->signal_cpu_int();
}
}
}
void GrandCentral::ack_int(uint64_t irq_id, uint8_t irq_line_state) {
+7 -4
View File
@@ -44,6 +44,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <memory>
#include <string>
/** MacIO ASICs report themselves as devices with unassigned PCI class code. */
constexpr uint32_t MACIO_DEVCLASS_ID = DEVCLASS_UNASSIGNED << 24;
/** PCI device IDs for various MacIO ASICs. */
enum {
MIO_DEV_ID_GRANDCENTRAL = 0x0002,
@@ -359,10 +362,10 @@ private:
uint32_t feat_ctrl = 0; // features control register
uint32_t aux_ctrl = 0; // aux features control register
uint8_t cpu_id = 0xF0; // CPUID field (LSB of the MIO_HEAT_ID)
uint8_t mb_id = 0x70; // Media Bay ID (bits 15:8 of the MIO_HEAT_ID)
uint8_t mon_id = 0x10; // Monitor ID (bits 23:16 of the MIO_HEAT_ID)
uint8_t fp_id = 0x70; // Flat panel ID (MSB of the MIO_HEAT_ID)
uint8_t cpu_id = 0xF0; // CPUID field (LSB of the MIO_OHARE_ID)
uint8_t mb_id = 0x70; // Media Bay ID (bits 15:8 of the MIO_OHARE_ID)
uint8_t mon_id = 0x10; // Monitor ID (bits 23:16 of the MIO_OHARE_ID)
uint8_t fp_id = 0x70; // Flat panel ID (MSB of the MIO_OHARE_ID)
// Subdevice object pointers
NVram* nvram; // NVRAM
+16 -10
View File
@@ -38,7 +38,7 @@ MacIoBase::MacIoBase(std::string name, uint16_t dev_id, uint8_t rev) :
// populate my PCI config header
this->vendor_id = PCI_VENDOR_APPLE;
this->device_id = dev_id;
this->class_rev = 0xFF000000 + rev;
this->class_rev = MACIO_DEVCLASS_ID + rev;
this->cache_ln_sz = 8;
// select memory mapped I/O size: 128Kb for Grand Central, 512Kb for others
@@ -133,8 +133,8 @@ uint64_t MacIoBase::register_dma_int(IntSrc src_id) {
}
void MacIoBase::ack_int_common(uint64_t irq_id, uint8_t irq_line_state) {
// native mode: set IRQ bits in int_events on a 0-to-1 transition
// emulated mode: set IRQ bits in int_events on all transitions
// MACIO_INT_MODE is 0: native mode: set IRQ bits in int_events on a 0-to-1 transition
// MACIO_INT_MODE is 1: emulated mode: set IRQ bits in int_events on all transitions
#if 0
LOG_F(INTERRUPT, "%s: native interrupt events:%08x.%08x levels:%08x.%08x change:%08x.%08x state:%d",
this->name.c_str(), uint32_t(this->int_events >> 32), uint32_t(this->int_events),
@@ -142,12 +142,9 @@ void MacIoBase::ack_int_common(uint64_t irq_id, uint8_t irq_line_state) {
uint32_t(irq_id >> 32), uint32_t(irq_id), irq_line_state
);
#endif
if ((this->int_mask & MACIO_INT_MODE) ||
(irq_line_state && !(this->int_levels & irq_id))) {
this->int_events |= irq_id;
} else {
this->int_events &= ~irq_id;
}
uint64_t old_levels = this->int_levels;
uint64_t old_events = this->int_events;
// update IRQ line state
if (irq_line_state) {
this->int_levels |= irq_id;
@@ -155,7 +152,16 @@ void MacIoBase::ack_int_common(uint64_t irq_id, uint8_t irq_line_state) {
this->int_levels &= ~irq_id;
}
this->signal_cpu_int();
if (
irq_line_state != !!(old_levels & irq_id)
&& (irq_line_state || (this->int_mask & MACIO_INT_MODE))
) {
this->int_events |= irq_id;
// Events remain latched until software writes InterruptClear.
if (old_events != this->int_events) {
this->signal_cpu_int();
}
}
}
void MacIoBase::ack_int(uint64_t irq_id, uint8_t irq_line_state) {
+7 -3
View File
@@ -291,7 +291,7 @@ uint32_t MacIoTwo::mio_ctrl_read(uint32_t offset, int size) {
switch (offset & ~3) {
case MIO_INT_EVENTS2:
value = this->int_events >> 32;
value = (this->int_events & this->int_mask) >> 32;
break;
case MIO_INT_MASK2:
value = this->int_mask >> 32;
@@ -300,7 +300,7 @@ uint32_t MacIoTwo::mio_ctrl_read(uint32_t offset, int size) {
value = this->int_levels >> 32;
break;
case MIO_INT_EVENTS1:
value = uint32_t(this->int_events);
value = uint32_t(this->int_events & this->int_mask);
break;
case MIO_INT_MASK1:
value = uint32_t(this->int_mask);
@@ -366,7 +366,10 @@ void MacIoTwo::mio_ctrl_write(uint32_t offset, uint32_t value, int size) {
switch (offset & ~3) {
case MIO_INT_MASK2:
this->int_mask |= uint64_t(value & ~MACIO_INT_MODE) << 32;
// Preserve the first bank and the read-only IntMode bit.
this->int_mask = (this->int_mask & 0x80000000FFFFFFFFULL) |
(uint64_t(value & ~MACIO_INT_MODE) << 32);
this->clear_cpu_int();
this->signal_cpu_int();
break;
case MIO_INT_CLEAR2:
@@ -377,6 +380,7 @@ void MacIoTwo::mio_ctrl_write(uint32_t offset, uint32_t value, int size) {
this->int_mask = (this->int_mask & 0x7FFFFFFF00000000ULL) | value;
// copy IntMode bit to InterruptMask2 register
this->int_mask |= uint64_t(this->int_mask & MACIO_INT_MODE) << 32;
this->clear_cpu_int();
this->signal_cpu_int();
break;
case MIO_INT_CLEAR1:
+34 -17
View File
@@ -40,7 +40,7 @@ MPC106::MPC106() : MemCtrlBase(), PCIDevice("Grackle"), PCIHost()
// populate PCI config header
this->vendor_id = PCI_VENDOR_MOTOROLA;
this->device_id = 0x0002;
this->class_rev = 0x06000040;
this->class_rev = DEVTYPE_HOST2PCI_BRIDGE | GRACKLE_REV_4_0;
this->cache_ln_sz = 8;
this->command = 6;
this->status = 0x80;
@@ -314,24 +314,41 @@ void MPC106::setup_ram() {
}
}
static const PropMap Grackle_Properties = {
{"pci_PERCH",
new StrProperty("")},
{"pci_A1",
new StrProperty("")},
{"pci_B1",
new StrProperty("")},
{"pci_C1",
new StrProperty("")},
//{"pci_GPU",
// new StrProperty("")},
{"pci_J12",
new StrProperty("")},
static const PropMap GrackleGossamer_Properties = {
{"pci_PERCH", new StrProperty("")},
{"pci_A1" , new StrProperty("")},
{"pci_B1" , new StrProperty("")},
{"pci_C1" , new StrProperty("")},
// {"pci_GPU" , new StrProperty("")},
};
static const DeviceDescription Grackle_Descriptor = {
MPC106::create, {}, Grackle_Properties,
static const PropMap GrackleYosemite_Properties = {
// {"pci_J12", new StrProperty("")},
};
static const PropMap GrackleBondi_Properties = {
{"pci_A1" , new StrProperty("")},
{"pci_B1" , new StrProperty("")},
{"pci_C1" , new StrProperty("")},
// {"pci_GPU" , new StrProperty("")},
{"pci_PERCH", new StrProperty("")},
};
static const DeviceDescription GrackleGossamer_Descriptor = {
MPC106::create, {}, GrackleGossamer_Properties,
HWCompType::MEM_CTRL | HWCompType::MMIO_DEV | HWCompType::PCI_HOST | HWCompType::PCI_DEV
};
REGISTER_DEVICE(Grackle, Grackle_Descriptor);
static const DeviceDescription GrackleYosemite_Descriptor = {
MPC106::create, {}, GrackleYosemite_Properties,
HWCompType::MEM_CTRL | HWCompType::MMIO_DEV | HWCompType::PCI_HOST | HWCompType::PCI_DEV
};
static const DeviceDescription GrackleBondi_Descriptor = {
MPC106::create, {}, GrackleBondi_Properties,
HWCompType::MEM_CTRL | HWCompType::MMIO_DEV | HWCompType::PCI_HOST | HWCompType::PCI_DEV
};
REGISTER_DEVICE(GrackleGossamer, GrackleGossamer_Descriptor);
REGISTER_DEVICE(GrackleYosemite, GrackleYosemite_Descriptor);
REGISTER_DEVICE(GrackleBondi , GrackleBondi_Descriptor );
+2 -1
View File
@@ -42,7 +42,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cinttypes>
#include <memory>
class InterruptCtrl;
/** Grackle ASIC revisions. */
constexpr uint8_t GRACKLE_REV_4_0 = 0x40;
/** Grackle configuration space registers. */
enum GrackleReg : uint32_t {
+55 -26
View File
@@ -58,7 +58,15 @@ PlatinumCtrl::PlatinumCtrl() : MemCtrlBase(), VideoCtrlBase() {
// initialize the CPUID register with the following CPU:
// PowerPC 601 @ 90 MHz, bus frequency: 45 MHz
this->cpu_id = (0x3001 << 16) | ClkSrc2 | (CpuSpeed2::CPU_90_BUS_45 << 8);
this->cpu_id =
( 0x3 << 28) | // Design Center: 3 = High-End RISC Design Center
( 0 << 24) | // Upper ID: 0 = machine with registers wider than 8-bit
(0x01 << 16) | // Lower ID: 1 = Platinum-based machine
ClkSrc2 | // Clock Source: bits 15 and 6
( 0 << 12) | // Motherboard ID: Catalyst motherboard with 1 MB of VRAM
(CpuSpeed2::CPU_90_BUS_45 << 8)
| // System/CPU Speed
( 0 << 7) ; // CPU Type: 0 = 601, 1 = 603/604
this->display_id = std::unique_ptr<DisplayID> (new DisplayID());
@@ -70,8 +78,10 @@ PlatinumCtrl::PlatinumCtrl() : MemCtrlBase(), VideoCtrlBase() {
};
this->dacula->set_clut_entry_cb = [this](uint8_t index, uint8_t *colors) {
this->set_palette_color(index, colors[0], colors[1], colors[2], 0xFF);
this->draw_fb = true;
};
this->dacula->cursor_ctrl_cb = [this](bool cursor_on) {
this->draw_fb = true;
if (cursor_on) {
this->dacula->measure_hw_cursor(this->fb_ptr - 16);
this->cursor_ovl_cb = [this](uint8_t *dst_buf, int dst_pitch) {
@@ -82,6 +92,14 @@ PlatinumCtrl::PlatinumCtrl() : MemCtrlBase(), VideoCtrlBase() {
this->cursor_ovl_cb = nullptr;
}
};
this->dacula->cursor_update_cb = [this]() {
this->draw_fb = true;
};
this->dacula->video_mode_ctrl_cb = [this]() {
this->change_display();
};
this->draw_fb_is_dynamic = true;
}
int PlatinumCtrl::device_postinit() {
@@ -114,7 +132,7 @@ uint32_t PlatinumCtrl::read(uint32_t rgn_start, uint32_t offset, int size) {
return read_mem(&this->vram_ptr[offset], size);
} else {
LOG_F(WARNING, "%s: read from unmapped aperture address 0x%X",
this->name.c_str(), this->fb_addr + offset);
this->name.c_str(), VRAM_REGION_BASE + offset);
return (uint32_t)-1;
}
}
@@ -215,11 +233,12 @@ void PlatinumCtrl::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
uint8_t mon_levels = 0;
if (rgn_start == VRAM_REGION_BASE) {
if (offset < this->vram_size)
if (offset < this->vram_size) {
this->draw_fb = true;
write_mem(&this->vram_ptr[offset], value, size);
else
} else
LOG_F(WARNING, "%s: write to unmapped aperture address 0x%X",
this->name.c_str(), this->fb_addr + offset);
this->name.c_str(), VRAM_REGION_BASE + offset);
return;
}
@@ -228,10 +247,10 @@ void PlatinumCtrl::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
this->rom_timing = value;
break;
case PlatinumReg::DRAM_TIMING:
this->dram_timing = value;
this->dram_timing = value & 0x1FFF;
break;
case PlatinumReg::DRAM_REFRESH:
this->dram_refresh = value;
this->dram_refresh = value & 0x7FF;
break;
case PlatinumReg::BANK_0_BASE:
case PlatinumReg::BANK_1_BASE:
@@ -241,20 +260,22 @@ void PlatinumCtrl::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
case PlatinumReg::BANK_5_BASE:
case PlatinumReg::BANK_6_BASE:
case PlatinumReg::BANK_7_BASE:
this->bank_base[(offset >> 4) - PlatinumReg::BANK_0_BASE] = value;
this->bank_base[(offset >> 4) - PlatinumReg::BANK_0_BASE] = value & 0xFF700000U;
this->map_phys_ram();
break;
case PlatinumReg::FB_BASE_ADDR:
this->fb_addr = value;
this->fb_offset = value & 0x3FFFFF;
this->change_display();
if (this->fb_addr != value) {
this->fb_addr = value;
this->fb_offset = value & 0x3FFFFF;
this->change_display();
}
break;
case PlatinumReg::ROW_WORDS:
this->row_words = value & ~7;
this->row_words = value & 0x7FF8;
this->change_display();
break;
case PlatinumReg::CLOCK_DIVISOR:
this->clock_divisor = value;
this->clock_divisor = value & 0xFFU;
this->change_display();
break;
case PlatinumReg::FB_CONFIG_1:
@@ -265,10 +286,10 @@ void PlatinumCtrl::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
this->half_bank = !!(this->vram_megs == 1 && (value & CFG1_FULL_BANKS));
break;
case PlatinumReg::FB_CONFIG_2:
this->fb_config_2 = value;
this->fb_config_2 = value & 0x1FFF;
break;
case PlatinumReg::VMEM_PAGE_MODE:
this->vmem_fp_mode = value;
this->vmem_fp_mode = value & 1;
break;
case PlatinumReg::MON_ID_SENSE:
value &= 7;
@@ -279,6 +300,7 @@ void PlatinumCtrl::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
(this->display_id->read_monitor_sense(mon_levels, mon_dirs) ^ 7);
break;
case PlatinumReg::FB_RESET:
value &= 7;
if (value == 7 && this->crtc_on) {
LOG_F(INFO, "%s: video disabled", this->name.c_str());
this->reset_step = 0;
@@ -314,10 +336,10 @@ void PlatinumCtrl::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
(value & (SENSE_LINE_OUTPUT_DATA | SYNCS_OUTPUT_ENABLE | FORCED_SYNC_LEVELS));
break;
case PlatinumReg::VRAM_REFRESH:
this->vram_refresh = value;
this->vram_refresh = value & 0x7FF;
break;
case PlatinumReg::SWATCH_CONFIG:
this->swatch_config = value;
this->swatch_config = (this->swatch_config & ~0xFFU) | (value & 0xFFU);
break;
case PlatinumReg::SWATCH_INT_MASK:
this->swatch_int_mask = value;
@@ -325,7 +347,7 @@ void PlatinumCtrl::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
LOG_F(INFO, "%s: VBL interrupt enabled", this->name.c_str());
break;
case PlatinumReg::CURSOR_LINE:
this->cursor_line = value;
this->cursor_line = value & 0x7FF;
if (this->swatch_int_mask & SWATCH_INT_CURSOR)
this->enable_cursor_int();
break;
@@ -338,7 +360,6 @@ void PlatinumCtrl::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
//break;
case PlatinumReg::SWATCH_HSERR:
case PlatinumReg::SWATCH_HLFLN:
case PlatinumReg::SWATCH_HEQ:
case PlatinumReg::SWATCH_HSP:
case PlatinumReg::SWATCH_HBWAY:
case PlatinumReg::SWATCH_HBRST:
@@ -353,11 +374,15 @@ void PlatinumCtrl::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
case PlatinumReg::SWATCH_VAL:
case PlatinumReg::SWATCH_VFP:
case PlatinumReg::SWATCH_VFPEQ:
this->swatch_params[REG_TO_INDEX(offset >> 4)] = value;
this->swatch_params[REG_TO_INDEX(offset >> 4)] = value & 0xFFF;
this->change_display();
break;
case PlatinumReg::SWATCH_HEQ:
this->swatch_params[REG_TO_INDEX(offset >> 4)] = value & 0xFF;
this->change_display();
break;
case PlatinumReg::TIMING_ADJUST:
this->timing_adjust = value;
this->timing_adjust = value & 0xFFF;
break;
case PlatinumReg::IRIDIUM_CONFIG:
if (!(value & 1))
@@ -514,16 +539,19 @@ void PlatinumCtrl::enable_display() {
switch (this->pixel_depth) {
case 8:
this->convert_fb_cb = [this](uint8_t *dst_buf, int dst_pitch) {
this->draw_fb = false;
this->convert_frame_8bpp_indexed(dst_buf, dst_pitch);
};
break;
case 16:
this->convert_fb_cb = [this](uint8_t *dst_buf, int dst_pitch) {
this->draw_fb = false;
this->convert_frame_15bpp<BE>(dst_buf, dst_pitch);
};
break;
case 32:
this->convert_fb_cb = [this](uint8_t *dst_buf, int dst_pitch) {
this->draw_fb = false;
this->convert_frame_32bpp<BE>(dst_buf, dst_pitch);
};
break;
@@ -564,6 +592,7 @@ void PlatinumCtrl::enable_display() {
this->blank_on = false;
this->crtc_on = true;
this->draw_fb = true;
}
void PlatinumCtrl::disable_display() {
@@ -586,12 +615,12 @@ void PlatinumCtrl::enable_cursor_int() {
LOG_F(INFO, "%s: cursor interrupt frequency %lld ns", this->name.c_str(),
cursor_int_freq);
if (this->cursor_task_id)
TimerManager::get_instance()->cancel_timer(this->cursor_task_id);
if (this->cursor_timer.active)
TimerManager::get_instance()->cancel_timer(this->cursor_timer);
this->cursor_task_id = TimerManager::get_instance()->add_cyclic_timer(
TimerManager::get_instance()->add_cyclic_timer(this->cursor_timer,
cursor_int_freq,
[this]() {
[this](uint64_t, uint64_t) {
this->update_irq(1, SWATCH_INT_CURSOR); // generate cursor interrupt
}
);
@@ -612,7 +641,7 @@ void PlatinumCtrl::update_irq(uint8_t irq_line_state, uint8_t irq_mask) {
// ========================== Device registry stuff ==========================
static const PropMap Platinum_Properties = {
{"gfxmem_size",
new IntProperty(1, std::vector<uint32_t>({1, 2, 4}))},
new IntProperty(4, std::vector<uint32_t>({1, 2, 4}))},
{"mon_id",
new StrProperty("HiRes12-14in")},
};
+1 -1
View File
@@ -363,7 +363,7 @@ private:
uint32_t swatch_int_mask = 0;
uint32_t swatch_int_stat = 0;
uint32_t cursor_line = 0;
uint32_t cursor_task_id = 0;
TimerInfo cursor_timer;
std::unique_ptr<uint8_t[]> vram_ptr = nullptr;
std::unique_ptr<DisplayID> display_id = nullptr;
-1
View File
@@ -38,7 +38,6 @@ PsxCtrl::PsxCtrl(int bridge_num, std::string name)
// add MMIO region for the PSX control registers
this->add_mmio_region(0xF8000000, 0x70, this);
this->sys_id = 0x10000000; // PSX register dump from a 6500 at 68kmla
this->set_revision_id(0x10); // PSX register dump from a 6500 at 68kmla
this->set_bus_speed(PSX_BUS_SPEED_50); // set bus speed to 50 MHz by default
}
+7 -7
View File
@@ -92,13 +92,13 @@ public:
void map_phys_ram();
private:
uint32_t sys_id;
uint32_t chip_rev;
uint32_t sys_config;
uint32_t rom_cfg;
uint32_t dram_cfg;
uint32_t dram_refresh;
uint32_t flash_cfg;
uint32_t sys_id = 0x10000000; // PSX register dump from a 6500 at 68kmla
uint32_t chip_rev = 0;
uint32_t sys_config = 0;
uint32_t rom_cfg = 0x000009D8;
uint32_t dram_cfg = 0x00E18534;
uint32_t dram_refresh = 0x001F0180;
uint32_t flash_cfg = 0x00000038;
uint32_t pages_cfg[5] = {0x88888888,0x88888888,0x88888888,0x88888888,0x88888888};
uint32_t bank_size[5] = {};
std::unique_ptr<uint8_t[]> dram_ptr = nullptr;
+7 -8
View File
@@ -114,11 +114,12 @@ void AwacsBase::dma_in_data() {
dbdma_ch->set_stat(sound_in_status);
LOG_F(INFO, "%s: status:%x", this->name.c_str(), sound_in_status);
this->dma_in_timer_id = TimerManager::get_instance()->add_oneshot_timer(
if (this->dma_in_timer.active)
LOG_F(ERROR, "%s: dma_in_timer is already active", this->name.c_str());
TimerManager::get_instance()->add_oneshot_timer(this->dma_in_timer,
10000,
[this]() {
[this](uint64_t, uint64_t) {
// re-enter the sequencer with the state specified in next_state
this->dma_in_timer_id = 0;
this->dma_in_data();
});
}
@@ -130,9 +131,8 @@ void AwacsBase::dma_in_start() {
}
void AwacsBase::dma_in_stop() {
if (this->dma_in_timer_id) {
TimerManager::get_instance()->cancel_timer(this->dma_in_timer_id);
this->dma_in_timer_id = 0;
if (this->dma_in_timer.active) {
TimerManager::get_instance()->cancel_timer(this->dma_in_timer);
}
LOG_F(ERROR, "%s: dma_in_stop", this->name.c_str());
}
@@ -199,7 +199,7 @@ uint32_t AwacsScreamer::snd_ctrl_read(uint32_t offset, int size) {
(AWAC_REV_SCREAMER << 20);
break;
case AWAC_CLIP_COUNT:
value = this->clip_count;
value = this->clip_count;
this->clip_count = 0;
break;
case AWAC_BYTE_SWAP:
@@ -221,7 +221,6 @@ void AwacsScreamer::snd_ctrl_write(uint32_t offset, uint32_t value, int size) {
this->snd_ctrl_reg = BYTESWAP_32(value);
this->set_sample_rate((this->snd_ctrl_reg >> 8) & 7);
break;
case AWAC_CODEC_CTRL_REG: {
if (this->is_busy)
return;
+1 -1
View File
@@ -66,7 +66,7 @@ protected:
SoundServer *snd_server; // SoundServer instance pointer
DmaOutChannel *dma_out_ch; // DMA output channel instance pointer
DmaInChannel *dma_in_ch; // DMA input channel instance pointer
uint32_t dma_in_timer_id = 0;
TimerInfo dma_in_timer;
int *sr_table; // pointer to the table of supported sample rates
int max_sr_id; // maximum value for sample rate ID
+45 -28
View File
@@ -28,8 +28,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <devices/sound/burgundy.h>
#include <loguru.hpp>
BurgundyCodec::BurgundyCodec(std::string name) : MacioSndCodec(name)
{
BurgundyCodec::BurgundyCodec(std::string name) : MacioSndCodec(name) {
supports_types(HWCompType::SND_CODEC);
static int burgundy_sample_rates[1] = { 44100 };
@@ -39,6 +38,8 @@ BurgundyCodec::BurgundyCodec(std::string name) : MacioSndCodec(name)
this->max_sr_id = 1;
this->set_sample_rate(0); // set default sample rate
this->reg_array[0x01] = 0x01010000; // ID 1 (Burgundy), Vendor 1 (Crystal), Version 0, Revision 0
}
uint32_t BurgundyCodec::snd_ctrl_read(uint32_t offset, int size) {
@@ -52,9 +53,20 @@ uint32_t BurgundyCodec::snd_ctrl_read(uint32_t offset, int size) {
value = this->last_ctrl_data;
break;
case AWAC_CODEC_STATUS_REG:
value = (this->first_valid << 23) | BURGUNDY_READY |
(this->byte_counter << 14) | (this->read_pos << 12) |
(this->data_byte << 4);
value =
(
(
9 |
CODEC_STATUS::SENSE_MIC |
CODEC_STATUS::SENSE_HEADPHONES
) << CODEC_STATUS::SENSE_POS
) |
(this->data_byte << CODEC_STATUS::DATA_POS) |
(this->read_pos << CODEC_STATUS::CURRENTBYTE_POS) |
(this->byte_counter << CODEC_STATUS::BYTECOUNTER_POS) |
(0 << CODEC_STATUS::INDICATOR_POS) |
CODEC_STATUS::READY |
(this->first_valid ? CODEC_STATUS::FIRST_VALID_BYTE : 0);
break;
case AWAC_FRAME_COUNT:
value = (uint32_t)(
@@ -73,42 +85,47 @@ uint32_t BurgundyCodec::snd_ctrl_read(uint32_t offset, int size) {
}
void BurgundyCodec::snd_ctrl_write(uint32_t offset, uint32_t value, int size) {
uint8_t reg_addr;
uint8_t cur_byte;
//uint8_t last_byte;
value = BYTESWAP_32(value);
switch (offset) {
case AWAC_SOUND_CTRL_REG:
this->snd_ctrl_reg = BYTESWAP_32(value);
//this->set_sample_rate((this->snd_ctrl_reg >> 8) & 7);
this->snd_ctrl_reg = value;
//this->set_sample_rate((this->snd_ctrl_reg & SOUND_CONTROL::RATE_MASK) >> SOUND_CONTROL::RATE_POS);
break;
case AWAC_CODEC_CTRL_REG:
this->last_ctrl_data = value;
reg_addr = (value >> 12) & 0xFF;
cur_byte = (value >> 8) & 3;
//last_byte = (value >> 10) & 3;
if (value & BURGUNDY_REG_WR) {
uint32_t mask = 0xFFU << (cur_byte * 8);
this->reg_array[reg_addr] = (this->reg_array[reg_addr] & ~mask) |
((value & 0xFFU) << (cur_byte * 8));
{
this->last_ctrl_data = value & ~CODEC_CONTROL::BUSY;
uint8_t write_byte = (value & CODEC_CONTROL::DATA_MASK) >> CODEC_CONTROL::DATA_POS;
uint8_t reg_addr = (value & CODEC_CONTROL::ADDR_MASK) >> CODEC_CONTROL::ADDR_POS;
uint8_t cur_byte = (value & CODEC_CONTROL::CURRENTBYTE_MASK) >> CODEC_CONTROL::CURRENTBYTE_POS;
uint8_t last_byte = (value & CODEC_CONTROL::LASTBYTE_MASK) >> CODEC_CONTROL::LASTBYTE_POS;
bool reset = value & CODEC_CONTROL::RESET;
bool write = value & CODEC_CONTROL::WRITE;
if (write) {
if (reg_addr < BURGUNDY_NUM_REGS) {
uint32_t mask = 0xFFU << (cur_byte * 8);
this->reg_array[reg_addr] = (this->reg_array[reg_addr] & ~mask) |
(write_byte << (cur_byte * 8));
}
} else {
this->reg_addr = reg_addr;
this->read_pos = cur_byte;
this->data_byte = (this->reg_array[reg_addr] >> (cur_byte * 8)) & 0xFFU;
this->first_valid = 1;
this->reg_addr = reg_addr;
this->read_pos = cur_byte;
this->data_byte = ((reg_addr < BURGUNDY_NUM_REGS ? this->reg_array[reg_addr] : 0) >> (cur_byte * 8)) & 0xFFU;
this->first_valid = true;
TimerManager::get_instance()->add_oneshot_timer(
USECS_TO_NSECS(10), // not sure if this is the correct delay
[this]() {
this->first_valid = 0;
if (this->first_valid_timer.active)
LOG_F(ERROR, "%s: first_valid_timer is already active", this->name.c_str());
TimerManager::get_instance()->add_oneshot_timer(this->first_valid_timer,
USECS_TO_NSECS(22), // average is approximately 22.6 µs on a real B&W G3
[this](uint64_t, uint64_t) {
this->first_valid = false;
this->byte_counter = (this->byte_counter + 1) & 3;
});
}
break;
}
case AWAC_FRAME_COUNT:
this->frame_count = BYTESWAP_32(value);
this->frame_count = value;
this->frame_count_start_time = TimerManager::get_instance()->current_time_ns();
break;
default:
+78 -6
View File
@@ -24,20 +24,91 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef BURGUNDY_H
#define BURGUNDY_H
#include <core/timermanager.h>
#include <devices/common/hwcomponent.h>
#include <devices/sound/awacs.h>
#include <cinttypes>
#include <string>
enum {
BURGUNDY_REG_WR = 1 << 21,
BURGUNDY_READY = 1 << 22,
};
/** Number of internal registers implemented in Burgundy. */
constexpr auto BURGUNDY_NUM_REGS = 123;
namespace SOUND_CONTROL { // 0x00
enum {
INSUBFRAME_MASK = 0x0000000F,
INSUBFRAME_POS = 0,
INSUBFRAME0 = 0x1,
INSUBFRAME1 = 0x2,
INSUBFRAME2 = 0x4,
INSUBFRAME3 = 0x8,
OUTSUBFRAME_MASK = 0x000000F0,
OUTSUBFRAME_POS = 4,
OUTSUBFRAME0 = 0x1,
OUTSUBFRAME1 = 0x2,
OUTSUBFRAME2 = 0x4,
OUTSUBFRAME3 = 0x8,
RATE_MASK = 0x00000700,
RATE_POS = 8,
RATE_44100 = 0x0,
ERROR = 0x00000800,
PORTCHANGE = 0x00001000,
ERRORINT = 0x00002000,
STATUSSUBFRAME_MASK = 0x00018000,
STATUSSUBFRAME_POS = 15,
STATUSSUBFRAME0 = 0x0,
STATUSSUBFRAME1 = 0x1,
STATUSSUBFRAME2 = 0x2,
STATUSSUBFRAME3 = 0x3,
};
}
namespace CODEC_CONTROL { // 0x10
enum {
DATA_MASK = 0x000000FF,
DATA_POS = 0,
CURRENTBYTE_MASK = 0x00000300,
CURRENTBYTE_POS = 8,
LASTBYTE_MASK = 0x00000C00,
LASTBYTE_POS = 10,
ADDR_MASK = 0x000FF000,
ADDR_POS = 12,
RESET = 0x00100000, // should be set when current byte is 0
WRITE = 0x00200000, // READ = 0
BUSY = 0x01000000, // set when writing to CODEC_CONTROL, clear when done
};
}
namespace CODEC_STATUS { // 0x20
enum {
SENSE_MASK = 0x0000000F,
SENSE_POS = 0,
SENSE_MIC = 0x2,
SENSE_HEADPHONES = 0x4,
SENSE_HEADPHONES2 = 0x8, // 1 = line level mic (default) 0 = powered mic
DATA_MASK = 0x00000FF0,
DATA_POS = 4,
CURRENTBYTE_MASK = 0x00003000,
CURRENTBYTE_POS = 12,
BYTECOUNTER_MASK = 0x0000C000,
BYTECOUNTER_POS = 14,
INDICATOR_MASK = 0x000F0000,
INDICATOR_POS = 16,
INDICATOR_TONECONTROL = 0x1,
INDICATOR_OVERFLOW0 = 0x2,
INDICATOR_OVERFLOW1 = 0x3,
INDICATOR_OVERFLOW2 = 0x4,
INDICATOR_INPUTLINECHG = 0x6,
INDICATOR_THRESHOLD0 = 0xB,
INDICATOR_THRESHOLD1 = 0xC,
INDICATOR_THRESHOLD2 = 0xD,
INDICATOR_THRESHOLD3 = 0xE,
INDICATOR_TWILIGHTCMP = 0xF,
READY = 0x00400000,
FIRST_VALID_BYTE = 0x00800000, // wait for set, then wait for clear before reading data
};
}
class BurgundyCodec : public MacioSndCodec {
public:
BurgundyCodec(std::string name);
@@ -55,7 +126,8 @@ private:
uint32_t last_ctrl_data = 0;
uint8_t byte_counter = 0;
uint8_t reg_addr = 0;
uint8_t first_valid = 0;
bool first_valid = false;
TimerInfo first_valid_timer;
uint8_t read_pos = 0;
uint8_t data_byte = 0;
uint32_t frame_count = 0;
+42 -24
View File
@@ -51,7 +51,7 @@ public:
cubeb *cubeb_ctx;
cubeb_stream *out_stream;
uint32_t deterministic_poll_timer = 0;
TimerInfo deterministic_poll_timer;
timer_cb deterministic_poll_cb;
};
@@ -167,22 +167,26 @@ static void status_callback(cubeb_stream *stream, void *user_data, cubeb_state s
int SoundServer::open_out_stream(uint32_t sample_rate, DmaOutChannel *dma_ch)
{
// Set up a cyclic-timer DMA drain callback. It keeps the guest sound DMA
// advancing even if the host audio stream cannot be started, otherwise
// the guest sound driver would stall forever waiting for DMA interrupts.
impl->deterministic_poll_cb = [dma_ch](uint64_t, uint64_t) {
if (!dma_ch->is_out_active()) {
return;
}
// Drain the DMA buffer, but don't do anything else.
while(1) {
uint8_t *chunk;
uint32_t chunk_size;
if (DmaPullResult::MoreData == dma_ch->pull_data(1024, &chunk_size, &chunk)) {
;
} else {
break;
}
}
};
if (is_deterministic) {
impl->deterministic_poll_cb = [dma_ch] {
if (!dma_ch->is_out_active()) {
return;
}
// Drain the DMA buffer, but don't do anything else.
while(1) {
uint8_t *chunk;
uint32_t chunk_size;
if (DmaPullResult::MoreData == dma_ch->pull_data(1024, &chunk_size, &chunk)) {
;
} else {
break;
}
}
};
impl->status = SND_STREAM_OPENED;
LOG_F(9, "Deterministic sound output callback set up.");
return 0;
@@ -223,21 +227,35 @@ int SoundServer::open_out_stream(uint32_t sample_rate, DmaOutChannel *dma_ch)
int SoundServer::start_out_stream()
{
if (is_deterministic) {
LOG_F(9, "Starting sound output deterministic polling.");
impl->deterministic_poll_timer =
TimerManager::get_instance()->add_cyclic_timer(MSECS_TO_NSECS(10), impl->deterministic_poll_cb);
// DMA can restart after a STOP command without closing the output
// stream; the timer may already be running.
if (!impl->deterministic_poll_timer.active) {
LOG_F(9, "Starting sound output deterministic polling.");
TimerManager::get_instance()->add_cyclic_timer(
impl->deterministic_poll_timer, MSECS_TO_NSECS(10), impl->deterministic_poll_cb);
}
return 0;
}
return cubeb_stream_start(impl->out_stream);
int res = cubeb_stream_start(impl->out_stream);
if (res != CUBEB_OK) {
// Fall back to draining the guest sound DMA via a cyclic timer so
// that the guest sound driver does not stall waiting for DMA progress
// that the failed host stream will never provide.
if (!impl->deterministic_poll_timer.active) {
TimerManager::get_instance()->add_cyclic_timer(
impl->deterministic_poll_timer, MSECS_TO_NSECS(10), impl->deterministic_poll_cb);
LOG_F(9, "Host sound output stream start failed; falling back to cyclic DMA drain.");
}
}
return res;
}
void SoundServer::close_out_stream()
{
if (!impl->out_stream)
return;
if (is_deterministic) {
LOG_F(9, "Stopping sound output deterministic polling.");
if (impl->deterministic_poll_timer.active) {
TimerManager::get_instance()->cancel_timer(impl->deterministic_poll_timer);
}
if (!impl->out_stream) {
impl->status = SND_STREAM_CLOSED;
return;
}
+30 -7
View File
@@ -39,22 +39,45 @@ BlockStorageDevice::BlockStorageDevice(const uint32_t cache_blocks,
}
BlockStorageDevice::~BlockStorageDevice() {
this->img_file.close();
this->detach_image();
}
int BlockStorageDevice::set_host_file(std::string file_path) {
this->is_ready = false;
bool BlockStorageDevice::attach_image(const std::string& file_path) {
if (!this->img_file.open(file_path))
return -1;
return false;
this->size_bytes = this->img_file.size();
this->is_ready = false;
this->size_bytes = this->img_file.size();
this->remain_size = 0;
this->write_size = 0;
this->data_offset = 0;
this->set_fpos(0);
this->is_ready = true;
return this->set_block_size(this->block_size);
if (this->set_block_size(this->block_size) < 0) {
this->detach_image();
return false;
}
return true;
}
bool BlockStorageDevice::detach_image() {
if (!this->is_ready)
return false;
this->is_ready = false;
this->img_file.close();
this->size_bytes = 0;
this->size_blocks = 0;
this->cur_fpos = 0;
this->write_size = 0;
this->remain_size = 0;
return true;
}
int BlockStorageDevice::set_block_size(const int blk_size) {
+4 -1
View File
@@ -36,7 +36,10 @@ public:
const uint64_t max_blocks=UINT64_MAX);
~BlockStorageDevice();
int set_host_file(std::string file_path);
bool attach_image(const std::string& file_path);
bool detach_image();
bool image_attached() const { return this->is_ready; }
int set_block_size(const int blk_size);
int set_fpos(const uint64_t lba);
+51 -3
View File
@@ -21,6 +21,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file Virtual CD-ROM device implementation. */
#include <core/hostevents.h>
#include <devices/storage/cdromdrive.h>
#include <loguru.hpp>
@@ -29,12 +30,46 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <string>
CdromDrive::CdromDrive() : BlockStorageDevice(31, CDR_STD_DATA_SIZE, 0xfffffffe) {
EventManager::get_instance()->add_cdrom_handler(
this, &CdromDrive::insert_image_event_handler);
this->is_writeable = false;
}
void CdromDrive::insert_image(std::string filename) {
if (this->set_host_file(filename) < 0)
ABORT_F("Could not open CD-ROM image file, %s", filename.c_str());
void CdromDrive::insert_image_event_handler(CdromImageEvent& event) {
if (event.handled)
return;
if (this->medium_present()) {
event.result = CdromInsertionResult::MEDIA_PRESENT;
return;
}
event.handled = true;
if (this->insert_image(event.image_path)) {
this->media_change_pending = true;
event.result = CdromInsertionResult::SUCCESS;
} else {
event.result = CdromInsertionResult::IMAGE_OPEN_FAILED;
}
}
bool CdromDrive::consume_media_change() {
bool pending = this->media_change_pending;
this->media_change_pending = false;
return pending;
}
bool CdromDrive::insert_image(const std::string& filename) {
if (this->medium_present()) {
LOG_F(ERROR, "Cannot insert CD-ROM image while media is present");
return false;
}
if (!this->attach_image(filename)) {
LOG_F(ERROR, "Could not open CD-ROM image file, %s", filename.c_str());
return false;
}
this->detect_raw_image();
@@ -45,6 +80,19 @@ void CdromDrive::insert_image(std::string filename) {
// create Lead-out descriptor containing all data
this->tracks[1] = {LEAD_OUT_TRK_NUM, /*.trk_num*/ 0x14, /*.adr_ctrl*/
static_cast<uint32_t>(this->size_blocks + 1) /*.start_lba*/};
return true;
}
bool CdromDrive::eject_image() {
if (!this->detach_image())
return false;
this->num_tracks = 0;
this->media_change_pending = false;
std::memset(this->tracks, 0, sizeof(this->tracks));
return true;
}
bool CdromDrive::detect_raw_image() {
+9 -2
View File
@@ -74,16 +74,22 @@ constexpr auto CDROM_MAX_TRACKS = 100;
constexpr auto LEAD_OUT_TRK_NUM = 0xAA;
constexpr auto CDR_STD_DATA_SIZE = 2048;
class CdromImageEvent;
class CdromDrive : public BlockStorageDevice {
public:
CdromDrive();
virtual ~CdromDrive() = default;
bool medium_present() { return this->is_ready; }
bool medium_present() const { return this->image_attached(); }
void insert_image(std::string filename);
bool insert_image(const std::string& filename);
bool eject_image();
protected:
void insert_image_event_handler(CdromImageEvent& event);
bool consume_media_change();
uint8_t hex_to_bcd(const uint8_t val);
AddrMsf lba_to_msf(const int lba);
bool detect_raw_image();
@@ -101,6 +107,7 @@ protected:
uint8_t sw_lock_sup = 1; // drive supports locking/unlocking via SW
uint8_t sw_eject_sup = 1; // drive supports ejecting via SW
uint8_t drive_locked = 0; // 1 - drive is currently locked
bool media_change_pending = false; // pending guest notification
uint8_t prevent_jump = 0; // prevent jumper not present
uint8_t more_support = 0;
uint16_t max_rd_speed = 706; // defaults to 4x
+26 -12
View File
@@ -83,48 +83,62 @@ void AppleRamdac::iodev_write(uint32_t address, uint16_t value) {
(this->clut_color[1] << 8) | this->clut_color[2];
this->dac_addr++; // auto-increment CLUT address
this->comp_index = 0;
this->cursor_update_cb();
}
break;
case RamdacRegs::MULTI:
switch (this->dac_addr) {
case RamdacRegs::CURSOR_POS_HI:
#ifdef CURSOR_LO_DELAY // HACK: prevents artifacts in some cases, disabled by default
if (this->cursor_timer_id) {
TimerManager::get_instance()->cancel_timer(this->cursor_timer_id);
cursor_timer_id = 0;
if (this->cursor_timer.active) {
TimerManager::get_instance()->cancel_timer(this->cursor_timer);
}
this->cursor_xpos = (value << 8) | this->cursor_pos_lo;
#else
this->cursor_xpos = (value << 8) | (this->cursor_xpos & 0xff);
#endif
this->cursor_update_cb();
break;
case RamdacRegs::CURSOR_POS_LO:
#ifdef CURSOR_LO_DELAY // HACK: prevents artifacts in some cases, disabled by default
if (this->cursor_timer_id) {
TimerManager::get_instance()->cancel_timer(this->cursor_timer_id);
if (this->cursor_timer.active) {
TimerManager::get_instance()->cancel_timer(this->cursor_timer);
this->cursor_xpos = (this->cursor_xpos & 0xff00) | (this->cursor_pos_lo & 0x00ff);
cursor_timer_id = 0;
}
this->cursor_pos_lo = value;
this->cursor_timer_id = TimerManager::get_instance()->add_oneshot_timer(
NS_PER_SEC / 60, [this]() {
this->cursor_pos_lo = value;
TimerManager::get_instance()->add_oneshot_timer(this->cursor_timer,
NS_PER_SEC / 60, [this](uint64_t, uint64_t) {
this->cursor_xpos = (this->cursor_xpos & 0xff00) | (this->cursor_pos_lo & 0x00ff);
});
this->cursor_update_cb();
}
);
#else
this->cursor_xpos = (this->cursor_xpos & 0xff00) | (value & 0x00ff);
#endif
this->cursor_update_cb();
break;
case RamdacRegs::MISC_CTRL:
case RamdacRegs::MISC_CTRL: {
if (bit_changed(this->dac_cr, value, 1)) {
if (value & 2)
this->cursor_ctrl_cb(true);
else
this->cursor_ctrl_cb(false);
}
int old_pix_width = this->get_pix_width();
int old_clock_div = this->get_clock_div();
this->dac_cr = value;
int new_pix_width = this->get_pix_width();
if (old_pix_width != new_pix_width || old_clock_div != this->get_clock_div()) {
this->video_mode_ctrl_cb();
}
break;
}
case RamdacRegs::DBL_BUF_CTRL:
this->dbl_buf_cr = value;
if (this->dbl_buf_cr != value) {
this->dbl_buf_cr = value;
if (this->buffer_update_cb)
this->buffer_update_cb();
}
break;
case RamdacRegs::TEST_CTRL:
this->tst_cr = value;
+5 -1
View File
@@ -91,6 +91,7 @@ enum RamdacRegs : uint8_t {
typedef std::function<void(uint8_t index, uint8_t *colors)> GetClutEntryCallback;
typedef std::function<void(uint8_t index, uint8_t *colors)> SetClutEntryCallback;
typedef std::function<void(bool cursor_on)> CursorCtrlCallback;
typedef std::function<void()> VideoModeCtrlCallback;
class AppleRamdac : public HWComponent, public IobusDevice {
public:
@@ -117,6 +118,9 @@ public:
GetClutEntryCallback get_clut_entry_cb = nullptr;
SetClutEntryCallback set_clut_entry_cb = nullptr;
CursorCtrlCallback cursor_ctrl_cb = nullptr;
std::function<void()> cursor_update_cb = nullptr;
std::function<void()> buffer_update_cb = nullptr;
VideoModeCtrlCallback video_mode_ctrl_cb = nullptr;
protected:
DacFlavour flavour;
@@ -139,7 +143,7 @@ protected:
uint32_t fb_pitch = 0;
#ifdef CURSOR_LO_DELAY
uint8_t cursor_pos_lo = 0;
uint32_t cursor_timer_id = 0;
TimerInfo cursor_timer;
#endif
};
+3 -3
View File
@@ -443,7 +443,9 @@ void ATIRage::write_reg(uint32_t reg_offset, uint32_t value, uint32_t size) {
bits_read_only |= bits_not_AKed; // the not AKed bits will remain unchanged
new_value = (old_value & bits_read_only) | (new_value & ~bits_read_only);
break;
WRITE_VALUE_AND_LOG(9);
this->update_interrupt();
return;
}
case ATI_CRTC_GEN_CNTL:
new_value = value;
@@ -658,8 +660,6 @@ void ATIRage::write_reg(uint32_t reg_offset, uint32_t value, uint32_t size) {
}
WRITE_VALUE_AND_LOG(9);
if (reg_num == ATI_CRTC_INT_CNTL)
this->update_interrupt();
}
bool ATIRage::io_access_allowed(uint32_t offset) {
+143 -51
View File
@@ -48,6 +48,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cinttypes>
// Big-endian VRAM aperture select bit; clear for the little-endian aperture.
// See Apple patent US5793996A, cols. 17-18.
constexpr uint32_t VRAM_BE_APERTURE = 0x800000;
namespace loguru {
enum : Verbosity {
Verbosity_RADACAL = loguru::Verbosity_INFO,
@@ -118,8 +122,10 @@ ControlVideo::ControlVideo()
};
this->radacal->set_clut_entry_cb = [this](uint8_t index, uint8_t *colors) {
this->set_palette_color(index, colors[0], colors[1], colors[2], 0xFF);
this->draw_fb = true;
};
this->radacal->cursor_ctrl_cb = [this](bool cursor_on) {
this->draw_fb = true;
if (cursor_on) {
this->radacal->measure_hw_cursor(this->fb_ptr - 16);
this->cursor_ovl_cb = [this](uint8_t *dst_buf, int dst_pitch) {
@@ -130,6 +136,20 @@ ControlVideo::ControlVideo()
this->cursor_ovl_cb = nullptr;
}
};
this->radacal->cursor_update_cb = [this]() {
this->draw_fb = true;
};
this->radacal->buffer_update_cb = [this]() {
this->draw_fb = true;
if (this->display_enabled) {
this->update_fb_ptr();
}
};
this->radacal->video_mode_ctrl_cb = [this]() {
if (this->display_enabled) {
this->enable_display();
}
};
// attach IOBus Device #2 0xF301B000 ; register RaDACal with the I/O controller
GrandCentral* gc_obj = dynamic_cast<GrandCentral*>(gMachineObj->get_comp_by_name("GrandCentralTnt"));
@@ -137,6 +157,8 @@ ControlVideo::ControlVideo()
// initialize display identification
this->display_id = std::unique_ptr<DisplayID> (new DisplayID());
this->draw_fb_is_dynamic = true;
}
void ControlVideo::change_one_bar(uint32_t &aperture, uint32_t aperture_size, uint32_t aperture_new, int bar_num) {
@@ -216,7 +238,7 @@ static const char * get_name_controlreg(int offset) {
uint32_t ControlVideo::read(uint32_t rgn_start, uint32_t offset, int size)
{
if (rgn_start == this->vram_base) {
if (offset & 0x800000) { // repeats every 16MB
if (offset & VRAM_BE_APERTURE) { // repeats every 16MB
// HACK: writing to VRAM in 128bit mode with only the standard
// bank populated seems to replicate the first 64bit portion of data
// in the second 64bit portion. This "feature" is used by
@@ -276,9 +298,38 @@ uint32_t ControlVideo::read(uint32_t rgn_start, uint32_t offset, int size)
} // if not VRAM_WIDE_MODE
}
LOG_F(ERROR, "%s: read from little-endian aperture address 0x%X", this->name.c_str(),
this->vram_base + offset);
return 0;
// Little-endian aperture, reverse bytes within each 16/32-bit pixel.
uint32_t value;
int pixel_width = this->radacal->get_pix_width();
switch (pixel_width) {
case 8:
return this->read(rgn_start, offset | VRAM_BE_APERTURE, size);
case 16:
if (offset & (size - 1)) // unaligned access, handled below
break;
value = this->read(rgn_start,
(offset ^ (size == 1 ? 1 : 0)) | VRAM_BE_APERTURE, size);
if (size == 2)
return BYTESWAP_16(value);
if (size == 4)
return (uint32_t(BYTESWAP_16(value >> 16)) << 16) | BYTESWAP_16(value);
return value;
case 32:
if (offset & (size - 1)) // unaligned access, handled below
break;
value = this->read(rgn_start, (offset ^ (4 - size)) | VRAM_BE_APERTURE, size);
return size == 4 ? BYTESWAP_32(value) : size == 2 ? BYTESWAP_16(value) : value;
default:
LOG_F(ERROR, "%s: unsupported pixel width %d for little-endian VRAM read",
this->name.c_str(), pixel_width);
return 0;
}
// Unaligned accesses can straddle pixels or VRAM banks. Split them
// into smaller accesses so each uses the correct byte lanes.
int half_size = size >> 1;
return (this->read(rgn_start, offset, half_size) << (half_size * 8)) |
this->read(rgn_start, offset + half_size, half_size);
}
if (rgn_start == this->regs_base) {
@@ -322,7 +373,7 @@ uint32_t ControlVideo::read(uint32_t rgn_start, uint32_t offset, int size)
case ControlRegs::MON_SENSE:
value = (this->cur_mon_id << 6) | this->mon_sense;
LOG_F(9, "%s: read MON_SENSE %03x.%c = %0*x", this->name.c_str(),
offset, SIZE_ARG(size), size * 2, value);
offset, SIZE_ARG(size), size * 2, value);
break;
case ControlRegs::MISC_ENABLES:
value = this->enables;
@@ -350,7 +401,7 @@ uint32_t ControlVideo::read(uint32_t rgn_start, uint32_t offset, int size)
uint32_t result = pci_conv_rd_data(value, value, details);
if ((offset & 3) || (size != 4)) {
LOG_F(WARNING, "%s: read %s %03x.%c = %08x -> %0*x", this->name.c_str(),
get_name_controlreg(offset), offset, SIZE_ARG(size), value, size * 2, result);
get_name_controlreg(offset), offset, SIZE_ARG(size), value, size * 2, result);
}
return result;
@@ -362,7 +413,8 @@ uint32_t ControlVideo::read(uint32_t rgn_start, uint32_t offset, int size)
void ControlVideo::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size)
{
if (rgn_start == this->vram_base) {
if (offset & 0x800000) {
this->draw_fb = true;
if (offset & VRAM_BE_APERTURE) {
if (this->enables & VRAM_WIDE_MODE) {
// Note: we ignore access to 4MB range at 0xC00000 because it is undefined for VRAM_WIDE_MODE.
// There is data there but it is not in the same order as the first 4MB.
@@ -417,9 +469,36 @@ void ControlVideo::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
}
} // switch
} // if not VRAM_WIDE_MODE
} else {
LOG_F(ERROR, "%s: write to little-endian aperture address 0x%X", this->name.c_str(),
this->vram_base + offset);
} else { // little-endian aperture
int pixel_width = this->radacal->get_pix_width();
switch (pixel_width) {
case 8:
return this->write(rgn_start, offset | VRAM_BE_APERTURE, value, size);
case 16:
if (offset & (size - 1)) // unaligned access, handled below
break;
offset ^= size == 1 ? 1 : 0;
if (size == 2)
value = BYTESWAP_16(value);
else if (size == 4)
value = (uint32_t(BYTESWAP_16(value >> 16)) << 16) | BYTESWAP_16(value);
return this->write(rgn_start, offset | VRAM_BE_APERTURE, value, size);
case 32:
if (offset & (size - 1)) // unaligned access, handled below
break;
offset ^= 4 - size;
value = size == 4 ? BYTESWAP_32(value) : size == 2 ? BYTESWAP_16(value) : value;
return this->write(rgn_start, offset | VRAM_BE_APERTURE, value, size);
default:
LOG_F(ERROR, "%s: unsupported pixel width %d for little-endian VRAM write",
this->name.c_str(), pixel_width);
return;
}
// Split unaligned accesses as in the read path.
int half_size = size >> 1;
this->write(rgn_start, offset, value >> (half_size * 8), half_size);
this->write(rgn_start, offset + half_size, value, half_size);
}
return;
}
@@ -432,10 +511,10 @@ void ControlVideo::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
this->swatch_params[(offset >> 4) - ControlRegs::VFPEQ] = value & 0x3FF;
if (value & ~0x3FF)
LOG_F(ERROR, "%s: write PIPE_DELAY %03x.%c = %0*x", this->name.c_str(),
offset, SIZE_ARG(size), size * 2, value);
offset, SIZE_ARG(size), size * 2, value);
else
LOG_F(CONTROL, "%s: write PIPE_DELAY %03x.%c = %0*x", this->name.c_str(),
offset, SIZE_ARG(size), size * 2, value);
offset, SIZE_ARG(size), size * 2, value);
if (this->display_enabled) {
this->enable_display();
}
@@ -444,10 +523,10 @@ void ControlVideo::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
this->swatch_params[(offset >> 4) - ControlRegs::VFPEQ] = value & 0xFFU;
if (value & ~0xFFU)
LOG_F(ERROR, "%s: write HEQ %03x.%c = %0*x", this->name.c_str(),
offset, SIZE_ARG(size), size * 2, value);
offset, SIZE_ARG(size), size * 2, value);
else
LOG_F(CONTROL, "%s: write HEQ %03x.%c = %0*x", this->name.c_str(),
offset, SIZE_ARG(size), size * 2, value);
offset, SIZE_ARG(size), size * 2, value);
if (this->display_enabled) {
this->enable_display();
}
@@ -469,10 +548,10 @@ void ControlVideo::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
this->swatch_params[(offset >> 4) - ControlRegs::VFPEQ] = value & 0xFFF;
if (value & ~0xFFF)
LOG_F(ERROR, "%s: write %s %03x.%c = %0*x", this->name.c_str(),
get_name_controlreg(offset), offset, SIZE_ARG(size), size * 2, value);
get_name_controlreg(offset), offset, SIZE_ARG(size), size * 2, value);
else
LOG_F(CONTROL, "%s: write %s %03x.%c = %0*x", this->name.c_str(),
get_name_controlreg(offset), offset, SIZE_ARG(size), size * 2, value);
get_name_controlreg(offset), offset, SIZE_ARG(size), size * 2, value);
if (this->display_enabled) {
this->enable_display();
}
@@ -504,12 +583,17 @@ void ControlVideo::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
} else
this->swatch_ctrl = value;
break;
case ControlRegs::GBASE:
this->fb_base = value & 0x3FFFE0;
if (this->display_enabled) {
this->enable_display();
case ControlRegs::GBASE:{
uint32_t old_value = this->fb_base;
uint32_t new_value = value & 0x3FFFE0;
if (new_value != old_value) {
this->fb_base = new_value;
if (this->display_enabled) {
this->enable_display();
}
}
break;
}
case ControlRegs::ROW_WORDS:
this->row_words = value & 0x7FE0;
if (this->display_enabled) {
@@ -517,12 +601,11 @@ void ControlVideo::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
}
break;
case ControlRegs::MON_SENSE: {
if (value & ~0x3F)
LOG_F(ERROR, "%s: write MON_SENSE %03x.%c = %0*x", this->name.c_str(),
offset, SIZE_ARG(size), size * 2, value);
else
LOG_F(9, "%s: write MON_SENSE %03x.%c = %0*x", this->name.c_str(),
offset, SIZE_ARG(size), size * 2, value);
// This is a nine-bit register (bits 6-8 are read-only sense
// inputs that can be written back). Log unexpected values.
VLOG_F((value & ~0x1FF) ? loguru::Verbosity_ERROR : 9,
"%s: write MON_SENSE %03x.%c = %0*x", this->name.c_str(),
offset, SIZE_ARG(size), size * 2, value);
uint8_t dirs = ((value >> 3) & 7) ^ 7;
uint8_t levels = ((value & 7) & dirs) | (dirs ^ 7);
this->mon_sense = value & 0x3F;
@@ -531,6 +614,7 @@ void ControlVideo::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
break;
case ControlRegs::MISC_ENABLES:
if ((this->enables ^ value) & BLANK_DISABLE) {
this->draw_fb = true;
if (value & BLANK_DISABLE)
this->blank_on = false;
else {
@@ -570,6 +654,31 @@ uint8_t* ControlVideo::GetVram()
return &this->vram_ptr[0];
}
void ControlVideo::update_fb_ptr()
{
this->fb_ptr = &this->vram_ptr[this->fb_base];
if (swatch_params[ControlRegs::HAL-1] != swatch_params[ControlRegs::PIPE_DELAY-1] + 1 ||
this->pixel_depth == 32 ||
(this->pixel_depth == 16 && this->active_width == 1280)
) {
// don't know how to calculate offset from GBASE (fb_base); it is always hard coded as + 16 in the ndrv.
this->fb_ptr += 16; // first 16 bytes are for 4 bpp HW cursor
}
else {
/*
Open Firmware frame buffer has these properties:
- GBASE == 0 // no offset from vram_ptr
- fb_ptr == vram_ptr // no offset from GBASE
- active_width == ROW_WORDS (row_words) // no offset between rows
- HAL == PIPE_DELAY + 1
- depth_mode = 0 // 8 bit indexed
*/
}
if (this->radacal->get_dbl_buf_cr() == 0 && this->vram_banks == 3) {
this->fb_ptr += 0x200000;
}
}
void ControlVideo::enable_display()
{
int new_width, new_height, clk_divisor;
@@ -592,49 +701,30 @@ void ControlVideo::enable_display()
this->active_width = new_width;
this->active_height = new_height;
// set framebuffer parameters
this->fb_ptr = &this->vram_ptr[this->fb_base];
this->fb_pitch = this->row_words;
if (~this->enables & SCAN_CONTROL) {
this->fb_pitch >>= 1;
}
this->pixel_depth = this->radacal->get_pix_width();
if (swatch_params[ControlRegs::HAL-1] != swatch_params[ControlRegs::PIPE_DELAY-1] + 1 ||
this->pixel_depth == 32 ||
(this->pixel_depth == 16 && this->active_width == 1280)
) {
// don't know how to calculate offset from GBASE (fb_base); it is always hard coded as + 16 in the ndrv.
this->fb_ptr += 16; // first 16 bytes are for 4 bpp HW cursor
}
else {
/*
Open Firmware frame buffer has these properties:
- GBASE == 0 // no offset from vram_ptr
- fb_ptr == vram_ptr // no offset from GBASE
- active_width == ROW_WORDS (row_words) // no offset between rows
- HAL == PIPE_DELAY + 1
- depth_mode = 0 // 8 bit indexed
*/
}
if (this->radacal->get_dbl_buf_cr() == 0 && this->vram_banks == 3) {
this->fb_ptr += 0x200000;
}
// get pixel depth from RaDACal
this->pixel_depth = this->radacal->get_pix_width();
this->update_fb_ptr();
switch (this->pixel_depth) {
case 8:
this->convert_fb_cb = [this](uint8_t *dst_buf, int dst_pitch) {
this->draw_fb = false;
this->convert_frame_8bpp_indexed(dst_buf, dst_pitch);
};
break;
case 16:
this->convert_fb_cb = [this](uint8_t *dst_buf, int dst_pitch) {
this->draw_fb = false;
this->convert_frame_15bpp<BE>(dst_buf, dst_pitch);
};
break;
case 32:
this->convert_fb_cb = [this](uint8_t *dst_buf, int dst_pitch) {
this->draw_fb = false;
this->convert_frame_32bpp<BE>(dst_buf, dst_pitch);
};
break;
@@ -682,6 +772,8 @@ void ControlVideo::enable_display()
this->blank_on = true;
this->crtc_on = false;
}
this->draw_fb = true;
}
void ControlVideo::disable_display()
+1
View File
@@ -131,6 +131,7 @@ protected:
void enable_display();
void disable_display();
void update_fb_ptr();
// HWComponent methods
int device_postinit();
+3 -3
View File
@@ -252,8 +252,8 @@ void Display::configure_dest() {
impl->dest_rect.w = std::round(scale * impl->display_w);
impl->dest_rect.h = std::round(scale * impl->display_h);
impl->dest_rect.x = std::round((impl->drawable_w - impl->dest_rect.w) / 2.0),
impl->dest_rect.y = std::round((impl->drawable_h - impl->dest_rect.h) / 2.0),
impl->dest_rect.x = std::round((impl->drawable_w - impl->dest_rect.w) / 2.0);
impl->dest_rect.y = std::round((impl->drawable_h - impl->dest_rect.h) / 2.0);
impl->renderer_scale_x = scale;
impl->renderer_scale_y = scale;
@@ -310,7 +310,7 @@ void Display::handle_events(const WindowEvent& wnd_event) {
case SDL_WINDOWEVENT_EXPOSED:
if (wnd_event.window_id == impl->disp_wnd_id) {
SDL_RenderPresent(impl->renderer);
video_ctrl->set_draw_fb();
}
break;
+47 -13
View File
@@ -126,18 +126,21 @@ void ValkyrieVideo::write(uint32_t rgn_start, uint32_t offset, uint32_t value, i
switch((offset >> this->reg_shift) & 0xFF) {
case Valkyrie::csr_mode:
if (value != this->mode) {
auto old_mode = this->mode;
{
uint8_t old_mode = this->mode;
if (value != old_mode) {
this->mode = value;
if ((value ^ old_mode) & 0x80) {
if (value & 0x80)
if (value & 0x80) { // is disabled
if (!(old_mode & 0x80)) // was enabled
this->disable_video_internal();
else
this->schedule_mode_switch();
}
else { // is enabled and was disabled or is enabled and mode changed
this->schedule_mode_switch();
}
}
LOG_F(INFO, "%s: mode reg set to 0x%X", this->name.c_str(), this->mode);
break;
}
case Valkyrie::csr_depth:
if (value != this->depth)
this->schedule_mode_switch();
@@ -189,11 +192,11 @@ void ValkyrieVideo::disable_video_internal() {
}
void ValkyrieVideo::schedule_mode_switch() {
if (this->mode_timer_id)
TimerManager::get_instance()->cancel_timer(this->mode_timer_id);
if (this->mode_timer.active)
TimerManager::get_instance()->cancel_timer(this->mode_timer);
this->mode_timer_id = TimerManager::get_instance()->add_oneshot_timer(
MSECS_TO_NSECS(3), [this] {
TimerManager::get_instance()->add_oneshot_timer(this->mode_timer,
MSECS_TO_NSECS(3), [this](uint64_t, uint64_t) {
this->enable_video_internal();
});
}
@@ -205,25 +208,56 @@ void ValkyrieVideo::enable_video_internal() {
this->pixel_clock = this->clk_gen->get_dot_freq();
// set video mode parameters
// MHz shown is calculated by get_dot_freq, not the ideal pixel clock.
switch(this->mode & 0x7F) {
case PdmVideoMode::Rgb13in:
case PdmVideoMode::Rgb12in: // 0x2: // 512x384 60 Hz 15.667200 MHz
new_width = 512;
new_height = 384;
hori_blank = 128;
vert_blank = 23;
break;
case PdmVideoMode::Rgb13in: // 0x6: // 640x480 67 Hz 30.215314 MHz
new_width = 640;
new_height = 480;
hori_blank = 224;
vert_blank = 45;
break;
case PdmVideoMode::Rgb16in:
case PdmVideoMode::Rgb16in: // 0x9: // 832x624 75 Hz 57.219340 MHz
new_width = 832;
new_height = 624;
hori_blank = 320;
vert_blank = 43;
break;
case PdmVideoMode::VGA:
case PdmVideoMode::VGA: // 0xB: // 640x480 60 Hz 25.203756 MHz
new_width = 640;
new_height = 480;
hori_blank = 160;
vert_blank = 45;
break;
case 0xC: // 800x600 60 Hz 39.880144 MHz
new_width = 800;
new_height = 600;
hori_blank = 256;
vert_blank = 28;
break;
case 0xD: // 800x600 72 Hz 49.850184 MHz
new_width = 800;
new_height = 600;
hori_blank = 240;
vert_blank = 66;
break;
case 0xE: // 1024x768 60 Hz 64.757760 MHz
new_width = 1024;
new_height = 768;
hori_blank = 320;
vert_blank = 38;
break;
case 0xF: // 1024x768 72 Hz 74.930088 MHz
new_width = 1024;
new_height = 768;
hori_blank = 304; // These blanking numbers are for 70 Hz, not 72 Hz.
vert_blank = 38; // There is no documentation for a 72 Hz mode?
break;
default:
LOG_F(ERROR, "%s: invalid video mode 0x%X", this->name.c_str(), this->mode & 0x7F);
return;
+1 -1
View File
@@ -101,7 +101,7 @@ private:
uint8_t *vram_ptr = nullptr;
int reg_shift = 3;
uint64_t mode_timer_id = 0;
TimerInfo mode_timer;
void disable_video_internal();
void enable_video_internal();
+26 -24
View File
@@ -101,40 +101,42 @@ void VideoCtrlBase::set_cursor_dirty() {
void VideoCtrlBase::start_refresh_task() {
this->display.configure(this->active_width, this->active_height);
uint64_t refresh_interval = static_cast<uint64_t>(1.0f / refresh_rate * NS_PER_SEC + 0.5);
this->refresh_task_id = TimerManager::get_instance()->add_cyclic_timer(
refresh_interval,
[this]() {
// assert VBL interrupt
this->vbl_cb(1);
this->update_screen();
}
);
if (vert_blank == 0) {
uint64_t refresh_interval = static_cast<uint64_t>(1.0f / this->refresh_rate * NS_PER_SEC + 0.5);
if (this->vert_blank == 0) {
LOG_F(ERROR, "Vertical blank is 0. Using 25 instead.");
vert_blank = 25;
this->vert_blank = 25;
}
uint64_t vbl_duration = static_cast<uint64_t>((double)hori_total * vert_blank / this->pixel_clock * NS_PER_SEC + 0.5);
this->vbl_end_task_id = TimerManager::get_instance()->add_cyclic_timer(
uint64_t vbl_duration = static_cast<uint64_t>((double)this->hori_total * this->vert_blank /
this->pixel_clock * NS_PER_SEC + 0.5);
TimerManager::get_instance()->add_cyclic_timer(
this->refresh_timer,
refresh_interval,
refresh_interval + vbl_duration,
[this]() {
// deassert VBL interrupt
this->vbl_cb(0);
[this, vbl_duration](uint64_t timeout_ns, uint64_t) {
this->vbl_cb(1); // assert VBL interrupt
if (this->vbl_end_timer.active) {
TimerManager::get_instance()->cancel_timer(this->vbl_end_timer);
}
TimerManager::get_instance()->add_absolute_timer(
this->vbl_end_timer,
timeout_ns + vbl_duration, 0,
[this](uint64_t, uint64_t) {
this->vbl_cb(0); // deassert VBL interrupt
}
);
this->update_screen();
}
);
}
void VideoCtrlBase::stop_refresh_task() {
if (this->refresh_task_id) {
TimerManager::get_instance()->cancel_timer(this->refresh_task_id);
this->refresh_task_id = 0;
if (this->refresh_timer.active) {
TimerManager::get_instance()->cancel_timer(this->refresh_timer);
}
if (this->vbl_end_task_id) {
TimerManager::get_instance()->cancel_timer(this->vbl_end_task_id);
this->vbl_end_task_id = 0;
if (this->vbl_end_timer.active) {
TimerManager::get_instance()->cancel_timer(this->vbl_end_timer);
}
}
+5 -4
View File
@@ -24,6 +24,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef VIDEO_CTRL_H
#define VIDEO_CTRL_H
#include <core/timermanager.h>
#include <devices/common/hwinterrupt.h>
#include <devices/video/display.h>
@@ -99,8 +100,8 @@ protected:
int vert_blank = 0;
int pixel_depth;
int pixel_format;
float pixel_clock;
float refresh_rate;
double pixel_clock; // float can represent all integers only up to 16 MHz
float refresh_rate = 0;
// Implementations may choose to track framebuffer writes and set draw_fb
// to false if updates can be skipped. If they do this, they should set
@@ -113,8 +114,8 @@ protected:
// Framebuffer parameters
uint8_t* fb_ptr = nullptr;
int fb_pitch = 0;
uint32_t refresh_task_id = 0;
uint32_t vbl_end_task_id = 0;
TimerInfo refresh_timer;
TimerInfo vbl_end_timer;
// interrupt suff
InterruptCtrl* int_ctrl = nullptr;
+2
View File
@@ -126,6 +126,8 @@ static const PropMap pm6400_settings = {
new IntProperty( 0, std::vector<uint32_t>({0, 4, 8, 16, 32}))},
{"hdd_config",
new StrProperty("Ide0:0")},
{"cdr_config",
new StrProperty("ScsiMesh:3")},
{"emmo",
new BinProperty(0)},
};
+2 -2
View File
@@ -63,7 +63,7 @@ int MachineBondi::initialize(const std::string &id) {
LOG_F(INFO, "Building machine Bondi...");
// get pointer to the memory controller/primary PCI bridge object
MPC106* grackle_obj = dynamic_cast<MPC106*>(gMachineObj->get_comp_by_name("Grackle"));
MPC106* grackle_obj = dynamic_cast<MPC106*>(gMachineObj->get_comp_by_name("GrackleBondi"));
grackle_obj->set_irq_map(grackle_irq_map);
MacIoTwo* mio_obj = dynamic_cast<MacIoTwo*>(gMachineObj->get_comp_by_name("Paddington"));
@@ -110,7 +110,7 @@ static const PropMap bondi_settings = {
};
static std::vector<std::string> bondi_devices = {
"Grackle", "BurgundySnd", "Paddington", "AtaHardDisk", "AtapiCdrom"};
"GrackleBondi", "BurgundySnd", "Paddington", "AtaHardDisk", "AtapiCdrom"};
static const DeviceDescription MachineBondi_descriptor = {
Machine::create<MachineBondi>, bondi_devices, bondi_settings
+11
View File
@@ -85,6 +85,15 @@ int MachineCatalyst::initialize(const std::string &id) {
return -1;
}
// Platinum uses the top 16 MB of the address space for ROM.
// The installed 4 MB ROM appears four times within that range.
for (uint32_t addr : {0xFF000000U, 0xFF400000U, 0xFF800000U}) {
if (!platinum_obj->add_mem_mirror(addr, 0xFFC00000)) {
LOG_F(ERROR, "Could not create ROM mirror!");
return -1;
}
}
// insert RAM DIMMs
platinum_obj->insert_ram_dimm(0, GET_INT_PROP("rambank1_size") * DRAM_CAP_1MB);
platinum_obj->insert_ram_dimm(1, GET_INT_PROP("rambank2_size") * DRAM_CAP_1MB);
@@ -123,6 +132,8 @@ static const PropMap pm7200_settings = {
new IntProperty( 0, std::vector<uint32_t>({0, 4, 8, 16, 32, 64, 128}))},
{"rambank4_size",
new IntProperty( 0, std::vector<uint32_t>({0, 4, 8, 16, 32, 64, 128}))},
{"cdr_config",
new StrProperty("ScsiCurio:3")},
{"emmo",
new BinProperty(0)},
{"cpu",
+2
View File
@@ -145,6 +145,8 @@ static const PropMap pm6500_settings = {
new IntProperty(32, std::vector<uint32_t>({ 4, 8, 16, 32, 64}))},
{"rambank2_size",
new IntProperty( 0, std::vector<uint32_t>({0, 4, 8, 16, 32, 64}))},
{"cdr_config",
new StrProperty("ScsiMesh:3")},
{"emmo",
new BinProperty(0)},
{"hdd_config",
+3 -3
View File
@@ -136,7 +136,7 @@ int MachineGossamer::initialize(const std::string &id) {
LOG_F(INFO, "Building machine Gossamer...");
// get pointer to the memory controller/PCI host bridge object
MPC106* grackle_obj = dynamic_cast<MPC106*>(gMachineObj->get_comp_by_name("Grackle"));
MPC106* grackle_obj = dynamic_cast<MPC106*>(gMachineObj->get_comp_by_name("GrackleGossamer"));
grackle_obj->set_irq_map(grackle_irq_map);
// configure the Gossamer system register
@@ -235,11 +235,11 @@ static const PropMap gossamer_tower_settings = {
};
static std::vector<std::string> pmg3_devices = {
"Grackle", "ScreamerSnd", "Heathrow", "AtaHardDisk", "AtapiCdrom"
"GrackleGossamer", "ScreamerSnd", "Heathrow", "AtaHardDisk", "AtapiCdrom"
};
static std::vector<std::string> pmg3twr_devices = {
"Grackle", "ScreamerSnd", "Heathrow", "AtaHardDisk", "AtapiCdrom"
"GrackleGossamer", "ScreamerSnd", "Heathrow", "AtaHardDisk", "AtapiCdrom"
};
static const DeviceDescription MachineGossamerDesktop_descriptor = {
+2
View File
@@ -158,6 +158,8 @@ static const PropMap pm6100_settings = {
new StrProperty("HiRes12-14in", PDMBuiltinMonitorIDs)},
{"pds",
new StrProperty("")},
{"cdr_config",
new StrProperty("ScsiCurio:3")},
{"emmo",
new BinProperty(0)},
};
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff. Show more