Compare commits

...
234 Commits
Author SHA1 Message Date
Mihai Parparita c6c48eff4b ppc: Model configurable CPU frequencies
Virtual time previously advanced by a fixed 16 ns per interpreted
instruction, making every CPU behave like the legacy 62.5 MHz model
regardless of the selected machine. G3 guests also received ad hoc HID1
values from individual machine implementations, while Gazelle supported
several frequencies that could not share that logic.

Require each machine to provide its hardware-appropriate bus, core, and
timebase clocks through one `PPC_CPU_Config` configuration object. We can then
derive things from it (e.g. supported MPC603ev and MPC750 HID1 PLL encodings).
We can also populate the `include_601` global based on `version` instead of a
separate flag.

To model time with more flexibility, we now use 60.4 fixed-point nanoseconds for
instruction timing. This lets us have a broad set of frequencies and still
support running the CPU for ~35 years of virtual time before it overflows.

This results in two emulation accuracy improvements:
- Tiger successfully gets to the Finder. The virtual time we were exposing to
  the guest was advancing too quickly, preventing loginwindow from connecting
  before WindowServer's internal five-second no-client timer expired.
  The server then exited normally,  loginwindow aborted when it could not
  establish its CoreGraphics connection, and we remained stuck at the last
  textual output from a verbose boot ("Waiting for IFC").
- Animations are now more accurate (e.g. Mac OS X dock icon bouncing is no
  longer too fast on a G3)
2026-08-13 20:27:34 -07:00
Mihai Parparita bb16a5de2a ati: Latch enabled display interrupts until acknowledged
More accurately model the VBL interrupt behavior of ATI chips. When VBL
begins, set the interrupt-pending bits and derive the PCI IRQ from each
pending bit and its matching enable bit. Keep the pending state and PCI IRQ
asserted until the guest driver acknowledges the event, even if VBL has
already ended.

The interrupt may therefore be asserted for less or more time than the
physical VBL interval, depending on when the guest acknowledges it.

This allows the driver to acknowledge the interrupt and resume other work
while VBL may still be active. Previously the PCI IRQ followed the entire
VBL interval, so it could remain asserted after the pending event had been
acknowledged.

Track the PCI IRQ output level and notify the interrupt controller only when
that level changes.
2026-08-11 22:16:52 -07:00
Mihai Parparita 72cf556a7c ati: Fix VBLANK status field updates
insert_bits expects its final argument to be the field width, but both ATI
VBL callbacks passed the current VBL state. When VBL ended, that meant
using zero as the width, so the update was a no-op. After the first vertical
blank began, the ATI_CRTC_VBLANK status bit was never cleared, confusing
guest code that polls the live VBL state.
2026-08-11 22:16:52 -07:00
joevt b3eb501277 main: Remove allow_windows_style_options. 2026-08-11 07:45:20 -07:00
joevt 14a352f497 hostevents_sdl: Add log off to Control-L hotkey. 2026-08-09 21:52:51 -07:00
joevt a432e44483 hostevents_sdl: Fix logging of keyboard state. 2026-08-09 21:38:08 -07:00
Aliceandjoevt 26b7566179 hostevents_sdl: Add icnt_factor and g_realtime shortcuts.
Added controls to increment/decrement icnt_factor and toggle g_realtime
for testing and debugging purposes.
Control Alt Shift = -> increment_icnt_factor();
Control Alt Shift - -> decrement_icnt_factor();
Control Alt r -> toggle_g_realtime();

Co-Authored-By: joevt <[email protected]>
2026-08-09 21:28:22 -07:00
joevt b7fa82ab92 hostevents_sdl: Fix comment spacing. 2026-08-09 21:13:08 -07:00
joevt a3b248ea3d ppcemu: Use ppc_off_reason setter.
Makes things slightly cleaner and helps debugging. Changes to
ppc_off_reason can be logged.
2026-08-09 21:04:04 -07:00
joevt db5ab5f63c display_sdl: Make auto grab mouse optional.
Add a command line option to enable auto grab.
Default to the previous behavior before the auto grab feature was added.

Add a debugger command to enable or disable auto grab.

Notes:
Auto grab mouse currently only works for graphics controllers and guest
OSs that use a hardware cursor and only if the emulation sets
cursor_dirty to true (i.e. not emulation that uses cursor_ovl_cb).
2026-08-09 21:01:00 -07:00
Maxim Poliakovski d542d9ef96 scsicdromcmds: move page handler 0x31 to the end of the source. 2026-08-09 20:17:15 +02:00
dingusdev 472f130e44 Tweak the manual
Suits current changes
2026-08-09 08:08:44 -07:00
joevt aa2f8c2664 main: Move setenv option to emulation commands. 2026-08-09 08:07:00 -07:00
joevt fdef70cddd main: Rename --realtime to --run.
Because it has nothing to do with timing.
2026-08-09 08:06:51 -07:00
joevt 1082a0c029 main: CLI11 changes.
Add --help-all option.
Move emulation options to an empty named subcommand.
Show defaults for --workingdir and --bootrom.
If --bootrom is not specified then validate the default.
2026-08-08 17:05:23 -07:00
probonopd 0f4957cbf4 display: show mouse grab state and shortcut in the window title
The window title now reflects whether the mouse is grabbed and how to toggle
it, so the user knows how to release the automatic grab and move the pointer
to other windows, or how to re-grab it.
2026-08-08 15:29:05 -07:00
probonopd f78f05f53b display: auto-grab the mouse when the guest draws its own cursor
While a guest cursor is drawn, the host mouse is now grabbed automatically
so the guest cursor can reach every screen area and the host pointer cannot
wander off the window. The grab is released again when the guest cursor
disappears, and re-established when the window regains focus, because SDL
may drop the grab on focus loss. A manual grab with Ctrl+G is sticky and
overrides the automatic behavior.
2026-08-08 15:29:05 -07:00
probonopd 6dd8b31b51 display: hide the SDL host pointer when the guest draws its own cursor
When the guest OS draws a hardware cursor into the framebuffer, the SDL
host pointer was still shown on top, so the user saw two cursors that did
not track each other. Hide the host pointer while a guest cursor is drawn
and show it again otherwise, so the user can aim the mouse at the window
when no guest cursor is present.
2026-08-08 15:29:05 -07:00
probonopd ed94cd2459 scsicdrom: Register Apple features mode page (0x31) for ATAPI CD-ROM
Move the Page 0x31 getter from ScsiCdrom into ScsiCdromCmds so it is also
registered for the ATAPI CD-ROM, which Mac OS queries via MODE_SENSE.
2026-08-08 14:33:39 -07:00
probonopd 0f168677b2 atapibasedevice: Clear BSY and signal interrupt on unsupported ATA command
The default case in perform_command() set the ABRT/ERR flags but left BSY
asserted and never fired the interrupt. Open Firmware therefore hung
waiting on the ATAPI CD-ROM after issuing commands it does not support
(e.g. 0xEC IDENTIFY_DEVICE during the boot device probe).
2026-08-08 14:33:39 -07:00
Mihai Parparita d5f607e50f core: mark non-mutating methods as const 2026-08-08 12:49:12 -07:00
joevt 834006d311 dbdma: Fix STORE_QUAD and LOAD_QUAD. 2026-08-08 06:51:03 -07:00
Mihai Parparita 8f6274ed8a ppcmmu: Ignore dcbz for MMIO regions
The ATI drivers uses dcbz to simulate a write-combining buffer when
sending HOST_DATA payloads.

The intent is something like this (on real hardware):

```
dcbz:
    cache line = [0, 0, 0, 0, 0, 0, 0, 0]
    ATI sees nothing

following stores:
    cache line = [A, B, C, D, E, F, G, H]
    ATI still sees nothing

dcbf or eviction:
    write back [A, B, C, D, E, F, G, H]
    ATI receives one completed cache line
```

With our previous cacheless implementation, the behavior was more like this:
```
dcbz:
    ATI immediately receives [0, 0, 0, 0, 0, 0, 0, 0]

following stores:
    ATI then receives [A, B, C, D, E, F, G, H]

dcbf:
    no-op
```

The zero-ed out values have side effects (32 pixels of black being
written), so the intermediate state was visible.

The truly correct fix is to fully model the data cache, and do an
eventual write back of the modified cache lines with their final values,
but that is very invasive (and likely to be slow).

We instead just make `dcbz` a no-op for MMIO regions, which lets us
avoid that intermediate state and unintended side effects.
2026-08-08 06:46:01 -07:00
Mihai Parparita e2a28ec287 atirage: Handle SGRAM color register blits
The Mac OS 8.6 driver enables color-register writes without enabling
block writes to update SGRAM state. Treat that command as a
register-only operation instead of sending it through the VRAM blitter,
while retaining the documented destination tiling side effects.

This prevents the command from producing stray pixels near the menu
bar and Control Strip.

References:
- ATI 3D Rage LT Pro Register Reference Guide, pp. 5-21--5-24.
- ATI Rage Pro and Derivatives Programmer's Guide, pp. 6-11--6-19.
2026-08-07 08:05:42 -07:00
Mihai Parparita 5c5faa626e atirage: Support general-pattern source blits
Mac OS 8.6 uses general and rotated source trajectories when drawing
Finder icons and the Control Strip. Preserve both source size/start
composites and repeat their first and second rectangles according to
SRC_CNTL.

Use the documented signed source coordinates and inclusive scissors
while advancing the source for clipped destination pixels. Unbounded
blits continue to use the existing linear trajectory.

References:
- ATI 3D Rage LT Pro Register Reference Guide, pp. 5-21--5-31 and
  5-39--5-42.
- ATI Rage Pro and Derivatives Programmer's Guide, pp. 6-11--6-19,
  6-31--6-33, and 6-42.
2026-08-07 08:05:42 -07:00
Mihai Parparita 1e4014739c atirage: Support solid and color host rectangle fills
Mac OS 8.6 programs GUI_TRAJ_CNTL to set draw-engine direction and
issues fills through several destination register initiators. Model the
composite register, destination initiators, signed inclusive scissors,
tiling side effects, and Always_1 source selection.

Accept source mix 7 independently of the unused background mix for
solid fills, and consume 8-bit HOST_DATA writes in trajectory order.
This lets the desktop paint and prevents host uploads from being
reversed or clipped.

References:
- ATI 3D Rage LT Pro Register Reference Guide, pp. 5-8--5-12,
  5-33, 5-39--5-42, 5-47--5-51, 5-58, and 5-64--5-65.
- ATI Rage Pro and Derivatives Programmer's Guide, pp. 6-5,
  6-11--6-19, and 6-27--6-29.
2026-08-07 08:05:42 -07:00
joevt eade7a0a30 ppcmmu: Fix indenting. 2026-08-07 06:47:41 -07:00
joevt 9fb34efcf3 soundserver_cubeb: Don't use get_pull_data_remaining.
Just pull data until the DMA buffer is empty.
2026-08-06 20:38:40 -07:00
joevt d3dfbc05ca soundserver_cubeb: Use enum name for pull_data. 2026-08-06 20:38:32 -07:00
Mihai Parparita abf20ce712 Allow different levels of determinism (#201)
Add an "interactive" mode that allows user input, but still disables
hard drive and PRAM persistence.
2026-08-06 19:03:48 -07:00
joevt 90b3119b8f dbdma: Use update_cmd for flush also. 2026-08-06 07:47:26 -07:00
Mihai Parparita 2c7a7c5c36 ppcmmu: Use generational flush for PAT entries
We end up flushing all entries very frequently (hundreds of thousands of times
during Mac OS X boot), and were spending a lot of time in `tlb_flush_entries`
walking through the array. We can instead store a generation counter and
make invalidation be a simple increment. This does make validity checks slightly
more expensive, but it appears to be a net win. On my machine it takes booting
the Mac OS X public meta to the Finder from ~58 seconds to ~35 seconds.
2026-08-06 07:33:54 -07:00
Mihai Parparita 1b0ac89674 ppcmmu: Move TLB internals into implementation
`TLBEntry` and its cache constants and flags are used exclusively by
ppcmmu.cpp. Keep them out of the public MMU header so future TLB changes
do not expand its interface.

This required a small fix in dbdma.cpp since it was implicitly relying on
an include that we removed.

Also declare `gTLBFlush*` variables as static to make it explicit that we
don't expect them to be accessed outside of ppcmmu.cpp.
2026-08-06 07:33:54 -07:00
joevt 577ddb28a9 dbdma: Add update_cmd. 2026-08-05 19:39:27 -07:00
joevt 49cc164a11 dbdma: Add comment. 2026-08-05 19:38:34 -07:00
dingusdev 0df52ad451 Workflows - Use MSVC instead of MSYS2 for Windows 2026-08-05 19:28:45 -07:00
Mihai Parparita 45ea0103ed dbdma: update xferStatus and resCount when handling FLUSH command (#198)
Per the DBDMA spec (section 15.4.3), this is required. Fixes a hang
when booting 9.0 and 9.0.4 on the Beige G3 (they would get stuck in a
loop polling the `xferStatus.active` field).
2026-08-05 18:43:52 -07:00
Mihai Parparita 172efccd1b cpu: remove unused global variables (#197)
Last glob_bb_start_la use was removed in d83fdd8866.

Last last_read_area, last_write_area, and last_exec_area uses were removed
in c9d4cc3321.
2026-08-05 18:43:25 -07:00
joevt 21324e200f burgundy: Implement AWAC_FRAME_COUNT.
Just count frame times using virtual time.
Should probably use real time since audio doesn't use virtual time.
2026-08-04 19:11:54 -07:00
joevt 51e5c95a1b burgundy: Implement AWAC_SOUND_CTRL_REG.
Placeholder for now.
2026-08-04 19:02:09 -07:00
joevt 24fad9fec7 burgundy: Rename value variable.
Read and Write should use the same variable name for the value.
2026-08-04 19:01:48 -07:00
dingusdev 10015af36d Merge pull request #195 from mihaip/upstream-fix-boot
atapicdrom: fix spurious reads during Mac OS boot
2026-08-03 22:23:39 -07:00
Mihai Parparita 4055dd07c4 atapicdrom: fix spurious reads during Mac OS boot
Fixes a couple of regressions after the generic SCSI command refactor:
- `not_ready_reason` was missing an override, so we were not actually returning
  `MEDIUM_NOT_PRESENT`
- `status_good()` was unconditionally called before every command, including for
  `REQ_SENSE`. It cleared `sense_key`, thus we were not returning the correct
   state back.
2026-08-03 22:18:42 -07:00
Maxim Poliakovski 6f86021ae6 atapicdrom: add missing check for being ready. 2026-08-04 03:33:04 +02:00
dingusdev c916954187 Add missing VX and FEX updates 2026-08-01 11:32:07 -07:00
Maxim Poliakovski 23de8c1c08 scsicdromcmds: reimplement SET_CD_SPEED.
Also remove the corresponding stub from atapicdrom.cpp
2026-07-31 02:40:05 +02:00
Maxim Poliakovski 94e0691caa scsi*cmds: undo temporary renames. 2026-07-31 01:21:20 +02:00
Maxim Poliakovski 958bd0f8e6 cdromdrive: remove implementations of SCSI commands.
This source should contain anything related to
the physical properties of a CD/DVD drive like
mechanical capabilities, formats supported as well as
handling of the underlying images.
2026-07-31 01:08:03 +02:00
Maxim Poliakovski b2bd9efbaa atapicdrom: use generic MODE_SENSE_x implementation. 2026-07-31 00:54:23 +02:00
Maxim Poliakovski 99ce46d510 scsicdromcmds: implement CD-ROM audio control page. 2026-07-31 00:38:39 +02:00
Maxim Poliakovski 78c438884c scsiphysinterface: rename set_eject_state to set_lock_state. 2026-07-30 23:56:16 +02:00
Maxim Poliakovski 87633e7fdf scsicdromcmds: add CD capabilities and mechanical status page. 2026-07-30 23:00:44 +02:00
Maxim Poliakovski 57d97370f1 cdromdrive: add mechanical properties and capabilities. 2026-07-30 23:00:25 +02:00
Maxim Poliakovski 045e6d9d7f atapicdrom: use generic SCSI commands, part 1. 2026-07-30 18:47:32 +02:00
Maxim Poliakovski 90b53a61ad atapibasedevice: implement ATAPI PHY for ScsiPhysInterface.
This permits reusing of generic SCSI commands that
don't contain anything related to the particular
physical layer.
2026-07-30 13:55:12 +02:00
dingusdev 7658707bd3 Add missing return statements 2026-07-29 18:49:54 -07:00
Maxim Poliakovski aad05628ea scsiphysinterface: add sense_key to set_status().
SCSI devices don't need that because it's usually stored
internally and returned during REQUEST SENSE command.
On the contrary, ATAPI devices always report sense key
in the upper bits of the error register.
2026-07-30 01:27:45 +02:00
Maxim Poliakovski 520518f2ac scsiblockcmds: improve a couple of logging messages. 2026-07-30 01:27:26 +02:00
joevt f5dbb4fa43 macio: Add more names for feature control bits. 2026-07-24 20:58:21 -07:00
dingusdev 79f1edc102 Adding additional regs in AMIC 2026-07-24 20:58:04 -07:00
Tim Jarzombekandjoevt 3ecf59233c amic: Make RcvDma fields unique_ptr like XmitDma.
From earlier commit:
"amic: Emulate SCC receive DMA registers instead of returning random
values."

Co-Authored-By: joevt <[email protected]>
2026-07-24 07:44:02 -07:00
joevt baeed79f12 amic: Add all the SCC DMA registers. 2026-07-23 20:56:53 -07:00
dingusdev f1c46cdc6d Last minute typo fixes 2026-07-24 00:32:06 +02:00
joevt 0779a171e0 scsi.h: add more defs to ScsiMessage and ScsiExtMessage. 2026-07-24 00:32:06 +02:00
Maxim Poliakovski b9e94b20b4 Revert "Appending ATA device identification stub"
ATAPI devices should NOT implement ATA IDENTIFY DRIVE
command (ECh) to avoid their false identification as ATA
drives. They should implement ATAPI IDENTIFY DEVICE
command (A1h) instead.

This reverts commit da7c8a4579.
2026-07-18 17:03:23 +02:00
joevt fd9899ae87 dbdma: xfer_quad improvements and fixes.
- Make the method call less confusing.
  - Use cur_host instead of passing cmd_struct.
  - Pass a boolean to differentiate LOAD_QUAD and STORE_QUAD.
- Use xfer_size instead of req_count for res_count.
- Don't LOAD_QUAD to read-only DBDMA command.
2026-07-15 07:52:16 -07:00
joevt ff911cc056 dbdma: Add is_active to more methods. 2026-07-15 07:11:18 -07:00
joevt 7af1235b8e dbdma: Flush only applies to INPUT commands. 2026-07-14 20:25:11 -07:00
joevt 06ea4a844e dbdma: Add is_active. 2026-07-14 20:23:41 -07:00
joevt 813350f14a dbdma: Remove superfluous update_irq method. 2026-07-14 19:57:37 -07:00
joevt 4bcd96e6b1 dbdma: Save current dbdma cmd host address.
Use the saved address for finish_cmd.
2026-07-14 19:24:03 -07:00
joevt 83775309e9 dbdma: Set res_count at beginning of command.
Don't need to reset it at the end of a command.
2026-07-14 18:52:22 -07:00
joevt 2a3b6d9cb7 dmacore: Rename is_ready.
So that it is not confused with other contexts.
2026-07-14 18:48:10 -07:00
joevt 538970d659 openfirmware.md: Add note about PCI2 PRSNT bits. 2026-07-14 18:45:38 -07:00
joevt fce52eacfb dbdma: Remove interpret_cmd result. 2026-07-14 07:59:22 -07:00
dingusdev a832d9cf90 Version 1.04b Prep 2026-07-13 10:37:28 -07:00
dingusdev e5b8ff49e4 Restore clearing CH_STAT_FLUSH
This is still required so that the MacTest Pro (Nov. 99) CD can boot up.
2026-07-13 08:30:35 -07:00
dingusdev 5e7c660622 Merge pull request #193 from mihaip/upstream-ati-blit
atirage: Implement source rectangle blitting
2026-07-13 07:39:51 -07:00
Mihai Parparita d9d7257d46 atirage: Also set the draw_fb flag for fill_rect
Happened to notice that we were not marking the framebuffer as dirty
when doing this update. Liekly not an issue in practice since there are
usually other updates, but might as well be correct.
2026-07-12 22:42:17 -07:00
Mihai Parparita 8cecc9b20b atirage: Implement source rectangle blitting
Implement the accelerated same-format source-copy operation (used by the
Mac OS X Public Beta when dragging windows).

Supports raw 8, 15, 16, and 32 bpp copies. Rejects unsupported mixes,
format conversions, partial write masks, color comparison, and source
trajectory modes.
2026-07-12 22:41:30 -07:00
dingusdev 42e617fde9 Merge pull request #192 from mihaip/upstream-ata-dma-take2
ata: Implement DMA transfers
2026-07-11 17:52:36 -07:00
Mihai Parparita 017a4a48b1 atahd: Implement hard disk DMA commands
Add read/write DMA command support to ATA hard disks (can mostly reuse the PIO paths).
2026-07-11 17:45:41 -07:00
Mihai Parparita bf1c9654c4 ata: Implement reusable DMA data transfers
Implement push_data in AtaBaseDevice using the device transfer buffer and
post-transfer callback.

Advance the read data pointer across DMA pulls so a transfer can span
multiple DBDMA descriptors, and clear the DMA state when transfers finish.
2026-07-11 17:44:48 -07:00
dingusdev 6c48fc1f91 BigMac: Typo squatting 2026-07-10 19:58:56 -07:00
joevt e259d8e2b2 machinealchemy: fix box id & emmo. 2026-07-08 14:39:34 +02:00
joevt 3d25cc592d machinegazelle: fix box id & emmo. 2026-07-08 14:17:08 +02:00
dingusdev da7c8a4579 Appending ATA device identification stub 2026-07-07 20:11:22 -07:00
Maxim Poliakovski bf2f7e5217 machinetnt: fix IOBus address for Board register 2.
Also file a bug in Open Firmware 1.0.5 that reads
PCI2 PRSNT bits from wrong location.
2026-07-08 04:05:54 +02:00
Maxim Poliakovski 5f49182c5b atapibasedevice: update two log messages. 2026-07-08 00:26:32 +02:00
joevt d4cb1fe872 machinegazelle: Add pm5500 and tam machines. 2026-07-07 17:01:35 +02:00
Maxim Poliakovski f8a2b19947 machinealchemy: activate factory tests if requested.
Please note that factory tests don't work
out of the box in Alchemy due to a bug in POST.
You need to patch the ROM first.
2026-07-07 13:50:22 +02:00
Maxim Poliakovski 2db1cc160e machinegossamer: activate factory tests if requested. 2026-07-07 13:50:22 +02:00
Maxim Poliakovski b81920fcb2 maciotwo: remove everything related to EMMO.
EMMO should be activated in the particular machine expert
because the location of that bit is board specific.
2026-07-07 13:38:52 +02:00
Mihai Parparita 01eb1356f5 utils: Use mmap for disk images in deterministic mode (#190)
We were reading the entire disk image into a stringstream for
deterministic mode, which is slow and memory-intensive. Instead on POSIX
hosts we can use `mmap` to lazily map the disk image into memory, allowing
it to be streamed in as the guest actually needs data from it.

Helps with iteration speed when debugging via deterministic mode.
2026-07-07 11:06:55 +02:00
Mihai Parparita f964359738 ata: Demote split DMA pull diagnostic
Mac OS X Public Beta commonly drives one ATA DMA transfer through
multiple DBDMA descriptors, so a single ATA pull can be smaller or larger
than the current descriptor request without indicating an error.

Reduce the logging level to avoid logspam during boot.
2026-07-07 11:06:55 +02:00
Mihai Parparita 36420c55b9 dbdma: Report residual descriptor byte counts
We were treating resCount as a "result" count, but it's actually a "residual"
count that reports how many bytes from a descriptor were not transferred
when processing a command. We now correctly handle partial descriptors.

This ended up being necessary for the 10.0 public beta bringup too (the
`AppleUltra66ATA::stopDma` implementation in xnu-103 computes the number
of bytes transferred by subtracting `resCount` from `reqCount`).
2026-07-07 11:06:55 +02:00
dingusdev aef197841b Remove SNAN checks from FABS, FNABS, and FNEG
None of these checks are required
2026-07-05 18:47:37 -07:00
Maxim Poliakovski e557bc1709 atirage: support non-32bpp rectangle fills.
Factored out of efa9d1c4c2984900f8d513abface0dc25c883d31

This is a temporary solution until the full drawing engine
is implemented.
2026-07-05 12:37:18 +02:00
Mihai Parparita 6a53025df9 atimach64defs.h: add enum for internal pixel formats.
Replace raw numbers in atirage.cpp with the appropriate
constants.
2026-07-05 12:26:09 +02:00
Maxim Poliakovski 9e70b3ce3f macio.h: remove board specific definitions. 2026-07-04 23:35:12 +02:00
Maxim Poliakovski 398ab2f7f6 maciobase: common support for IOBus devices. 2026-07-04 18:21:41 +02:00
Mihai Parparita c5d24e98a3 ppcexec: Respect CPU-specific POW behavior (#188)
Followup to #186 - select `MSR[POW]` handling mode once during CPU
initialization instead of treating every processor as `HID0`-gated.

We match documented (and QEMU) behavior:
- 603/7xx CPUs require `HID0` doze, nap, or sleep bits before we enter
  the emulator sleep loop
- 604-family CPUs use just for `POW` directly
- 601 does not support `POW` at all
2026-07-03 18:13:10 -07:00
joevt 37da4d3162 dmacore: Add DmaPushResult. 2026-07-02 08:10:04 -07:00
joevt 3e9397c478 dbdma: Set queue_len after all other fields.
If queue_len is a flag to determine when data is queued, then it
probably should be set last so that the other fields are valid when
another thread decides to act on the queued data.
2026-07-02 08:07:54 -07:00
joevt 3daa2b73d1 sc53c94: Remove obselete DMA stuff. 2026-07-02 07:52:29 -07:00
Mihai Parparita 79a06c55a4 ppcexec: Emulate PowerPC sleep on MSR POW (#186)
xnu-123.5 and similar vintage kernls enter the PowerPC 750 powersave mode
when the scheduler has no runnable work. `machine_idle_ppc` selects HID0
doze or nap, records a nap timestamp, then executes mtmsr with MSR[POW]
set. It stays in a loop there (in case the power saving had no effect
immediately) - it expects execution to resume at the `machine_idle_ret`
label (when an interrupt occurs), which ends up returning from the
function.

We model this state explicitly:
- When mtmsr sets MSR[POW] with the HID0 doze/nap/sleep flags, set a new
  EXEF_SLEEP flag.
- When EXEF_SLEEP is set, keep processing host events without advancing
  the guest PC.

Towards getting the 10.0 public beta to boot (#154) - before this we
would enter the DPPC debugger shortly after this instruction (due to a
bogus MSR LE flag eventually being set). Now we make more progress and
end up in a "Still waiting for root device" loop (presumably something
at the ATA layer)
2026-07-02 06:59:43 -07:00
Maxim Poliakovski 9561edcea2 sc53c94: remove obsolete DMA code. 2026-07-01 19:56:15 +02:00
Maxim Poliakovski ba34d78a7c grandcentral: fix interrupt clearing.
Fix an issue introduced in 4d9f6f33ee
2026-07-01 19:56:15 +02:00
dingusdev ecf8e4f1e1 Fix AWACS Codec Ctrl
Fixed enough to where the test in MacTech Pro passes
2026-07-01 07:33:17 -07:00
Maxim Poliakovski 2c2ad48a22 machinegazelle: configure PSX. 2026-06-27 12:33:45 +02:00
dingusdev 8d1d22416a Further FPU fixes
Now only 472 floating point tests fail
2026-06-26 22:24:48 -07:00
dingusdev 103a06536c Small PPC Floating-Point fixes 2026-06-26 07:44:38 -07:00
Maxim Poliakovski f1472e6f0e Add Alchemy machines emulation. 2026-06-22 23:38:21 +02:00
Maxim Poliakovski 4d9f6f33ee maciotwo: support partial writes to the control registers. 2026-06-21 22:14:09 +02:00
Maxim Poliakovski d8aa33f207 macio.h: add definition for Entry Systems Support register.
Rename and document MIO_AUX_CTL register as well.
2026-06-21 13:45:36 +02:00
Maxim Poliakovski 293f594cdc maciotwo: support partial/spanning reads from control registers. 2026-06-21 02:28:25 +02:00
dingusdev f3a5e48216 Fixed a slight message in compile message 2026-06-18 21:43:23 -07:00
joevt dd5ba1dcfc dbdma: Fix setting of gp channel control bits. 2026-06-18 20:06:44 -07:00
joevt d3483523d6 dbdma: Fix spelling. 2026-06-18 20:06:35 -07:00
joevt 67418b07b0 dbdma: Maintain and report res_count. 2026-06-18 20:06:12 -07:00
joevt cbe840ff3f dbdma: Set flush status when doing flush command. 2026-06-18 19:43:52 -07:00
joevt 290c575503 dbdma: Fix indenting of flush handler. 2026-06-18 19:43:30 -07:00
dingusdev 19c9266bbe MSVC compilation fix for Benchmark
Temp solution
2026-06-18 07:56:12 -07:00
joevt 811951ab91 memctrlbase: Add enums for larger DIMMs. 2026-06-17 07:03:21 -07:00
joevt a3c6d25cc5 grandcentral: Improve IOBus device 3/5 comments. 2026-06-17 07:02:12 -07:00
dingusdev 3ae509f83d More Cmake fixing 2026-06-16 21:27:15 -07:00
dingusdev 44fa69be65 CMake Workflows fix 2026-06-16 21:09:40 -07:00
Maxim Poliakovski 0a3277b286 psx: add setters for sys_id and bus_speed. 2026-06-16 13:38:10 +02:00
joevt b2660e2920 memaccess: Check compile time endianness. 2026-06-10 18:47:58 -07:00
Maxim Poliakovski 92bb6d1054 display.h: use existing macros instead of code duplication. 2026-06-08 13:02:21 +02:00
Maxim Poliakovski 619acb0109 memaccess.h: add read/write macros for native-endian DWORDs. 2026-06-08 13:02:21 +02:00
Maxim Poliakovski 0e2ffa7863 Move endianswap.h to core/* 2026-06-07 21:10:51 +02:00
Maxim Poliakovski 0e03cac082 Move memaccess.h to core/* 2026-06-07 20:32:46 +02:00
joevt 8f3f7cfe70 display: Add separate accessors for dest fb.
The destination framebuffer may be little endian or big endian.
For SDL2, the destination framebuffer's endianness matches the host's
CPU endianness.
2026-06-06 07:47:35 -07:00
joevt e70ab21787 machinefactory: Make a faster adler32. 2026-06-06 07:35:12 -07:00
joevt da7d2f9a92 romidentity: Separate New World product families. 2026-06-06 07:24:15 -07:00
joevt d2950ae319 romidentity: Add PowerBook 5300. 2026-06-06 07:23:24 -07:00
joevt 0e589ce1f6 debugger: Schedule viaint in ppc exec loop. 2026-06-05 19:23:23 -07:00
joevt 2f9c2408b2 pcicardbusbridge: Add PC Card specific BARs. 2026-06-04 19:04:40 -07:00
joevt 375749c48a dec21154: Add FWDET notes. 2026-06-04 19:02:01 -07:00
joevt fdb17a014b dec21154: Add more GPIO handling. 2026-06-04 19:00:37 -07:00
joevt c5a9f949c9 dec21154: Fix pserr_event_dis write.
Only the middle six bits are writable.
2026-06-04 19:00:31 -07:00
joevt 54a1eb49f7 ppcmmu: Add a debug version of mmu_map_dma_mem.
This is for the DPPC debugger, not for debugging DPPC.
2026-06-02 20:34:26 -07:00
joevt b665629168 ppcemu: Remove unused timebase_counter global. 2026-06-02 20:33:55 -07:00
Natalia Portillo 6407f1a566 main.cpp: change log verbosity flag from add_flag to add_option for better clarity 2026-06-02 19:19:25 -07:00
joevt 5abd37530d machinegossamer: Add system register comments. 2026-06-01 20:26:21 -07:00
Maxim Poliakovski 0f14a075cc dbdma: fix pausing/resuming of channel execution.
Suspend execution only if the ACTIVE bit is set.
Resume execution only if the channel was previously suspended.
2026-06-02 02:47:47 +02:00
joevt fcc912e1a8 romidentity: Note PowerBook5,9 ROM variant. 2026-06-01 08:09:25 -07:00
joevt d94c30a743 romidentity: Fix PowerMac11,2 description. 2026-06-01 08:04:44 -07:00
Nat Portillo 14b17a6e25 Fix SuperDrive behaviour when there is no disk in. (#182) 2026-05-31 20:58:13 -07:00
Maxim Poliakovski b291c28b35 atahd: implement stub for IDLE IMMEDIATE.
Mac OS 9.0.4 sometimes expects this command to be implemented.
2026-05-30 00:34:06 +02:00
Maxim Poliakovski 3f16b18bbd atadefs.h: add IDLE IMMEDIATE command code. 2026-05-30 00:34:06 +02:00
Maxim Poliakovski b63b658343 escc: remove old DMA implementation. 2026-05-29 23:36:24 +02:00
Maxim Poliakovski a68bd5b07e escc: switch to new DMA API. 2026-05-29 23:36:24 +02:00
Maxim Poliakovski 767811b952 dbdma: send notification messages to devices. 2026-05-29 23:36:24 +02:00
Maxim Poliakovski 30d95e1409 dmacore: add support for several channels per device. 2026-05-29 23:22:16 +02:00
Maxim Poliakovski 4138074789 dbdma: rewrite CH_STAT update logic. 2026-05-29 23:16:07 +02:00
Maxim Poliakovski 41f4af948f grandcentral: implement DMA interrupt clearing. 2026-05-29 21:22:56 +02:00
Maxim Poliakovski e4acb57429 escc: improve a couple of logging statements. 2026-05-29 19:41:11 +02:00
Maxim Poliakovski 745f5c85a9 dmacore.h: extend definitions and rename DMA messages. 2026-05-29 18:52:43 +02:00
Maxim Poliakovski 60825ce664 maciotwo: add dispatchers for the ESCC A DMA channels. 2026-05-29 18:14:08 +02:00
Maxim Poliakovski ee1b1dd873 maciotwo: clear DMA interrupt flags. 2026-05-29 17:48:55 +02:00
Maxim Poliakovski 3c1308d006 maciobase: implement DMA interrupt clearing. 2026-05-29 17:21:08 +02:00
joevt c28408fd80 scsi: Semicolon instead of comma. 2026-05-29 06:58:24 -07:00
joevt 3367db4494 scsi: Fix spelling of IS_TARGET_ROUTINE_NUMBER. 2026-05-29 06:52:05 -07:00
joevt ff8e98c26c mace: Fix name of datasheet. 2026-05-29 06:51:53 -07:00
joevt fe80d14e8a ppcmmu: uintptr_t (not size_t) for host pointers. 2026-05-29 06:51:32 -07:00
joevt a8dfc8d15c grandcentral: Decode entire DMA range.
Only DMA channels 0..0xA actually exist, but the range extends to 0x7F.
2026-05-27 06:43:40 -07:00
Maxim Poliakovski 0f4b4c0f67 dbdma.cpp: fix CommandPtrLo update.
Some Apple docs state that the CommandPtrLo can be written
if both the run and active bits are cleared.
Later docs say that only the active bit needs to be cleared.
Fix the code to conform to the logic of the latter.
2026-05-18 22:01:41 +02:00
Maxim Poliakovski 3f6f05694f maciotwo: add dispatchers for the ESCC B DMA channels. 2026-05-18 14:14:58 +02:00
Maxim Poliakovski cfde7ee045 escc: implement LTPC registers and logic.
LTPC aka LocalTalk Patch Chip or LocalTalk Protocol Controller
is a HW extension to the ESCC cell in a MacIO chip that is able
to detect the Abort sequence or End-Of-Packet specified in the
LocalTalk protocol.
This extension aims at reducing busy-waiting in SW.
2026-05-18 02:01:55 +02:00
Maxim Poliakovski c8ae8e7407 dbdma.h: add update_ch_stat() method. 2026-05-18 01:50:45 +02:00
Maxim Poliakovski 73e9a72f3d z85c30.h: reformat register descriptions. 2026-05-18 01:42:39 +02:00
Maxim Poliakovski ad9a9dbf80 escc: set SYNC/HUNT bit when SDLC mode is enabled.
The SYNC/HUNT bit in RR0 is set when the SDLC mode is enabled
and the receiver is disabled. Failing to do that will cause
the LocalTalk driver to wait forever for the line to become
ready for transmission.
2026-05-18 01:42:39 +02:00
Maxim Poliakovski ab1f9c59bc dbdma: fix endianness for STORE_QUAD targeting MMIO. 2026-05-16 00:13:16 +02:00
Stefanos Stefanidis 7e8526aa52 Implement ATA command 0xE5. (#179)
* Implement ATA command 0xE5.

* Correct a typo.
2026-05-14 20:15:47 -07:00
joevt 240f9e194e scsihd: Remove 8 GiB limit. 2026-05-12 07:10:15 -07:00
joevt 5a6a8fb26f sc53c94: Make read method use single return path.
Calculate the value that is read which will be used for logging later.
2026-05-12 07:08:58 -07:00
Maxim Poliakovski 2a85161b3a atahd: implement SEEK command.
Drive Setup 1.1 fails to recognize drives
that don't  support SEEK.
2026-05-03 19:02:11 +02:00
Maxim Poliakovski 3ab8e5c213 scsibusctrl: de-assert REQ between STATUS and MESSAGE IN.
REQ is checked after the MESH Status command by the
native SCSI Manager 4.3. If it's asserted the emulation
will hang.
2026-05-03 17:43:05 +02:00
Maxim Poliakovski 1b3a6b062c maciotwo: prevent logging when writing to MIO_INT_LEVELS1. 2026-05-03 14:59:04 +02:00
Maxim Poliakovski f0bb36b9da maciotwo: add Valkyrie interrupt registration. 2026-05-03 13:40:40 +02:00
Maxim Poliakovski c385b131d7 macio.h: remove documentation comment.
It has already been moved to zdocs/developers/heathrow.md
2026-05-03 13:07:12 +02:00
dingusdev 4bfb352b63 Add missing include in imgfile 2026-05-02 19:29:34 -07:00
Maxim Poliakovski b50a04fc79 Initial Valkyrie video controller emulation. 2026-05-03 03:25:58 +02:00
dingusdev dbcdbe7eb3 Start rules against AI 2026-04-20 13:40:34 -07:00
Maxim Poliakovski fe424df9a0 sc53c94: implement accesses to Config 4 register. 2026-04-19 23:29:17 +02:00
Maxim Poliakovski ca7a8e8163 sc53c94: implement bus phase latch. 2026-04-19 23:29:17 +02:00
Maxim Poliakovski 8bcd8829cb sc53c94: improve DMA transfer handling. 2026-04-19 23:29:17 +02:00
Maxim Poliakovski 7a1babc5e9 scsi.h: fix and clean up ScsiCommand definition. 2026-04-19 23:29:17 +02:00
Maxim Poliakovski 883c404601 scsicommoncmds: remove superfluous logging statement. 2026-04-19 23:29:17 +02:00
joevt d94bf01163 debugger: More parsing bat changes.
- For MPC601, ibat#l should be bat#.
- For non-MPC601, ibat#l should be dbat#l for dbats.
- Don't show info for invalid bats on MPC601.
2026-04-18 11:41:54 -07:00
joevt 20ed0f7620 hmc: Cleanup formatting and indenting. 2026-04-18 08:11:30 -07:00
Maxim Poliakovski 32912aac52 sc53c94.h: extend Config 2 bit definition. 2026-04-18 15:04:43 +02:00
Maxim Poliakovski dc7a97abbf scsicdrom: switch to generic ScsiCdromCmds. 2026-04-18 13:26:12 +02:00
Maxim Poliakovski b1fd435e2e New class ScsiCdromCmds. 2026-04-18 13:26:12 +02:00
Cacodemon345 afa7458131 videoctrl: Do not attempt recursively swapping.
Fixes stack overflow crashes when booting maciNTtosh ARC firmware.

Note from joevt: Fixes a problem in the previous commit which does not
exist in the original source of the previous commit.
2026-04-15 20:17:14 -07:00
joevt ecb397de57 ofnvram: Remove redundant "ok" message.
"ok" is output by debugger.cpp which handles the prompt.
2026-04-15 20:08:40 -07:00
joevt d0260d1fdf ofnvram: Simplify checksum expressions.
These methods were extracted from Open Firmware Forth code but we can
make things more readable in C++.
2026-04-15 20:07:39 -07:00
joevt 2f951acdee ofnvram: Add f-segment? flag.
This is an Apple Network Server flag. It is unused on other versions of
Open Firmware.
2026-04-15 20:03:06 -07:00
joevt 9dc3cb978e machinefactory: Use print_all_info. 2026-04-15 19:47:09 -07:00
joevt 621150f2f4 debugger: Fix disasm endian changes. 2026-04-15 19:44:10 -07:00
Maxim Poliakovski ffade95fb9 atapi: rename data_out_phase() to data_in_phase().
That closely matches the SCSI terminology:
data-in:  host <-- device
data-out: host --> device
2026-04-15 16:47:32 +02:00
Maxim Poliakovski 290d8d3fcd atapibasedevice: fix packets for Rhapsody.
ATAPI devices use 12-byte packets by default.
Support for bigger packets is indicated in the first word
of the IDENTIFY ATAPI DEVICE response.

Installers for Rhapsody/Mac OS X Server 1.x send 16-byte packets
instead ignoring the device packet length.
This fix will reject extraneous packet bytes so the Rhapsody
installers will work as they do in the real hardware.
2026-04-14 00:58:09 +02:00
joevt 265615e9f3 timermanager: Make sure the correct timer is popped.
Pop using the ID just in case some other thread pushes a timer with
higher priority to the priority queue.
2026-04-12 19:43:52 -07:00
joevt b5693f29ce timermanager: Fix cyclic timer next timeout. 2026-04-12 19:42:32 -07:00
joevt cb48f59eeb timermanager: Remove duplicate code. 2026-04-12 19:41:20 -07:00
joevt b65c228593 timermanager: Create notify_changes_cb type. 2026-04-12 19:40:00 -07:00
joevt 1ac01add3a timermanager: Deterministic sort.
If nanoseconds are equal then sort by id which is never equal.
2026-04-12 18:51:37 -07:00
Rairii 09c1248be7 CPU and memory controller endian changes.
===============
Rairii changes:

memctrlbase: The memory controller may have an endian swap mode.
mpc106: Only mmio regions need endian swap and only if PCIR_LE_MODE is
set.

videoctrl: Add framebuffer_in_main_memory flag. Use needs_swap_endian.

debugger: Fix disasm for little endian mode.

ppcmmu: little endian mode requires munging of the data and instruction
addresses, affecting the 3 least significant bits.

ppcexec: pc_real is always recalculated during little endian mode
because instructions are swapped every 8 bytes (due to the address
munging).

==============
joevt changes:

Add SUPPORTS_MEMORY_CTRL_ENDIAN_MODE for memory controller.
Use cmake -DDPPC_SUPPORT_PPC_LE=ON to enable.

Add SUPPORTS_PPC_LITTLE_ENDIAN_MODE for CPU.
Use cmake -DDPPC_SUPPORT_MEM_LE=ON to enable.

Add ppc_change_endian to handle endian switch for MPC601 (uses HID0
instead of MSR) and later PPC CPUs.

Add is_LE flag to ppc_state to indicate little endian mode for all
processor versions.

Create separate ppc_exec_inner template functions for little and big
endian.

Switch endian mode in the ppc_exec outer functions when power_off_reason
is po_endian_switch.

Since MPC601 doesn't have ILE and LE bits, remove that code for that
CPU.

videoctrl: Uses templated methods. See next commit for a fix that this
change introduces.
2026-04-12 10:06:32 -07:00
joevt 25860025b0 Add debug option LOG_INSTRUCTIONS.
Adds a log that remembers the last 16 million instructions.
2026-04-12 09:38:14 -07:00
joevt a3bc3a4d04 soundserver_cubeb: Set pointers to null after destroy.
This will make the shutdown method reusable.
2026-04-12 08:35:08 -07:00
joevt 807f961b56 soundserver_cubeb: Use callback type. 2026-04-12 08:34:26 -07:00
joevt 1d75f7ba38 soundserver_cubeb: Use correct endian macros. 2026-04-12 08:34:05 -07:00
joevt 04e0dd188c romidentity: Add more New World Macs. 2026-04-11 18:43:44 -07:00
joevt 008413817a romidentity: Add more Mac OS ROM files. 2026-04-11 18:43:26 -07:00
joevt 0bf6f8b47f romidentity: Add Old World ROM 64-bit checksum.
The 32-bit checksum of Old World ROMs only covers the first 3 MiB.
Some Old World ROMs may have differences only in the last 1 MiB.
Therefore, include the 64-bit checksum which covers all 4 MiB.

Verify ROM size before trying to read from config_info.
2026-04-11 18:29:45 -07:00
joevt 7aacd5c703 ppcmmu: Initialize bat structs after bat regs.
Needed for machine restart.
2026-04-11 13:36:58 -07:00
joevt 688ec133c5 ppcexec: Initialize int_pin.
Problems happen if this is true after a restart.
2026-04-11 13:22:44 -07:00
joevt ed28c8e9a6 display_sdl: Add SDL_SetWindowKeyboardGrab.
To capture the Alt+Tab or the Meta/Super key in Linux/Windows.
Not necessary in macOS for the Command key, and macOS doesn't let you
capture Command-Tab.
2026-04-11 10:31:53 -07:00
joevt e689d62067 debugger: Parse BAT registers. 2026-04-11 10:26:06 -07:00
joevt 52631da7c7 atimach64gx: Fix comments. 2026-04-11 10:18:55 -07:00
joevt 5bfc9a3f75 atirage: Fix comments. 2026-04-11 10:18:53 -07:00
joevt 94ee77e9a4 atirage: Log clock_sel and vertical blank. 2026-04-11 10:18:36 -07:00
joevt b3975cc11a spdram: Add EDO. 2026-04-06 19:16:59 -07:00
joevt f7b5a440e8 dbdma: Use saved_cmd_bits. 2026-04-04 17:17:13 -07:00
Copilotandjarz 798af27514 dbdma: Fix update_irq bug in finish_cmd.
Co-authored-by: jarz <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
2026-04-04 17:16:52 -07:00
joevt dd1cc7da61 scsihd: Fix compiler warnings. 2026-04-04 14:43:51 -07:00
joevt 39a4c7fc05 scsiblockcmds: Fix compiler warnings. 2026-04-04 14:43:43 -07:00
Copilotandjarz a2b0ca42d3 gitignore: Add build folders.
Co-authored-by: jarz <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
2026-04-04 08:53:19 -07:00
Maxim Poliakovski 8955be1eaa Move Apple copyright page to ScsiBlockcmds class. 2026-04-01 21:06:47 +02:00
Maxim Poliakovski 4931bcb6ff scsiblockcmds: allow setting density code from outside. 2026-04-01 21:06:47 +02:00
Maxim Poliakovski 9c003a8b64 scsiblockcmds: don't inherit from BlockStorageDevice. 2026-04-01 21:06:47 +02:00
Maxim Poliakovski 00068dd4af blockstoragedevice: add a couple of getters. 2026-04-01 21:06:47 +02:00
130 changed files with 5637 additions and 2568 deletions

No files matched your search

+15 -7
View File
@@ -220,14 +220,19 @@ jobs:
ccache_args: -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache
upload_suffix: MSVC
- name: msbuild
generator: "Visual Studio 17 2022"
cmake_args: ""
ccache_args: ""
generator: Ninja
cmake_args: -DCMAKE_C_COMPILER=cl -DCMAKE_CXX_COMPILER=cl
ccache_args: -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache
upload_suffix: MSBUILD
steps:
- uses: actions/checkout@v5
with:
submodules: recursive
# Configures MSVC/Clang environment natively for all subsequent steps
- name: Setup MSVC Developer Command Prompt
uses: TheMrMilchmann/setup-msvc-dev@v4
with:
arch: x64
- name: Setup msbuild
uses: microsoft/setup-msbuild@v3
- name: Install vcpkg packages
@@ -252,10 +257,12 @@ jobs:
CCACHE_DIR: ${{ github.workspace }}/.ccache/vsbuild-${{ matrix.name }}
CCACHE_BASEDIR: ${{ github.workspace }}
run: |
mkdir build
call "%ProgramFiles%\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvars64.bat"
cmake -S . -B build -G "${{ matrix.generator }}" -DCMAKE_BUILD_TYPE=${{ env.BUILD_TYPE }} -DDPPC_68K_DEBUGGER=ON -DDPPC_BUILD_PPC_TESTS=ON ${{ matrix.ccache_args }} -DCMAKE_TOOLCHAIN_FILE=%VCPKG_INSTALLATION_ROOT%/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows ${{ matrix.cmake_args }}
cmake --build build --config ${{ env.BUILD_TYPE }} --parallel
mkdir build
call "%ProgramFiles%\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvars64.bat"
cd build
cmake -S .. -B . -G "${{ matrix.generator }}" -DCMAKE_BUILD_TYPE=${{ env.BUILD_TYPE }} -DDPPC_68K_DEBUGGER=ON -DDPPC_BUILD_PPC_TESTS=ON ${{ matrix.ccache_args }} -DCMAKE_TOOLCHAIN_FILE=%VCPKG_INSTALLATION_ROOT%\scripts\buildsystems\vcpkg.cmake
cmake --build . --config ${{ env.BUILD_TYPE }} --parallel
cd ..
- name: ccache stats
if: matrix.generator == 'Ninja'
shell: cmd
@@ -264,6 +271,7 @@ jobs:
if %errorlevel% neq 0 echo ccache stats unavailable
- name: Test
working-directory: ${{github.workspace}}/build
shell: cmd
run: ctest -C ${{env.BUILD_TYPE}} --output-on-failure
- name: Upload logs on failure
if: failure()
+1
View File
@@ -41,6 +41,7 @@ ehthumbs.db
# IDE ignores
build
build*/
build-*
*.dir
*.user
+15 -3
View File
@@ -84,6 +84,19 @@ if (DPPC_68K_DEBUGGER)
add_subdirectory(thirdparty/capstone EXCLUDE_FROM_ALL)
endif()
option (DPPC_SUPPORT_PPC_LE "Enable PPC little endian mode" OFF)
option (DPPC_SUPPORT_MEM_LE "Enable memory controller little endian mode" OFF)
if (DPPC_SUPPORT_PPC_LE)
ADD_DEFINITIONS(-DSUPPORTS_PPC_LITTLE_ENDIAN_MODE=1)
else()
ADD_DEFINITIONS(-DSUPPORTS_PPC_LITTLE_ENDIAN_MODE=0)
endif()
if (DPPC_SUPPORT_MEM_LE)
ADD_DEFINITIONS(-DSUPPORTS_MEMORY_CTRL_ENDIAN_MODE=1)
else()
ADD_DEFINITIONS(-DSUPPORTS_MEMORY_CTRL_ENDIAN_MODE=0)
endif()
add_subdirectory("${PROJECT_SOURCE_DIR}/core")
add_subdirectory("${PROJECT_SOURCE_DIR}/cpu/ppc/")
add_subdirectory("${PROJECT_SOURCE_DIR}/debugger/")
@@ -157,7 +170,6 @@ add_executable(dingusppc ${SOURCES} $<TARGET_OBJECTS:core>
$<TARGET_OBJECTS:loguru>)
endif()
# 2. Configure Apple-specific Bundle Properties
if (APPLE)
# Identify if we are targeting iOS or macOS
if (IOS)
@@ -171,8 +183,8 @@ 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.4"
MACOSX_BUNDLE_SHORT_VERSION_STRING "a1.0.4"
MACOSX_BUNDLE_BUNDLE_VERSION "alpha 1.0.4b"
MACOSX_BUNDLE_SHORT_VERSION_STRING "a1.0.4b"
MACOSX_BUNDLE_EXECUTABLE_NAME "DingusPPC"
# Placeholder for the icon file:
# MACOSX_BUNDLE_ICON_FILE "icon.icns"
+1
View File
@@ -4,6 +4,7 @@ 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.
* Do not use artificial intelligence to make contributions. This is due to authorship issues and licensing issues regarding AI usage.
Code
=======
+6 -1
View File
@@ -9,6 +9,10 @@
- maximumspatium
- mihaip
## ATI Rage Support (WIP)
- Cacodemon345
## NT4/PPC fork
- Wack0
@@ -16,7 +20,8 @@
## DevOps
- alicela1n
- Cacodemon345
- calmsacibis995
- claunia
- dressupgeekout
- dyharlan
- erichelgeson
+5 -3
View File
@@ -1,6 +1,8 @@
# DingusPPC
Written by divingkatae and maximumspatium
Written by The DingusPPC Development Team
(who are Divingkatae, maximumspatium, joevt, mihaip, kkaisershot, Cacodemon345, Wack0, et. al. Check CREDITS.md for more info)
Be warned the program is highly unfinished and could use a lot of testing. Any feedback is welcome.
@@ -27,10 +29,10 @@ This program currently uses the command prompt to work.
There are a few command line arguments one can enter when starting the program.
```
-r, --realtime
-r, --run
```
Run the emulator in runtime.
Run the emulator. Currently only goes to an interpreter.
```
-d, --debugger
+58 -4
View File
@@ -29,8 +29,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#if defined(PPC_BENCHMARKS)
void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
power_on = false;
power_off_reason = po_benchmark_exception;
power_off(po_benchmark_exception);
}
#endif
@@ -70,9 +69,16 @@ int main(int argc, char** argv) {
return -1;
}
constexpr uint64_t tbr_freq = 16705000;
constexpr uint64_t bus_freq = 66'820'000ULL;
constexpr uint64_t tbr_freq = bus_freq / 4;
constexpr uint64_t core_freq = bus_freq * 7 / 2; // 233.87 MHz (CPU PLL ratio of 3.5)
ppc_cpu_init(grackle_obj, PPC_VER::MPC750, false, tbr_freq);
ppc_cpu_init(grackle_obj, {
.version = PPC_VER::MPC750,
.timebase_freq_hz = tbr_freq,
.bus_freq_hz = bus_freq,
.core_freq_hz = core_freq,
});
/* load executable code into RAM at address 0 */
for (i = 0; i < sizeof(cs_code) / sizeof(cs_code[0]); i++) {
@@ -115,6 +121,54 @@ int main(int argc, char** argv) {
power_on = true;
ppc_exec_until(0xC4);
#if SUPPORTS_PPC_LITTLE_ENDIAN_MODE
#ifdef _MSC_VER
#pragma message("PPC endian mode enabled")
#else
#warning PPC endian mode enabled
#endif
LOG_F(INFO, "PPC endian mode enabled");
#else
#ifdef _MSC_VER
#pragma message("PPC endian mode disabled")
#else
#warning PPC endian mode disabled
#endif
LOG_F(INFO, "PPC endian mode disabled");
#endif
#if SUPPORTS_MEMORY_CTRL_ENDIAN_MODE
#ifdef _MSC_VER
#pragma message("Memory endian mode enabled")
#else
#warning Memory endian mode enabled
#endif
LOG_F(INFO, "Memory endian mode enabled");
#else
#ifdef _MSC_VER
#pragma message("Memory endian mode disabled")
#else
#warning Memory endian mode disabled
#endif
LOG_F(INFO, "Memory endian mode disabled");
#endif
#ifdef LOG_INSTRUCTIONS
#ifdef _MSC_VER
#pragma message("Log instructions enabled")
#else
#warning Log instructions enabled
#endif
LOG_F(INFO, "Log instructions enabled");
#else
#ifdef _MSC_VER
#pragma message("Log instructions disabled")
#else
#warning Log instructions disabled
#endif
LOG_F(INFO, "Log instructions disabled");
#endif
LOG_F(INFO, "Checksum: 0x%08X", ppc_state.gpr[3]);
uint32_t checksum = ppc_state.gpr[3];
+2 -2
View File
@@ -52,7 +52,7 @@ public:
}
// Calls all connected slots.
void emit(Args... args) {
void emit(Args... args) const {
if (!_is_enabled) {
return;
}
@@ -77,7 +77,7 @@ public:
_is_enabled = true;
}
bool is_enabled() {
bool is_enabled() const {
return _is_enabled;
}
View File
File renamed without changes.
+77 -33
View File
@@ -44,8 +44,7 @@ void EventManager::poll_events() {
switch (event.type) {
case SDL_QUIT:
power_on = false;
power_off_reason = po_quit;
power_off(po_quit);
break;
case SDL_WINDOWEVENT: {
@@ -125,21 +124,55 @@ void EventManager::poll_events() {
}
return;
}
// Control-Alt-Shift-+: increase instruction period
if (event.key.keysym.sym == SDLK_EQUALS &&
(event.key.keysym.mod & KMOD_ALL) == (KMOD_LCTRL | KMOD_LALT | KMOD_LSHIFT)
) {
if (event.type == SDL_KEYUP) {
uint64_t instruction_period = increment_instruction_period();
LOG_F(INFO, "Incremented instruction period: %d", (int)instruction_period);
}
return;
}
// Control-Alt-Shift--: decrease instruction period
if (event.key.keysym.sym == SDLK_MINUS &&
(event.key.keysym.mod & KMOD_ALL) == (KMOD_LCTRL | KMOD_LALT | KMOD_LSHIFT)
) {
if (event.type == SDL_KEYUP) {
uint64_t instruction_period = decrement_instruction_period();
LOG_F(INFO, "Decremented instruction period: %d", (int)instruction_period);
}
return;
}
// Control-Alt-R: g_realtime toggle
if (event.key.keysym.sym == SDLK_r && (event.key.keysym.mod & KMOD_ALL) == (KMOD_LCTRL | KMOD_LALT)) {
if (event.type == SDL_KEYUP) {
bool g_realtime_status = toggle_g_realtime();
LOG_F(INFO, "g_realtime: %s", g_realtime_status ? "enabled" : "disabled");
}
}
// Control-L: log toggle
if (event.key.keysym.sym == SDLK_l && (event.key.keysym.mod & KMOD_ALL) == KMOD_LCTRL) {
if (event.type == SDL_KEYUP) {
loguru::g_stderr_verbosity = loguru::g_stderr_verbosity == loguru::Verbosity_MAX ?
loguru::Verbosity_INFO
:
loguru::Verbosity_MAX;
loguru::Verbosity new_verbosity = loguru::g_stderr_verbosity;
if (new_verbosity < loguru::Verbosity_INFO)
new_verbosity = loguru::Verbosity_INFO;
else if (new_verbosity < loguru::Verbosity_MAX)
new_verbosity = loguru::Verbosity_MAX;
else
new_verbosity = loguru::Verbosity_OFF;
loguru::g_stderr_verbosity = loguru::Verbosity_INFO;
LOG_F(INFO, "g_stderr_verbosity: %d", new_verbosity);
loguru::g_stderr_verbosity = new_verbosity;
}
return;
}
// Control-D: debugger
if (event.key.keysym.sym == SDLK_d && (event.key.keysym.mod & KMOD_ALL) == KMOD_LCTRL) {
if (event.type == SDL_KEYUP) {
power_on = false;
power_off_reason = po_enter_debugger;
power_off(po_enter_debugger);
}
return;
}
@@ -285,6 +318,7 @@ void EventManager::poll_events() {
}
void EventManager::post_keyboard_state_events() {
int count;
int numkeys;
const Uint8 *states = SDL_GetKeyboardState(&numkeys);
int modstate = SDL_GetModState();
@@ -300,46 +334,54 @@ void EventManager::post_keyboard_state_events() {
} Modifier_t;
static Modifier_t modifiers[] = {
SDL_SCANCODE_LSHIFT , KMOD_LSHIFT , AdbKey_Shift ,
SDL_SCANCODE_RSHIFT , KMOD_RSHIFT , AdbKey_RightShift ,
SDL_SCANCODE_LCTRL , KMOD_LCTRL , AdbKey_Control ,
SDL_SCANCODE_RCTRL , KMOD_RCTRL , AdbKey_RightControl,
SDL_SCANCODE_LALT , KMOD_LALT , AdbKey_Option ,
SDL_SCANCODE_RALT , KMOD_RALT , AdbKey_RightOption ,
SDL_SCANCODE_LGUI , KMOD_LGUI , AdbKey_Command ,
SDL_SCANCODE_RGUI , KMOD_RGUI , AdbKey_Command ,
// SDL_SCANCODE_NUMLOCKCLEAR , KMOD_NUM , AdbKey_KeypadClear ,
SDL_SCANCODE_CAPSLOCK , KMOD_CAPS , AdbKey_CapsLock ,
// SDL_SCANCODE_MODE , KMOD_MODE , AdbKey_???? ,
// SDL_SCANCODE_SCROLLLOCK , KMOD_SCROLL , AdbKey_F14 ,
SDL_SCANCODE_UNKNOWN
{ SDL_SCANCODE_LSHIFT , KMOD_LSHIFT , AdbKey_Shift },
{ SDL_SCANCODE_RSHIFT , KMOD_RSHIFT , AdbKey_RightShift },
{ SDL_SCANCODE_LCTRL , KMOD_LCTRL , AdbKey_Control },
{ SDL_SCANCODE_RCTRL , KMOD_RCTRL , AdbKey_RightControl },
{ SDL_SCANCODE_LALT , KMOD_LALT , AdbKey_Option },
{ SDL_SCANCODE_RALT , KMOD_RALT , AdbKey_RightOption },
{ SDL_SCANCODE_LGUI , KMOD_LGUI , AdbKey_Command },
{ SDL_SCANCODE_RGUI , KMOD_RGUI , AdbKey_Command },
// { SDL_SCANCODE_NUMLOCKCLEAR , KMOD_NUM , AdbKey_KeypadClear },
{ SDL_SCANCODE_CAPSLOCK , KMOD_CAPS , AdbKey_CapsLock },
// { SDL_SCANCODE_MODE , KMOD_MODE , AdbKey_???? },
// { SDL_SCANCODE_SCROLLLOCK , KMOD_SCROLL , AdbKey_F14 },
{ SDL_SCANCODE_UNKNOWN },
};
LOG_F(INFO, "Current keyboard state:");
LOG_F(INFO, " Modifiers:");
count = 0;
for (Modifier_t *mod = modifiers; mod->scancode != SDL_SCANCODE_UNKNOWN; mod++) {
if (!(modstate & mod->keymod))
continue;
LOG_F(INFO, " mod:%s", SDL_GetScancodeName(mod->scancode));
LOG_F(INFO, " Modifier: %s", SDL_GetScancodeName(mod->scancode));
count++;
ke.key = mod->adbkey;
ke.flags = KEYBOARD_EVENT_DOWN;
this->_keyboard_signal.emit(ke);
}
if (!count)
LOG_F(INFO, " (none)");
LOG_F(INFO, " Keys and Modifiers:");
count = 0;
for (int i = 0; i < numkeys; i++) {
if (!states[i])
continue;
count++;
scancode = (SDL_Scancode)i;
Modifier_t *mod = modifiers;
for (; mod->scancode != SDL_SCANCODE_UNKNOWN && mod->scancode != scancode; mod++);
if (mod->scancode == scancode) {
LOG_F(INFO, " ignore:%s", SDL_GetScancodeName(scancode));
LOG_F(INFO, " Modifier: %s", SDL_GetScancodeName(scancode));
continue;
}
LOG_F(INFO, " key:%s", SDL_GetScancodeName(scancode));
LOG_F(INFO, " Key: %s", SDL_GetScancodeName(scancode));
keyevent.keysym.scancode = scancode;
keyevent.keysym.sym = SDL_GetKeyFromScancode(scancode);
keyevent.keysym.mod = modstate;
@@ -350,9 +392,11 @@ void EventManager::post_keyboard_state_events() {
ke.flags = KEYBOARD_EVENT_DOWN;
this->_keyboard_signal.emit(ke);
} else {
LOG_F(WARNING, "Unknown key %x pressed", keyevent.keysym.sym);
LOG_F(WARNING, " Unknown key %x pressed", keyevent.keysym.sym);
}
}
if (!count)
LOG_F(INFO, " (none)");
}
static int get_sdl_event_key_code(const SDL_KeyboardEvent &event, uint32_t kbd_locale)
@@ -486,9 +530,9 @@ static int get_sdl_event_key_code(const SDL_KeyboardEvent &event, uint32_t kbd_l
case SDLK_SCROLLLOCK: return AdbKey_F14;
case SDLK_PAUSE: return AdbKey_F15;
//International keyboard support
// International keyboard support
//Japanese keyboard
// Japanese keyboard
case SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_INTERNATIONAL3):
if (kbd_locale == Jpn_JPN)
return AdbKey_JIS_Yen;
@@ -503,18 +547,18 @@ static int get_sdl_event_key_code(const SDL_KeyboardEvent &event, uint32_t kbd_l
case SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_INTERNATIONAL2):
return AdbKey_JIS_Kana;
//German keyboard
// German keyboard
case 0XB4: return AdbKey_Slash;
case 0X5E: return AdbKey_ISO1;
case 0XDF: return AdbKey_Minus; //Eszett
case 0XE4: return AdbKey_LeftBracket; //A-umlaut
case 0XF6: return AdbKey_Semicolon; //O-umlaut
case 0XFC: return AdbKey_LeftBracket; //U-umlaut
case 0XDF: return AdbKey_Minus; // Eszett
case 0XE4: return AdbKey_LeftBracket; // A-umlaut
case 0XF6: return AdbKey_Semicolon; // O-umlaut
case 0XFC: return AdbKey_LeftBracket; // U-umlaut
// French keyboard
case 0X29: return AdbKey_Minus; // Right parenthesis
case 0X43: return AdbKey_KeypadMultiply; // Star/Mu
//0XB2 is superscript 2. Which Mac key should this one map to?
// 0XB2 is superscript 2. Which Mac key should this one map to?
case 0XF9: return AdbKey_Quote; // U-grave
// Italian keyboard
+48 -37
View File
@@ -26,27 +26,18 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef MEM_ACCESS_H
#define MEM_ACCESS_H
#include "endianswap.h"
#include <cinttypes>
#include <core/endianswap.h>
#include <loguru.hpp>
/* read an aligned big-endian WORD (16bit) */
#define READ_WORD_BE_A( addr) (BYTESWAP_16(*((uint16_t*)(addr))))
#include <cinttypes>
/* read an aligned big-endian DWORD (32bit) */
#define READ_DWORD_BE_A(addr) (BYTESWAP_32(*((uint32_t*)(addr))))
/* read an aligned big-endian QWORD (64bit) */
#define READ_QWORD_BE_A(addr) (BYTESWAP_64(*((uint64_t*)(addr))))
/* read an aligned little-endian WORD (16bit) */
#define READ_WORD_LE_A( addr) (*(uint16_t*)(addr))
/* read an aligned little-endian DWORD (32bit) */
#define READ_DWORD_LE_A(addr) (*(uint32_t*)(addr))
/* read an aligned little-endian QWORD (64bit) */
#define READ_QWORD_LE_A(addr) (*(uint64_t*)(addr))
#if defined(WORDS_BIGENDIAN) || defined(__BIG_ENDIAN__)
#undef __BIG_ENDIAN__
#define __BIG_ENDIAN__ 1
#else
#undef __LITTLE_ENDIAN__
#define __LITTLE_ENDIAN__ 1
#endif
/* read an unaligned big-endian WORD (16bit) */
#define READ_WORD_BE_U( addr) ((((uint8_t*)(addr))[0] << 8) | ((uint8_t*)(addr))[1])
@@ -78,15 +69,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
(uint64_t(((uint8_t*)(addr))[3]) << 24) | ( ((uint8_t*)(addr))[2] << 16) | \
( ((uint8_t*)(addr))[1] << 8) | ((uint8_t*)(addr))[0] )
/* write an aligned big-endian WORD (16bit) */
#define WRITE_WORD_BE_A( addr, val) (*((uint16_t*)(addr)) = BYTESWAP_16(val))
/* write an aligned big-endian DWORD (32bit) */
#define WRITE_DWORD_BE_A(addr, val) (*((uint32_t*)(addr)) = BYTESWAP_32(val))
/* write an aligned big-endian QWORD (64bit) */
#define WRITE_QWORD_BE_A(addr, val) (*((uint64_t*)(addr)) = BYTESWAP_64(val))
/* write an unaligned big-endian WORD (16bit) */
#define WRITE_WORD_BE_U(addr, val) \
do { \
@@ -116,15 +98,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
((uint8_t*)(addr))[7] = (uint8_t)(val) ; \
} while (0)
/* write an aligned little-endian WORD (16bit) */
#define WRITE_WORD_LE_A( addr, val) (*((uint16_t*)(addr)) = (val))
/* write an aligned little-endian DWORD (32bit) */
#define WRITE_DWORD_LE_A(addr, val) (*((uint32_t*)(addr)) = (val))
/* write an aligned little-endian QWORD (64bit) */
#define WRITE_QWORD_LE_A(addr, val) (*((uint64_t*)(addr)) = (val))
/* write an unaligned little-endian WORD (16bit) */
#define WRITE_WORD_LE_U(addr, val) \
do { \
@@ -154,6 +127,44 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
((uint8_t*)(addr))[7] = ((uint64_t)(val) >> 56); \
} while (0)
#ifdef __LITTLE_ENDIAN__
#define READ_WORD_BE_A( addr) (BYTESWAP_16(*((uint16_t*)(addr))))
#define READ_DWORD_BE_A(addr) (BYTESWAP_32(*((uint32_t*)(addr))))
#define READ_QWORD_BE_A(addr) (BYTESWAP_64(*((uint64_t*)(addr))))
#define READ_WORD_LE_A( addr) (*(uint16_t*)(addr))
#define READ_DWORD_LE_A(addr) (*(uint32_t*)(addr))
#define READ_QWORD_LE_A(addr) (*(uint64_t*)(addr))
#define WRITE_WORD_BE_A( addr, val) (*((uint16_t*)(addr)) = BYTESWAP_16(val))
#define WRITE_DWORD_BE_A(addr, val) (*((uint32_t*)(addr)) = BYTESWAP_32(val))
#define WRITE_QWORD_BE_A(addr, val) (*((uint64_t*)(addr)) = BYTESWAP_64(val))
#define WRITE_WORD_LE_A( addr, val) (*((uint16_t*)(addr)) = (val))
#define WRITE_DWORD_LE_A(addr, val) (*((uint32_t*)(addr)) = (val))
#define WRITE_QWORD_LE_A(addr, val) (*((uint64_t*)(addr)) = (val))
#else // __BIG_ENDIAN__
#define READ_WORD_LE_A( addr) (BYTESWAP_16(*((uint16_t*)(addr))))
#define READ_DWORD_LE_A(addr) (BYTESWAP_32(*((uint32_t*)(addr))))
#define READ_QWORD_LE_A(addr) (BYTESWAP_64(*((uint64_t*)(addr))))
#define READ_WORD_BE_A( addr) (*(uint16_t*)(addr))
#define READ_DWORD_BE_A(addr) (*(uint32_t*)(addr))
#define READ_QWORD_BE_A(addr) (*(uint64_t*)(addr))
#define WRITE_WORD_LE_A( addr, val) (*((uint16_t*)(addr)) = BYTESWAP_16(val))
#define WRITE_DWORD_LE_A(addr, val) (*((uint32_t*)(addr)) = BYTESWAP_32(val))
#define WRITE_QWORD_LE_A(addr, val) (*((uint64_t*)(addr)) = BYTESWAP_64(val))
#define WRITE_WORD_BE_A( addr, val) (*((uint16_t*)(addr)) = (val))
#define WRITE_DWORD_BE_A(addr, val) (*((uint32_t*)(addr)) = (val))
#define WRITE_QWORD_BE_A(addr, val) (*((uint64_t*)(addr)) = (val))
#endif // __BIG_ENDIAN__
/* read an aligned native-endian DWORD */
#define READ_DWORD_NE_A READ_DWORD_LE_A // native-endian = little-endian for now
/* write an aligned native-endian DWORD */
#define WRITE_DWORD_NE_A WRITE_DWORD_LE_A // native-endian = little-endian for now
/* read value of the specified size from memory starting at addr,
perform byte swapping when necessary so that the source
byte order remains unchanged. */
@@ -232,4 +243,4 @@ inline void write_mem_rev(uint8_t* buf, uint32_t value, uint32_t size) {
}
}
#endif /* MEM_ACCESS_H */
#endif // MEM_ACCESS_H
+25 -51
View File
@@ -30,55 +30,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
TimerManager* TimerManager::timer_manager;
uint32_t TimerManager::add_oneshot_timer(uint64_t timeout, timer_cb cb)
uint32_t TimerManager::add_absolute_timer(uint64_t timeout_ns, uint64_t interval, timer_cb cb)
{
TimerInfo* ti = new TimerInfo;
ti->id = ++this->id;
ti->timeout_ns = this->get_time_now() + timeout;
ti->interval_ns = 0;
ti->cb = cb;
std::shared_ptr<TimerInfo> timer_desc(ti);
// add new timer to the timer queue
this->timer_queue.push(timer_desc);
// notify listeners about changes in the timer queue
if (!this->cb_active) {
this->notify_timer_changes();
}
return ti->id;
}
uint32_t TimerManager::add_immediate_timer(timer_cb cb) {
TimerInfo* ti = new TimerInfo;
ti->id = ++this->id;
ti->timeout_ns = this->get_time_now();
ti->interval_ns = 0;
ti->cb = cb;
std::shared_ptr<TimerInfo> timer_desc(ti);
// add new timer to the timer queue
this->timer_queue.push(timer_desc);
// notify listeners about changes in the timer queue
if (!this->cb_active) {
this->notify_timer_changes();
}
return ti->id;
}
uint32_t TimerManager::add_cyclic_timer(uint64_t interval, uint64_t delay, timer_cb cb)
{
TimerInfo* ti = new TimerInfo;
ti->id = ++this->id;
ti->timeout_ns = this->get_time_now() + delay;
ti->timeout_ns = timeout_ns;
ti->interval_ns = interval;
ti->cb = cb;
@@ -95,7 +52,23 @@ uint32_t TimerManager::add_cyclic_timer(uint64_t interval, uint64_t delay, timer
return ti->id;
}
uint32_t TimerManager::add_cyclic_timer(uint64_t interval, timer_cb cb) {
uint32_t TimerManager::add_oneshot_timer(uint64_t timeout, timer_cb cb)
{
return TimerManager::add_absolute_timer(this->get_time_now() + timeout, 0, cb);
}
uint32_t TimerManager::add_immediate_timer(timer_cb cb)
{
return TimerManager::add_absolute_timer(0, 0, cb);
}
uint32_t TimerManager::add_cyclic_timer(uint64_t interval, uint64_t delay, timer_cb cb)
{
return TimerManager::add_absolute_timer(this->get_time_now() + delay, interval, cb);
}
uint32_t TimerManager::add_cyclic_timer(uint64_t interval, timer_cb cb)
{
return this->add_cyclic_timer(interval, interval, cb);
}
@@ -122,17 +95,18 @@ 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);
uint64_t timeout_ns = cur_timer->timeout_ns;
timer_cb cb = cur_timer->cb;
// re-arm cyclic timers
if (cur_timer->interval_ns) {
std::lock_guard<std::recursive_mutex> lk(this->timer_queue.get_mtx());
cur_timer->timeout_ns = time_now + cur_timer->interval_ns;
this->timer_queue.remove_by_id(cur_timer->id);
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;
cur_timer->timeout_ns = timeout_ns_new;
this->timer_queue.push(cur_timer);
} else {
// remove one-shot timers from queue
this->timer_queue.pop();
}
this->cb_active = true;
+7 -4
View File
@@ -41,6 +41,7 @@ constexpr auto ONE_BILLION_NS = 1000000000;
#define MSECS_TO_NSECS(ms) (ms) * NS_PER_MSEC
typedef std::function<void()> timer_cb;
typedef std::function<void()> notify_changes_cb;
/** Extend std::priority_queue as suggested here:
https://stackoverflow.com/a/36711682
@@ -101,8 +102,9 @@ typedef struct 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) {
return l.get()->timeout_ns > r.get()->timeout_ns;
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);
}
};
@@ -121,14 +123,15 @@ public:
}
// callback for acknowledging time changes
void set_notify_changes_cb(const timer_cb &cb) {
void set_notify_changes_cb(const notify_changes_cb &cb) {
this->notify_timer_changes = cb;
}
// return current virtual time in nanoseconds
uint64_t current_time_ns() { return get_time_now(); }
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);
+80 -7
View File
@@ -22,9 +22,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef PPCEMU_H
#define PPCEMU_H
#include <core/endianswap.h>
#include <core/memaccess.h>
#include <devices/memctrl/memctrlbase.h>
#include <endianswap.h>
#include <memaccess.h>
#include <atomic>
#include <cinttypes>
@@ -37,6 +37,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
//#define CPU_PROFILING // enable CPU profiling
// Uncomment this to enable logging of executed instructions.
//#define LOG_INSTRUCTIONS
/** type of compiler used during execution */
enum EXEC_MODE:uint32_t {
interpreter = 0,
@@ -45,7 +48,7 @@ enum EXEC_MODE:uint32_t {
jit = 3
};
enum endian_switch { big_end = 0, little_end = 1 };
typedef enum { big_end = 0, little_end = 1 } endian_switch;
typedef void (*PPCOpcode)(uint32_t opcode);
@@ -79,6 +82,9 @@ typedef struct struct_ppc_state {
uint32_t msr;
uint32_t sr[16];
bool reserve; // reserve bit used for lwarx and stcwx
#if SUPPORTS_PPC_LITTLE_ENDIAN_MODE
bool is_LE;
#endif
} SetPRS;
extern SetPRS ppc_state;
@@ -173,7 +179,6 @@ SUPERVISOR MODEL
536 - 543 are the Data BAT registers
**/
extern uint64_t timebase_counter;
extern uint64_t tbr_wr_timestamp;
extern uint64_t dec_wr_timestamp;
extern uint64_t rtc_timestamp;
@@ -190,6 +195,7 @@ enum {
EXEF_EXCEPTION = 1 << 1, // Exception handler invoked
EXEF_RFI = 1 << 2, // RFI instruction executed
EXEF_OPC_DECODER = 1 << 3, // Opcode decoder has changed
EXEF_SLEEP = 1 << 4, // Processor is waiting in power-saving mode
};
enum CR_select : int32_t {
@@ -354,11 +360,17 @@ enum Po_Cause : int {
po_enter_debugger,
po_entered_debugger,
po_signal_interrupt,
po_benchmark_exception
po_benchmark_exception,
po_endian_switch,
};
extern bool power_on;
extern Po_Cause power_off_reason;
void p_set_power_off_reason(const char* file, int line, Po_Cause new_reason);
void p_power_off(const char* file, int line, Po_Cause new_reason);
#define set_power_off_reason(r) p_set_power_off_reason(__FILE__, __LINE__, r)
#define power_off(r) p_power_off(__FILE__, __LINE__, r)
extern bool int_pin;
extern bool dec_exception_pending;
@@ -368,14 +380,30 @@ extern bool include_601; // For non-PowerPC 601 emulation with 601 extras
extern bool is_altivec; // For Altivec Emulation
extern bool is_64bit; // For PowerPC G5 Emulation
// Make execution deterministic (ignore external input, used a fixed date, etc.)
enum class PPCPowMode : uint8_t {
None,
Unconditional,
HID0,
};
extern PPCPowMode ppc_pow_mode;
extern uint32_t ppc_pow_hid0_mask;
// Enable deterministic timing and non-persistent state. The selected mode may
// still permit external input.
extern bool is_deterministic;
// Important Addressing Integers
extern uint32_t ppc_next_instruction_address;
inline uint32_t ppc_read_instruction(const uint8_t* ptr) {
#if SUPPORTS_MEMORY_CTRL_ENDIAN_MODE
extern MemCtrlBase* mem_ctrl_instance;
bool needs_swap = mem_ctrl_instance->needs_swap_endian(false);
return needs_swap ? READ_DWORD_LE_A(ptr) : READ_DWORD_BE_A(ptr);
#else
return READ_DWORD_BE_A(ptr);
#endif
}
// Profiling Stats
@@ -442,8 +470,15 @@ typedef enum {
// Placeholder value for cases where we don't have a currently-executing instruction.
constexpr uint32_t NO_OPCODE = 0;
struct PPC_CPU_Config {
uint32_t version;
uint64_t timebase_freq_hz;
uint64_t bus_freq_hz;
uint64_t core_freq_hz;
};
// Function prototypes
extern void ppc_cpu_init(MemCtrlBase* mem_ctrl, uint32_t cpu_version, bool include_601, uint64_t tb_freq);
extern void ppc_cpu_init(MemCtrlBase* mem_ctrl, const PPC_CPU_Config& config);
extern void ppc_mmu_init();
void ppc_illegalop(uint32_t opcode);
@@ -686,9 +721,47 @@ extern void ppc_exec_dbg(uint32_t start_addr, uint32_t size);
extern PPCOpcode* ppc_opcode_grabber;
extern void ppc_msr_did_change(uint32_t old_msr_val, uint32_t new_msr_val, bool set_next_instruction_address = true);
extern void ppc_change_endian(bool newLE);
/* debugging support API */
uint64_t get_reg(std::string reg_name); /* get content of the register reg_name */
void set_reg(std::string reg_name, uint64_t val); /* set reg_name to val */
/* instruction period control */
extern uint64_t increment_instruction_period();
extern uint64_t decrement_instruction_period();
extern uint64_t get_instruction_period();
/* toggle_g_realtime */
extern bool toggle_g_realtime();
/* force_cycle_counter_reload */
static void force_cycle_counter_reload();
#ifdef LOG_INSTRUCTIONS
typedef struct {
uint64_t cycle;
uint32_t addr;
uint32_t paddr;
uint32_t ins;
uint32_t msr;
uint32_t msr_after;
uint32_t flags_before;
uint32_t flags_after;
uint32_t reserved1;
uint32_t reserved2;
uint32_t reserved3;
uint32_t reserved4;
uint32_t reserved5;
uint32_t reserved6;
uint32_t reserved7;
} InstructionRec; // 64 bytes
#define InstructionLogSize 0x1000000
extern InstructionRec InstructionLog[InstructionLogSize];
extern uint64_t InstructionNumber;
void dumpinstructionlog();
#endif
#endif /* PPCEMU_H */
+4
View File
@@ -119,6 +119,7 @@ void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
/* copy MSR[ILE] to MSR[LE] */
if (!is_601) {
new_msr_val = (new_msr_val & ~MSR::LE) | !!(new_msr_val & MSR::ILE);
ppc_change_endian((new_msr_val & MSR::LE) != 0);
}
// Don't clobber the ppc_next_instruction_address value
ppc_msr_did_change(old_msr_val, new_msr_val, false);
@@ -138,6 +139,9 @@ void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
mmu_change_mode();
if (exception_type != Except_Type::EXC_EXT_INT && exception_type != Except_Type::EXC_DECR) {
if (!power_on && power_off_reason == po_endian_switch) [[unlikely]] {
power_on = true;
}
longjmp(exc_env, 2); /* return to the main execution loop. */
}
}
+324 -54
View File
@@ -26,6 +26,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include "ppcdisasm.h"
#include <algorithm>
#include <cinttypes>
#include <chrono>
#include <cstring>
#include <iostream>
@@ -58,13 +59,67 @@ MemCtrlBase* mem_ctrl_instance = 0;
bool is_601 = false;
bool include_601 = false;
PPCPowMode ppc_pow_mode = PPCPowMode::None;
uint32_t ppc_pow_hid0_mask = 0;
// 603/7xx HID0 power-saving mode bits. They are selected in HID0,
// then entered by setting MSR[POW] with mtmsr.
static constexpr uint32_t HID0_DOZE = 0x00800000;
static constexpr uint32_t HID0_NAP = 0x00400000;
static constexpr uint32_t HID0_SLEEP = 0x00200000;
static constexpr uint32_t HID0_POWER_SAVE_MASK = HID0_DOZE | HID0_NAP | HID0_SLEEP;
bool is_deterministic = false;
bool power_on = false;
Po_Cause power_off_reason = po_enter_debugger;
const char * get_po_name(Po_Cause reason) {
#define onename(x) case x: return #x;
switch (reason) {
onename(po_none)
onename(po_starting_up)
onename(po_quit)
onename(po_quitting)
onename(po_shut_down)
onename(po_shutting_down)
onename(po_restart)
onename(po_restarting)
onename(po_disassemble_on)
onename(po_disassemble_off)
onename(po_enter_debugger)
onename(po_entered_debugger)
onename(po_signal_interrupt)
onename(po_benchmark_exception)
onename(po_endian_switch)
default: return "unknown";
}
#undef onename
}
void p_set_power_off_reason(const char* file, int line, Po_Cause new_reason) {
if (new_reason != power_off_reason) {
power_off_reason = new_reason;
#if 1
LOG_F(INFO, "power_off_reason changed to %s at \"%s\":%d", get_po_name(new_reason), file, line);
#endif
}
}
void p_power_off(const char* file, int line, Po_Cause new_reason) {
power_on = false;
p_set_power_off_reason(file, line, new_reason);
}
SetPRS ppc_state;
#ifdef LOG_INSTRUCTIONS
uint32_t pcp;
#define ATPCP , &pcp
#define INCPC(amount) do { pc_real += (amount); pcp += (amount); } while(0)
#else
#define ATPCP
#define INCPC(amount) pc_real += (amount)
#endif
uint32_t ppc_next_instruction_address; // Used for branching, setting up the NIA
@@ -75,16 +130,21 @@ volatile bool exec_timer;
bool int_pin = false; // interrupt request pin state: true - asserted
bool dec_exception_pending = false;
/* copy of local variable bb_start_la. Need for correct
calculation of CPU cycles after setjmp that clobbers
non-volatile local variables. */
uint32_t glob_bb_start_la;
/* variables related to virtual time */
const bool g_realtime = false;
bool g_realtime = false;
uint64_t g_nanoseconds_base;
uint64_t g_icycles;
int icnt_factor;
// Fixed-point nanoseconds, with four fractional bits. This provides enough
// precision for the supported CPU clocks and over 36 years before overflow.
using FixedNanoseconds = uint64_t;
static constexpr int VIRT_TIME_FRAC_BITS = 4;
static FixedNanoseconds g_virt_time;
static FixedNanoseconds g_instruction_period;
static constexpr FixedNanoseconds instruction_period_for_frequency(uint64_t core_freq_hz)
{
return (((uint64_t)NS_PER_SEC << VIRT_TIME_FRAC_BITS) + core_freq_hz / 2) /
core_freq_hz;
}
/* global variables related to the timebase facility */
uint64_t tbr_wr_timestamp; // stores vCPU virtual time of the last TBR write
@@ -95,7 +155,6 @@ uint32_t tbr_freq_ghz; // TBR/RTC driving frequency in GHz expressed as a
uint32_t tbr_freq_shift; // If 32 bits is not sufficient, then include a shift.
uint64_t tbr_period_ns; // TBR/RTC period in ns expressed as a 64 bit value
// with 32 fractional bits (<1 Hz minimum).
uint64_t timebase_counter; // internal timebase counter
uint64_t dec_wr_timestamp; // stores vCPU virtual time of the last DEC write
uint32_t dec_wr_value; // last value written to the DEC register
uint32_t rtc_lo; // MPC601 RTC lower, counts nanoseconds
@@ -185,6 +244,11 @@ public:
#endif
#ifdef LOG_INSTRUCTIONS
InstructionRec InstructionLog[InstructionLogSize] = {0};
uint64_t InstructionNumber = 0;
#endif
/** Opcode lookup table, indexed by
primary opcode (bits 0...5) and modifier (bits 21...31). */
static PPCOpcode OpcodeGrabber[64 * 2048];
@@ -208,12 +272,26 @@ void ppc_msr_did_change(uint32_t old_msr_val, uint32_t new_msr_val, bool set_nex
ppc_next_instruction_address = ppc_state.pc + 4;
}
#else
power_on = false;
power_off_reason = po_endian_switch;
power_off(po_endian_switch);
#endif
}
}
void ppc_change_endian(bool newLE) {
#if SUPPORTS_PPC_LITTLE_ENDIAN_MODE
if (ppc_state.is_LE != newLE) {
LOG_F(INFO, "changed endian to %s", newLE ? "LE" : "BE");
ppc_state.is_LE = newLE;
power_off(po_endian_switch);
}
#else
if (newLE) {
LOG_F(ERROR, "unsupported endian %s", newLE ? "LE" : "BE");
power_off(po_enter_debugger);
}
#endif
}
PPCOpcode* ppc_opcode_grabber = OpcodeGrabberNoFPU;
/** Exception helpers. */
@@ -251,7 +329,28 @@ void ppc_main_opcode(PPCOpcode *opcodeGrabber, uint32_t opcode)
num_opcodes[opcode]++;
#endif
#endif
#ifdef LOG_INSTRUCTIONS
if (InstructionNumber && !InstructionLog[(InstructionNumber - 1) & (InstructionLogSize - 1)].flags_after) {
// This happens for all exceptions except EXC_EXT_INT && EXC_DECR
//LOG_F(ERROR, "previous instruction did not complete");
}
InstructionRec * irec = &InstructionLog[InstructionNumber & (InstructionLogSize - 1)];
irec->cycle = InstructionNumber++;
irec->addr = ppc_state.pc;
irec->paddr = pcp;
irec->ins = opcode;
irec->msr = ppc_state.msr;
irec->flags_before = exec_flags | (exec_timer << 7);
irec->flags_after = 0;
#endif
opcodeGrabber[(opcode >> 15 & 0x1F800) | (opcode & 0x7FF)](opcode);
#ifdef LOG_INSTRUCTIONS
irec->flags_after = exec_flags | (exec_timer << 7) | 0x80000000;
irec->msr_after = ppc_state.msr;
#endif
}
static long long cpu_now_ns() {
@@ -268,20 +367,35 @@ uint64_t get_virt_time_ns()
if (g_realtime) {
return cpu_now_ns() - g_nanoseconds_base;
} else {
return g_icycles << icnt_factor;
return g_virt_time >> VIRT_TIME_FRAC_BITS;
}
}
static uint64_t process_events()
void set_virt_time_ns(uint64_t time_now)
{
if (g_realtime) {
g_nanoseconds_base = cpu_now_ns() - time_now - 5000;
} else {
g_virt_time = time_now << VIRT_TIME_FRAC_BITS;
}
uint64_t time_new = get_virt_time_ns();
if (g_realtime && time_new > time_now) {
g_nanoseconds_base += 2 * (time_new - time_now);
time_new = get_virt_time_ns();
}
LOG_F(INFO, "time before: %lld after: %lld change: %lld", time_now, time_new, time_new - time_now);
}
static FixedNanoseconds process_events()
{
exec_timer = false;
uint64_t slice_ns = TimerManager::get_instance()->process_timers();
if (slice_ns == 0) {
// execute 25.000 cycles
// execute 25,000 instructions
// if there are no pending timers
return g_icycles + 25000;
return g_virt_time + 25'000 * g_instruction_period;
}
return g_icycles + (slice_ns >> icnt_factor) + 1;
return g_virt_time + (slice_ns << VIRT_TIME_FRAC_BITS);
}
static void force_cycle_counter_reload()
@@ -290,6 +404,40 @@ static void force_cycle_counter_reload()
exec_timer = true;
}
uint64_t increment_instruction_period()
{
uint64_t time_now = get_virt_time_ns();
g_instruction_period += 1;
set_virt_time_ns(time_now);
force_cycle_counter_reload();
return g_instruction_period;
}
uint64_t decrement_instruction_period()
{
if (g_instruction_period > 0) {
uint64_t time_now = get_virt_time_ns();
g_instruction_period -= 1;
set_virt_time_ns(time_now);
force_cycle_counter_reload();
}
return g_instruction_period;
}
uint64_t get_instruction_period()
{
return g_instruction_period;
}
bool toggle_g_realtime()
{
uint64_t time_now = get_virt_time_ns();
g_realtime = !g_realtime;
set_virt_time_ns(time_now);
force_cycle_counter_reload();
return g_realtime;
}
typedef enum {
main,
until,
@@ -297,10 +445,13 @@ typedef enum {
} ppc_exec_type_t;
// inner interpreter loop
template <ppc_exec_type_t exec_type>
template <ppc_exec_type_t exec_type, endian_switch endian>
static void ppc_exec_inner(uint32_t start_addr, uint32_t size)
{
uint64_t max_cycles = 0;
FixedNanoseconds event_deadline = 0;
// Keep these hot-loop values in registers.
FixedNanoseconds virt_time = g_virt_time;
FixedNanoseconds instruction_period = g_instruction_period;
uint32_t page_start, eb_start, eb_end = 0;
uint32_t opcode;
PPCOpcode* opcode_grabber = ppc_opcode_grabber;
@@ -318,32 +469,59 @@ static void ppc_exec_inner(uint32_t start_addr, uint32_t size)
page_start = eb_start & PPC_PAGE_MASK;
eb_end = page_start + PPC_PAGE_SIZE - 1;
exec_flags = 0;
pc_real = mmu_translate_imem(eb_start);
pc_real = mmu_translate_imem(eb_start ATPCP); // &pcp
}
opcode = ppc_read_instruction(pc_real);
ppc_main_opcode(opcode_grabber, opcode);
if (g_icycles++ >= max_cycles || exec_timer) [[unlikely]]
max_cycles = process_events();
virt_time += instruction_period;
g_virt_time = virt_time;
if (virt_time >= event_deadline || exec_timer) [[unlikely]] {
event_deadline = process_events();
virt_time = g_virt_time;
instruction_period = g_instruction_period;
}
if (exec_flags) {
if ((exec_flags & EXEF_SLEEP) && !(exec_flags & EXEF_EXCEPTION)) [[unlikely]] {
while (power_on && (exec_flags & EXEF_SLEEP)) {
event_deadline = process_events();
virt_time = g_virt_time;
instruction_period = g_instruction_period;
if (!(exec_flags & EXEF_SLEEP)) {
break;
}
if (event_deadline > virt_time) {
virt_time = event_deadline;
} else {
virt_time += instruction_period;
}
g_virt_time = virt_time;
}
}
if (exec_flags & EXEF_OPC_DECODER) [[unlikely]] {
opcode_grabber = ppc_opcode_grabber;
}
// define next execution block
eb_start = ppc_next_instruction_address;
if (!(exec_flags & EXEF_RFI) && (eb_start & PPC_PAGE_MASK) == page_start) {
pc_real += (int)eb_start - (int)ppc_state.pc;
if (endian == big_end)
INCPC((int)eb_start - (int)ppc_state.pc);
else
pc_real = mmu_translate_imem(eb_start ATPCP); // &pcp
} else {
page_start = eb_start & PPC_PAGE_MASK;
eb_end = page_start + PPC_PAGE_SIZE - 1;
pc_real = mmu_translate_imem(eb_start);
pc_real = mmu_translate_imem(eb_start ATPCP); // &pcp
}
ppc_state.pc = eb_start;
exec_flags = 0;
} else { [[likely]]
} else [[likely]] {
ppc_state.pc += 4;
pc_real += 4;
if (endian == big_end)
INCPC(4);
else
pc_real = mmu_translate_imem(ppc_state.pc ATPCP); // &pcp
}
if (exec_type == until)
@@ -355,7 +533,8 @@ static void ppc_exec_inner(uint32_t start_addr, uint32_t size)
/** Execute PPC code as long as power is on. */
// inner interpreter loop
template void ppc_exec_inner<main>(uint32_t start_addr, uint32_t size);
template void ppc_exec_inner<main, big_end>(uint32_t start_addr, uint32_t size);
template void ppc_exec_inner<main, little_end>(uint32_t start_addr, uint32_t size);
// outer interpreter loop
void ppc_exec()
@@ -367,7 +546,17 @@ void ppc_exec()
}
while (power_on) {
ppc_exec_inner<main>(0, 0);
#if SUPPORTS_PPC_LITTLE_ENDIAN_MODE
if (ppc_state.is_LE)
ppc_exec_inner<main, little_end>(0, 0);
else
#endif
[[likely]] {
ppc_exec_inner<main, big_end>(0, 0);
}
if (!power_on && power_off_reason == po_endian_switch) [[unlikely]] {
power_on = true;
}
}
}
@@ -382,10 +571,10 @@ void ppc_exec_single()
return;
}
uint8_t* pc_real = mmu_translate_imem(ppc_state.pc);
uint8_t* pc_real = mmu_translate_imem(ppc_state.pc ATPCP); // &pcp
uint32_t opcode = ppc_read_instruction(pc_real);
ppc_main_opcode(ppc_opcode_grabber, opcode);
g_icycles++;
g_virt_time += g_instruction_period;
process_events();
if (exec_flags) {
@@ -399,7 +588,8 @@ void ppc_exec_single()
/** Execute PPC code until goal_addr is reached. */
// inner interpreter loop
template void ppc_exec_inner<until>(uint32_t start_addr, uint32_t size);
template void ppc_exec_inner<until, big_end>(uint32_t start_addr, uint32_t size);
template void ppc_exec_inner<until, little_end>(uint32_t start_addr, uint32_t size);
// outer interpreter loop
void ppc_exec_until(volatile uint32_t goal_addr) {
@@ -410,7 +600,17 @@ void ppc_exec_until(volatile uint32_t goal_addr) {
}
while (power_on) {
ppc_exec_inner<until>(goal_addr, 0);
#if SUPPORTS_PPC_LITTLE_ENDIAN_MODE
if (ppc_state.is_LE)
ppc_exec_inner<until, little_end>(goal_addr, 0);
else
#endif
[[likely]] {
ppc_exec_inner<until, big_end>(goal_addr, 0);
}
if (!power_on && power_off_reason == po_endian_switch) [[unlikely]] {
power_on = true;
}
if (ppc_state.pc == goal_addr)
break;
}
@@ -419,7 +619,8 @@ void ppc_exec_until(volatile uint32_t goal_addr) {
/** Execute PPC code until control is reached the specified region. */
// inner interpreter loop
template void ppc_exec_inner<debug>(uint32_t start_addr, uint32_t size);
template void ppc_exec_inner<debug, big_end>(uint32_t start_addr, uint32_t size);
template void ppc_exec_inner<debug, little_end>(uint32_t start_addr, uint32_t size);
// outer interpreter loop
void ppc_exec_dbg(volatile uint32_t start_addr, volatile uint32_t size)
@@ -431,7 +632,17 @@ void ppc_exec_dbg(volatile uint32_t start_addr, volatile uint32_t size)
}
while (power_on && (ppc_state.pc < start_addr || ppc_state.pc >= start_addr + size)) {
ppc_exec_inner<debug>(start_addr, size);
#if SUPPORTS_PPC_LITTLE_ENDIAN_MODE
if (ppc_state.is_LE)
ppc_exec_inner<debug, little_end>(start_addr, size);
else
#endif
[[likely]] {
ppc_exec_inner<debug, big_end>(start_addr, size);
}
if (!power_on && power_off_reason == po_endian_switch) [[unlikely]] {
power_on = true;
}
}
}
@@ -804,16 +1015,76 @@ void initialize_ppc_opcode_table() {
}
}
void ppc_cpu_init(MemCtrlBase* mem_ctrl, uint32_t cpu_version, bool do_include_601, uint64_t tb_freq)
static uint32_t get_cpu_pll_value(const PPC_CPU_Config& config)
{
switch (config.version) {
case PPC_VER::MPC603EV:
if (config.core_freq_hz * 2 == config.bus_freq_hz * 9)
return 7; // 4.5:1 ratio
if (config.core_freq_hz == config.bus_freq_hz * 5)
return 11; // 5:1 ratio
if (config.core_freq_hz * 2 == config.bus_freq_hz * 11)
return 9; // 5.5:1 ratio
break;
case PPC_VER::MPC750:
if (config.core_freq_hz * 2 == config.bus_freq_hz * 7)
return 14; // 3.5:1 ratio
if (config.core_freq_hz == config.bus_freq_hz * 6)
return 13; // 6:1 ratio
if (config.core_freq_hz == config.bus_freq_hz * 8)
return 12; // 8:1 ratio
break;
default:
break;
}
ABORT_F("Unsupported CPU/bus frequency combination: %" PRIu64 "/%" PRIu64 " Hz",
config.core_freq_hz, config.bus_freq_hz);
}
void ppc_cpu_init(MemCtrlBase* mem_ctrl, const PPC_CPU_Config& config)
{
if (!config.timebase_freq_hz || !config.bus_freq_hz || !config.core_freq_hz)
ABORT_F("CPU clock frequencies must be non-zero");
mem_ctrl_instance = mem_ctrl;
int_pin = false;
std::memset(&ppc_state, 0, sizeof(ppc_state));
set_host_rounding_mode(0);
ppc_state.spr[SPR::PVR] = cpu_version;
is_601 = (cpu_version >> 16) == 1;
include_601 = !is_601 & do_include_601;
ppc_state.spr[SPR::PVR] = config.version;
switch (config.version) {
case PPC_VER::MPC603EV:
case PPC_VER::MPC750:
ppc_state.spr[SPR::HID1] = get_cpu_pll_value(config) << 28;
break;
default:
break;
}
is_601 = (config.version >> 16) == 1;
include_601 = is_601;
ppc_pow_mode = PPCPowMode::None;
ppc_pow_hid0_mask = 0;
switch (config.version) {
case PPC_VER::MPC603:
case PPC_VER::MPC603E:
case PPC_VER::MPC603EV:
case PPC_VER::MPC750:
// 603/7xx enter power-saving modes through HID0 doze/nap/sleep
// bits selected before MSR[POW] is set.
ppc_pow_mode = PPCPowMode::HID0;
ppc_pow_hid0_mask = HID0_POWER_SAVE_MASK;
break;
case PPC_VER::MPC604:
case PPC_VER::MPC604E:
// 604-family processors use MSR[POW] directly.
ppc_pow_mode = PPCPowMode::Unconditional;
break;
default:
break;
}
initialize_ppc_opcode_table();
@@ -826,25 +1097,13 @@ void ppc_cpu_init(MemCtrlBase* mem_ctrl, uint32_t cpu_version, bool do_include_6
mach_timebase_info(&timebase_info);
#endif
g_nanoseconds_base = cpu_now_ns();
g_icycles = 0;
// // // PDM cpu clock calculated at 0x403036CC in r3
// icnt_factor = 11; // 1 instruction = 2048 ns = 0.488 MHz // 00068034 = 0.426036 MHz = 2347.219 ns // floppy doesn't work
// icnt_factor = 10; // 1 instruction = 1024 ns = 0.977 MHz // 000D204C = 0.860236 MHz = 1162.471 ns // [0..10] MHz = invalid clock for PDM gestalt calculation
// icnt_factor = 9; // 1 instruction = 512 ns = 1.953 MHz // 001A6081 = 1.728641 MHz = 578.489 ns // [0..10] MHz = invalid clock for PDM gestalt calculation
// icnt_factor = 8; // 1 instruction = 256 ns = 3.906 MHz // 0034E477 = 3.466359 MHz = 288.487 ns // [0..10] MHz = invalid clock for PDM gestalt calculation
// icnt_factor = 7; // 1 instruction = 128 ns = 7.813 MHz // 0069E54C = 6.939980 MHz = 144.092 ns // [0..10] MHz = invalid clock for PDM gestalt calculation
// icnt_factor = 6; // 1 instruction = 64 ns = 15.625 MHz // 00D3E6F5 = 13.887221 MHz = 72.008 ns // (10..60] = 50, (60..73] = 66, (73..100] = 80 MHz
// icnt_factor = 5; // 1 instruction = 32 ns = 31.250 MHz // 01A7B672 = 27.768434 MHz = 36.012 ns //
icnt_factor = 4; // 1 instruction = 16 ns = 62.500 MHz // 034F0F0F = 55.512847 MHz = 18.013 ns // 6100/60 in Apple System Profiler
// icnt_factor = 3; // 1 instruction = 8 ns = 125.000 MHz // 069E1E1E = 111.025694 MHz = 9.006 ns // (100...) MHz = invalid clock for PDM gestalt calculation
// icnt_factor = 2; // 1 instruction = 4 ns = 250.000 MHz // 0D3C3C3C = 222.051388 MHz = 4.503 ns // (100...) MHz = invalid clock for PDM gestalt calculation
// icnt_factor = 1; // 1 instruction = 2 ns = 500.000 MHz // 1A611A7B = 442.571387 MHz = 2.259 ns // (100...) MHz = invalid clock for PDM gestalt calculation
// icnt_factor = 0; // 1 instruction = 1 ns = 1500.000 MHz // 3465B2D9 = 879.080153 MHz = 1.137 ns // (100...) MHz = invalid clock for PDM gestalt calculation
g_virt_time = 0;
g_instruction_period = instruction_period_for_frequency(config.core_freq_hz);
tbr_wr_timestamp = 0;
rtc_timestamp = 0;
tbr_wr_value = 0;
uint64_t tb_freq = config.timebase_freq_hz;
if (is_601)
tb_freq <<= 7;
tbr_freq_shift = 0;
@@ -857,9 +1116,11 @@ void ppc_cpu_init(MemCtrlBase* mem_ctrl, uint32_t cpu_version, bool do_include_6
exec_flags = 0;
exec_timer = false;
timebase_counter = 0;
dec_wr_value = 0;
#ifdef LOG_INSTRUCTIONS
pcp = 0;
#endif
uint32_t new_msr_val;
if (is_601) {
@@ -868,6 +1129,7 @@ void ppc_cpu_init(MemCtrlBase* mem_ctrl, uint32_t cpu_version, bool do_include_6
} else {
new_msr_val = MSR::IP;
ppc_state.spr[SPR::DEC_S] = 0xFFFFFFFFUL;
ppc_change_endian((new_msr_val & MSR::LE) != 0);
}
ppc_msr_did_change(new_msr_val, new_msr_val, false);
@@ -930,6 +1192,9 @@ static uint64_t reg_op(string& reg_name, uint64_t val, bool is_write) {
if (is_write) {
uint32_t old_msr_val = ppc_state.msr;
uint32_t new_msr_val = (uint32_t)val;
if (!is_601) {
ppc_change_endian((new_msr_val & MSR::LE) != 0);
}
ppc_msr_did_change(old_msr_val, new_msr_val, false);
}
return ppc_state.msr;
@@ -985,8 +1250,13 @@ static uint64_t reg_op(string& reg_name, uint64_t val, bool is_write) {
case SPR::TBL_U : reg_num = SPR::TBL_S ; break;
case SPR::TBU_U : reg_num = SPR::TBU_S ; break;
}
if (is_write)
if (is_write) {
ppc_state.spr[reg_num] = (uint32_t)val;
if (reg_num == SPR::HID0)
if (is_601) {
ppc_change_endian((val & 0x10000000) != 0);
}
}
return ppc_state.spr[reg_num];
}
}
+41 -37
View File
@@ -37,7 +37,7 @@ inline static void ppc_update_cr1() {
}
static int32_t round_to_nearest(double f) {
return static_cast<int32_t>(static_cast<int64_t> (std::floor(f + 0.5)));
return static_cast<int32_t>(std::nearbyint(f));
}
void set_host_rounding_mode(uint8_t mode) {
@@ -111,8 +111,8 @@ inline static bool check_qnan(int check_reg) {
((check_int & (0x1ULL << 51)) == (0x1ULL << 51)));
}
static double set_endresult_nan(double ppc_result_d) {
ppc_state.fpscr += (FX + VX);
static double set_endresult_nan() {
ppc_state.fpscr |= (FX | VX);
return std::numeric_limits<double>::quiet_NaN();
}
@@ -154,11 +154,11 @@ static void ppc_update_vx() {
}
static void ppc_update_fex() {
uint32_t fpscr_check = (ppc_state.fpscr >> 22) & ppc_state.fpscr & 0x0F8;
uint32_t fpscr_check = ((ppc_state.fpscr >> 22) & 0x0F8);
if (fpscr_check)
ppc_state.fpscr |= VX;
ppc_state.fpscr |= FEX;
else
ppc_state.fpscr &= ~VX;
ppc_state.fpscr &= ~FEX;
}
// Floating Point Arithmetic
@@ -175,7 +175,7 @@ void dppc_interpreter::ppc_fadd(uint32_t opcode) {
((val_reg_a == -inf) && (val_reg_b == inf))) {
ppc_state.fpscr |= VXISI;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
@@ -206,7 +206,7 @@ void dppc_interpreter::ppc_fsub(uint32_t opcode) {
if ((val_reg_a == inf) && (val_reg_b == inf)) {
ppc_state.fpscr |= VXISI;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
@@ -255,7 +255,7 @@ void dppc_interpreter::ppc_fdiv(uint32_t opcode) {
if ((val_reg_a == 0.0) && (val_reg_b == 0.0)) {
ppc_state.fpscr |= VXZDZ;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
@@ -286,7 +286,7 @@ void dppc_interpreter::ppc_fmul(uint32_t opcode) {
(std::isinf(val_reg_c) && (val_reg_a == 0.0))) {
ppc_state.fpscr |= VXIMZ;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
@@ -321,7 +321,7 @@ void dppc_interpreter::ppc_fmadd(uint32_t opcode) {
((val_reg_a == -inf) && (val_reg_b == inf))) {
ppc_state.fpscr |= VXISI;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
@@ -329,7 +329,7 @@ void dppc_interpreter::ppc_fmadd(uint32_t opcode) {
(std::isinf(val_reg_c) && (val_reg_a == 0.0))) {
ppc_state.fpscr |= VXIMZ;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
@@ -359,7 +359,7 @@ void dppc_interpreter::ppc_fmsub(uint32_t opcode) {
(std::isinf(val_reg_c) && (val_reg_a == 0.0))) {
ppc_state.fpscr |= VXIMZ;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
@@ -367,7 +367,7 @@ void dppc_interpreter::ppc_fmsub(uint32_t opcode) {
if (((val_reg_a == inf) && (val_reg_b == -inf)) || ((val_reg_a == -inf) && (val_reg_b == inf))) {
ppc_state.fpscr |= VXISI;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
@@ -405,7 +405,7 @@ void dppc_interpreter::ppc_fnmadd(uint32_t opcode) {
if (((val_reg_a == inf) && (val_reg_b == -inf)) || ((val_reg_a == -inf) && (val_reg_b == inf))) {
ppc_state.fpscr |= VXISI;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
@@ -413,18 +413,18 @@ void dppc_interpreter::ppc_fnmadd(uint32_t opcode) {
(std::isinf(val_reg_c) && (val_reg_a == 0.0))) {
ppc_state.fpscr |= VXIMZ;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
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 {
}
else {
ppc_store_fpresult_flt(reg_d, ppc_dblresult64_d);
}
ppc_store_fpresult_flt(reg_d, ppc_dblresult64_d);
fpresult_update(ppc_dblresult64_d);
if (rec)
@@ -444,7 +444,7 @@ void dppc_interpreter::ppc_fnmsub(uint32_t opcode) {
(std::isinf(val_reg_c) && (val_reg_a == 0.0))) {
ppc_state.fpscr |= VXIMZ;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
@@ -452,7 +452,7 @@ void dppc_interpreter::ppc_fnmsub(uint32_t opcode) {
if (((val_reg_a == inf) && (val_reg_b == -inf)) || ((val_reg_a == -inf) && (val_reg_b == inf))) {
ppc_state.fpscr |= VXISI;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
@@ -484,7 +484,7 @@ void dppc_interpreter::ppc_fadds(uint32_t opcode) {
if (((val_reg_a == inf) && (val_reg_b == -inf)) || ((val_reg_a == -inf) && (val_reg_b == inf))) {
ppc_state.fpscr |= VXISI;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
@@ -515,7 +515,7 @@ void dppc_interpreter::ppc_fsubs(uint32_t opcode) {
((val_reg_a == -inf) && (val_reg_b == -inf))) {
ppc_state.fpscr |= VXISI;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
@@ -551,7 +551,7 @@ void dppc_interpreter::ppc_fdivs(uint32_t opcode) {
if ((val_reg_a == 0.0) && (val_reg_b == 0.0)) {
ppc_state.fpscr |= VXZDZ;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
@@ -585,7 +585,7 @@ void dppc_interpreter::ppc_fmuls(uint32_t opcode) {
(std::isinf(val_reg_c) && (val_reg_a == 0.0))) {
ppc_state.fpscr |= VXIMZ;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
@@ -623,7 +623,7 @@ void dppc_interpreter::ppc_fmadds(uint32_t opcode) {
(std::isinf(val_reg_c) && (val_reg_a == 0.0))) {
ppc_state.fpscr |= VXIMZ;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
@@ -634,7 +634,6 @@ void dppc_interpreter::ppc_fmadds(uint32_t opcode) {
ppc_store_fpresult_flt(reg_d, ppc_dblresult64_d);
}
ppc_store_fpresult_flt(reg_d, ppc_dblresult64_d);
fpresult_update(ppc_dblresult64_d);
if (rec)
@@ -654,7 +653,7 @@ void dppc_interpreter::ppc_fmsubs(uint32_t opcode) {
(std::isinf(val_reg_c) && (val_reg_a == 0.0))) {
ppc_state.fpscr |= VXIMZ;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
@@ -695,7 +694,7 @@ void dppc_interpreter::ppc_fnmadds(uint32_t opcode) {
(std::isinf(val_reg_c) && (val_reg_a == 0.0))) {
ppc_state.fpscr |= VXIMZ;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
@@ -728,7 +727,7 @@ void dppc_interpreter::ppc_fnmsubs(uint32_t opcode) {
(std::isinf(val_reg_c) && (val_reg_a == 0.0))) {
ppc_state.fpscr |= VXIMZ;
if (std::isnan(ppc_dblresult64_d)) {
ppc_dblresult64_d = set_endresult_nan(ppc_dblresult64_d);
ppc_dblresult64_d = set_endresult_nan();
}
}
@@ -764,8 +763,6 @@ void dppc_interpreter::ppc_fabs(uint32_t opcode) {
ppc_store_fpresult_int(reg_d, ppc_result64_d);
snan_single_check(reg_d);
if (rec)
ppc_update_cr1();
}
@@ -781,8 +778,6 @@ void dppc_interpreter::ppc_fnabs(uint32_t opcode) {
ppc_store_fpresult_int(reg_d, ppc_result64_d);
snan_single_check(reg_d);
if (rec)
ppc_update_cr1();
}
@@ -798,8 +793,6 @@ void dppc_interpreter::ppc_fneg(uint32_t opcode) {
ppc_store_fpresult_int(reg_d, ppc_result64_d);
snan_single_check(reg_d);
if (rec)
ppc_update_cr1();
}
@@ -1246,6 +1239,9 @@ void dppc_interpreter::ppc_mtfsf(uint32_t opcode) {
// copy FPR[reg_b] to FPSCR under control of cr_mask
ppc_state.fpscr = (ppc_state.fpscr & ~cr_mask) | (FPR_INT(reg_b) & cr_mask);
ppc_update_vx();
ppc_update_fex();
if (rec)
ppc_update_cr1();
}
@@ -1282,6 +1278,9 @@ void dppc_interpreter::ppc_mtfsb0(uint32_t opcode) {
ppc_state.fpscr &= ~(0x80000000UL >> crf_d);
}
ppc_update_vx();
ppc_update_fex();
if (rec)
ppc_update_cr1();
}
@@ -1296,6 +1295,9 @@ void dppc_interpreter::ppc_mtfsb1(uint32_t opcode) {
ppc_state.fpscr |= (0x80000000UL >> crf_d);
}
ppc_update_vx();
ppc_update_fex();
if (rec)
ppc_update_cr1();
}
@@ -1316,8 +1318,10 @@ void dppc_interpreter::ppc_mcrfs(uint32_t opcode) {
FPSCR::UX | FPSCR::ZX | FPSCR::XX | FPSCR::VXSNAN |
FPSCR::VXISI | FPSCR::VXIDI | FPSCR::VXZDZ | FPSCR::VXIMZ |
FPSCR::VXVC |
FPSCR::VXSOFT | FPSCR::VXSQRT | FPSCR::VXCVI
));
FPSCR::VXSOFT | FPSCR::VXSQRT | FPSCR::VXCVI));
ppc_update_vx();
ppc_update_fex();
}
// Floating Point Comparisons
+530 -128
View File
File diff suppressed because it is too large. Load diff
+5 -35
View File
@@ -24,8 +24,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef PPCMMU_H
#define PPCMMU_H
#include <devices/memctrl/memctrlbase.h>
#include <cinttypes>
#include <functional>
@@ -84,47 +82,19 @@ typedef struct MapDmaResult {
constexpr uint32_t PPC_PAGE_SIZE_BITS = 12;
constexpr uint32_t PPC_PAGE_SIZE = (1 << PPC_PAGE_SIZE_BITS);
constexpr uint32_t PPC_PAGE_MASK = ~(PPC_PAGE_SIZE - 1);
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
typedef struct TLBEntry {
uint32_t tag;
uint16_t flags;
uint16_t lru_bits;
union {
struct { // for memory pages
int64_t host_va_offs_r;
int64_t host_va_offs_w;
};
struct { // for MMIO pages
AddressMapEntry* rgn_desc;
int64_t dev_base_va;
};
};
uint32_t phys_tag;
uint32_t reserved;
} TLBEntry;
enum TLBFlags : uint16_t {
PAGE_MEM = 1 << 0, // memory page backed by host memory
PAGE_IO = 1 << 1, // memory mapped I/O page
PAGE_NOPHYS = 1 << 2, // no physical storage for this page (unmapped)
TLBE_FROM_BAT = 1 << 3, // TLB entry has been translated with BAT
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
};
extern std::function<void(uint32_t bat_reg)> ibat_update;
extern std::function<void(uint32_t bat_reg)> dbat_update;
extern MapDmaResult mmu_map_dma_mem(uint32_t addr, uint32_t size, bool allow_mmio);
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 void mmu_change_mode(void);
extern void mmu_pat_ctx_changed();
extern void tlb_flush_entry(uint32_t ea);
extern void mmu_dcbz(uint32_t opcode, uint32_t guest_va);
extern uint64_t mem_read_dbg(uint32_t virt_addr, uint32_t size);
extern void mem_write_dbg(uint32_t virt_addr, uint64_t value, int size);
+45 -7
View File
@@ -730,6 +730,7 @@ void dppc_interpreter::ppc_mtsr(uint32_t opcode) {
#endif
if (ppc_state.msr & MSR::PR) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::NOT_ALLOWED);
return;
}
int reg_s = (opcode >> 21) & 0x1F;
uint32_t grab_sr = (opcode >> 16) & 0x0F;
@@ -745,6 +746,7 @@ void dppc_interpreter::ppc_mtsrin(uint32_t opcode) {
#endif
if (ppc_state.msr & MSR::PR) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::NOT_ALLOWED);
return;
}
ppc_grab_regssb(opcode);
uint32_t grab_sr = ppc_result_b >> 28;
@@ -760,6 +762,7 @@ void dppc_interpreter::ppc_mfsr(uint32_t opcode) {
#endif
if (ppc_state.msr & MSR::PR) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::NOT_ALLOWED);
return;
}
int reg_d = (opcode >> 21) & 0x1F;
uint32_t grab_sr = (opcode >> 16) & 0x0F;
@@ -772,6 +775,7 @@ void dppc_interpreter::ppc_mfsrin(uint32_t opcode) {
#endif
if (ppc_state.msr & MSR::PR) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::NOT_ALLOWED);
return;
}
ppc_grab_regsdb(opcode);
uint32_t grab_sr = ppc_result_b >> 28;
@@ -784,6 +788,7 @@ void dppc_interpreter::ppc_mfmsr(uint32_t opcode) {
#endif
if (ppc_state.msr & MSR::PR) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::NOT_ALLOWED);
return;
}
uint32_t reg_d = (opcode >> 21) & 0x1F;
ppc_state.gpr[reg_d] = ppc_state.msr;
@@ -795,10 +800,14 @@ void dppc_interpreter::ppc_mtmsr(uint32_t opcode) {
#endif
if (ppc_state.msr & MSR::PR) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::NOT_ALLOWED);
return;
}
uint32_t reg_s = (opcode >> 21) & 0x1F;
uint32_t old_msr_val = ppc_state.msr;
uint32_t new_msr_val = ppc_state.gpr[reg_s];
if (!is_601) {
ppc_change_endian((new_msr_val & MSR::LE) != 0);
}
ppc_msr_did_change(old_msr_val, new_msr_val);
// generate External Interrupt Exception
@@ -810,6 +819,26 @@ 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::POW) [[unlikely]] {
bool enter_sleep = false;
switch (ppc_pow_mode) {
case PPCPowMode::Unconditional:
enter_sleep = true;
break;
case PPCPowMode::HID0:
enter_sleep = (ppc_state.spr[SPR::HID0] & ppc_pow_hid0_mask) != 0;
break;
case PPCPowMode::None:
break;
}
if (enter_sleep) {
exec_flags |= EXEF_SLEEP;
ppc_next_instruction_address = (ppc_state.pc & 0xFFFFFFFCUL) + 4;
} else {
mmu_change_mode();
}
} else {
mmu_change_mode();
}
@@ -968,12 +997,14 @@ void dppc_interpreter::ppc_mfspr(uint32_t opcode) {
case SPR::MQ:
if (!(is_601 || include_601)) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
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);
return;
}
calc_rtcl_value();
ppc_state.gpr[reg_d] =
@@ -983,6 +1014,7 @@ void dppc_interpreter::ppc_mfspr(uint32_t opcode) {
case SPR::RTCU_U:
if (!is_601) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
return;
}
calc_rtcl_value();
ppc_state.gpr[reg_d] =
@@ -992,6 +1024,7 @@ void dppc_interpreter::ppc_mfspr(uint32_t opcode) {
case SPR::DEC_U:
if (!is_601) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
return;
}
// fallthrough
case SPR::DEC_S:
@@ -1113,6 +1146,12 @@ void dppc_interpreter::ppc_mtspr(uint32_t opcode) {
ppc_state.spr[ref_spr] = val;
dbat_update(ref_spr);
break;
case SPR::HID0:
ppc_state.spr[ref_spr] = val;
if (is_601) {
ppc_change_endian((val & 0x10000000) != 0);
}
break;
default:
// FIXME: Unknown SPR should be noop or illegal instruction.
ppc_state.spr[ref_spr] = val;
@@ -1468,7 +1507,9 @@ void dppc_interpreter::ppc_rfi(uint32_t opcode) {
(msr_bits_to_replace & ~msr_bits_to_clear);
uint32_t new_msr_val = (ppc_state.msr & ~(msr_bits_to_replace | msr_bits_to_clear)) |
bits_from_srr1;
if (!is_601) {
ppc_change_endian((new_msr_val & MSR::LE) != 0);
}
ppc_msr_did_change(ppc_state.msr, new_msr_val);
// setting MSR[EE] may enable pending exceptions
@@ -1575,12 +1616,7 @@ void dppc_interpreter::ppc_dcbz(uint32_t opcode) {
ea &= 0xFFFFFFE0UL; // align EA on a 32-byte boundary
// the following is not especially efficient but necessary
// to make BlockZero under Mac OS 8.x and later to work
mmu_write_vmem<uint64_t>(opcode, ea + 0, 0);
mmu_write_vmem<uint64_t>(opcode, ea + 8, 0);
mmu_write_vmem<uint64_t>(opcode, ea + 16, 0);
mmu_write_vmem<uint64_t>(opcode, ea + 24, 0);
mmu_dcbz(opcode, ea);
}
@@ -2043,6 +2079,7 @@ void dppc_interpreter::ppc_eciwx(uint32_t opcode) {
// error if EAR[E] != 1
if (!(ppc_state.spr[SPR::EAR] & ear_enable)) {
ppc_exception_handler(Except_Type::EXC_DSI, 0x0);
return;
}
ppc_grab_regsdab(opcode);
@@ -2064,6 +2101,7 @@ void dppc_interpreter::ppc_ecowx(uint32_t opcode) {
if (!(ppc_state.spr[SPR::EAR] & ear_enable)) {
ppc_state.spr[SPR::DSISR] = 0x00100000;
ppc_exception_handler(Except_Type::EXC_DSI, 0x0);
return;
}
ppc_grab_regssab(opcode);
+176 -25
View File
@@ -19,13 +19,14 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <core/memaccess.h>
#include <core/timermanager.h>
#include <cpu/ppc/ppcdisasm.h>
#include <cpu/ppc/ppcemu.h>
#include <cpu/ppc/ppcmmu.h>
#include <debugger/debugger.h>
#include <devices/common/hwinterrupt.h>
#include <devices/common/ofnvram.h>
#include "memaccess.h"
#include <utils/profiler.h>
#include <array>
@@ -57,6 +58,8 @@ using namespace std;
#define COUT08X COUT0_X(8)
#define COUT04X COUT0_X(4)
extern bool g_auto_grab_mouse;
static uint32_t str2addr(string& addr_str) {
try {
return static_cast<uint32_t>(stoul(addr_str, NULL, 0));
@@ -115,6 +118,8 @@ static void show_help() {
cout << " printenv -- print current NVRAM settings." << endl;
cout << " setenv V N -- set NVRAM variable V to value N." << endl;
cout << endl;
cout << " autograbmouse H -- auto grab the mouse if H is not zero." << endl;
cout << endl;
cout << " restart -- restart the machine" << endl;
cout << " quit -- quit the debugger" << endl;
cout << endl;
@@ -426,10 +431,23 @@ static void patch_mem(string& params) {
}
static uint32_t disasm(PPCDisasmContext &ctx) {
ctx.instr_code = READ_DWORD_BE_A(mmu_translate_imem(ctx.instr_addr));
#if SUPPORTS_MEMORY_CTRL_ENDIAN_MODE
bool needs_swap = false;
if (mem_ctrl_instance != nullptr)
needs_swap = mem_ctrl_instance->needs_swap_endian(false);
#endif
uint8_t* real_addr = mmu_translate_imem(ctx.instr_addr);
ctx.instr_code =
#if SUPPORTS_MEMORY_CTRL_ENDIAN_MODE
needs_swap ? READ_DWORD_LE_A(real_addr) :
#endif
READ_DWORD_BE_A(real_addr);
cout << COUT08X << ctx.instr_addr;
cout << ": " << COUT08X << ctx.instr_code;
cout << " " << disassemble_single(&ctx) << setfill(' ') << right << dec;
return ctx.instr_addr;
}
@@ -473,6 +491,89 @@ static void disasm_out(PPCDisasmContext &ctx) {
cout << endl;
}
#ifdef LOG_INSTRUCTIONS
void dumpinstructionlog(uint64_t num) {
if (InstructionNumber == 0)
return;
if (num > InstructionNumber) {
num = InstructionNumber;
}
if (num > InstructionLogSize) {
num = InstructionLogSize;
}
printf("Dumping last %llu of %llu instructions:\n", num, InstructionNumber);
uint64_t i, end;
i = (InstructionNumber - num) & (InstructionLogSize - 1);
end = (InstructionNumber) & (InstructionLogSize - 1);
do {
if (!power_on)
break;
InstructionRec * irec = &InstructionLog[i];
PPCDisasmContext ctx;
ctx.kinds = 0;
ctx.level = 0;
ctx.simplified = true;
ctx.instr_code = irec->ins;
ctx.instr_addr = irec->addr;
std::string name = get_name(irec->addr, irec->paddr, nullptr, nullptr, 0);
cout << COUT08X << ctx.instr_addr;
if (irec->paddr != irec->addr) {
cout << "->" << COUT08X << irec->paddr;
}
if (!name.empty()) {
cout << " " << setw(27) << left << setfill(' ') << name;
}
cout << ": " << COUT08X << ctx.instr_code;
cout << " " << disassemble_single(&ctx) << setfill(' ') << left << dec;
if (ctx.instr_str.length() < 28)
cout << setw(28 - (int)ctx.instr_str.length()) << " ";
cout << " ;";
bool got_msr = false;
if (ctx.regs_in.size() > 0) {
cout << " in{" << COUTX;
for (auto & reg_name : ctx.regs_in) {
cout << " " << reg_name << ":";
if (reg_name == "msr") {
cout << irec->msr;
got_msr = true;
}
else
cout << "?";
}
cout << " }" << dec;
}
if (ctx.regs_out.size() > 0) {
cout << " out{" << COUTX;
for (auto & reg_name : ctx.regs_out) {
cout << " " << reg_name << ":" << "?";
}
cout << " }" << dec;
}
if (!got_msr) {
cout << " misc{" << COUTX;
cout << " " << "msr" << ":";
cout << irec->msr;
cout << " }" << dec;
}
cout << endl;
i++;
if (i >= InstructionLogSize)
i = 0;
} while (i != end);
}
#endif
static void print_gprs() {
string reg_name;
int i;
@@ -526,18 +627,34 @@ static void print_mmu_regs()
printf("\nBAT registers:\n");
for (int i = 0; i < 4; i++) {
printf(" ibat%du : %08X ibat%dl : %08X\n",
i, ppc_state.spr[528+i*2],
i, ppc_state.spr[529+i*2]);
}
if (!is_601) {
for (int i = 0; i < 4; i++) {
printf(" dbat%du : %08X dbat%dl : %08X\n",
i, ppc_state.spr[536+i*2],
i, ppc_state.spr[537+i*2]);
for (int i = 0; i < 4 + (is_601 ? 0 : 4); i++) {
PPC_BAT_entry *bat_entry = i < 4 ? ibat_array : dbat_array;
bat_entry = &bat_entry[i & 3];
printf(" %sbat%du : %08X %sbat%dl : %08X",
is_601 ? "" : i < 4 ? "i" : "d",
i & 3, ppc_state.spr[528+i*2],
is_601 ? "" : i < 4 ? "i" : "d",
i & 3, ppc_state.spr[529+i*2]
);
if (!is_601 || bat_entry->valid) {
printf(" ; range : %08X..%08X -> %08X..%08X access : %s%s protection : %s%s",
bat_entry->bepi, bat_entry->bepi + ~bat_entry->hi_mask,
bat_entry->phys_hi, bat_entry->phys_hi + ~bat_entry->hi_mask,
bat_entry->access & 2 ? is_601 ? "Ks" : "Vs" : "__",
bat_entry->access & 1 ? is_601 ? "Ku" : "Vp" : "__",
bat_entry->prot & 2 ? "P" : "_",
bat_entry->prot & 1 ? "P" : "_"
);
if (is_601) {
printf(" (%s)", "valid");
}
} else {
printf(" ; range : %8s..%8s -> %8s..%8s access : %s%s protection : %s%s",
"", "", "", "", "__", "__", "_", "_"
);
printf(" (%s)", "invalid");
}
printf("\n");
}
printf("\n");
@@ -613,21 +730,21 @@ void DppcDebugger::enter_debugger() {
while (1) {
if (power_off_reason == po_shut_down) {
power_off_reason = po_shutting_down;
set_power_off_reason(po_shutting_down);
break;
}
if (power_off_reason == po_restart) {
power_off_reason = po_restarting;
set_power_off_reason(po_restarting);
break;
}
if (power_off_reason == po_quit) {
power_off_reason = po_quitting;
set_power_off_reason(po_quitting);
break;
}
power_on = true;
if (power_off_reason == po_starting_up) {
power_off_reason = po_none;
set_power_off_reason(po_none);
cmd = "go";
}
else if (power_off_reason == po_disassemble_on) {
@@ -638,13 +755,13 @@ void DppcDebugger::enter_debugger() {
ss >> cmd;
}
else if (power_off_reason == po_disassemble_off) {
power_off_reason = po_none;
set_power_off_reason(po_none);
cmd = "go";
}
else
{
if (power_off_reason == po_enter_debugger) {
power_off_reason = po_entered_debugger;
set_power_off_reason(po_entered_debugger);
}
if (!did_message) {
cout << endl;
@@ -681,7 +798,7 @@ void DppcDebugger::enter_debugger() {
}
if (power_off_reason == po_signal_interrupt) {
power_off_reason = po_enter_debugger;
set_power_off_reason(po_enter_debugger);
// ignore command if interrupt happens because the input line is probably incomplete.
last_cmd = "";
continue;
@@ -708,8 +825,7 @@ void DppcDebugger::enter_debugger() {
break;
} else if (cmd == "restart") {
cmd = "";
power_on = false;
power_off_reason = po_restart;
power_off(po_restart);
} else if (cmd == "profile") {
cmd = "";
ss >> sub_cmd;
@@ -908,6 +1024,28 @@ void DppcDebugger::enter_debugger() {
cout << exc.what() << endl;
}
}
#ifdef LOG_INSTRUCTIONS
} else if (cmd == "dumpinstructionlog") {
cmd = "";
uint64_t count;
expr_str = "";
ss >> expr_str;
if (expr_str.length() > 0) {
try {
count = str2num(expr_str);
} catch (invalid_argument& exc) {
cout << exc.what() << endl;
count = 0;
}
} else {
count = InstructionNumber;
}
if (count)
dumpinstructionlog(count);
} else if (cmd == "clearinstructionlog") {
cmd = "";
InstructionNumber = 0;
#endif
} else if (cmd == "dump") {
expr_str = "";
ss >> expr_str;
@@ -1029,10 +1167,23 @@ void DppcDebugger::enter_debugger() {
cout << exc.what() << endl;
continue;
}
ViaCuda* via_obj = dynamic_cast<ViaCuda*>(gMachineObj->get_comp_by_name("ViaCuda"));
ppc_state.pc -= 4;
via_obj->assert_int(irq_bit);
TimerManager::get_instance()->add_oneshot_timer(0, [irq_bit](){
ViaCuda* via_obj = dynamic_cast<ViaCuda*>(gMachineObj->get_comp_by_name("ViaCuda"));
via_obj->assert_int(irq_bit);
});
#endif
} else if (cmd == "autograbmouse") {
cmd = "";
string value;
int num;
ss >> value;
try {
num = str2num(value);
} catch (invalid_argument& exc) {
cout << exc.what() << endl;
continue;
}
g_auto_grab_mouse = num;
} else {
if (!cmd.empty()) {
cout << "Unknown command: " << cmd << endl;
+1 -1
View File
@@ -21,11 +21,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file Apple Desktop Bus Mouse emulation. */
#include <core/memaccess.h>
#include <devices/common/adb/adbmouse.h>
#include <devices/common/adb/adbbus.h>
#include <devices/deviceregistry.h>
#include <core/hostevents.h>
#include <memaccess.h>
#include <loguru.hpp>
AdbMouse::AdbMouse(
+31 -3
View File
@@ -198,16 +198,21 @@ int AtaBaseDevice::pull_data(uint8_t *buf, int len) {
int xfer_size = std::min(this->xfer_cnt, len);
if (this->xfer_cnt != len)
LOG_F(WARNING, "%s: xfer_cnt != len", this->name.c_str());
if (this->xfer_cnt != len) {
LOG_F(9, "%s: DMA pull size differs from descriptor, remaining=%d requested=%d",
this->name.c_str(), this->xfer_cnt, len);
}
//for (int i = 0; i < xfer_size >> 1; i++)
// this->data_ptr[i] = BYTESWAP_16(this->data_ptr[i]);
std::memcpy(buf, this->data_ptr, xfer_size);
this->data_ptr = (uint16_t *)((uint8_t *)this->data_ptr + xfer_size);
this->xfer_cnt -= xfer_size;
if (!this->xfer_cnt) {
this->is_dma_xfer = false;
this->data_ptr = nullptr;
TimerManager::get_instance()->add_oneshot_timer(500, [this]() {
this->r_status &= ~(BSY | DRQ);
this->update_intrq(1);
@@ -221,7 +226,30 @@ int AtaBaseDevice::pull_data(uint8_t *buf, int len) {
}
int AtaBaseDevice::push_data(uint8_t *buf, int len) {
return 0;
if (!this->xfer_cnt || !this->is_dma_xfer)
return 0;
int xfer_size = std::min(this->xfer_cnt, len);
std::memcpy(this->cur_data_ptr, buf, xfer_size);
this->cur_data_ptr = (uint16_t *)((uint8_t *)this->cur_data_ptr + xfer_size);
this->xfer_cnt -= xfer_size;
if (!this->xfer_cnt) {
this->post_xfer_action();
this->is_dma_xfer = false;
this->data_ptr = nullptr;
this->cur_data_ptr = nullptr;
TimerManager::get_instance()->add_oneshot_timer(500, [this]() {
this->r_status &= ~(BSY | DRQ);
this->update_intrq(1);
});
} else {
this->r_status &= ~BSY;
this->r_status |= DRQ;
}
return xfer_size;
}
void AtaBaseDevice::update_intrq(uint8_t new_intrq_state) {
+1 -1
View File
@@ -24,9 +24,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef ATA_BASE_DEVICE_H
#define ATA_BASE_DEVICE_H
#include <core/endianswap.h>
#include <devices/common/ata/atadefs.h>
#include <devices/common/hwcomponent.h>
#include "endianswap.h"
#include <cinttypes>
#include <string>
+3 -1
View File
@@ -132,7 +132,7 @@ enum ATA_Cmd : uint8_t {
READ_VERIFY = 0x40,
ATAPI_COMMAND_GET_CONFIG = 0x46,
FORMAT_TRACKS = 0x50,
IDE_SEEK = 0x70,
SEEK = 0x70,
DIAGNOSTICS = 0x90,
INIT_DEV_PARAM = 0x91,
ATAPI_PACKET = 0xA0,
@@ -147,6 +147,8 @@ enum ATA_Cmd : uint8_t {
WRITE_DMA = 0xCA,
WRITE_DMA_NR = 0xCB,
STANDBY_IMMEDIATE = 0xE0,
IDLE_IMMEDIATE = 0xE1,
CHECK_POWER_MODE = 0xE5,
SLEEP = 0xE6,
FLUSH_CACHE = 0xE7, // ATA-5
WRITE_BUFFER_DMA = 0xE9,
+55 -12
View File
@@ -21,12 +21,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file ATA hard disk emulation. */
#include <core/memaccess.h>
#include <devices/common/ata/atahd.h>
#include <devices/deviceregistry.h>
#include <devices/common/ata/idechannel.h>
#include <loguru.hpp>
#include <machines/machinebase.h>
#include <memaccess.h>
#include <bitset>
#include <cstring>
@@ -99,11 +99,15 @@ int AtaHardDisk::perform_command() {
break;
case READ_MULTIPLE:
case READ_SECTOR:
case READ_SECTOR_NR: {
case READ_SECTOR_NR:
case READ_DMA:
case READ_DMA_NR: {
uint16_t sec_count = this->r_sect_count ? this->r_sect_count : 256;
int xfer_size = sec_count * ATA_HD_SEC_SIZE;
uint64_t offset = this->get_lba() * ATA_HD_SEC_SIZE;
uint32_t ints_size = ATA_HD_SEC_SIZE;
bool is_dma_cmd = this->r_command == READ_DMA ||
this->r_command == READ_DMA_NR;
uint32_t ints_size = is_dma_cmd ? xfer_size : ATA_HD_SEC_SIZE;
if (this->r_command == READ_MULTIPLE) {
if (!this->sectors_per_int) {
LOG_F(ERROR, "%s: READ_MULTIPLE disabled", this->name.c_str());
@@ -115,20 +119,34 @@ int AtaHardDisk::perform_command() {
}
hdd_img.read(buffer, offset, xfer_size);
this->data_ptr = (uint16_t *)this->buffer;
// those commands should generate IRQ for each sector
this->prepare_xfer(xfer_size, ints_size);
this->signal_data_ready();
if (is_dma_cmd) {
this->is_dma_xfer = true;
this->r_status &= ~(BSY | DRQ | ERR);
this->r_status |= DRDY | DSC;
// TODO: Model ATA DMAREQ as a latched signal instead of relying
// on this delay to avoid racing DBDMA command startup.
this->host_obj->assert_dmareq(500);
} else {
// PIO commands generate IRQ for each sector or multiple block.
this->signal_data_ready();
}
}
break;
case WRITE_MULTIPLE:
case WRITE_SECTOR:
case WRITE_SECTOR_NR: {
case WRITE_SECTOR_NR:
case WRITE_DMA:
case WRITE_DMA_NR: {
uint16_t sec_count = this->r_sect_count ? this->r_sect_count : 256;
this->cur_fpos = this->get_lba() * ATA_HD_SEC_SIZE;
this->data_ptr = (uint16_t *)this->buffer;
this->cur_data_ptr = this->data_ptr;
uint32_t xfer_size = sec_count * ATA_HD_SEC_SIZE;
uint32_t ints_size = ATA_HD_SEC_SIZE;
bool is_dma_cmd = this->r_command == WRITE_DMA ||
this->r_command == WRITE_DMA_NR;
uint32_t ints_size = is_dma_cmd ? xfer_size : ATA_HD_SEC_SIZE;
this->cur_fpos = this->get_lba() * ATA_HD_SEC_SIZE;
this->data_ptr = (uint16_t *)this->buffer;
this->cur_data_ptr = this->data_ptr;
if (this->r_command == WRITE_MULTIPLE) {
if (!this->sectors_per_int) {
LOG_F(ERROR, "%s: WRITE_MULTIPLE disabled", this->name.c_str());
@@ -144,10 +162,29 @@ int AtaHardDisk::perform_command() {
this->hdd_img.write(this->data_ptr, this->cur_fpos, write_len);
this->cur_fpos += write_len;
};
this->r_status |= DRQ;
this->r_status &= ~BSY;
if (is_dma_cmd) {
this->is_dma_xfer = true;
this->r_status &= ~(BSY | DRQ | ERR);
this->r_status |= DRDY | DSC;
// TODO: Model ATA DMAREQ as a latched signal instead of relying
// on this delay to avoid racing DBDMA command startup.
this->host_obj->assert_dmareq(500);
} else {
this->r_status |= DRQ;
this->r_status &= ~BSY;
}
}
break;
case CHECK_POWER_MODE:
this->r_sect_count = 0xFF; // always active or idle
this->r_status |= DRDY;
this->r_status &= ~BSY;
break;
case SEEK:
this->r_status |= DSC;
this->r_status &= ~BSY;
this->update_intrq(1);
break;
case DIAGNOSTICS:
this->r_error = 1; // device 0 passed, device 1 passed or not present
this->device_set_signature();
@@ -231,6 +268,12 @@ int AtaHardDisk::perform_command() {
this->r_status &= ~BSY;
this->update_intrq(1);
break;
case IDLE_IMMEDIATE:
LOG_F(INFO, "%s: immediate idle requested", this->name.c_str());
this->r_status &= ~(BSY | DRQ | ERR);
this->r_status |= DRDY;
this->update_intrq(1);
break;
default:
LOG_F(ERROR, "%s: unknown ATA command 0x%x", this->name.c_str(), this->r_command);
this->r_status &= ~BSY;
+66 -17
View File
@@ -21,10 +21,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file Basic ATAPI interface emulation. */
#include <core/endianswap.h>
#include <devices/common/ata/atabasedevice.h>
#include <devices/common/ata/atapibasedevice.h>
#include <devices/common/ata/atadefs.h>
#include <endianswap.h>
#include <loguru.hpp>
#include <cinttypes>
@@ -33,7 +33,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
using namespace ata_interface;
AtapiBaseDevice::AtapiBaseDevice(const std::string name)
: AtaBaseDevice(name, DEVICE_TYPE_ATAPI) {
: AtaBaseDevice(name, DEVICE_TYPE_ATAPI), ScsiPhysInterface(PHY_ID_ATAPI) {
}
void AtapiBaseDevice::device_set_signature() {
@@ -62,7 +62,9 @@ uint16_t AtapiBaseDevice::read(const uint8_t reg_addr) {
if (this->data_available()) {
this->r_status &= ~DRQ;
this->r_status |= BSY;
this->update_intrq(1); // Is this going to work here? The interrupt happens before returning ret_data.
// Is this going to work here?
// The interrupt happens before returning ret_data.
this->update_intrq(1);
}
else if (this->status_expected) {
this->present_status();
@@ -88,13 +90,14 @@ uint16_t AtapiBaseDevice::read(const uint8_t reg_addr) {
case ATA_Reg::STATUS:
this->update_intrq(0);
case ATA_Reg::ALT_STATUS:
if (this->r_status & BSY && this->data_available()) {
if ((this->r_status & BSY) && this->data_available()) {
this->r_byte_count = this->request_data();
this->data_out_phase();
this->data_in_phase();
}
return this->r_status;
default:
LOG_F(WARNING, "Attempted to read unknown register: %x", reg_addr);
LOG_F(WARNING, "%s: read from unknown register 0x%X", this->name.c_str(),
reg_addr);
return 0;
}
}
@@ -102,13 +105,22 @@ uint16_t AtapiBaseDevice::read(const uint8_t reg_addr) {
void AtapiBaseDevice::write(const uint8_t reg_addr, const uint16_t value) {
switch (reg_addr) {
case ATA_Reg::DATA:
if (has_data()) {
*this->data_ptr++ = BYTESWAP_16(value);
this->xfer_cnt -= 2;
if (this->xfer_cnt <= 0) {
this->r_status &= ~DRQ;
if (this->r_int_reason & CoD) {
this->perform_packet_command();
if (!(this->r_int_reason & ATAPI_Int_Reason::IO)) { // host --> device?
if (this->r_int_reason & ATAPI_Int_Reason::CoD) { // command phase?
if (this->xfer_cnt > 0) {
*this->data_ptr++ = BYTESWAP_16(value);
this->xfer_cnt -= 2;
if (this->xfer_cnt <= 0) {
this->r_status &= ~DRQ;
this->perform_packet_command();
}
}
} else { // data-out phase
if (this->xfer_cnt > 0) {
*this->data_ptr++ = BYTESWAP_16(value);
this->xfer_cnt -= 2;
if (this->xfer_cnt <= 0)
this->r_status &= ~DRQ;
}
}
}
@@ -138,7 +150,7 @@ void AtapiBaseDevice::write(const uint8_t reg_addr, const uint16_t value) {
this->device_control(value);
break;
default:
LOG_F(WARNING, "Attempted to write unknown IDE register: %x", reg_addr);
LOG_F(WARNING, "%s: write to unknown register 0x%X", this->name.c_str(), reg_addr);
}
}
@@ -168,7 +180,7 @@ int AtapiBaseDevice::perform_command() {
this->data_ptr = (uint16_t *)this->data_buf;
this->xfer_cnt = 512;
this->status_expected = false;
this->data_out_phase();
this->data_in_phase();
break;
case SET_FEATURES:
switch (this->r_features) {
@@ -189,12 +201,14 @@ int AtapiBaseDevice::perform_command() {
LOG_F(ERROR, "%s: unsupported command 0x%X", this->name.c_str(), this->r_command);
this->r_error |= ATA_Error::ABRT;
this->r_status |= ATA_Status::ERR;
this->r_status &= ~BSY;
this->update_intrq(1);
}
return 0;
}
void AtapiBaseDevice::data_out_phase() {
this->r_int_reason |= ATAPI_Int_Reason::IO; // device->host
void AtapiBaseDevice::data_in_phase() {
this->r_int_reason |= ATAPI_Int_Reason::IO; // device->host
this->r_int_reason &= ~ATAPI_Int_Reason::CoD; // data
this->signal_data_ready();
}
@@ -206,3 +220,38 @@ void AtapiBaseDevice::present_status() {
this->r_status &= ~BSY;
this->update_intrq(1);
}
void AtapiBaseDevice::switch_phase(const int new_phase) {
switch(new_phase) {
case ScsiPhase::DATA_IN:
this->data_in_phase();
break;
case ScsiPhase::DATA_OUT:
this->r_int_reason &= ATAPI_Int_Reason::IO; // host->device
this->r_int_reason &= ~ATAPI_Int_Reason::CoD; // data
this->signal_data_ready();
break;
case ScsiPhase::STATUS:
this->present_status();
break;
default:
LOG_F(WARNING, "ATAPI PHY: unsupported phase %d switch_phase", new_phase);
}
}
void AtapiBaseDevice::set_status(uint8_t status_code, uint8_t sense_key) {
switch(status_code) {
case ScsiStatus::GOOD:
this->status_expected = true;
this->r_error = 0;
this->r_status &= ~ATA_Status::ERR;
break;
case ScsiStatus::CHECK_CONDITION:
this->status_expected = true;
this->r_error = (sense_key << 4) | ATA_Error::ABRT;
this->r_status |= ATA_Status::ERR;
break;
default:
LOG_F(WARNING, "ATAPI PHY: unsupported status %d set_status", status_code);
}
}
+22 -2
View File
@@ -25,11 +25,13 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#define ATAPI_BASE_DEVICE_H
#include <devices/common/ata/atabasedevice.h>
#include <devices/common/scsi/scsi.h>
#include <devices/common/scsi/scsiphysinterface.h>
#include <cinttypes>
#include <string>
class AtapiBaseDevice : public AtaBaseDevice
class AtapiBaseDevice : public AtaBaseDevice, public ScsiPhysInterface
{
public:
AtapiBaseDevice(const std::string name);
@@ -40,6 +42,24 @@ public:
uint16_t read(const uint8_t reg_addr) override;
void write(const uint8_t reg_addr, const uint16_t value) override;
// ScsiPhysInterface methods
void set_lock_state(bool is_locked) override {};
void set_xfer_len(uint64_t len) override {
this->xfer_cnt = len;
this->r_byte_count = len;
}
void set_buffer(uint8_t *buf_ptr) override {
this->data_ptr = (uint16_t*)buf_ptr;
}
void set_status(uint8_t status_code, uint8_t sense_key) override;
void switch_phase(const int new_phase) override;
void set_read_more_data_cb(more_data_cb_t cb) override {};
void set_write_more_data_cb(more_data_cb_t cb) override {};
void set_post_xfer_action(action_callback cb) override {};
// methods to be implemented in the particular device
int perform_command() override;
virtual void perform_packet_command() = 0;
@@ -48,7 +68,7 @@ public:
virtual bool data_available() = 0;
// methods with default implementation
virtual void data_out_phase();
virtual void data_in_phase();
virtual void present_status();
protected:
+32 -179
View File
@@ -21,14 +21,13 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file ATAPI CDROM implementation. */
#include <core/memaccess.h>
#include <devices/common/ata/atadefs.h>
#include <devices/common/ata/atapicdrom.h>
#include <devices/common/ata/idechannel.h>
#include <devices/common/scsi/scsi.h> // ATAPI CDROM reuses SCSI commands (sic!)
#include <devices/deviceregistry.h>
#include <machines/machinebase.h>
#include <machines/machineproperties.h>
#include <memaccess.h>
#include <cstring>
#include <string>
@@ -36,12 +35,23 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
using namespace ata_interface;
AtapiCdrom::AtapiCdrom(std::string name) : CdromDrive(), AtapiBaseDevice(name) {
this->set_error_callback(
[this](uint8_t sense_key, uint8_t asc) {
this->status_error(sense_key, asc);
}
);
static char cdrom_vendor_id[] = "DINGUS ";
static char cdrom_product_id[] = "DINGUS CD-ROM ";
static char cdrom_revision_id[] = "1.0 ";
AtapiCdrom::AtapiCdrom(std::string name) : AtapiBaseDevice(name) {
this->set_phys_dev(this);
this->set_cdb_ptr(this->cmd_pkt);
this->set_buf_ptr(this->data_buf);
// populate device info for INQUIRY
this->dev_type = ScsiDevType::CD_ROM;
this->is_removable = true; // removable medium
this->std_versions = 2; // ANSI version: SCSI-2
this->resp_fmt = 0x21; // ATAPI Version + response data format
this->set_vendor_id(cdrom_vendor_id);
this->set_product_id(cdrom_product_id);
this->set_revision_id(cdrom_revision_id);
}
int AtapiCdrom::device_postinit() {
@@ -77,166 +87,16 @@ void AtapiCdrom::perform_packet_command() {
LOG_F(WARNING, "%s: doing_sector_areas reset", this->name.c_str());
}
// Assume successful command execution
if (this->cmd_pkt[0] == ScsiCommand::REQ_SENSE) {
// For REQ_SENSE we only set the status, status_good() also resets
// sense_key, which we'll need to return.
this->set_status(ScsiStatus::GOOD, 0);
} else {
this->status_good();
}
switch (this->cmd_pkt[0]) {
case ScsiCommand::TEST_UNIT_READY:
if (this->medium_present())
this->status_good();
else
this->status_error(ScsiSense::NOT_READY, ScsiError::MEDIUM_NOT_PRESENT);
this->present_status();
break;
case ScsiCommand::REQ_SENSE:
xfer_len = this->request_sense(this->data_buf, this->sense_key, this->asc, this->ascq);
if (!xfer_len) {
this->present_status();
} else {
this->xfer_cnt = std::min((uint32_t)this->r_byte_count, xfer_len);
this->data_ptr = (uint16_t*)this->data_buf;
this->status_good();
this->data_out_phase();
}
break;
case ScsiCommand::INQUIRY:
this->xfer_cnt = this->inquiry(this->cmd_pkt, this->data_buf);
this->r_byte_count = this->xfer_cnt;
this->data_ptr = (uint16_t*)this->data_buf;
this->status_good();
this->data_out_phase();
break;
case ScsiCommand::START_STOP_UNIT:
if ((this->cmd_pkt[4] & 3) == 2) {
LOG_F(WARNING, "CD-ROM eject requested");
}
this->status_good();
this->present_status();
break;
case ScsiCommand::PREVENT_ALLOW_MEDIUM_REMOVAL:
LOG_F(INFO, "%s: medium removal %s", this->name.c_str(),
this->cmd_pkt[4] & 1 ? "prevented" : "allowed");
this->status_good();
this->present_status();
break;
case ScsiCommand::READ_CAPACITY:
this->xfer_cnt = this->report_capacity(this->data_buf);
this->r_byte_count = this->xfer_cnt;
this->data_ptr = (uint16_t*)this->data_buf;
this->status_good();
this->data_out_phase();
break;
case ScsiCommand::READ_TOC:
this->status_good();
xfer_len = this->read_toc(this->cmd_pkt, this->data_buf);
if (!xfer_len) {
this->present_status();
} else {
this->xfer_cnt = std::min((uint32_t)this->r_byte_count, xfer_len);
this->data_ptr = (uint16_t*)this->data_buf;
this->data_out_phase();
}
break;
case ScsiCommand::MODE_SENSE_6:
this->xfer_cnt = this->mode_sense_ex(true, this->cmd_pkt, this->data_buf);
if (!this->xfer_cnt) {
this->present_status();
} else {
this->r_byte_count = this->xfer_cnt;
this->data_ptr = (uint16_t*)this->data_buf;
this->status_good();
this->data_out_phase();
}
break;
case ScsiCommand::MODE_SENSE_10:
this->xfer_cnt = this->mode_sense_ex(false, this->cmd_pkt, this->data_buf);
if (!this->xfer_cnt) {
this->present_status();
} else {
this->r_byte_count = this->xfer_cnt;
this->data_ptr = (uint16_t*)this->data_buf;
this->status_good();
this->data_out_phase();
}
break;
case ScsiCommand::READ_6:
lba = this->cmd_pkt[1] << 16 | READ_WORD_BE_U(&this->cmd_pkt[2]);
xfer_len = this->cmd_pkt[4];
// if transfer length is zero then just complete command
if (xfer_len == 0) {
this->status_good();
this->present_status();
break;
}
if (this->r_features & ATAPI_Features::DMA) {
LOG_F(WARNING, "ATAPI DMA transfer requsted");
}
this->set_fpos(lba);
this->xfer_cnt = this->read_begin(xfer_len, this->r_byte_count);
this->r_byte_count = this->xfer_cnt;
this->data_ptr = (uint16_t*)this->data_cache.get();
this->status_good();
this->data_out_phase();
break;
case ScsiCommand::READ_10:
if (this->xfer_cnt > 0) {
LOG_F(ERROR, "%s: READ(10) when transfer already in progress", name.c_str());
this->status_error(ScsiSense::NOT_READY, ScsiError::DEV_NOT_READY);
this->present_status();
break;
}
lba = READ_DWORD_BE_U(&this->cmd_pkt[2]);
xfer_len = READ_WORD_BE_U(&this->cmd_pkt[7]);
// if transfer length is zero then just complete command
if (xfer_len == 0) {
this->status_good();
this->present_status();
break;
}
if (this->r_features & ATAPI_Features::DMA) {
LOG_F(WARNING, "ATAPI DMA transfer requsted");
}
this->set_fpos(lba);
this->xfer_cnt = this->read_begin(xfer_len, this->r_byte_count);
this->r_byte_count = this->xfer_cnt;
this->data_ptr = (uint16_t*)this->data_cache.get();
this->status_good();
#if 0
TimerManager::get_instance()->add_oneshot_timer(
USECS_TO_NSECS(100), [this]() { this->data_out_phase(); });
#else
this->data_out_phase();
#endif
break;
case ScsiCommand::READ_12:
lba = READ_DWORD_BE_U(&this->cmd_pkt[2]);
xfer_len = READ_DWORD_BE_U(&this->cmd_pkt[6]);
// if transfer length is zero then just complete command
if (xfer_len == 0) {
this->status_good();
this->present_status();
break;
}
if (this->r_features & ATAPI_Features::DMA) {
LOG_F(WARNING, "ATAPI DMA transfer requsted");
}
this->set_fpos(lba);
this->xfer_cnt = this->read_begin(xfer_len, this->r_byte_count);
this->r_byte_count = this->xfer_cnt;
this->data_ptr = (uint16_t*)this->data_cache.get();
this->status_good();
this->data_out_phase();
break;
case ScsiCommand::SET_CD_SPEED:
LOG_F(INFO, "%s: speed set to %d kBps", this->name.c_str(),
READ_WORD_BE_U(&this->cmd_pkt[2]));
this->status_good();
this->present_status();
break;
case ScsiCommand::READ_CD:
{
lba = READ_DWORD_BE_U(&this->cmd_pkt[2]);
@@ -313,7 +173,7 @@ void AtapiCdrom::perform_packet_command() {
this->data_ptr = (uint16_t*)this->data_cache.get();
this->status_good();
this->data_out_phase();
this->data_in_phase();
break;
}
case ScsiCommand::GET_CONFIG: {
@@ -324,15 +184,12 @@ void AtapiCdrom::perform_packet_command() {
this->xfer_cnt = std::min((int)this->r_byte_count, this->xfer_cnt);
this->data_ptr = (uint16_t*)this->data_buf;
this->status_good();
this->data_out_phase();
this->data_in_phase();
}
break;
}
default:
LOG_F(ERROR, "%s: unsupported ATAPI command 0x%X", this->name.c_str(),
this->cmd_pkt[0]);
this->status_error(ScsiSense::ILLEGAL_REQ, ScsiError::INVALID_CMD);
this->present_status();
ScsiCdromCmds::process_command();
}
}
@@ -456,18 +313,14 @@ uint16_t AtapiCdrom::get_data() {
}
void AtapiCdrom::status_good() {
this->status_expected = true;
this->r_error = 0;
this->sense_key = 0;
this->r_status &= ~ATA_Status::ERR;
this->set_status(ScsiStatus::GOOD, this->sense_key);
}
void AtapiCdrom::status_error(uint8_t sense_key, uint8_t asc) {
this->status_expected = true;
this->sense_key = sense_key;
this->asc = asc;
this->r_error = (sense_key << 4) | ATA_Error::ABRT;
this->r_status |= ATA_Status::ERR;
this->set_status(ScsiStatus::CHECK_CONDITION, this->sense_key);
}
static const PropMap AtapiCdrom_Properties = {
+10 -6
View File
@@ -25,11 +25,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#define ATAPI_CDROM_H
#include <devices/common/ata/atapibasedevice.h>
#include <devices/storage/cdromdrive.h>
#include <devices/common/scsi/scsicdromcmds.h>
#include <string>
class AtapiCdrom : public CdromDrive, public AtapiBaseDevice {
class AtapiCdrom : public AtapiBaseDevice, public ScsiCdromCmds {
public:
AtapiCdrom(std::string name);
~AtapiCdrom() = default;
@@ -38,10 +38,17 @@ public:
return std::unique_ptr<AtapiCdrom>(new AtapiCdrom("ATAPI-CDROM"));
}
bool is_device_ready() override { return this->is_ready; }
uint8_t not_ready_reason() override { return ScsiError::MEDIUM_NOT_PRESENT; }
int device_postinit() override;
void perform_packet_command() override;
void set_lock_state(bool is_locked) override {
this->drive_locked = is_locked ? 1 : 0;
}
int get_config(uint8_t* pkt, uint8_t* buf) override;
int request_data() override;
@@ -54,11 +61,8 @@ public:
void status_error(uint8_t sense_key, uint8_t asc);
uint16_t get_data();
private:
uint8_t sense_key = 0;
uint8_t asc = 0;
uint8_t ascq = 0;
private:
bool doing_sector_areas = false;
uint8_t sector_areas;
uint32_t current_block;
+2 -2
View File
@@ -82,11 +82,11 @@ void IdeChannel::write(const uint8_t reg_addr, const uint32_t val, const int siz
}
}
int IdeChannel::xfer_from(uint8_t *buf, int len) {
int IdeChannel::xfer_from(DmaChannel *ch_obj, uint8_t *buf, int len) {
return this->devices[this->cur_dev]->pull_data(buf, len);
}
int IdeChannel::xfer_to(uint8_t *buf, int len) {
int IdeChannel::xfer_to(DmaChannel *ch_obj, uint8_t *buf, int len) {
return this->devices[this->cur_dev]->push_data(buf, len);
}
+2 -2
View File
@@ -45,8 +45,8 @@ public:
virtual uint32_t read(const uint8_t reg_addr, const int size);
virtual void write(const uint8_t reg_addr, const uint32_t val, const int size);
int xfer_from(uint8_t *buf, int len) override;
int xfer_to(uint8_t *buf, int len) override;
int xfer_from(DmaChannel *ch_obj, uint8_t *buf, int len) override;
int xfer_to(DmaChannel *ch_obj, uint8_t *buf, int len) override;
void assert_pdiag() {
this->devices[0]->pdiag_callback();
+173 -139
View File
@@ -21,14 +21,15 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file Descriptor-based direct memory access emulation. */
#include <core/endianswap.h>
#include <core/memaccess.h>
#include <core/timermanager.h>
#include <cpu/ppc/ppcmmu.h>
#include <devices/common/dbdma.h>
#include <devices/common/dmacore.h>
#include <devices/common/hwinterrupt.h>
#include <devices/common/mmiodevice.h>
#include <endianswap.h>
#include <memaccess.h>
#include <devices/memctrl/memctrlbase.h>
#include <cinttypes>
#include <cstring>
@@ -60,20 +61,21 @@ DMACmd* DMAChannel::fetch_cmd(uint32_t cmd_addr, DMACmd* p_cmd, bool *is_writabl
return cmd_host;
}
uint8_t DMAChannel::interpret_cmd() {
void DMAChannel::interpret_cmd() {
DMACmd cmd_struct;
MapDmaResult res;
if (this->cmd_in_progress) {
// return current command if there is data to transfer
// if there is data remaining to transfer then the command is not finished
if (this->queue_len)
return this->cur_cmd;
return;
// if there is no data remaining to transfer then the command is finished
// and the program should procede to the next command
this->finish_cmd();
}
bool cmd_is_writable;
DMACmd *cmd_host = fetch_cmd(this->cmd_ptr, &cmd_struct, &cmd_is_writable);
this->cur_host = fetch_cmd(this->cmd_ptr, &cmd_struct, &this->cur_is_writable);
this->ch_stat &= ~CH_STAT_WAKE; // clear wake bit (DMA spec, 5.5.3.4)
@@ -88,11 +90,11 @@ uint8_t DMAChannel::interpret_cmd() {
LOG_F(ERROR, "%s: Key > 0 not implemented", this->get_name().c_str());
break;
}
this->queue_len = cmd_struct.req_count;
if (this->queue_len) {
if (cmd_struct.req_count) {
res = mmu_map_dma_mem(cmd_struct.address, cmd_struct.req_count, false);
this->queue_data = res.host_va;
this->res_count = 0;
this->res_count = cmd_struct.req_count;
this->queue_len = cmd_struct.req_count; // don't set queue_len until all the other fields are set
this->cmd_in_progress = true;
switch (this->cur_cmd) {
case DBDMA_Cmd::OUTPUT_MORE:
@@ -108,23 +110,24 @@ uint8_t DMAChannel::interpret_cmd() {
this->in_cb();
break;
}
} else
} else {
this->queue_len = 0;
this->res_count = 0;
this->finish_cmd();
}
break;
case DBDMA_Cmd::STORE_QUAD:
if ((cmd_struct.cmd_key & 7) != 6)
LOG_F(ERROR, "%s: Invalid key %d in STORE_QUAD", this->get_name().c_str(),
cmd_struct.cmd_key & 7);
this->xfer_quad(&cmd_struct, nullptr);
this->xfer_quad(true);
break;
case DBDMA_Cmd::LOAD_QUAD:
if ((cmd_struct.cmd_key & 7) != 6) {
LOG_F(ERROR, "%s: Invalid key %d in LOAD_QUAD", this->get_name().c_str(),
cmd_struct.cmd_key & 7);
}
if (!cmd_is_writable)
LOG_F(ERROR, "%s: DMACmd is not writeable!", this->get_name().c_str());
this->xfer_quad(&cmd_struct, cmd_host);
this->xfer_quad(false);
break;
case DBDMA_Cmd::NOP:
this->finish_cmd();
@@ -140,30 +143,36 @@ uint8_t DMAChannel::interpret_cmd() {
this->ch_stat |= CH_STAT_DEAD;
this->ch_stat &= ~CH_STAT_ACTIVE;
}
}
return this->cur_cmd;
void DMAChannel::update_cmd() {
if (this->cur_is_writable) {
if (this->cur_cmd < DBDMA_Cmd::STOP)
WRITE_WORD_LE_A(&this->cur_host->xfer_stat, this->ch_stat | CH_STAT_ACTIVE);
// all INPUT and OUTPUT commands including LOAD_QUAD and STORE_QUAD update cmd.resCount
if (this->cur_cmd < DBDMA_Cmd::NOP)
WRITE_WORD_LE_A(&this->cur_host->res_count, this->res_count);
}
this->ch_stat &= ~(CH_STAT_FLUSH | CH_STAT_BT);
}
void DMAChannel::finish_cmd() {
bool branch_taken = false;
// obtain real pointer to the descriptor of the command to be finished
MapDmaResult res = mmu_map_dma_mem(this->cmd_ptr, 16, false);
uint8_t *cmd_desc = res.host_va;
// get command code
this->cur_cmd = cmd_desc[3] >> 4;
// save interrupt bits from the completing command before cmd_ptr may change
uint8_t saved_cmd_bits = this->cur_host->cmd_bits;
// all commands except STOP update cmd.xferStatus and
// perform actions under control of "i" interrupt, "b" branch, and "w" wait bits
if (this->cur_cmd < DBDMA_Cmd::STOP) {
// react to cmd.w (wait) bits
if (cmd_desc[2] & 3) {
if (saved_cmd_bits & 3) {
bool cond = true;
if ((cmd_desc[2] & 3) != 3) {
if ((saved_cmd_bits & 3) != 3) {
uint16_t wt_mask = this->wait_select >> 16;
cond = (this->ch_stat & wt_mask) == (this->wait_select & wt_mask);
if ((cmd_desc[2] & 3) == 2) {
if ((saved_cmd_bits & 3) == 2) {
cond = !cond; // wait if cond = false
}
}
@@ -175,50 +184,44 @@ void DMAChannel::finish_cmd() {
this->ch_stat &= ~CH_STAT_BT;
// react to cmd.b (branch) bits
if (cmd_desc[2] & 0xC) {
if (saved_cmd_bits & 0xC) {
bool cond = true;
if ((cmd_desc[2] & 0xC) != 0xC) {
if ((saved_cmd_bits & 0xC) != 0xC) {
uint16_t br_mask = this->branch_select >> 16;
cond = (this->ch_stat & br_mask) == (this->branch_select & br_mask);
if ((cmd_desc[2] & 0xC) == 0x8) {
if ((saved_cmd_bits & 0xC) == 0x8) {
cond = !cond; // branch if cond = false
}
}
if (cond) {
this->cmd_ptr = READ_DWORD_LE_A(&cmd_desc[8]);
this->cmd_ptr = READ_DWORD_LE_A(&this->cur_host->cmd_arg);
branch_taken = true;
this->ch_stat |= CH_STAT_BT;
}
}
if (res.is_writable)
WRITE_WORD_LE_A(&cmd_desc[14], this->ch_stat | CH_STAT_ACTIVE);
}
this->ch_stat &= ~(CH_STAT_FLUSH | CH_STAT_BT);
// all INPUT and OUTPUT commands including LOAD_QUAD and STORE_QUAD update cmd.resCount
if (this->cur_cmd < DBDMA_Cmd::NOP && res.is_writable) {
WRITE_WORD_LE_A(&cmd_desc[12], this->queue_len);
this->res_count = 0;
}
this->update_cmd();
if (this->cur_cmd < DBDMA_Cmd::STOP && !branch_taken)
this->cmd_ptr += 16;
// use the interrupt bits saved before cmd_ptr was advanced or branched
if (this->cur_cmd < DBDMA_Cmd::STOP) {
this->update_irq();
this->update_irq(saved_cmd_bits);
}
this->cmd_in_progress = false;
}
void DMAChannel::xfer_quad(const DMACmd *cmd_desc, DMACmd *cmd_host) {
void DMAChannel::xfer_quad(bool is_store) {
MapDmaResult res;
uint32_t addr;
uint32_t addr = READ_DWORD_LE_A(&this->cur_host->address);
uint16_t req_count = READ_WORD_LE_A (&this->cur_host->req_count);
uint32_t cmd_arg = READ_DWORD_LE_A(&this->cur_host->cmd_arg);
// parse and fix reqCount
uint32_t xfer_size = cmd_desc->req_count & 7;
uint32_t xfer_size = req_count & 7;
if (xfer_size & 4) {
xfer_size = 4;
} else if (xfer_size & 2) {
@@ -226,9 +229,8 @@ void DMAChannel::xfer_quad(const DMACmd *cmd_desc, DMACmd *cmd_host) {
} else {
xfer_size = 1;
}
this->res_count = cmd_desc->req_count; // this is the value that gets written to cmd.resCount
this->res_count = req_count; // this is the value that gets written to cmd.resCount
addr = cmd_desc->address;
if (addr & (xfer_size - 1)) {
LOG_F(ERROR, "%s: QUAD address 0x%08x is not aligned!", this->get_name().c_str(), addr);
addr &= ~(xfer_size - 1);
@@ -237,14 +239,15 @@ void DMAChannel::xfer_quad(const DMACmd *cmd_desc, DMACmd *cmd_host) {
res = mmu_map_dma_mem(addr, xfer_size, true);
// prepare data pointers and perform data transfer
if (!cmd_host) {
if (is_store) {
if (res.type & RT_MMIO) {
res.dev_obj->write(res.dev_base, addr - res.dev_base, cmd_desc->cmd_arg, xfer_size);
res.dev_obj->write(res.dev_base, addr - res.dev_base,
BYTESWAP_SIZED(cmd_arg, xfer_size), xfer_size);
} else if (res.is_writable) {
switch (xfer_size) {
case 1: *res.host_va = cmd_desc->cmd_arg; break;
case 2: WRITE_WORD_LE_A(res.host_va, cmd_desc->cmd_arg); break;
case 4: WRITE_DWORD_LE_A(res.host_va, cmd_desc->cmd_arg); break;
case 1: *res.host_va = cmd_arg; break;
case 2: WRITE_WORD_LE_A(res.host_va, cmd_arg); break;
case 4: WRITE_DWORD_LE_A(res.host_va, cmd_arg); break;
}
} else {
LOG_F(ERROR, "SOS: DMA access is not to RAM %08X!\n", addr);
@@ -261,30 +264,29 @@ void DMAChannel::xfer_quad(const DMACmd *cmd_desc, DMACmd *cmd_host) {
default: value = 0; break;
}
}
WRITE_DWORD_LE_A(&cmd_host->cmd_arg, value);
if (!this->cur_is_writable)
LOG_F(ERROR, "%s: DMACmd is not writeable!", this->get_name().c_str());
else
WRITE_DWORD_LE_A(&this->cur_host->cmd_arg, value);
}
if (cmd_desc->cmd_bits & 0xC)
if (this->cur_host->cmd_bits & 0xC)
ABORT_F("%s: cmd_bits.b should be zero for LOAD/STORE_QUAD!",
this->get_name().c_str());
this->finish_cmd();
}
void DMAChannel::update_irq() {
// obtain real pointer to the descriptor of the completed command
MapDmaResult res = mmu_map_dma_mem(this->cmd_ptr, 16, false);
uint8_t *cmd_desc = res.host_va;
void DMAChannel::update_irq(uint8_t cmd_bits) {
// STOP doesn't generate interrupts
if (this->cur_cmd < DBDMA_Cmd::STOP) {
// react to cmd.i (interrupt) bits
if (cmd_desc[2] & 0x30) {
if (cmd_bits & 0x30) {
bool cond = true;
if ((cmd_desc[2] & 0x30) != 0x30) {
if ((cmd_bits & 0x30) != 0x30) {
uint16_t int_mask = this->int_select >> 16;
cond = (this->ch_stat & int_mask) == (this->int_select & int_mask);
if ((cmd_desc[2] & 0x30) == 0x20) {
if ((cmd_bits & 0x30) == 0x20) {
cond = !cond; // generate interrupt if cond = false
}
}
@@ -334,7 +336,7 @@ uint32_t DMAChannel::reg_read(uint32_t offset, int size) {
}
void DMAChannel::reg_write(uint32_t offset, uint32_t value, int size) {
uint16_t mask, old_stat, new_stat;
uint16_t mask, data;
if (size != 4) {
ABORT_F("%s: non-DWORD writes to a DMA channel not supported",
@@ -342,61 +344,82 @@ void DMAChannel::reg_write(uint32_t offset, uint32_t value, int size) {
}
value = BYTESWAP_32(value);
old_stat = this->ch_stat;
switch (offset) {
case DMAReg::CH_CTRL:
mask = value >> 16;
new_stat = (value & mask & 0xF0FFU) | (old_stat & ~(mask & 0xC0FF));
LOG_F(9, "%s: New ChannelStatus value = 0x%X", this->get_name().c_str(), new_stat);
mask = value >> 16;
data = value & 0xFFFF;
// update ch_stat.s0...s7 if requested (needed for interrupt generation)
if ((new_stat & 0xFF) != (old_stat & 0xFF)) {
this->ch_stat |= new_stat & 0xFF;
}
// update general purpose channel status & control bits s0...s7
// if requested (needed for interrupt generation)
if (mask & 0xFF)
this->ch_stat = (this->ch_stat & ~(mask & 0xFF)) | (data & mask & 0xFF);
// flush bit can be set at the same time the run bit is cleared.
// That means we need to update memory before channel operation
// is aborted to prevent data loss.
if (new_stat & CH_STAT_FLUSH) {
if (this->cur_cmd <= DBDMA_Cmd::INPUT_LAST &&
this->flush_cb && (new_stat & CH_STAT_ACTIVE) &&
!(this->ch_stat & CH_STAT_DEAD)) {
this->flush_cb();
} else {
// NOTE: because this implementation doesn't currently support
// partial memory updates no special action is taken here
new_stat &= ~CH_STAT_FLUSH;
if (mask & CH_STAT_FLUSH) {
// FLUSH=1 should update memory for INPUT_MORE & INPUT_LAST commands
// when the channel is active and not dead.
// Setting FLUSH to 0 has no effect.
if (data & CH_STAT_FLUSH) {
if (
(this->cur_cmd == DBDMA_Cmd::INPUT_MORE || this->cur_cmd == DBDMA_Cmd::INPUT_LAST) &&
this->is_active()
) {
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();
}
}
this->ch_stat = new_stat;
this->ch_stat &= ~CH_STAT_FLUSH;
}
if ((new_stat & CH_STAT_RUN) != (old_stat & CH_STAT_RUN)) {
if (new_stat & CH_STAT_RUN) {
new_stat |= CH_STAT_ACTIVE;
this->ch_stat = new_stat;
this->start();
if (mask & CH_STAT_RUN) {
if (data & CH_STAT_RUN) {
// some drivers clear the PAUSE bit while setting the RUN bit.
// Clear the PAUSE bit without resuming the channel operation
// in this case.
if (mask & CH_STAT_PAUSE) {
if (data & CH_STAT_PAUSE)
ABORT_F("%s: Attempt to set both run and pause bits at the same time",
this->get_name().c_str());
else
this->ch_stat &= ~CH_STAT_PAUSE;
}
if (!(this->ch_stat & CH_STAT_ACTIVE)) {
this->ch_stat |= CH_STAT_ACTIVE | CH_STAT_RUN;
this->start();
}
} else {
this->abort();
this->update_irq();
new_stat &= ~CH_STAT_ACTIVE;
new_stat &= ~CH_STAT_DEAD;
this->cmd_in_progress = false;
this->ch_stat = new_stat;
if (this->ch_stat & CH_STAT_ACTIVE) {
this->abort();
this->update_irq(this->cur_host->cmd_bits);
this->cmd_in_progress = false;
}
this->ch_stat &= ~(CH_STAT_RUN | CH_STAT_ACTIVE | CH_STAT_DEAD);
}
} else if ((new_stat & CH_STAT_WAKE) != (old_stat & CH_STAT_WAKE)) {
if (new_stat & CH_STAT_WAKE) {
new_stat |= CH_STAT_ACTIVE;
this->ch_stat = new_stat;
} else if (mask & CH_STAT_PAUSE) {
if (data & CH_STAT_PAUSE) {
if (this->ch_stat & CH_STAT_ACTIVE)
this->pause();
this->ch_stat |= CH_STAT_PAUSE;
this->ch_stat &= ~CH_STAT_ACTIVE;
} else {
this->ch_stat &= ~CH_STAT_PAUSE;
if (!(this->ch_stat & CH_STAT_ACTIVE) && this->is_paused) {
this->is_paused = false;
this->ch_stat |= CH_STAT_ACTIVE;
this->resume();
}
}
} else if (mask & CH_STAT_WAKE) {
if (data & CH_STAT_WAKE && !(this->ch_stat & CH_STAT_ACTIVE)) {
this->ch_stat |= CH_STAT_ACTIVE;
this->resume();
} else {
LOG_F(ERROR, "%s: Attempt to clear wake status bit 0x%04x", this->get_name().c_str(), CH_STAT_WAKE);
}
} else if ((new_stat & CH_STAT_PAUSE) != (old_stat & CH_STAT_PAUSE)) {
if (new_stat & CH_STAT_PAUSE) {
new_stat &= ~CH_STAT_ACTIVE;
this->ch_stat = new_stat;
this->pause();
}
}
break;
@@ -409,11 +432,12 @@ void DMAChannel::reg_write(uint32_t offset, uint32_t value, int size) {
}
break;
case DMAReg::CMD_PTR_LO:
if (!(this->ch_stat & CH_STAT_RUN) && !(this->ch_stat & CH_STAT_ACTIVE)) {
if (!(this->ch_stat & CH_STAT_ACTIVE)) { // DBDMA spec 5.5.4 (disagrees with 2.9.1.3)
this->cmd_ptr = value;
LOG_F(9, "%s: CommandPtrLo set to 0x%X", this->get_name().c_str(),
this->cmd_ptr);
}
LOG_F(9, "%s: CommandPtrLo set to 0x%X%s", this->get_name().c_str(),
this->cmd_ptr, (this->ch_stat & CH_STAT_RUN) ? " while running!" : "");
} else
LOG_F(WARNING, "%s: CommandPtrLo update skipped", this->get_name().c_str());
break;
case DMAReg::INT_SELECT:
this->int_select = value & 0xFF00FFUL;
@@ -436,9 +460,11 @@ void DMAChannel::xfer_from_device() {
this->xfer_dir = DMA_DIR_FROM_DEV;
int got_bytes = this->dev_obj->xfer_from(this->queue_data, this->queue_len);
if (got_bytes == this->queue_len) {
this->queue_len = 0;
int got_bytes = this->dev_obj->xfer_from(this, this->queue_data, this->queue_len);
this->queue_data += got_bytes;
this->res_count -= got_bytes;
this->queue_len -= got_bytes;
if (!this->queue_len) {
this->finish_cmd();
} else if (got_bytes) {
LOG_F(WARNING, "%s: got unexpected amount of data in xfer_from_device",
@@ -454,9 +480,11 @@ void DMAChannel::xfer_to_device() {
this->xfer_dir = DMA_DIR_TO_DEV;
int got_bytes = this->dev_obj->xfer_to(this->queue_data, this->queue_len);
if (got_bytes == this->queue_len) {
this->queue_len = 0;
int got_bytes = this->dev_obj->xfer_to(this, this->queue_data, this->queue_len);
this->queue_data += got_bytes;
this->res_count -= got_bytes;
this->queue_len -= got_bytes;
if (!this->queue_len) {
this->finish_cmd();
}
@@ -473,9 +501,10 @@ void DMAChannel::xfer_retry() {
this->xfer_to_device();
}
bool DMAChannel::is_ready() {
if (this->ch_stat & CH_STAT_DEAD || !(this->ch_stat & CH_STAT_ACTIVE) ||
this->xfer_dir == DMA_DIR_UNDEF || this->cur_cmd >= DBDMA_Cmd::NOP)
bool DMAChannel::dma_is_ready() {
if (!this->is_active() ||
this->xfer_dir == DMA_DIR_UNDEF || this->cur_cmd >= DBDMA_Cmd::NOP
)
return false;
return true;
@@ -485,7 +514,7 @@ DmaPullResult DMAChannel::pull_data(uint32_t req_len, uint32_t *avail_len, uint8
{
*avail_len = 0;
if (this->ch_stat & CH_STAT_DEAD || !(this->ch_stat & CH_STAT_ACTIVE)) {
if (!this->is_active()) {
// dead or idle channel? -> no more data
LOG_F(WARNING, "%s: Dead/idle channel -> no more data", this->get_name().c_str());
return DmaPullResult::NoMoreData;
@@ -503,14 +532,14 @@ DmaPullResult DMAChannel::pull_data(uint32_t req_len, uint32_t *avail_len, uint8
*p_data = this->queue_data;
*avail_len = req_len;
this->queue_len -= req_len;
this->res_count += req_len;
this->res_count -= req_len;
this->queue_data += req_len;
} else { // return less data than req_len
LOG_F(9, "%s: Return queue_len = %d data", this->get_name().c_str(),
this->queue_len);
*p_data = this->queue_data;
*avail_len = this->queue_len;
this->res_count += this->queue_len;
this->res_count -= this->queue_len;
this->queue_len = 0;
}
return DmaPullResult::MoreData; // tell the caller there is more data
@@ -519,11 +548,11 @@ DmaPullResult DMAChannel::pull_data(uint32_t req_len, uint32_t *avail_len, uint8
return DmaPullResult::NoMoreData; // tell the caller there is no more data
}
int DMAChannel::push_data(const char* src_ptr, int len) {
if (this->ch_stat & CH_STAT_DEAD || !(this->ch_stat & CH_STAT_ACTIVE)) {
LOG_F(WARNING, "%s: attempt to push data to dead/idle channel",
DmaPushResult DMAChannel::push_data(const char* src_ptr, int len) {
if (!this->is_active()) {
LOG_F(WARNING, "%s: Attempt to push data to dead/idle channel",
this->get_name().c_str());
return -1;
return DmaPushResult::NoData;
}
// interpret DBDMA program until we get buffer to fill in or become idle
@@ -535,7 +564,7 @@ int DMAChannel::push_data(const char* src_ptr, int len) {
len = std::min((int)this->queue_len, len);
std::memcpy(this->queue_data, src_ptr, len);
this->queue_data += len;
this->res_count += len;
this->res_count -= len;
this->queue_len -= len;
}
@@ -544,11 +573,11 @@ int DMAChannel::push_data(const char* src_ptr, int len) {
this->interpret_cmd();
}
return 0;
return DmaPushResult::PushedData;
}
void DMAChannel::end_pull_data() {
if (this->ch_stat & CH_STAT_DEAD || !(this->ch_stat & CH_STAT_ACTIVE)) {
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());
@@ -566,7 +595,7 @@ void DMAChannel::end_pull_data() {
}
void DMAChannel::end_push_data() {
if (this->ch_stat & CH_STAT_DEAD || !(this->ch_stat & CH_STAT_ACTIVE)) {
if (!this->is_active()) {
LOG_F(WARNING, "%s: Attempt to end push data to dead/idle channel",
this->get_name().c_str());
return;
@@ -583,16 +612,15 @@ void DMAChannel::end_push_data() {
}
bool DMAChannel::is_out_active() {
if (this->ch_stat & CH_STAT_DEAD || !(this->ch_stat & CH_STAT_ACTIVE)) {
return false;
}
else {
return true;
}
return this->is_active();
}
bool DMAChannel::is_in_active() {
if (this->ch_stat & CH_STAT_DEAD || !(this->ch_stat & CH_STAT_ACTIVE)) {
return this->is_active();
}
bool DMAChannel::is_active() {
if ((this->ch_stat & CH_STAT_DEAD) || !(this->ch_stat & CH_STAT_ACTIVE)) {
return false;
}
else {
@@ -612,6 +640,9 @@ void DMAChannel::start() {
this->cmd_in_progress = false;
if (this->dev_obj != nullptr)
this->dev_obj->notify(this, DMA_MSG_START);
if (this->start_cb)
this->start_cb();
@@ -619,9 +650,8 @@ void DMAChannel::start() {
// 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->ch_stat & CH_STAT_DEAD) &&
(this->ch_stat & CH_STAT_ACTIVE)) {
this->interpret_cmd();
while (!this->cmd_in_progress && this->is_active()) {
this->interpret_cmd();
}
}
@@ -638,20 +668,24 @@ void DMAChannel::resume() {
// 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->ch_stat & CH_STAT_DEAD) &&
(this->ch_stat & CH_STAT_ACTIVE)) {
this->interpret_cmd();
while (!this->cmd_in_progress && this->is_active()) {
this->interpret_cmd();
}
}
void DMAChannel::abort() {
LOG_F(9, "%s: Aborting DMA channel", this->get_name().c_str());
if (this->dev_obj != nullptr)
this->dev_obj->notify(this, DMA_MSG_STOP);
if (this->stop_cb)
this->stop_cb();
}
void DMAChannel::pause() {
LOG_F(INFO, "%s: Pausing DMA channel", this->get_name().c_str());
if (this->dev_obj != nullptr)
this->dev_obj->notify(this, DMA_MSG_STOP);
if (this->stop_cb)
this->stop_cb();
this->is_paused = true;
}
+19 -6
View File
@@ -112,18 +112,25 @@ public:
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);
void set_stat(uint8_t new_stat) { this->ch_stat = (this->ch_stat & 0xff00) | new_stat; }
void set_stat(uint8_t new_stat) {
this->ch_stat = (this->ch_stat & 0xff00) | new_stat;
}
void update_ch_stat(uint8_t mask, uint8_t new_val) {
this->ch_stat = (this->ch_stat & ~mask) | new_val;
}
bool is_out_active() override;
bool is_in_active() override;
DmaPullResult pull_data(uint32_t req_len, uint32_t *avail_len, uint8_t **p_data) override;
int push_data(const char* src_ptr, int len) 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 is_ready() override;
bool dma_is_ready() override;
void xfer_retry() override;
void register_dma_int(InterruptCtrl* int_ctrl_obj, uint64_t irq_id) {
@@ -133,10 +140,11 @@ public:
protected:
DMACmd* fetch_cmd(uint32_t cmd_addr, DMACmd* p_cmd, bool *is_writable);
uint8_t interpret_cmd(void);
void interpret_cmd(void);
void update_cmd();
void finish_cmd();
void xfer_quad(const DMACmd *cmd_desc, DMACmd *cmd_host);
void update_irq();
void xfer_quad(bool is_store);
void update_irq(uint8_t cmd_bits);
void xfer_from_device();
void xfer_to_device();
@@ -145,6 +153,8 @@ protected:
void abort(void);
void pause(void);
bool is_active();
private:
std::function<void(void)> start_cb = nullptr; // DMA channel start callback
std::function<void(void)> stop_cb = nullptr; // DMA channel stop callback
@@ -162,7 +172,10 @@ private:
uint32_t wait_select = 0;
bool cmd_in_progress = false;
bool is_paused = false;
uint8_t cur_cmd;
DMACmd * cur_host = nullptr; // host virtual address of current command
bool cur_is_writable = false; // current command is writable
// Interrupt related stuff
InterruptCtrl* int_ctrl = nullptr;
+41 -13
View File
@@ -33,6 +33,11 @@ enum DmaPullResult : int {
NoMoreData, // data source has no more data to be pulled
};
enum DmaPushResult : int {
NoData = -1, // data source is not running
PushedData = 0, // data was pushed
};
class DmaOutChannel {
public:
DmaOutChannel(std::string name) { this->name = name; }
@@ -54,7 +59,7 @@ public:
DmaInChannel(std::string name) { this->name = name; }
virtual bool is_in_active() { return true; }
virtual int push_data(const char* src_ptr, int len) = 0;
virtual DmaPushResult push_data(const char* src_ptr, int len) = 0;
virtual int get_push_data_remaining() { return 1; }
virtual void end_push_data() {}
@@ -77,12 +82,23 @@ private:
};
// ---------------------- New DMA API -------------------------
enum DmaMsg : unsigned {
CH_START = 1,
CH_STOP,
DATA_AVAIL,
/** DMA channel types. */
enum DmaChannelType : unsigned {
DMA_CH_TYPE_UNDEF = 0,
DMA_CH_TYPE_IN, // unidirectional channel, host <--- device
DMA_CH_TYPE_OUT, // unidirectional channel, host ---> device
DMA_CH_TYPE_BIDIR, // bidirectional channel, host <--> device
};
/** DMA messages. */
enum DmaMsg : unsigned {
DMA_MSG_START = 1,
DMA_MSG_STOP,
DMA_MSG_FLUSH,
DMA_MSG_DATA_AVAIL,
};
/** DMA transfer direction constants. */
enum XferDir : unsigned {
DMA_DIR_UNDEF = 0,
DMA_DIR_TO_DEV,
@@ -97,10 +113,10 @@ public:
~DmaDevice() = default;
virtual void connect(DmaChannel *ch_obj) { this->channel_obj = ch_obj; }
virtual void notify(DmaMsg msg) {}
virtual int xfer_from(uint8_t *buf, int len) { return len; }
virtual int xfer_to(uint8_t *buf, int len) { return len; }
virtual int tell_xfer_size() { return 0; }
virtual void notify(DmaChannel *ch_obj, DmaMsg msg) {}
virtual int xfer_from(DmaChannel *ch_obj, uint8_t *buf, int len) { return len; }
virtual int xfer_to(DmaChannel *ch_obj, uint8_t *buf, int len) { return len; }
virtual int tell_xfer_size(DmaChannel *ch_obj) { return 0; }
protected:
DmaChannel* channel_obj = nullptr;
@@ -108,17 +124,29 @@ protected:
class DmaChannel {
public:
DmaChannel() = default;
DmaChannel(const uint32_t id = 1) { this->ch_id = id; }
DmaChannel(const DmaChannelType type, const uint32_t id = 1) {
this->ch_type = type;
this->ch_id = id;
}
~DmaChannel() = default;
// setters/getters
void set_id(const uint32_t id) { this->ch_id = id; }
uint32_t get_id() { return this->ch_id; }
void set_type(const DmaChannelType type) { this->ch_type = type; }
virtual void connect(DmaDevice *dev_obj) { this->dev_obj = dev_obj; }
virtual void notify(DmaMsg msg) {}
virtual bool is_ready() { return false; }
virtual bool dma_is_ready() { return false; }
virtual void xfer_retry() {}
protected:
DmaDevice* dev_obj = nullptr;
XferDir xfer_dir = DMA_DIR_UNDEF;
DmaDevice* dev_obj = nullptr;
uint32_t ch_id = 0; // support for several channels per device
DmaChannelType ch_type = DMA_CH_TYPE_BIDIR;
XferDir xfer_dir = DMA_DIR_UNDEF;
};
/*
+1
View File
@@ -93,6 +93,7 @@ enum IntSrc : uint32_t {
SLOT_PDS,
SLOT_VDS,
VBL,
VALKYRIE,
};
/** Base class for interrupt controllers. */
+1 -1
View File
@@ -19,12 +19,12 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <core/memaccess.h>
#include <devices/common/hwcomponent.h>
#include <devices/common/nubus/nubusutils.h>
#include <devices/memctrl/memctrlbase.h>
#include <machines/machinebase.h>
#include <loguru.hpp>
#include <memaccess.h>
#include <cinttypes>
#include <fstream>
+15 -14
View File
@@ -21,11 +21,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** Utilities for working with Apple Open Firmware and CHRP NVRAM partitions. */
#include <core/endianswap.h>
#include <core/memaccess.h>
#include <devices/common/ofnvram.h>
#include <devices/common/nvram.h>
#include <endianswap.h>
#include <machines/machinebase.h>
#include <memaccess.h>
#include <cinttypes>
#include <cstring>
@@ -85,7 +85,7 @@ bool OfConfigAppl::validate() {
}
// verify partition checksum
if (this->checksum_partition() ^ 0xFFFFU)
if (this->checksum_partition() != 0xFFFFU)
return false;
return true;
@@ -101,7 +101,7 @@ uint16_t OfConfigAppl::checksum_partition() {
return acc + (acc >> 16);
}
static const string flag_names[8] = {
static const string flag_names[] = {
"little-endian?",
"real-mode?",
"auto-boot?",
@@ -109,8 +109,10 @@ static const string flag_names[8] = {
"fcode-debug?",
"oem-banner?",
"oem-logo?",
"use-nvramrc?"
"use-nvramrc?",
"f-segment?" // ANS only
};
constexpr int num_flags = sizeof(flag_names) / sizeof(flag_names[0]);
static const map<string, std::tuple<int, uint16_t>> of_vars = {
// name, type, offset
@@ -141,12 +143,12 @@ const OfConfigImpl::config_dict& OfConfigAppl::get_config_vars() {
if (!this->validate())
return _config_vars;
uint8_t of_flags = this->buf[12];
uint32_t of_flags = READ_DWORD_BE_A(&this->buf[12]);
// populate flags
for (int i = 0; i < 8; i++) {
for (unsigned i = 0; i < num_flags; i++) {
_config_vars.push_back(std::make_pair(flag_names[i],
((of_flags << i) & 0x80) ? "true" : "false"));
(int32_t(of_flags << i) < 0) ? "true" : "false"));
}
// populate the remaining variables
@@ -187,7 +189,7 @@ void OfConfigAppl::update_partition() {
// calculate new checksum
uint16_t checksum = this->checksum_partition();
checksum = checksum ? ~checksum : 0xFFFFU;
checksum = ~checksum;
// stuff checksum into the header
WRITE_WORD_BE_A(&this->buf[4], checksum);
@@ -205,7 +207,7 @@ bool OfConfigAppl::set_var(std::string& var_name, std::string& value) {
return false;
// check if the user tries to change a flag
for (i = 0; i < 8; i++) {
for (i = 0; i < num_flags; i++) {
if (var_name == flag_names[i]) {
if (value == "true")
flag = 1;
@@ -215,15 +217,15 @@ bool OfConfigAppl::set_var(std::string& var_name, std::string& value) {
cout << "Invalid property value: " << value << endl;
return false;
}
uint8_t flag_bit = 0x80U >> i;
uint8_t of_flags = this->buf[12];
uint32_t flag_bit = 0x80000000U >> i;
uint32_t of_flags = READ_DWORD_BE_A(&this->buf[12]);
if (flag)
of_flags |= flag_bit;
else
of_flags &= ~flag_bit;
this->buf[12] = of_flags;
WRITE_DWORD_BE_A(&this->buf[12], of_flags);
this->update_partition();
return true;
}
@@ -248,7 +250,6 @@ bool OfConfigAppl::set_var(std::string& var_name, std::string& value) {
}
WRITE_DWORD_BE_A(&this->buf[offset], num);
this->update_partition();
cout << " ok" << endl; // mimic Forth
} else {
uint16_t str_offset = READ_WORD_BE_A(&this->buf[offset]);
uint16_t str_len = READ_WORD_BE_A(&this->buf[offset+2]);
+1 -1
View File
@@ -21,10 +21,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** Bandit/Chaos ARBus-to-PCI Bridge emulation. */
#include <core/endianswap.h>
#include <devices/common/pci/bandit.h>
#include <devices/deviceregistry.h>
#include <devices/memctrl/memctrlbase.h>
#include <endianswap.h>
#include <loguru.hpp>
#include <machines/machinebase.h>
+19 -2
View File
@@ -28,6 +28,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cinttypes>
enum YosemiteGpioMask: uint8_t {
GPIO_FWDET = 2, // FireWire detect
};
DecPciBridge::DecPciBridge(std::string name) : PCIBridge(name)
{
supports_types(HWCompType::PCI_HOST | HWCompType::PCI_DEV);
@@ -51,7 +55,7 @@ uint32_t DecPciBridge::pci_cfg_read(uint32_t reg_offs, AccessDetails &details)
case CHIP_CTRL:
return (this->arb_ctrl << 16) | (this-> diag_ctrl << 8) | this->chip_ctrl;
case PSERR_EVENT_DIS:
return (this->gpio_out_en << 16) | this->pserr_event_dis;
return (this->gpio_out_en << 16) | (this->gpio_out_data << 8) | this->pserr_event_dis;
case SEC_CLK_CTRL:
return this->sec_clock_ctrl;
default:
@@ -75,8 +79,21 @@ void DecPciBridge::pci_cfg_write(uint32_t reg_offs, uint32_t value, AccessDetail
this->arb_ctrl = value >> 16;
break;
case PSERR_EVENT_DIS:
this->pserr_event_dis = value & 0xFFU;
this->pserr_event_dis = value & 0x7EU;
this->gpio_out_data = (value >> 8) & 0xFFU;
this->gpio_out_en = (value >> 16) & 0xFFU;
{
uint8_t bits_to_set = gpio_out_data >> 4;
uint8_t bits_to_clr = gpio_out_data & 0xFU;
this->gpio_out_data_val |= bits_to_set;
this->gpio_out_data_val &= ~bits_to_clr;
}
{
uint8_t bits_to_set = gpio_out_en >> 4;
uint8_t bits_to_clr = gpio_out_en & 0xFU;
this->gpio_out_en_val |= bits_to_set;
this->gpio_out_en_val &= ~bits_to_clr;
}
break;
case SEC_CLK_CTRL:
this->sec_clock_ctrl = value & 0xFFFFU;
+2
View File
@@ -61,6 +61,8 @@ private:
uint8_t gpio_out_en = 0;
uint8_t gpio_in_data = 0;
uint16_t sec_clock_ctrl = 0;
uint8_t gpio_out_data_val = 0;
uint8_t gpio_out_en_val = 0;
};
#endif // DEC_P2P_H
+2 -2
View File
@@ -19,10 +19,10 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <core/endianswap.h>
#include <core/memaccess.h>
#include <devices/common/pci/pcibase.h>
#include <endianswap.h>
#include <loguru.hpp>
#include <memaccess.h>
#include <cinttypes>
#include <fstream>
+1 -1
View File
@@ -19,8 +19,8 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <core/memaccess.h>
#include <devices/common/pci/pcibridgebase.h>
#include <memaccess.h>
PCIBridgeBase::PCIBridgeBase(std::string name, PCIHeaderType hdr_type, int num_bars) : PCIBase(name, hdr_type, num_bars)
{
+21 -3
View File
@@ -19,8 +19,8 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <core/memaccess.h>
#include <devices/common/pci/pcicardbusbridge.h>
#include <memaccess.h>
typedef struct {
// CardBus Registers
@@ -155,6 +155,10 @@ uint32_t PCICardbusBridge::pci_cfg_read(uint32_t reg_offs, AccessDetails &detail
return (this->subsys_id << 16) | (this->subsys_vndr);
case PCI_CFG_CB_LEGACY_MODE_BASE:
return this->legacy_mode_base;
case PCI_CFG_CB_SOCKET_DMA_0:
return this->dreq_pin;
case PCI_CFG_CB_SOCKET_DMA_1:
return this->dma_base;
default:
return PCIBridgeBase::pci_cfg_read(reg_offs, details);
}
@@ -193,11 +197,19 @@ void PCICardbusBridge::pci_cfg_write(uint32_t reg_offs, uint32_t value, AccessDe
case PCI_CFG_CB_IO_LIMIT_1:
this->pci_wr_io_limit_0(value);
break;
/*
#if 0
// FIXME: handle legacy_mode_base and dma_base changes here
case PCI_CFG_CB_LEGACY_MODE_BASE:
this->legacy_mode_base = value;
break;
*/
case PCI_CFG_CB_SOCKET_DMA_0:
this->dreq_pin = value & DREQ_PIN_MASK;
break;
case PCI_CFG_CB_SOCKET_DMA_1:
this->dma_base = (value & DDMA_EXTMODE_MASK) | (value & (0xFFFF & ~DDMA_EXTMODE_MASK));
break;
#endif
default:
PCIBridgeBase::pci_cfg_write(reg_offs, value, details);
break;
@@ -210,6 +222,9 @@ bool PCICardbusBridge::pci_io_read(uint32_t offset, uint32_t size, uint32_t* res
if ((offset < this->io_base_0_32 || offset + size >= this->io_limit_0_32) &&
(offset < this->io_base_1_32 || offset + size >= this->io_limit_1_32)
) return false;
#if 0
// FIXME: check legacy_mode_base and dma_base here
#endif
return this->pci_io_read_loop(offset, size, *res);
}
@@ -219,5 +234,8 @@ bool PCICardbusBridge::pci_io_write(uint32_t offset, uint32_t value, uint32_t si
if ((offset < this->io_base_0_32 || offset + size >= this->io_limit_0_32) &&
(offset < this->io_base_1_32 || offset + size >= this->io_limit_1_32)
) return false;
#if 0
// FIXME: check legacy_mode_base and dma_base here
#endif
return this->pci_io_write_loop(offset, size, value);
}
+24
View File
@@ -44,6 +44,28 @@ enum {
PCI_CFG_CB_IO_LIMIT_1 = 0x38,
PCI_CFG_CB_SUBSYSTEM_IDS = 0x40, // CB_SUBSYSTEM_VENDOR_ID.w, CB_SUBSYSTEM_ID.w
PCI_CFG_CB_LEGACY_MODE_BASE = 0x44,
PCI_CFG_CB_SOCKET_DMA_0 = 0x94,
PCI_CFG_CB_SOCKET_DMA_1 = 0x98,
};
/** PC Card bits */
enum {
DREQ_PIN_MASK = 3,
DREQ_NO_DMA = 0, // 0 = Socket is not configured for DMA
DREQ_USES_SPKR = 1,
DREQ_USES_IOIS16 = 2,
DREQ_USES_INPACK = 3,
DDMA_BASE_MASK = (0xFFF0),
DDMA_EXTMODE_MASK = (1 << 3),
DDMA_EXTMODE_DISABLE = (0 << 3),
DDMA_EXTMODE_ENABLE = (1 << 3),
DDMA_XFERSIZE_8_BITS = (0 << 1),
DDMA_XFERSIZE_16_BITS = (1 << 1),
DDMA_XFERSIZE_2 = (2 << 1),
DDMA_XFERSIZE_3 = (3 << 1),
DDMA_ENABLE = (1 << 0),
DDMA_DISABLE = (0 << 0),
};
class PCICardbusBridge : public PCIBridgeBase {
@@ -89,6 +111,8 @@ protected:
uint16_t subsys_id = 0;
uint16_t subsys_vndr = 0;
uint32_t legacy_mode_base = 0;
uint32_t dreq_pin = DREQ_NO_DMA;
uint32_t dma_base = 0 | DDMA_EXTMODE_DISABLE | DDMA_XFERSIZE_8_BITS | DDMA_DISABLE;
// 0 = not writable
uint32_t memory_0_cfg = 0xfffff000;
+1 -1
View File
@@ -19,13 +19,13 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <core/endianswap.h>
#include <devices/common/hwcomponent.h>
#include <devices/common/pci/pcibridge.h>
#include <devices/common/pci/pcihost.h>
#include <devices/deviceregistry.h>
#include <machines/machinefactory.h>
#include <machines/machinebase.h>
#include <endianswap.h>
#include <loguru.hpp>
#include <cinttypes>
+13 -2
View File
@@ -23,9 +23,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#define PCI_HOST_H
#include <core/bitops.h>
#include <core/endianswap.h>
#include <devices/common/hwinterrupt.h>
#include <devices/memctrl/memctrlbase.h>
#include <endianswap.h>
#include <cinttypes>
#include <string>
@@ -110,7 +110,8 @@ protected:
// Helpers for data conversion in the PCI Configuration space.
/**
Perform size dependent endian swapping for value that is dword from PCI config or any other dword little endian register.
Perform size dependent endian swapping for value that is dword from PCI config
or any other dword little endian register.
Unaligned data is handled properly by using bytes from the next dword.
*/
@@ -198,4 +199,14 @@ inline uint32_t pci_conv_wr_data(uint32_t v1, uint32_t v2, AccessDetails &detail
}
}
/** Merge val_hi and val_lo into a QWORD, then extract a portion
indicated by pos and size and return the right-justified result.
This macro is a variant of pci_conv_rd_data() with less code
aiming to simplify spanning reads from PCI registers.
No endian swappping is performed.
*/
#define REG_READ_HELPER(val_hi, val_lo, pos, size) \
((((uint64_t)(val_hi) << 32) | (val_lo)) >> (8 - (pos) - (size)) * 8) & \
((1ULL << ((size) * 8)) - 1) // apply size-dependent mask
#endif /* PCI_HOST_H */
+86 -136
View File
@@ -84,54 +84,67 @@ void Sc53C94::reset_device()
uint8_t Sc53C94::read(uint8_t reg_offset)
{
uint8_t bus_phase, int_flags;
uint8_t value;
switch (reg_offset) {
case Read::Reg53C94::Xfer_Cnt_LSB:
return this->xfer_count & 0xFFU;
value = this->xfer_count & 0xFFU;
break;
case Read::Reg53C94::Xfer_Cnt_MSB:
return (this->xfer_count >> 8) & 0xFFU;
value = (this->xfer_count >> 8) & 0xFFU;
break;
case Read::Reg53C94::FIFO:
return this->fifo_pop();
value = this->fifo_pop();
break;
case Read::Reg53C94::Command:
return this->cmd_fifo[0];
case Read::Reg53C94::Status:
if (this->config2 & CFG2_ENF) {
static bool log_it = true;
if (log_it) {
LOG_F(WARNING, "%s: phase latch not implemented", this->name.c_str());
log_it = false;
}
bus_phase = SCSI_CTRL_MSG; // use reserved bus phase
} else
value = this->cmd_fifo[0];
break;
case Read::Reg53C94::Status: {
uint8_t bus_phase;
if (this->config2 & CFG2_ENF)
bus_phase = this->phase_latch;
else
bus_phase = bus_obj->test_ctrl_lines(SCSI_CTRL_MSG | SCSI_CTRL_CD | SCSI_CTRL_IO);
return (this->status & 0xF8) | bus_phase;
value = (this->status & 0xF8) | bus_phase;
break;
}
case Read::Reg53C94::Int_Status:
int_flags = this->int_status;
value = this->int_status;
if (this->irq) {
this->status &= ~(STAT_GE | STAT_PE | STAT_GCV);
this->int_status = 0;
this->seq_step = 0;
}
if (this->phase_latch_closed)
this->phase_latch_closed = false; // open the bus phase latch
this->update_irq();
return int_flags;
break;
case Read::Reg53C94::Seq_Step:
return this->seq_step;
value = this->seq_step;
break;
case Read::Reg53C94::FIFO_Flags:
return (this->cur_step << 5) | (this->data_fifo_pos & 0x1F);
value = (this->cur_step << 5) | (this->data_fifo_pos & 0x1F);
break;
case Read::Reg53C94::Config_1:
return this->config1;
value = this->config1;
break;
case Read::Reg53C94::Config_3:
return this->config3;
value = this->config3;
break;
case Read::Reg53C94::Config_4:
value = this->config4;
break;
case Read::Reg53C94::Xfer_Cnt_Hi:
if (this->config2 & CFG2_ENF) {
return (this->xfer_count >> 16) & 0xFFU;
value = (this->xfer_count >> 16) & 0xFFU;
} else {
value = 0;
}
break;
default:
LOG_F(INFO, "%s: reading from register %d", this->name.c_str(), reg_offset);
}
return 0;
return value;
}
void Sc53C94::write(uint8_t reg_offset, uint8_t value)
@@ -176,8 +189,13 @@ void Sc53C94::write(uint8_t reg_offset, uint8_t value)
case Write::Reg53C94::Config_3:
this->config3 = value;
break;
case Write::Reg53C94::Config_4:
this->config4 = value;
if (value)
LOG_F(WARNING, "%s: config 4 set to 0x%X", this->name.c_str(), value);
break;
default:
LOG_F(INFO, "%s: writing 0x%X to %d register", this->name.c_str(), value,
LOG_F(INFO, "%s: writing 0x%X to register # %d", this->name.c_str(), value,
reg_offset);
}
}
@@ -346,8 +364,10 @@ void Sc53C94::exec_command()
if (this->is_initiator) {
this->bus_obj->target_next_step();
}
this->int_status |= INTSTAT_SR;
this->update_irq();
// SCSI Manager expects this function to generate an interrupt.
// Don't set INTSTAT_SR or INISTAT_SO bits - that will confuse
// the SCSI driver in Open Firmware!
// Let's hope the target hung up already causing INTSTAT_DIS to be set.
exec_next_command();
break;
case CMD_XFER_PAD_BYTES:
@@ -538,6 +558,7 @@ void Sc53C94::sequencer()
break;
case SeqState::SEND_MSG:
case SeqState::SEND_MSG_EX:
this->is_dma_xfer = this->is_dma_cmd;
if (this->data_fifo_pos < 1 && this->is_dma_cmd) {
if (this->drq_cb)
this->drq_cb(1);
@@ -553,6 +574,7 @@ void Sc53C94::sequencer()
}
break;
case SeqState::SEND_CMD:
this->is_dma_xfer = this->is_dma_cmd;
if (this->data_fifo_pos < 1 && this->is_dma_cmd) {
if (this->drq_cb)
this->drq_cb(1);
@@ -560,25 +582,29 @@ void Sc53C94::sequencer()
this->bus_obj->target_xfer_data();
break;
case SeqState::CMD_COMPLETE:
this->is_dma_xfer = false;
this->cur_state = SeqState::IDLE;
this->update_phase_latch();
this->update_irq();
exec_next_command();
break;
case SeqState::XFER_BEGIN:
this->is_dma_xfer = this->is_dma_cmd;
this->cur_bus_phase = this->bus_obj->current_phase();
switch (this->cur_bus_phase) {
case ScsiPhase::DATA_OUT:
if (this->is_dma_cmd && this->channel_obj->is_ready()) {
this->channel_obj->xfer_retry();
break;
if (this->is_dma_cmd) {
if (this->channel_obj->dma_is_ready())
this->channel_obj->xfer_retry();
} else {
this->bus_obj->push_data(this->target_id, this->data_fifo, this->data_fifo_pos);
this->data_fifo_pos = 0;
this->cur_state = SeqState::XFER_END;
this->sequencer();
}
this->bus_obj->push_data(this->target_id, this->data_fifo, this->data_fifo_pos);
this->data_fifo_pos = 0;
this->cur_state = SeqState::XFER_END;
this->sequencer();
break;
case ScsiPhase::DATA_IN:
if (this->is_dma_cmd && this->channel_obj->is_ready()) {
if (this->is_dma_cmd && this->channel_obj->dma_is_ready()) {
this->channel_obj->xfer_retry();
break;
}
@@ -603,11 +629,13 @@ void Sc53C94::sequencer()
}
break;
case SeqState::XFER_END:
this->is_dma_xfer = false;
if (this->is_initiator) {
this->bus_obj->target_next_step();
}
this->int_status = INTSTAT_SR;
this->cur_state = SeqState::IDLE;
this->update_phase_latch();
this->int_status = INTSTAT_SR;
this->update_irq();
exec_next_command();
break;
@@ -620,11 +648,13 @@ void Sc53C94::sequencer()
this->int_status = INTSTAT_SR;
this->update_irq();
} else {
this->is_dma_xfer = this->is_dma_cmd;
this->rcv_data();
}
break;
case SeqState::RCV_STATUS:
case SeqState::RCV_MESSAGE:
this->is_dma_xfer = this->is_dma_cmd;
this->rcv_data();
if (this->is_initiator) {
if (this->cur_state == SeqState::RCV_STATUS) {
@@ -659,6 +689,19 @@ void Sc53C94::update_irq()
}
}
void Sc53C94::update_phase_latch() {
if (this->config2 & CFG2_ENF) {
if (this->phase_latch_closed) {
LOG_F(WARNING, "%s: ignored update of the closed bus phase latch",
this->name.c_str());
} else {
this->phase_latch = bus_obj->test_ctrl_lines(
SCSI_CTRL_MSG | SCSI_CTRL_CD | SCSI_CTRL_IO);
this->phase_latch_closed = true;
}
}
}
void Sc53C94::notify(ScsiNotification notif_type, int param)
{
switch (notif_type) {
@@ -691,8 +734,10 @@ void Sc53C94::notify(ScsiNotification notif_type, int param)
this->seq_step = this->cur_step;
this->int_status = this->cmd_steps->status;
this->update_irq();
if (this->cmd_steps->next_state == SeqState::CMD_COMPLETE)
if (this->cmd_steps->next_state == SeqState::CMD_COMPLETE) {
this->update_phase_latch();
this->exec_next_command();
}
}
}
break;
@@ -745,108 +790,13 @@ bool Sc53C94::rcv_data()
return true;
}
void Sc53C94::real_dma_xfer_out()
{
// transfer data from host's memory to target
if (this->xfer_count) {
uint32_t got_bytes;
uint8_t* src_ptr;
this->dma_ch->pull_data(std::min((int)this->xfer_count, DATA_FIFO_MAX),
&got_bytes, &src_ptr);
std::memcpy(this->data_fifo, src_ptr, got_bytes);
this->data_fifo_pos = got_bytes;
this->bus_obj->push_data(this->target_id, this->data_fifo, this->data_fifo_pos);
this->xfer_count -= this->data_fifo_pos;
this->data_fifo_pos = 0;
if (!this->xfer_count) {
this->status |= STAT_TC; // signal zero transfer count
this->cur_state = SeqState::XFER_END;
this->sequencer();
}
}
if (this->xfer_count) {
this->dma_timer_id = TimerManager::get_instance()->add_oneshot_timer(
10000,
[this]() {
// re-enter the sequencer with the state specified in next_state
this->dma_timer_id = 0;
this->real_dma_xfer_out();
});
}
}
void Sc53C94::real_dma_xfer_in()
{
bool is_done = false;
// transfer data from target to host's memory
if (this->xfer_count && this->data_fifo_pos) {
this->dma_ch->push_data((char*)this->data_fifo, this->data_fifo_pos);
this->xfer_count -= this->data_fifo_pos;
this->data_fifo_pos = 0;
if (!this->xfer_count) {
is_done = true;
this->status |= STAT_TC; // signal zero transfer count
this->cur_state = SeqState::XFER_END;
this->sequencer();
}
}
// see if we need to refill FIFO
if (!this->data_fifo_pos && !is_done) {
this->sequencer();
this->dma_timer_id = TimerManager::get_instance()->add_oneshot_timer(
10000,
[this]() {
// re-enter the sequencer with the state specified in next_state
this->dma_timer_id = 0;
this->real_dma_xfer_in();
});
}
}
void Sc53C94::dma_wait() {
if (this->cur_bus_phase == ScsiPhase::DATA_IN && this->cur_state == SeqState::RCV_DATA) {
real_dma_xfer_in();
}
else if (this->cur_bus_phase == ScsiPhase::DATA_OUT && this->cur_state == SeqState::SEND_DATA) {
real_dma_xfer_out();
}
else {
this->dma_timer_id = TimerManager::get_instance()->add_oneshot_timer(
10000,
[this]() {
this->dma_timer_id = 0;
this->dma_wait();
});
}
}
void Sc53C94::dma_start()
{
dma_wait();
}
void Sc53C94::dma_stop()
{
if (this->dma_timer_id) {
TimerManager::get_instance()->cancel_timer(this->dma_timer_id);
this->dma_timer_id = 0;
}
}
int Sc53C94::xfer_from(uint8_t *buf, int len) {
int Sc53C94::xfer_from(DmaChannel *ch_obj, uint8_t *buf, int len) {
int bytes_moved = 0;
if (this->cur_cmd != CMD_XFER || !this->is_dma_cmd ||
this->cur_bus_phase != ScsiPhase::DATA_IN) {
LOG_F(9, "%s: ignoring DMA data transfer request", this->name.c_str());
return bytes_moved;
return 0;
}
len = std::min(len, (int)(this->xfer_count));
@@ -881,12 +831,12 @@ int Sc53C94::xfer_from(uint8_t *buf, int len) {
return bytes_moved;
}
int Sc53C94::xfer_to(uint8_t *buf, int len) {
int Sc53C94::xfer_to(DmaChannel *ch_obj, uint8_t *buf, int len) {
int bytes_moved = 0;
if (!this->xfer_count || !this->is_dma_cmd) {
if (!this->xfer_count || !this->is_dma_xfer) {
LOG_F(9, "%s: ignoring DMA data transfer request", this->name.c_str());
return bytes_moved;
return 0;
}
len = std::min(len, (int)(this->xfer_count));
+18 -29
View File
@@ -54,7 +54,7 @@ namespace Read {
//
Config_2 = 0xB, // Control Register 2
Config_3 = 0xC, // Control Register 3
Config_4 = 0xD, // Control Register 4
Config_4 = 0xD, // Control Register 4 ; Am53CF94 extension
Xfer_Cnt_Hi = 0xE, // Current Transfer Count Register High ; Am53CF94 extension
//
};
@@ -150,14 +150,16 @@ enum {
INTSTAT_SEL = 0x01, // selected as a target without attention
};
/** Configuration register 1 bits. */
enum {
/** Configuration register 1 bit definitions. */
enum : uint8_t {
CFG1_DISR = 0x40, // disable interrupt on SCSI reset
};
/** Configuration register 2 bits. */
enum {
CFG2_ENF = 0x40, // Am53CF94: enable features (ENF) bit
/** Configuration register 2 bit definitions. */
enum : uint8_t {
CFG2_ENF = 0x40, // Am53CF94: enable extended chip features
// ASC: enable phase latch (EPL)
CFG2_S2FE = 0x08, // enable SCSI-2 features
};
/** Sequencer states. */
@@ -212,24 +214,6 @@ public:
uint16_t pseudo_dma_read();
void pseudo_dma_write(uint16_t data);
// real DMA control
void real_dma_xfer_out();
void real_dma_xfer_in();
void dma_start();
void dma_wait();
void dma_stop();
void set_dma_channel(DmaBidirChannel *dma_ch) {
this->dma_ch = dma_ch;
auto dbdma_ch = dynamic_cast<DMAChannel*>(dma_ch);
if (dbdma_ch) {
dbdma_ch->set_callbacks(
std::bind(&Sc53C94::dma_start, this),
std::bind(&Sc53C94::dma_stop, this)
);
}
}
void set_drq_callback(DrqCb cb) {
this->drq_cb = cb;
}
@@ -241,15 +225,16 @@ public:
void process_command() override {}
// DmaDevice methods
int xfer_from(uint8_t *buf, int len) override;
int xfer_to(uint8_t *buf, int len) override;
int tell_xfer_size() override {
int xfer_from(DmaChannel *ch_obj, uint8_t *buf, int len) override;
int xfer_to(DmaChannel *ch_obj, uint8_t *buf, int len) override;
int tell_xfer_size(DmaChannel *ch_obj) override {
return this->xfer_count;
}
protected:
void reset_device();
void update_command_reg(uint8_t cmd);
void update_phase_latch();
void exec_command();
void exec_next_command();
void fifo_push(const uint8_t data);
@@ -286,6 +271,11 @@ private:
uint8_t config1 = 0;
uint8_t config2 = 0;
uint8_t config3 = 0;
uint8_t config4 = 0;
// bus phase latch
bool phase_latch_closed = false;
uint8_t phase_latch = 0;
// sequencer state
uint32_t seq_timer_id = 0;
@@ -295,6 +285,7 @@ private:
bool is_initiator = false;
uint8_t cur_cmd = 0;
bool is_dma_cmd = false;
bool is_dma_xfer = false;
int cur_bus_phase = 0;
uint8_t cur_step = 0; // internal step counter for multistep commands
@@ -304,9 +295,7 @@ private:
uint8_t irq = 0;
// DMA related stuff
DmaBidirChannel* dma_ch = nullptr;
DrqCb drq_cb = nullptr;
uint32_t dma_timer_id = 0;
};
#endif // SC_53C94_H
+44 -15
View File
@@ -76,11 +76,36 @@ namespace ScsiStatus {
/** Standard message codes. */
namespace ScsiMessage {
enum : uint8_t {
COMMAND_COMPLETE = 0,
COMMAND_COMPLETE = 0x00,
EXTENDED_MESSAGE = 0x01,
SAVE_POINTERS = 0x02,
RESTORE_POINTERS = 0x03,
DISCONNECT = 0x04,
INITIATOR_ERROR = 0x05,
ABORT_TASK_SET = 0x06,
MESSAGE_REJECT = 0x07,
NOP = 0x08,
MSG_PARITY_ERROR = 0x09,
LINKED_CMD_COMPLETE = 0x0A,
LINKED_FLG_CMD_COMPLETE = 0x0B,
TARGET_RESET = 0x0C,
ABORT_TASK = 0x0D,
CLEAR_TASK_SET = 0x0E,
INITIATE_RECOVERY = 0x0F, // SCSI-II only
RELEASE_RECOVERY = 0x10, // SCSI-II only
TERMINATE_IO_PROC = 0x11, // SCSI-II only
CLEAR_ACA = 0x16,
LOGICAL_UNIT_RESET = 0x17,
SIMPLE_QUEUE_TAG = 0x20,
HEAD_OF_QUEUE_TAG = 0x21,
ORDERED_QUEUE_TAG = 0x22,
IGNORE_WIDE_RESIDUE = 0x23,
ACA = 0x24,
QAS_REQUEST = 0x55,
TARGET_ROUTINE_NUMBER_MASK = 0x07,
LOGICAL_UNIT_NUMBER_MASK = 0x07,
IS_TARGET_ROUTINE_NuMBER = 0x20,
IS_TARGET_ROUTINE_NUMBER = 0x20,
HAS_DISCONNECT_PRIVILEDGE = 0x40,
IDENTIFY = 0x80,
};
@@ -89,9 +114,12 @@ namespace ScsiMessage {
/** Extended message codes. */
namespace ScsiExtMessage {
enum : uint8_t {
MODIFY_DATA_PTR = 0,
SYNCH_XFER_REQ = 1,
WIDE_XFER_REQ = 3,
MODIFY_DATA_PTR = 0,
SYNCH_XFER_REQ = 1,
EXTENDED_IDENTIFY = 2, // SCSI-I only
WIDE_XFER_REQ = 3,
PPR_REQ = 4,
MODIFY_BIDI_DATA_PTR = 5,
};
}
@@ -106,8 +134,8 @@ enum ScsiCommand : uint8_t {
REWIND = 0x01,
REQ_SENSE = 0x03,
FORMAT_UNIT = 0x04,
READ_BLK_LIMITS = 0x05,
REASSIGN = 0x07,
READ_BLOCK_LIMITS = 0x05,
REASSIGN_BLOCKS = 0x07,
READ_6 = 0x08,
WRITE_6 = 0x0A,
SEEK_6 = 0x0B,
@@ -118,16 +146,16 @@ enum ScsiCommand : uint8_t {
ERASE_6 = 0x19,
MODE_SENSE_6 = 0x1A,
START_STOP_UNIT = 0x1B,
DIAG_RESULTS = 0x1C,
SEND_DIAGS = 0x1D,
RECEIVE_DIAG_RESULTS = 0x1C,
SEND_DIAGNOSTIC = 0x1D,
PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1E,
READ_CAPACITY = 0x25,
READ_10 = 0x28,
WRITE_10 = 0x2A,
SEEK_10 = 0x2B,
VERIFY_WRITE_10 = 0x2E,
WRITE_AND_VERIFY = 0x2E,
VERIFY_10 = 0x2F,
READ_LONG_10 = 0x35,
SYNC_CACHE = 0x35,
WRITE_BUFFER = 0x3B,
READ_BUFFER = 0x3C,
GET_CONFIG = 0x46,
@@ -143,6 +171,7 @@ enum ScsiCommand : uint8_t {
// CD-ROM specific commands
READ_TOC = 0x43,
SET_CD_SPEED = 0xBB,
PLAY_CD = 0xBC,
READ_CD = 0xBE,
};
@@ -219,7 +248,7 @@ enum ModePage : uint8_t {
DEV_FORMAT_PARAMS = 0x3,
RIGID_DISK_GEOMETRY = 0x4,
CDROM_PARAMS = 0xD,
CDROM_AUDIO = 0xE,
CDROM_AUDIO_CONTROL = 0xE,
POWER_CONDITION = 0x1A,
CDROM_CAPABILITIES = 0x2A,
VENDOR_PAGE_31 = 0x31,
@@ -278,12 +307,12 @@ public:
this->post_xfer_action = cb;
}
void set_status(uint8_t status_code) override {
void set_status(uint8_t status_code, uint8_t sense_key) override {
this->status = status_code;
}
void set_eject_state(bool eject_allowed) override {
this->eject_allowed = eject_allowed;
void set_lock_state(bool is_locked) override {
this->eject_allowed = !is_locked;
}
virtual void notify(ScsiNotification notif_type, int param);
+59 -32
View File
@@ -19,11 +19,11 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <core/memaccess.h>
#include <devices/common/scsi/scsiblockcmds.h>
#include <loguru.hpp>
#include <memaccess.h>
ScsiBlockCmds::ScsiBlockCmds(int cache_blocks) : BlockStorageDevice(cache_blocks) {
ScsiBlockCmds::ScsiBlockCmds() {
this->enable_cmd(ScsiCommand::READ_6);
this->enable_cmd(ScsiCommand::READ_10);
this->enable_cmd(ScsiCommand::READ_12);
@@ -38,27 +38,29 @@ ScsiBlockCmds::ScsiBlockCmds(int cache_blocks) : BlockStorageDevice(cache_blocks
&ScsiBlockCmds::get_error_recovery_page);
}
void ScsiBlockCmds::init_block_device(uint8_t medium_type, uint8_t dev_flags) {
void ScsiBlockCmds::init_block_device(uint8_t medium_type, uint8_t dev_flags,
uint8_t density_code, bool is_apple_compliant)
{
this->medium_type = medium_type;
this->device_flags = dev_flags;
phy_impl->set_read_more_data_cb(
[this](int* dsize, uint8_t** dptr) -> bool {
if (this->remain_size) {
*dsize = this->read_more();
*dptr = (uint8_t *)this->data_cache.get();
if (this->blk_dev->get_remaining_size()) {
*dsize = this->blk_dev->read_more();
*dptr = this->blk_dev->get_cache_ptr();
return true;
} else
return false;
}
);
if (this->is_writeable) {
if (this->blk_dev->medium_writable()) {
phy_impl->set_write_more_data_cb(
[this](int* dsize, uint8_t** dptr) -> bool {
if (this->remain_size) {
*dsize = this->write_more();
*dptr = (uint8_t *)this->data_cache.get();
if (this->blk_dev->get_remaining_size()) {
*dsize = this->blk_dev->write_more();
*dptr = this->blk_dev->get_cache_ptr();
return true;
} else
return false;
@@ -71,6 +73,9 @@ void ScsiBlockCmds::init_block_device(uint8_t medium_type, uint8_t dev_flags) {
}
);
}
if (is_apple_compliant)
this->add_page_getter(this, 0x30, &ScsiBlockCmds::get_apple_copyright_page);
}
void ScsiBlockCmds::process_command() {
@@ -83,18 +88,18 @@ void ScsiBlockCmds::process_command() {
case ScsiCommand::READ_6:
case ScsiCommand::READ_10:
case ScsiCommand::READ_12:
next_phase = this->read_new();
next_phase = this->read();
break;
case ScsiCommand::WRITE_6:
case ScsiCommand::WRITE_10:
case ScsiCommand::WRITE_12:
next_phase = this->write_new();
next_phase = this->write();
break;
case ScsiCommand::START_STOP_UNIT:
next_phase = this->start_stop_unit();
break;
case ScsiCommand::PREVENT_ALLOW_MEDIUM_REMOVAL:
phy_impl->set_eject_state((this->cdb_ptr[4] & 1) == 0);
phy_impl->set_lock_state((this->cdb_ptr[4] & 1) != 0);
next_phase = ScsiPhase::STATUS;
break;
case ScsiCommand::READ_CAPACITY:
@@ -108,7 +113,7 @@ void ScsiBlockCmds::process_command() {
phy_impl->switch_phase(next_phase);
}
int ScsiBlockCmds::read_new() {
int ScsiBlockCmds::read() {
int nblocks = this->get_xfer_len();
// special case: zero transfer length means 256 blocks for READ_6
@@ -117,7 +122,7 @@ int ScsiBlockCmds::read_new() {
nblocks = 256;
} else {
if ((this->cdb_ptr[1] & 1) && !this->linked_cmds_supported()) {
LOG_F(WARNING, "READ: RelAdr bit set");
LOG_F(WARNING, "READ: RelAdr bit set but it should not be");
this->set_field_pointer(1);
this->set_bit_pointer(0);
this->invalid_cdb();
@@ -131,14 +136,14 @@ int ScsiBlockCmds::read_new() {
return ScsiPhase::STATUS;
}
this->set_fpos(this->get_lba());
phy_impl->set_xfer_len(this->read_begin(nblocks));
phy_impl->set_buffer((uint8_t *)this->data_cache.get());
this->blk_dev->set_fpos(this->get_lba());
phy_impl->set_xfer_len(this->blk_dev->read_begin(nblocks));
phy_impl->set_buffer(this->blk_dev->get_cache_ptr());
return ScsiPhase::DATA_IN;
}
int ScsiBlockCmds::write_new() {
int ScsiBlockCmds::write() {
int nblocks = this->get_xfer_len();
// special case: zero transfer length means 256 blocks for WRITE_6
@@ -147,7 +152,7 @@ int ScsiBlockCmds::write_new() {
nblocks = 256;
} else {
if ((this->cdb_ptr[1] & 1) && !this->linked_cmds_supported()) {
LOG_F(WARNING, "WRITE: RelAdr bit set");
LOG_F(WARNING, "WRITE: RelAdr bit set but it should not be");
this->set_field_pointer(1);
this->set_bit_pointer(0);
this->invalid_cdb();
@@ -161,12 +166,12 @@ int ScsiBlockCmds::write_new() {
return ScsiPhase::STATUS;
}
this->set_fpos(this->get_lba());
phy_impl->set_xfer_len(this->write_begin(nblocks));
phy_impl->set_buffer((uint8_t *)this->data_cache.get());
this->blk_dev->set_fpos(this->get_lba());
phy_impl->set_xfer_len(this->blk_dev->write_begin(nblocks));
phy_impl->set_buffer(this->blk_dev->get_cache_ptr());
phy_impl->set_post_xfer_action([this]() {
this->write_cache();
this->blk_dev->write_cache();
}
);
@@ -189,7 +194,7 @@ int ScsiBlockCmds::read_capacity() {
uint32_t lba = this->get_lba();
if ((this->cdb_ptr[1] & 1) && !this->linked_cmds_supported()) {
LOG_F(WARNING, "READ_CAPACITY: RelAdr bit set");
LOG_F(WARNING, "READ_CAPACITY: RelAdr bit set but it should not be");
this->set_field_pointer(1);
this->set_bit_pointer(0);
this->invalid_cdb();
@@ -198,13 +203,14 @@ int ScsiBlockCmds::read_capacity() {
if (!(this->cdb_ptr[8] & 1) && lba) {
LOG_F(ERROR, "READ_CAPACITY: non-zero LBA for PMI=0");
this->set_field_pointer(2),
this->set_field_pointer(2);
this->invalid_cdb();
return ScsiPhase::STATUS;
}
uint32_t last_lba = this->size_blocks - 1;
uint32_t blk_len = this->block_size;
uint32_t last_lba = (uint32_t)std::min(
this->blk_dev->get_size_in_blocks() - 1, (uint64_t)0xFFFFFFFFU);
uint32_t blk_len = this->blk_dev->get_block_size();
WRITE_DWORD_BE_A(&this->buf_ptr[0], last_lba);
WRITE_DWORD_BE_A(&this->buf_ptr[4], blk_len);
@@ -215,12 +221,12 @@ int ScsiBlockCmds::read_capacity() {
}
int ScsiBlockCmds::format_block_descriptors(uint8_t* out_ptr) {
uint8_t density_code = 0;
uint32_t nblocks = std::min((int64_t)this->size_blocks, (int64_t)0xFFFFFFFFUL);
uint32_t nblocks = (uint32_t)std::min(
this->blk_dev->get_size_in_blocks(), (uint64_t)0xFFFFFFFFU);
WRITE_DWORD_BE_A(&out_ptr[0], nblocks);
WRITE_DWORD_BE_A(&out_ptr[4], (density_code << 24) | (this->block_size & 0xFFFFFF));
WRITE_DWORD_BE_A(&out_ptr[4], (this->density_code << 24) |
(this->blk_dev->get_block_size() & 0xFFFFFF));
return 8;
}
@@ -257,3 +263,24 @@ uint32_t ScsiBlockCmds::get_lba() {
ABORT_F("unsupported command length %d in get_lba", cmd_len);
}
}
static char Apple_Copyright_Page_Data[] = "APPLE COMPUTER, INC ";
int ScsiBlockCmds::get_apple_copyright_page(uint8_t ctrl, uint8_t subpage, uint8_t *out_ptr,
int avail_len)
{
if (subpage && subpage != 0xFFU)
return FORMAT_ERR_BAD_SUBPAGE;
if (ctrl == 3)
return FORMAT_ERR_BAD_CONTROL;
int page_size = 22;
if (page_size > avail_len)
return FORMAT_ERR_DATA_TOO_BIG;
std::memcpy(out_ptr, Apple_Copyright_Page_Data, page_size);
return page_size;
}
+18 -5
View File
@@ -29,15 +29,20 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cinttypes>
/** Base class for SCSI block device commands. */
class ScsiBlockCmds : public ScsiCommonCmds, public BlockStorageDevice {
class ScsiBlockCmds : public ScsiCommonCmds {
public:
ScsiBlockCmds(int cache_blocks = 256);
ScsiBlockCmds();
~ScsiBlockCmds() = default;
void init_block_device(uint8_t medium_type, uint8_t dev_flags);
void set_phys_block_dev(BlockStorageDevice *blk_dev_obj) {
this->blk_dev = blk_dev_obj;
}
virtual int read_new();
virtual int write_new();
void init_block_device(uint8_t medium_type, uint8_t dev_flags,
uint8_t density_code, bool is_apple_compliant);
virtual int read();
virtual int write();
virtual int start_stop_unit();
virtual int read_capacity();
@@ -51,13 +56,21 @@ public:
int get_error_recovery_page(uint8_t ctrl, uint8_t subpage, uint8_t *out_ptr,
int avail_len);
// this page is supported by a bunch of Apple-certified HD and CD-ROM devices
// so implement it here for reusability
int get_apple_copyright_page(uint8_t ctrl, uint8_t subpage, uint8_t *out_ptr,
int avail_len);
protected:
virtual void process_command() override;
uint32_t get_lba();
BlockStorageDevice* blk_dev = nullptr;
uint8_t medium_type = 0;
uint8_t device_flags = 0;
uint8_t density_code = 0;
};
#endif // SCSI_BLOCK_COMMANDS_H
+6 -4
View File
@@ -145,14 +145,16 @@ void ScsiBusController::sequencer() {
break;
case SeqState::RCV_STATUS:
case SeqState::RCV_MESSAGE:
if (this->cur_bus_phase == ScsiPhase::MESSAGE_IN)
this->bus_obj->assert_ctrl_line(this->src_id, SCSI_CTRL_REQ);
this->rcv_data();
if (this->is_initiator) {
if (this->cur_state == SeqState::RCV_STATUS) {
this->bus_obj->target_next_step();
if (this->cur_bus_phase == ScsiPhase::MESSAGE_IN)
this->bus_obj->assert_ctrl_line(this->src_id, SCSI_CTRL_REQ);
} else if (this->cur_state == SeqState::RCV_MESSAGE)
} else if (this->cur_state == SeqState::RCV_MESSAGE) {
this->bus_obj->release_ctrl_line(this->src_id, SCSI_CTRL_REQ);
this->bus_obj->assert_ctrl_line(this->src_id, SCSI_CTRL_ACK);
}
this->step_completed();
this->cur_state = SeqState::IDLE;
}
@@ -230,7 +232,7 @@ int ScsiBusController::send_data(uint8_t* dst_ptr, int count) {
return actual_count;
}
int ScsiBusController::xfer_from(uint8_t *buf, int len) {
int ScsiBusController::xfer_from(DmaChannel *ch_obj, uint8_t *buf, int len) {
if (len > this->to_xfer + this->fifo_pos)
LOG_F(WARNING, "%s: DMA xfer len > command xfer len", this->name.c_str());
+1 -1
View File
@@ -81,7 +81,7 @@ public:
void process_command() override {}
// DmaDevice methods
int xfer_from(uint8_t *buf, int len) override;
int xfer_from(DmaChannel *ch_obj, uint8_t *buf, int len) override;
protected:
void seq_defer_state(uint64_t delay_ns);
+7 -176
View File
@@ -21,50 +21,22 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file SCSI CD-ROM emulation. */
#include <devices/common/scsi/scsi.h>
#include <devices/common/scsi/scsicdrom.h>
#include <devices/deviceregistry.h>
#include <loguru.hpp>
#include <machines/machineproperties.h>
#include <memaccess.h>
#include <cstring>
using namespace std;
static char my_vendor_id[] = "SONY ";
static char my_product_id[] = "CD-ROM CDU-8003A";
static char my_revision_id[] = "1.9a";
ScsiCdrom::ScsiCdrom(std::string name, int my_id) :
CdromDrive(), ScsiPhysDevice(name, my_id), ScsiCommonCmds()
ScsiCdrom::ScsiCdrom(std::string name, int my_id) : ScsiPhysDevice(name, my_id)
{
this->set_phys_dev(this);
this->set_cdb_ptr(this->cmd_buf);
this->set_buf_ptr(this->data_buf);
this->set_error_callback(
[this](uint8_t sense_key, uint8_t asc) {
//his->report_error(sense_key, asc);
this->invalid_cdb(); // HACK! to make CdromDrive::read_toc() work
}
);
this->set_read_more_data_cb(
[this](int* dsize, uint8_t** dptr) {
if (this->remain_size) {
*dsize = this->read_more();
*dptr = (uint8_t *)this->data_cache.get();
return true;
} else
return false;
}
);
this->set_write_more_data_cb(
[this](int* dsize, uint8_t** dptr) {
return false;
}
);
this->init_block_device(1, 0, 1, true);
// populate device info for INQUIRY
this->dev_type = ScsiDevType::CD_ROM;
@@ -77,8 +49,7 @@ ScsiCdrom::ScsiCdrom(std::string name, int my_id) :
this->set_revision_id(my_revision_id);
}
void ScsiCdrom::process_command()
{
void ScsiCdrom::process_command() {
uint32_t lba;
if (this->verify_cdb() < 0) {
@@ -96,129 +67,17 @@ void ScsiCdrom::process_command()
uint8_t* cmd = this->cmd_buf;
switch (cmd[0]) {
case ScsiCommand::READ_6:
lba = ((cmd[1] & 0x1F) << 16) + (cmd[2] << 8) + cmd[3];
this->read(lba, cmd[4], 6);
break;
case ScsiCommand::MODE_SELECT_6:
this->mode_select_6(cmd[4]);
break;
case ScsiCommand::MODE_SENSE_6:
this->mode_sense_6();
break;
case ScsiCommand::START_STOP_UNIT:
this->switch_phase(ScsiPhase::STATUS);
break;
case ScsiCommand::PREVENT_ALLOW_MEDIUM_REMOVAL:
this->eject_allowed = (cmd[4] & 1) == 0;
this->switch_phase(ScsiPhase::STATUS);
break;
case ScsiCommand::READ_CAPACITY:
this->read_capacity_10();
break;
case ScsiCommand::READ_10:
lba = READ_DWORD_BE_U(&cmd[2]);
if (cmd[1] & 1) {
ABORT_F("%s: RelAdr bit set in READ_10", this->name.c_str());
}
read(lba, READ_WORD_BE_U(&cmd[7]), 10);
break;
// CD-ROM specific commands
case ScsiCommand::READ_TOC:
phy_impl->set_xfer_len(read_toc(cmd, this->data_buf));
if (this->status == ScsiStatus::GOOD) {
this->msg_buf[0] = ScsiMessage::COMMAND_COMPLETE;
this->switch_phase(ScsiPhase::DATA_IN);
}
break;
default:
ScsiCommonCmds::process_command();
ScsiCdromCmds::process_command();
}
}
void ScsiCdrom::read(uint32_t lba, uint16_t nblocks, uint8_t cmd_len)
{
if (cmd_len == 6 && nblocks == 0)
nblocks = 256;
this->set_fpos(lba);
phy_impl->set_buffer((uint8_t *)this->data_cache.get());
phy_impl->set_xfer_len(this->read_begin(nblocks, UINT32_MAX));
this->msg_buf[0] = ScsiMessage::COMMAND_COMPLETE;
this->switch_phase(ScsiPhase::DATA_IN);
}
int ScsiCdrom::format_block_descriptors(uint8_t* out_ptr) {
uint8_t density_code = 1; // user data only, 2048 bytes per physical sector
WRITE_DWORD_BE_A(&out_ptr[0], (density_code << 24) | (this->size_blocks & 0xFFFFFF));
WRITE_DWORD_BE_A(&out_ptr[4], (this->block_size & 0xFFFFFF));
return 8;
}
static char Apple_Copyright_Page_Data[] = "APPLE COMPUTER, INC ";
void ScsiCdrom::mode_sense_6()
{
uint8_t page_code = this->cmd_buf[2] & 0x3F;
//uint8_t alloc_len = this->cmd_buf[4];
this->data_buf[ 0] = 13; // initial data size
this->data_buf[ 1] = 0; // medium type
this->data_buf[ 2] = 0x80; // medium is write protected
this->data_buf[ 3] = 8; // block description length
this->data_buf[ 4] = 0; // density code
this->data_buf[ 5] = (this->size_blocks >> 16) & 0xFFU;
this->data_buf[ 6] = (this->size_blocks >> 8) & 0xFFU;
this->data_buf[ 7] = (this->size_blocks ) & 0xFFU;
this->data_buf[ 8] = 0;
this->data_buf[ 9] = 0;
this->data_buf[10] = (this->block_size >> 8) & 0xFFU;
this->data_buf[11] = (this->block_size ) & 0xFFU;
this->data_buf[12] = page_code;
switch (page_code) {
case 0x01:
this->data_buf[13] = 6; // data size
std::memset(&this->data_buf[14], 0, 6);
this->data_buf[0] += 7;
break;
case 0x30:
this->data_buf[13] = 22; // data size
std::memcpy(&this->data_buf[14], Apple_Copyright_Page_Data, 22);
this->data_buf[0] += 23;
break;
case 0x31:
this->data_buf[13] = 6; // data size
std::memset(&this->data_buf[14], 0, 6);
this->data_buf[14] = '.';
this->data_buf[15] = 'A';
this->data_buf[16] = 'p';
this->data_buf[17] = 'p';
break;
default:
LOG_F(WARNING, "%s: unsupported page 0x%02x in MODE_SENSE_6", this->name.c_str(),
page_code);
this->set_field_pointer(2), // error is in the 3rd byte
this->set_bit_pointer(5), // starting with bit 5
this->invalid_cdb();
this->switch_phase(ScsiPhase::STATUS);
return;
}
phy_impl->set_xfer_len(this->data_buf[0]);
this->msg_buf[0] = ScsiMessage::COMMAND_COMPLETE;
this->switch_phase(ScsiPhase::DATA_IN);
}
// Apple SCSI/ATAPI driver requests this page in the case of a device error.
// PearPC implements it under the name "Apple Features".
// I couldn't find any drive whose firmware supports it.
void ScsiCdrom::mode_select_6(uint8_t param_len)
{
if (!param_len)
@@ -235,31 +94,3 @@ void ScsiCdrom::mode_select_6(uint8_t param_len)
this->switch_phase(ScsiPhase::DATA_OUT);
}
void ScsiCdrom::read_capacity_10()
{
uint32_t lba = READ_DWORD_BE_U(&this->cmd_buf[2]);
if (this->cmd_buf[1] & 1) {
ABORT_F("%s: RelAdr bit set in READ_CAPACITY_10", this->name.c_str());
}
if (!(this->cmd_buf[8] & 1) && lba) {
LOG_F(ERROR, "%s: non-zero LBA for PMI=0", this->name.c_str());
this->set_field_pointer(2),
this->invalid_cdb();
this->switch_phase(ScsiPhase::STATUS);
return;
}
int last_lba = (int)this->size_blocks - 1;
WRITE_DWORD_BE_A(&this->data_buf[0], last_lba);
WRITE_DWORD_BE_A(&this->data_buf[4], this->block_size);
phy_impl->set_xfer_len(8);
this->msg_buf[0] = ScsiMessage::COMMAND_COMPLETE;
this->switch_phase(ScsiPhase::DATA_IN);
}
+9 -22
View File
@@ -25,43 +25,30 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#define SCSI_CDROM_H
#include <devices/common/scsi/scsi.h>
#include <devices/common/scsi/scsicommoncmds.h>
#include <devices/storage/cdromdrive.h>
#include <utils/imgfile.h>
#include <devices/common/scsi/scsicdromcmds.h>
#include <cinttypes>
#include <memory>
#include <string>
class ScsiCdrom : public ScsiPhysDevice, public CdromDrive, public ScsiCommonCmds {
class ScsiCdrom : public ScsiPhysDevice, public ScsiCdromCmds {
public:
ScsiCdrom(std::string name, int my_id);
~ScsiCdrom() = default;
virtual void process_command() override;
protected:
bool is_device_ready() override { return true; }
// temporary implementation that should be elsewhere
void get_medium_type(uint8_t& medium_type, uint8_t& dev_flags) override {
medium_type = 1; // 120mm CD-ROM data only
dev_flags = 0;
void set_lock_state(bool is_locked) override {
this->drive_locked = is_locked ? 1 : 0;
ScsiPhysDevice::set_lock_state(is_locked);
}
// temporary implementation that should be elsewhere
int format_block_descriptors(uint8_t* out_ptr) override;
protected:
bool is_device_ready() override { return this->is_ready; }
void read(uint32_t lba, uint16_t nblocks, uint8_t cmd_len);
void mode_select_6(uint8_t param_len);
void mode_sense_6();
void read_capacity_10();
void mode_select_6(uint8_t param_len);
private:
bool eject_allowed = true;
int bytes_out = 0;
uint8_t data_buf[2048] = {};
uint8_t data_buf[2048] = {};
};
#endif // SCSI_CDROM_H
+338
View File
@@ -0,0 +1,338 @@
/*
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/>.
*/
#include <core/memaccess.h>
#include <devices/common/scsi/scsicdromcmds.h>
#include <loguru.hpp>
#include <cstring>
ScsiCdromCmds::ScsiCdromCmds() {
this->set_phys_block_dev(this);
this->enable_cmd(ScsiCommand::READ_TOC);
this->enable_cmd(ScsiCommand::SET_CD_SPEED);
this->add_page_getter(this, ModePage::CDROM_AUDIO_CONTROL,
&ScsiCdromCmds::get_cdrom_audio_control_page);
this->add_page_getter(this, ModePage::CDROM_CAPABILITIES,
&ScsiCdromCmds::get_cd_capabilities_page);
this->add_page_getter(this, ModePage::VENDOR_PAGE_31,
&ScsiCdromCmds::get_apple_page_49);
}
void ScsiCdromCmds::process_command() {
int next_phase;
// use non-disk buffer by default
phy_impl->set_buffer(this->buf_ptr);
switch(this->cdb_ptr[0]) {
case ScsiCommand::READ_TOC:
next_phase = this->read_toc();
break;
case ScsiCommand::SET_CD_SPEED:
next_phase = this->set_cd_speed();
break;
default:
ScsiBlockCmds::process_command();
return;
}
phy_impl->switch_phase(next_phase);
}
int ScsiCdromCmds:: read_toc() {
uint8_t start_track, session_num;
int tot_tracks, resp_len = 0;
int alloc_len = this->get_xfer_len();
bool is_msf = !!(this->cdb_ptr[1] & 2);
bool is_alt_fmt = false;
// go directly to the STATUS phase if alloc_len = 0
if (!alloc_len) {
LOG_F(WARNING, "READ_TOC: skip data transfer because alloc_len = 0");
return ScsiPhase::STATUS;
}
// SCSI-2 supports only one response format so the format field in CDB (byte 2)
// is reserved and should be set to zero.
// ATAPI CD-ROM draft rev 2.6 advises to grab format code from the upper
// two bits of byte 9 if byte 2 is zero.
// This extension is implemented in the most SCSI drives as well as in
// Apple CD-ROM driver in Mac OS.
// SCSI-3 devices should use byte 2 to specify the response format.
// I decided to stick to the above described ATAPI way for now.
// It should work for both SCSI and ATAPI as well as SCSI-3 devices.
uint8_t format = this->cdb_ptr[2] & 7;
if (!format) {
format = this->cdb_ptr[9] >> 6;
is_alt_fmt = true;
LOG_F(9, "READ_TOC: grabbed format code 0x%X from byte 9", format);
}
uint8_t *out_ptr = this->buf_ptr;
switch(format) {
case 0: // Formatted TOC
start_track = this->cdb_ptr[6];
if (!start_track) { // special case: track zero (lead-in) as starting track
// return all tracks starting with track 1 plus lead-out
start_track = 1;
tot_tracks = this->num_tracks + 1;
} else if (start_track == LEAD_OUT_TRK_NUM) {
start_track = this->num_tracks + 1;
tot_tracks = 1;
} else if (start_track <= this->num_tracks) {
tot_tracks = (this->num_tracks - start_track) + 2;
} else {
LOG_F(ERROR, "READ_TOC: invalid starting track %d", start_track);
this->set_field_pointer(6),
this->invalid_cdb();
return ScsiPhase::STATUS;
}
// write TOC data header
WRITE_WORD_BE_A(out_ptr, tot_tracks * 8 + 2); // TOC data length
out_ptr[2] = 1; // 1st track number
out_ptr[3] = this->num_tracks; // last track number
out_ptr += 4;
resp_len = 4;
for (int tx = 0; tx < tot_tracks; tx++, out_ptr += 8, resp_len += 8) {
if (resp_len >= alloc_len)
break; // exit the loop if the output buffer is exhausted
TrackDescriptor& td = this->tracks[start_track + tx - 1];
// write TOC track descriptor
out_ptr[0] = 0; // reserved
out_ptr[1] = td.adr_ctrl;
out_ptr[2] = td.trk_num;
out_ptr[3] = 0; // reserved
if (is_msf) {
AddrMsf msf = lba_to_msf(td.start_lba + 150);
out_ptr[4] = 0; // reserved
out_ptr[5] = msf.min;
out_ptr[6] = msf.sec;
out_ptr[7] = msf.frm;
} else
WRITE_DWORD_BE_A(&out_ptr[4], td.start_lba);
}
break;
case 1: // Multi-session info --> we currently support only one session
resp_len = 12;
std::memset(out_ptr, 0, resp_len);
out_ptr[1] = 10; // TOC data length
out_ptr[2] = 1; // first session number
out_ptr[3] = 1; // last session number
out_ptr[5] = this->tracks[0].adr_ctrl;
out_ptr[6] = 1;
if (is_msf) {
AddrMsf msf = lba_to_msf(this->tracks[0].start_lba + 150);
out_ptr[ 8] = 0; // reserved
out_ptr[ 9] = msf.min;
out_ptr[10] = msf.sec;
out_ptr[11] = msf.frm;
}
break;
case 2: // Raw TOC
session_num = this->cdb_ptr[6];
if (!session_num)
session_num = 1;
if (session_num > 1) {
LOG_F(ERROR, "READ_TOC: invalid session number %d", session_num);
this->set_field_pointer(6),
this->invalid_cdb();
return ScsiPhase::STATUS;
}
resp_len = 48;
std::memset(out_ptr, 0, resp_len);
// prepare data header
out_ptr[1] = resp_len - 2; // TOC data length
out_ptr[2] = 1; // first session number
out_ptr[3] = 1; // last session number
out_ptr += 4;
// descriptor #1 -> first track
out_ptr[0] = session_num;
out_ptr[1] = this->tracks[0].adr_ctrl;
out_ptr[3] = 0xA0; // point -> first track
out_ptr[8] = 1; // first track number
out_ptr += 11;
// descriptor #2 -> last track
out_ptr[0] = session_num;
out_ptr[1] = this->tracks[0].adr_ctrl;
out_ptr[3] = 0xA1; // point -> last track
out_ptr[8] = 1; // last track number
out_ptr += 11;
// descriptor #3 -> lead-out
out_ptr[0] = session_num;
out_ptr[1] = this->tracks[0].adr_ctrl;
out_ptr[3] = 0xA2; // point -> lead-out
if (is_msf) {
AddrMsf msf = lba_to_msf(this->tracks[1].start_lba + 150);
out_ptr[ 7] = 0; // reserved
out_ptr[ 8] = msf.min;
out_ptr[ 9] = msf.sec;
out_ptr[10] = msf.frm;
} else
WRITE_DWORD_BE_U(&out_ptr[7], this->tracks[1].start_lba);
out_ptr += 11;
// descriptor #4 -> data track
out_ptr[0] = session_num;
out_ptr[1] = this->tracks[0].adr_ctrl;
out_ptr[3] = 1; // point -> data track
if (is_msf) {
AddrMsf msf = lba_to_msf(this->tracks[0].start_lba + 150);
out_ptr[ 7] = 0; // reserved
out_ptr[ 8] = msf.min;
out_ptr[ 9] = msf.sec;
out_ptr[10] = msf.frm;
}
break;
default:
LOG_F(ERROR, "READ_TOC: unsupported format %d", format);
this->set_field_pointer(is_alt_fmt ? 9 : 2),
this->set_bit_pointer(is_alt_fmt ? 7 : 3),
this->invalid_cdb();
return ScsiPhase::STATUS;
}
phy_impl->set_xfer_len(std::min(alloc_len, resp_len));
return ScsiPhase::DATA_IN;
}
int ScsiCdromCmds::set_cd_speed() {
phy_impl->set_status(ScsiStatus::GOOD);
uint16_t new_rd_speed = READ_WORD_BE_U(&this->cdb_ptr[2]);
if (new_rd_speed == 0xFFFFU || new_rd_speed > this->max_rd_speed)
this->cur_rd_speed = this->max_rd_speed;
else
this->cur_rd_speed = new_rd_speed;
LOG_F(INFO, "SET_CD_SPEED: drive speed set to %d kBps", this->cur_rd_speed);
return ScsiPhase::STATUS;
}
int ScsiCdromCmds::get_cd_capabilities_page(uint8_t subpage, uint8_t ctrl,
uint8_t *out_ptr, int avail_len)
{
if (subpage && subpage != 0xFFU)
return FORMAT_ERR_BAD_SUBPAGE;
if (ctrl == 3)
return FORMAT_ERR_BAD_CONTROL;
int page_size = 28; // min length defined in MMC-3
if (page_size > avail_len)
return FORMAT_ERR_DATA_TOO_BIG;
std::memset(out_ptr, 0, page_size); // clear everything
out_ptr[ 0] = this->read_cap;
out_ptr[ 1] = this->write_cap;
out_ptr[ 2] = this->fmt_support;
out_ptr[ 3] = this->ext_support;
out_ptr[ 4] = (this->mech_type << 5) | this->sw_lock_sup |
(this->drive_locked << 1) | (this->prevent_jump << 2) |
(this->sw_eject_sup << 3);
out_ptr[ 5] = this->more_support;
out_ptr[15] = this->dgt_out_desc;
WRITE_WORD_BE_A(&out_ptr[ 6], this->max_rd_speed); // max read speed
WRITE_WORD_BE_A(&out_ptr[ 8], this->max_vol_levs); // max of volume levels
WRITE_WORD_BE_A(&out_ptr[10], (this->cache_size / 1024)); // buffer size kB
WRITE_WORD_BE_A(&out_ptr[12], this->cur_rd_speed); // current read speed
return page_size;
}
int ScsiCdromCmds::get_cdrom_audio_control_page(uint8_t subpage, uint8_t ctrl,
uint8_t *out_ptr, int avail_len)
{
if (subpage && subpage != 0xFFU)
return FORMAT_ERR_BAD_SUBPAGE;
if (ctrl == 3)
return FORMAT_ERR_BAD_CONTROL;
int page_size = 14;
if (page_size > avail_len)
return FORMAT_ERR_DATA_TOO_BIG;
std::memset(out_ptr, 0, page_size); // clear everything
out_ptr[ 0] = (1 << 2); // Immed defaults to 1, SOTC defaults to 0
// logical block per second of audio playback defaults to 75
WRITE_WORD_BE_A(&out_ptr[4], 75);
out_ptr[ 6] = 0x01; // Left Channel
out_ptr[ 7] = 0xFF; // Volume (0-255)
out_ptr[ 8] = 0x02; // Right Channel
out_ptr[ 9] = 0xFF; // Volume (0-255)
out_ptr[10] = 0x04; // Output Port 2
out_ptr[11] = 0x00; // Volume (0-255)
out_ptr[12] = 0x08; // Output Port 3
out_ptr[13] = 0x00; // Volume (0-255)
return page_size;
}
// Apple SCSI/ATAPI driver requests this page in the case of a device error.
// PearPC implements it under the name "Apple Features".
int ScsiCdromCmds::get_apple_page_49(uint8_t subpage, uint8_t ctrl,
uint8_t *out_ptr, int avail_len)
{
LOG_F(WARNING, "Page 0x31 requested");
if (subpage && subpage != 0xFFU)
return FORMAT_ERR_BAD_SUBPAGE;
if (ctrl == 3)
return FORMAT_ERR_BAD_CONTROL;
int page_size = 6;
if (page_size > avail_len)
return FORMAT_ERR_DATA_TOO_BIG;
std::memset(out_ptr, 0, page_size);
out_ptr[0] = '.';
out_ptr[1] = 'A';
out_ptr[2] = 'p';
out_ptr[3] = 'p';
return page_size;
}
+52
View File
@@ -0,0 +1,52 @@
/*
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 SCSI_CDROM_COMMANDS_H
#define SCSI_CDROM_COMMANDS_H
#include <devices/common/scsi/scsiblockcmds.h>
#include <devices/storage/cdromdrive.h>
#include <cinttypes>
/** Base class for SCSI CD-ROM device commands. */
class ScsiCdromCmds : public ScsiBlockCmds, public CdromDrive {
public:
ScsiCdromCmds();
~ScsiCdromCmds() = default;
protected:
virtual void process_command() override;
int get_apple_page_49(uint8_t subpage, uint8_t ctrl,
uint8_t *out_ptr, int avail_len);
int read_toc();
int set_cd_speed();
int get_cd_capabilities_page(uint8_t subpage, uint8_t ctrl,
uint8_t *out_ptr, int avail_len);
int get_cdrom_audio_control_page(uint8_t subpage, uint8_t ctrl,
uint8_t *out_ptr, int avail_len);
};
#endif // SCSI_CDROM_COMMANDS_H
+15 -16
View File
@@ -19,9 +19,9 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <core/memaccess.h>
#include <devices/common/scsi/scsicommoncmds.h>
#include <loguru.hpp>
#include <memaccess.h>
ScsiCommonCmds::ScsiCommonCmds() {
this->enable_cmd(ScsiCommand::TEST_UNIT_READY);
@@ -39,17 +39,16 @@ void ScsiCommonCmds::process_command() {
next_phase = this->test_unit_ready();
break;
case ScsiCommand::REQ_SENSE:
next_phase = this->request_sense_new();
next_phase = this->request_sense();
break;
case ScsiCommand::INQUIRY:
next_phase = this->inquiry_new();
next_phase = this->inquiry();
break;
case ScsiCommand::MODE_SENSE_6:
case ScsiCommand::MODE_SENSE_10:
next_phase = this->mode_sense();
break;
default:
LOG_F(ERROR, "no support for command 0x%X", this->cdb_ptr[0]);
this->invalid_command();
next_phase = ScsiPhase::STATUS;
}
@@ -86,7 +85,7 @@ int ScsiCommonCmds::verify_cdb() {
if (!this->lun_supported(lun)) {
LOG_F(ERROR, "unsupported LUN 0x%X", lun);
this->invalid_lun();
phy_impl->set_status(ScsiStatus::CHECK_CONDITION);
phy_impl->set_status(ScsiStatus::CHECK_CONDITION, this->sense_key);
return -1;
}
} else if (this->cdb_ptr[1] >> 5)
@@ -116,13 +115,13 @@ int ScsiCommonCmds::test_unit_ready() {
this->sense_key = ScsiSense::NOT_READY;
this->asc = phy_impl->not_ready_reason();
this->ascq = 0;
phy_impl->set_status(ScsiStatus::CHECK_CONDITION);
phy_impl->set_status(ScsiStatus::CHECK_CONDITION, this->sense_key);
}
return ScsiPhase::STATUS;
}
int ScsiCommonCmds::inquiry_new() {
int ScsiCommonCmds::inquiry() {
int alloc_len = this->get_xfer_len();
int resp_len = 36; // standard response length
@@ -179,7 +178,7 @@ int ScsiCommonCmds::inquiry_new() {
return ScsiPhase::DATA_IN;
}
int ScsiCommonCmds::request_sense_new() {
int ScsiCommonCmds::request_sense() {
int alloc_len = this->get_xfer_len();
int resp_len = 18; // standard response length
@@ -232,8 +231,8 @@ int ScsiCommonCmds::mode_sense() {
if (page_ctrl == PageControl::SAVED_VALUES && !this->supports_params_saving()) {
LOG_F(ERROR, "MODE_SENSE: Page control mode (%s) not supported",
Page_Control_Modes[page_ctrl]);
this->set_field_pointer(2), // error in the 3rd byte
this->set_bit_pointer(7), // starting with bit 7
this->set_field_pointer(2); // error in the 3rd byte
this->set_bit_pointer(7); // starting with bit 7
this->illegal_request(ScsiError::SAVING_NOT_SUPPORTED, 0);
return ScsiPhase::STATUS;
}
@@ -317,8 +316,8 @@ int ScsiCommonCmds::mode_sense() {
resp_len += page_len;
} else {
LOG_F(ERROR, "MODE_SENSE: page 0x%X not supported", page_code);
this->set_field_pointer(2), // error in the 3rd byte
this->set_bit_pointer(5), // starting with bit 5
this->set_field_pointer(2); // error in the 3rd byte
this->set_bit_pointer(5); // starting with bit 5
this->invalid_cdb();
return ScsiPhase::STATUS;
}
@@ -351,7 +350,7 @@ try_again:
} else if (err == FORMAT_ERR_BAD_CONTROL) {
LOG_F(ERROR, "MODE_SENSE: Page control (%s) not supported for page 0x%X",
Page_Control_Modes[ctrl], page);
this->set_field_pointer(2), // error in the 3rd byte
this->set_field_pointer(2); // error in the 3rd byte
this->set_bit_pointer(7); // starting with bit 7
} else if (err == FORMAT_ERR_BAD_SUBPAGE) {
LOG_F(ERROR, "MODE_SENSE: unsupported subpage 0x%X for page 0x%X",
@@ -421,7 +420,7 @@ void ScsiCommonCmds::invalid_cdb() {
this->ascq = 0;
this->is_cdb_err = true;
phy_impl->set_status(ScsiStatus::CHECK_CONDITION);
phy_impl->set_status(ScsiStatus::CHECK_CONDITION, this->sense_key);
}
void ScsiCommonCmds::invalid_command() {
@@ -434,7 +433,7 @@ void ScsiCommonCmds::invalid_command() {
this->field_ptr_valid = true;
this->field_ptr = 0; // error in the 1st byte
phy_impl->set_status(ScsiStatus::CHECK_CONDITION);
phy_impl->set_status(ScsiStatus::CHECK_CONDITION, this->sense_key);
}
void ScsiCommonCmds::illegal_request(uint8_t asc, uint8_t ascq, bool is_cdb) {
@@ -443,5 +442,5 @@ void ScsiCommonCmds::illegal_request(uint8_t asc, uint8_t ascq, bool is_cdb) {
this->ascq = ascq;
this->is_cdb_err = is_cdb;
phy_impl->set_status(ScsiStatus::CHECK_CONDITION);
phy_impl->set_status(ScsiStatus::CHECK_CONDITION, this->sense_key);
}
+2 -2
View File
@@ -87,8 +87,8 @@ public:
protected:
virtual void process_command();
virtual int test_unit_ready();
virtual int inquiry_new();
virtual int request_sense_new();
virtual int inquiry();
virtual int request_sense();
virtual int mode_sense();
virtual uint8_t get_lun();
virtual uint32_t get_xfer_len();
+6 -29
View File
@@ -21,10 +21,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file Generic SCSI Hard Disk emulation. */
#include <core/memaccess.h>
#include <core/timermanager.h>
#include <devices/common/scsi/scsihd.h>
#include <loguru.hpp>
#include <memaccess.h>
#include <cstring>
@@ -32,9 +32,11 @@ static char my_vendor_id[] = "QUANTUM ";
static char my_product_id[] = "Emulated Disk ";
static char my_revision_id[] = "di01";
ScsiHardDisk::ScsiHardDisk(std::string name, int my_id) : ScsiPhysDevice(name, my_id)
ScsiHardDisk::ScsiHardDisk(std::string name, int my_id) : ScsiPhysDevice(name, my_id),
BlockStorageDevice(256)
{
this->set_phys_dev(this);
this->set_phys_block_dev(this);
this->set_cdb_ptr(this->cmd_buf);
this->set_buf_ptr(this->data_buf);
this->set_buffer(this->data_buf);
@@ -51,19 +53,15 @@ ScsiHardDisk::ScsiHardDisk(std::string name, int my_id) : ScsiPhysDevice(name, m
this->add_page_getter(this, ModePage::DEV_FORMAT_PARAMS, &ScsiHardDisk::get_dev_format_page);
this->add_page_getter(this, ModePage::RIGID_DISK_GEOMETRY, &ScsiHardDisk::get_rigid_geometry_page);
this->add_page_getter(this, 0x30, &ScsiHardDisk::get_apple_copyright_page);
}
void ScsiHardDisk::insert_image(std::string filename) {
if (this->set_host_file(filename) < 0)
ABORT_F("%s: could not open image file %s", this->name.c_str(), filename.c_str());
if (this->size_blocks > 0xFFFFFFU)
ABORT_F("%s: image file too large", this->name.c_str());
this->is_writeable = true;
this->init_block_device(0, 0);
this->init_block_device(0, 0, 0, true);
}
void ScsiHardDisk::process_command() {
@@ -162,7 +160,7 @@ int ScsiHardDisk::get_rigid_geometry_page(uint8_t ctrl, uint8_t subpage, uint8_t
std::memset(out_ptr, 0, page_size);
// num_cylinders = total_blocks / sectors_per_track / number_of_heads
int num_cylinders = this->size_blocks / 64 / 4;
uint64_t num_cylinders = this->size_blocks / 64 / 4;
// num_cylinders is a 24bit value!
out_ptr[0] = (num_cylinders >> 16) & 0xFF;
@@ -173,27 +171,6 @@ int ScsiHardDisk::get_rigid_geometry_page(uint8_t ctrl, uint8_t subpage, uint8_t
return page_size;
}
static char Apple_Copyright_Page_Data[] = "APPLE COMPUTER, INC ";
int ScsiHardDisk::get_apple_copyright_page(uint8_t ctrl, uint8_t subpage, uint8_t *out_ptr,
int avail_len)
{
if (subpage && subpage != 0xFFU)
return FORMAT_ERR_BAD_SUBPAGE;
if (ctrl == 3)
return FORMAT_ERR_BAD_CONTROL;
int page_size = 22;
if (page_size > avail_len)
return FORMAT_ERR_DATA_TOO_BIG;
std::memcpy(out_ptr, Apple_Copyright_Page_Data, page_size);
return page_size;
}
void ScsiHardDisk::format() {
LOG_F(WARNING, "%s: attempt to format the disk!", this->name.c_str());
+3 -5
View File
@@ -26,11 +26,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <devices/common/scsi/scsi.h>
#include <devices/common/scsi/scsiblockcmds.h>
#include <devices/storage/blockstoragedevice.h>
#include <cinttypes>
#include <string>
class ScsiHardDisk : public ScsiPhysDevice, public ScsiBlockCmds {
class ScsiHardDisk : public ScsiPhysDevice, public BlockStorageDevice, public ScsiBlockCmds {
public:
ScsiHardDisk(std::string name, int my_id);
~ScsiHardDisk() = default;
@@ -39,7 +40,7 @@ public:
void process_command() override;
protected:
bool is_device_ready() override { return true; }
bool is_device_ready() override { return this->is_ready; }
void mode_select_6(uint8_t param_len);
@@ -49,9 +50,6 @@ protected:
int get_rigid_geometry_page(uint8_t ctrl, uint8_t subpage, uint8_t *out_ptr,
int avail_len);
int get_apple_copyright_page(uint8_t ctrl, uint8_t subpage, uint8_t *out_ptr,
int avail_len);
void format();
void read_buffer();
+2 -2
View File
@@ -47,13 +47,13 @@ public:
virtual int get_phy_id() { return this->phy_id; };
virtual bool is_device_ready() { return true; }
virtual void set_eject_state(bool eject_allowed) = 0;
virtual void set_lock_state(bool is_locked) = 0;
virtual uint8_t not_ready_reason() { return 0; }
virtual bool last_sel_has_attention() { return false; }
virtual uint8_t last_sel_msg() { return 0; }
virtual void set_xfer_len(uint64_t len) = 0;
virtual void set_buffer(uint8_t *buf_ptr) = 0;
virtual void set_status(uint8_t status_code) = 0;
virtual void set_status(uint8_t status_code, uint8_t sense_key = 0) = 0;
virtual void switch_phase(const int new_phase) = 0;
virtual void set_read_more_data_cb(more_data_cb_t cb) = 0;
virtual void set_write_more_data_cb(more_data_cb_t cb) = 0;
+4 -6
View File
@@ -24,16 +24,16 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <core/hostevents.h>
#include <core/mathutils.h>
#include <core/memaccess.h>
#include <core/timermanager.h>
#include <devices/common/adb/adbbus.h>
#include <cpu/ppc/ppcemu.h>
#include <devices/common/adb/adbbus.h>
#include <devices/common/hwcomponent.h>
#include <devices/common/hwinterrupt.h>
#include <devices/common/viacuda.h>
#include <devices/deviceregistry.h>
#include <loguru.hpp>
#include <machines/machinebase.h>
#include <memaccess.h>
#include <cinttypes>
#include <string>
@@ -814,13 +814,11 @@ void ViaCuda::pseudo_command() {
break;
case CUDA_RESTART_SYSTEM:
LOG_F(INFO, "Cuda: system restart");
power_on = false;
power_off_reason = po_restart;
power_off(po_restart);
break;
case CUDA_POWER_DOWN:
LOG_F(INFO, "Cuda: system shutdown");
power_on = false;
power_off_reason = po_shut_down;
power_off(po_shut_down);
break;
case CUDA_SET_POWER_UPTIME: {
uint32_t alarm_time = READ_DWORD_BE_U(&this->in_buf[2]);
+3 -3
View File
@@ -52,11 +52,11 @@ uint16_t BigMac::read(uint16_t reg_offset) {
case BigMacReg::CHIP_ID:
return this->chip_id;
case BigMacReg::TX_FIFO_TH:
return this->tx_fifo_tresh;
return this->tx_fifo_thresh;
case BigMacReg::TX_FIFO_CSR:
return (this->tx_fifo_enable & 1) | ((((this->tx_fifo_size >> 7) - 1) & 0xFF) << 1);
case BigMacReg::RX_FIFO_CSR:
return (this->tx_fifo_enable & 1) | ((((this->tx_fifo_size >> 7) - 1) & 0xFF) << 1);
return (this->rx_fifo_enable & 1) | ((((this->rx_fifo_size >> 7) - 1) & 0xFF) << 1);
case BigMacReg::TX_PNTR:
return this->tx_ptr;
case BigMacReg::RX_PNTR:
@@ -171,7 +171,7 @@ void BigMac::write(uint16_t reg_offset, uint16_t value) {
this->tx_fifo_size = (((value >> 1) & 0xFF) + 1) << 7;
break;
case BigMacReg::TX_FIFO_TH:
this->tx_fifo_tresh = value;
this->tx_fifo_thresh = value;
break;
case BigMacReg::RX_FIFO_CSR:
this->rx_fifo_enable = !!(value & 1);
+1 -1
View File
@@ -195,7 +195,7 @@ private:
uint8_t fcs_err_cnt = 0;
uint8_t cv_err_cnt = 0;
uint8_t peak_attempts = 0;
uint8_t tx_fifo_tresh = 0;
uint8_t tx_fifo_thresh = 0;
bool tx_fifo_enable = false;
bool rx_fifo_enable = false;
uint16_t tx_fifo_size = 0;
+1 -1
View File
@@ -35,7 +35,7 @@ constexpr auto MACE_ID_REV_B0 = 0x0940; // Darwin-0.3 source
constexpr auto MACE_ID_REV_A2 = 0x0941; // Darwin-0.3 source & Curio datasheet
/** MACE registers offsets. */
// Refer to the Am79C940 datasheet for details
// Refer to the Am79C950 datasheet for details
namespace MaceEnet {
enum MaceReg : uint8_t {
Rcv_FIFO = 0,
+1 -1
View File
@@ -21,10 +21,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file Support for reading and writing of various floppy images. */
#include <core/memaccess.h>
#include <devices/floppy/floppyimg.h>
#include <machines/machineproperties.h>
#include <loguru.hpp>
#include <memaccess.h>
#include <utils/imgfile.h>
#include <cinttypes>
+9 -2
View File
@@ -150,11 +150,18 @@ void MacSuperDrive::set_motor_stat(uint8_t new_motor_stat)
this->track_start_time = 0;
this->sector_start_time = 0;
this->init_track_search(-1);
this->is_ready = 1;
// Only assert is_ready (SEEK_COMPLETE) when a disk is present.
// A real drive with no media can spin the motor but will never
// lock onto a track, so SEEK_COMPLETE stays de-asserted.
this->is_ready = this->has_disk;
LOG_F(INFO, "%s: turn spindle motor on", this->get_name().c_str());
} else {
this->motor_on_time = 0;
this->is_ready = 0;
// NB: do NOT clear is_ready here. Status address 0xE (Drive_Ready /
// SEEK_COMPLETE on Apple Drive Interface) reflects "no seek
// currently in progress", not motor state. Clearing it on motor-off
// makes the BeOS bootloader spin forever polling Drive_Ready after
// it asks the empty Superdrive to power down.
LOG_F(INFO, "%s: turn spindle motor off", this->get_name().c_str());
}
}
+29 -23
View File
@@ -68,6 +68,8 @@ AMIC::AMIC() : MMIODevice()
this->escc = dynamic_cast<EsccController*>(gMachineObj->get_comp_by_name("Escc"));
this->escc_xmit_b_dma = std::unique_ptr<AmicSerialXmitDma>(new AmicSerialXmitDma("EsccBXmit"));
this->escc_xmit_a_dma = std::unique_ptr<AmicSerialXmitDma>(new AmicSerialXmitDma("EsccAXmit"));
this->escc_rcv_b_dma = std::unique_ptr<AmicSerialRcvDma>(new AmicSerialRcvDma("EsccBRcv"));
this->escc_rcv_a_dma = std::unique_ptr<AmicSerialRcvDma>(new AmicSerialRcvDma("EsccARcv"));
// connect Ethernet HW
this->mace = dynamic_cast<MaceController*>(gMachineObj->get_comp_by_name("Mace"));
@@ -150,6 +152,10 @@ uint32_t AMIC::read(uint32_t rgn_start, uint32_t offset, int size)
}
case 0x14: // Sound registers
switch (offset) {
case AMICReg::Snd_Ctrl_0:
case AMICReg::Snd_Ctrl_1:
case AMICReg::Snd_Ctrl_2:
return this->imm_snd_regs[offset & 3];
case AMICReg::Snd_Stat_0:
case AMICReg::Snd_Stat_1:
case AMICReg::Snd_Stat_2:
@@ -218,19 +224,19 @@ uint32_t AMIC::read(uint32_t rgn_start, uint32_t offset, int size)
case SCC_DMA_Xmt_A_Ctrl:
return this->escc_xmit_a_dma->read_stat();
case SCC_RXA_Byte_Cnt_Hi:
return this->escc_rcv_a_dma.get_byte_count_hi();
return this->escc_rcv_a_dma->get_byte_count_hi();
case SCC_RXA_Byte_Cnt_Lo:
return this->escc_rcv_a_dma.get_byte_count_lo();
return this->escc_rcv_a_dma->get_byte_count_lo();
case SCC_DMA_Rcv_A_Ctrl:
return this->escc_rcv_a_dma.read_stat();
return this->escc_rcv_a_dma->read_stat();
case SCC_DMA_Xmt_B_Ctrl:
return this->escc_xmit_b_dma->read_stat();
case SCC_RXB_Byte_Cnt_Hi:
return this->escc_rcv_b_dma.get_byte_count_hi();
return this->escc_rcv_b_dma->get_byte_count_hi();
case SCC_RXB_Byte_Cnt_Lo:
return this->escc_rcv_b_dma.get_byte_count_lo();
return this->escc_rcv_b_dma->get_byte_count_lo();
case SCC_DMA_Rcv_B_Ctrl:
return this->escc_rcv_b_dma.read_stat();
return this->escc_rcv_b_dma->read_stat();
default:
LOG_F(WARNING, "Unknown AMIC register read, offset=%x", offset);
}
@@ -444,15 +450,15 @@ void AMIC::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size)
break;
case AMICReg::SCC_DMA_Rcv_A_Ctrl:
LOG_F(INFO, "AMIC SCC Receive Ch A DMA Ctrl updated, val=%x", value);
this->escc_rcv_a_dma.write_ctrl(value);
this->escc_rcv_a_dma->write_ctrl(value);
break;
case AMICReg::SCC_RXA_Byte_Cnt_Hi:
this->escc_rcv_a_dma.set_byte_count(
(this->escc_rcv_a_dma.get_byte_count_lo()) | ((value & 0x1F) << 8));
this->escc_rcv_a_dma->set_byte_count(
(this->escc_rcv_a_dma->get_byte_count_lo()) | ((value & 0x1F) << 8));
break;
case AMICReg::SCC_RXA_Byte_Cnt_Lo:
this->escc_rcv_a_dma.set_byte_count(
(this->escc_rcv_a_dma.get_byte_count_hi() << 8) | (value & 0xFF));
this->escc_rcv_a_dma->set_byte_count(
(this->escc_rcv_a_dma->get_byte_count_hi() << 8) | (value & 0xFF));
break;
case AMICReg::SCC_DMA_Xmt_B_Ctrl:
LOG_F(INFO, "AMIC SCC Transmit Ch B DMA Ctrl updated, val=%x", value);
@@ -460,15 +466,15 @@ void AMIC::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size)
break;
case AMICReg::SCC_DMA_Rcv_B_Ctrl:
LOG_F(INFO, "AMIC SCC Receive Ch B DMA Ctrl updated, val=%x", value);
this->escc_rcv_b_dma.write_ctrl(value);
this->escc_rcv_b_dma->write_ctrl(value);
break;
case AMICReg::SCC_RXB_Byte_Cnt_Hi:
this->escc_rcv_b_dma.set_byte_count(
(this->escc_rcv_b_dma.get_byte_count_lo()) | ((value & 0x1F) << 8));
this->escc_rcv_b_dma->set_byte_count(
(this->escc_rcv_b_dma->get_byte_count_lo()) | ((value & 0x1F) << 8));
break;
case AMICReg::SCC_RXB_Byte_Cnt_Lo:
this->escc_rcv_b_dma.set_byte_count(
(this->escc_rcv_b_dma.get_byte_count_hi() << 8) | (value & 0xFF));
this->escc_rcv_b_dma->set_byte_count(
(this->escc_rcv_b_dma->get_byte_count_hi() << 8) | (value & 0xFF));
break;
default:
LOG_F(WARNING, "Unknown AMIC register write, offset=%x, val=%x",
@@ -713,7 +719,7 @@ void AmicFloppyDma::write_ctrl(uint8_t value)
}
}
int AmicFloppyDma::push_data(const char* src_ptr, int len)
DmaPushResult AmicFloppyDma::push_data(const char* src_ptr, int len)
{
len = std::min((int)this->byte_count, len);
@@ -730,7 +736,7 @@ int AmicFloppyDma::push_data(const char* src_ptr, int len)
LOG_F(WARNING, "AMIC: DMA interrupts not implemented yet");
}
return 0;
return DmaPushResult::PushedData;
}
DmaPullResult AmicFloppyDma::pull_data(uint32_t req_len, uint32_t *avail_len,
@@ -764,7 +770,7 @@ void AmicScsiDma::write_ctrl(uint8_t value)
}
}
bool AmicScsiDma::is_ready() {
bool AmicScsiDma::dma_is_ready() {
return (this->stat & 2) ? true : false;
}
@@ -774,11 +780,11 @@ void AmicScsiDma::xfer_from_device() {
this->xfer_dir = DMA_DIR_FROM_DEV;
uint32_t len = this->dev_obj->tell_xfer_size();
uint32_t len = this->dev_obj->tell_xfer_size(this);
MapDmaResult res = mmu_map_dma_mem(this->addr_ptr, len, false);
int got_bytes = this->dev_obj->xfer_from(res.host_va, len);
int got_bytes = this->dev_obj->xfer_from(this, res.host_va, len);
if (got_bytes > 0) {
this->addr_ptr += got_bytes;
}
@@ -790,11 +796,11 @@ void AmicScsiDma::xfer_to_device() {
this->xfer_dir = DMA_DIR_TO_DEV;
uint32_t len = this->dev_obj->tell_xfer_size();
uint32_t len = this->dev_obj->tell_xfer_size(this);
MapDmaResult res = mmu_map_dma_mem(this->addr_ptr, len, false);
int got_bytes = this->dev_obj->xfer_to(res.host_va, len);
int got_bytes = this->dev_obj->xfer_to(this, res.host_va, len);
if (got_bytes > 0) {
this->addr_ptr += got_bytes;
}
+49 -14
View File
@@ -146,7 +146,7 @@ public:
void write_ctrl(const uint8_t value);
uint8_t read_stat() { return this->stat; }
int push_data(const char* src_ptr, int len);
DmaPushResult push_data(const char* src_ptr, int len);
DmaPullResult pull_data(uint32_t req_len, uint32_t *avail_len,
uint8_t **p_data);
@@ -177,6 +177,9 @@ private:
/** AMIC specific Serial Receive DMA channel (stub — control register only). */
class AmicSerialRcvDma {
public:
AmicSerialRcvDma(const std::string name) {}
~AmicSerialRcvDma() = default;
void write_ctrl(const uint8_t value);
uint8_t read_stat() { return this->stat; }
void set_byte_count(const uint16_t count) { this->byte_count = count; }
@@ -202,7 +205,7 @@ public:
void xfer_to_device();
void xfer_from_device();
bool is_ready() override;
bool dma_is_ready() override;
void xfer_retry() override;
private:
@@ -276,6 +279,13 @@ enum AMICReg : uint32_t {
DMA_Base_Addr_1 = 0x31001,
DMA_Base_Addr_2 = 0x31002,
DMA_Base_Addr_3 = 0x31003,
DMA_Bus_Error_IE0 = 0x32100,
DMA_Bus_Error_IE1 = 0x32101,
DMA_Bus_Error_IF0 = 0x32102,
DMA_Bus_Error_IF1 = 0x32103,
//Ethernet DMA
Enet_DMA_Xmt_Ctrl = 0x31C20,
Enet_DMA_Rcv_Ctrl = 0x32028,
@@ -285,6 +295,10 @@ enum AMICReg : uint32_t {
SCSI_DMA_Base_2 = 0x32002,
SCSI_DMA_Base_3 = 0x32003,
SCSI_DMA_Ctrl = 0x32008,
SCSI_DMA_Addr_Ptr_0 = 0x32010,
SCSI_DMA_Addr_Ptr_1 = 0x32011,
SCSI_DMA_Addr_Ptr_2 = 0x32012,
SCSI_DMA_Addr_Ptr_3 = 0x32013,
// Floppy (SWIM3) DMA registers
Floppy_Addr_Ptr_0 = 0x32060,
@@ -295,19 +309,40 @@ enum AMICReg : uint32_t {
Floppy_Byte_Cnt_Lo = 0x32065,
Floppy_DMA_Ctrl = 0x32068,
// SSC DMA Channel A Transmit registers
SCC_DMA_Xmt_A_Adr_3 = 0x32080,
SCC_DMA_Xmt_A_Adr_2 = 0x32081,
SCC_DMA_Xmt_A_Adr_1 = 0x32082,
SCC_RXA_Xmt_A_Adr_0 = 0x32083,
SCC_TXA_Byte_Cnt_Hi = 0x32084,
SCC_TXA_Byte_Cnt_Lo = 0x32085,
SCC_DMA_Xmt_A_Ctrl = 0x32088,
// = 0x32092, // byte, read
// = 0x32093, // byte, read
SCC_RXA_Byte_Cnt_Hi = 0x32094, // 5 bits, read; byte, write 0x10
SCC_RXA_Byte_Cnt_Lo = 0x32095, // 8 bits, read; byte, write 0x00
// SSC DMA Channel A Receive registers
SCC_DMA_Rcv_A_Adr_3 = 0x32090,
SCC_DMA_Rcv_A_Adr_2 = 0x32091,
SCC_DMA_Rcv_A_Adr_1 = 0x32092,
SCC_RXA_Rcv_A_Adr_0 = 0x32093,
SCC_RXA_Byte_Cnt_Hi = 0x32094,
SCC_RXA_Byte_Cnt_Lo = 0x32095,
SCC_DMA_Rcv_A_Ctrl = 0x32098,
// = 0x320A4, // byte, write 0x00
// = 0x320A5, // byte, write 0x07
// SSC DMA Channel B Transmit registers
SCC_DMA_Xmt_B_Adr_3 = 0x320A0,
SCC_DMA_Xmt_B_Adr_2 = 0x320A1,
SCC_DMA_Xmt_B_Adr_1 = 0x320A2,
SCC_RXA_Xmt_B_Adr_0 = 0x320A3,
SCC_TXB_Byte_Cnt_Hi = 0x320A4,
SCC_TXB_Byte_Cnt_Lo = 0x320A5,
SCC_DMA_Xmt_B_Ctrl = 0x320A8,
// = 0x320B2, // byte, read
// = 0x320B3, // byte, read
SCC_RXB_Byte_Cnt_Hi = 0x320B4, // 5 bits, read; byte, write 0x10
SCC_RXB_Byte_Cnt_Lo = 0x320B5, // 8 bits, read; byte, write 0x00
// SSC DMA Channel B Receive registers
SCC_DMA_Rcv_B_Adr_3 = 0x320B0,
SCC_DMA_Rcv_B_Adr_2 = 0x320B1,
SCC_DMA_Rcv_B_Adr_1 = 0x320B2,
SCC_RXA_Rcv_B_Adr_0 = 0x320B3,
SCC_RXB_Byte_Cnt_Hi = 0x320B4,
SCC_RXB_Byte_Cnt_Lo = 0x320B5,
SCC_DMA_Rcv_B_Ctrl = 0x320B8,
};
@@ -391,8 +426,8 @@ private:
std::unique_ptr<AmicScsiDma> curio_dma;
std::unique_ptr<AmicSerialXmitDma> escc_xmit_b_dma;
std::unique_ptr<AmicSerialXmitDma> escc_xmit_a_dma;
AmicSerialRcvDma escc_rcv_b_dma;
AmicSerialRcvDma escc_rcv_a_dma;
std::unique_ptr<AmicSerialRcvDma> escc_rcv_b_dma;
std::unique_ptr<AmicSerialRcvDma> escc_rcv_a_dma;
// on-board video
std::unique_ptr<DisplayID> disp_id;
+40 -20
View File
@@ -19,6 +19,7 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <core/endianswap.h>
#include <cpu/ppc/ppcemu.h>
#include <devices/deviceregistry.h>
#include <devices/common/scsi/sc53c94.h>
@@ -26,7 +27,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <devices/floppy/swim3.h>
#include <devices/ioctrl/macio.h>
#include <devices/serial/escc.h>
#include <endianswap.h>
#include <loguru.hpp>
#include <machines/machinebase.h>
@@ -86,10 +86,10 @@ GrandCentral::GrandCentral() : PCIDevice("mac-io_grandcentral"), InterruptCtrl()
this->escc_a_rx_dma->register_dma_int(this, this->register_dma_int(IntSrc::DMA_SCCA_Rx));
this->escc_b_tx_dma->register_dma_int(this, this->register_dma_int(IntSrc::DMA_SCCB_Tx));
this->escc_b_rx_dma->register_dma_int(this, this->register_dma_int(IntSrc::DMA_SCCB_Rx));
this->escc->set_dma_channel(CH_A, DIR_TX, this->escc_a_tx_dma.get());
this->escc->set_dma_channel(CH_A, DIR_RX, this->escc_a_rx_dma.get());
this->escc->set_dma_channel(CH_B, DIR_TX, this->escc_b_tx_dma.get());
this->escc->set_dma_channel(CH_B, DIR_RX, this->escc_b_rx_dma.get());
this->escc->connect_dma_channel(CH_A, DIR_TX, this->escc_a_tx_dma.get());
this->escc->connect_dma_channel(CH_A, DIR_RX, this->escc_a_rx_dma.get());
this->escc->connect_dma_channel(CH_B, DIR_TX, this->escc_b_tx_dma.get());
this->escc->connect_dma_channel(CH_B, DIR_RX, this->escc_b_rx_dma.get());
// connect MESH (internal SCSI)
this->mesh = dynamic_cast<MeshBase*>(gMachineObj->get_comp_by_name_optional("MeshTnt"));
@@ -112,7 +112,6 @@ GrandCentral::GrandCentral() : PCIDevice("mac-io_grandcentral"), InterruptCtrl()
this->curio_dma->register_dma_int(this, this->register_dma_int(IntSrc::DMA_SCSI_CURIO));
this->curio_dma->connect(this->curio);
this->curio->connect(this->curio_dma.get());
//this->curio->set_dma_channel(this->curio_dma.get());
this->curio->set_drq_callback([this](const uint8_t drq_state) {
this->curio_dma->set_stat((drq_state & 1) << 5);
});
@@ -225,9 +224,9 @@ uint32_t GrandCentral::read(uint32_t rgn_start, uint32_t offset, int size)
}
case 0xA: // IOBus device #1 ; Board register 1 and bandit1 PRSNT bits
case 0xB: // IOBus device #2 ; RaDACal/DACula
case 0xC: // IOBus device #3 ; chaos or bandit2 PRSNT bits ; sixty6
case 0xC: // IOBus device #3 ; sixty6 // Open Firmware incorrectly reads chaos or bandit2 PRSNT bits from here
case 0xD: // IOBus device #4 ; NVRAM High Address
case 0xE: // IOBus device #5 ; sixty6 composite/s-video (not for fatman)
case 0xE: // IOBus device #5 ; Board register 2 and bandit2 PRSNT bits, sixty6 composite/s-video detect (not for fatman)
case 0xF: // IOBus device #6 ; NVRAM Data
if (this->iobus_devs[subdev_num - 10] != nullptr) {
uint64_t value = this->iobus_devs[subdev_num - 10]->iodev_read((offset >> 4) & 0x1F);
@@ -246,7 +245,7 @@ uint32_t GrandCentral::read(uint32_t rgn_start, uint32_t offset, int size)
break;
}
} else if (offset & 0x8000) { // DMA register space
unsigned dma_channel = (offset >> 8) & 0xF;
unsigned dma_channel = (offset >> 8) & 0x7F;
switch (dma_channel) {
case MIO_GC_DMA_SCSI_CURIO:
@@ -354,9 +353,9 @@ void GrandCentral::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
break;
case 0xA: // IOBus device #1 ; Board register 1 and bandit1 PRSNT bits
case 0xB: // IOBus device #2 ; RaDACal/DACula
case 0xC: // IOBus device #3 ; chaos or bandit2 PRSNT bits
case 0xC: // IOBus device #3 ; sixty6 // Open Firmware incorrectly reads chaos or bandit2 PRSNT bits from here
case 0xD: // IOBus device #4 ; NVRAM High Address
case 0xE: // IOBus device #5 ; sixty6 composite/s-video (not for fatman)
case 0xE: // IOBus device #5 ; Board register 2 and bandit2 PRSNT bits, sixty6 composite/s-video detect (not for fatman)
case 0xF: // IOBus device #6 ; NVRAM Data
uint16_t val;
switch (size) {
@@ -382,7 +381,7 @@ void GrandCentral::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
this->name.c_str(), this->base_addr + offset);
}
} else if (offset & 0x8000) { // DMA register space
unsigned dma_channel = (offset >> 8) & 0xF;
unsigned dma_channel = (offset >> 8) & 0x7F;
switch (dma_channel) {
case MIO_GC_DMA_SCSI_CURIO:
@@ -434,14 +433,18 @@ 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->signal_cpu_int(this->int_events & this->int_mask);
this->signal_cpu_int();
break;
case MIO_INT_CLEAR1:
if ((this->int_mask & MACIO_INT_MODE) && (value & MACIO_INT_CLR))
value = BYTESWAP_32(value);
if ((this->int_mask & MACIO_INT_MODE) && (value & MACIO_INT_CLR)) {
this->int_events = 0;
else
this->int_events &= ~(BYTESWAP_32(value) & 0x7FFFFFFFUL);
clear_cpu_int();
this->clear_cpu_int();
} else {
this->int_events &= ~(value & 0x7FFFFFFFUL);
this->clear_cpu_int();
this->clear_dma_int(value);
}
break;
case MIO_INT_LEVELS1:
break; // ignore writes to this read-only register
@@ -537,7 +540,7 @@ 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(irq_id);
this->signal_cpu_int();
}
void GrandCentral::ack_int(uint64_t irq_id, uint8_t irq_line_state) {
@@ -548,12 +551,29 @@ void GrandCentral::ack_dma_int(uint64_t irq_id, uint8_t irq_line_state) {
this->ack_int_common(irq_id, irq_line_state);
}
void GrandCentral::signal_cpu_int(uint64_t irq_id) {
void GrandCentral::clear_dma_int(uint32_t clear_flags) {
clear_flags &= 0x7FF; // mask off non-DMA interrupt flags
if (!clear_flags)
return; // return if no DMA IRQ clear bit is set
// emulated mode: set DMA IRQ bits in int_events on 1-to-0 transitions
// while clearing DMA bits in int_levels.
// Any pending bits in int_events will generate an interrupt
// that will be propagated to the 68k emulator
if (this->int_mask & MACIO_INT_MODE) {
this->int_events |= this->int_levels & clear_flags;
this->int_levels &= ~clear_flags;
this->signal_cpu_int();
} else // in native mode, 1-to-0 transitions don't generate interrupts
this->int_levels &= ~clear_flags;
}
void GrandCentral::signal_cpu_int() {
if (this->int_events & this->int_mask) {
if (!this->cpu_int_latch) {
this->cpu_int_latch = true;
ppc_assert_int();
LOG_F(5, "%s: CPU INT asserted, source: 0x%08llx", this->name.c_str(), irq_id);
} else {
LOG_F(5, "%s: CPU INT already latched", this->name.c_str());
}
+20 -49
View File
@@ -19,34 +19,7 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** MacIO device family emulation
Mac I/O (MIO) is a family of ASICs to bring support for Apple legacy
I/O hardware to the PCI-based Power Macintosh. That legacy hardware has
existed long before Power Macintosh was introduced. It includes:
- versatile interface adapter (VIA)
- Sander-Woz integrated machine (SWIM) that is a floppy disk controller
- CUDA MCU for ADB, parameter RAM, realtime clock and power management support
- serial communication controller (SCC)
- Macintosh Enhanced SCSI Hardware (MESH)
In the 68k Macintosh era, all this hardware was implemented using several
custom chips. In a PCI-compatible Power Macintosh, the above devices are part
of the MIO chip itself. MIO's functional blocks implementing virtual devices
are called "cells", i.e. "VIA cell", "SWIM cell" etc.
MIO itself is PCI compliant while the legacy hardware it emulates isn't.
MIO occupies 512Kb of the PCI memory space divided into registers space and
DMA space. Access to emulated legacy devices is accomplished by reading from/
writing to MIO's PCI address space at predefined offsets.
MIO includes a DMA controller that offers up to 12 DMA channels implementing
Apple's own DMA protocol called descriptor-based DMA (DBDMA).
Official documentation (that is somewhat incomplete and erroneous) can be
found in the second chapter of the book "Macintosh Technology in the Common
Hardware Reference Platform" by Apple Computer, Inc.
*/
/** @file MacIO device family emulation. */
#ifndef MACIO_H
#define MACIO_H
@@ -80,7 +53,7 @@ enum {
};
/** Interrupt related constants. */
#define MACIO_INT_CLR 0x80UL // clears bits in the interrupt events registers
#define MACIO_INT_CLR 0x80000000UL // clears all bits in the interrupt events registers
#define MACIO_INT_MODE 0x80000000UL // interrupt mode: 0 - native, 1 - 68k-style
#define INT_TO_IRQ_ID(intx) (1ULL << intx)
@@ -157,6 +130,9 @@ public:
MacIoBase(std::string name, uint16_t dev_id, uint8_t rev=1);
~MacIoBase() = default;
// IOBus devices management
void attach_iobus_device(int dev_num, IobusDevice* dev_obj);
uint64_t register_dma_int(IntSrc src_id) override;
void ack_int(uint64_t irq_id, uint8_t irq_line_state) override;
void ack_dma_int(uint64_t irq_id, uint8_t irq_line_state) override;
@@ -164,6 +140,7 @@ public:
protected:
void notify_bar_change(int bar_num);
void ack_int_common(uint64_t irq_id, uint8_t irq_line_state);
void clear_dma_int(uint32_t clear_flags);
void signal_cpu_int();
void clear_cpu_int();
@@ -183,6 +160,9 @@ protected:
MacioSndCodec* snd_codec; // audio codec instance
EsccController* escc; // ESCC serial controller
// IOBus devices
IobusDevice* iobus_devs[6] = { nullptr };
// DMA channels
std::unique_ptr<DMAChannel> floppy_dma;
std::unique_ptr<DMAChannel> snd_out_dma;
@@ -206,9 +186,9 @@ public:
uint32_t read(uint32_t rgn_start, uint32_t offset, int size) override;
void write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size) override;
// InterruptCtrl methods
void attach_iodevice(int dev_num, IobusDevice* dev_obj);
// InterruptCtrl methods
uint64_t register_dev_int(IntSrc src_id) override;
uint64_t register_dma_int(IntSrc src_id) override;
void ack_int(uint64_t irq_id, uint8_t irq_line_state) override;
@@ -217,7 +197,8 @@ public:
protected:
void notify_bar_change(int bar_num);
void ack_int_common(uint64_t irq_id, uint8_t irq_line_state);
void signal_cpu_int(uint64_t irq_id);
void clear_dma_int(uint32_t clear_flags);
void signal_cpu_int();
void clear_cpu_int();
private:
@@ -263,20 +244,11 @@ private:
/** O'Hare/Heathrow specific registers. */
enum {
MIO_OHARE_ENTRY_SPT = 0x30, // entry systems support register
MIO_OHARE_ID = 0x34, // IDs register
MIO_OHARE_FEAT_CTRL = 0x38, // feature control register
MIO_AUX_CTRL = 0x3C,
};
/** MIO_OHARE_ID bits. */
enum {
MIO_OH_ID_FP = 0x70000000, // Flat panel ID
MIO_OH_ID_MON = 0x00300000, // Monitor ID (mon_id?=1, no s-video/composite=3 but only if fatman exists).
MIO_OH_ID_MB = 0x0000F000, // Media Bay ID (0,1=swim, 3=ata, 5=pci, 7=?, 4=TAM)
MIO_OH_ID_CPU = 0x000000E0, // CPUID field
MIO_OH_ID_DISABLE_SCSI_TERMINATORS = 0x00000010, // clear this bit to disable-scsi-terminators - read this bit for emmo_pin
MIO_OH_ID_ENABLE_SCSI_TERMINATORS = 0x00000008, // set this bit to enable-scsi-terminators
MIO_OH_ID_DO_SCSI_TERMINATORS = 0x00000001, // set this bit to enable or disable scsi-terminators
MIO_HEATH_AUX_CTRL = 0x3C, // auxiliary feature control/internal ints register
// (Heathrow/Paddington only)
};
/** MIO_OHARE_FEAT_CTRL bits. */
@@ -310,10 +282,10 @@ enum {
MIO_OH_FC_RESET_SCC = 1 << 25,
MIO_OH_FC_MFDC_CELL_EN = 1 << 26, // Heathrow/Paddington only
MIO_OH_FC_USE_MFDC = 1 << 27, // Heathrow/Paddington only
MIO_OH_FC_RESVD28 = 1 << 28,
MIO_OH_FC_RESVD29 = 1 << 29,
MIO_OH_FC_RESVD30 = 1 << 30,
MIO_OH_FC_RESVD31 = 1 << 31,
MIO_OH_FC_ADB_CELL_EN = 1 << 28, // Heathrow/Paddington only
MIO_OH_FC_ETH_EN = 1 << 29, // Heathrow/Paddington only
MIO_OH_FC_ETH_XCVR_EN = 1 << 30, // Heathrow/Paddington only
MIO_OH_FC_RESET_ETH_CELL = 1 << 31, // Heathrow/Paddington only
};
/** O'Hare/Heathrow DBDMA channels. */
@@ -387,11 +359,10 @@ private:
uint32_t feat_ctrl = 0; // features control register
uint32_t aux_ctrl = 0; // aux features control register
uint8_t cpu_id = 0xE0; // CPUID field (LSB of the MIO_HEAT_ID)
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 emmo = 0x01; // factory tester status, active low
// Subdevice object pointers
NVram* nvram; // NVRAM
+32 -4
View File
@@ -86,10 +86,10 @@ MacIoBase::MacIoBase(std::string name, uint16_t dev_id, uint8_t rev) :
this->escc_a_rx_dma->register_dma_int(this, this->register_dma_int(IntSrc::DMA_SCCA_Rx));
this->escc_b_tx_dma->register_dma_int(this, this->register_dma_int(IntSrc::DMA_SCCB_Tx));
this->escc_b_rx_dma->register_dma_int(this, this->register_dma_int(IntSrc::DMA_SCCB_Rx));
this->escc->set_dma_channel(CH_A, DIR_TX, this->escc_a_tx_dma.get());
this->escc->set_dma_channel(CH_A, DIR_RX, this->escc_a_rx_dma.get());
this->escc->set_dma_channel(CH_B, DIR_TX, this->escc_b_tx_dma.get());
this->escc->set_dma_channel(CH_B, DIR_RX, this->escc_b_rx_dma.get());
this->escc->connect_dma_channel(CH_A, DIR_TX, this->escc_a_tx_dma.get());
this->escc->connect_dma_channel(CH_A, DIR_RX, this->escc_a_rx_dma.get());
this->escc->connect_dma_channel(CH_B, DIR_TX, this->escc_b_tx_dma.get());
this->escc->connect_dma_channel(CH_B, DIR_RX, this->escc_b_rx_dma.get());
}
void MacIoBase::notify_bar_change(int bar_num) {
@@ -107,6 +107,16 @@ void MacIoBase::notify_bar_change(int bar_num) {
}
}
void MacIoBase::attach_iobus_device(int dev_num, IobusDevice* dev_obj) {
if (dev_num >= 0 && dev_num < (this->device_id >= MIO_DEV_ID_OHARE ? 4 : 6)) {
if (this->iobus_devs[dev_num])
LOG_F(WARNING, "%s: replacing existing IOBus device #%d",
this->name.c_str(), dev_num + 1);
this->iobus_devs[dev_num] = dev_obj;
} else
LOG_F(WARNING, "%s: invalid IOBus device #%d", this->name.c_str(), dev_num + 1);
}
uint64_t MacIoBase::register_dma_int(IntSrc src_id) {
switch (src_id) {
case IntSrc::DMA_SWIM3 : return INT_TO_IRQ_ID(0x01);
@@ -156,6 +166,24 @@ void MacIoBase::ack_dma_int(uint64_t irq_id, uint8_t irq_line_state) {
this->ack_int_common(irq_id, irq_line_state);
}
void MacIoBase::clear_dma_int(uint32_t clear_flags) {
clear_flags &= 0x7FF; // mask off non-DMA interrupt flags
if (!clear_flags)
return; // return if no DMA IRQ clear bit is set
// emulated mode: set DMA IRQ bits in int_events on 1-to-0 transitions
// while clearing DMA bits in int_levels.
// Any pending bits in int_events will generate an interrupt
// that will be propagated to the 68k emulator
if (this->int_mask & MACIO_INT_MODE) {
this->int_events |= this->int_levels & clear_flags;
this->int_levels &= ~clear_flags;
this->signal_cpu_int();
} else // in native mode, 1-to-0 transitions don't generate interrupts
this->int_levels &= ~clear_flags;
}
void MacIoBase::signal_cpu_int() {
if (this->int_events & this->int_mask) {
if (!this->cpu_int_latch) {
+77 -18
View File
@@ -58,9 +58,6 @@ MacIoTwo::MacIoTwo(std::string name, uint16_t dev_id) : MacIoBase(name, dev_id)
this->enet_xmit_dma = std::unique_ptr<DMAChannel> (new DMAChannel("BmacTx"));
this->enet_rcv_dma = std::unique_ptr<DMAChannel> (new DMAChannel("BmacRx"));
}
// set EMMO status (active low)
this->emmo = GET_BIN_PROP("emmo") ^ 1;
}
uint32_t MacIoTwo::read(uint32_t rgn_start, uint32_t offset, int size) {
@@ -217,9 +214,14 @@ uint32_t MacIoTwo::dma_read(uint32_t offset, int size) {
return this->enet_xmit_dma->reg_read(offset & 0xFF, size);
case MIO_OHARE_DMA_ETH_RCV:
return this->enet_rcv_dma->reg_read(offset & 0xFF, size);
case MIO_OHARE_DMA_ESCC_A_XMIT:
return this->escc_a_tx_dma->reg_read(offset & 0xFF, size);
case MIO_OHARE_DMA_ESCC_A_RCV:
return this->escc_a_rx_dma->reg_read(offset & 0xFF, size);
case MIO_OHARE_DMA_ESCC_B_XMIT:
return this->escc_b_tx_dma->reg_read(offset & 0xFF, size);
case MIO_OHARE_DMA_ESCC_B_RCV:
return 0;
//return this->escc_b_rx_dma->reg_read(offset & 0xFF, size);
return this->escc_b_rx_dma->reg_read(offset & 0xFF, size);
case MIO_OHARE_DMA_AUDIO_OUT:
return this->snd_out_dma->reg_read(offset & 0xFF, size);
case MIO_OHARE_DMA_IDE0:
@@ -253,6 +255,15 @@ void MacIoTwo::dma_write(uint32_t offset, uint32_t value, int size) {
case MIO_OHARE_DMA_ETH_RCV:
this->enet_rcv_dma->reg_write(offset & 0xFF, value, size);
break;
case MIO_OHARE_DMA_ESCC_A_XMIT:
this->escc_a_tx_dma->reg_write(offset & 0xFF, value, size);
break;
case MIO_OHARE_DMA_ESCC_A_RCV:
this->escc_a_rx_dma->reg_write(offset & 0xFF, value, size);
break;
case MIO_OHARE_DMA_ESCC_B_XMIT:
this->escc_b_tx_dma->reg_write(offset & 0xFF, value, size);
break;
case MIO_OHARE_DMA_ESCC_B_RCV:
this->escc_b_rx_dma->reg_write(offset & 0xFF, value, size);
break;
@@ -278,7 +289,7 @@ void MacIoTwo::dma_write(uint32_t offset, uint32_t value, int size) {
uint32_t MacIoTwo::mio_ctrl_read(uint32_t offset, int size) {
uint32_t value;
switch (offset & 0xFC) {
switch (offset & ~3) {
case MIO_INT_EVENTS2:
value = this->int_events >> 32;
break;
@@ -305,7 +316,7 @@ uint32_t MacIoTwo::mio_ctrl_read(uint32_t offset, int size) {
break;
case MIO_OHARE_ID:
value = (this->fp_id << 24) | (this->mon_id << 16) | (this->mb_id << 8) |
(this->cpu_id | (this->emmo << 4));
(this->cpu_id);
LOG_F(9, "%s: read OHARE_ID @%02x = %08x",
this->get_name().c_str(), offset, value);
break;
@@ -320,21 +331,50 @@ uint32_t MacIoTwo::mio_ctrl_read(uint32_t offset, int size) {
this->get_name().c_str(), offset);
}
return BYTESWAP_32(value);
if (!((offset | size) & 3)) // aligned DWORD reads --> fast path
return BYTESWAP_32(value);
else {
uint32_t mask = (1ULL << (size * 8)) - 1;
if (((offset & 3) + size) <= 4) // partial register reads
return BYTESWAP_SIZED(value >> ((offset & 3) * 8), size) & mask;
else { // spanning reads; don't make much sense but the HW supports them anyway
uint32_t value2 = this->mio_ctrl_read((offset & ~3) + 4, 4);
value = REG_READ_HELPER(BYTESWAP_32(value), value2, offset & 3, size);
LOG_F(WARNING, "%s: spanning register read, offset = 0x%X, size = %d",
this->get_name().c_str(), offset, size);
return value;
}
}
}
void MacIoTwo::mio_ctrl_write(uint32_t offset, uint32_t value, int size) {
switch (offset & 0xFC) {
uint32_t mask = (1ULL << (size * 8)) - 1;
if (!((offset | size) & 3)) // aligned DWORD writes --> fast path
value = BYTESWAP_32(value);
else {
if (((offset & 3) + size) > 4)
LOG_F(WARNING, "%s: spanning register write, "
"offset = 0x%X, size = %d, value = 0x%X",
this->get_name().c_str(), offset, size, value);
value = BYTESWAP_SIZED(value, size) << ((offset & 3) * 8);
mask <<= (offset & 3);
if (offset <= MIO_OHARE_ENTRY_SPT || offset >= MIO_OHARE_FEAT_CTRL)
value = (this->mio_ctrl_read(offset & ~3, 4) & ~mask) | value;
}
switch (offset & ~3) {
case MIO_INT_MASK2:
this->int_mask |= uint64_t(BYTESWAP_32(value) & ~MACIO_INT_MODE) << 32;
this->int_mask |= uint64_t(value & ~MACIO_INT_MODE) << 32;
this->signal_cpu_int();
break;
case MIO_INT_CLEAR2:
this->int_events &= ~(uint64_t(BYTESWAP_32(value) & 0x7FFFFFFFUL) << 32);
this->int_events &= ~(uint64_t(value & 0x7FFFFFFFUL) << 32);
clear_cpu_int();
break;
case MIO_INT_MASK1:
this->int_mask = (this->int_mask & 0x7FFFFFFF00000000ULL) | BYTESWAP_32(value);
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->signal_cpu_int();
@@ -342,21 +382,38 @@ void MacIoTwo::mio_ctrl_write(uint32_t offset, uint32_t value, int size) {
case MIO_INT_CLEAR1:
if ((this->int_mask & MACIO_INT_MODE) && (value & MACIO_INT_CLR)) {
this->int_events = 0;
this->clear_cpu_int();
} else {
this->int_events &= ~uint64_t(BYTESWAP_32(value) & 0x7FFFFFFFUL);
this->int_events &= ~uint64_t(value & 0x7FFFFFFFUL);
this->clear_cpu_int();
this->clear_dma_int(value);
}
clear_cpu_int();
break;
case MIO_INT_LEVELS1:
// The purpose of this stub is to silence warnings in the log when
// writing to this read-only register. Especially, SCSI Manager 4.3
// writes to it in clearSCSIxIRQ(). Don't ask me why.
// Doing that has no effect - IRQ flags are cleared in the Nanokernel.
break;
case MIO_OHARE_ID:
LOG_F(ERROR, "%s: write OHARE_ID @%x.%c = %0*x",
this->get_name().c_str(), offset, SIZE_ARG(size), size * 2, value);
if (mask & 0xFF)
LOG_F(INFO, "%s: CPU_ID register written with 0x%X", this->name.c_str(), value & 0xFF);
if (mask & 0xFF00)
LOG_F(INFO, "%s: MB_ID register written with 0x%X", this->name.c_str(),
(value >> 8) & 0xFF);
if (mask & 0xFF0000)
LOG_F(INFO, "%s: MON_ID register written with 0x%X", this->name.c_str(),
(value >> 16) & 0xFF);
if (mask & 0xFF000000UL)
LOG_F(INFO, "%s: FP_ID register written with 0x%X", this->name.c_str(),
(value >> 24) & 0xFF);
break;
case MIO_OHARE_FEAT_CTRL:
LOG_F(WARNING, "%s: write FEAT_CTRL @%x.%c = %0*x",
this->get_name().c_str(), offset, SIZE_ARG(size), size * 2, value);
this->feature_control(BYTESWAP_32(value));
this->feature_control(value);
break;
case MIO_AUX_CTRL:
case MIO_HEATH_AUX_CTRL:
LOG_F(9, "%s: write AUX_CTRL @%x.%c = %0*x",
this->get_name().c_str(), offset, SIZE_ARG(size), size * 2, value);
this->aux_ctrl = value;
@@ -409,6 +466,8 @@ uint64_t MacIoTwo::register_dev_int(IntSrc src_id) {
? INT_TO_IRQ_ID(0x1C)
: INT_TO_IRQ_ID(0x19);
case IntSrc::VALKYRIE : return INT_TO_IRQ_ID(0x18); // Alchemy built-in video
case IntSrc::PERCH2 : return INT_TO_IRQ_ID(0x15);
case IntSrc::PCI_GPU : return INT_TO_IRQ_ID(0x16);
case IntSrc::PERCH1 : return INT_TO_IRQ_ID(0x1A);
+10 -6
View File
@@ -57,12 +57,15 @@ void HMC::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size)
switch(offset) {
case 0:
bit = 1ULL << this->bit_pos++;
this->ctrl_reg = (value & 1) ? this->ctrl_reg | bit :
this->ctrl_reg & ~bit;
this->ctrl_reg = (value & 1) ?
this->ctrl_reg | bit
:
this->ctrl_reg & ~bit;
if (this->bit_pos >= HMC_CTRL_BITS) {
this->bit_pos = 0;
if (((this->ctrl_reg >> HMC_RAM_CFG_POS) & 3) != this->bank_config) {
this->bank_config = (this->ctrl_reg >> HMC_RAM_CFG_POS) & 3;
uint8_t new_bank_config = (this->ctrl_reg >> HMC_RAM_CFG_POS) & 3;
if (new_bank_config != this->bank_config) {
this->bank_config = new_bank_config;
this->remap_ram_regions();
}
}
@@ -76,7 +79,7 @@ void HMC::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size)
void HMC::remap_ram_regions() {
uint32_t bank_b_addr;
switch (this->bank_config & 3) {
switch (this->bank_config) {
case BANK_CFG_128MB:
bank_b_addr = BANK_B_START;
break;
@@ -165,7 +168,8 @@ int HMC::install_ram(uint32_t mb_bank_size, uint32_t bank_a_size, uint32_t bank_
// for the warm start signature.
if (bank_a_size < BANK_SIZE_8MB) {
for (uint32_t alias_start = BANK_B_START + bank_a_size - BANK_SIZE_8MB;
alias_start < BANK_B_START; alias_start += bank_a_size) {
alias_start < BANK_B_START; alias_start += bank_a_size
) {
if (!this->add_mem_mirror(alias_start, this->bank_a_start)) {
LOG_F(ERROR, "%s: could not create alias for RAM bank A!",
this->name.c_str());
+6
View File
@@ -433,6 +433,12 @@ AddressMapEntry* MemCtrlBase::remove_region(AddressMapEntry* entry)
}
#if SUPPORTS_MEMORY_CTRL_ENDIAN_MODE
bool MemCtrlBase::needs_swap_endian(bool is_mmio) {
return false;
}
#endif
AddressMapEntry* MemCtrlBase::find_rom_region()
{
for (auto& entry : address_map) {
+11 -1
View File
@@ -38,13 +38,16 @@ enum {
DRAM_CAP_32MB = (1 << 25),
DRAM_CAP_64MB = (1 << 26),
DRAM_CAP_128MB = (1 << 27),
DRAM_CAP_256MB = (1 << 28),
DRAM_CAP_512MB = (1 << 29),
};
enum RangeType {
RT_NONE = 0,
RT_ROM = 1, // read-only memory
RT_RAM = 2, // random access memory
RT_MMIO = 4, // memory mapped I/O
RT_MIRROR = 8 // region mirror (content of another region acessible at some
RT_MIRROR = 8, // region mirror (content of another region acessible at some
// other address)
};
@@ -80,6 +83,13 @@ public:
virtual AddressMapEntry* set_data(uint32_t reg_addr, const uint8_t* data, uint32_t size);
#if SUPPORTS_MEMORY_CTRL_ENDIAN_MODE
virtual bool needs_swap_endian(bool is_mmio);
bool needs_swap_endian(AddressMapEntry* entry) {
return needs_swap_endian((entry->type & RT_MMIO) != 0);
}
#endif
AddressMapEntry* find_range(uint32_t addr);
AddressMapEntry* find_range_exact(uint32_t addr, uint32_t size,
MMIODevice* dev_instance);
+6
View File
@@ -59,6 +59,12 @@ int MPC106::device_postinit()
return this->pcihost_device_postinit();
}
#if SUPPORTS_MEMORY_CTRL_ENDIAN_MODE
bool MPC106::needs_swap_endian(bool is_mmio) {
return is_mmio && needs_swap_endian_pci();
}
#endif
uint32_t MPC106::read(uint32_t rgn_start, uint32_t offset, int size) {
if (rgn_start == 0xFE000000) {
return pci_io_read_broadcast(offset, size);
+10
View File
@@ -174,6 +174,10 @@ public:
uint32_t read(uint32_t rgn_start, uint32_t offset, int size) override;
void write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size) override;
#if SUPPORTS_MEMORY_CTRL_ENDIAN_MODE
bool needs_swap_endian(bool is_mmio) override;
#endif
int device_postinit() override;
protected:
@@ -188,6 +192,12 @@ private:
int &fun_num, uint8_t &reg_offs, AccessDetails &details,
PCIBase *&device);
#if SUPPORTS_MEMORY_CTRL_ENDIAN_MODE
inline bool needs_swap_endian_pci() {
return (picr1 & LE_MODE) != 0;
}
#endif
uint32_t config_addr;
uint16_t pmcr1 = 0; // power management config 1
+1 -1
View File
@@ -21,6 +21,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** Platinum Memory/Display Controller emulation. */
#include <core/memaccess.h>
#include <core/timermanager.h>
#include <devices/deviceregistry.h>
#include <devices/ioctrl/macio.h>
@@ -28,7 +29,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <devices/video/displayid.h>
#include <loguru.hpp>
#include <machines/machinebase.h>
#include <memaccess.h>
#include <cinttypes>
+3 -3
View File
@@ -38,9 +38,9 @@ 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;
this->chip_rev = 0; // old PSX, what's about PSX+?
this->sys_config = PSX_BUS_SPEED_50;
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
}
uint32_t PsxCtrl::read(uint32_t rgn_start, uint32_t offset, int size)
+19 -1
View File
@@ -24,6 +24,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef PSX_MEMCTRL_H
#define PSX_MEMCTRL_H
#include <core/bitops.h>
#include <devices/common/mmiodevice.h>
#include <devices/memctrl/memctrlbase.h>
@@ -50,7 +51,8 @@ namespace PsxReg {
} // namespace PsxReg
/** Bus (aka CPU) speed constants. */
enum {
using PsxBusSpeed = uint32_t;
enum : PsxBusSpeed {
PSX_BUS_SPEED_38 = 0, // bus frequency 38 MHz
PSX_BUS_SPEED_33 = 1, // bus frequency 33 MHz
PSX_BUS_SPEED_40 = 2, // bus frequency 40 MHz
@@ -66,6 +68,22 @@ public:
return std::unique_ptr<PsxCtrl>(new PsxCtrl(1, "PSX-PCI1"));
}
// the lower bits of Sys_Id register are set after a hard reset
// by reading the voltage on the RA[9:8] pins.
// Desktop computers use pulldown resistors to set them to %00
// while portables have %01 hardcoded there.
void set_lower_sysid(uint32_t id) {
insert_bits(this->sys_id, id, 16, 2);
}
void set_revision_id(uint8_t rev_id) { this->chip_rev = rev_id << 24; }
// Bus speed is latched after a hard reset from the RA[1:0] pins.
// The method below allows specifying bus speed during machine initialization.
void set_bus_speed(PsxBusSpeed bus_speed) {
insert_bits(this->sys_config, bus_speed, 0, 2);
}
// MMIODevice methods
uint32_t read(uint32_t rgn_start, uint32_t offset, int size);
void write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size);
+4 -1
View File
@@ -55,7 +55,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <stdexcept>
#include <string>
enum RAMType : int { SDRAM = 4 };
enum RAMType : int {
EDO = 2,
SDRAM = 4,
};
class SpdSdram168 : public I2CDevice {
+69 -86
View File
@@ -34,7 +34,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <string>
#include <vector>
/** Remap the compatible addressing scheme to MacRISC one. */
/** Remap the compatible addressing scheme to the MacRISC one. */
const uint8_t compat_to_macrisc[6] = {
EsccReg::Port_B_Cmd, EsccReg::Port_A_Cmd,
EsccReg::Port_B_Data, EsccReg::Port_A_Data,
@@ -97,8 +97,21 @@ uint8_t EsccController::read(uint8_t reg_offset)
case EsccReg::Enh_Reg_A:
value = this->ch_a->get_enh_reg();
break;
case LocalTalkReg::Rec_Count:
value = this->recovery_counter;
break;
case LocalTalkReg::Start_A:
value = this->start_a;
break;
case LocalTalkReg::Start_B:
value = this->start_b;
break;
case LocalTalkReg::Detect_AB:
value = this->detect_ab;
break;
default:
LOG_F(WARNING, "ESCC: reading from unimplemented register 0x%x", reg_offset);
LOG_F(WARNING, "%s: reading from unimplemented register 0x%x", this->name.c_str(),
reg_offset);
value = 0;
}
@@ -126,8 +139,33 @@ void EsccController::write(uint8_t reg_offset, uint8_t value)
case EsccReg::Enh_Reg_A:
this->ch_a->set_enh_reg(value);
break;
case LocalTalkReg::Rec_Count:
this->recovery_counter = value;
LOG_F(INFO, "ESCC recovery counter set to 0x%X", this->recovery_counter);
break;
case LocalTalkReg::Start_A:
this->start_a = value & 1;
if (this->start_a) {
this->detect_ab |= 2; // say we've just detected the Abort sequence
this->ch_a->update_ltpc_eop_flag(1);
} else {
this->detect_ab &= ~2; // reset Abort detected flag
this->ch_a->update_ltpc_eop_flag(0);
}
break;
case LocalTalkReg::Start_B:
this->start_b = value & 1;
if (this->start_b) {
this->detect_ab |= 1; // say we've just detected the Abort sequence
this->ch_b->update_ltpc_eop_flag(1);
} else {
this->detect_ab &= ~1; // reset Abort detected flag
this->ch_b->update_ltpc_eop_flag(0);
}
break;
default:
LOG_F(9, "ESCC: writing 0x%X to unimplemented register 0x%x", value, reg_offset);
LOG_F(WARNING, "%s: writing 0x%X to unimplemented register 0x%x", this->name.c_str(),
value, reg_offset);
}
}
@@ -282,9 +320,11 @@ void EsccChannel::write_reg(int reg_num, uint8_t value)
(this->write_regs[WR3] & (WR3_RX_ENABLE | WR3_ENTER_HUNT_MODE)) |
(value & ~(WR3_RX_ENABLE | WR3_ENTER_HUNT_MODE));
return;
case WR7:
break;
case WR7Prime:
case WR4:
if ((value & WR4_STOP_BITS) == WR4_SYNC_MODES_ENABLE &&
(value & WR4_SYNC_MODE) == WR4_SDLC_MODE &&
!(this->write_regs[WR3] & WR3_RX_ENABLE))
this->read_regs[RR0] |= RR0_SYNC_HUNT;
break;
case WR8:
this->send_byte(value);
@@ -392,95 +432,38 @@ void EsccChannel::set_enh_reg(uint8_t value)
}
}
void EsccChannel::dma_start_tx()
{
}
void EsccChannel::dma_start_rx()
{
}
void EsccChannel::dma_stop_tx()
{
if (this->timer_id_tx) {
TimerManager::get_instance()->cancel_timer(this->timer_id_tx);
this->timer_id_tx = 0;
int EsccChannel::xfer_from(DmaChannel *ch_obj, uint8_t *buf, int len) {
if (ch_obj->get_id() == DIR_TX) {
LOG_F(WARNING, "%s: attempt to receive data over the DMA TX channel",
this->name.c_str());
return 0;
}
}
void EsccChannel::dma_stop_rx()
{
if (this->timer_id_rx) {
TimerManager::get_instance()->cancel_timer(this->timer_id_rx);
this->timer_id_rx = 0;
int bytes_moved = 0;
while (this->chario->rcv_char_available_now()) {
*buf++ = this->receive_byte();
len--;
bytes_moved++;
}
return bytes_moved;
}
void EsccChannel::dma_in_tx()
{
LOG_F(ERROR, "%s: Unexpected DMA INPUT command for transmit.", this->name.c_str());
}
void EsccChannel::dma_in_rx()
{
if (dma_ch[DIR_RX]->get_push_data_remaining()) {
this->timer_id_rx = TimerManager::get_instance()->add_oneshot_timer(
0,
[this]() {
this->timer_id_rx = 0;
char c = receive_byte();
dma_ch[DIR_RX]->push_data(&c, 1);
this->dma_in_rx();
});
int EsccChannel::xfer_to(DmaChannel *ch_obj, uint8_t *buf, int len) {
if (ch_obj->get_id() == DIR_RX) {
LOG_F(WARNING, "%s: attempt to transmit data over the DMA RX channel",
this->name.c_str());
return 0;
}
}
void EsccChannel::dma_out_tx()
{
this->timer_id_tx = TimerManager::get_instance()->add_oneshot_timer(
10,
[this]() {
this->timer_id_tx = 0;
uint8_t *data;
uint32_t avail_len;
int bytes_moved = 0;
if (dma_ch[DIR_TX]->pull_data(256, &avail_len, &data) == MoreData) {
while(avail_len) {
this->send_byte(*data++);
avail_len--;
}
this->dma_out_tx();
}
});
}
for (; len > 0; len--, bytes_moved++) {
this->send_byte(*buf++);
}
void EsccChannel::dma_out_rx()
{
LOG_F(ERROR, "%s: Unexpected DMA OUTPUT command for receive.", this->name.c_str());
}
void EsccChannel::dma_flush_tx()
{
this->dma_stop_tx();
this->timer_id_tx = TimerManager::get_instance()->add_oneshot_timer(
10,
[this]() {
this->timer_id_tx = 0;
dma_ch[DIR_TX]->end_pull_data();
});
}
void EsccChannel::dma_flush_rx()
{
this->dma_stop_rx();
this->timer_id_rx = TimerManager::get_instance()->add_oneshot_timer(
10,
[this]() {
this->timer_id_rx = 0;
dma_ch[DIR_RX]->end_push_data();
});
return bytes_moved;
}
static const std::vector<std::string> CharIoBackends = {"null", "stdio", "socket"};
+32 -55
View File
@@ -26,14 +26,13 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <devices/common/hwcomponent.h>
#include <devices/common/dbdma.h>
#include <devices/common/dmacore.h>
#include <devices/serial/chario.h>
#include <cinttypes>
#include <memory>
#include <string>
class DmaBidirChannel;
/** ESCC register positions */
/* Please note that the registers below are provided
by the Apple I/O controllers for accessing ESCC
@@ -50,13 +49,13 @@ enum EsccReg : uint8_t {
Port_B_Data = 1, // direct access to WR8/RR8
Port_A_Cmd = 2,
Port_A_Data = 3, // direct access to WR8/RR8
Enh_Reg_B = 4, // undocumented Apple extension
Enh_Reg_A = 5, // undocumented Apple extension
Enh_Reg_B = 4, // extended Curio/Geoport features
Enh_Reg_A = 5, // extended Curio/Geoport features
};
extern const uint8_t compat_to_macrisc[6];
/** LocalTalk LTPC registers provided by a MacIO controller. */
/** LocalTalk LTPC registers implemented in a MacIO controller. */
enum LocalTalkReg : uint8_t {
Rec_Count = 8,
Start_A = 9,
@@ -82,7 +81,7 @@ enum ChIndex : uint8_t {
};
/** ESCC Channel class. */
class EsccChannel {
class EsccChannel : public DmaDevice {
public:
EsccChannel(std::string name) { this->name = name; }
~EsccChannel() = default;
@@ -96,54 +95,26 @@ public:
uint8_t get_enh_reg();
void set_enh_reg(uint8_t value);
void set_dma_channel(DirIndex dir_index, DmaBidirChannel *dma_ch) {
this->dma_ch[dir_index] = dma_ch;
auto dbdma_ch = dynamic_cast<DMAChannel*>(dma_ch);
if (dbdma_ch) {
switch (dir_index) {
case DIR_TX:
dbdma_ch->set_callbacks(
std::bind(&EsccChannel::dma_start_tx, this),
std::bind(&EsccChannel::dma_stop_tx, this)
);
dbdma_ch->set_data_callbacks(
std::bind(&EsccChannel::dma_in_tx, this),
std::bind(&EsccChannel::dma_out_tx, this),
std::bind(&EsccChannel::dma_flush_tx, this)
);
break;
case DIR_RX:
dbdma_ch->set_callbacks(
std::bind(&EsccChannel::dma_start_rx, this),
std::bind(&EsccChannel::dma_stop_rx, this)
);
dbdma_ch->set_data_callbacks(
std::bind(&EsccChannel::dma_in_rx, this),
std::bind(&EsccChannel::dma_out_rx, this),
std::bind(&EsccChannel::dma_flush_rx, this)
);
break;
}
}
void set_dma_channel(DirIndex dir_index, DmaChannel *ch_obj) {
this->dma_channels[dir_index] = ch_obj;
ch_obj->set_id(dir_index);
ch_obj->set_type(dir_index == DIR_TX ? DMA_CH_TYPE_OUT : DMA_CH_TYPE_IN);
ch_obj->connect(this);
}
// End of packet (EOP) flag is reflected by s5 bit of the DMA TX channel status
void update_ltpc_eop_flag(uint8_t flag) {
auto dbdma_ch = static_cast<DMAChannel*>(this->dma_channels[DIR_TX]);
dbdma_ch->update_ch_stat(1 << 5, (flag & 1) << 5);
}
// DmaChannel methods
int xfer_from(DmaChannel *ch_obj, uint8_t *buf, int len) override;
int xfer_to (DmaChannel *ch_obj, uint8_t *buf, int len) override;
private:
uint32_t timer_id_tx = 0;
uint32_t timer_id_rx = 0;
void dma_start_tx();
void dma_stop_tx();
void dma_in_tx();
void dma_out_tx();
void dma_flush_tx();
void dma_start_rx();
void dma_stop_rx();
void dma_in_rx();
void dma_out_rx();
void dma_flush_rx();
DmaBidirChannel* dma_ch[DIR_MAX+1];
DmaChannel* dma_channels[2];
std::string name;
uint8_t read_regs[16] = {};
@@ -172,10 +143,10 @@ public:
uint8_t read(uint8_t reg_offset);
void write(uint8_t reg_offset, uint8_t value);
void set_dma_channel(ChIndex ch_index, DirIndex dir_index, DmaBidirChannel *dma_ch) {
switch (ch_index) {
case CH_A: ch_a->set_dma_channel(dir_index, dma_ch); break;
case CH_B: ch_b->set_dma_channel(dir_index, dma_ch); break;
void connect_dma_channel(ChIndex ch_idx, DirIndex dir_idx, DmaChannel *ch_obj) {
switch (ch_idx) {
case CH_A: ch_a->set_dma_channel(dir_idx, ch_obj); break;
case CH_B: ch_b->set_dma_channel(dir_idx, ch_obj); break;
}
}
@@ -191,6 +162,12 @@ private:
uint8_t master_int_cntrl = 0;
uint8_t int_vec = 0;
uint8_t recovery_counter = 8;
// LTPC state
uint8_t start_a = 0;
uint8_t start_b = 0;
uint8_t detect_ab = 0;
};
#endif // ESCC_H
+22 -11
View File
@@ -89,7 +89,8 @@ enum
RR1_CRC_FRAMING_ERROR = 1 << 6,
RR1_END_OF_FRAME_SDLC = 1 << 7,
// RR2 - Modified (Channel B only) interrupt vector and Unmodified interrupt vector (Channel A only)
// RR2 - Modified (Channel B only) interrupt vector and
// Unmodified interrupt vector (Channel A only)
RR2_V0 = 1 << 0,
RR2_V1 = 1 << 1,
@@ -151,7 +152,8 @@ enum
RR15_TX_UNDERRUN_EOM_IE = 1 << 6,
RR15_BREAK_ABORT_IE = 1 << 7,
// WR0 - Command Register // Command Register, (Register Pointers), CRC initialization, resets for various modes
// WR0 - Command Register // Command Register, (Register Pointers),
// CRC initialization, resets for various modes
WR0_CRC_RESET_CODES = 3 << 6,
WR0_RESET_NULL_CODE = 0 << 6,
@@ -177,7 +179,8 @@ enum
WR0_REGISTER_6 = 6 << 0,
WR0_REGISTER_7 = 7 << 0,
// WR1 - Transmit/Receive Interrupt and Data Transfer Mode Definition // Interrupt conditions, Wait/DMA request control
// WR1 - Transmit/Receive Interrupt and Data Transfer Mode Definition
// Interrupt conditions, Wait/DMA request control
WR1_WAIT_DMA_REQUEST_ENABLE = 1 << 7,
WR1_WAIT_DMA_REQUEST_FUNCTION = 1 << 6,
@@ -191,7 +194,8 @@ enum
WR1_TX_INT_ENABLE = 1 << 1,
WR1_EXT_INT_ENABLE = 1 << 0,
// WR2 - Interrupt Vector // Interrupt vector (access through either channel)
// WR2 - Interrupt Vector
// Interrupt vector (access through either channel)
WR2_V0 = 1 << 0,
WR2_V1 = 1 << 1,
@@ -202,7 +206,8 @@ enum
WR2_V6 = 1 << 6,
WR2_V7 = 1 << 7,
// WR3 - Receive Parameters and Control // Receive/Control parameters, number of bits per character, Rx CRC enable
// WR3 - Receive Parameters and Control
// Receive/Control parameters, number of bits per character, Rx CRC enable
WR3_RECEIVER_BITS_PER_CHARACTER = 3 << 6,
WR3_BITS_PER_CHARACTER_5 = 0 << 6,
@@ -217,7 +222,8 @@ enum
WR3_RX_ENABLE = 1 << 0,
// WR4 - Transmit/Receiver Miscellaneous Parameters and Modes
// Transmit/Receive miscellaneous parameters and codes, clock rate, number of sync characters, stop bits, parity
// Transmit/Receive miscellaneous parameters and codes, clock rate,
// number of sync characters, stop bits, parity
WR4_CLOCK_RATE = 3 << 6,
WR4_X1_CLOCK_MODE = 0 << 6,
@@ -239,7 +245,8 @@ enum
WR4_PARITY_EVEN = 1 << 1,
WR4_PARITY_ENABLE = 1 << 0,
// WR5 - Transmit Parameter and Controls // Transmit parameters and control, number of Tx bits per character, Tx CRC enable
// WR5 - Transmit Parameter and Controls
// Transmit parameters and control, number of Tx bits per character, Tx CRC enable
WR5_DTR = 1 << 7,
WR5_TX_BITS_PER_CHARACTER = 3 << 5,
@@ -271,7 +278,8 @@ enum
// WR8 - Transmit buffer
// WR9 - Master Interrupt Control
// Master interrupt control and reset (accessed through either channel), reset bits, control interrupt daisy chain
// Master interrupt control and reset (accessed through either channel),
// reset bits, control interrupt daisy chain
WR9_RESET_COMMAND_BITS = 3 << 6,
WR9_NO_RESET = 0 << 6,
@@ -287,7 +295,8 @@ enum
WR9_VECTOR_INCLUDES_STATUS = 1 << 0,
// WR10 - Miscellaneous Transmitter/Receiver Control Bits
// Miscellaneous transmitter/receiver control bits, NRZI, NRZ, FM encoding, CRC reset
// Miscellaneous transmitter/receiver control bits, NRZI, NRZ,
// FM encoding, CRC reset
WR10_CRC_PRESET = 1 << 7,
WR10_DATA_ENCODING = 3 << 5,
@@ -334,7 +343,8 @@ enum
// WR13 - Upper Byte of Baud Rate Generator Time Constant
// WR14 - Miscellaneous Control Bits
// Miscellaneous control bits: baud rate generator, Phase-Locked Loop control, auto echo, local loopback
// Miscellaneous control bits: baud rate generator, Phase-Locked Loop control,
// auto echo, local loopback
WR14_DPLL_COMMAND_BITS = 7 << 5,
WR14_DPLL_NULL_COMMAND = 0 << 5,
@@ -354,7 +364,8 @@ enum
WR14_BR_GENERATOR_ENABLE = 1 << 0,
// WR15 - External/Status Interrupt Control
// External/Status interrupt control information-control external conditions causing interrupts
// External/Status interrupt control information-control external
// conditions causing interrupts
WR15_BREAK_ABORT_IE = 1 << 7,
WR15_TX_UNDERRUN_EOM_IE = 1 << 6,
+22 -16
View File
@@ -26,12 +26,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
- Screamer AWACs in Beige G3
*/
#include <core/endianswap.h>
#include <core/timermanager.h>
#include <devices/deviceregistry.h>
#include <devices/sound/awacs.h>
#include <devices/sound/soundserver.h>
#include <devices/common/dbdma.h>
#include <endianswap.h>
#include <machines/machinebase.h>
#include <loguru.hpp>
@@ -185,21 +185,21 @@ int AwacsScreamer::device_postinit() {
}
uint32_t AwacsScreamer::snd_ctrl_read(uint32_t offset, int size) {
uint32_t value;
uint32_t value = 0;
switch (offset) {
case AWAC_SOUND_CTRL_REG:
value = this->snd_ctrl_reg;
break;
case AWAC_CODEC_CTRL_REG:
value = this->is_busy;
value = this->codec_ctrl_reg;
break;
case AWAC_CODEC_STATUS_REG:
value = (AWAC_AVAILABLE << 8) | (AWAC_MAKER_CRYSTAL << 16) |
(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:
@@ -210,30 +210,36 @@ uint32_t AwacsScreamer::snd_ctrl_read(uint32_t offset, int size) {
break;
default:
LOG_F(ERROR, "%s: unsupported register at offset 0x%X", this->name.c_str(), offset);
value = 0;
}
return value;
}
void AwacsScreamer::snd_ctrl_write(uint32_t offset, uint32_t value, int size) {
int subframe, reg_num;
uint16_t data;
switch (offset) {
case AWAC_SOUND_CTRL_REG:
this->snd_ctrl_reg = BYTESWAP_32(value);
this->set_sample_rate((this->snd_ctrl_reg >> 8) & 7);
break;
case AWAC_CODEC_CTRL_REG:
subframe = (value >> 14) & 3;
reg_num = (value >> 20) & 7;
data = ((value >> 8) & 0xF00) | ((value >> 24) & 0xFF);
LOG_F(9, "%s subframe = %d, reg = %d, data = %08X", this->name.c_str(),
subframe, reg_num, data);
if (!subframe)
this->shadow_regs[reg_num] = data;
case AWAC_CODEC_CTRL_REG: {
if (this->is_busy)
return;
int subframe = (value >> 14) & 3;
int reg_num = (value >> 20) & 7;
this->codec_ctrl_reg = value | (subframe << 22);
this->is_busy = this->codec_ctrl_reg & 0x1000000;
uint16_t data = ((value >> 8) & 0xF00) | ((value >> 24) & 0xFF);
LOG_F(
9, "%s subframe = %d, reg = %d, data = %04X", this->name.c_str(),
subframe, reg_num, data);
this->shadow_regs[reg_num] = data;
this->is_busy = 0;
break;
}
case AWAC_CLIP_COUNT:
this->clip_count = BYTESWAP_32(value);
break;
+26 -7
View File
@@ -21,11 +21,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** Burgundy sound codec emulation. */
#include <core/endianswap.h>
#include <core/timermanager.h>
#include <devices/common/hwcomponent.h>
#include <devices/deviceregistry.h>
#include <devices/sound/burgundy.h>
#include <endianswap.h>
#include <loguru.hpp>
BurgundyCodec::BurgundyCodec(std::string name) : MacioSndCodec(name)
@@ -42,23 +42,34 @@ BurgundyCodec::BurgundyCodec(std::string name) : MacioSndCodec(name)
}
uint32_t BurgundyCodec::snd_ctrl_read(uint32_t offset, int size) {
uint32_t result = 0;
uint32_t value = 0;
switch (offset) {
case AWAC_SOUND_CTRL_REG:
value = this->snd_ctrl_reg;
break;
case AWAC_CODEC_CTRL_REG:
result = this->last_ctrl_data;
value = this->last_ctrl_data;
break;
case AWAC_CODEC_STATUS_REG:
result = (this->first_valid << 23) | BURGUNDY_READY |
(this->byte_counter << 14) | (this->read_pos << 12) |
(this->data_byte << 4);
value = (this->first_valid << 23) | BURGUNDY_READY |
(this->byte_counter << 14) | (this->read_pos << 12) |
(this->data_byte << 4);
break;
case AWAC_FRAME_COUNT:
value = (uint32_t)(
(
(TimerManager::get_instance()->current_time_ns() - frame_count_start_time) * this->sr_table[0]
+ 500000000
) / 1000000000 + this->frame_count
);
break;
default:
LOG_F(ERROR, "%s: read from unsupported register 0x%X", this->name.c_str(),
offset);
}
return BYTESWAP_32(result);
return BYTESWAP_32(value);
}
void BurgundyCodec::snd_ctrl_write(uint32_t offset, uint32_t value, int size) {
@@ -69,6 +80,10 @@ void BurgundyCodec::snd_ctrl_write(uint32_t offset, uint32_t value, int size) {
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);
break;
case AWAC_CODEC_CTRL_REG:
this->last_ctrl_data = value;
reg_addr = (value >> 12) & 0xFF;
@@ -92,6 +107,10 @@ void BurgundyCodec::snd_ctrl_write(uint32_t offset, uint32_t value, int size) {
});
}
break;
case AWAC_FRAME_COUNT:
this->frame_count = BYTESWAP_32(value);
this->frame_count_start_time = TimerManager::get_instance()->current_time_ns();
break;
default:
LOG_F(ERROR, "%s: write to unsupported register 0x%X", this->name.c_str(),
offset);
+3
View File
@@ -51,12 +51,15 @@ public:
}
private:
uint32_t snd_ctrl_reg = 0x1011;
uint32_t last_ctrl_data = 0;
uint8_t byte_counter = 0;
uint8_t reg_addr = 0;
uint8_t first_valid = 0;
uint8_t read_pos = 0;
uint8_t data_byte = 0;
uint32_t frame_count = 0;
uint64_t frame_count_start_time = 0;
uint32_t reg_array[BURGUNDY_NUM_REGS] = {};
};
+15 -10
View File
@@ -23,11 +23,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#define NOMINMAX
#endif // NOMINMAX
#include <core/endianswap.h>
#include <core/timermanager.h>
#include <cpu/ppc/ppcemu.h>
#include <devices/common/dmacore.h>
#include <devices/sound/soundserver.h>
#include <endianswap.h>
#include <algorithm>
#include <functional>
@@ -52,7 +52,7 @@ public:
cubeb_stream *out_stream;
uint32_t deterministic_poll_timer = 0;
std::function<void()> deterministic_poll_cb;
timer_cb deterministic_poll_cb;
};
SoundServer::SoundServer(): impl(std::make_unique<Impl>())
@@ -100,11 +100,14 @@ void SoundServer::shutdown()
case SND_SERVER_UP:
/* fall through */
case SND_API_READY:
if (!impl->cubeb_ctx)
break;
cubeb_destroy(impl->cubeb_ctx);
impl->cubeb_ctx = nullptr;
break;
case SND_SERVER_DOWN:
// Nothing to do.
break;
return;
}
impl->status = SND_SERVER_DOWN;
@@ -131,13 +134,13 @@ static long sound_out_callback(cubeb_stream* stream, void* user_data,
out_frames = 0;
while (req_frames > 0) {
if (!dma_ch->pull_data((uint32_t)req_frames << 2, &got_len, &p_in)) {
if (DmaPullResult::MoreData == dma_ch->pull_data((uint32_t)req_frames << 2, &got_len, &p_in)) {
if ((in_buf = (int16_t*)p_in)) {
frames = got_len >> 2;
for (int i = (int)frames; i > 0; i--) {
out_buf[0] = BYTESWAP_16(in_buf[0]);
out_buf[1] = BYTESWAP_16(in_buf[1]);
out_buf[0] = READ_WORD_BE_A(&in_buf[0]);
out_buf[1] = READ_WORD_BE_A(&in_buf[1]);
in_buf += 2;
out_buf += 2;
}
@@ -170,12 +173,11 @@ int SoundServer::open_out_stream(uint32_t sample_rate, DmaOutChannel *dma_ch)
return;
}
// Drain the DMA buffer, but don't do anything else.
int req_size = std::max(dma_ch->get_pull_data_remaining(), 1024);
while (req_size > 0) {
while(1) {
uint8_t *chunk;
uint32_t chunk_size;
if (!dma_ch->pull_data(req_size, &chunk_size, &chunk)) {
req_size -= chunk_size;
if (DmaPullResult::MoreData == dma_ch->pull_data(1024, &chunk_size, &chunk)) {
;
} else {
break;
}
@@ -231,6 +233,8 @@ int SoundServer::start_out_stream()
void SoundServer::close_out_stream()
{
if (!impl->out_stream)
return;
if (is_deterministic) {
LOG_F(9, "Stopping sound output deterministic polling.");
TimerManager::get_instance()->cancel_timer(impl->deterministic_poll_timer);
@@ -239,6 +243,7 @@ void SoundServer::close_out_stream()
}
cubeb_stream_stop(impl->out_stream);
cubeb_stream_destroy(impl->out_stream);
impl->out_stream = nullptr;
impl->status = SND_STREAM_CLOSED;
LOG_F(9, "Sound output stream closed.");
}
+20
View File
@@ -47,6 +47,26 @@ public:
int write_more();
void write_cache();
uint32_t get_remaining_size() {
return this->remain_size;
}
uint8_t* get_cache_ptr() {
return (uint8_t *)this->data_cache.get();
}
bool medium_writable() {
return this->is_writeable;
}
uint64_t get_size_in_blocks() {
return this->size_blocks;
}
uint32_t get_block_size() {
return this->block_size;
}
protected:
void fill_cache(const int nblocks);
-290
View File
@@ -21,10 +21,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file Virtual CD-ROM device implementation. */
#include <devices/common/scsi/scsi.h> // reuse SCSI definitions
#include <devices/storage/cdromdrive.h>
#include <loguru.hpp>
#include <memaccess.h>
#include <cinttypes>
#include <cstring>
@@ -72,152 +70,6 @@ bool CdromDrive::detect_raw_image() {
return false;
}
static char cdrom_vendor_dingus_id[] = "DINGUS ";
static char cdrom_product_id[] = "DINGUS CD-ROM ";
static char cdrom_revision_id[] = "1.0 ";
uint32_t CdromDrive::inquiry(uint8_t *cmd_ptr, uint8_t *data_ptr) {
int page_num = cmd_ptr[2];
int alloc_len = cmd_ptr[4];
if (page_num) {
ABORT_F("%s: invalid page number in INQUIRY", "CdromDrive");
}
if (alloc_len > 36) {
LOG_F(WARNING, "%s: more than 36 bytes requested in INQUIRY", "CdromDrive");
}
data_ptr[0] = 5; // device type: CD-ROM
data_ptr[1] = 0x80; // removable media
data_ptr[2] = 2; // ANSI version: SCSI-2
data_ptr[3] = 0x21; // ATAPI Version + response data format
data_ptr[4] = 0x1F; // additional length
data_ptr[5] = 0;
data_ptr[6] = 0;
data_ptr[7] = 0;
std::memcpy(&data_ptr[8], cdrom_vendor_dingus_id, 8);
std::memcpy(&data_ptr[16], cdrom_product_id, 16);
std::memcpy(&data_ptr[32], cdrom_revision_id, 4);
//std::memcpy(&data_ptr[36], serial_number, 8);
//etc.
if (alloc_len < 36) {
LOG_F(ERROR, "%s: allocation length too small: %d", "CdromDrive",
alloc_len);
}
else {
memset(&data_ptr[36], 0, alloc_len - 36);
}
return alloc_len;
}
uint32_t CdromDrive::mode_sense_ex(bool is_sense_6, uint8_t* cmd_ptr, uint8_t* data_ptr) {
uint8_t *resp_ptr;
uint8_t page_code = cmd_ptr[2] & 0x3F;
uint8_t alloc_len = is_sense_6 ? READ_WORD_BE_U(&cmd_ptr[4]) : READ_WORD_BE_U(&cmd_ptr[7]);
std::memset(data_ptr, 0, alloc_len);
data_ptr[0] = 0; // initial data size MSB
data_ptr[1] = 6; // initial data size LSB
data_ptr[2] = 1; // medium type: 120mm CD-ROM
data_ptr[3] = 0; // device-specific parameter
data_ptr[4] = 0;
data_ptr[5] = 0;
data_ptr[6] = 0; // block description length MSB
data_ptr[7] = 0; // block description length LSB
resp_ptr = data_ptr + 8;
resp_ptr[0] = page_code;
switch (page_code) {
case ModePage::ERROR_RECOVERY:
resp_ptr[1] = 6; // data size
std::memset(&resp_ptr[2], 0, 6);
data_ptr[1] += 8; // adjust overall length
break;
case ModePage::CDROM_AUDIO:
resp_ptr[1] = 16; // page length
std::memset(&resp_ptr[2], 0, 16);
resp_ptr[2] = (1 << 2); //immediately return status
WRITE_WORD_BE_A(&resp_ptr[6], 75); // logical block per second of audio playback
resp_ptr[8] = 0x01; // Left Channel
resp_ptr[9] = 0xFF; // Volume (0-255)
resp_ptr[10] = 0x02; // Right Channel
resp_ptr[11] = 0xFF; // Volume (0-255)
resp_ptr[12] = 0x04; // Output Port 2
resp_ptr[13] = 0x00; // Volume (0-255)
resp_ptr[14] = 0x08; // Output Port 3
resp_ptr[15] = 0x00; // Volume (0-255)
data_ptr[1] += 8; // adjust overall length
break;
case ModePage::POWER_CONDITION:
resp_ptr[1] = 10; // page length
std::memset(&resp_ptr[2], 0, 10);
resp_ptr[3] = 0; //idle and standby off
WRITE_DWORD_BE_A(&resp_ptr[4], 0); // Idle Timer (100ms units)
WRITE_DWORD_BE_A(&resp_ptr[8], 0); // Standby Timer (100ms units)
data_ptr[1] += 12; // adjust overall length
break;
case ModePage::CDROM_CAPABILITIES:
resp_ptr[1] = 18; // page data length
std::memset(&resp_ptr[2], 0, 18);
resp_ptr[2] = 0x03; // supports reading CD-R and CD-E
resp_ptr[3] = 0x00; // doesn't support writing to CD-R and CD-E
resp_ptr[6] = (1 << 5) | (1 << 3) | (1 << 0); // tray type + eject + lock support
WRITE_WORD_BE_A(&resp_ptr[ 8], 706); // report 4x speed
WRITE_WORD_BE_A(&resp_ptr[10], 2); // supports audio on/off only
WRITE_WORD_BE_A(&resp_ptr[12], 512); // 512Kb cache
WRITE_WORD_BE_A(&resp_ptr[14], 706); // report current speed (4x)
data_ptr[1] += 20; // adjust overall length
break;
case ModePage::VENDOR_PAGE_31:
resp_ptr[1] = 14; // page data length
std::memset(&resp_ptr[2], 0, 14);
resp_ptr[8] = 0x31;
resp_ptr[9] = 6;
resp_ptr[10] = '.';
resp_ptr[11] = 'A';
resp_ptr[12] = 'p';
resp_ptr[13] = 'p';
data_ptr[1] += 2; // adjust overall length
break;
default:
LOG_F(ERROR, "ATAPI CD-ROM: Invalid Page Code 0x%x", page_code);
this->set_error(ScsiSense::ILLEGAL_REQ, ScsiError::INVALID_CDB);
return 0;
}
return data_ptr[1] + 2; // return total response length
}
uint32_t CdromDrive::request_sense(uint8_t *data_ptr, uint8_t sense_key,
uint8_t asc, uint8_t ascq) {
std::memset(data_ptr, 0, 18);
data_ptr[ 0] = 0x80 | 0x70; // valid + current error
data_ptr[ 2] = sense_key;
data_ptr[ 7] = 10; // additional sense length
data_ptr[12] = asc;
data_ptr[13] = ascq;
return 18;
}
uint32_t CdromDrive::report_capacity(uint8_t *data_ptr) {
WRITE_DWORD_BE_A(data_ptr, static_cast<uint32_t>(this->size_blocks));
WRITE_DWORD_BE_A(&data_ptr[4], this->block_size);
return 8;
}
uint8_t CdromDrive::hex_to_bcd(const uint8_t val) {
uint8_t hi = val / 10;
uint8_t lo = val % 10;
@@ -230,145 +82,3 @@ AddrMsf CdromDrive::lba_to_msf(const int lba) {
hex_to_bcd( lba % 75) /*.frm*/
};
}
uint32_t CdromDrive::read_toc(uint8_t *cmd_ptr, uint8_t *data_ptr) {
int tot_tracks, data_len;
uint8_t start_track, session_num;
uint8_t* out_ptr;
uint16_t alloc_len = READ_WORD_BE_U(&cmd_ptr[7]);
bool is_msf = !!(cmd_ptr[1] & 2);
// ATAPI specific handling of the format field
uint8_t format = cmd_ptr[2] & 7;
if (!format) {
format = cmd_ptr[9] >> 6;
}
if (!alloc_len)
return 0;
switch(format) {
case 0: // Formatted TOC
start_track = cmd_ptr[6];
if (!start_track) { // special case: track zero (lead-in) as starting track
// return all tracks starting with track 1 plus lead-out
start_track = 1;
tot_tracks = this->num_tracks + 1;
} else if (start_track == LEAD_OUT_TRK_NUM) {
start_track = this->num_tracks + 1;
tot_tracks = 1;
} else if (start_track <= this->num_tracks) {
tot_tracks = (this->num_tracks - start_track) + 2;
} else {
LOG_F(ERROR, "CDROM: invalid starting track %d in READ_TOC", start_track);
this->set_error(ScsiSense::ILLEGAL_REQ, ScsiError::INVALID_CDB);
return 0;
}
out_ptr = data_ptr;
data_len = (tot_tracks * 8) + 4;
// write TOC data header
WRITE_WORD_BE_A(out_ptr, data_len - 2);
out_ptr[2] = 1; // 1st track number
out_ptr[3] = this->num_tracks; // last track number
out_ptr += 4;
for (int tx = 0; tx < tot_tracks; tx++) {
if ((out_ptr - data_ptr + 8) > alloc_len)
break; // exit the loop if the output buffer length is exhausted
TrackDescriptor& td = this->tracks[start_track + tx - 1];
*out_ptr++ = 0; // reserved
*out_ptr++ = td.adr_ctrl;
*out_ptr++ = td.trk_num;
*out_ptr++ = 0; // reserved
if (is_msf) {
AddrMsf msf = lba_to_msf(td.start_lba + 150);
*out_ptr++ = 0; // reserved
*out_ptr++ = msf.min;
*out_ptr++ = msf.sec;
*out_ptr++ = msf.frm;
} else {
WRITE_DWORD_BE_A(out_ptr, td.start_lba);
out_ptr += 4;
}
}
return alloc_len;
case 1: // Multi-session info
std::memset(data_ptr, 0, 12);
data_ptr[1] = 10; // TOC data length
data_ptr[2] = 1; // first session number
data_ptr[3] = 1; // last session number
data_ptr[5] = this->tracks[0].adr_ctrl;
data_ptr[6] = 1;
if (is_msf) {
AddrMsf msf = lba_to_msf(this->tracks[0].start_lba + 150);
data_ptr[ 8] = 0; // reserved
data_ptr[ 9] = msf.min;
data_ptr[10] = msf.sec;
data_ptr[11] = msf.frm;
}
return 12;
case 2: // Raw TOC
session_num = cmd_ptr[6];
if (!session_num)
session_num = 1;
if (session_num > 1) {
LOG_F(ERROR, "CDROM: invalid session number %d", session_num);
this->set_error(ScsiSense::ILLEGAL_REQ, ScsiError::INVALID_CDB);
return 0;
}
std::memset(data_ptr, 0, 48);
out_ptr = data_ptr;
// prepare data header
out_ptr[1] = 46; // TOC data length
out_ptr[2] = 1; // first session number
out_ptr[3] = 1; // last session number
out_ptr += 4;
// descriptor #1 -> first track
out_ptr[0] = session_num;
out_ptr[1] = this->tracks[0].adr_ctrl;
out_ptr[3] = 0xA0; // point -> first track
out_ptr[8] = 1; // first track number
out_ptr += 11;
// descriptor #2 -> last track
out_ptr[0] = session_num;
out_ptr[1] = this->tracks[0].adr_ctrl;
out_ptr[3] = 0xA1; // point -> last track
out_ptr[8] = 1; // last track number
out_ptr += 11;
// descriptor #3 -> lead-out
out_ptr[0] = session_num;
out_ptr[1] = this->tracks[0].adr_ctrl;
out_ptr[3] = 0xA2; // point -> lead-out
if (is_msf) {
AddrMsf msf = lba_to_msf(this->tracks[1].start_lba + 150);
out_ptr[ 7] = 0; // reserved
out_ptr[ 8] = msf.min;
out_ptr[ 9] = msf.sec;
out_ptr[10] = msf.frm;
} else {
WRITE_DWORD_BE_U(&out_ptr[7], this->tracks[1].start_lba);
}
out_ptr += 11;
// descriptor #4 -> data track
out_ptr[0] = session_num;
out_ptr[1] = this->tracks[0].adr_ctrl;
out_ptr[3] = 1; // point -> data track
if (is_msf) {
AddrMsf msf = lba_to_msf(this->tracks[0].start_lba + 150);
out_ptr[ 7] = 0; // reserved
out_ptr[ 8] = msf.min;
out_ptr[ 9] = msf.sec;
out_ptr[10] = msf.frm;
}
return 48;
default:
LOG_F(ERROR, "CDROM: unsupported format in READ_TOC");
this->set_error(ScsiSense::ILLEGAL_REQ, ScsiError::INVALID_CDB);
return 0;
}
}
+43 -12
View File
@@ -29,6 +29,32 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cinttypes>
#include <functional>
/** CD/DVD drive read/write capabilities. */
enum CdDriveCapabilities : uint8_t {
CDCAP_CDR_READ = 0x01,
CDCAP_CDE_READ = 0x02,
CDCAP_CDR_WRITE = 0x01,
CDCAP_CDE_WRITE = 0x02,
};
/** Support for various disk formats and outputs. */
enum CdDriveFormatSupport : uint8_t {
CDFMT_AUDIO_PLAY = 1 << 0,
CDFMT_COMPOSITE = 1 << 1,
CDFMT_PORT_1 = 1 << 2,
CDFMT_PORT_2 = 1 << 3,
CDFMT_MODE2_FORM1 = 1 << 4,
CDFMT_MODE2_FORM2 = 1 << 5,
CDFMT_MULTI_SESSION = 1 << 6,
};
/** Loading mechanism types. */
enum MechanismType : uint8_t {
LDTYPE_CADDY = 0,
LDTYPE_TRAY = 1,
LDTYPE_POPUP = 2,
};
/* Original CD-ROM addressing mode expressed
in minutes, seconds and frames */
typedef struct {
@@ -53,29 +79,34 @@ public:
CdromDrive();
virtual ~CdromDrive() = default;
void set_error_callback(std::function<void(uint8_t, uint8_t)>&& err_cb) {
this->set_error = std::move(err_cb);
}
bool medium_present() { return this->is_ready; }
void insert_image(std::string filename);
virtual uint32_t inquiry(uint8_t *cmd_ptr, uint8_t *data_ptr);
virtual uint32_t mode_sense_ex(bool is_sense_6, uint8_t *cmd_ptr, uint8_t *data_ptr);
virtual uint32_t request_sense(uint8_t *data_ptr, uint8_t sense_key, uint8_t asc,
uint8_t ascq);
virtual uint32_t report_capacity(uint8_t *data_ptr);
virtual uint32_t read_toc(uint8_t *cmd_ptr, uint8_t *data_ptr);
protected:
std::function<void(uint8_t, uint8_t)> set_error;
uint8_t hex_to_bcd(const uint8_t val);
AddrMsf lba_to_msf(const int lba);
bool detect_raw_image();
TrackDescriptor tracks[CDROM_MAX_TRACKS];
int num_tracks;
// drive capabilities
uint8_t read_cap = CdDriveCapabilities::CDCAP_CDE_READ |
CdDriveCapabilities::CDCAP_CDR_READ;
uint8_t write_cap = 0; // no write support
uint8_t fmt_support = 0;
uint8_t ext_support = 0;
uint8_t mech_type = MechanismType::LDTYPE_TRAY;
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
uint8_t prevent_jump = 0; // prevent jumper not present
uint8_t more_support = 0;
uint16_t max_rd_speed = 706; // defaults to 4x
uint16_t max_vol_levs = 2; // audio can be only turned on and off
uint16_t cur_rd_speed = 706; // defaults to 4x
uint8_t dgt_out_desc = 0; // digital output format description
};
#endif // CD_ROM_DRIVE_H
+5 -4
View File
@@ -22,9 +22,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** Apple RAMDAC ASICs (RaDACal & DACula) emulation. */
#include <core/bitops.h>
#include <core/memaccess.h>
#include <devices/video/display.h>
#include <devices/video/appleramdac.h>
#include <loguru.hpp>
#include <memaccess.h>
AppleRamdac::AppleRamdac(DacFlavour flavour) {
this->flavour = flavour;
@@ -254,10 +255,10 @@ void AppleRamdac::draw_hw_cursor(uint8_t *src_buf, uint8_t *dst_buf, int dst_pit
while (pix_data) {
uint8_t pix = pix_data >> 60; // each pixel is 4 bits wide
if (pix & 8) { // check control bit: 0 - transparent, 1 - opaque
WRITE_DWORD_LE_A(dst_1, color[pix & 7]);
FB_WRITE(dst_1, color[pix & 7]);
} else if (pix & 1) {
uint32_t c = (((READ_DWORD_LE_A(dst_1) >> 7) & 0x010101) * 0xFFU) ^ 0xFFFFFFU;
WRITE_DWORD_LE_A(dst_1, c);
uint32_t c = (((FB_READ(dst_1) >> 7) & 0x010101) * 0xFFU) ^ 0xFFFFFFU;
FB_WRITE(dst_1, c);
}
pix_data <<= 4;
dst_1 += sizeof(uint32_t);
+52 -10
View File
@@ -31,6 +31,29 @@ enum {
// = 0x5654, // VT
};
/* Pixel format values used by the CRTC and draw engine pixel-width fields. */
enum {
ATI_PIX_FMT_4BPP = 1,
ATI_PIX_FMT_8BPP = 2,
ATI_PIX_FMT_RGB555 = 3,
ATI_PIX_FMT_RGB565 = 4,
ATI_PIX_FMT_RGB888 = 5,
ATI_PIX_FMT_ARGB8888 = 6,
};
/* Draw engine data-path values. */
enum {
ATI_DP_COLOR_SRC_BKGD_CLR = 0,
ATI_DP_COLOR_SRC_FRGD_CLR = 1,
ATI_DP_COLOR_SRC_HOST = 2,
ATI_DP_COLOR_SRC_BLIT = 3,
ATI_DP_MONO_SRC_ALWAYS_1 = 0,
ATI_DP_MIX_SRC = 7,
ATI_SRC_TRAJ_UNBOUNDED = 0,
ATI_SRC_TRAJ_PATTERN = 1,
ATI_SRC_TRAJ_ROTATED = 3,
};
/** Mach64 register offsets. */
enum {
ATI_CRTC_H_TOTAL_DISP = 0x000, // 0x0000
@@ -471,19 +494,34 @@ enum {
ATI_Z_CNTL = 0x053, // 0x014C
ATI_ALPHA_TST_CNTL = 0x054, // 0x0150
ATI_SRC_OFF_PITCH = 0x060, // 0x0180
ATI_SRC_OFFSET = 0, ATI_SRC_OFFSET_size = 20,
ATI_SRC_PITCH = 22, ATI_SRC_PITCH_size = 10,
ATI_SRC_X = 0x061, // 0x0184
ATI_SRC_X_pos = 0, ATI_SRC_X_size = 14,
ATI_SRC_Y = 0x062, // 0x0188
ATI_SRC_Y_pos = 0, ATI_SRC_Y_size = 15,
ATI_SRC_Y_X = 0x063, // 0x018C
ATI_SRC_WIDTH1 = 0x064, // 0x0190
ATI_SRC_WIDTH1_pos = 0, ATI_SRC_WIDTH1_size = 14,
ATI_SRC_HEIGHT1 = 0x065, // 0x0194
ATI_SRC_HEIGHT1_pos = 0, ATI_SRC_HEIGHT1_size = 15,
ATI_SRC_HEIGHT1_WIDTH1 = 0x066, // 0x0198
ATI_SRC_X_START = 0x067, // 0x019C
ATI_SRC_X_START_pos = 0, ATI_SRC_X_START_size = 14,
ATI_SRC_Y_START = 0x068, // 0x01A0
ATI_SRC_Y_START_pos = 0, ATI_SRC_Y_START_size = 15,
ATI_SRC_Y_X_START = 0x069, // 0x01A4
ATI_SRC_WIDTH2 = 0x06A, // 0x01A8
ATI_SRC_WIDTH2_pos = 0, ATI_SRC_WIDTH2_size = 14,
ATI_SRC_HEIGHT2 = 0x06B, // 0x01AC
ATI_SRC_HEIGHT2_pos = 0, ATI_SRC_HEIGHT2_size = 15,
ATI_SRC_HEIGHT2_WIDTH2 = 0x06C, // 0x01B0
ATI_SRC_CNTL = 0x06D, // 0x01B4
ATI_SRC_COLOR_REG_WRITE_EN = 13,
ATI_SRC_BLOCK_WRITE_EN = 14,
ATI_SCALE_OFF = 0x070, // 0x01C0
ATI_SCALE_WIDTH = 0x077, // 0x01DC
ATI_SCALE_HEIGHT = 0x078, // 0x01E0
@@ -492,6 +530,8 @@ enum {
ATI_SCALE_Y_INC = 0x07D, // 0x01F4
ATI_SCALE_VACC = 0x07E, // 0x01F8
ATI_SCALE_3D_CNTL = 0x07F, // 0x01FC
ATI_HOST_DATA0 = 0x080, // 0x0200
ATI_HOST_DATA15 = 0x08F, // 0x023C
ATI_HOST_CNTL = 0x090, // 0x0240
ATI_BM_HOSTDATA = 0x091, // 0x0244
ATI_BM_ADDR = 0x092, // 0x0248
@@ -503,10 +543,10 @@ enum {
ATI_PAT_CNTL = 0x0A2, // 0x0288
ATI_SC_LEFT = 0x0A8, // 0x02A0
ATI_SC_LEFT_pos = 0, ATI_SC_LEFT_size = 13,
ATI_SC_LEFT_pos = 0, ATI_SC_LEFT_size = 14,
ATI_SC_RIGHT = 0x0A9, // 0x02A4
ATI_SC_RIGHT_pos = 0, ATI_SC_RIGHT_size = 13,
ATI_SC_RIGHT_pos = 0, ATI_SC_RIGHT_size = 14,
ATI_SC_LEFT_RIGHT = 0x0AA, // 0x02A8
@@ -582,14 +622,16 @@ enum {
ATI_SRC_PATT_EN = 16, // VT/GT
ATI_SRC_PATT_ROT_EN = 17, // VT/GT
ATI_SRC_LINEAR_EN = 18, // VT/GT
ATI_SRC_LINE_X_DIR = 19, // VT/GT
ATI_SRC_TRACK_DST = 20, // VT/GT
ATI_PAT_MONO_EN = 23, // GT
ATI_PAT_CLR_4x2_EN = 24, // VT/GT
ATI_PAT_CLR_8x1_EN = 25, // VT/GT
ATI_HOST_BYTE_ALIGN = 26, // VT/GT
ATI_HOST_BIG_ENDIAN_EN = 28, // VT/GT
ATI_SRC_BYTE_ALIGN = 29, // VT/GT
ATI_SRC_BYTE_ALIGN = 19, // VT/GT
ATI_SRC_LINE_X_DIR = 20, // VT/GT
ATI_SRC_8x8x8_BRUSH = 21, // GT
ATI_FAST_FILL_EN = 22, // GT
ATI_SRC_TRACK_DST = 23, // VT/GT
ATI_PAT_MONO_EN = 24, // GT
ATI_PAT_CLR_4x2_EN = 25, // VT/GT
ATI_PAT_CLR_8x1_EN = 26, // VT/GT
ATI_HOST_BYTE_ALIGN = 28, // VT/GT
ATI_HOST_BIG_ENDIAN_EN = 29, // VT/GT
ATI_GUI_STAT = 0x0CE, // 0x0338
ATI_GUI_ACTIVE = 0,
+30 -27
View File
@@ -25,12 +25,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <core/bitops.h>
#include <core/memaccess.h>
#include <devices/deviceregistry.h>
#include <devices/video/atimach64gx.h>
#include <devices/video/displayid.h>
#include <devices/video/rgb514defs.h>
#include <loguru.hpp>
#include <memaccess.h>
#include <string>
@@ -525,6 +525,7 @@ void AtiMach64Gx::write_reg(uint32_t reg_offset, uint32_t value, uint32_t size)
new_value = (old_value & bits_read_only) | (new_value & ~bits_read_only);
WRITE_VALUE_AND_LOG(ATIINTERRUPT);
this->update_interrupt();
return;
}
case ATI_CRTC_GEN_CNTL:
@@ -847,9 +848,9 @@ void AtiMach64Gx::crtc_update()
LOG_F(INFO, "%s: primary CRT controller enabled:", this->name.c_str());
LOG_F(INFO, "Video mode: %s",
bit_set(this->regs[ATI_CRTC_GEN_CNTL], ATI_CRTC_EXT_DISP_EN) ? "extended" : "VGA");
LOG_F(INFO, "Video width: %d px", this->active_width);
LOG_F(INFO, "Video height: %d px", this->active_height);
LOG_F(INFO, "Vertical blank: %d px", this->vert_blank);
LOG_F(INFO, "Video width: %d pixels", this->active_width);
LOG_F(INFO, "Video height: %d lines", this->active_height);
LOG_F(INFO, "Vertical blank: %d lines", this->vert_blank);
verbose_pixel_format(0);
LOG_F(INFO, "Pixel (dot) clock: %f MHz", this->pixel_clock * 1e-6);
LOG_F(INFO, "Refresh rate: %f Hz", this->refresh_rate);
@@ -865,8 +866,8 @@ void AtiMach64Gx::draw_hw_cursor(uint8_t *dst_row, int dst_pitch) {
ATI_CUR_VERT_OFF, ATI_CUR_VERT_OFF_size);
int cur_height = 64 - vert_offset;
uint32_t color0 = this->regs[ATI_CUR_CLR0] | 0x000000FFUL;
uint32_t color1 = this->regs[ATI_CUR_CLR1] | 0x000000FFUL;
uint32_t color0 = (this->regs[ATI_CUR_CLR0] >> 8) | 0xFF000000UL;
uint32_t color1 = (this->regs[ATI_CUR_CLR1] >> 8) | 0xFF000000UL;
uint64_t *src_row = (uint64_t *)&this->vram_ptr[this->regs[ATI_CUR_OFFSET] * 8];
dst_pitch -= 64 * 4;
@@ -877,16 +878,16 @@ void AtiMach64Gx::draw_hw_cursor(uint8_t *dst_row, int dst_pitch) {
for (int p = 32; p > 0; p--, px >>= 2, dst_row += 4) {
switch(px & 3) {
case 0: // cursor color 0
WRITE_DWORD_BE_A(dst_row, color0);
FB_WRITE(dst_row, color0);
break;
case 1: // cursor color 1
WRITE_DWORD_BE_A(dst_row, color1);
FB_WRITE(dst_row, color1);
break;
case 2: // transparent
WRITE_DWORD_BE_A(dst_row, 0);
FB_WRITE(dst_row, 0);
break;
case 3: // 1's complement of display pixel
WRITE_DWORD_BE_A(dst_row, 0x0000007F);
FB_WRITE(dst_row, 0x7F000000);
break;
}
}
@@ -904,7 +905,7 @@ void AtiMach64Gx::get_cursor_position(int& x, int& y) {
int AtiMach64Gx::device_postinit()
{
this->vbl_cb = [this](uint8_t irq_line_state) {
insert_bits<uint32_t>(this->regs[ATI_CRTC_INT_CNTL], irq_line_state, ATI_CRTC_VBLANK, irq_line_state);
insert_bits<uint32_t>(this->regs[ATI_CRTC_INT_CNTL], irq_line_state, ATI_CRTC_VBLANK, 1);
if (irq_line_state) {
set_bit(this->regs[ATI_CRTC_INT_CNTL], ATI_CRTC_VBLANK_INT);
set_bit(this->regs[ATI_CRTC_INT_CNTL], ATI_CRTC_VLINE_INT);
@@ -914,26 +915,28 @@ int AtiMach64Gx::device_postinit()
#endif
}
bool do_interrupt =
bit_set(this->regs[ATI_CRTC_INT_CNTL], ATI_CRTC_VBLANK_INT_EN) ||
bit_set(this->regs[ATI_CRTC_INT_CNTL], ATI_CRTC_VLINE_INT_EN) ||
#if 1
#else
bit_set(this->regs[ATI_CRTC_GEN_CNTL], ATI_CRTC_VSYNC_INT_EN) ||
#endif
0;
LOG_F(ATIINTERRUPT, "%s: irq_line_state:%d do_interrupt:%d CRTC_INT_CNTL:%08x",
this->name.c_str(), irq_line_state, do_interrupt,
this->regs[ATI_CRTC_INT_CNTL]);
if (do_interrupt) {
this->pci_interrupt(irq_line_state);
}
this->update_interrupt();
};
return 0;
}
void AtiMach64Gx::update_interrupt()
{
uint32_t int_cntl = this->regs[ATI_CRTC_INT_CNTL];
bool new_pci_irq_line_state =
(bit_set(int_cntl, ATI_CRTC_VBLANK_INT_EN) &&
bit_set(int_cntl, ATI_CRTC_VBLANK_INT)) ||
(bit_set(int_cntl, ATI_CRTC_VLINE_INT_EN) &&
bit_set(int_cntl, ATI_CRTC_VLINE_INT));
if (new_pci_irq_line_state != this->pci_irq_line_state) {
this->pci_irq_line_state = new_pci_irq_line_state;
LOG_F(ATIINTERRUPT, "%s: pci_irq_line_state:%d CRTC_INT_CNTL:%08x",
this->name.c_str(), this->pci_irq_line_state, int_cntl);
this->pci_interrupt(this->pci_irq_line_state);
}
}
// ========================== IBM RGB514 related code ==========================
const char* AtiMach64Gx::rgb514_get_reg_name(uint32_t reg_addr)
{
+2
View File
@@ -76,8 +76,10 @@ protected:
private:
void change_one_bar(uint32_t &aperture, uint32_t aperture_size, uint32_t aperture_new, int bar_num);
void update_interrupt();
uint32_t regs[256] = {}; // internal registers
bool pci_irq_line_state = false;
int vram_size;
+524 -72
View File
@@ -20,14 +20,14 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <core/bitops.h>
#include <core/endianswap.h>
#include <core/memaccess.h>
#include <devices/common/hwcomponent.h>
#include <devices/common/pci/pcidevice.h>
#include <devices/deviceregistry.h>
#include <devices/video/atirage.h>
#include <devices/video/displayid.h>
#include <endianswap.h>
#include <loguru.hpp>
#include <memaccess.h>
#include <map>
@@ -37,6 +37,28 @@ static const int mach64_post_div[8] = {
3, 5, 6, 12 // alternate post dividers
};
static int32_t mach64_extract_signed(uint32_t value, int pos, int width) {
value = extract_bits<uint32_t>(value, pos, width);
return static_cast<int32_t>(value << (32 - width)) >> (32 - width);
}
static bool mach64_clip_axis(int coord, int increment, uint32_t length,
int scissor_min, int scissor_max,
int& skip, uint32_t& clipped_length) {
int first = increment > 0 ? scissor_min - coord : coord - scissor_max;
int last = increment > 0 ? scissor_max - coord : coord - scissor_min;
first = std::max(first, 0);
last = std::min(last, int(length) - 1);
if (first > last) {
return false;
}
skip = first;
clipped_length = last - first + 1;
return true;
}
/* Human readable Mach64 HW register names for easier debugging. */
static const std::map<uint16_t, std::string> mach64_reg_names = {
#define one_reg_name(x) {ATI_ ## x, #x}
@@ -266,26 +288,33 @@ uint32_t ATIRage::read_reg(uint32_t reg_offset, uint32_t size) {
case ATI_GUI_STAT:
result = uint64_t(this->cmd_fifo_size << 16); // HACK: pretend empty FIFO
break;
case ATI_GUI_TRAJ_CNTL:
result = 0;
insert_bits<uint64_t>(result, this->regs[ATI_DST_CNTL], 0, 16);
insert_bits<uint64_t>(result, this->regs[ATI_SRC_CNTL], 16, 8);
insert_bits<uint64_t>(result, this->regs[ATI_PAT_CNTL], 24, 3);
insert_bits<uint64_t>(result, this->regs[ATI_HOST_CNTL], 28, 2);
break;
case ATI_DP_BKGD_CLR:
case ATI_DP_FRGD_CLR:
uint32_t pix_fmt = extract_bits<uint32_t>(
this->regs[ATI_CRTC_GEN_CNTL], ATI_CRTC_PIX_WIDTH, ATI_CRTC_PIX_WIDTH_size);
switch (pix_fmt) {
case 1:
case ATI_PIX_FMT_4BPP:
result = result & 0x1;
break;
case 2:
case ATI_PIX_FMT_8BPP:
result = result & 0xFF;
break;
case 3:
case 4:
case ATI_PIX_FMT_RGB555:
case ATI_PIX_FMT_RGB565:
result = result & 0xFFFF;
break;
case 5:
case ATI_PIX_FMT_RGB888:
result = result & 0xFFFFFF;
break;
case 6:
case ATI_PIX_FMT_ARGB8888:
break;
default:
LOG_F(ERROR, "Incorrect bit depth");
@@ -320,6 +349,11 @@ void ATIRage::write_reg(uint32_t reg_offset, uint32_t value, uint32_t size) {
uint32_t old_value = this->regs[reg_num];
uint32_t new_value;
if (reg_num >= ATI_HOST_DATA0 && reg_num <= ATI_HOST_DATA15) {
this->write_host_data(value, size);
return;
}
if (offset || size != 4) { // slow path
if ((offset + size) > 4) {
ABORT_F("%s: unaligned DWORD writes not implemented", this->name.c_str());
@@ -560,9 +594,61 @@ void ATIRage::write_reg(uint32_t reg_offset, uint32_t value, uint32_t size) {
new_value = (old_value & bits_read_only) | (new_value & ~bits_read_only);
break;
}
case ATI_DST_Y_X:
case ATI_DST_Y_X_ALIAS1:
new_value = value;
this->regs[ATI_DST_Y] = extract_bits<uint32_t>(value, 0, ATI_DST_Y_size);
this->regs[ATI_DST_X] = extract_bits<uint32_t>(value, 16, ATI_DST_X_size);
break;
case ATI_DST_X_Y:
new_value = value;
this->regs[ATI_DST_X] = extract_bits<uint32_t>(value, 0, ATI_DST_X_size);
this->regs[ATI_DST_Y] = extract_bits<uint32_t>(value, 16, ATI_DST_Y_size);
break;
case ATI_SRC_Y_X:
new_value = value;
this->regs[ATI_SRC_Y] = extract_bits<uint32_t>(value, 0, ATI_SRC_Y_size);
this->regs[ATI_SRC_X] = extract_bits<uint32_t>(value, 16, ATI_SRC_X_size);
break;
case ATI_SRC_HEIGHT1_WIDTH1:
new_value = value;
this->regs[ATI_SRC_HEIGHT1] = extract_bits<uint32_t>(value, 0, ATI_SRC_HEIGHT1_size);
this->regs[ATI_SRC_WIDTH1] = extract_bits<uint32_t>(value, 16, ATI_SRC_WIDTH1_size);
break;
case ATI_SRC_Y_X_START:
new_value = value;
this->regs[ATI_SRC_Y_START] = extract_bits<uint32_t>(value, 0, ATI_SRC_Y_START_size);
this->regs[ATI_SRC_X_START] = extract_bits<uint32_t>(value, 16, ATI_SRC_X_START_size);
break;
case ATI_SRC_HEIGHT2_WIDTH2:
new_value = value;
this->regs[ATI_SRC_HEIGHT2] = extract_bits<uint32_t>(value, 0, ATI_SRC_HEIGHT2_size);
this->regs[ATI_SRC_WIDTH2] = extract_bits<uint32_t>(value, 16, ATI_SRC_WIDTH2_size);
break;
case ATI_SC_LEFT_RIGHT:
new_value = value;
this->regs[ATI_SC_LEFT] = extract_bits<uint32_t>(value, 0, ATI_SC_LEFT_size);
this->regs[ATI_SC_RIGHT] = extract_bits<uint32_t>(value, 16, ATI_SC_RIGHT_size);
break;
case ATI_SC_TOP_BOTTOM:
new_value = value;
this->regs[ATI_SC_TOP] = extract_bits<uint32_t>(value, 0, ATI_SC_TOP_size);
this->regs[ATI_SC_BOTTOM] = extract_bits<uint32_t>(value, 16, ATI_SC_BOTTOM_size);
break;
case ATI_GUI_TRAJ_CNTL:
new_value = value;
insert_bits<uint32_t>(this->regs[ATI_DST_CNTL], value, 0, 16);
insert_bits<uint32_t>(this->regs[ATI_SRC_CNTL], value >> 16, 0, 8);
insert_bits<uint32_t>(this->regs[ATI_PAT_CNTL], value >> 24, 0, 3);
insert_bits<uint32_t>(this->regs[ATI_HOST_CNTL], value >> 28, 0, 2);
break;
case ATI_DST_WIDTH:
case ATI_DST_HEIGHT_WIDTH:
case ATI_DST_X_WIDTH:
case ATI_DST_WIDTH_HEIGHT:
this->begin_drawing(reg_num, value);
new_value = this->regs[reg_num];
break;
case ATI_DST_BRES_LNTH:
this->begin_drawing(reg_num, value);
break;
@@ -572,6 +658,8 @@ 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) {
@@ -709,10 +797,10 @@ void ATIRage::verbose_pixel_format(int crtc_index) {
const char* what = "Pixel format:";
switch (pix_fmt) {
case 1:
case ATI_PIX_FMT_4BPP:
LOG_F(INFO, "%s 4 bpp with DAC palette", what);
break;
case 2:
case ATI_PIX_FMT_8BPP:
// check the undocumented DAC_DIRECT bit
if (bit_set(this->regs[ATI_DAC_CNTL], ATI_DAC_DIRECT)) {
LOG_F(INFO, "%s 8 bpp direct color (RGB332)", what);
@@ -720,16 +808,16 @@ void ATIRage::verbose_pixel_format(int crtc_index) {
LOG_F(INFO, "%s 8 bpp with DAC palette", what);
}
break;
case 3:
case ATI_PIX_FMT_RGB555:
LOG_F(INFO, "%s 15 bpp direct color (RGB555)", what);
break;
case 4:
case ATI_PIX_FMT_RGB565:
LOG_F(INFO, "%s 16 bpp direct color (RGB565)", what);
break;
case 5:
case ATI_PIX_FMT_RGB888:
LOG_F(INFO, "%s 24 bpp direct color (RGB888)", what);
break;
case 6:
case ATI_PIX_FMT_ARGB8888:
LOG_F(INFO, "%s 32 bpp direct color (ARGB8888)", what);
break;
default:
@@ -825,6 +913,7 @@ void ATIRage::crtc_update() {
return;
this->draw_fb = true;
LOG_F(INFO, "%s: clock_sel:%d fb_div:%02x", this->name.c_str(), clock_sel, this->plls[VCLK0_FB_DIV + clock_sel]);
// calculate display refresh rate
this->refresh_rate = pixel_clock / this->hori_total / this->vert_total;
@@ -837,13 +926,13 @@ void ATIRage::crtc_update() {
// set up frame buffer converter
switch (this->pixel_format) {
case 1:
case ATI_PIX_FMT_4BPP:
this->convert_fb_cb = [this](uint8_t *dst_buf, int dst_pitch) {
draw_fb = false;
this->convert_frame_4bpp_indexed(dst_buf, dst_pitch);
};
break;
case 2:
case ATI_PIX_FMT_8BPP:
if (bit_set(this->regs[ATI_DAC_CNTL], ATI_DAC_DIRECT)) {
this->convert_fb_cb = [this](uint8_t *dst_buf, int dst_pitch) {
draw_fb = false;
@@ -857,25 +946,25 @@ void ATIRage::crtc_update() {
};
}
break;
case 3:
case ATI_PIX_FMT_RGB555:
this->convert_fb_cb = [this](uint8_t *dst_buf, int dst_pitch) {
draw_fb = false;
this->convert_frame_15bpp<BE>(dst_buf, dst_pitch);
};
break;
case 4:
case ATI_PIX_FMT_RGB565:
this->convert_fb_cb = [this](uint8_t *dst_buf, int dst_pitch) {
draw_fb = false;
this->convert_frame_16bpp<LE>(dst_buf, dst_pitch);
};
break;
case 5:
case ATI_PIX_FMT_RGB888:
this->convert_fb_cb = [this](uint8_t *dst_buf, int dst_pitch) {
draw_fb = false;
this->convert_frame_24bpp(dst_buf, dst_pitch);
};
break;
case 6:
case ATI_PIX_FMT_ARGB8888:
this->convert_fb_cb = [this](uint8_t *dst_buf, int dst_pitch) {
draw_fb = false;
this->convert_frame_32bpp<BE>(dst_buf, dst_pitch);
@@ -888,8 +977,9 @@ void ATIRage::crtc_update() {
LOG_F(INFO, "%s: primary CRT controller enabled:", this->name.c_str());
LOG_F(INFO, "Video mode: %s",
bit_set(this->regs[ATI_CRTC_GEN_CNTL], ATI_CRTC_EXT_DISP_EN) ? "extended" : "VGA");
LOG_F(INFO, "Video width: %d px", this->active_width);
LOG_F(INFO, "Video height: %d px", this->active_height);
LOG_F(INFO, "Video width: %d pixels", this->active_width);
LOG_F(INFO, "Video height: %d lines", this->active_height);
LOG_F(INFO, "Vertical blank: %d lines", this->vert_blank);
verbose_pixel_format(0);
LOG_F(INFO, "VPLL frequency: %f MHz", vpll_freq * 1e-6);
LOG_F(INFO, "Pixel (dot) clock: %f MHz", this->pixel_clock * 1e-6);
@@ -906,8 +996,8 @@ void ATIRage::draw_hw_cursor(uint8_t* dst_row, int dst_pitch) {
this->regs[ATI_CUR_HORZ_VERT_OFF], ATI_CUR_VERT_OFF, ATI_CUR_VERT_OFF_size);
int cur_height = 64 - vert_offset;
uint32_t color0 = this->regs[ATI_CUR_CLR0] | 0x000000FFUL;
uint32_t color1 = this->regs[ATI_CUR_CLR1] | 0x000000FFUL;
uint32_t color0 = (this->regs[ATI_CUR_CLR0] >> 8) | 0xFF000000UL;
uint32_t color1 = (this->regs[ATI_CUR_CLR1] >> 8) | 0xFF000000UL;
uint64_t* src_row = (uint64_t*)&this->vram_ptr[this->regs[ATI_CUR_OFFSET] * 8];
dst_pitch -= 64 * 4;
@@ -918,16 +1008,16 @@ void ATIRage::draw_hw_cursor(uint8_t* dst_row, int dst_pitch) {
for (int p = 32; p > 0; p--, px >>= 2, dst_row += 4) {
switch (px & 3) {
case 0: // cursor color 0
WRITE_DWORD_BE_A(dst_row, color0);
FB_WRITE(dst_row, color0);
break;
case 1: // cursor color 1
WRITE_DWORD_BE_A(dst_row, color1);
FB_WRITE(dst_row, color1);
break;
case 2: // transparent
WRITE_DWORD_BE_A(dst_row, 0);
FB_WRITE(dst_row, 0);
break;
case 3: // 1's complement of display pixel
WRITE_DWORD_BE_A(dst_row, 0x0000007F);
FB_WRITE(dst_row, 0x7F000000);
break;
}
}
@@ -945,7 +1035,7 @@ void ATIRage::get_cursor_position(int& x, int& y) {
int ATIRage::device_postinit()
{
this->vbl_cb = [this](uint8_t irq_line_state) {
insert_bits<uint32_t>(this->regs[ATI_CRTC_INT_CNTL], irq_line_state, ATI_CRTC_VBLANK, irq_line_state);
insert_bits<uint32_t>(this->regs[ATI_CRTC_INT_CNTL], irq_line_state, ATI_CRTC_VBLANK, 1);
if (irq_line_state) {
set_bit(this->regs[ATI_CRTC_INT_CNTL], ATI_CRTC_VBLANK_INT);
set_bit(this->regs[ATI_CRTC_INT_CNTL], ATI_CRTC_VLINE_INT);
@@ -955,29 +1045,69 @@ int ATIRage::device_postinit()
#endif
}
bool do_interrupt =
bit_set(this->regs[ATI_CRTC_INT_CNTL], ATI_CRTC_VBLANK_INT_EN) ||
bit_set(this->regs[ATI_CRTC_INT_CNTL], ATI_CRTC_VLINE_INT_EN) ||
#if 1
#else
bit_set(this->regs[ATI_CRTC_GEN_CNTL], ATI_CRTC_VSYNC_INT_EN) ||
#endif
0;
if (do_interrupt) {
this->pci_interrupt(irq_line_state);
}
this->update_interrupt();
};
return 0;
}
void ATIRage::update_interrupt()
{
uint32_t int_cntl = this->regs[ATI_CRTC_INT_CNTL];
bool new_pci_irq_line_state =
(bit_set(int_cntl, ATI_CRTC_VBLANK_INT_EN) &&
bit_set(int_cntl, ATI_CRTC_VBLANK_INT)) ||
(bit_set(int_cntl, ATI_CRTC_VLINE_INT_EN) &&
bit_set(int_cntl, ATI_CRTC_VLINE_INT));
if (new_pci_irq_line_state != this->pci_irq_line_state) {
this->pci_irq_line_state = new_pci_irq_line_state;
this->pci_interrupt(this->pci_irq_line_state);
}
}
// =================================== Draw Engine =====================================
void ATIRage::begin_drawing(uint32_t initiator, uint32_t value) {
switch(initiator) {
case ATI_DST_HEIGHT_WIDTH:
this->regs[ATI_DST_HEIGHT_WIDTH] = value;
this->draw_rect(extract_bits<uint32_t>(value, 16, 14), extract_bits<uint32_t>(value, 0, 15));
case ATI_DST_WIDTH: {
uint32_t width = extract_bits<uint32_t>(value, ATI_DST_WIDTH_pos, ATI_DST_WIDTH_size);
this->regs[ATI_DST_WIDTH] = width;
if (!bit_set(value, DST_WIDTH_FILL_DIS)) {
this->draw_rect(
width,
extract_bits<uint32_t>(
this->regs[ATI_DST_HEIGHT], ATI_DST_HEIGHT_pos, ATI_DST_HEIGHT_size));
}
break;
}
case ATI_DST_HEIGHT_WIDTH: {
uint32_t width = extract_bits<uint32_t>(value, 16, ATI_DST_WIDTH_size);
uint32_t height = extract_bits<uint32_t>(value, 0, ATI_DST_HEIGHT_size);
this->regs[ATI_DST_HEIGHT_WIDTH] = value;
this->regs[ATI_DST_WIDTH] = width;
this->regs[ATI_DST_HEIGHT] = height;
this->draw_rect(width, height);
break;
}
case ATI_DST_X_WIDTH: {
uint32_t width = extract_bits<uint32_t>(value, 16, ATI_DST_WIDTH_size);
this->regs[ATI_DST_X_WIDTH] = value;
this->regs[ATI_DST_X] = extract_bits<uint32_t>(value, 0, ATI_DST_X_size);
this->regs[ATI_DST_WIDTH] = width;
this->draw_rect(
width,
extract_bits<uint32_t>(
this->regs[ATI_DST_HEIGHT], ATI_DST_HEIGHT_pos, ATI_DST_HEIGHT_size));
break;
}
case ATI_DST_WIDTH_HEIGHT: {
uint32_t width = extract_bits<uint32_t>(value, 0, ATI_DST_WIDTH_size);
uint32_t height = extract_bits<uint32_t>(value, 16, ATI_DST_HEIGHT_size);
this->regs[ATI_DST_WIDTH_HEIGHT] = value;
this->regs[ATI_DST_WIDTH] = width;
this->regs[ATI_DST_HEIGHT] = height;
this->draw_rect(width, height);
break;
}
default:
LOG_F(WARNING, "%s: unimplemented engine operation, initiator=0x%X", this->name.c_str(),
initiator);
@@ -985,26 +1115,65 @@ void ATIRage::begin_drawing(uint32_t initiator, uint32_t value) {
}
void ATIRage::draw_rect(uint32_t width, uint32_t height) {
uint8_t frgd_src = extract_bits<uint32_t>(this->regs[ATI_DP_SRC], ATI_DP_FRGD_SRC, ATI_DP_FRGD_SRC_size);
uint8_t bkgd_src = extract_bits<uint32_t>(this->regs[ATI_DP_SRC], ATI_DP_BKGD_SRC, ATI_DP_BKGD_SRC_size);
uint8_t mono_src = extract_bits<uint32_t>(this->regs[ATI_DP_SRC], ATI_DP_MONO_SRC, ATI_DP_MONO_SRC_size);
uint8_t frgd_src = extract_bits<uint32_t>(
this->regs[ATI_DP_SRC], ATI_DP_FRGD_SRC, ATI_DP_FRGD_SRC_size);
uint8_t mono_src = extract_bits<uint32_t>(
this->regs[ATI_DP_SRC], ATI_DP_MONO_SRC, ATI_DP_MONO_SRC_size);
uint32_t src_cntl = this->regs[ATI_SRC_CNTL];
if (frgd_src == 1 && !mono_src) { // rectangle fill with foreground color
this->fill_rect(width, height);
this->host_data_active = false;
// Color register blits update SGRAM state rather than VRAM.
if (bit_set(src_cntl, ATI_SRC_COLOR_REG_WRITE_EN) &&
!bit_set(src_cntl, ATI_SRC_BLOCK_WRITE_EN)) {
this->finish_rect(width, height);
return;
}
if ((frgd_src == ATI_DP_COLOR_SRC_BKGD_CLR || frgd_src == ATI_DP_COLOR_SRC_FRGD_CLR) &&
mono_src == ATI_DP_MONO_SRC_ALWAYS_1) {
uint32_t color = frgd_src == ATI_DP_COLOR_SRC_BKGD_CLR ? this->regs[ATI_DP_BKGD_CLR]
: this->regs[ATI_DP_FRGD_CLR];
this->fill_rect(width, height, color);
this->finish_rect(width, height);
} else if (frgd_src == ATI_DP_COLOR_SRC_HOST &&
mono_src == ATI_DP_MONO_SRC_ALWAYS_1) {
this->start_host_rect(width, height);
} else if (frgd_src == ATI_DP_COLOR_SRC_BLIT &&
mono_src == ATI_DP_MONO_SRC_ALWAYS_1) {
this->blit_rect(width, height);
this->finish_rect(width, height);
} else {
LOG_F(WARNING, "%s: unimplemented rectangle draw op, DP_FRGD_SRC=0x%X", this->name.c_str(),
frgd_src);
LOG_F(WARNING, "%s: unimplemented rectangle draw op, DP_SRC=0x%08X, DP_MIX=0x%08X, "
"DP_PIX_WIDTH=0x%08X, SRC_CNTL=0x%08X", this->name.c_str(),
this->regs[ATI_DP_SRC], this->regs[ATI_DP_MIX], this->regs[ATI_DP_PIX_WIDTH],
this->regs[ATI_SRC_CNTL]);
}
}
void ATIRage::fill_rect(uint32_t dst_width, uint32_t dst_height) {
uint8_t frgd_mix = extract_bits<uint32_t>(this->regs[ATI_DP_MIX], ATI_DP_FRGD_MIX, ATI_DP_FRGD_MIX_size);
uint8_t bkgd_mix = extract_bits<uint32_t>(this->regs[ATI_DP_MIX], ATI_DP_BKGD_MIX, ATI_DP_BKGD_MIX_size);
void ATIRage::finish_rect(uint32_t width, uint32_t height) {
int dst_x = mach64_extract_signed(this->regs[ATI_DST_X], ATI_DST_X_pos, ATI_DST_X_size);
int dst_y = mach64_extract_signed(this->regs[ATI_DST_Y], ATI_DST_Y_pos, ATI_DST_Y_size);
int x_delta = int(width);
int y_delta = int(height);
// check for non-trivial operations
if (frgd_mix != 7 || bkgd_mix != 3) {
LOG_F(WARNING, "%s: unimplemented rectangle fill op, DP_FRGD_MIX=0x%X, DP_BKGD_MIX=0x%X",
this->name.c_str(), frgd_mix, bkgd_mix);
if (bit_set(this->regs[ATI_DST_CNTL], ATI_DST_X_TILE)) {
dst_x += bit_set(this->regs[ATI_DST_CNTL], ATI_DST_X_DIR) ? x_delta : -x_delta;
insert_bits<uint32_t>(this->regs[ATI_DST_X], dst_x, ATI_DST_X_pos, ATI_DST_X_size);
}
if (bit_set(this->regs[ATI_DST_CNTL], ATI_DST_Y_TILE)) {
dst_y += bit_set(this->regs[ATI_DST_CNTL], ATI_DST_Y_DIR) ? y_delta : -y_delta;
insert_bits<uint32_t>(this->regs[ATI_DST_Y], dst_y, ATI_DST_Y_pos, ATI_DST_Y_size);
}
}
void ATIRage::fill_rect(uint32_t dst_width, uint32_t dst_height, uint32_t color) {
uint8_t frgd_mix = extract_bits<uint32_t>(this->regs[ATI_DP_MIX], ATI_DP_FRGD_MIX,
ATI_DP_FRGD_MIX_size);
if (frgd_mix != ATI_DP_MIX_SRC) {
LOG_F(WARNING, "%s: unimplemented rectangle fill op, DP_FRGD_MIX=0x%X",
this->name.c_str(), frgd_mix);
return;
}
@@ -1020,39 +1189,322 @@ void ATIRage::fill_rect(uint32_t dst_width, uint32_t dst_height) {
uint8_t dst_pix_fmt = extract_bits<uint32_t>(this->regs[ATI_DP_PIX_WIDTH], ATI_DP_DST_PIX_WIDTH,
ATI_DP_DST_PIX_WIDTH_size);
if (src_pix_fmt != 6 || dst_pix_fmt != src_pix_fmt) {
if (dst_pix_fmt != src_pix_fmt) {
LOG_F(WARNING, "%s: unsupported pixel format conversion, DP_SRC_PIX_WIDTH=0x%X, DP_DST_PIX_WIDTH=0x%X",
this->name.c_str(), src_pix_fmt, dst_pix_fmt);
return;
}
int bytes_per_pixel;
switch (dst_pix_fmt) {
case ATI_PIX_FMT_8BPP:
bytes_per_pixel = 1;
break;
case ATI_PIX_FMT_RGB555:
case ATI_PIX_FMT_RGB565:
bytes_per_pixel = 2;
break;
case ATI_PIX_FMT_RGB888:
bytes_per_pixel = 3;
break;
case ATI_PIX_FMT_ARGB8888:
bytes_per_pixel = 4;
break;
default:
LOG_F(WARNING, "%s: unsupported rectangle fill pixel format, DP_DST_PIX_WIDTH=0x%X",
this->name.c_str(), dst_pix_fmt);
return;
}
// grab trajectory params
int dst_offs = extract_bits<uint32_t>(this->regs[ATI_DST_OFF_PITCH], ATI_DST_OFFSET, ATI_DST_OFFSET_size);
int dst_pitch = extract_bits<uint32_t>(this->regs[ATI_DST_OFF_PITCH], ATI_DST_PITCH, ATI_DST_PITCH_size);
int dst_x = extract_bits<uint32_t>(this->regs[ATI_DST_X], ATI_DST_X_pos, ATI_DST_X_size);
int dst_y = extract_bits<uint32_t>(this->regs[ATI_DST_Y], ATI_DST_Y_pos, ATI_DST_Y_size);
int dst_x = mach64_extract_signed(this->regs[ATI_DST_X], ATI_DST_X_pos, ATI_DST_X_size);
int dst_y = mach64_extract_signed(this->regs[ATI_DST_Y], ATI_DST_Y_pos, ATI_DST_Y_size);
dst_offs *= 8;
dst_pitch *= 8;
dst_pitch *= 8 * bytes_per_pixel;
int x_inc = (this->regs[ATI_DST_CNTL] & 1) ? 1 : -1;
int y_inc = (this->regs[ATI_DST_CNTL] & 2) ? 1 : -1;
int x_inc = bit_set(this->regs[ATI_DST_CNTL], ATI_DST_X_DIR) ? 1 : -1;
int y_inc = bit_set(this->regs[ATI_DST_CNTL], ATI_DST_Y_DIR) ? 1 : -1;
uint32_t pix = BYTESWAP_32(this->regs[ATI_DP_FRGD_CLR] & this->regs[ATI_DP_WRITE_MSK]);
int sc_left = mach64_extract_signed(this->regs[ATI_SC_LEFT], ATI_SC_LEFT_pos, ATI_SC_LEFT_size);
int sc_right = mach64_extract_signed(
this->regs[ATI_SC_RIGHT], ATI_SC_RIGHT_pos, ATI_SC_RIGHT_size);
int sc_top = mach64_extract_signed(this->regs[ATI_SC_TOP], ATI_SC_TOP_pos, ATI_SC_TOP_size);
int sc_bottom = mach64_extract_signed(
this->regs[ATI_SC_BOTTOM], ATI_SC_BOTTOM_pos, ATI_SC_BOTTOM_size);
uint32_t* dst_ptr = (uint32_t*)&this->vram_ptr[dst_offs];
dst_ptr += dst_y * dst_pitch;
int x_skip, y_skip;
if (!mach64_clip_axis(dst_x, x_inc, dst_width, sc_left, sc_right, x_skip, dst_width) ||
!mach64_clip_axis(dst_y, y_inc, dst_height, sc_top, sc_bottom, y_skip, dst_height)) {
return;
}
dst_x += x_skip * x_inc;
dst_y += y_skip * y_inc;
int x_pos, width;
uint32_t pix = color & this->regs[ATI_DP_WRITE_MSK];
dst_pitch *= y_inc;
switch (dst_pix_fmt) {
case ATI_PIX_FMT_8BPP:
for (uint32_t y = 0; y < dst_height; y++) {
uint8_t* row = &this->vram_ptr[dst_offs + (dst_y + int(y) * y_inc) * dst_pitch];
for (int x = dst_x, width = dst_width; width-- > 0; x += x_inc) {
row[x] = uint8_t(pix);
}
}
break;
case ATI_PIX_FMT_RGB555:
pix = BYTESWAP_16(pix);
for (uint32_t y = 0; y < dst_height; y++) {
uint16_t* row = (uint16_t*)&this->vram_ptr[dst_offs + (dst_y + int(y) * y_inc) * dst_pitch];
for (int x = dst_x, width = dst_width; width-- > 0; x += x_inc) {
row[x] = pix;
}
}
break;
case ATI_PIX_FMT_RGB565:
pix &= 0xFFFF;
for (uint32_t y = 0; y < dst_height; y++) {
uint16_t* row = (uint16_t*)&this->vram_ptr[dst_offs + (dst_y + int(y) * y_inc) * dst_pitch];
for (int x = dst_x, width = dst_width; width-- > 0; x += x_inc) {
row[x] = pix;
}
}
break;
case ATI_PIX_FMT_RGB888:
for (uint32_t y = 0; y < dst_height; y++) {
uint8_t* row = &this->vram_ptr[dst_offs + (dst_y + int(y) * y_inc) * dst_pitch];
for (int x = dst_x, width = dst_width; width-- > 0; x += x_inc) {
uint8_t* dst_ptr = row + x * 3;
dst_ptr[0] = uint8_t(pix >> 16);
dst_ptr[1] = uint8_t(pix >> 8);
dst_ptr[2] = uint8_t(pix);
}
}
break;
case ATI_PIX_FMT_ARGB8888:
pix = BYTESWAP_32(pix);
for (uint32_t y = 0; y < dst_height; y++) {
uint32_t* row = (uint32_t*)&this->vram_ptr[dst_offs + (dst_y + int(y) * y_inc) * dst_pitch];
for (int x = dst_x, width = dst_width; width-- > 0; x += x_inc) {
row[x] = pix;
}
}
break;
}
for (; dst_height-- > 0; dst_ptr += dst_pitch) {
for (x_pos = dst_x, width = dst_width; width-- > 0; x_pos += x_inc) {
dst_ptr[x_pos] = pix;
this->draw_fb = true;
}
void ATIRage::start_host_rect(uint32_t dst_width, uint32_t dst_height) {
uint8_t frgd_mix = extract_bits<uint32_t>(this->regs[ATI_DP_MIX], ATI_DP_FRGD_MIX,
ATI_DP_FRGD_MIX_size);
uint8_t host_pix_fmt = extract_bits<uint32_t>(this->regs[ATI_DP_PIX_WIDTH], ATI_DP_HOST_PIX_WIDTH,
ATI_DP_HOST_PIX_WIDTH_size);
uint8_t dst_pix_fmt = extract_bits<uint32_t>(this->regs[ATI_DP_PIX_WIDTH], ATI_DP_DST_PIX_WIDTH,
ATI_DP_DST_PIX_WIDTH_size);
if (frgd_mix != ATI_DP_MIX_SRC || host_pix_fmt != ATI_PIX_FMT_8BPP ||
dst_pix_fmt != ATI_PIX_FMT_8BPP || this->regs[ATI_CLR_CMP_CNTL]) {
LOG_F(WARNING, "%s: unsupported color host rectangle, DP_MIX=0x%08X, "
"DP_PIX_WIDTH=0x%08X, CLR_CMP_CNTL=0x%08X", this->name.c_str(),
this->regs[ATI_DP_MIX], this->regs[ATI_DP_PIX_WIDTH],
this->regs[ATI_CLR_CMP_CNTL]);
return;
}
this->host_dst_width = dst_width;
this->host_dst_height = dst_height;
this->host_dst_col = 0;
this->host_dst_row = 0;
this->host_data_active = true;
}
void ATIRage::write_host_data(uint32_t value, uint32_t size) {
if (!this->host_data_active) {
return;
}
int dst_offs = extract_bits<uint32_t>(
this->regs[ATI_DST_OFF_PITCH], ATI_DST_OFFSET, ATI_DST_OFFSET_size) *
8;
int dst_pitch =
extract_bits<uint32_t>(this->regs[ATI_DST_OFF_PITCH], ATI_DST_PITCH, ATI_DST_PITCH_size) * 8;
int dst_x = mach64_extract_signed(this->regs[ATI_DST_X], ATI_DST_X_pos, ATI_DST_X_size);
int dst_y = mach64_extract_signed(this->regs[ATI_DST_Y], ATI_DST_Y_pos, ATI_DST_Y_size);
int sc_left = mach64_extract_signed(this->regs[ATI_SC_LEFT], ATI_SC_LEFT_pos, ATI_SC_LEFT_size);
int sc_right = mach64_extract_signed(
this->regs[ATI_SC_RIGHT], ATI_SC_RIGHT_pos, ATI_SC_RIGHT_size);
int sc_top = mach64_extract_signed(this->regs[ATI_SC_TOP], ATI_SC_TOP_pos, ATI_SC_TOP_size);
int sc_bottom = mach64_extract_signed(
this->regs[ATI_SC_BOTTOM], ATI_SC_BOTTOM_pos, ATI_SC_BOTTOM_size);
int x_inc = bit_set(this->regs[ATI_DST_CNTL], ATI_DST_X_DIR) ? 1 : -1;
int y_inc = bit_set(this->regs[ATI_DST_CNTL], ATI_DST_Y_DIR) ? 1 : -1;
uint8_t write_mask = this->regs[ATI_DP_WRITE_MSK];
for (uint32_t byte = 0; byte < size && this->host_data_active; byte++) {
int shift = x_inc > 0 ? int(byte) * 8 : int(size - byte - 1) * 8;
uint8_t pixel = value >> shift;
int x = dst_x + int(this->host_dst_col) * x_inc;
int y = dst_y + int(this->host_dst_row) * y_inc;
if (x >= sc_left && x <= sc_right && y >= sc_top && y <= sc_bottom) {
uint8_t* dst = &this->vram_ptr[dst_offs + y * dst_pitch + x];
*dst = (*dst & ~write_mask) | (pixel & write_mask);
this->draw_fb = true;
}
if (++this->host_dst_col >= this->host_dst_width) {
this->host_dst_col = 0;
if (++this->host_dst_row >= this->host_dst_height) {
this->host_data_active = false;
this->finish_rect(this->host_dst_width, this->host_dst_height);
}
}
}
}
void ATIRage::blit_rect(uint32_t dst_width, uint32_t dst_height) {
uint8_t frgd_mix = extract_bits<uint32_t>(this->regs[ATI_DP_MIX], ATI_DP_FRGD_MIX,
ATI_DP_FRGD_MIX_size);
uint8_t src_pix_fmt = extract_bits<uint32_t>(this->regs[ATI_DP_PIX_WIDTH], ATI_DP_SRC_PIX_WIDTH,
ATI_DP_SRC_PIX_WIDTH_size);
uint8_t dst_pix_fmt = extract_bits<uint32_t>(this->regs[ATI_DP_PIX_WIDTH], ATI_DP_DST_PIX_WIDTH,
ATI_DP_DST_PIX_WIDTH_size);
int bytes_per_pixel;
switch (dst_pix_fmt) {
case ATI_PIX_FMT_8BPP:
bytes_per_pixel = 1;
break;
case ATI_PIX_FMT_RGB555:
case ATI_PIX_FMT_RGB565:
bytes_per_pixel = 2;
break;
case ATI_PIX_FMT_ARGB8888:
bytes_per_pixel = 4;
break;
default:
bytes_per_pixel = 0;
break;
}
uint32_t pixel_mask = bytes_per_pixel == 4 ? 0xFFFFFFFFU :
((1U << (bytes_per_pixel * 8)) - 1);
uint32_t src_cntl = this->regs[ATI_SRC_CNTL];
bool supported_src_trajectory = src_cntl == ATI_SRC_TRAJ_UNBOUNDED ||
src_cntl == ATI_SRC_TRAJ_PATTERN || src_cntl == ATI_SRC_TRAJ_ROTATED;
if (frgd_mix != ATI_DP_MIX_SRC || !supported_src_trajectory || this->regs[ATI_CLR_CMP_CNTL] ||
src_pix_fmt != dst_pix_fmt || !bytes_per_pixel ||
(this->regs[ATI_DP_WRITE_MSK] & pixel_mask) != pixel_mask) {
LOG_F(WARNING, "%s: unsupported rectangle blit, DP_SRC=0x%08X, DP_MIX=0x%08X, "
"DP_PIX_WIDTH=0x%08X, DP_WRITE_MSK=0x%08X, SRC_CNTL=0x%08X, "
"CLR_CMP_CNTL=0x%08X", this->name.c_str(), this->regs[ATI_DP_SRC],
this->regs[ATI_DP_MIX], this->regs[ATI_DP_PIX_WIDTH], this->regs[ATI_DP_WRITE_MSK],
this->regs[ATI_SRC_CNTL], this->regs[ATI_CLR_CMP_CNTL]);
return;
}
int src_offs = extract_bits<uint32_t>(
this->regs[ATI_SRC_OFF_PITCH], ATI_SRC_OFFSET, ATI_SRC_OFFSET_size) *
8;
int src_pitch = extract_bits<uint32_t>(
this->regs[ATI_SRC_OFF_PITCH], ATI_SRC_PITCH, ATI_SRC_PITCH_size) *
8 * bytes_per_pixel;
int src_x = mach64_extract_signed(this->regs[ATI_SRC_X], ATI_SRC_X_pos, ATI_SRC_X_size);
int src_y = mach64_extract_signed(this->regs[ATI_SRC_Y], ATI_SRC_Y_pos, ATI_SRC_Y_size);
int src_x_start = mach64_extract_signed(
this->regs[ATI_SRC_X_START], ATI_SRC_X_START_pos, ATI_SRC_X_START_size);
int src_y_start = mach64_extract_signed(
this->regs[ATI_SRC_Y_START], ATI_SRC_Y_START_pos, ATI_SRC_Y_START_size);
uint32_t src_width1 = extract_bits<uint32_t>(
this->regs[ATI_SRC_WIDTH1], ATI_SRC_WIDTH1_pos, ATI_SRC_WIDTH1_size);
uint32_t src_height1 = extract_bits<uint32_t>(
this->regs[ATI_SRC_HEIGHT1], ATI_SRC_HEIGHT1_pos, ATI_SRC_HEIGHT1_size);
uint32_t src_width2 = extract_bits<uint32_t>(
this->regs[ATI_SRC_WIDTH2], ATI_SRC_WIDTH2_pos, ATI_SRC_WIDTH2_size);
uint32_t src_height2 = extract_bits<uint32_t>(
this->regs[ATI_SRC_HEIGHT2], ATI_SRC_HEIGHT2_pos, ATI_SRC_HEIGHT2_size);
if ((src_cntl == ATI_SRC_TRAJ_PATTERN && (!src_width1 || !src_height1)) ||
(src_cntl == ATI_SRC_TRAJ_ROTATED &&
(!src_width1 || !src_height1 || !src_width2 || !src_height2))) {
LOG_F(WARNING, "%s: invalid rectangle blit source trajectory, SRC_CNTL=0x%08X, "
"SRC_HEIGHT1_WIDTH1=0x%08X, SRC_HEIGHT2_WIDTH2=0x%08X", this->name.c_str(),
src_cntl, this->regs[ATI_SRC_HEIGHT1_WIDTH1],
this->regs[ATI_SRC_HEIGHT2_WIDTH2]);
return;
}
int dst_offs = extract_bits<uint32_t>(
this->regs[ATI_DST_OFF_PITCH], ATI_DST_OFFSET, ATI_DST_OFFSET_size) *
8;
int dst_pitch = extract_bits<uint32_t>(
this->regs[ATI_DST_OFF_PITCH], ATI_DST_PITCH, ATI_DST_PITCH_size) *
8 * bytes_per_pixel;
int dst_x = mach64_extract_signed(this->regs[ATI_DST_X], ATI_DST_X_pos, ATI_DST_X_size);
int dst_y = mach64_extract_signed(this->regs[ATI_DST_Y], ATI_DST_Y_pos, ATI_DST_Y_size);
int x_inc = bit_set(this->regs[ATI_DST_CNTL], ATI_DST_X_DIR) ? 1 : -1;
int y_inc = bit_set(this->regs[ATI_DST_CNTL], ATI_DST_Y_DIR) ? 1 : -1;
int sc_left = mach64_extract_signed(this->regs[ATI_SC_LEFT], ATI_SC_LEFT_pos, ATI_SC_LEFT_size);
int sc_right = mach64_extract_signed(
this->regs[ATI_SC_RIGHT], ATI_SC_RIGHT_pos, ATI_SC_RIGHT_size);
int sc_top = mach64_extract_signed(this->regs[ATI_SC_TOP], ATI_SC_TOP_pos, ATI_SC_TOP_size);
int sc_bottom = mach64_extract_signed(
this->regs[ATI_SC_BOTTOM], ATI_SC_BOTTOM_pos, ATI_SC_BOTTOM_size);
int x_skip, y_skip;
if (!mach64_clip_axis(dst_x, x_inc, dst_width, sc_left, sc_right, x_skip, dst_width) ||
!mach64_clip_axis(dst_y, y_inc, dst_height, sc_top, sc_bottom, y_skip, dst_height)) {
return;
}
dst_x += x_skip * x_inc;
dst_y += y_skip * y_inc;
for (uint32_t y = 0; y < dst_height; y++) {
uint32_t src_row_index = y_skip + y;
int sy;
if (src_cntl == ATI_SRC_TRAJ_PATTERN) {
sy = src_y + int(src_row_index % src_height1) * y_inc;
} else if (src_cntl == ATI_SRC_TRAJ_ROTATED && src_row_index >= src_height1) {
sy = src_y_start + int((src_row_index - src_height1) % src_height2) * y_inc;
} else {
sy = src_y + int(src_row_index) * y_inc;
}
uint8_t* src_row = &this->vram_ptr[src_offs + sy * src_pitch];
int dy = dst_y + int(y) * y_inc;
uint8_t* dst_row = &this->vram_ptr[dst_offs + dy * dst_pitch];
for (uint32_t x = 0; x < dst_width; x++) {
uint32_t src_col_index = x_skip + x;
int sx;
if (src_cntl == ATI_SRC_TRAJ_PATTERN) {
sx = src_x + int(src_col_index % src_width1) * x_inc;
} else if (src_cntl == ATI_SRC_TRAJ_ROTATED && src_row_index > 0) {
sx = src_x_start + int(src_col_index % src_width2) * x_inc;
} else if (src_cntl == ATI_SRC_TRAJ_ROTATED && src_col_index >= src_width1) {
sx = src_x_start + int((src_col_index - src_width1) % src_width2) * x_inc;
} else {
sx = src_x + int(src_col_index) * x_inc;
}
int dx = dst_x + int(x) * x_inc;
uint8_t* src_pixel = &src_row[sx * bytes_per_pixel];
uint8_t* dst_pixel = &dst_row[dx * bytes_per_pixel];
for (int byte = 0; byte < bytes_per_pixel; byte++) {
dst_pixel[byte] = src_pixel[byte];
}
}
}
this->draw_fb = true;
}
// ================================== Device config ====================================
static const PropMap AtiRage_Properties = {
+13 -1
View File
@@ -89,15 +89,27 @@ protected:
private:
void change_one_bar(uint32_t &aperture, uint32_t aperture_size,
uint32_t aperture_new, int bar_num);
void update_interrupt();
void begin_drawing(uint32_t initiator, uint32_t value);
void draw_rect(uint32_t width, uint32_t height);
void fill_rect(uint32_t dst_width, uint32_t dst_height);
void finish_rect(uint32_t width, uint32_t height);
void fill_rect(uint32_t dst_width, uint32_t dst_height, uint32_t color);
void blit_rect(uint32_t dst_width, uint32_t dst_height);
void start_host_rect(uint32_t dst_width, uint32_t dst_height);
void write_host_data(uint32_t value, uint32_t size);
uint32_t regs[512] = {}; // internal registers
uint8_t plls[64] = {}; // internal PLL registers
uint8_t cmd_fifo_size = 0;
bool pci_irq_line_state = false;
bool host_data_active = false;
uint32_t host_dst_width = 0;
uint32_t host_dst_height = 0;
uint32_t host_dst_col = 0;
uint32_t host_dst_row = 0;
// Video RAM variables
std::unique_ptr<uint8_t[]> vram_ptr;
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff. Show more