Compare commits

..
Author SHA1 Message Date
dingusdevandjoevt e1a0adde8b Fixing compilation
Co-Authored-By: joevt <[email protected]>
2024-12-21 14:06:40 -07:00
dingusdev c25ad96e3a initial attempt to remove global variable exec_flags 2024-12-20 21:25:50 -07:00
234 changed files with 9916 additions and 19108 deletions

No files matched your search

+220 -248
View File
@@ -4,290 +4,262 @@ on:
branches: [ master ] branches: [ master ]
pull_request: pull_request:
branches: [ master ] branches: [ master ]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
env: env:
# Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.)
BUILD_TYPE: Release BUILD_TYPE: Release
jobs: jobs:
build-linux: build:
# The CMake configure and build commands are platform agnostic and should work equally well on Windows or Mac. # The CMake configure and build commands are platform agnostic and should work equally well on Windows or Mac.
# You can convert this to a matrix build if you need cross-platform coverage. # You can convert this to a matrix build if you need cross-platform coverage.
# See: https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix # See: https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 20
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@v3
with: - name: install_dependencies
submodules: recursive
- name: Cache ccache
uses: actions/cache@v5
with:
path: ${{ github.workspace }}/.ccache/linux
key: linux-ccache-${{ runner.os }}-${{ env.BUILD_TYPE }}-${{ hashFiles('**/CMakeLists.txt') }}
restore-keys: linux-ccache-${{ runner.os }}-${{ env.BUILD_TYPE }}-
- name: Install dependencies
run: | run: |
sudo apt-get update -y -qq sudo apt-get update -y -qq
sudo apt-get install -y -qq libsdl2-dev ninja-build ccache sudo apt-get install libsdl2-dev
- name: init_submodules
run: git submodule update --init --recursive
- name: Configure CMake - name: Configure CMake
# Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make. # Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make.
# See https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type # See https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type
env: run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DDPPC_68K_DEBUGGER=ON
CCACHE_DIR: ${{ github.workspace }}/.ccache/linux
CCACHE_BASEDIR: ${{ github.workspace }}
run: cmake -S . -B ${{github.workspace}}/build -GNinja -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DDPPC_68K_DEBUGGER=ON -DDPPC_BUILD_PPC_TESTS=ON -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache
- name: Build - name: Build
# Build your program with the given configuration # Build your program with the given configuration
run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} --parallel run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}}
- name: ccache stats - name: Upload artifact
run: ccache --show-stats || true uses: actions/upload-artifact@v4
with:
name: DingusPPC-LINUX
path: ${{github.workspace}}/build/bin
- name: Test - name: Test
working-directory: ${{github.workspace}}/build working-directory: ${{github.workspace}}/build
# Execute tests defined by the CMake configuration. # Execute tests defined by the CMake configuration.
# See https://cmake.org/cmake/help/latest/manual/ctest.1.html for more detail # See https://cmake.org/cmake/help/latest/manual/ctest.1.html for more detail
run: ctest -C ${{env.BUILD_TYPE}} --output-on-failure run: ctest -C ${{env.BUILD_TYPE}}
- name: Upload logs on failure build-windows:
if: failure()
uses: actions/upload-artifact@v6
with:
name: logs-${{ github.job }}
path: |
${{ github.workspace }}/build/Testing/Temporary/LastTest.log
${{ github.workspace }}/build/CMakeFiles/CMakeOutput.log
${{ github.workspace }}/build/CMakeFiles/CMakeError.log
if-no-files-found: ignore
retention-days: ${{ github.event_name == 'pull_request' && 7 || 30 }}
- name: Upload artifact
if: always()
uses: actions/upload-artifact@v6
with:
name: DingusPPC-LINUX
path: ${{github.workspace}}/build/bin
retention-days: ${{ github.event_name == 'pull_request' && 7 || 30 }}
build-macos:
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
include:
- runner: macos-latest
arch: arm64
brew_prefix: /opt/homebrew
- runner: macos-15-intel
arch: x86_64
brew_prefix: /usr/local
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@v5
with:
submodules: recursive
- name: Cache ccache
uses: actions/cache@v5
with:
path: ${{ github.workspace }}/.ccache/${{ matrix.arch }}
key: macos-${{ matrix.runner }}-${{ matrix.arch }}-ccache-${{ env.BUILD_TYPE }}-${{ hashFiles('**/CMakeLists.txt') }}
restore-keys: macos-${{ matrix.runner }}-${{ matrix.arch }}-ccache-${{ env.BUILD_TYPE }}-
- name: Install dependencies
run: |
export HOMEBREW_NO_AUTO_UPDATE=1
export HOMEBREW_NO_INSTALL_CLEANUP=1
brew install sdl2 ccache ninja
- name: Configure CMake
env:
CCACHE_DIR: ${{ github.workspace }}/.ccache/${{ matrix.arch }}
CCACHE_BASEDIR: ${{ github.workspace }}
run: |
export PATH="${{ matrix.brew_prefix }}/opt/ccache/libexec:$PATH"
cmake -S . -B ${{github.workspace}}/build -GNinja -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DDPPC_68K_DEBUGGER=ON -DDPPC_BUILD_PPC_TESTS=ON -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_OSX_ARCHITECTURES=${{ matrix.arch }}
- name: Build
run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} --parallel
- name: ccache stats
run: ccache --show-stats || true
- name: Test
working-directory: ${{github.workspace}}/build
run: ctest -C ${{env.BUILD_TYPE}} --output-on-failure
- name: Upload logs on failure
if: failure()
uses: actions/upload-artifact@v6
with:
name: logs-${{ github.job }}-${{ matrix.arch }}
path: |
${{ github.workspace }}/build/Testing/Temporary/LastTest.log
${{ github.workspace }}/build/CMakeFiles/CMakeOutput.log
${{ github.workspace }}/build/CMakeFiles/CMakeError.log
if-no-files-found: ignore
retention-days: ${{ github.event_name == 'pull_request' && 7 || 30 }}
- name: Upload artifact
if: always()
uses: actions/upload-artifact@v6
with:
name: DingusPPC-macOS-${{ matrix.arch }}
path: ${{github.workspace}}/build/bin
retention-days: ${{ github.event_name == 'pull_request' && 7 || 30 }}
build-windows-msys2:
runs-on: windows-latest runs-on: windows-latest
timeout-minutes: 45 strategy:
matrix:
cache-name: [msys64-cache]
env: env:
MSYSTEM: MINGW64 MSYSTEM: MINGW64
FF_SCRIPT_SECTIONS: '0'
CONFIGURE_ARGS: '--target-list=x86_64-softmmu --without-default-devices -Ddebug=false -Doptimization=0'
TEST_ARGS: '--no-suite qtest'
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v5 uses: actions/checkout@v2
with: - name: Set up MSYS2
submodules: recursive run: |
- name: Cache ccache Write-Output "Acquiring msys2.exe installer at $(Get-Date -Format u)"
uses: actions/cache@v5 If ( !(Test-Path -Path msys64\var\cache ) ) {
with: mkdir msys64\var\cache
path: ${{ github.workspace }}/.ccache/msys }
key: windows-msys-ccache-${{ env.BUILD_TYPE }}-${{ hashFiles('**/CMakeLists.txt') }} Invoke-WebRequest "https://repo.msys2.org/distrib/msys2-x86_64-latest.sfx.exe.sig" -outfile "msys2.exe.sig"
restore-keys: windows-msys-ccache-${{ env.BUILD_TYPE }}- if ( Test-Path -Path msys64\var\cache\msys2.exe.sig ) {
- name: Setup MSYS2 Write-Output "Cached installer sig" ;
uses: msys2/setup-msys2@v2 if ( ((Get-FileHash msys2.exe.sig).Hash -ne (Get-FileHash msys64\var\cache\msys2.exe.sig).Hash) ) {
with: Write-Output "Mis-matched installer sig, new installer download required" ;
msystem: MINGW64 Remove-Item -Path msys64\var\cache\msys2.exe.sig ;
update: true if ( Test-Path -Path msys64\var\cache\msys2.exe ) {
install: >- Remove-Item -Path msys64\var\cache\msys2.exe
cmake }
ninja } else {
git Write-Output "Matched installer sig, cached installer still valid"
mingw-w64-x86_64-cmake }
mingw-w64-x86_64-gcc } else {
mingw-w64-x86_64-binutils Write-Output "No cached installer sig, new installer download required" ;
mingw-w64-x86_64-ninja if ( Test-Path -Path msys64\var\cache\msys2.exe ) {
mingw-w64-x86_64-pkgconf Remove-Item -Path msys64\var\cache\msys2.exe
mingw-w64-x86_64-SDL2 }
mingw-w64-x86_64-ccache }
if ( !(Test-Path -Path msys64\var\cache\msys2.exe ) ) {
Write-Output "Fetching latest installer" ;
Invoke-WebRequest "https://repo.msys2.org/distrib/msys2-x86_64-latest.sfx.exe" -outfile "msys64\var\cache\msys2.exe" ;
Copy-Item -Path msys2.exe.sig -Destination msys64\var\cache\msys2.exe.sig
} else {
Write-Output "Using cached installer"
}
Write-Output "Invoking msys2.exe installer at $(Get-Date -Format u)"
msys64\var\cache\msys2.exe -y
((Get-Content -path .\msys64\etc\post-install\07-pacman-key.post -Raw) -replace '--refresh-keys', '--version') | Set-Content -Path .\msys64\etc\post-install\07-pacman-key.post
.\msys64\usr\bin\bash -lc "sed -i 's/^CheckSpace/#CheckSpace/g' /etc/pacman.conf"
.\msys64\usr\bin\bash -lc 'pacman --noconfirm -Syuu' # Core update
.\msys64\usr\bin\bash -lc 'pacman --noconfirm -Syuu' # Normal update
taskkill /F /FI "MODULES eq msys-2.0.dll"
- name: Install dependencies
run: |
Write-Output "Installing mingw packages at $(Get-Date -Format u)"
.\msys64\usr\bin\bash -lc 'pacman -Sy --noconfirm --needed \
bison \
diffutils \
flex \
tar \
doxygen \
cmake \
wget \
git \
grep \
make \
rsync \
ninja \
glib2-devel \
patch \
sed \
mingw-w64-x86_64-cmake \
mingw-w64-x86_64-binutils \
mingw-w64-x86_64-doxygen \
mingw-w64-x86_64-capstone \
mingw-w64-x86_64-ccache \
mingw-w64-x86_64-curl \
mingw-w64-x86_64-cyrus-sasl \
mingw-w64-x86_64-dtc \
mingw-w64-x86_64-gcc \
mingw-w64-x86_64-glib2 \
mingw-w64-x86_64-gnutls \
mingw-w64-x86_64-gtk3 \
mingw-w64-x86_64-libgcrypt \
mingw-w64-x86_64-libjpeg-turbo \
mingw-w64-x86_64-libnfs \
mingw-w64-x86_64-libpng \
mingw-w64-x86_64-libssh \
mingw-w64-x86_64-libtasn1 \
mingw-w64-x86_64-libusb \
mingw-w64-x86_64-lzo2 \
mingw-w64-x86_64-libslirp \
mingw-w64-x86_64-nettle \
mingw-w64-x86_64-clang \
mingw-w64-x86_64-ninja \
mingw-w64-x86_64-pixman \
mingw-w64-x86_64-pkgconf \
mingw-w64-x86_64-python \
mingw-w64-x86_64-SDL2 \
mingw-w64-x86_64-SDL2_image \
mingw-w64-x86_64-snappy \
mingw-w64-x86_64-spice \
mingw-w64-x86_64-usbredir \
mingw-w64-x86_64-zstd \
mingw-w64-x86_64-make'
- name: init_submodules
run: git submodule update --init --recursive
- name: Build - name: Build
shell: msys2 {0}
run: |
echo "Running build at $(date -u +'%Y-%m-%dT%H:%M:%SZ')"
export CHERE_INVOKING=yes
export MSYS=winsymlinks:native
export CCACHE_BASEDIR="${GITHUB_WORKSPACE}"
export CCACHE_DIR="${GITHUB_WORKSPACE}/.ccache/msys"
export CCACHE_DEPEND=1
ccache --zero-stats || true
cmake -S . -B build -GNinja -DCMAKE_BUILD_TYPE=${{ env.BUILD_TYPE }} -DDPPC_68K_DEBUGGER=ON -DDPPC_BUILD_PPC_TESTS=ON -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache
cmake --build build --config ${{ env.BUILD_TYPE }} --parallel
ccache --show-stats || true
echo "Finished build at $(date -u +'%Y-%m-%dT%H:%M:%SZ')"
- name: Test
shell: msys2 {0}
run: | run: |
Write-Output "Running build at $(Get-Date -Format u)"
$env:CHERE_INVOKING = 'yes' # Preserve the current working directory
$env:MSYS = 'winsymlinks:native' # Enable native Windows symlink
$env:CCACHE_BASEDIR = "$env:CI_PROJECT_DIR"
$env:CCACHE_DIR = "$env:CCACHE_BASEDIR/ccache"
$env:CCACHE_MAXSIZE = "500M"
$env:CCACHE_DEPEND = 1 # cache misses are too expensive with preprocessor mode
$env:CC = "ccache gcc"
mkdir build
cd build cd build
ctest --output-on-failure --parallel D:\a\dingusppc\dingusppc\msys64\usr\bin\bash -lc "ccache --zero-stats"
- name: Upload logs on failure D:\a\dingusppc\dingusppc\msys64\usr\bin\bash -lc "cmake -DCMAKE_BUILD_TYPE=Release -DPPC_BUILD_PPC_TESTS=True .. && ninja"
if: failure() D:\a\dingusppc\dingusppc\msys64\usr\bin\bash -lc "ccache --show-stats"
uses: actions/upload-artifact@v6 Write-Output "Finished build at $(Get-Date -Format u)"
with:
name: logs-${{ github.job }}
path: |
${{ github.workspace }}/build/Testing/Temporary/LastTest.log
${{ github.workspace }}/build/CMakeFiles/CMakeOutput.log
${{ github.workspace }}/build/CMakeFiles/CMakeError.log
if-no-files-found: ignore
retention-days: ${{ github.event_name == 'pull_request' && 7 || 30 }}
- name: Upload artifact
if: always()
uses: actions/upload-artifact@v6
with:
name: DingusPPC-MSYS
path: ${{github.workspace}}/build/bin
retention-days: ${{ github.event_name == 'pull_request' && 7 || 30 }}
build-windows-vsbuild:
vsbuild-CLANG:
runs-on: windows-latest runs-on: windows-latest
timeout-minutes: 45
env:
VCPKG_FEATURE_FLAGS: binarycaching
strategy:
fail-fast: false
matrix:
include:
- name: clang
generator: Ninja
cmake_args: -DCMAKE_C_COMPILER=clang-cl -DCMAKE_CXX_COMPILER=clang-cl
ccache_args: -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache
upload_suffix: CLANG
- name: msvc
generator: Ninja
cmake_args: ""
ccache_args: -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache
upload_suffix: MSVC
- name: msbuild
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: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@v3
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 - name: Setup msbuild
uses: microsoft/setup-msbuild@v3 if: inputs.configuration != 'CMake'
- name: Install vcpkg packages uses: microsoft/setup-msbuild@v1
shell: cmd - name: Setup VCPKG
run: '"%VCPKG_INSTALLATION_ROOT%\vcpkg.exe" install --triplet x64-windows'
- name: Install Ninja
if: matrix.generator == 'Ninja'
run: choco install ninja -y
- name: Cache ccache
if: matrix.generator == 'Ninja'
uses: actions/cache@v5
with:
path: ${{ github.workspace }}/.ccache/vsbuild-${{ matrix.name }}
key: vsbuild-${{ matrix.name }}-ccache-${{ env.BUILD_TYPE }}-${{ hashFiles('**/CMakeLists.txt') }}
restore-keys: vsbuild-${{ matrix.name }}-ccache-${{ env.BUILD_TYPE }}-
- name: Install ccache
if: matrix.generator == 'Ninja'
run: choco install ccache -y
- name: Configure & Build
shell: cmd
env:
CCACHE_DIR: ${{ github.workspace }}/.ccache/vsbuild-${{ matrix.name }}
CCACHE_BASEDIR: ${{ github.workspace }}
run: | run: |
mkdir build vcpkg integrate install
call "%ProgramFiles%\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvars64.bat" vcpkg install pthread:x64-windows
cd build vcpkg install pthreads:x64-windows
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 vcpkg install pthread-stubs:x64-windows
cmake --build . --config ${{ env.BUILD_TYPE }} --parallel vcpkg install pthreadpool:x64-windows
cd .. vcpkg install
- name: ccache stats - name: init_submodules
if: matrix.generator == 'Ninja' run: git submodule update --init --recursive
- name: Build
shell: cmd shell: cmd
run: | run: |
ccache --show-stats mkdir build
if %errorlevel% neq 0 echo ccache stats unavailable cd build
- name: Test call "%ProgramFiles%\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvars64.bat"
working-directory: ${{github.workspace}}/build cmake -G "NMake Makefiles" -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=clang-cl -DCMAKE_CXX_COMPILER=clang-cl -DPPC_BUILD_PPC_TESTS=True -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows ..
shell: cmd nmake
run: ctest -C ${{env.BUILD_TYPE}} --output-on-failure
- name: Upload logs on failure
if: failure()
uses: actions/upload-artifact@v6
with:
name: logs-${{ github.job }}-${{ matrix.name }}
path: |
${{ github.workspace }}/build/Testing/Temporary/LastTest.log
${{ github.workspace }}/build/CMakeFiles/CMakeOutput.log
${{ github.workspace }}/build/CMakeFiles/CMakeError.log
if-no-files-found: ignore
retention-days: ${{ github.event_name == 'pull_request' && 7 || 30 }}
- name: Upload artifact - name: Upload artifact
if: always() if: always()
uses: actions/upload-artifact@v6 uses: actions/upload-artifact@v4
with: with:
name: DingusPPC-${{ matrix.upload_suffix }} name: DingusPPC-CLANG
path: ${{github.workspace}}/build/bin
vsbuild-MSVC:
runs-on: windows-latest
steps:
- uses: actions/checkout@v3
- name: Setup msbuild
if: inputs.configuration != 'CMake'
uses: microsoft/setup-msbuild@v1
- name: Setup VCPKG
run: |
vcpkg integrate install
vcpkg install pthread:x64-windows
vcpkg install pthreads:x64-windows
vcpkg install pthread-stubs:x64-windows
vcpkg install pthreadpool:x64-windows
vcpkg install
- name: init_submodules
run: git submodule update --init --recursive
- name: Build
shell: cmd
run: |
mkdir build
cd build
call "%ProgramFiles%\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvars64.bat"
cmake -G "NMake Makefiles" -DCMAKE_BUILD_TYPE=Release -DPPC_BUILD_PPC_TESTS=True -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows ..
nmake
- name: Upload artifact
if: always()
uses: actions/upload-artifact@v4
with:
name: DingusPPC-MSVC
path: ${{github.workspace}}/build/bin
vsbuild-MSVC-MSBUILD:
runs-on: windows-latest
steps:
- uses: actions/checkout@v3
- name: Setup msbuild
if: inputs.configuration != 'CMake'
uses: microsoft/setup-msbuild@v1
- name: Setup VCPKG
run: |
vcpkg integrate install
vcpkg install pthread:x64-windows
vcpkg install pthreads:x64-windows
vcpkg install pthread-stubs:x64-windows
vcpkg install pthreadpool:x64-windows
vcpkg install
- name: init_submodules
run: git submodule update --init --recursive
- name: Build
shell: cmd
run: |
mkdir build
cd build
call "%ProgramFiles%\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvars64.bat"
cmake -G "Visual Studio 17 2022" -DCMAKE_BUILD_TYPE=Release -DPPC_BUILD_PPC_TESTS=True -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows ..
msbuild dingusppc.sln
- name: Upload artifact
if: always()
uses: actions/upload-artifact@v4
with:
name: DingusPPC-MSBUILD
path: ${{github.workspace}}/build/bin path: ${{github.workspace}}/build/bin
retention-days: ${{ github.event_name == 'pull_request' && 7 || 30 }}
-1
View File
@@ -41,7 +41,6 @@ ehthumbs.db
# IDE ignores # IDE ignores
build build
build*/
build-* build-*
*.dir *.dir
*.user *.user
+6 -94
View File
@@ -84,19 +84,6 @@ if (DPPC_68K_DEBUGGER)
add_subdirectory(thirdparty/capstone EXCLUDE_FROM_ALL) add_subdirectory(thirdparty/capstone EXCLUDE_FROM_ALL)
endif() 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}/core")
add_subdirectory("${PROJECT_SOURCE_DIR}/cpu/ppc/") add_subdirectory("${PROJECT_SOURCE_DIR}/cpu/ppc/")
add_subdirectory("${PROJECT_SOURCE_DIR}/debugger/") add_subdirectory("${PROJECT_SOURCE_DIR}/debugger/")
@@ -110,21 +97,6 @@ if (NOT EMSCRIPTEN)
set(BUILD_SHARED_LIBS OFF CACHE BOOL "Build shared libraries") set(BUILD_SHARED_LIBS OFF CACHE BOOL "Build shared libraries")
set(BUILD_TOOLS OFF CACHE BOOL "Build Cubeb tools") set(BUILD_TOOLS OFF CACHE BOOL "Build Cubeb tools")
add_subdirectory(thirdparty/cubeb EXCLUDE_FROM_ALL) add_subdirectory(thirdparty/cubeb EXCLUDE_FROM_ALL)
# Warn if no audio backends were detected on Linux/Unix systems
if (UNIX AND NOT APPLE)
if (NOT USE_PULSE AND NOT USE_ALSA AND NOT USE_JACK AND
NOT USE_SNDIO AND NOT USE_OSS AND NOT USE_SUN)
message(WARNING
"No Cubeb audio backends detected on Linux/Unix system!\n"
"Audio will NOT work at runtime.\n"
"Please install development headers for at least one of:\n"
" - PulseAudio (libpulse-dev / pulseaudio-libs-devel)\n"
" - ALSA (libasound2-dev / alsa-lib-devel)\n"
" - JACK (libjack-dev / jack-audio-connection-kit-devel)\n"
" - sndio (libsndio-dev)")
endif()
endif()
endif() endif()
set(CLI11_ROOT ${PROJECT_SOURCE_DIR}/thirdparty/CLI11) set(CLI11_ROOT ${PROJECT_SOURCE_DIR}/thirdparty/CLI11)
@@ -151,16 +123,6 @@ endif()
file(GLOB TEST_SOURCES "${PROJECT_SOURCE_DIR}/cpu/ppc/test/*.cpp") file(GLOB TEST_SOURCES "${PROJECT_SOURCE_DIR}/cpu/ppc/test/*.cpp")
if (APPLE)
add_executable(dingusppc MACOSX_BUNDLE ${SOURCES}
$<TARGET_OBJECTS:core>
$<TARGET_OBJECTS:cpu_ppc>
$<TARGET_OBJECTS:debugger>
$<TARGET_OBJECTS:devices>
$<TARGET_OBJECTS:machines>
$<TARGET_OBJECTS:utils>
$<TARGET_OBJECTS:loguru>)
else()
add_executable(dingusppc ${SOURCES} $<TARGET_OBJECTS:core> add_executable(dingusppc ${SOURCES} $<TARGET_OBJECTS:core>
$<TARGET_OBJECTS:cpu_ppc> $<TARGET_OBJECTS:cpu_ppc>
$<TARGET_OBJECTS:debugger> $<TARGET_OBJECTS:debugger>
@@ -168,55 +130,9 @@ add_executable(dingusppc ${SOURCES} $<TARGET_OBJECTS:core>
$<TARGET_OBJECTS:machines> $<TARGET_OBJECTS:machines>
$<TARGET_OBJECTS:utils> $<TARGET_OBJECTS:utils>
$<TARGET_OBJECTS:loguru>) $<TARGET_OBJECTS:loguru>)
endif()
if (APPLE)
# Identify if we are targeting iOS or macOS
if (IOS)
set(BUNDLE_ID "com.dingusdev.dingusppc-ios")
message(STATUS "Configuring for iOS Bundle")
else()
set(BUNDLE_ID "com.dingusdev.dingusppc")
message(STATUS "Configuring for macOS Bundle")
endif()
set_target_properties(dingusppc PROPERTIES
MACOSX_BUNDLE_GUI_IDENTIFIER "${BUNDLE_ID}"
MACOSX_BUNDLE_BUNDLE_NAME "DingusPPC"
MACOSX_BUNDLE_BUNDLE_VERSION "alpha 1.0.4c"
MACOSX_BUNDLE_SHORT_VERSION_STRING "a1.0.4c"
MACOSX_BUNDLE_EXECUTABLE_NAME "DingusPPC"
# Placeholder for the icon file:
# MACOSX_BUNDLE_ICON_FILE "icon.icns"
)
if (NOT IOS)
set_target_properties(dingusppc PROPERTIES
MACOSX_BUNDLE_INFO_PLIST "${PROJECT_SOURCE_DIR}/cmake/DingusPPCInfo.plist.in"
XCODE_ATTRIBUTE_PRODUCT_BUNDLE_IDENTIFIER "${BUNDLE_ID}"
)
endif()
find_library(COCOA_LIBRARY Cocoa)
find_library(IOKIT_LIBRARY IOKit)
find_library(COREAUDIO_LIBRARY CoreAudio)
find_library(AUDIOTOOLBOX_LIBRARY AudioToolbox)
target_link_libraries(dingusppc PRIVATE
${COCOA_LIBRARY}
${IOKIT_LIBRARY}
${COREAUDIO_LIBRARY}
${AUDIOTOOLBOX_LIBRARY}
)
if (IOS)
target_link_libraries(dingusppc PRIVATE "-framework Foundation" "-framework UIKit")
endif()
endif()
if (WIN32) if (WIN32)
target_link_libraries(dingusppc PRIVATE SDL2::SDL2 cubeb) target_link_libraries(dingusppc PRIVATE SDL2::SDL2 SDL2::SDL2main cubeb)
target_compile_definitions(dingusppc PRIVATE SDL_MAIN_HANDLED)
elseif (EMSCRIPTEN) elseif (EMSCRIPTEN)
target_link_libraries(dingusppc PRIVATE target_link_libraries(dingusppc PRIVATE
${CMAKE_DL_LIBS} ${CMAKE_THREAD_LIBS_INIT} ${CMAKE_DL_LIBS} ${CMAKE_THREAD_LIBS_INIT}
@@ -228,7 +144,7 @@ elseif (EMSCRIPTEN)
"-s EXPORT_NAME=emulator" "-s EXPORT_NAME=emulator"
"-s 'EXTRA_EXPORTED_RUNTIME_METHODS=[\"FS\"]'") "-s 'EXTRA_EXPORTED_RUNTIME_METHODS=[\"FS\"]'")
else() else()
target_link_libraries(dingusppc PRIVATE SDL2::SDL2main SDL2::SDL2 cubeb target_link_libraries(dingusppc PRIVATE SDL2::SDL2 SDL2::SDL2main cubeb
${CMAKE_DL_LIBS} ${CMAKE_THREAD_LIBS_INIT}) ${CMAKE_DL_LIBS} ${CMAKE_THREAD_LIBS_INIT})
endif() endif()
@@ -252,10 +168,9 @@ if (DPPC_BUILD_PPC_TESTS)
$<TARGET_OBJECTS:loguru>) $<TARGET_OBJECTS:loguru>)
if (WIN32) if (WIN32)
target_link_libraries(testppc PRIVATE SDL2::SDL2 cubeb) target_link_libraries(testppc PRIVATE SDL2::SDL2 SDL2::SDL2main cubeb)
target_compile_definitions(testppc PRIVATE SDL_MAIN_HANDLED)
else() else()
target_link_libraries(testppc PRIVATE SDL2::SDL2main SDL2::SDL2 cubeb target_link_libraries(testppc PRIVATE SDL2::SDL2 SDL2::SDL2main cubeb
${CMAKE_DL_LIBS} ${CMAKE_THREAD_LIBS_INIT}) ${CMAKE_DL_LIBS} ${CMAKE_THREAD_LIBS_INIT})
endif() endif()
@@ -278,11 +193,8 @@ if (DPPC_BUILD_BENCHMARKS)
$<TARGET_OBJECTS:utils> $<TARGET_OBJECTS:utils>
$<TARGET_OBJECTS:loguru>) $<TARGET_OBJECTS:loguru>)
target_link_libraries(bench1 PRIVATE cubeb SDL2::SDL2 ${CMAKE_DL_LIBS} target_link_libraries(bench1 PRIVATE cubeb SDL2::SDL2 SDL2::SDL2main ${CMAKE_DL_LIBS}
${CMAKE_THREAD_LIBS_INIT}) ${CMAKE_THREAD_LIBS_INIT})
if (WIN32)
target_compile_definitions(bench1 PRIVATE SDL_MAIN_HANDLED)
endif()
if (DPPC_68K_DEBUGGER) if (DPPC_68K_DEBUGGER)
target_link_libraries(bench1 PRIVATE capstone) target_link_libraries(bench1 PRIVATE capstone)
@@ -296,7 +208,7 @@ if (DPPC_BUILD_PPC_TESTS)
"${PROJECT_SOURCE_DIR}/cpu/ppc/test/ppcinttests.csv" "${PROJECT_SOURCE_DIR}/cpu/ppc/test/ppcinttests.csv"
"${PROJECT_SOURCE_DIR}/cpu/ppc/test/ppcfloattests.csv" "${PROJECT_SOURCE_DIR}/cpu/ppc/test/ppcfloattests.csv"
"${PROJECT_SOURCE_DIR}/cpu/ppc/test/ppcdisasmtest.csv" "${PROJECT_SOURCE_DIR}/cpu/ppc/test/ppcdisasmtest.csv"
"$<TARGET_FILE_DIR:$<TARGET_PROPERTY:NAME>>") $<TARGET_FILE_DIR:${PROJECT_NAME}>)
endif() endif()
install (TARGETS dingusppc DESTINATION ${PROJECT_SOURCE_DIR}/build) install (TARGETS dingusppc DESTINATION ${PROJECT_SOURCE_DIR}/build)
-1
View File
@@ -4,7 +4,6 @@ General
* Test your contributions to assure they do not break existing functionality. * 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. * Commits to the repo should be done by portions; that is, by individual functionalities of the program.
* Don't use any disrespectful language. * 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 Code
======= =======
+8 -31
View File
@@ -4,14 +4,10 @@
## Developers ## Developers
- divingkatae - divingkatae
- joevt
- kkaisershot
- maximumspatium - maximumspatium
- joevt
- mihaip - mihaip
- kkaisershot
## ATI Rage Support (WIP)
- Cacodemon345
## NT4/PPC fork ## NT4/PPC fork
@@ -19,37 +15,19 @@
## DevOps ## DevOps
- alicela1n
- calmsacibis995
- claunia
- dressupgeekout
- dyharlan
- erichelgeson
- jarz
- kth5
- leap0x7b
- lefp
- mathstuf
- mrpapersonic
- probonopd
- Randrianasulu
- roytam1
- sdkmap
- seanm
- Waqar144 - Waqar144
- webspacecreations - webspacecreations
- leap0x7b
- sdkmap
- dressupgeekout
- kth5
- dyharlan
- roytam1
## Testing ## Testing
- LagLifeYT - LagLifeYT
## 3rd Party Libraries
- [Capstone](https://github.com/capstone-engine/capstone)
- [CLI11](https://github.com/CLIUtils/CLI11)
- [Loguru](https://github.com/emilk/loguru)
- [SDL 2](https://github.com/libsdl-org/SDL)
## Thanks ## Thanks
- 68kmla - 68kmla
@@ -59,7 +37,6 @@
- Blitter.net - Blitter.net
- Emaculation - Emaculation
- GitHub - GitHub
- pagetable.com
- PenguinPPC - PenguinPPC
- VirtuallyFun - VirtuallyFun
- The makers of Loguru, SDL2, Capstone, and CLI11 - The makers of Loguru, SDL2, Capstone, and CLI11
+22 -53
View File
@@ -1,38 +1,30 @@
# DingusPPC # DingusPPC
Written by The DingusPPC Development Team Written by divingkatae and maximumspatium
(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. Be warned the program is highly unfinished and could use a lot of testing. Any feedback is welcome.
## Philosophy of Use ## Philosophy of Use
While many other PowerPC emus exist (PearPC, Sheepshaver), none of them currently attempt emulation of PowerPC Macs While many other PowerPC emus exist (PearPC, Sheepshaver), none of them currently attempt emulation of PowerPC Macs accurately (except for QEMU).
accurately (except for QEMU).
This program aims to not only improve upon what Sheepshaver, PearPC, and other PowerPC Mac emulators have done, but This program aims to not only improve upon what Sheepshaver, PearPC, and other PowerPC Mac emulators have done, but also to provide a better debugging environment. This currently is designed to work best with PowerPC Old World ROMs, including those of the Power Mac 6100, 7200, and G3 Beige.
also to provide a better debugging environment. This currently is designed to work best with PowerPC NuBus and Old
World ROMs, including those of the Power Mac 6100, 7200, and G3 Beige.
## Implemented Features ## Implemented Features
Several machines have been implemented to varying degrees, like many Old World PowerPC Macs, early New World This emulator has a debugging environment, complete with a disassembler. We also have implemented enough to allow Open Firmware to boot, going so far as to allow audio playback of the boot-up jingles.
PowerPC Macs, and the Pippin.
This emulator has a debugging environment, complete with a disassembler.
## How to Use ## How to Use
This program currently uses the command prompt to work. This program currently uses the command prompt to work.
There are a few command line arguments one can enter when starting the program. There are a few command line arguments one must enter when starting the program.
``` ```
-r, --run -r, --realtime
``` ```
Run the emulator. Currently only goes to an interpreter. Run the emulator in runtime.
``` ```
-d, --debugger -d, --debugger
@@ -44,34 +36,23 @@ Enter the interactive debugger.
-b, --bootrom TEXT:FILE -b, --bootrom TEXT:FILE
``` ```
Specifies the Boot ROM path. It otherwise looks for bootrom.bin. Specifies the Boot ROM path (optional; looks for bootrom.bin by default)
``` ```
-m, --machine TEXT -m, --machine TEXT
``` ```
Specify machine ID. Otherwise, the emulator will attempt to determine machine ID from the boot rom otherwise. Specify machine ID (optional; will attempt to determine machine ID from the boot rom otherwise)
As of now, the most complete machines are the Power Mac 6100, the Power Mac 7500, and the Power Mac G3 Beige. As of now, the most complete machines are the Power Mac 6100 (SCSI emulation in progress) and the Power Mac G3 Beige (SCSI + ATA emulation in progress, No ATI Rage acceleration).
To go into to the debugger regardless of how you started the emulator, press Control and C on the terminal window.
## How to Compile ## How to Compile
You need to install development tools first. You need to install development tools first.
At minimum, a C++20 compliant compiler and [CMake](https://cmake.org) are required. At least, a C++20 compliant compiler and [CMake](https://cmake.org) are required.
Clone the repository using the appropriate command:
```
git clone https://github.com/dingusdev/dingusppc
```
If this is from a mirror, replace the argument with the source you want to use instead.
You will also have to recursive clone or run You will also have to recursive clone or run
``` ```
git submodule update --init --recursive git submodule update --init --recursive
``` ```
@@ -84,43 +65,27 @@ For SDL2, Linux users may also have to run:
sudo apt install libsdl2-dev sudo apt install libsdl2-dev
``` ```
macOS users can use Homebrew or MacPorts to install SDL2. CLI11 and loguru are already included in the thirdparty folder and compiled along with the rest of DingusPPC.
CLI11 and loguru are already included in the thirdparty folder and compiled along with the rest of DingusPPC.
For Raspbian, you may also need the following command:
```
sudo apt install doxygen graphviz
```
To build the project in a Unix-like environment, create a build folder, change the directory to the build folder,
and use `cmake` to create the `Makefile` files in that build folder.
Use `make` to do the building. You don't need to execute `cmake` again unless you add/remove/change options or
source files.
For example, to build the project in a Unix-like environment, you will need to run
the following commands in the OS terminal:
``` ```
mkdir build mkdir build
cd build cd build
cmake -DCMAKE_BUILD_TYPE=Release .. cmake -DCMAKE_BUILD_TYPE=Release ..
make make dingusppc
``` ```
You may specify another build type using the variable CMAKE_BUILD_TYPE.
You may specify another build type using the variable `CMAKE_BUILD_TYPE`. For Raspbian, you may also need the following command:
Each build type should have its own build folder.
``` ```
mkdir build-debug sudo apt install doxygen graphviz
cd build-debug
cmake -DCMAKE_BUILD_TYPE=Debug ..
make
``` ```
## Testing ## Testing
DingusPPC includes a test suite for verifying the correctness of its PowerPC CPU DingusPPC includes a test suite for verifying the correctness of its PowerPC CPU
emulation. To build the tests, use the following terminal commands: emulation. To build the tests, use the following terminal commands:
``` ```
mkdir build mkdir build
cd build cd build
@@ -135,3 +100,7 @@ make testppc
- 2 GB of RAM - 2 GB of RAM
- 2 GB of Hard Disk Space - 2 GB of Hard Disk Space
- Graphics Card with a minimum resolution of 800*600 - Graphics Card with a minimum resolution of 800*600
## Compiler Requirements
- Any C++20 compatible compiler
+8 -54
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -28,8 +28,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <debugger/debugger.h> #include <debugger/debugger.h>
#if defined(PPC_BENCHMARKS) #if defined(PPC_BENCHMARKS)
void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) { uint32_t ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits, uint32_t exec_flags) {
power_off(po_benchmark_exception); power_on = false;
power_off_reason = po_benchmark_exception;
return 0;
} }
#endif #endif
@@ -104,7 +106,7 @@ int main(int argc, char** argv) {
ppc_state.gpr[3] = 0x1000; // buf ppc_state.gpr[3] = 0x1000; // buf
ppc_state.gpr[4] = test_size; // len ppc_state.gpr[4] = test_size; // len
ppc_state.gpr[5] = 0; // sum ppc_state.gpr[5] = 0; // sum
enter_debugger(); DppcDebugger::get_instance()->enter_debugger();
#endif #endif
ppc_state.pc = 0; ppc_state.pc = 0;
@@ -114,54 +116,6 @@ int main(int argc, char** argv) {
power_on = true; power_on = true;
ppc_exec_until(0xC4); 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]); LOG_F(INFO, "Checksum: 0x%08X", ppc_state.gpr[3]);
uint32_t checksum = ppc_state.gpr[3]; uint32_t checksum = ppc_state.gpr[3];
-70
View File
@@ -1,70 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key>
<string>CD-ROM image</string>
<key>CFBundleTypeRole</key>
<string>Viewer</string>
<key>LSHandlerRank</key>
<string>Alternate</string>
<key>LSItemContentTypes</key>
<array>
<string>public.iso-image</string>
<string>com.roxio.disk-image-toast</string>
</array>
</dict>
</array>
<key>CFBundleExecutable</key>
<string>${MACOSX_BUNDLE_EXECUTABLE_NAME}</string>
<key>CFBundleGetInfoString</key>
<string>${MACOSX_BUNDLE_INFO_STRING}</string>
<key>CFBundleIconFile</key>
<string>${MACOSX_BUNDLE_ICON_FILE}</string>
<key>CFBundleIdentifier</key>
<string>${MACOSX_BUNDLE_GUI_IDENTIFIER}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleLongVersionString</key>
<string>${MACOSX_BUNDLE_LONG_VERSION_STRING}</string>
<key>CFBundleName</key>
<string>${MACOSX_BUNDLE_BUNDLE_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>${MACOSX_BUNDLE_SHORT_VERSION_STRING}</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>${MACOSX_BUNDLE_BUNDLE_VERSION}</string>
<key>CSResourcesFileMapped</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>${MACOSX_BUNDLE_COPYRIGHT}</string>
<key>UTImportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>public.disk-image</string>
</array>
<key>UTTypeDescription</key>
<string>Toast disk image</string>
<key>UTTypeIdentifier</key>
<string>com.roxio.disk-image-toast</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>toast</string>
</array>
</dict>
</dict>
</array>
</dict>
</plist>
+6 -10
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -44,20 +44,16 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
// cyclic rotation idioms that modern compilers will // cyclic rotation idioms that modern compilers will
// recognize and generate very compact code for // recognize and generate very compact code for
// involving specific machine instructions // evolving specific machine instructions
inline unsigned ROTL_32(unsigned x, unsigned n) { inline unsigned ROTL_32(unsigned x, unsigned n) {
n &= 0x1F; n &= 0x1F;
if (n) return (x << n) | (x >> (32 - n));
return (x << n) | (x >> (32 - n));
return x;
} }
inline unsigned ROTR_32(unsigned x, unsigned n) { inline unsigned ROTR_32(unsigned x, unsigned n) {
n &= 0x1F; n &= 0x1F;
if (n) return (x >> n) | (x << (32 - n));
return (x >> n) | (x << (32 - n));
return x;
} }
#endif #endif
+5 -5
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -52,7 +52,7 @@ public:
} }
// Calls all connected slots. // Calls all connected slots.
void emit(Args... args) const { void emit(Args... args) {
if (!_is_enabled) { if (!_is_enabled) {
return; return;
} }
@@ -77,7 +77,7 @@ public:
_is_enabled = true; _is_enabled = true;
} }
bool is_enabled() const { bool is_enabled() {
return _is_enabled; return _is_enabled;
} }
-103
View File
@@ -1,103 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team
(See CREDITS.MD for more details)
(You may also contact divingkxt or powermax2286 on Discord)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file Macros for performing byte swapping for quick endian conversion.
It will try to use the fast built-in machine instructions first
and fall back to the slow conversion if none were found.
*/
#ifndef ENDIAN_SWAP_H
#define ENDIAN_SWAP_H
#ifdef __GNUG__ /* GCC, ICC and Clang */
# define BYTESWAP_16(x) (__builtin_bswap16 (x))
# define BYTESWAP_32(x) (__builtin_bswap32 (x))
# define BYTESWAP_64(x) (__builtin_bswap64 (x))
#elif _MSC_VER /* MSVC */
# include <stdlib.h>
# define BYTESWAP_16(x) (_byteswap_ushort (x))
# define BYTESWAP_32(x) (_byteswap_ulong (x))
# define BYTESWAP_64(x) (_byteswap_uint64 (x))
#elif __has_include(<byteswap.h>) /* Many unixes */
# include <byteswap.h>
# define BYTESWAP_16(x) (bswap_16(x))
# define BYTESWAP_32(x) (bswap_32(x))
# define BYTESWAP_64(x) (bswap_64(x))
// TODO: C++23 has std::byteswap
#else
// #warning is not standard until C++23:
//
// # warning "Unknown byte swapping built-ins (do it the slow way)!"
# include <cstdint>
// Most optimizing compilers will translate these functions directly
// into their native instructions (e.g. bswap on x86).
inline std::uint16_t byteswap_16_impl(std::uint16_t x)
{
return (x >> 8) | (x << 8);
}
inline std::uint32_t byteswap_32_impl(std::uint32_t x)
{
return (
((x & UINT32_C(0x000000FF)) << 24)
| ((x & UINT32_C(0x0000FF00)) << 8)
| ((x & UINT32_C(0x00FF0000)) >> 8)
| ((x & UINT32_C(0xFF000000)) >> 24)
);
}
inline std::uint64_t byteswap_64_impl(std::uint64_t x)
{
return (
((x & UINT64_C(0x00000000000000FF)) << 56)
| ((x & UINT64_C(0x000000000000FF00)) << 40)
| ((x & UINT64_C(0x0000000000FF0000)) << 24)
| ((x & UINT64_C(0x00000000FF000000)) << 8)
| ((x & UINT64_C(0x000000FF00000000)) >> 8)
| ((x & UINT64_C(0x0000FF0000000000)) >> 24)
| ((x & UINT64_C(0x00FF000000000000)) >> 40)
| ((x & UINT64_C(0xFF00000000000000)) >> 56)
);
}
# define BYTESWAP_16(x) (byteswap_16_impl(x))
# define BYTESWAP_32(x) (byteswap_32_impl(x))
# define BYTESWAP_64(x) (byteswap_64_impl(x))
#endif
#define BYTESWAP_SIZED(val, size) \
((size) == 2 ? BYTESWAP_16(val) : (size) == 4 ? BYTESWAP_32(val) : (val))
#endif /* ENDIAN_SWAP_H */
+11 -57
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -25,7 +25,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <core/coresignal.h> #include <core/coresignal.h>
#include <cinttypes> #include <cinttypes>
#include <string>
class WindowEvent { class WindowEvent {
public: public:
@@ -37,15 +36,9 @@ public:
}; };
enum : uint16_t { enum : uint16_t {
// Standard SDL window event types are uint8_t's. // Standard SDL window event types are uint8_t's, we add our own custom
// We add our own custom events after that. // events after that.
DPPC_WINDOWEVENT_WINDOW_SCALE_QUALITY_TOGGLE = 1 << 8, WINDOW_SCALE_QUALITY_TOGGLE = 1 << 8,
DPPC_WINDOWEVENT_MOUSE_GRAB_TOGGLE,
DPPC_WINDOWEVENT_MOUSE_GRAB_CHANGED,
DPPC_WINDOWEVENT_WINDOW_FULL_SCREEN_TOGGLE,
DPPC_WINDOWEVENT_WINDOW_FULL_SCREEN_TOGGLE_REVERSE,
DPPC_WINDOWEVENT_WINDOW_BIGGER,
DPPC_WINDOWEVENT_WINDOW_SMALLER,
}; };
enum : uint32_t { enum : uint32_t {
@@ -63,8 +56,8 @@ public:
~MouseEvent() = default; ~MouseEvent() = default;
uint32_t flags; uint32_t flags;
int32_t xrel; uint32_t xrel;
int32_t yrel; uint32_t yrel;
uint32_t xabs; uint32_t xabs;
uint32_t yabs; uint32_t yabs;
uint8_t buttons_state; uint8_t buttons_state;
@@ -77,17 +70,7 @@ public:
uint32_t flags; uint32_t flags;
uint32_t key; uint32_t key;
}; uint16_t keys_state;
enum KeyboardLocale : uint32_t {
Eng_USA = 0,
Eng_GBR = 1,
Fra_FRA = 10,
Deu_DEU = 20,
Ita_ITA = 30,
Spa_ESP = 40,
Jpn_JPN = 80,
}; };
/* AppleJack bits 3-7 are supported but unused */ /* AppleJack bits 3-7 are supported but unused */
@@ -120,20 +103,6 @@ public:
uint8_t button; uint8_t button;
}; };
enum class CdromInsertionResult {
SUCCESS,
NO_DRIVE,
MEDIA_PRESENT,
IMAGE_OPEN_FAILED,
};
class CdromImageEvent {
public:
std::string image_path;
CdromInsertionResult result = CdromInsertionResult::NO_DRIVE;
bool handled = false;
};
class EventManager { class EventManager {
public: public:
static EventManager* get_instance() { static EventManager* get_instance() {
@@ -141,14 +110,9 @@ public:
event_manager = new EventManager(); event_manager = new EventManager();
} }
return event_manager; return event_manager;
} };
void poll_events(); void poll_events();
void set_keyboard_locale(uint32_t keyboard_id);
void post_keyboard_state_events();
void post_cdrom_event(CdromImageEvent& event) {
_cdrom_signal.emit(event);
}
template <typename T> template <typename T>
void add_window_handler(T *inst, void (T::*func)(const WindowEvent&)) { void add_window_handler(T *inst, void (T::*func)(const WindowEvent&)) {
@@ -170,11 +134,6 @@ public:
_gamepad_signal.connect_method(inst, func); _gamepad_signal.connect_method(inst, func);
} }
template <typename T>
void add_cdrom_handler(T* inst, void (T::*func)(CdromImageEvent&)) {
_cdrom_signal.connect_method(inst, func);
}
template <typename T> template <typename T>
void add_post_handler(T *inst, void (T::*func)()) { void add_post_handler(T *inst, void (T::*func)()) {
_post_signal.connect_method(inst, func); _post_signal.connect_method(inst, func);
@@ -184,26 +143,22 @@ public:
_window_signal.disconnect_all(); _window_signal.disconnect_all();
_mouse_signal.disconnect_all(); _mouse_signal.disconnect_all();
_keyboard_signal.disconnect_all(); _keyboard_signal.disconnect_all();
_gamepad_signal.disconnect_all();
_cdrom_signal.disconnect_all();
_post_signal.disconnect_all(); _post_signal.disconnect_all();
} }
void disable_input_handlers() { void disable_input_handlers() {
_mouse_signal.disable(); _mouse_signal.disable();
_keyboard_signal.disable(); _keyboard_signal.disable();
_gamepad_signal.disable();
} }
private: private:
static EventManager* event_manager; static EventManager* event_manager;
EventManager() {} // private constructor to implement a singleton EventManager() {}; // private constructor to implement a singleton
CoreSignal<const WindowEvent&> _window_signal; CoreSignal<const WindowEvent&> _window_signal;
CoreSignal<const MouseEvent&> _mouse_signal; CoreSignal<const MouseEvent&> _mouse_signal;
CoreSignal<const KeyboardEvent&> _keyboard_signal; CoreSignal<const KeyboardEvent&> _keyboard_signal;
CoreSignal<const GamepadEvent&> _gamepad_signal; CoreSignal<const GamepadEvent&> _gamepad_signal;
CoreSignal<CdromImageEvent&> _cdrom_signal;
CoreSignal<> _post_signal; CoreSignal<> _post_signal;
uint64_t events_captured = 0; uint64_t events_captured = 0;
@@ -211,7 +166,6 @@ private:
uint64_t key_downs = 0; uint64_t key_downs = 0;
uint64_t key_ups = 0; uint64_t key_ups = 0;
uint8_t buttons_state = 0; uint8_t buttons_state = 0;
uint32_t kbd_locale = 0;
}; };
#endif // EVENT_MANAGER_H #endif // EVENT_MANAGER_H
+63 -290
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -28,29 +28,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
EventManager* EventManager::event_manager; EventManager* EventManager::event_manager;
static int get_sdl_event_key_code(const SDL_KeyboardEvent& event, uint32_t kbd_locale); static int get_sdl_event_key_code(const SDL_KeyboardEvent &event);
static void toggle_mouse_grab(const SDL_KeyboardEvent &event);
constexpr int KMOD_ALL = KMOD_LSHIFT | KMOD_RSHIFT | KMOD_LCTRL | KMOD_RCTRL | KMOD_LALT | KMOD_RALT | KMOD_LGUI | KMOD_RGUI; void EventManager::poll_events()
bool g_swap_command_option = false;
static AdbKey swap_command_option(AdbKey key)
{ {
if (!g_swap_command_option)
return key;
switch (key) {
case AdbKey_Option: return AdbKey_Command;
case AdbKey_RightOption: return AdbKey_Command;
case AdbKey_Command: return AdbKey_Option;
default: return key;
}
}
void EventManager::set_keyboard_locale(uint32_t keyboard_id) {
this->kbd_locale = keyboard_id;
}
void EventManager::poll_events() {
SDL_Event event; SDL_Event event;
while (SDL_PollEvent(&event)) { while (SDL_PollEvent(&event)) {
@@ -58,11 +40,12 @@ void EventManager::poll_events() {
switch (event.type) { switch (event.type) {
case SDL_QUIT: case SDL_QUIT:
power_off(po_quit); power_on = false;
power_off_reason = po_quit;
break; break;
case SDL_WINDOWEVENT: { case SDL_WINDOWEVENT: {
WindowEvent we{}; WindowEvent we;
we.sub_type = event.window.event; we.sub_type = event.window.event;
we.window_id = event.window.windowID; we.window_id = event.window.windowID;
this->_window_signal.emit(we); this->_window_signal.emit(we);
@@ -71,146 +54,27 @@ void EventManager::poll_events() {
case SDL_KEYDOWN: case SDL_KEYDOWN:
case SDL_KEYUP: { case SDL_KEYUP: {
if (event.key.repeat)
break;
// Internal shortcuts, intentionally not sent to the host. // Internal shortcuts, intentionally not sent to the host.
// Control-G: mouse grab // Control-G: mouse grab
if (event.key.keysym.sym == SDLK_g && (event.key.keysym.mod & KMOD_ALL) == KMOD_LCTRL) { if (event.key.keysym.sym == SDLK_g && SDL_GetModState() & KMOD_LCTRL) {
if (event.type == SDL_KEYUP) { if (event.type == SDL_KEYUP) {
WindowEvent we; toggle_mouse_grab(event.key);
we.sub_type = DPPC_WINDOWEVENT_MOUSE_GRAB_TOGGLE;
we.window_id = event.window.windowID;
this->_window_signal.emit(we);
we.sub_type = DPPC_WINDOWEVENT_MOUSE_GRAB_CHANGED;
we.window_id = event.window.windowID;
this->_window_signal.emit(we);
} }
return; return;
} }
// Control-S: scale quality // Control-S: scale quality
if (event.key.keysym.sym == SDLK_s && (event.key.keysym.mod & KMOD_ALL) == KMOD_LCTRL) { if (event.key.keysym.sym == SDLK_s && SDL_GetModState() & KMOD_LCTRL) {
if (event.type == SDL_KEYUP) { if (event.type == SDL_KEYUP) {
WindowEvent we{}; WindowEvent we;
we.sub_type = DPPC_WINDOWEVENT_WINDOW_SCALE_QUALITY_TOGGLE; we.sub_type = WINDOW_SCALE_QUALITY_TOGGLE;
we.window_id = event.window.windowID; we.window_id = event.window.windowID;
this->_window_signal.emit(we); this->_window_signal.emit(we);
} }
return; return;
} }
// Control-F: fullscreen int key_code = get_sdl_event_key_code(event.key);
if (event.key.keysym.sym == SDLK_f && (event.key.keysym.mod & KMOD_ALL) == KMOD_LCTRL) {
if (event.type == SDL_KEYUP) {
WindowEvent we{};
we.sub_type = DPPC_WINDOWEVENT_WINDOW_FULL_SCREEN_TOGGLE;
we.window_id = event.window.windowID;
this->_window_signal.emit(we);
}
return;
}
// Control-Shift-F: fullscreen reverse
if (event.key.keysym.sym == SDLK_f && (event.key.keysym.mod & KMOD_ALL) == (KMOD_LCTRL | KMOD_LSHIFT)) {
if (event.type == SDL_KEYUP) {
WindowEvent we{};
we.sub_type = DPPC_WINDOWEVENT_WINDOW_FULL_SCREEN_TOGGLE_REVERSE;
we.window_id = event.window.windowID;
this->_window_signal.emit(we);
}
return;
}
// Control-+: bigger
if (event.key.keysym.sym == SDLK_EQUALS && (event.key.keysym.mod & KMOD_ALL) == KMOD_LCTRL) {
if (event.type == SDL_KEYUP) {
WindowEvent we{};
we.sub_type = DPPC_WINDOWEVENT_WINDOW_BIGGER;
we.window_id = event.window.windowID;
this->_window_signal.emit(we);
}
return;
}
// Control--: smaller
if (event.key.keysym.sym == SDLK_MINUS && (event.key.keysym.mod & KMOD_ALL) == KMOD_LCTRL) {
if (event.type == SDL_KEYUP) {
WindowEvent we{};
we.sub_type = DPPC_WINDOWEVENT_WINDOW_SMALLER;
we.window_id = event.window.windowID;
this->_window_signal.emit(we);
}
return;
}
// Control-Alt-Shift-+: speed up icnt_factor
if (event.key.keysym.sym == SDLK_EQUALS &&
(event.key.keysym.mod & KMOD_ALL) == (KMOD_LCTRL | KMOD_LALT | KMOD_LSHIFT)
) {
if (event.type == SDL_KEYUP) {
int icnt_counter_val = increment_icnt_factor();
LOG_F(INFO, "Incremented icnt_factor: %d", icnt_counter_val);
}
return;
}
// Control-Alt-Shift--: slow down icnt_factor
if (event.key.keysym.sym == SDLK_MINUS &&
(event.key.keysym.mod & KMOD_ALL) == (KMOD_LCTRL | KMOD_LALT | KMOD_LSHIFT)
) {
if (event.type == SDL_KEYUP) {
int icnt_counter_val = decrement_icnt_factor();
LOG_F(INFO, "Decremented icnt_factor: %d", icnt_counter_val);
}
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::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_off(po_enter_debugger);
}
return;
}
// Ralt+delete => ctrl+alt+del
if (event.key.keysym.sym == SDLK_DELETE && ((event.key.keysym.mod & KMOD_ALL) == KMOD_RALT) != 0) {
KeyboardEvent ke{};
ke.key = AdbKey_Control;
if (event.type == SDL_KEYDOWN) {
ke.flags = KEYBOARD_EVENT_DOWN;
key_downs++;
} else {
ke.flags = KEYBOARD_EVENT_UP;
key_ups++;
}
this->_keyboard_signal.emit(ke);
ke.key = AdbKey_Delete;
this->_keyboard_signal.emit(ke);
return;
}
int key_code = get_sdl_event_key_code(event.key, this->kbd_locale);
if (key_code != -1) { if (key_code != -1) {
KeyboardEvent ke{}; KeyboardEvent ke;
ke.key = key_code; ke.key = key_code;
if (event.type == SDL_KEYDOWN) { if (event.type == SDL_KEYDOWN) {
ke.flags = KEYBOARD_EVENT_DOWN; ke.flags = KEYBOARD_EVENT_DOWN;
@@ -221,7 +85,7 @@ void EventManager::poll_events() {
} }
// Caps Lock is a special case, since it's a toggle key // Caps Lock is a special case, since it's a toggle key
if (ke.key == AdbKey_CapsLock) { if (ke.key == AdbKey_CapsLock) {
ke.flags = event.key.keysym.mod & KMOD_CAPS ? ke.flags = SDL_GetModState() & KMOD_CAPS ?
KEYBOARD_EVENT_DOWN : KEYBOARD_EVENT_UP; KEYBOARD_EVENT_DOWN : KEYBOARD_EVENT_UP;
} }
this->_keyboard_signal.emit(ke); this->_keyboard_signal.emit(ke);
@@ -232,7 +96,7 @@ void EventManager::poll_events() {
break; break;
case SDL_MOUSEMOTION: { case SDL_MOUSEMOTION: {
MouseEvent me{}; MouseEvent me;
me.xrel = event.motion.xrel; me.xrel = event.motion.xrel;
me.yrel = event.motion.yrel; me.yrel = event.motion.yrel;
me.xabs = event.motion.x; me.xabs = event.motion.x;
@@ -243,7 +107,7 @@ void EventManager::poll_events() {
break; break;
case SDL_MOUSEBUTTONDOWN: { case SDL_MOUSEBUTTONDOWN: {
MouseEvent me{}; MouseEvent me;
Uint8 adb_button; Uint8 adb_button;
switch (event.button.button) { switch (event.button.button) {
case SDL_BUTTON_LEFT : adb_button = 0; break; case SDL_BUTTON_LEFT : adb_button = 0; break;
@@ -260,7 +124,7 @@ void EventManager::poll_events() {
break; break;
case SDL_MOUSEBUTTONUP: { case SDL_MOUSEBUTTONUP: {
MouseEvent me{}; MouseEvent me;
Uint8 adb_button; Uint8 adb_button;
switch (event.button.button) { switch (event.button.button) {
case SDL_BUTTON_LEFT : adb_button = 0; break; case SDL_BUTTON_LEFT : adb_button = 0; break;
@@ -277,7 +141,7 @@ void EventManager::poll_events() {
break; break;
case SDL_CONTROLLERBUTTONDOWN: { case SDL_CONTROLLERBUTTONDOWN: {
GamepadEvent ge{}; GamepadEvent ge;
switch (event.cbutton.button) { switch (event.cbutton.button) {
case SDL_CONTROLLER_BUTTON_BACK: ge.button = GamepadButton::FrontLeft; break; case SDL_CONTROLLER_BUTTON_BACK: ge.button = GamepadButton::FrontLeft; break;
case SDL_CONTROLLER_BUTTON_GUIDE: ge.button = GamepadButton::FrontMiddle; break; case SDL_CONTROLLER_BUTTON_GUIDE: ge.button = GamepadButton::FrontMiddle; break;
@@ -300,7 +164,7 @@ void EventManager::poll_events() {
break; break;
case SDL_CONTROLLERBUTTONUP: { case SDL_CONTROLLERBUTTONUP: {
GamepadEvent ge{}; GamepadEvent ge;
switch (event.cbutton.button) { switch (event.cbutton.button) {
case SDL_CONTROLLER_BUTTON_BACK: ge.button = GamepadButton::FrontLeft; break; case SDL_CONTROLLER_BUTTON_BACK: ge.button = GamepadButton::FrontLeft; break;
case SDL_CONTROLLER_BUTTON_GUIDE: ge.button = GamepadButton::FrontMiddle; break; case SDL_CONTROLLER_BUTTON_GUIDE: ge.button = GamepadButton::FrontMiddle; break;
@@ -322,35 +186,6 @@ void EventManager::poll_events() {
} }
break; break;
case SDL_DROPFILE: {
const char* path = event.drop.file;
// TODO: Distinguish CD-ROM and floppy images once dynamic
// floppy insertion is supported.
CdromImageEvent cdrom_event{};
cdrom_event.image_path = path;
this->post_cdrom_event(cdrom_event);
switch (cdrom_event.result) {
case CdromInsertionResult::SUCCESS:
LOG_F(INFO, "Inserted CD-ROM image: %s", path);
break;
case CdromInsertionResult::NO_DRIVE:
LOG_F(ERROR, "Cannot insert CD-ROM image; no CD-ROM drive is available: %s",
path);
break;
case CdromInsertionResult::MEDIA_PRESENT:
LOG_F(ERROR, "Cannot insert CD-ROM image; eject the current media first: %s",
path);
break;
case CdromInsertionResult::IMAGE_OPEN_FAILED:
LOG_F(ERROR, "Cannot insert CD-ROM image: %s", path);
break;
}
SDL_free(event.drop.file);
}
break;
default: default:
unhandled_events++; unhandled_events++;
} }
@@ -360,89 +195,8 @@ void EventManager::poll_events() {
this->_post_signal.emit(); this->_post_signal.emit();
} }
void EventManager::post_keyboard_state_events() {
int count;
int numkeys;
const Uint8 *states = SDL_GetKeyboardState(&numkeys);
int modstate = SDL_GetModState();
SDL_KeyboardEvent keyevent = { .type = SDL_KEYDOWN }; static int get_sdl_event_key_code(const SDL_KeyboardEvent &event)
SDL_Scancode scancode;
KeyboardEvent ke{};
typedef struct {
SDL_Scancode scancode;
SDL_Keymod keymod;
AdbKey adbkey;
} 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 },
};
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, " Modifier: %s", SDL_GetScancodeName(mod->scancode));
count++;
ke.key = swap_command_option(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, " Modifier: %s", SDL_GetScancodeName(scancode));
continue;
}
LOG_F(INFO, " Key: %s", SDL_GetScancodeName(scancode));
keyevent.keysym.scancode = scancode;
keyevent.keysym.sym = SDL_GetKeyFromScancode(scancode);
keyevent.keysym.mod = modstate;
int key_code = get_sdl_event_key_code(keyevent, this->kbd_locale);
if (key_code != -1) {
ke.key = key_code;
ke.flags = KEYBOARD_EVENT_DOWN;
this->_keyboard_signal.emit(ke);
} else {
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)
{ {
switch (event.keysym.sym) { switch (event.keysym.sym) {
case SDLK_a: return AdbKey_A; case SDLK_a: return AdbKey_A;
@@ -523,13 +277,13 @@ static int get_sdl_event_key_code(const SDL_KeyboardEvent &event, uint32_t kbd_l
case SDLK_PAGEDOWN: return AdbKey_PageDown; case SDLK_PAGEDOWN: return AdbKey_PageDown;
case SDLK_LCTRL: return AdbKey_Control; case SDLK_LCTRL: return AdbKey_Control;
case SDLK_RCTRL: return AdbKey_RightControl; case SDLK_RCTRL: return AdbKey_Control;
case SDLK_LSHIFT: return AdbKey_Shift; case SDLK_LSHIFT: return AdbKey_Shift;
case SDLK_RSHIFT: return AdbKey_RightShift; case SDLK_RSHIFT: return AdbKey_Shift;
case SDLK_LALT: return swap_command_option(AdbKey_Option); case SDLK_LALT: return AdbKey_Option;
case SDLK_RALT: return swap_command_option(AdbKey_RightOption); case SDLK_RALT: return AdbKey_Option;
case SDLK_LGUI: return swap_command_option(AdbKey_Command); case SDLK_LGUI: return AdbKey_Command;
case SDLK_RGUI: return swap_command_option(AdbKey_Command); case SDLK_RGUI: return AdbKey_Command;
case SDLK_MENU: return AdbKey_Grave; case SDLK_MENU: return AdbKey_Grave;
case SDLK_CAPSLOCK: return AdbKey_CapsLock; case SDLK_CAPSLOCK: return AdbKey_CapsLock;
@@ -537,7 +291,7 @@ static int get_sdl_event_key_code(const SDL_KeyboardEvent &event, uint32_t kbd_l
case SDLK_DOWN: return AdbKey_ArrowDown; case SDLK_DOWN: return AdbKey_ArrowDown;
case SDLK_LEFT: return AdbKey_ArrowLeft; case SDLK_LEFT: return AdbKey_ArrowLeft;
case SDLK_RIGHT: return AdbKey_ArrowRight; case SDLK_RIGHT: return AdbKey_ArrowRight;
;
case SDLK_KP_0: return AdbKey_Keypad0; case SDLK_KP_0: return AdbKey_Keypad0;
case SDLK_KP_1: return AdbKey_Keypad1; case SDLK_KP_1: return AdbKey_Keypad1;
case SDLK_KP_2: return AdbKey_Keypad2; case SDLK_KP_2: return AdbKey_Keypad2;
@@ -556,7 +310,7 @@ static int get_sdl_event_key_code(const SDL_KeyboardEvent &event, uint32_t kbd_l
case SDLK_KP_ENTER: return AdbKey_KeypadEnter; case SDLK_KP_ENTER: return AdbKey_KeypadEnter;
case SDLK_KP_EQUALS: return AdbKey_KeypadEquals; case SDLK_KP_EQUALS: return AdbKey_KeypadEquals;
case SDLK_NUMLOCKCLEAR: return AdbKey_KeypadClear; case SDLK_NUMLOCKCLEAR: return AdbKey_KeypadClear;
;
case SDLK_F1: return AdbKey_F1; case SDLK_F1: return AdbKey_F1;
case SDLK_F2: return AdbKey_F2; case SDLK_F2: return AdbKey_F2;
case SDLK_F3: return AdbKey_F3; case SDLK_F3: return AdbKey_F3;
@@ -573,35 +327,32 @@ static int get_sdl_event_key_code(const SDL_KeyboardEvent &event, uint32_t kbd_l
case SDLK_SCROLLLOCK: return AdbKey_F14; case SDLK_SCROLLLOCK: return AdbKey_F14;
case SDLK_PAUSE: return AdbKey_F15; case SDLK_PAUSE: return AdbKey_F15;
// International keyboard support //International keyboard support
// Japanese keyboard //Japanese keyboard
case SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_INTERNATIONAL3): case SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_INTERNATIONAL3):
if (kbd_locale == Jpn_JPN) return AdbKey_JIS_Yen;
return AdbKey_JIS_Yen;
else
return -1;
case SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_INTERNATIONAL1): case SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_INTERNATIONAL1):
return AdbKey_JIS_Underscore; return AdbKey_JIS_Underscore;
case 0XBC: case 0XBC:
return AdbKey_JIS_KP_Comma; return AdbKey_JIS_KP_Comma;
case 0X89: case 0X89:
return AdbKey_JIS_Eisu; return AdbKey_JIS_Eisu;
case SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_INTERNATIONAL2): case SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_INTERNATIONAL2):
return AdbKey_JIS_Kana; return AdbKey_JIS_Kana;
// German keyboard //German keyboard
case 0XB4: return AdbKey_Slash; case 0XB4: return AdbKey_Slash;
case 0X5E: return AdbKey_ISO1; case 0X5E: return AdbKey_ISO1;
case 0XDF: return AdbKey_Minus; // Eszett case 0XDF: return AdbKey_Minus; //Eszett
case 0XE4: return AdbKey_LeftBracket; // A-umlaut case 0XE4: return AdbKey_LeftBracket; //A-umlaut
case 0XF6: return AdbKey_Semicolon; // O-umlaut case 0XF6: return AdbKey_Semicolon; //O-umlaut
case 0XFC: return AdbKey_LeftBracket; // U-umlaut case 0XFC: return AdbKey_LeftBracket; //U-umlaut
// French keyboard // French keyboard
case 0X29: return AdbKey_Minus; // Right parenthesis case 0X29: return AdbKey_Minus; // Right parenthesis
case 0X43: return AdbKey_KeypadMultiply; // Star/Mu 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 case 0XF9: return AdbKey_Quote; // U-grave
// Italian keyboard // Italian keyboard
@@ -622,3 +373,25 @@ static int get_sdl_event_key_code(const SDL_KeyboardEvent &event, uint32_t kbd_l
} }
return -1; return -1;
} }
static void toggle_mouse_grab(const SDL_KeyboardEvent &event) {
SDL_Window *window = SDL_GetWindowFromID(event.windowID);
if (SDL_GetRelativeMouseMode()) {
SDL_SetRelativeMouseMode(SDL_FALSE);
SDL_SetWindowTitle(window, "DingusPPC Display");
} else {
// If the mouse is initially outside the window, move it to the middle,
// so that clicks are handled by the window (instead making it lose
// focus, at least with macOS hosts).
int mouse_x, mouse_y, window_x, window_y, window_width, window_height;
SDL_GetGlobalMouseState(&mouse_x, &mouse_y);
SDL_GetWindowPosition(window, &window_x, &window_y);
SDL_GetWindowSize(window, &window_width, &window_height);
if (mouse_x < window_x || mouse_x >= window_x + window_width ||
mouse_y < window_y || mouse_y >= window_y + window_height) {
SDL_WarpMouseInWindow(window, window_width / 2, window_height / 2);
}
SDL_SetRelativeMouseMode(SDL_TRUE);
SDL_SetWindowTitle(window, "DingusPPC Display (Mouse Grabbed)");
}
}
+3 -5
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-22 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -19,8 +19,6 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
#include <cstdint>
#ifndef MATH_UTILS_H #ifndef MATH_UTILS_H
#define MATH_UTILS_H #define MATH_UTILS_H
+66 -46
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -30,47 +30,78 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
TimerManager* TimerManager::timer_manager; TimerManager* TimerManager::timer_manager;
void TimerManager::add_absolute_timer(TimerInfo &ti, uint64_t timeout_ns, uint64_t interval, timer_cb cb) uint32_t TimerManager::add_oneshot_timer(uint64_t timeout, timer_cb cb)
{ {
ti.timeout_ns = timeout_ns; TimerInfo* ti = new TimerInfo;
ti.interval_ns = interval;
ti.active = true; ti->id = ++this->id;
ti.cb = cb; 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 // add new timer to the timer queue
//if (this->timer_queue.remove_by_id(&ti)) this->timer_queue.push(timer_desc);
// LOG_F(ERROR, "timer was in queue!");
this->timer_queue.push(&ti);
// notify listeners about changes in the timer queue // notify listeners about changes in the timer queue
if (!this->cb_active) { if (!this->cb_active) {
this->notify_timer_changes(); this->notify_timer_changes();
} }
return ti->id;
} }
void TimerManager::add_oneshot_timer(TimerInfo &ti, uint64_t timeout, timer_cb cb) uint32_t TimerManager::add_immediate_timer(timer_cb cb) {
{ TimerInfo* ti = new TimerInfo;
TimerManager::add_absolute_timer(ti, this->get_time_now() + timeout, 0, cb);
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;
} }
void TimerManager::add_immediate_timer(TimerInfo &ti, timer_cb cb) uint32_t TimerManager::add_cyclic_timer(uint64_t interval, uint64_t delay, timer_cb cb)
{ {
TimerManager::add_absolute_timer(ti, 0, 0, cb); TimerInfo* ti = new TimerInfo;
ti->id = ++this->id;
ti->timeout_ns = this->get_time_now() + delay;
ti->interval_ns = interval;
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;
} }
void TimerManager::add_cyclic_timer(TimerInfo &ti, uint64_t interval, uint64_t delay, timer_cb cb) uint32_t TimerManager::add_cyclic_timer(uint64_t interval, timer_cb cb) {
{ return this->add_cyclic_timer(interval, interval, cb);
TimerManager::add_absolute_timer(ti, this->get_time_now() + delay, interval, cb);
} }
void TimerManager::add_cyclic_timer(TimerInfo &ti, uint64_t interval, timer_cb cb) void TimerManager::cancel_timer(uint32_t id)
{ {
this->add_cyclic_timer(ti, interval, interval, cb); this->timer_queue.remove_by_id(id);
}
void TimerManager::cancel_timer(TimerInfo &ti)
{
this->timer_queue.remove_by_id(&ti);
if (!this->cb_active) { if (!this->cb_active) {
this->notify_timer_changes(); this->notify_timer_changes();
} }
@@ -78,7 +109,7 @@ void TimerManager::cancel_timer(TimerInfo &ti)
uint64_t TimerManager::process_timers() uint64_t TimerManager::process_timers()
{ {
TimerInfo *cur_timer; std::shared_ptr<TimerInfo> cur_timer;
uint64_t time_now = get_time_now(); uint64_t time_now = get_time_now();
{ // mtx scope { // mtx scope
@@ -91,24 +122,23 @@ uint64_t TimerManager::process_timers()
cur_timer = this->timer_queue.top(); cur_timer = this->timer_queue.top();
} // ] mtx scope } // ] mtx scope
while (cur_timer->timeout_ns <= time_now) { while (cur_timer->timeout_ns <= time_now) {
this->timer_queue.remove_by_id(cur_timer);
uint64_t timeout_ns = cur_timer->timeout_ns;
timer_cb cb = cur_timer->cb; timer_cb cb = cur_timer->cb;
// re-arm cyclic timers // re-arm cyclic timers
if (cur_timer->interval_ns) { if (cur_timer->interval_ns) {
std::lock_guard<std::recursive_mutex> lk(this->timer_queue.get_mtx()); std::lock_guard<std::recursive_mutex> lk(this->timer_queue.get_mtx());
uint64_t timeout_ns_new = timeout_ns + cur_timer->interval_ns; cur_timer->timeout_ns = time_now + cur_timer->interval_ns;
if (timeout_ns_new <= time_now) this->timer_queue.remove_by_id(cur_timer->id);
timeout_ns_new = time_now + cur_timer->interval_ns;
cur_timer->timeout_ns = timeout_ns_new;
this->timer_queue.push(cur_timer); this->timer_queue.push(cur_timer);
} else {
// remove one-shot timers from queue
this->timer_queue.pop();
} }
this->cb_active = true; this->cb_active = true;
// invoke timer callback // invoke timer callback
cb(time_now, timeout_ns); cb();
this->cb_active = false; this->cb_active = false;
@@ -123,16 +153,6 @@ uint64_t TimerManager::process_timers()
} // ] mtx scope } // ] mtx scope
} }
// return next timer's expiry // return time slice in nanoseconds until next timer's expiry
return cur_timer->timeout_ns; return cur_timer->timeout_ns - time_now;
}
void TimerManager::cancel_all_timers()
{
TimerInfo *cur_timer;
while (!this->timer_queue.empty()) {
cur_timer = this->timer_queue.top();
LOG_F(WARNING, "Canceling timer id:%llu ns:%llu", uint64_t(cur_timer), cur_timer->timeout_ns);
this->timer_queue.pop();
}
} }
+32 -38
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -31,17 +31,16 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <vector> #include <vector>
#include <mutex> #include <mutex>
constexpr auto NS_PER_SEC = 1000000000; #define NS_PER_SEC 1000000000
constexpr auto USEC_PER_SEC = 1000000; #define USEC_PER_SEC 1000000
constexpr auto NS_PER_USEC = 1000; #define NS_PER_USEC 1000
constexpr auto NS_PER_MSEC = 1000000; #define NS_PER_MSEC 1000000
constexpr auto ONE_BILLION_NS = 1000000000; #define ONE_BILLION_NS 1000000000
#define USECS_TO_NSECS(us) (us) * NS_PER_USEC #define USECS_TO_NSECS(us) (us) * NS_PER_USEC
#define MSECS_TO_NSECS(ms) (ms) * NS_PER_MSEC #define MSECS_TO_NSECS(ms) (ms) * NS_PER_MSEC
typedef std::function<void(uint64_t timeout_ns, uint64_t time_now)> timer_cb; typedef std::function<void()> timer_cb;
typedef std::function<void()> notify_changes_cb;
/** Extend std::priority_queue as suggested here: /** Extend std::priority_queue as suggested here:
https://stackoverflow.com/a/36711682 https://stackoverflow.com/a/36711682
@@ -50,30 +49,28 @@ typedef std::function<void()> notify_changes_cb;
template <typename T, class Container = std::vector<T>, class Compare = std::less<typename Container::value_type>> template <typename T, class Container = std::vector<T>, class Compare = std::less<typename Container::value_type>>
class my_priority_queue : public std::priority_queue<T, Container, Compare> { class my_priority_queue : public std::priority_queue<T, Container, Compare> {
public: public:
bool remove_by_id(T id){ bool remove_by_id(const uint32_t id){
std::lock_guard<std::recursive_mutex> lk(mtx); std::lock_guard<std::recursive_mutex> lk(mtx);
if (this->empty())
return false;
auto el = this->top(); auto el = this->top();
if (el == id) { if (el->id == id) {
std::priority_queue<T, Container, Compare>::pop(); std::priority_queue<T, Container, Compare>::pop();
return true; return true;
} }
auto it = std::find_if( auto it = std::find_if(
this->c.begin(), this->c.end(), [id](const T& el) { return el == id; }); this->c.begin(), this->c.end(), [id](const T& el) { return el->id == id; });
if (it != this->c.end()) { if (it != this->c.end()) {
this->c.erase(it); this->c.erase(it);
std::make_heap(this->c.begin(), this->c.end(), this->comp); std::make_heap(this->c.begin(), this->c.end(), this->comp);
return true; return true;
} }
return false; return false;
} };
void push(T val) void push(T val)
{ {
std::lock_guard<std::recursive_mutex> lk(mtx); std::lock_guard<std::recursive_mutex> lk(mtx);
std::priority_queue<T, Container, Compare>::push(val); std::priority_queue<T, Container, Compare>::push(val);
} };
T pop() T pop()
{ {
@@ -81,7 +78,7 @@ public:
T val = std::priority_queue<T, Container, Compare>::top(); T val = std::priority_queue<T, Container, Compare>::top();
std::priority_queue<T, Container, Compare>::pop(); std::priority_queue<T, Container, Compare>::pop();
return val; return val;
} };
std::recursive_mutex& get_mtx() std::recursive_mutex& get_mtx()
{ {
@@ -93,18 +90,17 @@ private:
}; };
typedef struct TimerInfo { typedef struct TimerInfo {
uint32_t id;
uint64_t timeout_ns; // timer expiry uint64_t timeout_ns; // timer expiry
uint64_t interval_ns; // 0 for one-shot timers uint64_t interval_ns; // 0 for one-shot timers
bool active = false; // set to true when added to the queue
timer_cb cb; // timer callback timer_cb cb; // timer callback
} TimerInfo; } TimerInfo;
// Custom comparator for sorting our timer queue in ascending order // Custom comparator for sorting our timer queue in ascending order
class MyGtComparator { class MyGtComparator {
public: public:
bool operator()(const TimerInfo *l, const TimerInfo *r) const { bool operator()(const std::shared_ptr<TimerInfo>& l, const std::shared_ptr<TimerInfo>& r) {
return l->timeout_ns > r->timeout_ns || return l.get()->timeout_ns > r.get()->timeout_ns;
(l->timeout_ns == r->timeout_ns && l > r);
} }
}; };
@@ -115,44 +111,42 @@ public:
timer_manager = new TimerManager(); timer_manager = new TimerManager();
} }
return timer_manager; return timer_manager;
} };
// callback for retrieving current time // callback for retrieving current time
void set_time_now_cb(const std::function<uint64_t()> &cb) { void set_time_now_cb(const std::function<uint64_t()> &cb) {
this->get_time_now = cb; this->get_time_now = cb;
} };
// callback for acknowledging time changes // callback for acknowledging time changes
void set_notify_changes_cb(const notify_changes_cb &cb) { void set_notify_changes_cb(const timer_cb &cb) {
this->notify_timer_changes = cb; this->notify_timer_changes = cb;
} };
// return current virtual time in nanoseconds // return current virtual time in nanoseconds
uint64_t current_time_ns() const { return get_time_now(); } uint64_t current_time_ns() { return get_time_now(); };
// creating and cancelling timers // creating and cancelling timers
void add_absolute_timer(TimerInfo &ti, uint64_t timeout_ns, uint64_t interval, timer_cb cb); uint32_t add_oneshot_timer(uint64_t timeout, timer_cb cb);
void add_oneshot_timer(TimerInfo &ti, uint64_t timeout, timer_cb cb); uint32_t add_immediate_timer(timer_cb cb);
void add_immediate_timer(TimerInfo &ti, timer_cb cb); uint32_t add_cyclic_timer(uint64_t interval, timer_cb cb);
void add_cyclic_timer(TimerInfo &ti, uint64_t interval, timer_cb cb); uint32_t add_cyclic_timer(uint64_t interval, uint64_t delay, timer_cb cb);
void add_cyclic_timer(TimerInfo &ti, uint64_t interval, uint64_t delay, timer_cb cb); void cancel_timer(uint32_t id);
void cancel_timer(TimerInfo &ti);
void cancel_all_timers();
uint64_t process_timers(); uint64_t process_timers();
private: private:
static TimerManager* timer_manager; static TimerManager* timer_manager;
TimerManager(){} // private constructor to implement a singleton TimerManager(){}; // private constructor to implement a singleton
// timer queue // timer queue
my_priority_queue<TimerInfo*, std::vector<TimerInfo*>, MyGtComparator> timer_queue; my_priority_queue<std::shared_ptr<TimerInfo>, std::vector<std::shared_ptr<TimerInfo>>, MyGtComparator> timer_queue;
std::function<uint64_t()> get_time_now; std::function<uint64_t()> get_time_now;
std::function<void()> notify_timer_changes; std::function<void()> notify_timer_changes;
// FIXME: Do we need this? It gets written in main thread and read in audio thread. std::atomic<uint32_t> id{0};
bool cb_active = false; // true if a timer callback is executing bool cb_active = false; // true if a timer callback is executing // FIXME: Do we need this? It gets written in main thread and read in audio thread.
}; };
#endif // TIMER_MANAGER_H #endif // TIMER_MANAGER_H
+143 -114
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -22,11 +22,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
// The Power-specific opcodes for the processor - ppcopcodes.cpp // The Power-specific opcodes for the processor - ppcopcodes.cpp
// Any shared opcodes are in ppcopcodes.cpp // Any shared opcodes are in ppcopcodes.cpp
#include <core/bitops.h> #include "ppcemu.h"
#include <cpu/ppc/ppcdechelpers.h> #include "ppcmacros.h"
#include <cpu/ppc/ppcemu.h> #include "ppcmmu.h"
#include <cpu/ppc/ppcmmu.h>
#include <stdint.h> #include <stdint.h>
/** mask generator for rotate and shift instructions (§ 4.2.1.4 PowerpC PEM) */ /** mask generator for rotate and shift instructions (§ 4.2.1.4 PowerpC PEM) */
@@ -37,7 +35,7 @@ static inline uint32_t power_rot_mask(unsigned rot_mb, unsigned rot_me) {
} }
template <field_rc rec, field_ov ov> template <field_rc rec, field_ov ov>
void dppc_interpreter::power_abs(uint32_t opcode) { uint32_t dppc_interpreter::power_abs(uint32_t opcode) {
uint32_t ppc_result_d; uint32_t ppc_result_d;
ppc_grab_regsda(opcode); ppc_grab_regsda(opcode);
if (ppc_result_a == 0x80000000) { if (ppc_result_a == 0x80000000) {
@@ -54,14 +52,15 @@ void dppc_interpreter::power_abs(uint32_t opcode) {
ppc_changecrf0(ppc_result_d); ppc_changecrf0(ppc_result_d);
ppc_store_iresult_reg(reg_d, ppc_result_d); ppc_store_iresult_reg(reg_d, ppc_result_d);
return 0;
} }
template void dppc_interpreter::power_abs<RC0, OV0>(uint32_t opcode); template uint32_t dppc_interpreter::power_abs<RC0, OV0>(uint32_t opcode);
template void dppc_interpreter::power_abs<RC0, OV1>(uint32_t opcode); template uint32_t dppc_interpreter::power_abs<RC0, OV1>(uint32_t opcode);
template void dppc_interpreter::power_abs<RC1, OV0>(uint32_t opcode); template uint32_t dppc_interpreter::power_abs<RC1, OV0>(uint32_t opcode);
template void dppc_interpreter::power_abs<RC1, OV1>(uint32_t opcode); template uint32_t dppc_interpreter::power_abs<RC1, OV1>(uint32_t opcode);
void dppc_interpreter::power_clcs(uint32_t opcode) { uint32_t dppc_interpreter::power_clcs(uint32_t opcode) {
uint32_t ppc_result_d; uint32_t ppc_result_d;
ppc_grab_da(opcode); ppc_grab_da(opcode);
switch (reg_a & 15) { switch (reg_a & 15) {
@@ -85,10 +84,11 @@ void dppc_interpreter::power_clcs(uint32_t opcode) {
} }
ppc_store_iresult_reg(reg_d, ppc_result_d); ppc_store_iresult_reg(reg_d, ppc_result_d);
return 0;
} }
template <field_rc rec, field_ov ov> template <field_rc rec, field_ov ov>
void dppc_interpreter::power_div(uint32_t opcode) { uint32_t dppc_interpreter::power_div(uint32_t opcode) {
uint32_t ppc_result_d; uint32_t ppc_result_d;
ppc_grab_regsdab(opcode); ppc_grab_regsdab(opcode);
@@ -125,15 +125,16 @@ void dppc_interpreter::power_div(uint32_t opcode) {
ppc_store_iresult_reg(reg_d, ppc_result_d); ppc_store_iresult_reg(reg_d, ppc_result_d);
ppc_state.spr[SPR::MQ] = remainder; ppc_state.spr[SPR::MQ] = remainder;
return 0;
} }
template void dppc_interpreter::power_div<RC0, OV0>(uint32_t opcode); template uint32_t dppc_interpreter::power_div<RC0, OV0>(uint32_t opcode);
template void dppc_interpreter::power_div<RC0, OV1>(uint32_t opcode); template uint32_t dppc_interpreter::power_div<RC0, OV1>(uint32_t opcode);
template void dppc_interpreter::power_div<RC1, OV0>(uint32_t opcode); template uint32_t dppc_interpreter::power_div<RC1, OV0>(uint32_t opcode);
template void dppc_interpreter::power_div<RC1, OV1>(uint32_t opcode); template uint32_t dppc_interpreter::power_div<RC1, OV1>(uint32_t opcode);
template <field_rc rec, field_ov ov> template <field_rc rec, field_ov ov>
void dppc_interpreter::power_divs(uint32_t opcode) { uint32_t dppc_interpreter::power_divs(uint32_t opcode) {
uint32_t ppc_result_d; uint32_t ppc_result_d;
int32_t remainder; int32_t remainder;
ppc_grab_regsdab(opcode); ppc_grab_regsdab(opcode);
@@ -159,15 +160,16 @@ void dppc_interpreter::power_divs(uint32_t opcode) {
ppc_store_iresult_reg(reg_d, ppc_result_d); ppc_store_iresult_reg(reg_d, ppc_result_d);
ppc_state.spr[SPR::MQ] = remainder; ppc_state.spr[SPR::MQ] = remainder;
return 0;
} }
template void dppc_interpreter::power_divs<RC0, OV0>(uint32_t opcode); template uint32_t dppc_interpreter::power_divs<RC0, OV0>(uint32_t opcode);
template void dppc_interpreter::power_divs<RC0, OV1>(uint32_t opcode); template uint32_t dppc_interpreter::power_divs<RC0, OV1>(uint32_t opcode);
template void dppc_interpreter::power_divs<RC1, OV0>(uint32_t opcode); template uint32_t dppc_interpreter::power_divs<RC1, OV0>(uint32_t opcode);
template void dppc_interpreter::power_divs<RC1, OV1>(uint32_t opcode); template uint32_t dppc_interpreter::power_divs<RC1, OV1>(uint32_t opcode);
template <field_rc rec, field_ov ov> template <field_rc rec, field_ov ov>
void dppc_interpreter::power_doz(uint32_t opcode) { uint32_t dppc_interpreter::power_doz(uint32_t opcode) {
ppc_grab_regsdab(opcode); ppc_grab_regsdab(opcode);
uint32_t ppc_result_d = (int32_t(ppc_result_a) < int32_t(ppc_result_b)) ? uint32_t ppc_result_d = (int32_t(ppc_result_a) < int32_t(ppc_result_b)) ?
ppc_result_b - ppc_result_a : 0; ppc_result_b - ppc_result_a : 0;
@@ -183,14 +185,15 @@ void dppc_interpreter::power_doz(uint32_t opcode) {
ppc_changecrf0(ppc_result_d); ppc_changecrf0(ppc_result_d);
ppc_store_iresult_reg(reg_d, ppc_result_d); ppc_store_iresult_reg(reg_d, ppc_result_d);
return 0;
} }
template void dppc_interpreter::power_doz<RC0, OV0>(uint32_t opcode); template uint32_t dppc_interpreter::power_doz<RC0, OV0>(uint32_t opcode);
template void dppc_interpreter::power_doz<RC0, OV1>(uint32_t opcode); template uint32_t dppc_interpreter::power_doz<RC0, OV1>(uint32_t opcode);
template void dppc_interpreter::power_doz<RC1, OV0>(uint32_t opcode); template uint32_t dppc_interpreter::power_doz<RC1, OV0>(uint32_t opcode);
template void dppc_interpreter::power_doz<RC1, OV1>(uint32_t opcode); template uint32_t dppc_interpreter::power_doz<RC1, OV1>(uint32_t opcode);
void dppc_interpreter::power_dozi(uint32_t opcode) { uint32_t dppc_interpreter::power_dozi(uint32_t opcode) {
uint32_t ppc_result_d; uint32_t ppc_result_d;
ppc_grab_regsdasimm(opcode); ppc_grab_regsdasimm(opcode);
if (((int32_t)ppc_result_a) > simm) { if (((int32_t)ppc_result_a) > simm) {
@@ -199,10 +202,11 @@ void dppc_interpreter::power_dozi(uint32_t opcode) {
ppc_result_d = simm - ppc_result_a; ppc_result_d = simm - ppc_result_a;
} }
ppc_store_iresult_reg(reg_d, ppc_result_d); ppc_store_iresult_reg(reg_d, ppc_result_d);
return 0;
} }
template <field_rc rec> template <field_rc rec>
void dppc_interpreter::power_lscbx(uint32_t opcode) { uint32_t dppc_interpreter::power_lscbx(uint32_t opcode) {
ppc_grab_regsdab(opcode); ppc_grab_regsdab(opcode);
uint32_t ea = ppc_result_b + (reg_a ? ppc_result_a : 0); uint32_t ea = ppc_result_b + (reg_a ? ppc_result_a : 0);
@@ -250,13 +254,15 @@ void dppc_interpreter::power_lscbx(uint32_t opcode) {
(is_match ? CRx_bit::CR_EQ : 0) | (is_match ? CRx_bit::CR_EQ : 0) |
((ppc_state.spr[SPR::XER] & XER::SO) >> 3); ((ppc_state.spr[SPR::XER] & XER::SO) >> 3);
} }
return 0;
} }
template void dppc_interpreter::power_lscbx<RC0>(uint32_t opcode); template uint32_t dppc_interpreter::power_lscbx<RC0>(uint32_t opcode);
template void dppc_interpreter::power_lscbx<RC1>(uint32_t opcode); template uint32_t dppc_interpreter::power_lscbx<RC1>(uint32_t opcode);
template <field_rc rec> template <field_rc rec>
void dppc_interpreter::power_maskg(uint32_t opcode) { uint32_t dppc_interpreter::power_maskg(uint32_t opcode) {
ppc_grab_regssab(opcode); ppc_grab_regssab(opcode);
uint32_t mask_start = ppc_result_d & 0x1F; uint32_t mask_start = ppc_result_d & 0x1F;
uint32_t mask_end = ppc_result_b & 0x1F; uint32_t mask_end = ppc_result_b & 0x1F;
@@ -278,13 +284,14 @@ void dppc_interpreter::power_maskg(uint32_t opcode) {
ppc_changecrf0(ppc_result_a); ppc_changecrf0(ppc_result_a);
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
return 0;
} }
template void dppc_interpreter::power_maskg<RC0>(uint32_t opcode); template uint32_t dppc_interpreter::power_maskg<RC0>(uint32_t opcode);
template void dppc_interpreter::power_maskg<RC1>(uint32_t opcode); template uint32_t dppc_interpreter::power_maskg<RC1>(uint32_t opcode);
template <field_rc rec> template <field_rc rec>
void dppc_interpreter::power_maskir(uint32_t opcode) { uint32_t dppc_interpreter::power_maskir(uint32_t opcode) {
ppc_grab_regssab(opcode); ppc_grab_regssab(opcode);
ppc_result_a = (ppc_result_a & ~ppc_result_b) | (ppc_result_d & ppc_result_b); ppc_result_a = (ppc_result_a & ~ppc_result_b) | (ppc_result_d & ppc_result_b);
@@ -292,13 +299,14 @@ void dppc_interpreter::power_maskir(uint32_t opcode) {
ppc_changecrf0(ppc_result_a); ppc_changecrf0(ppc_result_a);
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
return 0;
} }
template void dppc_interpreter::power_maskir<RC0>(uint32_t opcode); template uint32_t dppc_interpreter::power_maskir<RC0>(uint32_t opcode);
template void dppc_interpreter::power_maskir<RC1>(uint32_t opcode); template uint32_t dppc_interpreter::power_maskir<RC1>(uint32_t opcode);
template <field_rc rec, field_ov ov> template <field_rc rec, field_ov ov>
void dppc_interpreter::power_mul(uint32_t opcode) { uint32_t dppc_interpreter::power_mul(uint32_t opcode) {
ppc_grab_regsdab(opcode); ppc_grab_regsdab(opcode);
int64_t product = int64_t(int32_t(ppc_result_a)) * int32_t(ppc_result_b); int64_t product = int64_t(int32_t(ppc_result_a)) * int32_t(ppc_result_b);
uint32_t ppc_result_d = uint32_t(uint64_t(product) >> 32); uint32_t ppc_result_d = uint32_t(uint64_t(product) >> 32);
@@ -313,16 +321,18 @@ void dppc_interpreter::power_mul(uint32_t opcode) {
} }
if (rec) if (rec)
ppc_changecrf0(uint32_t(product)); ppc_changecrf0(uint32_t(product));
ppc_store_iresult_reg(reg_d, ppc_result_d); ppc_store_iresult_reg(reg_d, ppc_result_d);
return 0;
} }
template void dppc_interpreter::power_mul<RC0, OV0>(uint32_t opcode); template uint32_t dppc_interpreter::power_mul<RC0, OV0>(uint32_t opcode);
template void dppc_interpreter::power_mul<RC0, OV1>(uint32_t opcode); template uint32_t dppc_interpreter::power_mul<RC0, OV1>(uint32_t opcode);
template void dppc_interpreter::power_mul<RC1, OV0>(uint32_t opcode); template uint32_t dppc_interpreter::power_mul<RC1, OV0>(uint32_t opcode);
template void dppc_interpreter::power_mul<RC1, OV1>(uint32_t opcode); template uint32_t dppc_interpreter::power_mul<RC1, OV1>(uint32_t opcode);
template <field_rc rec, field_ov ov> template <field_rc rec, field_ov ov>
void dppc_interpreter::power_nabs(uint32_t opcode) { uint32_t dppc_interpreter::power_nabs(uint32_t opcode) {
ppc_grab_regsda(opcode); ppc_grab_regsda(opcode);
uint32_t ppc_result_d = (int32_t(ppc_result_a) < 0) ? ppc_result_a : -ppc_result_a; uint32_t ppc_result_d = (int32_t(ppc_result_a) < 0) ? ppc_result_a : -ppc_result_a;
@@ -332,19 +342,21 @@ void dppc_interpreter::power_nabs(uint32_t opcode) {
ppc_changecrf0(ppc_result_d); ppc_changecrf0(ppc_result_d);
ppc_store_iresult_reg(reg_d, ppc_result_d); ppc_store_iresult_reg(reg_d, ppc_result_d);
return 0;
} }
template void dppc_interpreter::power_nabs<RC0, OV0>(uint32_t opcode); template uint32_t dppc_interpreter::power_nabs<RC0, OV0>(uint32_t opcode);
template void dppc_interpreter::power_nabs<RC0, OV1>(uint32_t opcode); template uint32_t dppc_interpreter::power_nabs<RC0, OV1>(uint32_t opcode);
template void dppc_interpreter::power_nabs<RC1, OV0>(uint32_t opcode); template uint32_t dppc_interpreter::power_nabs<RC1, OV0>(uint32_t opcode);
template void dppc_interpreter::power_nabs<RC1, OV1>(uint32_t opcode); template uint32_t dppc_interpreter::power_nabs<RC1, OV1>(uint32_t opcode);
void dppc_interpreter::power_rlmi(uint32_t opcode) { uint32_t dppc_interpreter::power_rlmi(uint32_t opcode) {
ppc_grab_regssab(opcode); ppc_grab_regssab(opcode);
unsigned rot_mb = (opcode >> 6) & 0x1F; unsigned rot_mb = (opcode >> 6) & 0x1F;
unsigned rot_me = (opcode >> 1) & 0x1F; unsigned rot_me = (opcode >> 1) & 0x1F;
unsigned rot_sh = ppc_result_b & 0x1F;
uint32_t r = ROTL_32(ppc_result_d, ppc_result_b); uint32_t r = rot_sh ? ((ppc_result_d << rot_sh) | (ppc_result_d >> (32 - rot_sh))) : ppc_result_d;
uint32_t mask = power_rot_mask(rot_mb, rot_me); uint32_t mask = power_rot_mask(rot_mb, rot_me);
ppc_result_a = ((r & mask) | (ppc_result_a & ~mask)); ppc_result_a = ((r & mask) | (ppc_result_a & ~mask));
@@ -353,10 +365,11 @@ void dppc_interpreter::power_rlmi(uint32_t opcode) {
ppc_changecrf0(ppc_result_a); ppc_changecrf0(ppc_result_a);
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
return 0;
} }
template <field_rc rec> template <field_rc rec>
void dppc_interpreter::power_rrib(uint32_t opcode) { uint32_t dppc_interpreter::power_rrib(uint32_t opcode) {
ppc_grab_regssab(opcode); ppc_grab_regssab(opcode);
unsigned rot_sh = ppc_result_b & 0x1F; unsigned rot_sh = ppc_result_b & 0x1F;
@@ -370,18 +383,19 @@ void dppc_interpreter::power_rrib(uint32_t opcode) {
ppc_changecrf0(ppc_result_a); ppc_changecrf0(ppc_result_a);
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
return 0;
} }
template void dppc_interpreter::power_rrib<RC0>(uint32_t opcode); template uint32_t dppc_interpreter::power_rrib<RC0>(uint32_t opcode);
template void dppc_interpreter::power_rrib<RC1>(uint32_t opcode); template uint32_t dppc_interpreter::power_rrib<RC1>(uint32_t opcode);
template <field_rc rec> template <field_rc rec>
void dppc_interpreter::power_sle(uint32_t opcode) { uint32_t dppc_interpreter::power_sle(uint32_t opcode) {
ppc_grab_regssab(opcode); ppc_grab_regssab(opcode);
unsigned rot_sh = ppc_result_b & 0x1F; unsigned rot_sh = ppc_result_b & 0x1F;
ppc_result_a = ppc_result_d << rot_sh; ppc_result_a = ppc_result_d << rot_sh;
ppc_state.spr[SPR::MQ] = ROTL_32(ppc_result_d, rot_sh); ppc_state.spr[SPR::MQ] = rot_sh ? ((ppc_result_d << rot_sh) | (ppc_result_d >> (32 - rot_sh))) : ppc_result_d;
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
@@ -389,16 +403,17 @@ void dppc_interpreter::power_sle(uint32_t opcode) {
ppc_changecrf0(ppc_result_a); ppc_changecrf0(ppc_result_a);
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
return 0;
} }
template void dppc_interpreter::power_sle<RC0>(uint32_t opcode); template uint32_t dppc_interpreter::power_sle<RC0>(uint32_t opcode);
template void dppc_interpreter::power_sle<RC1>(uint32_t opcode); template uint32_t dppc_interpreter::power_sle<RC1>(uint32_t opcode);
template <field_rc rec> template <field_rc rec>
void dppc_interpreter::power_sleq(uint32_t opcode) { uint32_t dppc_interpreter::power_sleq(uint32_t opcode) {
ppc_grab_regssab(opcode); ppc_grab_regssab(opcode);
unsigned rot_sh = ppc_result_b & 0x1F; unsigned rot_sh = ppc_result_b & 0x1F;
uint32_t r = ROTL_32(ppc_result_d, rot_sh); uint32_t r = rot_sh ? ((ppc_result_d << rot_sh) | (ppc_result_d >> (32 - rot_sh))) : ppc_result_d;
uint32_t mask = power_rot_mask(0, 31 - rot_sh); uint32_t mask = power_rot_mask(0, 31 - rot_sh);
ppc_result_a = ((r & mask) | (ppc_state.spr[SPR::MQ] & ~mask)); ppc_result_a = ((r & mask) | (ppc_state.spr[SPR::MQ] & ~mask));
@@ -408,31 +423,33 @@ void dppc_interpreter::power_sleq(uint32_t opcode) {
ppc_changecrf0(ppc_result_a); ppc_changecrf0(ppc_result_a);
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
return 0;
} }
template void dppc_interpreter::power_sleq<RC0>(uint32_t opcode); template uint32_t dppc_interpreter::power_sleq<RC0>(uint32_t opcode);
template void dppc_interpreter::power_sleq<RC1>(uint32_t opcode); template uint32_t dppc_interpreter::power_sleq<RC1>(uint32_t opcode);
template <field_rc rec> template <field_rc rec>
void dppc_interpreter::power_sliq(uint32_t opcode) { uint32_t dppc_interpreter::power_sliq(uint32_t opcode) {
ppc_grab_regssash(opcode); ppc_grab_regssash(opcode);
ppc_result_a = ppc_result_d << rot_sh; ppc_result_a = ppc_result_d << rot_sh;
ppc_state.spr[SPR::MQ] = ROTL_32(ppc_result_d, rot_sh); ppc_state.spr[SPR::MQ] = rot_sh ? ((ppc_result_d << rot_sh) | (ppc_result_d >> (32 - rot_sh))) : ppc_result_d;
if (rec) if (rec)
ppc_changecrf0(ppc_result_a); ppc_changecrf0(ppc_result_a);
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
return 0;
} }
template void dppc_interpreter::power_sliq<RC0>(uint32_t opcode); template uint32_t dppc_interpreter::power_sliq<RC0>(uint32_t opcode);
template void dppc_interpreter::power_sliq<RC1>(uint32_t opcode); template uint32_t dppc_interpreter::power_sliq<RC1>(uint32_t opcode);
template <field_rc rec> template <field_rc rec>
void dppc_interpreter::power_slliq(uint32_t opcode) { uint32_t dppc_interpreter::power_slliq(uint32_t opcode) {
ppc_grab_regssash(opcode); ppc_grab_regssash(opcode);
uint32_t r = ROTL_32(ppc_result_d, rot_sh); uint32_t r = rot_sh ? ((ppc_result_d << rot_sh) | (ppc_result_d >> (32 - rot_sh))) : ppc_result_d;
uint32_t mask = power_rot_mask(0, 31 - rot_sh); uint32_t mask = power_rot_mask(0, 31 - rot_sh);
ppc_result_a = ((r & mask) | (ppc_state.spr[SPR::MQ] & ~mask)); ppc_result_a = ((r & mask) | (ppc_state.spr[SPR::MQ] & ~mask));
@@ -442,13 +459,14 @@ void dppc_interpreter::power_slliq(uint32_t opcode) {
ppc_changecrf0(ppc_result_a); ppc_changecrf0(ppc_result_a);
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
return 0;
} }
template void dppc_interpreter::power_slliq<RC0>(uint32_t opcode); template uint32_t dppc_interpreter::power_slliq<RC0>(uint32_t opcode);
template void dppc_interpreter::power_slliq<RC1>(uint32_t opcode); template uint32_t dppc_interpreter::power_slliq<RC1>(uint32_t opcode);
template <field_rc rec> template <field_rc rec>
void dppc_interpreter::power_sllq(uint32_t opcode) { uint32_t dppc_interpreter::power_sllq(uint32_t opcode) {
ppc_grab_regssab(opcode); ppc_grab_regssab(opcode);
unsigned rot_sh = ppc_result_b & 0x1F; unsigned rot_sh = ppc_result_b & 0x1F;
@@ -462,13 +480,14 @@ void dppc_interpreter::power_sllq(uint32_t opcode) {
ppc_changecrf0(ppc_result_a); ppc_changecrf0(ppc_result_a);
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
return 0;
} }
template void dppc_interpreter::power_sllq<RC0>(uint32_t opcode); template uint32_t dppc_interpreter::power_sllq<RC0>(uint32_t opcode);
template void dppc_interpreter::power_sllq<RC1>(uint32_t opcode); template uint32_t dppc_interpreter::power_sllq<RC1>(uint32_t opcode);
template <field_rc rec> template <field_rc rec>
void dppc_interpreter::power_slq(uint32_t opcode) { uint32_t dppc_interpreter::power_slq(uint32_t opcode) {
ppc_grab_regssab(opcode); ppc_grab_regssab(opcode);
unsigned rot_sh = ppc_result_b & 0x1F; unsigned rot_sh = ppc_result_b & 0x1F;
@@ -481,19 +500,20 @@ void dppc_interpreter::power_slq(uint32_t opcode) {
if (rec) if (rec)
ppc_changecrf0(ppc_result_a); ppc_changecrf0(ppc_result_a);
ppc_state.spr[SPR::MQ] = ROTL_32(ppc_result_d, rot_sh); ppc_state.spr[SPR::MQ] = rot_sh ? ((ppc_result_d << rot_sh) | (ppc_result_d >> (32 - rot_sh))) : ppc_result_d;
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
return 0;
} }
template void dppc_interpreter::power_slq<RC0>(uint32_t opcode); template uint32_t dppc_interpreter::power_slq<RC0>(uint32_t opcode);
template void dppc_interpreter::power_slq<RC1>(uint32_t opcode); template uint32_t dppc_interpreter::power_slq<RC1>(uint32_t opcode);
template <field_rc rec> template <field_rc rec>
void dppc_interpreter::power_sraiq(uint32_t opcode) { uint32_t dppc_interpreter::power_sraiq(uint32_t opcode) {
ppc_grab_regssash(opcode); ppc_grab_regssash(opcode);
uint32_t mask = (1U << rot_sh) - 1; uint32_t mask = (1U << rot_sh) - 1;
ppc_result_a = (int32_t)ppc_result_d >> rot_sh; ppc_result_a = (int32_t)ppc_result_d >> rot_sh;
ppc_state.spr[SPR::MQ] = ROTR_32(ppc_result_d, rot_sh); ppc_state.spr[SPR::MQ] = rot_sh ? ((ppc_result_d >> rot_sh) | (ppc_result_d << (32 - rot_sh))) : ppc_result_d;
if ((int32_t(ppc_result_d) < 0) && (ppc_result_d & mask)) { if ((int32_t(ppc_result_d) < 0) && (ppc_result_d & mask)) {
ppc_state.spr[SPR::XER] |= XER::CA; ppc_state.spr[SPR::XER] |= XER::CA;
@@ -505,18 +525,19 @@ void dppc_interpreter::power_sraiq(uint32_t opcode) {
ppc_changecrf0(ppc_result_a); ppc_changecrf0(ppc_result_a);
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
return 0;
} }
template void dppc_interpreter::power_sraiq<RC0>(uint32_t opcode); template uint32_t dppc_interpreter::power_sraiq<RC0>(uint32_t opcode);
template void dppc_interpreter::power_sraiq<RC1>(uint32_t opcode); template uint32_t dppc_interpreter::power_sraiq<RC1>(uint32_t opcode);
template <field_rc rec> template <field_rc rec>
void dppc_interpreter::power_sraq(uint32_t opcode) { uint32_t dppc_interpreter::power_sraq(uint32_t opcode) {
ppc_grab_regssab(opcode); ppc_grab_regssab(opcode);
unsigned rot_sh = ppc_result_b & 0x1F; unsigned rot_sh = ppc_result_b & 0x1F;
uint32_t mask = (ppc_result_b & 0x20) ? -1 : (1U << rot_sh) - 1; uint32_t mask = (ppc_result_b & 0x20) ? -1 : (1U << rot_sh) - 1;
ppc_result_a = (int32_t)ppc_result_d >> ((ppc_result_b & 0x20) ? 31 : rot_sh); ppc_result_a = (int32_t)ppc_result_d >> ((ppc_result_b & 0x20) ? 31 : rot_sh);
ppc_state.spr[SPR::MQ] = ROTL_32(ppc_result_d, rot_sh); ppc_state.spr[SPR::MQ] = rot_sh ? ((ppc_result_d << rot_sh) | (ppc_result_d >> (32 - rot_sh))) : ppc_result_d;
if ((int32_t(ppc_result_d) < 0) && (ppc_result_d & mask)) { if ((int32_t(ppc_result_d) < 0) && (ppc_result_d & mask)) {
ppc_state.spr[SPR::XER] |= XER::CA; ppc_state.spr[SPR::XER] |= XER::CA;
@@ -524,41 +545,43 @@ void dppc_interpreter::power_sraq(uint32_t opcode) {
ppc_state.spr[SPR::XER] &= ~XER::CA; ppc_state.spr[SPR::XER] &= ~XER::CA;
} }
ppc_state.spr[SPR::MQ] = ROTR_32(ppc_result_d, rot_sh); ppc_state.spr[SPR::MQ] = rot_sh ? ((ppc_result_d >> rot_sh) | (ppc_result_d << (32 - rot_sh))) : ppc_result_d;
if (rec) if (rec)
ppc_changecrf0(ppc_result_a); ppc_changecrf0(ppc_result_a);
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
return 0;
} }
template void dppc_interpreter::power_sraq<RC0>(uint32_t opcode); template uint32_t dppc_interpreter::power_sraq<RC0>(uint32_t opcode);
template void dppc_interpreter::power_sraq<RC1>(uint32_t opcode); template uint32_t dppc_interpreter::power_sraq<RC1>(uint32_t opcode);
template <field_rc rec> template <field_rc rec>
void dppc_interpreter::power_sre(uint32_t opcode) { uint32_t dppc_interpreter::power_sre(uint32_t opcode) {
ppc_grab_regssab(opcode); ppc_grab_regssab(opcode);
unsigned rot_sh = ppc_result_b & 0x1F; unsigned rot_sh = ppc_result_b & 0x1F;
ppc_result_a = ppc_result_d >> rot_sh; ppc_result_a = ppc_result_d >> rot_sh;
ppc_state.spr[SPR::MQ] = ROTR_32(ppc_result_d, rot_sh); ppc_state.spr[SPR::MQ] = rot_sh ? ((ppc_result_d >> rot_sh) | (ppc_result_d << (32 - rot_sh))) : ppc_result_d;
if (rec) if (rec)
ppc_changecrf0(ppc_result_a); ppc_changecrf0(ppc_result_a);
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
return 0;
} }
template void dppc_interpreter::power_sre<RC0>(uint32_t opcode); template uint32_t dppc_interpreter::power_sre<RC0>(uint32_t opcode);
template void dppc_interpreter::power_sre<RC1>(uint32_t opcode); template uint32_t dppc_interpreter::power_sre<RC1>(uint32_t opcode);
template <field_rc rec> template <field_rc rec>
void dppc_interpreter::power_srea(uint32_t opcode) { uint32_t dppc_interpreter::power_srea(uint32_t opcode) {
ppc_grab_regssab(opcode); ppc_grab_regssab(opcode);
unsigned rot_sh = ppc_result_b & 0x1F; unsigned rot_sh = ppc_result_b & 0x1F;
ppc_result_a = (int32_t)ppc_result_d >> rot_sh; ppc_result_a = (int32_t)ppc_result_d >> rot_sh;
uint32_t r = ROTR_32(ppc_result_d, rot_sh); uint32_t r = (rot_sh ? ((ppc_result_d >> rot_sh) | (ppc_result_d << (32 - rot_sh))) : ppc_result_d);
uint32_t mask = -1U >> rot_sh; uint32_t mask = -1U >> rot_sh;
if ((int32_t(ppc_result_d) < 0) && (r & ~mask)) { if ((int32_t(ppc_result_d) < 0) && (r & ~mask)) {
@@ -572,48 +595,51 @@ void dppc_interpreter::power_srea(uint32_t opcode) {
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
ppc_state.spr[SPR::MQ] = r; ppc_state.spr[SPR::MQ] = r;
return 0;
} }
template void dppc_interpreter::power_srea<RC0>(uint32_t opcode); template uint32_t dppc_interpreter::power_srea<RC0>(uint32_t opcode);
template void dppc_interpreter::power_srea<RC1>(uint32_t opcode); template uint32_t dppc_interpreter::power_srea<RC1>(uint32_t opcode);
template <field_rc rec> template <field_rc rec>
void dppc_interpreter::power_sreq(uint32_t opcode) { uint32_t dppc_interpreter::power_sreq(uint32_t opcode) {
ppc_grab_regssab(opcode); ppc_grab_regssab(opcode);
unsigned rot_sh = ppc_result_b & 0x1F; unsigned rot_sh = ppc_result_b & 0x1F;
uint32_t mask = -1U >> rot_sh; uint32_t mask = -1U >> rot_sh;
ppc_result_a = (ppc_result_d >> rot_sh) | (ppc_state.spr[SPR::MQ] & ~mask); ppc_result_a = (ppc_result_d >> rot_sh) | (ppc_state.spr[SPR::MQ] & ~mask);
ppc_state.spr[SPR::MQ] = ROTR_32(ppc_result_d, rot_sh); ppc_state.spr[SPR::MQ] = rot_sh ? ((ppc_result_d >> rot_sh) | (ppc_result_d << (32 - rot_sh))) : ppc_result_d;
if (rec) if (rec)
ppc_changecrf0(ppc_result_a); ppc_changecrf0(ppc_result_a);
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
return 0;
} }
template void dppc_interpreter::power_sreq<RC0>(uint32_t opcode); template uint32_t dppc_interpreter::power_sreq<RC0>(uint32_t opcode);
template void dppc_interpreter::power_sreq<RC1>(uint32_t opcode); template uint32_t dppc_interpreter::power_sreq<RC1>(uint32_t opcode);
template <field_rc rec> template <field_rc rec>
void dppc_interpreter::power_sriq(uint32_t opcode) { uint32_t dppc_interpreter::power_sriq(uint32_t opcode) {
ppc_grab_regssash(opcode); ppc_grab_regssash(opcode);
ppc_result_a = ppc_result_d >> rot_sh; ppc_result_a = ppc_result_d >> rot_sh;
ppc_state.spr[SPR::MQ] = ROTR_32(ppc_result_d, rot_sh); ppc_state.spr[SPR::MQ] = rot_sh ? ((ppc_result_d >> rot_sh) | (ppc_result_d << (32 - rot_sh))) : ppc_result_d;
if (rec) if (rec)
ppc_changecrf0(ppc_result_a); ppc_changecrf0(ppc_result_a);
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
return 0;
} }
template void dppc_interpreter::power_sriq<RC0>(uint32_t opcode); template uint32_t dppc_interpreter::power_sriq<RC0>(uint32_t opcode);
template void dppc_interpreter::power_sriq<RC1>(uint32_t opcode); template uint32_t dppc_interpreter::power_sriq<RC1>(uint32_t opcode);
template <field_rc rec> template <field_rc rec>
void dppc_interpreter::power_srliq(uint32_t opcode) { uint32_t dppc_interpreter::power_srliq(uint32_t opcode) {
ppc_grab_regssash(opcode); ppc_grab_regssash(opcode);
uint32_t r = ROTR_32(ppc_result_d, rot_sh); uint32_t r = rot_sh ? ((ppc_result_d >> rot_sh) | (ppc_result_d << (32 - rot_sh))) : ppc_result_d;
unsigned mask = power_rot_mask(rot_sh, 31); unsigned mask = power_rot_mask(rot_sh, 31);
ppc_result_a = ((r & mask) | (ppc_state.spr[SPR::MQ] & ~mask)); ppc_result_a = ((r & mask) | (ppc_state.spr[SPR::MQ] & ~mask));
@@ -623,16 +649,17 @@ void dppc_interpreter::power_srliq(uint32_t opcode) {
ppc_changecrf0(ppc_result_a); ppc_changecrf0(ppc_result_a);
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
return 0;
} }
template void dppc_interpreter::power_srliq<RC0>(uint32_t opcode); template uint32_t dppc_interpreter::power_srliq<RC0>(uint32_t opcode);
template void dppc_interpreter::power_srliq<RC1>(uint32_t opcode); template uint32_t dppc_interpreter::power_srliq<RC1>(uint32_t opcode);
template <field_rc rec> template <field_rc rec>
void dppc_interpreter::power_srlq(uint32_t opcode) { uint32_t dppc_interpreter::power_srlq(uint32_t opcode) {
ppc_grab_regssab(opcode); ppc_grab_regssab(opcode);
unsigned rot_sh = ppc_result_b & 0x1F; unsigned rot_sh = ppc_result_b & 0x1F;
uint32_t r = ROTR_32(ppc_result_d, rot_sh); uint32_t r = rot_sh ? ((ppc_result_d >> rot_sh) | (ppc_result_d << (32 - rot_sh))) : ppc_result_d;
unsigned mask = power_rot_mask(rot_sh, 31); unsigned mask = power_rot_mask(rot_sh, 31);
if (ppc_result_b & 0x20) { if (ppc_result_b & 0x20) {
@@ -645,13 +672,14 @@ void dppc_interpreter::power_srlq(uint32_t opcode) {
ppc_changecrf0(ppc_result_a); ppc_changecrf0(ppc_result_a);
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
return 0;
} }
template void dppc_interpreter::power_srlq<RC0>(uint32_t opcode); template uint32_t dppc_interpreter::power_srlq<RC0>(uint32_t opcode);
template void dppc_interpreter::power_srlq<RC1>(uint32_t opcode); template uint32_t dppc_interpreter::power_srlq<RC1>(uint32_t opcode);
template <field_rc rec> template <field_rc rec>
void dppc_interpreter::power_srq(uint32_t opcode) { uint32_t dppc_interpreter::power_srq(uint32_t opcode) {
ppc_grab_regssab(opcode); ppc_grab_regssab(opcode);
unsigned rot_sh = ppc_result_b & 0x1F; unsigned rot_sh = ppc_result_b & 0x1F;
@@ -661,13 +689,14 @@ void dppc_interpreter::power_srq(uint32_t opcode) {
ppc_result_a = ppc_result_d >> rot_sh; ppc_result_a = ppc_result_d >> rot_sh;
} }
ppc_state.spr[SPR::MQ] = ROTR_32(ppc_result_d, rot_sh); ppc_state.spr[SPR::MQ] = rot_sh ? ((ppc_result_d >> rot_sh) | (ppc_result_d << (32 - rot_sh))) : ppc_result_d;
if (rec) if (rec)
ppc_changecrf0(ppc_result_a); ppc_changecrf0(ppc_result_a);
ppc_store_iresult_reg(reg_a, ppc_result_a); ppc_store_iresult_reg(reg_a, ppc_result_a);
return 0;
} }
template void dppc_interpreter::power_srq<RC0>(uint32_t opcode); template uint32_t dppc_interpreter::power_srq<RC0>(uint32_t opcode);
template void dppc_interpreter::power_srq<RC1>(uint32_t opcode); template uint32_t dppc_interpreter::power_srq<RC1>(uint32_t opcode);
-215
View File
@@ -1,215 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team
(See CREDITS.MD for more details)
(You may also contact divingkxt or powermax2286 on Discord)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef PPC_DECODE_HELPERS_H
#define PPC_DECODE_HELPERS_H
#include <cinttypes>
// ============== Helpers for extracting operands from opcodes ================
#define decode_ops_sa(opcode) \
int reg_s = (opcode >> 21) & 0x1F; \
int reg_a = (opcode >> 16) & 0x1F;
#define decode_ops_da(opcode) \
int reg_d = (opcode >> 21) & 0x1F; \
int reg_a = (opcode >> 16) & 0x1F;
#define decode_ops_sab(opcode) \
decode_ops_sa(opcode); \
int reg_b = (opcode >> 11) & 0x1F;
#define decode_ops_dab(opcode) \
decode_ops_da(opcode); \
int reg_b = (opcode >> 11) & 0x1F;
#define decode_ops_dasimm(opcode) \
decode_ops_da(opcode); \
int32_t simm = int32_t(int16_t(opcode));
#define decode_ops_sauimm(opcode) \
decode_ops_sa(opcode); \
uint32_t uimm = uint16_t(opcode);
#define decode_ops_dauimm(opcode) \
decode_ops_da(opcode); \
uint32_t uimm = uint16_t(opcode);
// ================= Helpers for the original interpreter =====================
// The helpers below do the same work as those above but also pre-load some
// register values and place them into local variables.
// That significantly reduces interpreter code.
#define ppc_grab_regsdasimm(opcode) \
decode_ops_dasimm(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsdauimm(opcode) \
decode_ops_dauimm(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsasimm(opcode) \
int reg_a = (opcode >> 16) & 0x1F; \
int32_t simm = int32_t(int16_t(opcode)); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssauimm(opcode) \
decode_ops_sauimm(opcode); \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_crfd_regsauimm(opcode) \
int crf_d = (opcode >> 21) & 0x1C; \
int reg_a = (opcode >> 16) & 0x1F; \
uint32_t uimm = uint16_t(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_da(opcode) \
decode_ops_da(opcode)
#define ppc_grab_dab(opcode) \
decode_ops_dab(opcode)
#define ppc_grab_s(opcode) \
int reg_s = (opcode >> 21) & 0x1F; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s];
#define ppc_grab_regsdab(opcode) \
decode_ops_dab(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regssab(opcode) \
decode_ops_sab(opcode); \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regssab_stswx(opcode) \
decode_ops_sab(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regsab(opcode) \
int reg_a = (opcode >> 16) & 0x1F; \
int reg_b = (opcode >> 11) & 0x1F; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regssa(opcode) \
decode_ops_sa(opcode); \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssa_stmw(opcode) \
decode_ops_sa(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssash(opcode) \
decode_ops_sa(opcode); \
unsigned rot_sh = (opcode >> 11) & 0x1F; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssash_stswi(opcode) \
decode_ops_sa(opcode); \
unsigned rot_sh = (opcode >> 11) & 0x1F; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssb(opcode) \
int reg_s = (opcode >> 21) & 0x1F; \
int reg_b = (opcode >> 11) & 0x1F; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regsda(opcode) \
decode_ops_da(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsdb(opcode) \
int reg_d = (opcode >> 21) & 0x1F; \
uint32_t reg_b = (opcode >> 11) & 0x1F; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regsfpdb(opcode) \
int reg_d = (opcode >> 21) & 0x1F; \
int reg_b = (opcode >> 11) & 0x1F;
#define ppc_grab_regsfpdiab(opcode) \
decode_ops_dab(opcode); \
uint32_t val_reg_a = ppc_state.gpr[reg_a]; \
uint32_t val_reg_b = ppc_state.gpr[reg_b];
#define ppc_grab_regsfpdia(opcode) \
decode_ops_da(opcode); \
uint32_t val_reg_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsfpsia(opcode) \
decode_ops_sa(opcode); \
uint32_t val_reg_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsfpsiab(opcode) \
decode_ops_sab(opcode); \
uint32_t val_reg_a = ppc_state.gpr[reg_a]; \
uint32_t val_reg_b = ppc_state.gpr[reg_b];
#define ppc_grab_regsfpsab(opcode) \
int reg_a = (opcode >> 16) & 0x1F; \
int reg_b = (opcode >> 11) & 0x1F; \
int crf_d = (opcode >> 21) & 0x1C; \
double db_test_a = GET_FPR(reg_a); \
double db_test_b = GET_FPR(reg_b);
#define ppc_grab_regsfpdab(opcode) \
decode_ops_dab(opcode); \
double val_reg_a = GET_FPR(reg_a); \
double val_reg_b = GET_FPR(reg_b);
#define ppc_grab_regsfpdac(opcode) \
decode_ops_da(opcode); \
int reg_c = (opcode >> 6) & 0x1F; \
double val_reg_a = GET_FPR(reg_a); \
double val_reg_c = GET_FPR(reg_c);
#define ppc_grab_regsfpdabc(opcode) \
decode_ops_dab(opcode); \
int reg_c = (opcode >> 6) & 0x1F; \
double val_reg_a = GET_FPR(reg_a); \
double val_reg_b = GET_FPR(reg_b); \
double val_reg_c = GET_FPR(reg_c);
#define ppc_store_iresult_reg(reg, ppc_result) \
ppc_state.gpr[reg] = ppc_result
#define ppc_store_fpresult_int(reg, ppc_result64_d) \
ppc_state.fpr[(reg)].int64_r = ppc_result64_d
#define ppc_store_fpresult_flt(reg, ppc_dblresult64_d) \
ppc_state.fpr[(reg)].dbl64_r = ppc_dblresult64_d
#define GET_FPR(reg) \
ppc_state.fpr[(reg)].dbl64_r
#define FPR_INT(reg) \
ppc_state.fpr[reg].int64_r
#endif // PPC_DECODE_HELPERS_H
+15 -22
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -253,15 +253,15 @@ const char* trap_cond[32] = {/*Trap conditions*/
"twlt", "", "", "", "twle", "", "", "", "twlt", "", "", "", "twle", "", "", "",
"twne", "", "", "", "", "", "", ""}; "twne", "", "", "", "", "", "", ""};
const char* spr_index0[32] = {"mq", "xer", "", "", "rtcu", "rtcl", "dec", "", const char* spr_index0[32] = {"mq", "xer", "", "", "rtcu", "rtcl", "", "",
"lr", "ctr", "", "", "", "", "", "", "lr", "ctr", "", "", "", "", "", "",
"", "", "dsisr", "dar", "rtcu", "rtcl", "dec", "", "", "", "dsisr", "dar", "", "", "dec", "",
"", "sdr1", "srr0", "srr1", "", "", "", ""}; "", "sdr1", "srr0", "srr1", "", "", "", ""};
const char* spr_index8[32] = { const char* spr_index8[32] = {
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "tbl_u", "tbu_u", "", "", "sprg0", "sprg1", "sprg2", "sprg3", "sprg4", "sprg5", "", "", "", "", "", "sprg0", "sprg1", "sprg2", "sprg3", "sprg4", "sprg5",
"sprg6", "sprg7", "", "", "ear", "", "tbl", "tbu", "", "pvr"}; "sprg6", "sprg7", "", "", "ear", "", "tbl", "tbu", "", "pvr"};
const char* spr_index16[32] = { const char* spr_index16[32] = {
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
@@ -392,13 +392,6 @@ void fmt_rotateop(PPCDisasmContext* ctx, const char* opc, int dst, int src, int
} }
} }
void fmt_rotateinsert(PPCDisasmContext* ctx, const char* opc, int dst, int src, int sh, int mb, int me) {
ctx->instr_str = my_sprintf("%-7s r%d, r%d, %d, %d, %d", opc, dst, src, sh, mb, me);
add_reg_in(ctx, "r%d", dst);
add_reg_in(ctx, "r%d", src);
add_reg_out(ctx, "r%d", dst);
}
/* Opcodes */ /* Opcodes */
void opc_illegal(PPCDisasmContext* ctx) { void opc_illegal(PPCDisasmContext* ctx) {
@@ -529,7 +522,7 @@ void opc_rlwimi(PPCDisasmContext* ctx) {
add_reg_out(ctx, "cr"); add_reg_out(ctx, "cr");
} }
fmt_rotateinsert(ctx, opcode, ra, rs, sh, mb, me); fmt_rotateop(ctx, opcode, ra, rs, sh, mb, me, true);
} }
void opc_rlwinm(PPCDisasmContext* ctx) { void opc_rlwinm(PPCDisasmContext* ctx) {
@@ -1183,14 +1176,14 @@ void opc_group31(PPCDisasmContext* ctx) {
if (!rs && !ra) if (!rs && !ra)
opc_illegal(ctx); opc_illegal(ctx);
else { else {
ctx->instr_str = my_sprintf("%-7s r%d", "tlbld", rb); ctx->instr_str = my_sprintf("%-7s r%s", "tlbld", rb);
add_reg_in(ctx, "r%d", rb); add_reg_in(ctx, "r%d", rb);
} }
} else if (index == 31) { /* tlbli - 603 only */ } else if (index == 30) { /* tlbli - 603 only */
if (!rs && !ra) if (!rs && !ra)
opc_illegal(ctx); opc_illegal(ctx);
else { else {
ctx->instr_str = my_sprintf("%-7s r%d", "tlbli", rb); ctx->instr_str = my_sprintf("%-7s r%s", "tlbli", rb);
add_reg_in(ctx, "r%d", rb); add_reg_in(ctx, "r%d", rb);
} }
} }
@@ -1257,10 +1250,10 @@ void opc_group31(PPCDisasmContext* ctx) {
add_reg_out(ctx, "cr"); add_reg_out(ctx, "cr");
} }
} else { } else {
if (index >= 16 || !strlen(opc_logic[index])) { strcpy(opcode, opc_logic[index]);
if (!strlen(opcode)) {
opc_illegal(ctx); opc_illegal(ctx);
} else { } else {
strcpy(opcode, opc_logic[index]);
if (rc_set) { if (rc_set) {
strcat(opcode, "."); strcat(opcode, ".");
add_reg_out(ctx, "cr"); add_reg_out(ctx, "cr");
@@ -1401,9 +1394,9 @@ void opc_group31(PPCDisasmContext* ctx) {
break; break;
} }
auto ref_spr = (((ctx->instr_code >> 11) & 31) << 5) | ((ctx->instr_code >> 16) & 31);
auto spr_high = (ctx->instr_code >> 11) & 31; auto spr_high = (ctx->instr_code >> 11) & 31;
auto spr_low = (ctx->instr_code >> 16) & 31; auto spr_low = (ctx->instr_code >> 16) & 31;
auto ref_spr = (spr_high << 5) | spr_low;
switch (ext_opc) { switch (ext_opc) {
case 0: /* cmp */ case 0: /* cmp */
+3 -3
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-21 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
+232 -347
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -22,9 +22,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef PPCEMU_H #ifndef PPCEMU_H
#define PPCEMU_H #define PPCEMU_H
#include <core/endianswap.h>
#include <core/memaccess.h>
#include <devices/memctrl/memctrlbase.h> #include <devices/memctrl/memctrlbase.h>
#include <endianswap.h>
#include <memaccess.h>
#include <atomic> #include <atomic>
#include <cinttypes> #include <cinttypes>
@@ -37,9 +37,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
//#define CPU_PROFILING // enable CPU profiling //#define CPU_PROFILING // enable CPU profiling
// Uncomment this to enable logging of executed instructions.
//#define LOG_INSTRUCTIONS
/** type of compiler used during execution */ /** type of compiler used during execution */
enum EXEC_MODE:uint32_t { enum EXEC_MODE:uint32_t {
interpreter = 0, interpreter = 0,
@@ -48,9 +45,9 @@ enum EXEC_MODE:uint32_t {
jit = 3 jit = 3
}; };
typedef enum { big_end = 0, little_end = 1 } endian_switch; enum endian_switch { big_end = 0, little_end = 1 };
typedef void (*PPCOpcode)(uint32_t opcode); typedef uint32_t (*PPCOpcode)(uint32_t opcode);
union FPR_storage { union FPR_storage {
double dbl64_r; // double floating-point representation double dbl64_r; // double floating-point representation
@@ -82,9 +79,6 @@ typedef struct struct_ppc_state {
uint32_t msr; uint32_t msr;
uint32_t sr[16]; uint32_t sr[16];
bool reserve; // reserve bit used for lwarx and stcwx bool reserve; // reserve bit used for lwarx and stcwx
#if SUPPORTS_PPC_LITTLE_ENDIAN_MODE
bool is_LE;
#endif
} SetPRS; } SetPRS;
extern SetPRS ppc_state; extern SetPRS ppc_state;
@@ -112,7 +106,6 @@ enum SPR : int {
SPRG1 = 273, SPRG1 = 273,
SPRG2 = 274, SPRG2 = 274,
SPRG3 = 275, SPRG3 = 275,
EAR = 282,
TBL_S = 284, // supervisor TBL TBL_S = 284, // supervisor TBL
TBU_S = 285, // supervisor TBU TBU_S = 285, // supervisor TBU
PVR = 287, PVR = 287,
@@ -121,14 +114,9 @@ enum SPR : int {
PMC2 = 954, PMC2 = 954,
SIA = 955, SIA = 955,
MMCR1 = 956, MMCR1 = 956,
PMC3 = 957,
PMC4 = 958,
SDA = 959, SDA = 959,
HID0 = 1008, HID0 = 1008,
HID1 = 1009, HID1 = 1009,
THRM1 = 1020,
THRM2 = 1021,
THRM3 = 1022,
}; };
/** symbolic names for common PPC processors */ /** symbolic names for common PPC processors */
@@ -182,23 +170,21 @@ SUPERVISOR MODEL
536 - 543 are the Data BAT registers 536 - 543 are the Data BAT registers
**/ **/
extern uint64_t timebase_counter;
extern uint64_t tbr_wr_timestamp; extern uint64_t tbr_wr_timestamp;
extern uint64_t dec_wr_timestamp; extern uint64_t dec_wr_timestamp;
extern uint64_t rtc_timestamp; extern uint64_t rtc_timestamp;
extern uint64_t tbr_wr_value; extern uint64_t tbr_wr_value;
extern uint32_t dec_wr_value; extern uint32_t dec_wr_value;
extern uint32_t tbr_freq_ghz; extern uint32_t tbr_freq_ghz;
extern uint32_t tbr_freq_shift;
extern uint64_t tbr_period_ns; extern uint64_t tbr_period_ns;
extern uint32_t rtc_lo, rtc_hi; extern uint32_t rtc_lo, rtc_hi;
/* Flags for controlling interpreter execution. */ /* Flags for controlling interpreter execution. */
enum { enum {
EXEF_BRANCH = 1 << 0, // Branch taken, target PC is is in ppc_next_instruction_address EXEF_BRANCH = 1 << 0,
EXEF_EXCEPTION = 1 << 1, // Exception handler invoked EXEF_EXCEPTION = 1 << 1,
EXEF_RFI = 1 << 2, // RFI instruction executed EXEF_RFI = 1 << 2,
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 { enum CR_select : int32_t {
@@ -257,54 +243,22 @@ enum FPSCR : uint32_t {
FX = 1UL << 31 FX = 1UL << 31
}; };
/** Bit definitions for the Machine State Register (MSR). */
enum MSR : int { enum MSR : int {
// ---------------------------------------------------------------------------------------- LE = 0x1, //little endian mode
// 64-bit // 32-bit // Notes for MPC601 (601), PowerPC (PPC), RI = 0x2,
// // // MPC750 (750), Altivec (AV), Power ISA (ISA) DR = 0x10,
// ---------------------------------------------------------------------------------------- IR = 0x20,
LE = (1 << (63 - 63)), // 31 // Little-endian mode enable (not 601); IP = 0x40,
// Little-Endian Mode (ISA) FE1 = 0x100,
RI = (1 << (63 - 62)), // 30 // Recoverable exception (not 601); BE = 0x200,
// Recoverable Interrupt (ISA) SE = 0x400,
PM = (1 << (63 - 61)), // 29 // Performance monitor marked mode (750); FE0 = 0x800,
// Performance Monitor Mark (PMM for ISA) ME = 0x1000,
// = (1 << (63 - 60)), // 28 // Reserved FP = 0x2000,
DR = (1 << (63 - 59)), // 27 // Data address translation (DT on 601); PR = 0x4000,
// Data Relocate (ISA) EE = 0x8000, //external interrupt
IR = (1 << (63 - 58)), // 26 // Instruction address translation (IT on 601); ILE = 0x10000,
// Instruction Relocate (ISA) POW = 0x40000
IP = (1 << (63 - 57)), // 25 // Exception prefix (EP); Reserved (ISA)
// = (1 << (63 - 56)), // 24 // Reserved (AL for POWER)
FE1 = (1 << (63 - 55)), // 23 // Floating-point exception mode 1
BE = (1 << (63 - 54)), // 22 // Branch trace enable (Optional, not 601);
// Trace Enable (TE): Branch Trace (ISA)
SE = (1 << (63 - 53)), // 21 // Single-step trace enable (Optional);
// Trace Enable (TE): Single Step Trace (ISA)
FE0 = (1 << (63 - 52)), // 20 // Floating-point exception mode 0
ME = (1 << (63 - 51)), // 19 // Machine check enable;
// Machine Check Interrupt Enable (ISA)
FP = (1 << (63 - 50)), // 18 // Floating-point available
PR = (1 << (63 - 49)), // 17 // Privilege level; Problem State (ISA)
EE = (1 << (63 - 48)), // 16 // External exception enable (601);
// External interrupt enable
// ----------------------------------------------------------------------------------------
ILE = (1 << (63 - 47)), // 15 // Exception little-endian mode (not 601, not ISA)
TGPR = (1 << (63 - 46)), // 14 // Temporary GPR remapping (603e)
POW = (1 << (63 - 45)), // 13 // Power management enable (not 601, not ISA)
// = (1 << (63 - 44)), // 12 // Reserved
// = (1 << (63 - 42)), // 10 // Reserved
// S = (1 << (63 - 41)), // 9 // Secure (ISA)
// VSX = (1 << (63 - 40)), // 8 // VSX Available (ISA)
// = (1 << (63 - 39)), // 7 // Reserved
VEC = (1 << (63 - 38)), // 6 // AltiVec available (AV); Vector Available (ISA)
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// HV = (1ULL << (63 - 3)), // // Hypervisor State (ISA)
// ISF = (1ULL << (63 - 2)), // // Exception 64-bit mode (optional, PPC)
// = (1ULL << (63 - 1)), // // Reserved
// SF = (1ULL << (63 - 0)), // // Sixty-four bit mode (PowerPC, PowerISA)
// ----------------------------------------------------------------------------------------
}; };
enum XER : uint32_t { enum XER : uint32_t {
@@ -324,22 +278,17 @@ enum FPOP : int {
/** PowerPC exception types. */ /** PowerPC exception types. */
enum class Except_Type { enum class Except_Type {
EXC_SYSTEM_RESET = 0x01, EXC_SYSTEM_RESET = 1,
EXC_MACHINE_CHECK = 0x02, EXC_MACHINE_CHECK,
EXC_DSI = 0x03, EXC_DSI,
EXC_ISI = 0x04, EXC_ISI,
EXC_EXT_INT = 0x05, EXC_EXT_INT,
EXC_ALIGNMENT = 0x06, EXC_ALIGNMENT,
EXC_PROGRAM = 0x07, EXC_PROGRAM,
EXC_NO_FPU = 0x08, EXC_NO_FPU,
EXC_DECR = 0x09, EXC_DECR,
EXC_SYSCALL = 0x0C, EXC_SYSCALL = 12,
EXC_TRACE = 0x0D, EXC_TRACE = 13
EXC_FP_ASSIST = 0x0E,
EXC_PERF_MON_INT = 0x0F,
EXC_INST_ADDR_BP = 0x13,
EXC_SYS_MGMT_INT = 0x14,
EXC_THRM_MGMT_INT = 0x17,
}; };
/** Program Exception subclasses. */ /** Program Exception subclasses. */
@@ -350,8 +299,6 @@ enum Exc_Cause : uint32_t {
TRAP = 1 << (31 - 14), TRAP = 1 << (31 - 14),
}; };
extern unsigned exec_flags;
extern jmp_buf exc_env; extern jmp_buf exc_env;
enum Po_Cause : int { enum Po_Cause : int {
@@ -368,51 +315,27 @@ enum Po_Cause : int {
po_enter_debugger, po_enter_debugger,
po_entered_debugger, po_entered_debugger,
po_signal_interrupt, po_signal_interrupt,
po_benchmark_exception, po_benchmark_exception
po_endian_switch,
}; };
extern bool power_on; extern bool power_on;
extern Po_Cause power_off_reason; 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 int_pin;
extern bool dec_exception_pending; extern bool dec_exception_pending;
extern bool thrm_exception_pending;
extern bool is_601; // For PowerPC 601 Emulation extern bool is_601; // For PowerPC 601 Emulation
extern bool include_601; // For non-PowerPC 601 emulation with 601 extras extern bool include_601; // For non-PowerPC 601 emulation with 601 extras (matches Mac OS 9 environment which can emulate MPC 601 instructions)
// (matches Mac OS 9 environment which can emulate MPC 601 instructions)
extern bool is_altivec; // For Altivec Emulation extern bool is_altivec; // For Altivec Emulation
extern bool is_64bit; // For PowerPC G5 Emulation extern bool is_64bit; // For PowerPC G5 Emulation
enum class PPCPowMode : uint8_t { // Make execution deterministic (ignore external input, used a fixed date, etc.)
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; extern bool is_deterministic;
// Important Addressing Integers // Important Addressing Integers
extern uint32_t ppc_next_instruction_address; extern uint32_t ppc_next_instruction_address;
inline uint32_t ppc_read_instruction(const uint8_t* ptr) { 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); return READ_DWORD_BE_A(ptr);
#endif
} }
// Profiling Stats // Profiling Stats
@@ -483,7 +406,7 @@ constexpr uint32_t NO_OPCODE = 0;
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, uint32_t cpu_version, bool include_601, uint64_t tb_freq);
extern void ppc_mmu_init(); extern void ppc_mmu_init();
void ppc_illegalop(uint32_t opcode); uint32_t ppc_illegalop(uint32_t opcode);
void ppc_assert_int(); void ppc_assert_int();
void ppc_release_int(); void ppc_release_int();
@@ -494,8 +417,10 @@ void set_host_rounding_mode(uint8_t mode);
void update_fpscr(uint32_t new_fpscr); void update_fpscr(uint32_t new_fpscr);
/* Exception handlers. */ /* Exception handlers. */
void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits); uint32_t ppc_exception_handler(
[[noreturn]] void dbg_exception_handler(Except_Type exception_type, uint32_t srr1_bits); Except_Type exception_type, uint32_t srr1_bits, uint32_t exec_flags = 0);
[[noreturn]] uint32_t dbg_exception_handler(
Except_Type exception_type, uint32_t srr1_bits, uint32_t exec_flags);
void ppc_floating_point_exception(uint32_t opcode); void ppc_floating_point_exception(uint32_t opcode);
void ppc_alignment_exception(uint32_t opcode, uint32_t ea); void ppc_alignment_exception(uint32_t opcode, uint32_t ea);
@@ -508,203 +433,203 @@ extern void do_ctx_sync(void);
// The functions used by the PowerPC processor // The functions used by the PowerPC processor
namespace dppc_interpreter { namespace dppc_interpreter {
template <field_lk l, field_601 for601> extern void ppc_bcctr(uint32_t opcode); template <field_lk l, field_601 for601> extern uint32_t ppc_bcctr(uint32_t opcode);
template <field_lk l> extern void ppc_bclr(uint32_t opcode); template <field_lk l> extern uint32_t ppc_bclr(uint32_t opcode);
extern void ppc_crand(uint32_t opcode); extern uint32_t ppc_crand(uint32_t opcode);
extern void ppc_crandc(uint32_t opcode); extern uint32_t ppc_crandc(uint32_t opcode);
extern void ppc_creqv(uint32_t opcode); extern uint32_t ppc_creqv(uint32_t opcode);
extern void ppc_crnand(uint32_t opcode); extern uint32_t ppc_crnand(uint32_t opcode);
extern void ppc_crnor(uint32_t opcode); extern uint32_t ppc_crnor(uint32_t opcode);
extern void ppc_cror(uint32_t opcode); extern uint32_t ppc_cror(uint32_t opcode);
extern void ppc_crorc(uint32_t opcode); extern uint32_t ppc_crorc(uint32_t opcode);
extern void ppc_crxor(uint32_t opcode); extern uint32_t ppc_crxor(uint32_t opcode);
extern void ppc_isync(uint32_t opcode); extern uint32_t ppc_isync(uint32_t opcode);
template <logical_fun logical_op, field_rc rec> extern void ppc_logical(uint32_t opcode); template <logical_fun logical_op, field_rc rec> extern uint32_t ppc_logical(uint32_t opcode);
template <field_carry carry, field_rc rec, field_ov ov> extern void ppc_add(uint32_t opcode); template <field_carry carry, field_rc rec, field_ov ov> extern uint32_t ppc_add(uint32_t opcode);
template <field_rc rec, field_ov ov> extern void ppc_adde(uint32_t opcode); template <field_rc rec, field_ov ov> extern uint32_t ppc_adde(uint32_t opcode);
template <field_rc rec, field_ov ov> extern void ppc_addme(uint32_t opcode); template <field_rc rec, field_ov ov> extern uint32_t ppc_addme(uint32_t opcode);
template <field_rc rec, field_ov ov> extern void ppc_addze(uint32_t opcode); template <field_rc rec, field_ov ov> extern uint32_t ppc_addze(uint32_t opcode);
extern void ppc_cmp(uint32_t opcode); extern uint32_t ppc_cmp(uint32_t opcode);
extern void ppc_cmpl(uint32_t opcode); extern uint32_t ppc_cmpl(uint32_t opcode);
template <field_rc rec> extern void ppc_cntlzw(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_cntlzw(uint32_t opcode);
extern void ppc_dcbf(uint32_t opcode); extern uint32_t ppc_dcbf(uint32_t opcode);
extern void ppc_dcbi(uint32_t opcode); extern uint32_t ppc_dcbi(uint32_t opcode);
extern void ppc_dcbst(uint32_t opcode); extern uint32_t ppc_dcbst(uint32_t opcode);
extern void ppc_dcbt(uint32_t opcode); extern uint32_t ppc_dcbt(uint32_t opcode);
extern void ppc_dcbtst(uint32_t opcode); extern uint32_t ppc_dcbtst(uint32_t opcode);
extern void ppc_dcbz(uint32_t opcode); extern uint32_t ppc_dcbz(uint32_t opcode);
template <field_rc rec, field_ov ov> extern void ppc_divw(uint32_t opcode); template <field_rc rec, field_ov ov> extern uint32_t ppc_divw(uint32_t opcode);
template <field_rc rec, field_ov ov> extern void ppc_divwu(uint32_t opcode); template <field_rc rec, field_ov ov> extern uint32_t ppc_divwu(uint32_t opcode);
extern void ppc_eciwx(uint32_t opcode); extern uint32_t ppc_eciwx(uint32_t opcode);
extern void ppc_ecowx(uint32_t opcode); extern uint32_t ppc_ecowx(uint32_t opcode);
extern void ppc_eieio(uint32_t opcode); extern uint32_t ppc_eieio(uint32_t opcode);
template <class T, field_rc rec>extern void ppc_exts(uint32_t opcode); template <class T, field_rc rec>extern uint32_t ppc_exts(uint32_t opcode);
extern void ppc_icbi(uint32_t opcode); extern uint32_t ppc_icbi(uint32_t opcode);
extern void ppc_mftb(uint32_t opcode); extern uint32_t ppc_mftb(uint32_t opcode);
extern void ppc_lhaux(uint32_t opcode); extern uint32_t ppc_lhaux(uint32_t opcode);
extern void ppc_lhax(uint32_t opcode); extern uint32_t ppc_lhax(uint32_t opcode);
extern void ppc_lhbrx(uint32_t opcode); extern uint32_t ppc_lhbrx(uint32_t opcode);
extern void ppc_lwarx(uint32_t opcode); extern uint32_t ppc_lwarx(uint32_t opcode);
extern void ppc_lwbrx(uint32_t opcode); extern uint32_t ppc_lwbrx(uint32_t opcode);
template <class T> extern void ppc_lzx(uint32_t opcode); template <class T> extern uint32_t ppc_lzx(uint32_t opcode);
template <class T> extern void ppc_lzux(uint32_t opcode); template <class T> extern uint32_t ppc_lzux(uint32_t opcode);
extern void ppc_mcrxr(uint32_t opcode); extern uint32_t ppc_mcrxr(uint32_t opcode);
extern void ppc_mfcr(uint32_t opcode); extern uint32_t ppc_mfcr(uint32_t opcode);
template <field_rc rec> extern void ppc_mulhwu(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_mulhwu(uint32_t opcode);
template <field_rc rec> extern void ppc_mulhw(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_mulhw(uint32_t opcode);
template <field_rc rec, field_ov ov> extern void ppc_mullw(uint32_t opcode); template <field_rc rec, field_ov ov> extern uint32_t ppc_mullw(uint32_t opcode);
template <field_rc rec, field_ov ov> extern void ppc_neg(uint32_t opcode); template <field_rc rec, field_ov ov> extern uint32_t ppc_neg(uint32_t opcode);
template <field_direction shift, field_rc rec> extern void ppc_shift(uint32_t opcode); template <field_direction shift, field_rc rec> extern uint32_t ppc_shift(uint32_t opcode);
template <field_rc rec> extern void ppc_sraw(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_sraw(uint32_t opcode);
template <field_rc rec> extern void ppc_srawi(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_srawi(uint32_t opcode);
template <class T> extern void ppc_stx(uint32_t opcode); template <class T> extern uint32_t ppc_stx(uint32_t opcode);
template <class T> extern void ppc_stux(uint32_t opcode); template <class T> extern uint32_t ppc_stux(uint32_t opcode);
extern void ppc_stfiwx(uint32_t opcode); extern uint32_t ppc_stfiwx(uint32_t opcode);
extern void ppc_sthbrx(uint32_t opcode); extern uint32_t ppc_sthbrx(uint32_t opcode);
extern void ppc_stwcx(uint32_t opcode); extern uint32_t ppc_stwcx(uint32_t opcode);
extern void ppc_stwbrx(uint32_t opcode); extern uint32_t ppc_stwbrx(uint32_t opcode);
template <field_carry carry, field_rc rec, field_ov ov> extern void ppc_subf(uint32_t opcode); template <field_carry carry, field_rc rec, field_ov ov> extern uint32_t ppc_subf(uint32_t opcode);
template <field_rc rec, field_ov ov> extern void ppc_subfe(uint32_t opcode); template <field_rc rec, field_ov ov> extern uint32_t ppc_subfe(uint32_t opcode);
template <field_rc rec, field_ov ov> extern void ppc_subfme(uint32_t opcode); template <field_rc rec, field_ov ov> extern uint32_t ppc_subfme(uint32_t opcode);
template <field_rc rec, field_ov ov> extern void ppc_subfze(uint32_t opcode); template <field_rc rec, field_ov ov> extern uint32_t ppc_subfze(uint32_t opcode);
extern void ppc_sync(uint32_t opcode); extern uint32_t ppc_sync(uint32_t opcode);
extern void ppc_tlbia(uint32_t opcode); extern uint32_t ppc_tlbia(uint32_t opcode);
extern void ppc_tlbie(uint32_t opcode); extern uint32_t ppc_tlbie(uint32_t opcode);
extern void ppc_tlbli(uint32_t opcode); extern uint32_t ppc_tlbli(uint32_t opcode);
extern void ppc_tlbld(uint32_t opcode); extern uint32_t ppc_tlbld(uint32_t opcode);
extern void ppc_tlbsync(uint32_t opcode); extern uint32_t ppc_tlbsync(uint32_t opcode);
extern void ppc_tw(uint32_t opcode); extern uint32_t ppc_tw(uint32_t opcode);
extern void ppc_lswi(uint32_t opcode); extern uint32_t ppc_lswi(uint32_t opcode);
extern void ppc_lswx(uint32_t opcode); extern uint32_t ppc_lswx(uint32_t opcode);
extern void ppc_stswi(uint32_t opcode); extern uint32_t ppc_stswi(uint32_t opcode);
extern void ppc_stswx(uint32_t opcode); extern uint32_t ppc_stswx(uint32_t opcode);
extern void ppc_mfsr(uint32_t opcode); extern uint32_t ppc_mfsr(uint32_t opcode);
extern void ppc_mfsrin(uint32_t opcode); extern uint32_t ppc_mfsrin(uint32_t opcode);
extern void ppc_mtsr(uint32_t opcode); extern uint32_t ppc_mtsr(uint32_t opcode);
extern void ppc_mtsrin(uint32_t opcode); extern uint32_t ppc_mtsrin(uint32_t opcode);
extern void ppc_mcrf(uint32_t opcode); extern uint32_t ppc_mcrf(uint32_t opcode);
extern void ppc_mtcrf(uint32_t opcode); extern uint32_t ppc_mtcrf(uint32_t opcode);
extern void ppc_mfmsr(uint32_t opcode); extern uint32_t ppc_mfmsr(uint32_t opcode);
extern void ppc_mfspr(uint32_t opcode); extern uint32_t ppc_mfspr(uint32_t opcode);
extern void ppc_mtmsr(uint32_t opcode); extern uint32_t ppc_mtmsr(uint32_t opcode);
extern void ppc_mtspr(uint32_t opcode); extern uint32_t ppc_mtspr(uint32_t opcode);
template <field_rc rec> extern void ppc_mtfsb0(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_mtfsb0(uint32_t opcode);
template <field_rc rec> extern void ppc_mtfsb1(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_mtfsb1(uint32_t opcode);
extern void ppc_mcrfs(uint32_t opcode); extern uint32_t ppc_mcrfs(uint32_t opcode);
template <field_rc rec> extern void ppc_fmr(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fmr(uint32_t opcode);
template <field_601 for601, field_rc rec> extern void ppc_mffs(uint32_t opcode); template <field_601 for601, field_rc rec> extern uint32_t ppc_mffs(uint32_t opcode);
template <field_rc rec> extern void ppc_mtfsf(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_mtfsf(uint32_t opcode);
template <field_rc rec> extern void ppc_mtfsfi(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_mtfsfi(uint32_t opcode);
template <field_shift shift> extern void ppc_addi(uint32_t opcode); template <field_shift shift> extern uint32_t ppc_addi(uint32_t opcode);
template <field_rc rec> extern void ppc_addic(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_addic(uint32_t opcode);
template <field_shift shift> extern void ppc_andirc(uint32_t opcode); template <field_shift shift> extern uint32_t ppc_andirc(uint32_t opcode);
template <field_lk l, field_aa a> extern void ppc_b(uint32_t opcode); template <field_lk l, field_aa a> extern uint32_t ppc_b(uint32_t opcode);
template <field_lk l, field_aa a> extern void ppc_bc(uint32_t opcode); template <field_lk l, field_aa a> extern uint32_t ppc_bc(uint32_t opcode);
extern void ppc_cmpi(uint32_t opcode); extern uint32_t ppc_cmpi(uint32_t opcode);
extern void ppc_cmpli(uint32_t opcode); extern uint32_t ppc_cmpli(uint32_t opcode);
template <class T> extern void ppc_lz(uint32_t opcode); template <class T> extern uint32_t ppc_lz(uint32_t opcode);
template <class T> extern void ppc_lzu(uint32_t opcode); template <class T> extern uint32_t ppc_lzu(uint32_t opcode);
extern void ppc_lha(uint32_t opcode); extern uint32_t ppc_lha(uint32_t opcode);
extern void ppc_lhau(uint32_t opcode); extern uint32_t ppc_lhau(uint32_t opcode);
extern void ppc_lmw(uint32_t opcode); extern uint32_t ppc_lmw(uint32_t opcode);
extern void ppc_mulli(uint32_t opcode); extern uint32_t ppc_mulli(uint32_t opcode);
template <field_shift shift> extern void ppc_ori(uint32_t opcode); template <field_shift shift> extern uint32_t ppc_ori(uint32_t opcode);
extern void ppc_rfi(uint32_t opcode); extern uint32_t ppc_rfi(uint32_t opcode);
extern void ppc_rlwimi(uint32_t opcode); extern uint32_t ppc_rlwimi(uint32_t opcode);
extern void ppc_rlwinm(uint32_t opcode); extern uint32_t ppc_rlwinm(uint32_t opcode);
extern void ppc_rlwnm(uint32_t opcode); extern uint32_t ppc_rlwnm(uint32_t opcode);
extern void ppc_sc(uint32_t opcode); extern uint32_t ppc_sc(uint32_t opcode);
template <class T> extern void ppc_st(uint32_t opcode); template <class T> extern uint32_t ppc_st(uint32_t opcode);
template <class T> extern void ppc_stu(uint32_t opcode); template <class T> extern uint32_t ppc_stu(uint32_t opcode);
extern void ppc_stmw(uint32_t opcode); extern uint32_t ppc_stmw(uint32_t opcode);
extern void ppc_subfic(uint32_t opcode); extern uint32_t ppc_subfic(uint32_t opcode);
extern void ppc_twi(uint32_t opcode); extern uint32_t ppc_twi(uint32_t opcode);
template <field_shift shift> extern void ppc_xori(uint32_t opcode); template <field_shift shift> extern uint32_t ppc_xori(uint32_t opcode);
extern void ppc_lfs(uint32_t opcode); extern uint32_t ppc_lfs(uint32_t opcode);
extern void ppc_lfsu(uint32_t opcode); extern uint32_t ppc_lfsu(uint32_t opcode);
extern void ppc_lfsx(uint32_t opcode); extern uint32_t ppc_lfsx(uint32_t opcode);
extern void ppc_lfsux(uint32_t opcode); extern uint32_t ppc_lfsux(uint32_t opcode);
extern void ppc_lfd(uint32_t opcode); extern uint32_t ppc_lfd(uint32_t opcode);
extern void ppc_lfdu(uint32_t opcode); extern uint32_t ppc_lfdu(uint32_t opcode);
extern void ppc_lfdx(uint32_t opcode); extern uint32_t ppc_lfdx(uint32_t opcode);
extern void ppc_lfdux(uint32_t opcode); extern uint32_t ppc_lfdux(uint32_t opcode);
extern void ppc_stfs(uint32_t opcode); extern uint32_t ppc_stfs(uint32_t opcode);
extern void ppc_stfsu(uint32_t opcode); extern uint32_t ppc_stfsu(uint32_t opcode);
extern void ppc_stfsx(uint32_t opcode); extern uint32_t ppc_stfsx(uint32_t opcode);
extern void ppc_stfsux(uint32_t opcode); extern uint32_t ppc_stfsux(uint32_t opcode);
extern void ppc_stfd(uint32_t opcode); extern uint32_t ppc_stfd(uint32_t opcode);
extern void ppc_stfdu(uint32_t opcode); extern uint32_t ppc_stfdu(uint32_t opcode);
extern void ppc_stfdx(uint32_t opcode); extern uint32_t ppc_stfdx(uint32_t opcode);
extern void ppc_stfdux(uint32_t opcode); extern uint32_t ppc_stfdux(uint32_t opcode);
template <field_rc rec> extern void ppc_fadd(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fadd(uint32_t opcode);
template <field_rc rec> extern void ppc_fsub(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fsub(uint32_t opcode);
template <field_rc rec> extern void ppc_fmul(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fmul(uint32_t opcode);
template <field_rc rec> extern void ppc_fdiv(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fdiv(uint32_t opcode);
template <field_rc rec> extern void ppc_fadds(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fadds(uint32_t opcode);
template <field_rc rec> extern void ppc_fsubs(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fsubs(uint32_t opcode);
template <field_rc rec> extern void ppc_fmuls(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fmuls(uint32_t opcode);
template <field_rc rec> extern void ppc_fdivs(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fdivs(uint32_t opcode);
template <field_rc rec> extern void ppc_fmadd(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fmadd(uint32_t opcode);
template <field_rc rec> extern void ppc_fmsub(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fmsub(uint32_t opcode);
template <field_rc rec> extern void ppc_fnmadd(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fnmadd(uint32_t opcode);
template <field_rc rec> extern void ppc_fnmsub(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fnmsub(uint32_t opcode);
template <field_rc rec> extern void ppc_fmadds(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fmadds(uint32_t opcode);
template <field_rc rec> extern void ppc_fmsubs(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fmsubs(uint32_t opcode);
template <field_rc rec> extern void ppc_fnmadds(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fnmadds(uint32_t opcode);
template <field_rc rec> extern void ppc_fnmsubs(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fnmsubs(uint32_t opcode);
template <field_rc rec> extern void ppc_fabs(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fabs(uint32_t opcode);
template <field_rc rec> extern void ppc_fnabs(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fnabs(uint32_t opcode);
template <field_rc rec> extern void ppc_fneg(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fneg(uint32_t opcode);
template <field_rc rec> extern void ppc_fsel(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fsel(uint32_t opcode);
template <field_rc rec> extern void ppc_fres(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fres(uint32_t opcode);
template <field_rc rec> extern void ppc_fsqrts(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fsqrts(uint32_t opcode);
template <field_rc rec> extern void ppc_fsqrt(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fsqrt(uint32_t opcode);
template <field_rc rec> extern void ppc_frsqrte(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_frsqrte(uint32_t opcode);
template <field_rc rec> extern void ppc_frsp(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_frsp(uint32_t opcode);
template <field_rc rec> extern void ppc_fctiw(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fctiw(uint32_t opcode);
template <field_rc rec> extern void ppc_fctiwz(uint32_t opcode); template <field_rc rec> extern uint32_t ppc_fctiwz(uint32_t opcode);
extern void ppc_fcmpo(uint32_t opcode); extern uint32_t ppc_fcmpo(uint32_t opcode);
extern void ppc_fcmpu(uint32_t opcode); extern uint32_t ppc_fcmpu(uint32_t opcode);
// Power-specific instructions // Power-specific instructions
template <field_rc rec, field_ov ov> extern void power_abs(uint32_t opcode); template <field_rc rec, field_ov ov> extern uint32_t power_abs(uint32_t opcode);
extern void power_clcs(uint32_t opcode); extern uint32_t power_clcs(uint32_t opcode);
template <field_rc rec, field_ov ov> extern void power_div(uint32_t opcode); template <field_rc rec, field_ov ov> extern uint32_t power_div(uint32_t opcode);
template <field_rc rec, field_ov ov> extern void power_divs(uint32_t opcode); template <field_rc rec, field_ov ov> extern uint32_t power_divs(uint32_t opcode);
template <field_rc rec, field_ov ov> extern void power_doz(uint32_t opcode); template <field_rc rec, field_ov ov> extern uint32_t power_doz(uint32_t opcode);
extern void power_dozi(uint32_t opcode); extern uint32_t power_dozi(uint32_t opcode);
template <field_rc rec> extern void power_lscbx(uint32_t opcode); template <field_rc rec> extern uint32_t power_lscbx(uint32_t opcode);
template <field_rc rec> extern void power_maskg(uint32_t opcode); template <field_rc rec> extern uint32_t power_maskg(uint32_t opcode);
template <field_rc rec> extern void power_maskir(uint32_t opcode); template <field_rc rec> extern uint32_t power_maskir(uint32_t opcode);
template <field_rc rec, field_ov ov> extern void power_mul(uint32_t opcode); template <field_rc rec, field_ov ov> extern uint32_t power_mul(uint32_t opcode);
template <field_rc rec, field_ov ov> extern void power_nabs(uint32_t opcode); template <field_rc rec, field_ov ov> extern uint32_t power_nabs(uint32_t opcode);
extern void power_rlmi(uint32_t opcode); extern uint32_t power_rlmi(uint32_t opcode);
template <field_rc rec> extern void power_rrib(uint32_t opcode); template <field_rc rec> extern uint32_t power_rrib(uint32_t opcode);
template <field_rc rec> extern void power_sle(uint32_t opcode); template <field_rc rec> extern uint32_t power_sle(uint32_t opcode);
template <field_rc rec> extern void power_sleq(uint32_t opcode); template <field_rc rec> extern uint32_t power_sleq(uint32_t opcode);
template <field_rc rec> extern void power_sliq(uint32_t opcode); template <field_rc rec> extern uint32_t power_sliq(uint32_t opcode);
template <field_rc rec> extern void power_slliq(uint32_t opcode); template <field_rc rec> extern uint32_t power_slliq(uint32_t opcode);
template <field_rc rec> extern void power_sllq(uint32_t opcode); template <field_rc rec> extern uint32_t power_sllq(uint32_t opcode);
template <field_rc rec> extern void power_slq(uint32_t opcode); template <field_rc rec> extern uint32_t power_slq(uint32_t opcode);
template <field_rc rec> extern void power_sraiq(uint32_t opcode); template <field_rc rec> extern uint32_t power_sraiq(uint32_t opcode);
template <field_rc rec> extern void power_sraq(uint32_t opcode); template <field_rc rec> extern uint32_t power_sraq(uint32_t opcode);
template <field_rc rec> extern void power_sre(uint32_t opcode); template <field_rc rec> extern uint32_t power_sre(uint32_t opcode);
template <field_rc rec> extern void power_srea(uint32_t opcode); template <field_rc rec> extern uint32_t power_srea(uint32_t opcode);
template <field_rc rec> extern void power_sreq(uint32_t opcode); template <field_rc rec> extern uint32_t power_sreq(uint32_t opcode);
template <field_rc rec> extern void power_sriq(uint32_t opcode); template <field_rc rec> extern uint32_t power_sriq(uint32_t opcode);
template <field_rc rec> extern void power_srliq(uint32_t opcode); template <field_rc rec> extern uint32_t power_srliq(uint32_t opcode);
template <field_rc rec> extern void power_srlq(uint32_t opcode); template <field_rc rec> extern uint32_t power_srlq(uint32_t opcode);
template <field_rc rec> extern void power_srq(uint32_t opcode); template <field_rc rec> extern uint32_t power_srq(uint32_t opcode);
} // namespace dppc_interpreter } // namespace dppc_interpreter
// AltiVec instructions // AltiVec instructions
@@ -715,55 +640,15 @@ template <field_rc rec> extern void power_srq(uint32_t opcode);
extern uint64_t get_virt_time_ns(void); extern uint64_t get_virt_time_ns(void);
extern void ppc_main_opcode(PPCOpcode* ppc_opcode_grabber, uint32_t opcode); extern uint32_t ppc_main_opcode(uint32_t opcode);
extern void ppc_exec(void); extern void ppc_exec(void);
extern void ppc_exec_single(void); extern void ppc_exec_single(void);
extern void ppc_exec_until(uint32_t goal_addr); extern void ppc_exec_until(uint32_t goal_addr);
extern void ppc_exec_dbg(uint32_t start_addr, uint32_t size); 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 */ /* debugging support API */
void print_fprs(void); /* print content of the floating-point registers */
uint64_t get_reg(std::string reg_name); /* get content of the register reg_name */ 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 */ void set_reg(std::string reg_name, uint64_t val); /* set reg_name to val */
/* icnt_factor control */
extern int increment_icnt_factor();
extern int decrement_icnt_factor();
extern int get_icnt_factor();
/* 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 */ #endif /* PPCEMU_H */
+50 -37
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -32,18 +32,15 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
jmp_buf exc_env; /* Global exception environment. */ jmp_buf exc_env; /* Global exception environment. */
#if !defined(PPC_TESTS) && !defined(PPC_BENCHMARKS) #if !defined(PPC_TESTS) && !defined(PPC_BENCHMARKS)
void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) { uint32_t ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits, uint32_t exec_flags) {
#ifdef CPU_PROFILING #ifdef CPU_PROFILING
exceptions_processed++; exceptions_processed++;
#endif #endif
switch (exception_type) { switch (exception_type) {
case Except_Type::EXC_SYSTEM_RESET: case Except_Type::EXC_SYSTEM_RESET:
case Except_Type::EXC_DSI:
case Except_Type::EXC_ALIGNMENT:
case Except_Type::EXC_PROGRAM:
case Except_Type::EXC_NO_FPU:
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC; ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0100;
break; break;
case Except_Type::EXC_MACHINE_CHECK: case Except_Type::EXC_MACHINE_CHECK:
@@ -51,47 +48,75 @@ void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
/* TODO: handle internal checkstop */ /* TODO: handle internal checkstop */
} }
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC; ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0200;
break;
case Except_Type::EXC_DSI:
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0300;
break; break;
case Except_Type::EXC_ISI: case Except_Type::EXC_ISI:
if (exec_flags & ~EXEF_OPC_DECODER) { if (exec_flags) {
ppc_state.spr[SPR::SRR0] = ppc_next_instruction_address; ppc_state.spr[SPR::SRR0] = ppc_next_instruction_address;
} else { } else {
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFCUL; ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFCUL;
} }
ppc_next_instruction_address = 0x0400;
break; break;
case Except_Type::EXC_EXT_INT: case Except_Type::EXC_EXT_INT:
case Except_Type::EXC_DECR: if (exec_flags) {
case Except_Type::EXC_THRM_MGMT_INT:
if (exec_flags & ~EXEF_OPC_DECODER) {
ppc_state.spr[SPR::SRR0] = ppc_next_instruction_address; ppc_state.spr[SPR::SRR0] = ppc_next_instruction_address;
} else { } else {
ppc_state.spr[SPR::SRR0] = (ppc_state.pc & 0xFFFFFFFCUL) + 4; ppc_state.spr[SPR::SRR0] = (ppc_state.pc & 0xFFFFFFFCUL) + 4;
} }
ppc_next_instruction_address = 0x0500;
break;
case Except_Type::EXC_ALIGNMENT:
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0600;
break;
case Except_Type::EXC_PROGRAM:
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0700;
break;
case Except_Type::EXC_NO_FPU:
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0800;
break;
case Except_Type::EXC_DECR:
if (exec_flags) {
ppc_state.spr[SPR::SRR0] = ppc_next_instruction_address;
} else {
ppc_state.spr[SPR::SRR0] = (ppc_state.pc & 0xFFFFFFFCUL) + 4;
}
ppc_next_instruction_address = 0x0900;
break; break;
case Except_Type::EXC_SYSCALL: case Except_Type::EXC_SYSCALL:
ppc_state.spr[SPR::SRR0] = (ppc_state.pc & 0xFFFFFFFC) + 4;
ppc_next_instruction_address = 0x0C00;
break;
case Except_Type::EXC_TRACE: case Except_Type::EXC_TRACE:
ppc_state.spr[SPR::SRR0] = (ppc_state.pc & 0xFFFFFFFC) + 4; ppc_state.spr[SPR::SRR0] = (ppc_state.pc & 0xFFFFFFFC) + 4;
ppc_next_instruction_address = 0x0D00;
break; break;
default: default:
ABORT_F("Unknown exception occurred: %X\n", (unsigned)exception_type); ABORT_F("Unknown exception occurred: %X\n", (unsigned)exception_type);
break; break;
} }
ppc_next_instruction_address = uint32_t(exception_type) << 8;
ppc_state.spr[SPR::SRR1] = (ppc_state.msr & 0x0000FF73) | srr1_bits; ppc_state.spr[SPR::SRR1] = (ppc_state.msr & 0x0000FF73) | srr1_bits;
uint32_t old_msr_val = ppc_state.msr; ppc_state.msr &= 0xFFFB1041;
uint32_t new_msr_val = old_msr_val & 0xFFFB1041;
/* copy MSR[ILE] to MSR[LE] */ /* copy MSR[ILE] to MSR[LE] */
if (!is_601) { ppc_state.msr = (ppc_state.msr & ~MSR::LE) | !!(ppc_state.msr & MSR::ILE);
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);
if (ppc_state.msr & MSR::IP) { if (ppc_state.msr & MSR::IP) {
ppc_next_instruction_address |= 0xFFF00000; ppc_next_instruction_address |= 0xFFF00000;
@@ -108,15 +133,14 @@ void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
mmu_change_mode(); mmu_change_mode();
if (exception_type != Except_Type::EXC_EXT_INT && exception_type != Except_Type::EXC_DECR) { 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. */ longjmp(exc_env, 2); /* return to the main execution loop. */
} }
return exec_flags;
} }
#endif #endif
[[noreturn]] void dbg_exception_handler(Except_Type exception_type, uint32_t srr1_bits) { [[noreturn]] uint32_t dbg_exception_handler(Except_Type exception_type, uint32_t srr1_bits, uint32_t exec_flags) {
std::string exc_descriptor; std::string exc_descriptor;
switch (exception_type) { switch (exception_type) {
@@ -134,8 +158,6 @@ void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
exc_descriptor = "DSI/ISI exception: unmapped memory access"; exc_descriptor = "DSI/ISI exception: unmapped memory access";
else if (ppc_state.spr[SPR::DSISR] & 0x08000000) else if (ppc_state.spr[SPR::DSISR] & 0x08000000)
exc_descriptor = "DSI/ISI exception: access protection violation"; exc_descriptor = "DSI/ISI exception: access protection violation";
else if (ppc_state.spr[SPR::DSISR] & 0x00100000)
exc_descriptor = "DSI exception: External access is disabled";
else { else {
if (exception_type == Except_Type::EXC_DSI) if (exception_type == Except_Type::EXC_DSI)
exc_descriptor = "DSI exception"; exc_descriptor = "DSI exception";
@@ -171,15 +193,6 @@ void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
case Except_Type::EXC_TRACE: case Except_Type::EXC_TRACE:
exc_descriptor = "Trace exception occurred"; exc_descriptor = "Trace exception occurred";
break; break;
case Except_Type::EXC_THRM_MGMT_INT:
exc_descriptor = "Thermal management interrupt exception occurred";
break;
default:
char buffer[100];
snprintf(buffer, sizeof(buffer), "Exception 0x%X occurred", int(exception_type));
exc_descriptor = buffer;
} }
throw std::invalid_argument(exc_descriptor); throw std::invalid_argument(exc_descriptor);
@@ -300,5 +313,5 @@ unexpected_instruction:
ppc_state.spr[SPR::DSISR] = dsisr; ppc_state.spr[SPR::DSISR] = dsisr;
ppc_state.spr[SPR::DAR] = ea; ppc_state.spr[SPR::DAR] = ea;
ppc_exception_handler(Except_Type::EXC_ALIGNMENT, 0x0); ppc_exception_handler(Except_Type::EXC_ALIGNMENT, 0x0, 0);
} }
+146 -459
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -26,7 +26,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include "ppcdisasm.h" #include "ppcdisasm.h"
#include <algorithm> #include <algorithm>
#include <chrono>
#include <cstring> #include <cstring>
#include <iostream> #include <iostream>
#include <map> #include <map>
@@ -58,80 +57,29 @@ MemCtrlBase* mem_ctrl_instance = 0;
bool is_601 = false; bool is_601 = false;
bool include_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 is_deterministic = false;
bool power_on = false; bool power_on = false;
Po_Cause power_off_reason = po_enter_debugger; 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; 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 uint32_t ppc_next_instruction_address; // Used for branching, setting up the NIA
unsigned exec_flags; // execution control flags
// FIXME: exec_timer is read by main thread ppc_main_opcode; // FIXME: exec_timer is read by main thread ppc_main_opcode;
// written by audio dbdma DMAChannel::update_irq .. add_immediate_timer // written by audio dbdma DMAChannel::update_irq .. add_immediate_timer
volatile bool exec_timer; volatile bool exec_timer;
bool int_pin = false; // interrupt request pin state: true - asserted bool int_pin = false; // interrupt request pin state: true - asserted
bool dec_exception_pending = false; bool dec_exception_pending = false;
bool thrm_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 */ /* variables related to virtual time */
bool g_realtime = false; const bool g_realtime = false;
uint64_t g_nanoseconds_base; uint64_t g_nanoseconds_base;
uint64_t g_icycles; uint64_t g_icycles;
int icnt_factor; int icnt_factor;
@@ -142,9 +90,9 @@ uint64_t rtc_timestamp; // stores vCPU virtual time of the last RTC write
uint64_t tbr_wr_value; // last value written to the TBR uint64_t tbr_wr_value; // last value written to the TBR
uint32_t tbr_freq_ghz; // TBR/RTC driving frequency in GHz expressed as a uint32_t tbr_freq_ghz; // TBR/RTC driving frequency in GHz expressed as a
// 32 bit fraction less than 1.0 (999.999999 MHz maximum). // 32 bit fraction less than 1.0 (999.999999 MHz maximum).
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 uint64_t tbr_period_ns; // TBR/RTC period in ns expressed as a 64 bit value
// with 32 fractional bits (<1 Hz minimum). // 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 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 dec_wr_value; // last value written to the DEC register
uint32_t rtc_lo; // MPC601 RTC lower, counts nanoseconds uint32_t rtc_lo; // MPC601 RTC lower, counts nanoseconds
@@ -167,7 +115,7 @@ std::unordered_map<uint32_t, uint64_t> num_opcodes;
class CPUProfile : public BaseProfile { class CPUProfile : public BaseProfile {
public: public:
CPUProfile() : BaseProfile("PPC_CPU") {} CPUProfile() : BaseProfile("PPC_CPU") {};
void populate_variables(std::vector<ProfileVar>& vars) { void populate_variables(std::vector<ProfileVar>& vars) {
vars.clear(); vars.clear();
@@ -204,12 +152,9 @@ public:
op_name_counts.emplace_back(op_name, pair.second); op_name_counts.emplace_back(op_name, pair.second);
} }
size_t top_ops_size = std::min(op_name_counts.size(), size_t(20)); size_t top_ops_size = std::min(op_name_counts.size(), size_t(20));
std::partial_sort( std::partial_sort(op_name_counts.begin(), op_name_counts.begin() + top_ops_size, op_name_counts.end(), [](const auto& a, const auto& b) {
op_name_counts.begin(), op_name_counts.begin() + top_ops_size, op_name_counts.end(), return b.second < a.second;
[](const auto& a, const auto& b) { });
return b.second < a.second;
}
);
op_name_counts.resize(top_ops_size); op_name_counts.resize(top_ops_size);
for (const auto& pair : op_name_counts) { for (const auto& pair : op_name_counts) {
vars.push_back({.name = "Instruction " + pair.first, vars.push_back({.name = "Instruction " + pair.first,
@@ -218,7 +163,7 @@ public:
.count_total = num_executed_instrs}); .count_total = num_executed_instrs});
} }
#endif #endif
} };
void reset() { void reset() {
num_executed_instrs = 0; num_executed_instrs = 0;
@@ -229,76 +174,26 @@ public:
#ifdef CPU_PROFILING_OPS #ifdef CPU_PROFILING_OPS
num_opcodes.clear(); num_opcodes.clear();
#endif #endif
} };
}; };
#endif #endif
#ifdef LOG_INSTRUCTIONS
InstructionRec InstructionLog[InstructionLogSize] = {0};
uint64_t InstructionNumber = 0;
#endif
/** Opcode lookup table, indexed by /** Opcode lookup table, indexed by
primary opcode (bits 0...5) and modifier (bits 21...31). */ primary opcode (bits 0...5) and modifier (bits 21...31). */
static PPCOpcode OpcodeGrabber[64 * 2048]; static PPCOpcode OpcodeGrabber[64 * 2048];
/** Alternate lookup table when floating point instructions are disabled.
Floating point instructions are mapped to ppc_fpu_off,
everything else is the same.*/
static PPCOpcode OpcodeGrabberNoFPU[64 * 2048];
void ppc_msr_did_change(uint32_t old_msr_val, uint32_t new_msr_val, bool set_next_instruction_address) {
ppc_state.msr = new_msr_val;
if ((old_msr_val ^ new_msr_val) & MSR::FP) {
bool newFP = (new_msr_val & MSR::FP) != 0;
ppc_opcode_grabber = newFP ? OpcodeGrabber : OpcodeGrabberNoFPU;
//LOG_F(INFO, "changed FP to %s", newFP ? "yes" : "no");
#if 1
exec_flags |= EXEF_OPC_DECODER;
if (set_next_instruction_address) {
// Even though we're setting an exception flag, we want normal
// instruction execution to continue.
ppc_next_instruction_address = ppc_state.pc + 4;
}
#else
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. */ /** Exception helpers. */
void ppc_illegalop(uint32_t opcode) { uint32_t ppc_illegalop(uint32_t opcode) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP); return ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP, 0);
}
void ppc_fpu_off(uint32_t opcode) {
ppc_exception_handler(Except_Type::EXC_NO_FPU, Exc_Cause::FPU_OFF);
} }
void ppc_assert_int() { void ppc_assert_int() {
int_pin = true; int_pin = true;
if (ppc_state.msr & MSR::EE) { if (ppc_state.msr & MSR::EE) {
LOG_F(5, "CPU ExtIntHandler called"); LOG_F(5, "CPU ExtIntHandler called");
ppc_exception_handler(Except_Type::EXC_EXT_INT, 0); ppc_exception_handler(Except_Type::EXC_EXT_INT, 0, 0);
} else { } else {
LOG_F(5, "CPU IRQ ignored!"); LOG_F(5, "CPU IRQ ignored!");
} }
@@ -311,7 +206,7 @@ void ppc_release_int() {
/** Opcode decoding functions. */ /** Opcode decoding functions. */
/* Dispatch using primary and modifier opcode */ /* Dispatch using primary and modifier opcode */
void ppc_main_opcode(PPCOpcode *opcodeGrabber, uint32_t opcode) uint32_t ppc_main_opcode(uint32_t opcode)
{ {
#ifdef CPU_PROFILING #ifdef CPU_PROFILING
num_executed_instrs++; num_executed_instrs++;
@@ -319,28 +214,7 @@ void ppc_main_opcode(PPCOpcode *opcodeGrabber, uint32_t opcode)
num_opcodes[opcode]++; num_opcodes[opcode]++;
#endif #endif
#endif #endif
return OpcodeGrabber[(opcode >> 15 & 0x1F800) | (opcode & 0x7FF)](opcode);
#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() { static long long cpu_now_ns() {
@@ -361,33 +235,16 @@ uint64_t get_virt_time_ns()
} }
} }
void set_virt_time_ns(uint64_t time_now)
{
if (g_realtime) {
g_nanoseconds_base = cpu_now_ns() - time_now - 5000;
} else {
g_icycles = time_now >> icnt_factor;
}
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 uint64_t process_events() static uint64_t process_events()
{ {
exec_timer = false; exec_timer = false;
uint64_t next_ns = TimerManager::get_instance()->process_timers(); uint64_t slice_ns = TimerManager::get_instance()->process_timers();
return ( if (slice_ns == 0) {
( // execute 25.000 cycles
next_ns ? // if there are no pending timers
next_ns return g_icycles + 25000;
: }
TimerManager::get_instance()->current_time_ns() + 500'000 return g_icycles + (slice_ns >> icnt_factor) + 1;
) >> icnt_factor
) + 1;
} }
static void force_cycle_counter_reload() static void force_cycle_counter_reload()
@@ -396,40 +253,6 @@ static void force_cycle_counter_reload()
exec_timer = true; exec_timer = true;
} }
int increment_icnt_factor()
{
uint64_t time_now = get_virt_time_ns();
icnt_factor += 1;
set_virt_time_ns(time_now);
force_cycle_counter_reload();
return icnt_factor;
}
int decrement_icnt_factor()
{
if (icnt_factor > 0) {
uint64_t time_now = get_virt_time_ns();
icnt_factor -= 1;
set_virt_time_ns(time_now);
force_cycle_counter_reload();
}
return icnt_factor;
}
int get_icnt_factor()
{
return icnt_factor;
}
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 { typedef enum {
main, main,
until, until,
@@ -437,13 +260,13 @@ typedef enum {
} ppc_exec_type_t; } ppc_exec_type_t;
// inner interpreter loop // inner interpreter loop
template <ppc_exec_type_t exec_type, endian_switch endian> template <ppc_exec_type_t exec_type>
static void ppc_exec_inner(uint32_t start_addr, uint32_t size) static void ppc_exec_inner(uint32_t start_addr, uint32_t size)
{ {
uint64_t max_cycles = 0; uint64_t max_cycles = 0;
uint32_t page_start, eb_start, eb_end = 0; uint32_t page_start, eb_start, eb_end = 0;
uint32_t opcode; uint32_t opcode;
PPCOpcode* opcode_grabber = ppc_opcode_grabber; uint32_t exec_flags; // execution control flags
uint8_t* pc_real; uint8_t* pc_real;
while (power_on) { while (power_on) {
@@ -457,52 +280,28 @@ static void ppc_exec_inner(uint32_t start_addr, uint32_t size)
eb_start = ppc_state.pc; eb_start = ppc_state.pc;
page_start = eb_start & PPC_PAGE_MASK; page_start = eb_start & PPC_PAGE_MASK;
eb_end = page_start + PPC_PAGE_SIZE - 1; 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); opcode = ppc_read_instruction(pc_real);
ppc_main_opcode(opcode_grabber, opcode); exec_flags = ppc_main_opcode(opcode);
if (g_icycles++ >= max_cycles || exec_timer) [[unlikely]] if (g_icycles++ >= max_cycles || exec_timer)
max_cycles = process_events(); max_cycles = process_events();
if (exec_flags) { if (exec_flags) {
if ((exec_flags & EXEF_SLEEP) && !(exec_flags & EXEF_EXCEPTION)) [[unlikely]] {
while (power_on && (exec_flags & EXEF_SLEEP)) {
max_cycles = process_events();
if (!(exec_flags & EXEF_SLEEP)) {
break;
}
if (max_cycles > g_icycles) {
g_icycles = max_cycles;
} else {
g_icycles++;
}
}
}
if (exec_flags & EXEF_OPC_DECODER) [[unlikely]] {
opcode_grabber = ppc_opcode_grabber;
}
// define next execution block // define next execution block
eb_start = ppc_next_instruction_address; eb_start = ppc_next_instruction_address;
if (!(exec_flags & EXEF_RFI) && (eb_start & PPC_PAGE_MASK) == page_start) { if (!(exec_flags & EXEF_RFI) && (eb_start & PPC_PAGE_MASK) == page_start) {
if (endian == big_end) pc_real += (int)eb_start - (int)ppc_state.pc;
INCPC((int)eb_start - (int)ppc_state.pc);
else
pc_real = mmu_translate_imem(eb_start ATPCP); // &pcp
} else { } else {
page_start = eb_start & PPC_PAGE_MASK; page_start = eb_start & PPC_PAGE_MASK;
eb_end = page_start + PPC_PAGE_SIZE - 1; eb_end = page_start + PPC_PAGE_SIZE - 1;
pc_real = mmu_translate_imem(eb_start ATPCP); // &pcp pc_real = mmu_translate_imem(eb_start);
} }
ppc_state.pc = eb_start; ppc_state.pc = eb_start;
exec_flags = 0; } else { [[likely]]
} else [[likely]] {
ppc_state.pc += 4; ppc_state.pc += 4;
if (endian == big_end) pc_real += 4;
INCPC(4);
else
pc_real = mmu_translate_imem(ppc_state.pc ATPCP); // &pcp
} }
if (exec_type == until) if (exec_type == until)
@@ -514,8 +313,7 @@ static void ppc_exec_inner(uint32_t start_addr, uint32_t size)
/** Execute PPC code as long as power is on. */ /** Execute PPC code as long as power is on. */
// inner interpreter loop // inner interpreter loop
template void ppc_exec_inner<main, big_end>(uint32_t start_addr, uint32_t size); template void ppc_exec_inner<main>(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 // outer interpreter loop
void ppc_exec() void ppc_exec()
@@ -527,40 +325,30 @@ void ppc_exec()
} }
while (power_on) { while (power_on) {
#if SUPPORTS_PPC_LITTLE_ENDIAN_MODE ppc_exec_inner<main>(0, 0);
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;
}
} }
} }
/** Execute one PPC instruction. */ /** Execute one PPC instruction. */
void ppc_exec_single() void ppc_exec_single()
{ {
uint32_t exec_flags = 0;
if (setjmp(exc_env)) { if (setjmp(exc_env)) {
// process low-level exceptions // process low-level exceptions
//LOG_F(9, "PPC-EXEC: low_level exception raised!"); //LOG_F(9, "PPC-EXEC: low_level exception raised!");
ppc_state.pc = ppc_next_instruction_address; ppc_state.pc = ppc_next_instruction_address;
exec_flags = 0;
return; return;
} }
uint8_t* pc_real = mmu_translate_imem(ppc_state.pc ATPCP); // &pcp uint8_t* pc_real = mmu_translate_imem(ppc_state.pc);
uint32_t opcode = ppc_read_instruction(pc_real); uint32_t opcode = ppc_read_instruction(pc_real);
ppc_main_opcode(ppc_opcode_grabber, opcode); exec_flags = ppc_main_opcode(opcode);
g_icycles++; g_icycles++;
process_events(); process_events();
if (exec_flags) { if (exec_flags) {
ppc_state.pc = ppc_next_instruction_address; ppc_state.pc = ppc_next_instruction_address;
exec_flags = 0;
} else { } else {
ppc_state.pc += 4; ppc_state.pc += 4;
} }
@@ -569,29 +357,19 @@ void ppc_exec_single()
/** Execute PPC code until goal_addr is reached. */ /** Execute PPC code until goal_addr is reached. */
// inner interpreter loop // inner interpreter loop
template void ppc_exec_inner<until, big_end>(uint32_t start_addr, uint32_t size); template void ppc_exec_inner<until>(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 // outer interpreter loop
void ppc_exec_until(volatile uint32_t goal_addr) { void ppc_exec_until(volatile uint32_t goal_addr)
{
if (setjmp(exc_env)) { if (setjmp(exc_env)) {
// process low-level exceptions // process low-level exceptions
// LOG_F(9, "PPC-EXEC: low_level exception raised!"); //LOG_F(9, "PPC-EXEC: low_level exception raised!");
ppc_state.pc = ppc_next_instruction_address; ppc_state.pc = ppc_next_instruction_address;
} }
while (power_on) { while (power_on) {
#if SUPPORTS_PPC_LITTLE_ENDIAN_MODE ppc_exec_inner<until>(goal_addr, 0);
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) if (ppc_state.pc == goal_addr)
break; break;
} }
@@ -600,8 +378,7 @@ void ppc_exec_until(volatile uint32_t goal_addr) {
/** Execute PPC code until control is reached the specified region. */ /** Execute PPC code until control is reached the specified region. */
// inner interpreter loop // inner interpreter loop
template void ppc_exec_inner<debug, big_end>(uint32_t start_addr, uint32_t size); template void ppc_exec_inner<debug>(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 // outer interpreter loop
void ppc_exec_dbg(volatile uint32_t start_addr, volatile uint32_t size) void ppc_exec_dbg(volatile uint32_t start_addr, volatile uint32_t size)
@@ -613,17 +390,7 @@ 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)) { while (power_on && (ppc_state.pc < start_addr || ppc_state.pc >= start_addr + size)) {
#if SUPPORTS_PPC_LITTLE_ENDIAN_MODE ppc_exec_inner<debug>(start_addr, size);
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;
}
} }
} }
@@ -638,107 +405,89 @@ Opcode table macros:
- r is for raw (adding custom entries to the table) - r is for raw (adding custom entries to the table)
*/ */
#define OP(opcode, fn) \
do { \
for (uint32_t mod = 0; mod < 2048; mod++) { \
OpcodeGrabber[((opcode) << 11) | mod] = fn; \
} \
} while (0)
#define OPX(opcode, subopcode, fn) \
do { \
OpcodeGrabber[((opcode) << 11) | ((subopcode)<<1)] = fn; \
} while (0)
#define OPXd(opcode, subopcode, fn) \
do { \
OpcodeGrabber[((opcode) << 11) | ((subopcode)<<1) | 0x000] = fn<RC0>; \
OpcodeGrabber[((opcode) << 11) | ((subopcode)<<1) | 0x001] = fn<RC1>; \
} while (0)
#define OPXod(opcode, subopcode, fn) \
do { \
OpcodeGrabber[((opcode) << 11) | ((subopcode)<<1) | 0x000] = fn<RC0, OV0>; \
OpcodeGrabber[((opcode) << 11) | ((subopcode)<<1) | 0x001] = fn<RC1, OV0>; \
OpcodeGrabber[((opcode) << 11) | ((subopcode)<<1) | 0x400] = fn<RC0, OV1>; \
OpcodeGrabber[((opcode) << 11) | ((subopcode)<<1) | 0x401] = fn<RC1, OV1>; \
} while (0)
#define OPXdc(opcode, subopcode, fn, carry) \
do { \
OpcodeGrabber[((opcode) << 11) | ((subopcode)<<1) | 0x000] = fn<carry, RC0>; \
OpcodeGrabber[((opcode) << 11) | ((subopcode)<<1) | 0x001] = fn<carry, RC1>; \
} while (0)
#define OPXcod(opcode, subopcode, fn, carry) \
do { \
OpcodeGrabber[((opcode) << 11) | ((subopcode)<<1) | 0x000] = fn<carry, RC0, OV0>; \
OpcodeGrabber[((opcode) << 11) | ((subopcode)<<1) | 0x001] = fn<carry, RC1, OV0>; \
OpcodeGrabber[((opcode) << 11) | ((subopcode)<<1) | 0x400] = fn<carry, RC0, OV1>; \
OpcodeGrabber[((opcode) << 11) | ((subopcode)<<1) | 0x401] = fn<carry, RC1, OV1>; \
} while (0)
#define OPla(opcode, subopcode, fn) \
do { \
for (uint32_t mod = 0; mod < 512; mod++) { \
OpcodeGrabber[((opcode) << 11) | (mod << 2) | (subopcode)] = fn; \
} \
} while (0)
#define OPr(opcode, mod, fn) \ #define OPr(opcode, mod, fn) \
do { \ do { \
OpcodeGrabber[((opcode) << 11) | (mod)] = fn; \ OpcodeGrabber[((opcode) << 11) | (mod)] = fn; \
} while (0) } while (0)
#define OPr_fp(opcode, mod, fn) \
do { \
OPr(opcode, mod, fn); \
OpcodeGrabberNoFPU[((opcode) << 11) | (mod)] = ppc_fpu_off; \
} while (0)
#define OP(opcode, fn) \
do { \
for (uint32_t mod = 0; mod < 2048; mod++) { \
OPr(opcode, mod, fn); \
} \
} while (0)
#define OP_fp(opcode, fn) \
do { \
for (uint32_t mod = 0; mod < 2048; mod++) { \
OPr_fp(opcode, mod, fn); \
} \
} while (0)
#define OPX(opcode, subopcode, fn) OPr(opcode, (subopcode)<<1, fn)
#define OPX_fp(opcode, subopcode, fn) OPr_fp(opcode, (subopcode)<<1, fn)
#define OPXd(opcode, subopcode, fn) \
do { \
OPr(opcode, ((subopcode)<<1) | 0, fn<RC0>); \
OPr(opcode, ((subopcode)<<1) | 1, fn<RC1>); \
} while (0)
#define OPXd_fp(opcode, subopcode, fn) \
do { \
OPr_fp(opcode, ((subopcode)<<1) | 0, fn<RC0>); \
OPr_fp(opcode, ((subopcode)<<1) | 1, fn<RC1>); \
} while (0)
#define OPXod(opcode, subopcode, fn) \
do { \
OPr(opcode, ((subopcode)<<1) | 0x000, (fn<RC0, OV0>)); \
OPr(opcode, ((subopcode)<<1) | 0x001, (fn<RC1, OV0>)); \
OPr(opcode, ((subopcode)<<1) | 0x400, (fn<RC0, OV1>)); \
OPr(opcode, ((subopcode)<<1) | 0x401, (fn<RC1, OV1>)); \
} while (0)
#define OPXdc(opcode, subopcode, fn, carry) \
do { \
OPr(opcode, ((subopcode)<<1) | 0, (fn<carry, RC0>)); \
OPr(opcode, ((subopcode)<<1) | 1, (fn<carry, RC1>)); \
} while (0)
#define OPXdc_fp(opcode, subopcode, fn, carry) \
do { \
OPr_fp(opcode, ((subopcode)<<1) | 0, (fn<carry, RC0>)); \
OPr_fp(opcode, ((subopcode)<<1) | 1, (fn<carry, RC1>)); \
} while (0)
#define OPXcod(opcode, subopcode, fn, carry) \
do { \
OPr(opcode, ((subopcode)<<1) | 0x000, (fn<carry, RC0, OV0>)); \
OPr(opcode, ((subopcode)<<1) | 0x001, (fn<carry, RC1, OV0>)); \
OPr(opcode, ((subopcode)<<1) | 0x400, (fn<carry, RC0, OV1>)); \
OPr(opcode, ((subopcode)<<1) | 0x401, (fn<carry, RC1, OV1>)); \
} while (0)
#define OPla(opcode, subopcode, fn) \
do { \
for (uint32_t mod = 0; mod < 512; mod++) { \
OPr(opcode, (mod << 2) | (subopcode), fn); \
} \
} while (0)
#define OP31(subopcode, fn) OPX(31, subopcode, fn) #define OP31(subopcode, fn) OPX(31, subopcode, fn)
#define OP31_fp(subopcode, fn) OPX_fp(31, subopcode, fn)
#define OP31d(subopcode, fn) OPXd(31, subopcode, fn) #define OP31d(subopcode, fn) OPXd(31, subopcode, fn)
#define OP31od(subopcode, fn) OPXod(31, subopcode, fn) #define OP31od(subopcode, fn) OPXod(31, subopcode, fn)
#define OP31dc(subopcode, fn, carry) OPXdc(31, subopcode, fn, carry) #define OP31dc(subopcode, fn, carry) OPXdc(31, subopcode, fn, carry)
#define OP31cod(subopcode, fn, carry) OPXcod(31, subopcode, fn, carry) #define OP31cod(subopcode, fn, carry) OPXcod(31, subopcode, fn, carry)
#define OP63(subopcode, fn) OPX_fp(63, subopcode, fn) #define OP63(subopcode, fn) OPX(63, subopcode, fn)
#define OP63d(subopcode, fn) OPXd_fp(63, subopcode, fn) #define OP63d(subopcode, fn) OPXd(63, subopcode, fn)
#define OP63dc(subopcode, fn, carry) OPXdc_fp(63, subopcode, fn, carry) #define OP63dc(subopcode, fn, carry) OPXdc(63, subopcode, fn, carry)
#define OP59d(subopcode, fn) OPXd_fp(59, (subopcode), fn) #define OP59d(subopcode, fn) \
do { \
OPXd(59, (subopcode), fn); \
} while (0)
#define OP59cd(subopcode, fn) \ #define OP59cd(subopcode, fn) \
do { \ do { \
for (uint32_t ccccc = 0; ccccc < 32; ccccc++) { \ for (uint32_t ccccc = 0; ccccc < 32; ccccc++) { \
OPXd_fp(59, (ccccc << 5) | (subopcode), fn); \ OPXd(59, (ccccc << 5) | (subopcode), fn); \
} \
} while (0)
#define OP4_ccccc10xxxx(subopcode, fn) \
do { \
for (uint32_t ccccc = 0; ccccc < 32; ccccc++) { \
OPr(4, (ccccc << 6) | (subopcode), fn); \
} \ } \
} while (0) } while (0)
void initialize_ppc_opcode_table() { void initialize_ppc_opcode_table() {
auto opcodeGrabberSize = sizeof(OpcodeGrabber) / sizeof(OpcodeGrabber[0]); std::fill_n(OpcodeGrabber, 64 * 2048, ppc_illegalop);
std::fill_n(OpcodeGrabber, opcodeGrabberSize, ppc_illegalop);
std::fill_n(OpcodeGrabberNoFPU, opcodeGrabberSize, ppc_illegalop);
OP(3, ppc_twi); OP(3, ppc_twi);
//OP(4, ppc_opcode4); - Altivec instructions not emulated yet. Uncomment once they're implemented. //OP(4, ppc_opcode4); - Altivec instructions not emulated yet. Uncomment once they're implemented.
OP(7, ppc_mulli); OP(7, ppc_mulli);
@@ -777,14 +526,14 @@ void initialize_ppc_opcode_table() {
OP(45, ppc_stu<uint16_t>); OP(45, ppc_stu<uint16_t>);
OP(46, ppc_lmw); OP(46, ppc_lmw);
OP(47, ppc_stmw); OP(47, ppc_stmw);
OP_fp(48, ppc_lfs); OP(48, ppc_lfs);
OP_fp(49, ppc_lfsu); OP(49, ppc_lfsu);
OP_fp(50, ppc_lfd); OP(50, ppc_lfd);
OP_fp(51, ppc_lfdu); OP(51, ppc_lfdu);
OP_fp(52, ppc_stfs); OP(52, ppc_stfs);
OP_fp(53, ppc_stfsu); OP(53, ppc_stfsu);
OP_fp(54, ppc_stfd); OP(54, ppc_stfd);
OP_fp(55, ppc_stfdu); OP(55, ppc_stfdu);
OPla(16, 0x0, (dppc_interpreter::ppc_bc<LK0, AA0>)); // bc OPla(16, 0x0, (dppc_interpreter::ppc_bc<LK0, AA0>)); // bc
OPla(16, 0x1, (dppc_interpreter::ppc_bc<LK1, AA0>)); // bcl OPla(16, 0x1, (dppc_interpreter::ppc_bc<LK1, AA0>)); // bcl
@@ -846,11 +595,11 @@ void initialize_ppc_opcode_table() {
OP31(375, ppc_lhaux); OP31(375, ppc_lhaux);
OP31(533, ppc_lswx); OP31(533, ppc_lswx);
OP31(534, ppc_lwbrx); OP31(534, ppc_lwbrx);
OP31_fp(535, ppc_lfsx); OP31(535, ppc_lfsx);
OP31_fp(567, ppc_lfsux); OP31(567, ppc_lfsux);
OP31(597, ppc_lswi); OP31(597, ppc_lswi);
OP31_fp(599, ppc_lfdx); OP31(599, ppc_lfdx);
OP31_fp(631, ppc_lfdux); OP31(631, ppc_lfdux);
OP31(790, ppc_lhbrx); OP31(790, ppc_lhbrx);
OPr(31, (150<<1) | 1, ppc_stwcx); // No Rc=0 variant. OPr(31, (150<<1) | 1, ppc_stwcx); // No Rc=0 variant.
@@ -862,13 +611,13 @@ void initialize_ppc_opcode_table() {
OP31(439, ppc_stux<uint16_t>); OP31(439, ppc_stux<uint16_t>);
OP31(661, ppc_stswx); OP31(661, ppc_stswx);
OP31(662, ppc_stwbrx); OP31(662, ppc_stwbrx);
OP31_fp(663, ppc_stfsx); OP31(663, ppc_stfsx);
OP31_fp(695, ppc_stfsux); OP31(695, ppc_stfsux);
OP31(725, ppc_stswi); OP31(725, ppc_stswi);
OP31_fp(727, ppc_stfdx); OP31(727, ppc_stfdx);
OP31_fp(759, ppc_stfdux); OP31(759, ppc_stfdux);
OP31(918, ppc_sthbrx); OP31(918, ppc_sthbrx);
if (!is_601) OP31_fp(983, ppc_stfiwx); if (!is_601) OP31(983, ppc_stfiwx);
OP31(310, ppc_eciwx); OP31(310, ppc_eciwx);
OP31(438, ppc_ecowx); OP31(438, ppc_ecowx);
@@ -988,46 +737,18 @@ void initialize_ppc_opcode_table() {
OP63d(i + 30, ppc_fnmsub); OP63d(i + 30, ppc_fnmsub);
OP63d(i + 31, ppc_fnmadd); OP63d(i + 31, ppc_fnmadd);
} }
for (auto i = 0; i < opcodeGrabberSize; i++) {
if (OpcodeGrabberNoFPU[i] != ppc_fpu_off) {
OpcodeGrabberNoFPU[i] = OpcodeGrabber[i];
}
}
} }
void ppc_cpu_init(MemCtrlBase* mem_ctrl, uint32_t cpu_version, bool do_include_601, uint64_t tb_freq) void ppc_cpu_init(MemCtrlBase* mem_ctrl, uint32_t cpu_version, bool do_include_601, uint64_t tb_freq)
{ {
mem_ctrl_instance = mem_ctrl; mem_ctrl_instance = mem_ctrl;
int_pin = false;
std::memset(&ppc_state, 0, sizeof(ppc_state)); std::memset(&ppc_state, 0, sizeof(ppc_state));
set_host_rounding_mode(0); set_host_rounding_mode(0);
ppc_state.spr[SPR::PVR] = cpu_version; ppc_state.spr[SPR::PVR] = cpu_version;
is_601 = (cpu_version >> 16) == 1; is_601 = (cpu_version >> 16) == 1;
include_601 = !is_601 & do_include_601; include_601 = !is_601 & do_include_601;
ppc_pow_mode = PPCPowMode::None;
ppc_pow_hid0_mask = 0;
switch (cpu_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(); initialize_ppc_opcode_table();
@@ -1041,52 +762,27 @@ void ppc_cpu_init(MemCtrlBase* mem_ctrl, uint32_t cpu_version, bool do_include_6
#endif #endif
g_nanoseconds_base = cpu_now_ns(); g_nanoseconds_base = cpu_now_ns();
g_icycles = 0; g_icycles = 0;
//icnt_factor = 6;
// // // PDM cpu clock calculated at 0x403036CC in r3 icnt_factor = 4;
// 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
tbr_wr_timestamp = 0; tbr_wr_timestamp = 0;
rtc_timestamp = 0; rtc_timestamp = 0;
tbr_wr_value = 0; tbr_wr_value = 0;
if (is_601) tbr_freq_ghz = (tb_freq << 32) / NS_PER_SEC;
tb_freq <<= 7;
tbr_freq_shift = 0;
uint64_t x;
for (x = (tb_freq << 32) / NS_PER_SEC; x >> 32; x >>= 1)
tbr_freq_shift++;
tbr_freq_ghz = (uint32_t)x;
tbr_period_ns = ((uint64_t)NS_PER_SEC << 32) / tb_freq; tbr_period_ns = ((uint64_t)NS_PER_SEC << 32) / tb_freq;
exec_flags = 0;
exec_timer = false; exec_timer = false;
timebase_counter = 0;
dec_wr_value = 0; dec_wr_value = 0;
#ifdef LOG_INSTRUCTIONS
pcp = 0;
#endif
uint32_t new_msr_val;
if (is_601) { if (is_601) {
/* MPC601 sets MSR[ME] bit during hard reset / Power-On */ /* MPC601 sets MSR[ME] bit during hard reset / Power-On */
new_msr_val = (MSR::ME + MSR::IP); ppc_state.msr = (MSR::ME + MSR::IP);
} else { } else {
new_msr_val = MSR::IP; ppc_state.msr = MSR::IP;
ppc_state.spr[SPR::DEC_S] = 0xFFFFFFFFUL; 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);
ppc_mmu_init(); ppc_mmu_init();
@@ -1099,6 +795,11 @@ void ppc_cpu_init(MemCtrlBase* mem_ctrl, uint32_t cpu_version, bool do_include_6
#endif #endif
} }
void print_fprs() {
for (int i = 0; i < 32; i++)
cout << "FPR " << dec << i << " : " << ppc_state.fpr[i].dbl64_r << endl;
}
static map<string, int> SPRName2Num = { static map<string, int> SPRName2Num = {
{"XER", SPR::XER}, {"LR", SPR::LR}, {"CTR", SPR::CTR}, {"XER", SPR::XER}, {"LR", SPR::LR}, {"CTR", SPR::CTR},
{"DEC", SPR::DEC_S}, {"PVR", SPR::PVR}, {"SPRG0", SPR::SPRG0}, {"DEC", SPR::DEC_S}, {"PVR", SPR::PVR}, {"SPRG0", SPR::SPRG0},
@@ -1111,15 +812,12 @@ static map<string, int> SPRName2Num = {
{"DBAT2L", 541}, {"DBAT3U", 542}, {"DBAT3L", 543}, {"DBAT2L", 541}, {"DBAT3U", 542}, {"DBAT3L", 543},
{"HID0", SPR::HID0}, {"HID1", SPR::HID1}, {"IABR", 1010}, {"HID0", SPR::HID0}, {"HID1", SPR::HID1}, {"IABR", 1010},
{"DABR", 1013}, {"L2CR", 1017}, {"ICTC", 1019}, {"DABR", 1013}, {"L2CR", 1017}, {"ICTC", 1019},
{"THRM1", SPR::THRM1}, {"THRM2", SPR::THRM2}, {"THRM3", SPR::THRM3}, {"THRM1", 1020}, {"THRM2", 1021}, {"THRM3", 1022},
{"PIR", 1023}, {"TBL", SPR::TBL_S}, {"TBU", SPR::TBU_S}, {"PIR", 1023}, {"TBL", SPR::TBL_S}, {"TBU", SPR::TBU_S},
{"SDR1", SPR::SDR1}, {"MQ", SPR::MQ}, {"RTCU", SPR::RTCU_S}, {"SDR1", SPR::SDR1}, {"MQ", SPR::MQ}, {"RTCU", SPR::RTCU_S},
{"RTCL", SPR::RTCL_S}, {"DSISR", SPR::DSISR}, {"DAR", SPR::DAR}, {"RTCL", SPR::RTCL_S}, {"DSISR", SPR::DSISR}, {"DAR", SPR::DAR},
{"MMCR0", SPR::MMCR0}, {"PMC1", SPR::PMC1}, {"PMC2", SPR::PMC2}, {"MMCR0", SPR::MMCR0}, {"PMC1", SPR::PMC1}, {"PMC2", SPR::PMC2},
{"SDA", SPR::SDA}, {"SIA", SPR::SIA}, {"MMCR1", SPR::MMCR1}, {"SDA", SPR::SDA}, {"SIA", SPR::SIA}, {"MMCR1", SPR::MMCR1}
{"PMC3", SPR::PMC3}, {"PMC4", SPR::PMC4},
// get value from supervisor index same as we do for SPR268 and SPR269
{"TBL_U", SPR::TBL_S}, {"TBU_U", SPR::TBU_S},
}; };
static uint64_t reg_op(string& reg_name, uint64_t val, bool is_write) { static uint64_t reg_op(string& reg_name, uint64_t val, bool is_write) {
@@ -1144,14 +842,8 @@ static uint64_t reg_op(string& reg_name, uint64_t val, bool is_write) {
return ppc_state.pc; return ppc_state.pc;
} }
if (reg_name_u == "MSR") { if (reg_name_u == "MSR") {
if (is_write) { if (is_write)
uint32_t old_msr_val = ppc_state.msr; ppc_state.msr = (uint32_t)val;
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; return ppc_state.msr;
} }
if (reg_name_u == "CR") { if (reg_name_u == "CR") {
@@ -1205,13 +897,8 @@ 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::TBL_U : reg_num = SPR::TBL_S ; break;
case SPR::TBU_U : reg_num = SPR::TBU_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; 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]; return ppc_state.spr[reg_num];
} }
} }
+250 -185
View File
File diff suppressed because it is too large. Load diff
+213
View File
@@ -0,0 +1,213 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-24 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef PPC_MACROS_H
#define PPC_MACROS_H
#include <cinttypes>
#define ppc_grab_regsdasimm(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int32_t simm = int32_t(int16_t(opcode)); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsdauimm(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
uint32_t uimm = uint16_t(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsasimm(opcode) \
int reg_a = (opcode >> 16) & 31; \
int32_t simm = int32_t(int16_t(opcode)); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssauimm(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
uint32_t uimm = uint16_t(opcode); \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_crfd_regsauimm(opcode) \
int crf_d = (opcode >> 21) & 0x1C; \
int reg_a = (opcode >> 16) & 31; \
uint32_t uimm = uint16_t(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_da(opcode)\
int reg_d = (opcode >> 21) & 31;\
int reg_a = (opcode >> 16) & 31;\
#define ppc_grab_dab(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31;
#define ppc_grab_s(opcode) \
int reg_s = (opcode >> 21) & 31; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s];
#define ppc_grab_regsdab(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regssab(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b]; \
#define ppc_grab_regssab_stswx(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regsab(opcode) \
int reg_a = (opcode >> 16) & 31;\
int reg_b = (opcode >> 11) & 31;\
uint32_t ppc_result_a = ppc_state.gpr[reg_a];\
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regssa(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssa_stmw(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssash(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
unsigned rot_sh = (opcode >> 11) & 31; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssash_stswi(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
unsigned rot_sh = (opcode >> 11) & 31; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssb(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_b = (opcode >> 11) & 31; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b]; \
#define ppc_grab_regsda(opcode) \
int reg_d = (opcode >> 21) & 31; \
uint32_t reg_a = (opcode >> 16) & 31; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsdb(opcode) \
int reg_d = (opcode >> 21) & 31; \
uint32_t reg_b = (opcode >> 11) & 31; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_store_iresult_reg(reg, ppc_result)\
ppc_state.gpr[reg] = ppc_result
#define ppc_store_fpresult_int(reg, ppc_result64_d)\
ppc_state.fpr[(reg)].int64_r = ppc_result64_d
#define ppc_store_fpresult_flt(reg, ppc_dblresult64_d)\
ppc_state.fpr[(reg)].dbl64_r = ppc_dblresult64_d
#define ppc_grab_regsfpdb(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_b = (opcode >> 11) & 31;
#define GET_FPR(reg) \
ppc_state.fpr[(reg)].dbl64_r
#define FPR_INT(reg) \
ppc_state.fpr[reg].int64_r
#define ppc_grab_regsfpdiab(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
uint32_t val_reg_a = ppc_state.gpr[reg_a]; \
uint32_t val_reg_b = ppc_state.gpr[reg_b];
#define ppc_grab_regsfpdia(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
uint32_t val_reg_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsfpsia(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
uint32_t val_reg_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsfpsiab(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
uint32_t val_reg_a = ppc_state.gpr[reg_a]; \
uint32_t val_reg_b = ppc_state.gpr[reg_b];
#define ppc_grab_regsfpsab(opcode) \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
int crf_d = (opcode >> 21) & 0x1C; \
double db_test_a = GET_FPR(reg_a); \
double db_test_b = GET_FPR(reg_b);
#define ppc_grab_regsfpdab(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
double val_reg_a = GET_FPR(reg_a); \
double val_reg_b = GET_FPR(reg_b);
#define ppc_grab_regsfpdac(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_c = (opcode >> 6) & 31; \
double val_reg_a = GET_FPR(reg_a); \
double val_reg_c = GET_FPR(reg_c);
#define ppc_grab_regsfpdabc(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
int reg_c = (opcode >> 6) & 31; \
double val_reg_a = GET_FPR(reg_a); \
double val_reg_b = GET_FPR(reg_b); \
double val_reg_c = GET_FPR(reg_c);
#endif // PPC_MACROS_H
+351 -755
View File
File diff suppressed because it is too large. Load diff
+38 -9
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-21 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -24,6 +24,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef PPCMMU_H #ifndef PPCMMU_H
#define PPCMMU_H #define PPCMMU_H
#include <devices/memctrl/memctrlbase.h>
#include <cinttypes> #include <cinttypes>
#include <functional> #include <functional>
@@ -82,19 +84,46 @@ typedef struct MapDmaResult {
constexpr uint32_t PPC_PAGE_SIZE_BITS = 12; constexpr uint32_t PPC_PAGE_SIZE_BITS = 12;
constexpr uint32_t PPC_PAGE_SIZE = (1 << PPC_PAGE_SIZE_BITS); constexpr uint32_t PPC_PAGE_SIZE = (1 << PPC_PAGE_SIZE_BITS);
constexpr uint32_t PPC_PAGE_MASK = ~(PPC_PAGE_SIZE - 1); 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;
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)> ibat_update;
extern std::function<void(uint32_t bat_reg)> dbat_update; extern std::function<void(uint32_t bat_reg)> dbat_update;
extern PPC_BAT_entry ibat_array[4]; extern MapDmaResult mmu_map_dma_mem(uint32_t addr, uint32_t size, bool allow_mmio);
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_change_mode(void);
extern void mmu_pat_ctx_changed(); extern void mmu_pat_ctx_changed();
extern void tlb_flush_all_pat(); 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 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); extern void mem_write_dbg(uint32_t virt_addr, uint64_t value, int size);
+474 -596
View File
File diff suppressed because it is too large. Load diff
-4
View File
@@ -313,10 +313,6 @@ def gen_rot_opcode(opc_str, sh, mb, me):
return (0x15 << 26) + (4 << 21) + (3 << 16) + (sh << 11) + (mb << 6) + (me << 1) return (0x15 << 26) + (4 << 21) + (3 << 16) + (sh << 11) + (mb << 6) + (me << 1)
elif opc_str == "RLWINM.": elif opc_str == "RLWINM.":
return (0x15 << 26) + (4 << 21) + (3 << 16) + (sh << 11) + (mb << 6) + (me << 1) + 1 return (0x15 << 26) + (4 << 21) + (3 << 16) + (sh << 11) + (mb << 6) + (me << 1) + 1
elif opc_str == "RLWNM":
return (0x17 << 26) + (4 << 21) + (3 << 16) + (3 << 11) + (mb << 6) + (me << 1)
elif opc_str == "RLWNM.":
return (0x17 << 26) + (4 << 21) + (3 << 16) + (3 << 11) + (mb << 6) + (me << 1) + 1
def extract_imm(line): def extract_imm(line):
pos = 12 pos = 12
-4
View File
@@ -407,10 +407,6 @@
0xFFF00100,0x7D453D2A,stswx,r10,r5,r7 0xFFF00100,0x7D453D2A,stswx,r10,r5,r7
0xFFF00100,0x7C0002E4,tlbia 0xFFF00100,0x7C0002E4,tlbia
0xFFF00100,0x7C004A64,tlbie,r9 0xFFF00100,0x7C004A64,tlbie,r9
0xFFF00100,0x7C202FA4,tlbld,r5
0xFFF00100,0x7C6007A4,tlbld,r0
0xFFF00100,0x7C203FE4,tlbli,r7
0xFFF00100,0x7C40FFE4,tlbli,r31
# various simplified (extended) mnemonics # various simplified (extended) mnemonics
0xFFF00100,0x60000000,nop 0xFFF00100,0x60000000,nop
1 # Test data for PowerPC disassembler supplied as comma-separated values
407 0xFFF00100,0x7C00003A,maskg,r0,r0,r0 0xFFF00100,0x7C430C32,rrib,r3,r2,r1
408 0xFFF00100,0x7E3EE43A,maskir,r30,r17,r28 0xFFF00100,0x7C430C33,rrib.,r3,r2,r1
409 0xFFF00100,0x58411800,rlmi,r1,r2,r3,0,0 0xFFF00100,0x7C410132,sle,r1,r2,r0
0xFFF00100,0x58411801,rlmi.,r1,r2,r3,0,0
0xFFF00100,0x7C430C32,rrib,r3,r2,r1
0xFFF00100,0x7C430C33,rrib.,r3,r2,r1
0xFFF00100,0x7C410132,sle,r1,r2,r0
410 0xFFF00100,0x7C410133,sle.,r1,r2,r0
411 0xFFF00100,0x7C4101B2,sleq,r1,r2,r0
412 0xFFF00100,0x7C4101B3,sleq.,r1,r2,r0
+9 -14
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -37,7 +37,7 @@ int ntested; // number of tested instructions
int nfailed; // number of failed instructions int nfailed; // number of failed instructions
#if defined(PPC_TESTS) #if defined(PPC_TESTS)
void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) { void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits, uint32_t exec_flags) {
power_on = false; power_on = false;
} }
#endif #endif
@@ -46,7 +46,7 @@ void xer_ov_test(string mnem, uint32_t opcode) {
ppc_state.gpr[3] = 2; ppc_state.gpr[3] = 2;
ppc_state.gpr[4] = 2; ppc_state.gpr[4] = 2;
ppc_state.spr[SPR::XER] = 0xFFFFFFFF; ppc_state.spr[SPR::XER] = 0xFFFFFFFF;
ppc_main_opcode(ppc_opcode_grabber, opcode); ppc_main_opcode(opcode);
if (ppc_state.spr[SPR::XER] & 0x40000000UL) { if (ppc_state.spr[SPR::XER] & 0x40000000UL) {
cout << "Invalid " << mnem << " emulation! XER[OV] should not be set." << endl; cout << "Invalid " << mnem << " emulation! XER[OV] should not be set." << endl;
nfailed++; nfailed++;
@@ -150,7 +150,7 @@ static void read_test_data() {
ppc_state.spr[SPR::XER] = 0; ppc_state.spr[SPR::XER] = 0;
ppc_state.cr = 0; ppc_state.cr = 0;
ppc_main_opcode(ppc_opcode_grabber, opcode); ppc_main_opcode(opcode);
ntested++; ntested++;
@@ -292,7 +292,7 @@ static void read_test_float_data() {
ppc_state.cr = 0; ppc_state.cr = 0;
ppc_main_opcode(ppc_opcode_grabber, opcode); ppc_main_opcode(opcode);
ntested++; ntested++;
@@ -302,11 +302,10 @@ static void read_test_float_data() {
if ((tokens[0].rfind("FCMP") && (ppc_state.fpr[3].int64_r != dest_64)) || if ((tokens[0].rfind("FCMP") && (ppc_state.fpr[3].int64_r != dest_64)) ||
(ppc_state.fpscr != check_fpscr) || (ppc_state.fpscr != check_fpscr) ||
(ppc_state.cr != check_cr)) { (ppc_state.cr != check_cr)) {
cout << "Mismatch: instr=" << tokens[0] << ", src1=" << scientific << dfp_src1 cout << "Mismatch: instr=" << tokens[0] << ", src1=" << scientific << dfp_src1 << ", src2=" << scientific << dfp_src2 << ", src3=" << scientific << dfp_src3 << endl;
<< ", src2=" << scientific << dfp_src2 << ", src3=" << scientific << dfp_src3 << endl;
cout << "expected: dest=0x" << hex << dest_64 << ", FPSCR=0x" << hex << check_fpscr cout << "expected: dest=0x" << hex << dest_64 << ", FPSCR=0x" << hex << check_fpscr
<< ", CR=0x" << ", CR=0x"
<< hex << check_cr << endl; << hex << check_cr << endl;
cout << "got: dest=0x" << hex << ppc_state.fpr[3].int64_r << ", FPSCR=0x" << hex cout << "got: dest=0x" << hex << ppc_state.fpr[3].int64_r << ", FPSCR=0x" << hex
<< ppc_state.fpscr << ", CR=0x" << hex << ppc_state.cr << endl; << ppc_state.fpscr << ", CR=0x" << hex << ppc_state.cr << endl;
cout << "Test file line #: " << dec << lineno << endl << endl; cout << "Test file line #: " << dec << lineno << endl << endl;
@@ -319,10 +318,6 @@ static void read_test_float_data() {
int main() { int main() {
is_601 = true; is_601 = true;
initialize_ppc_opcode_table(); //kludge initialize_ppc_opcode_table(); //kludge
// MPC601 sets MSR[ME] bit during hard reset / Power-On.
// Also set MSR[FP] bit so we can test FPU instructions.
int new_msr = (MSR::ME | MSR::IP | MSR::FP);
ppc_msr_did_change(ppc_state.msr, new_msr, false);
cout << "Running DingusPPC emulator tests..." << endl << endl; cout << "Running DingusPPC emulator tests..." << endl << endl;
+4 -4
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-21 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -73,7 +73,7 @@ static vector<PPCDisasmContext> read_test_data() {
/* put instruction mnemonic padded with trailing spaces */ /* put instruction mnemonic padded with trailing spaces */
idisasm << tokens[2]; idisasm << tokens[2];
idisasm << setw(streamsize(8) - (int)tokens[2].length()) << " "; idisasm << setw(8 - (int)tokens[2].length()) << " ";
/* now add comma-separated operands */ /* now add comma-separated operands */
for (i = 3; i < tokens.size(); i++) { for (i = 3; i < tokens.size(); i++) {
+1 -2
View File
@@ -2,7 +2,6 @@ include_directories("${PROJECT_SOURCE_DIR}"
"${PROJECT_SOURCE_DIR}/thirdparty/loguru/" "${PROJECT_SOURCE_DIR}/thirdparty/loguru/"
"${PROJECT_SOURCE_DIR}/thirdparty/capstone/include") "${PROJECT_SOURCE_DIR}/thirdparty/capstone/include")
file(GLOB SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp" file(GLOB SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp")
"${CMAKE_CURRENT_SOURCE_DIR}/*.h")
add_library(debugger OBJECT ${SOURCES}) add_library(debugger OBJECT ${SOURCES})
+101 -430
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -19,14 +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/>. 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/ppcdisasm.h>
#include <cpu/ppc/ppcemu.h> #include <cpu/ppc/ppcemu.h>
#include <cpu/ppc/ppcmmu.h> #include <cpu/ppc/ppcmmu.h>
#include <debugger/debugger.h> #include <debugger/debugger.h>
#include <devices/common/hwinterrupt.h> #include <devices/common/hwinterrupt.h>
#include <devices/common/ofnvram.h> #include <devices/common/ofnvram.h>
#include "memaccess.h"
#include <utils/profiler.h> #include <utils/profiler.h>
#include <array> #include <array>
@@ -52,17 +51,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
using namespace std; using namespace std;
#define COUTX uppercase << hex
#define COUT0_X(w) setfill('0') << setw(w) << right << COUTX
#define COUT016X COUT0_X(16)
#define COUT08X COUT0_X(8)
#define COUT04X COUT0_X(4)
extern bool g_auto_grab_mouse;
static uint32_t str2addr(string& addr_str) { static uint32_t str2addr(string& addr_str) {
try { try {
return static_cast<uint32_t>(stoul(addr_str, NULL, 0)); return (uint32_t)stoul(addr_str, NULL, 0);
} catch (invalid_argument& exc) { } catch (invalid_argument& exc) {
throw invalid_argument(string("Cannot convert ") + addr_str); throw invalid_argument(string("Cannot convert ") + addr_str);
} }
@@ -70,7 +61,7 @@ static uint32_t str2addr(string& addr_str) {
static uint32_t str2num(string& num_str) { static uint32_t str2num(string& num_str) {
try { try {
return static_cast<uint32_t>(stol(num_str, NULL, 0)); return (uint32_t)stol(num_str, NULL, 0);
} catch (invalid_argument& exc) { } catch (invalid_argument& exc) {
throw invalid_argument(string("Cannot convert ") + num_str); throw invalid_argument(string("Cannot convert ") + num_str);
} }
@@ -78,51 +69,41 @@ static uint32_t str2num(string& num_str) {
static void show_help() { static void show_help() {
cout << "Debugger commands:" << endl; cout << "Debugger commands:" << endl;
cout << " step [N] -- execute single instruction" << endl; cout << " step [N] -- execute single instruction" << endl;
cout << " N is an optional step count" << endl; cout << " N is an optional step count" << endl;
cout << " si [N] -- shortcut for step" << endl; cout << " si [N] -- shortcut for step" << endl;
cout << " next -- same as step but treats subroutine calls" << endl; cout << " next -- same as step but treats subroutine calls" << endl;
cout << " as single instructions." << endl; cout << " as single instructions." << endl;
cout << " ni -- shortcut for next" << endl; cout << " ni -- shortcut for next" << endl;
cout << " until X -- execute until address X is reached" << endl; cout << " until X -- execute until address X is reached" << endl;
cout << " go -- exit debugger and continue emulator execution" << endl; cout << " go -- exit debugger and continue emulator execution" << endl;
cout << " regs -- dump content of the GPRs" << endl; cout << " regs -- dump content of the GRPs" << endl;
cout << " fregs -- dump content of the FPRs" << endl; cout << " mregs -- dump content of the MMU registers" << endl;
cout << " mregs -- dump content of the MMU registers" << endl; cout << " set R=X -- assign value X to register R" << endl;
cout << " set R=X -- assign value X to register R" << endl; cout << " if R=loglevel, set the internal" << endl;
cout << " if R=loglevel, set the internal" << endl; cout << " log level to X whose range is -2...9" << endl;
cout << " log level to X whose range is -2...9" << endl; cout << " dump NT,X -- dump N memory cells of size T at address X" << endl;
cout << " dump NT,X -- dump N memory cells of size T at address X" << endl; cout << " T can be b(byte), w(word), d(double)," << endl;
cout << " T can be b(byte), w(word), d(double)," << endl; cout << " q(quad) or c(character)." << endl;
cout << " q(quad) or c(character)." << endl; cout << " profile C N -- run subcommand C on profile N" << endl;
cout << " setmem X=V.T -- set memory at address X to value V of size T" << endl; cout << " supported subcommands:" << endl;
cout << " T can be b(byte), w(word), d(double)," << endl; cout << " 'show' - show profile report" << endl;
cout << " q(quad) or c(character)." << endl; cout << " 'reset' - reset profile variables" << endl;
cout << " regions -- dump memory regions" << endl;
cout << " profile C N -- run subcommand C on profile N" << endl;
cout << " supported subcommands:" << endl;
cout << " 'show' - show profile report" << endl;
cout << " 'reset' - reset profile variables" << endl;
#ifdef PROFILER #ifdef PROFILER
cout << " profiler -- show stats related to the processor" << endl; cout << " profiler -- show stats related to the processor" << endl;
#endif #endif
cout << " disas N,X -- disassemble N instructions starting at address X" << endl; cout << " disas N,X -- disassemble N instructions starting at address X" << endl;
cout << " X can be any number or a known register name" << endl; cout << " X can be any number or a known register name" << endl;
cout << " disas with no arguments defaults to disas 1,pc" << endl; cout << " disas with no arguments defaults to disas 1,pc" << endl;
cout << " da N,X -- shortcut for disas" << endl; cout << " da N,X -- shortcut for disas" << endl;
#ifdef ENABLE_68K_DEBUGGER #ifdef ENABLE_68K_DEBUGGER
cout << " context X -- switch to the debugging context X." << endl; cout << " context X -- switch to the debugging context X." << endl;
cout << " X can be either 'ppc' (default) or '68k'" << endl; cout << " X can be either 'ppc' (default) or '68k'" << endl;
cout << " Use 68k for debugging emulated 68k code only." << endl; cout << " Use 68k for debugging emulated 68k code only." << endl;
#endif #endif
cout << " printenv -- print current NVRAM settings." << endl; cout << " printenv -- print current NVRAM settings." << endl;
cout << " setenv V N -- set NVRAM variable V to value N." << endl; cout << " setenv V N -- set NVRAM variable V to value N." << endl;
cout << endl; cout << " quit -- quit the debugger" << endl << 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;
cout << "Pressing ENTER will repeat last command." << endl; cout << "Pressing ENTER will repeat last command." << endl;
} }
@@ -130,7 +111,7 @@ static void show_help() {
static uint32_t disasm_68k(uint32_t count, uint32_t address) { static uint32_t disasm_68k(uint32_t count, uint32_t address) {
csh cs_handle; csh cs_handle;
uint8_t code[12]{}; uint8_t code[10];
size_t code_size; size_t code_size;
uint64_t dis_addr; uint64_t dis_addr;
@@ -142,14 +123,9 @@ static uint32_t disasm_68k(uint32_t count, uint32_t address) {
cs_insn* insn = cs_malloc(cs_handle); cs_insn* insn = cs_malloc(cs_handle);
for (; power_on && count > 0; count--) { for (; power_on && count > 0; count--) {
// prefetch opcode bytes (a 68k instruction can occupy 2...12 bytes) /* prefetch opcode bytes (a 68k instruction can occupy 2...10 bytes) */
for (int i = 0; i < sizeof(code); i++) { for (int i = 0; i < sizeof(code); i++) {
try { code[i] = mem_read_dbg(address + i, 1);
code[i] = mem_read_dbg(address + i, 1);
}
catch(...) {
printf("<memerror>");
}
} }
const uint8_t *code_ptr = code; const uint8_t *code_ptr = code;
@@ -163,16 +139,16 @@ static uint32_t disasm_68k(uint32_t count, uint32_t address) {
} }
if (cs_disasm_iter(cs_handle, &code_ptr, &code_size, &dis_addr, insn)) { if (cs_disasm_iter(cs_handle, &code_ptr, &code_size, &dis_addr, insn)) {
cout << COUTX << insn->address << " "; cout << uppercase << hex << insn->address << " ";
cout << setfill(' '); cout << setfill(' ');
cout << setw(10) << left << insn->mnemonic << insn->op_str << right << endl; cout << setw(10) << left << insn->mnemonic << insn->op_str << endl;
address = static_cast<uint32_t>(dis_addr); address = dis_addr;
} else { } else {
print_bin: print_bin:
cout << COUTX << address << " "; cout << uppercase << hex << address << " ";
cout << setfill(' '); cout << setfill(' ');
cout << setw(10) << left << "dc.w" << "$" << hex << cout << setw(10) << left << "dc.w" << "$" << hex <<
((code[0] << 8) | code[1]) << right << endl; ((code[0] << 8) | code[1]) << endl;
address += 2; address += 2;
} }
} }
@@ -183,7 +159,7 @@ print_bin:
} }
/* emulator opcode table size --> 512 KB */ /* emulator opcode table size --> 512 KB */
constexpr auto EMU_68K_TABLE_SIZE = 0x80000; #define EMU_68K_TABLE_SIZE 0x80000
/** Execute one emulated 68k instruction. */ /** Execute one emulated 68k instruction. */
void exec_single_68k() void exec_single_68k()
@@ -192,7 +168,7 @@ void exec_single_68k()
/* PPC r24 contains 68k PC advanced by two bytes /* PPC r24 contains 68k PC advanced by two bytes
as part of instruction prefetching */ as part of instruction prefetching */
cur_68k_pc = static_cast<uint32_t>(get_reg(string("R24")) - 2); cur_68k_pc = get_reg(string("R24")) - 2;
/* PPC r29 contains base address of the emulator opcode table */ /* PPC r29 contains base address of the emulator opcode table */
emu_table_virt = get_reg(string("R29")) & 0xFFF80000; emu_table_virt = get_reg(string("R29")) & 0xFFF80000;
@@ -202,7 +178,7 @@ void exec_single_68k()
cur_instr_tab_entry = mmu_read_vmem<uint16_t>(NO_OPCODE, cur_68k_pc) * 8 + emu_table_virt; cur_instr_tab_entry = mmu_read_vmem<uint16_t>(NO_OPCODE, cur_68k_pc) * 8 + emu_table_virt;
/* grab the PPC PC too */ /* grab the PPC PC too */
ppc_pc = static_cast<uint32_t>(get_reg(string("PC"))); ppc_pc = get_reg(string("PC"));
//printf("cur_instr_tab_entry = %X\n", cur_instr_tab_entry); //printf("cur_instr_tab_entry = %X\n", cur_instr_tab_entry);
@@ -211,7 +187,7 @@ void exec_single_68k()
one by one until the execution goes outside the opcode table. */ one by one until the execution goes outside the opcode table. */
while (power_on && ppc_pc >= cur_instr_tab_entry && ppc_pc < cur_instr_tab_entry + 8) { while (power_on && ppc_pc >= cur_instr_tab_entry && ppc_pc < cur_instr_tab_entry + 8) {
ppc_exec_single(); ppc_exec_single();
ppc_pc = static_cast<uint32_t>(get_reg(string("PC"))); ppc_pc = get_reg(string("PC"));
} }
/* Getting here means we're outside the emualtor opcode table. /* Getting here means we're outside the emualtor opcode table.
@@ -244,22 +220,21 @@ void print_68k_regs()
for (i = 0; i < 8; i++) { for (i = 0; i < 8; i++) {
reg = "R" + to_string(i + 8); reg = "R" + to_string(i + 8);
cout << " D" << dec << i << " : " << COUT08X << get_reg(reg) << endl; cout << "D" << dec << i << " : " << uppercase << hex << get_reg(reg) << endl;
} }
for (i = 0; i < 7; i++) { for (i = 0; i < 7; i++) {
reg = "R" + to_string(i + 16); reg = "R" + to_string(i + 16);
cout << " A" << dec << i << " : " << COUT08X << get_reg(reg) << endl; cout << "A" << dec << i << " : " << uppercase << hex << get_reg(reg) << endl;
} }
cout << " A7 : " << COUT08X << get_reg(string("R1")) << endl; cout << "A7 : " << uppercase << hex << get_reg(string("R1")) << endl;
cout << " PC : " << COUT08X << get_reg(string("R24")) - 2 << endl; cout << "PC: " << uppercase << hex << get_reg(string("R24")) - 2 << endl;
cout << " SR : " << COUT08X << ((get_reg("R25") & 0xFF) << 8) << endl; cout << "SR: " << uppercase << hex << ((get_reg("R25") & 0xFF) << 8) << endl;
cout << " CCR : " << COUT08X << get_reg(string("R26")) << endl; cout << "CCR: " << uppercase << hex << get_reg(string("R26")) << endl;
cout << dec << setfill(' ');
} }
#endif // ENABLE_68K_DEBUGGER #endif // ENABLE_68K_DEBUGGER
@@ -345,7 +320,8 @@ static void dump_mem(string& params) {
cout << (char)val; cout << (char)val;
chars_per_line += cell_size; chars_per_line += cell_size;
} else { } else {
cout << COUT0_X(cell_size * 2) << val << " "; cout << setw(cell_size * 2) << setfill('0') << right;
cout << uppercase << hex << val << " ";
chars_per_line += cell_size * 2 + 2; chars_per_line += cell_size * 2 + 2;
} }
} }
@@ -357,232 +333,30 @@ static void dump_mem(string& params) {
cout << endl << endl; cout << endl << endl;
} }
static void patch_mem(string& params) {
int value_size = 1;
uint32_t addr, value;
string addr_str, value_str, size_str;
if (params.find_first_of("=") == std::string::npos) {
cout << "setmem: not enough arguments specified. Try 'help'." << endl;
return;
}
addr_str = params.substr(0, params.find_first_of("="));
value_str = params.substr(params.find_first_of("=") + 1);
if (value_str.find_first_of(".") == std::string::npos) {
cout << "setmem: no value size specified. Try 'help'." << endl;
return;
}
size_str = value_str.substr(value_str.find_first_of(".") + 1);
value_str = value_str.substr(0, value_str.find_first_of("."));
switch (size_str.back()) {
case 'b':
case 'B':
value_size = 1;
break;
case 'w':
case 'W':
value_size = 2;
break;
case 'd':
case 'D':
value_size = 4;
break;
case 'q':
case 'Q':
value_size = 8;
break;
case 'c':
case 'C':
value_size = 1;
break;
default:
cout << "Invalid value size " << size_str << endl;
return;
}
try {
addr = str2addr(addr_str);
} catch (invalid_argument& exc) {
try {
// number conversion failed, trying reg name
addr = get_reg(addr_str);
} catch (invalid_argument& exc) {
cout << exc.what() << endl;
return;
}
}
try {
value = str2num(value_str);
} catch (invalid_argument& exc) {
cout << exc.what() << endl;
return;
}
try {
mem_write_dbg(addr, value, value_size);
} catch (invalid_argument& exc) {
cout << exc.what() << endl;
}
}
static uint32_t disasm(PPCDisasmContext &ctx) {
#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;
}
static uint32_t disasm(uint32_t count, uint32_t address) { static uint32_t disasm(uint32_t count, uint32_t address) {
PPCDisasmContext ctx; PPCDisasmContext ctx;
ctx.instr_addr = address; ctx.instr_addr = address;
ctx.simplified = true; ctx.simplified = true;
for (int i = 0; power_on && i < count; i++) { for (int i = 0; power_on && i < count; i++) {
disasm(ctx); ctx.instr_code = READ_DWORD_BE_A(mmu_translate_imem(ctx.instr_addr));
cout << endl; cout << setfill('0') << setw(8) << right << uppercase << hex << ctx.instr_addr;
cout << ": " << setfill('0') << setw(8) << right << uppercase << hex << ctx.instr_code;
cout << " " << disassemble_single(&ctx) << setfill(' ') << left << endl;
} }
return ctx.instr_addr; return ctx.instr_addr;
} }
static void disasm_in(PPCDisasmContext &ctx, uint32_t address) {
ctx.instr_addr = address;
ctx.simplified = true;
disasm(ctx);
if (ctx.regs_in.size() > 0 || ctx.regs_out.size() > 0) {
if (ctx.instr_str.length() < 28)
cout << setw(28 - (int)ctx.instr_str.length()) << " ";
cout << " ;";
if (ctx.regs_in.size() > 0) {
cout << " in{" << COUTX;
for (auto & reg_name : ctx.regs_in) {
cout << " " << reg_name << ":" << get_reg(reg_name);
}
cout << " }" << dec;
}
}
}
static void disasm_out(PPCDisasmContext &ctx) {
if (ctx.regs_out.size() > 0) {
cout << " out{" << COUTX;
for (auto & reg_name : ctx.regs_out) {
cout << " " << reg_name << ":" << get_reg(reg_name);
}
cout << " }" << dec;
}
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() { static void print_gprs() {
string reg_name; string reg_name;
int i; int i;
for (i = 0; i < 32; i++) { for (i = 0; i < 32; i++) {
reg_name = "r" + to_string(i); reg_name = "R" + to_string(i);
cout << right << std::setw(5) << setfill(' ') << reg_name << " : " << cout << right << std::setw(3) << setfill(' ') << reg_name << " : " <<
COUT08X << get_reg(reg_name) << setfill(' '); setw(8) << setfill('0') << right << uppercase << hex << get_reg(reg_name) << setfill(' ');
if (i & 1) { if (i & 1) {
cout << endl; cout << endl;
@@ -591,11 +365,11 @@ static void print_gprs() {
} }
} }
array<string, 8> sprs = {"pc", "lr", "cr", "ctr", "xer", "msr", "srr0", "srr1"}; array<string,6> sprs = {"PC", "LR", "CR", "CTR", "XER", "MSR"};
for (auto &spr : sprs) { for (auto &spr : sprs) {
cout << right << std::setw(5) << setfill(' ') << spr << " : " << cout << right << std::setw(3) << setfill(' ') << spr << " : " <<
COUT08X << get_reg(spr) << setfill(' '); setw(8) << setfill('0') << uppercase << hex << get_reg(spr) << setfill(' ');
if (i & 1) { if (i & 1) {
cout << endl; cout << endl;
@@ -607,62 +381,34 @@ static void print_gprs() {
} }
} }
static void print_fprs() {
string reg_name;
for (int i = 0; i < 32; i++) {
reg_name = "f" + to_string(i);
cout << right << std::setw(6) << setfill(' ') << reg_name << " : " <<
COUT016X << ppc_state.fpr[i].int64_r <<
" = " << left << setfill(' ') << ppc_state.fpr[i].dbl64_r << endl;
}
cout << right << std::setw(6) << setfill(' ') << "fpscr" << " : " <<
COUT08X << ppc_state.fpscr << setfill(' ') << endl;
}
extern bool is_601; extern bool is_601;
static void print_mmu_regs() static void print_mmu_regs()
{ {
printf(" msr : %08X\n", ppc_state.msr); printf("MSR : 0x%08X\n", ppc_state.msr);
printf("\nBAT registers:\n"); printf("\nBAT registers:\n");
for (int i = 0; i < 4 + (is_601 ? 0 : 4); i++) { for (int i = 0; i < 4; i++) {
PPC_BAT_entry *bat_entry = i < 4 ? ibat_array : dbat_array; printf("IBAT%dU : 0x%08X, IBAT%dL : 0x%08X\n",
bat_entry = &bat_entry[i & 3]; i, ppc_state.spr[528+i*2],
printf(" %sbat%du : %08X %sbat%dl : %08X", i, ppc_state.spr[529+i*2]);
is_601 ? "" : i < 4 ? "i" : "d", }
i & 3, ppc_state.spr[528+i*2],
is_601 ? "" : i < 4 ? "i" : "d", if (!is_601) {
i & 3, ppc_state.spr[529+i*2] for (int i = 0; i < 4; i++) {
); printf("DBAT%dU : 0x%08X, DBAT%dL : 0x%08X\n",
if (!is_601 || bat_entry->valid) { i, ppc_state.spr[536+i*2],
printf(" ; range : %08X..%08X -> %08X..%08X access : %s%s protection : %s%s", i, ppc_state.spr[537+i*2]);
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"); printf("\n");
printf(" sdr1 : %08X\n", ppc_state.spr[SPR::SDR1]); printf("SDR1 : 0x%08X\n", ppc_state.spr[SPR::SDR1]);
printf("\nSegment registers:\n"); printf("\nSegment registers:\n");
for (int i = 0; i < 16; i++) { for (int i = 0; i < 16; i++) {
printf(" %ssr%d : %08X\n", (i < 10) ? " " : "", i, ppc_state.sr[i]); printf("SR%-2d : 0x%08X\n", i, ppc_state.sr[i]);
} }
} }
@@ -717,7 +463,6 @@ void DppcDebugger::enter_debugger() {
uint32_t next_addr_68k; uint32_t next_addr_68k;
#endif #endif
bool cmd_repeat; bool cmd_repeat;
int repeat_count = 0;
unique_ptr<OfConfigUtils> ofnvram = unique_ptr<OfConfigUtils>(new OfConfigUtils); unique_ptr<OfConfigUtils> ofnvram = unique_ptr<OfConfigUtils>(new OfConfigUtils);
@@ -725,26 +470,26 @@ void DppcDebugger::enter_debugger() {
#ifndef _WIN32 #ifndef _WIN32
struct winsize win_size_previous; struct winsize win_size_previous;
ioctl(STDIN_FILENO, TIOCGWINSZ, &win_size_previous); ioctl(0, TIOCGWINSZ, &win_size_previous);
#endif #endif
while (1) { while (1) {
if (power_off_reason == po_shut_down) { if (power_off_reason == po_shut_down) {
set_power_off_reason(po_shutting_down); power_off_reason = po_shutting_down;
break; break;
} }
if (power_off_reason == po_restart) { if (power_off_reason == po_restart) {
set_power_off_reason(po_restarting); power_off_reason = po_restarting;
break; break;
} }
if (power_off_reason == po_quit) { if (power_off_reason == po_quit) {
set_power_off_reason(po_quitting); power_off_reason = po_quitting;
break; break;
} }
power_on = true; power_on = true;
if (power_off_reason == po_starting_up) { if (power_off_reason == po_starting_up) {
set_power_off_reason(po_none); power_off_reason = po_none;
cmd = "go"; cmd = "go";
} }
else if (power_off_reason == po_disassemble_on) { else if (power_off_reason == po_disassemble_on) {
@@ -755,16 +500,15 @@ void DppcDebugger::enter_debugger() {
ss >> cmd; ss >> cmd;
} }
else if (power_off_reason == po_disassemble_off) { else if (power_off_reason == po_disassemble_off) {
set_power_off_reason(po_none); power_off_reason = po_none;
cmd = "go"; cmd = "go";
} }
else else
{ {
if (power_off_reason == po_enter_debugger) { if (power_off_reason == po_enter_debugger) {
set_power_off_reason(po_entered_debugger); power_off_reason = po_entered_debugger;
} }
if (!did_message) { if (!did_message) {
cout << endl;
cout << "Welcome to the DingusPPC command line debugger." << endl; cout << "Welcome to the DingusPPC command line debugger." << endl;
cout << "Please enter a command or 'help'." << endl << endl; cout << "Please enter a command or 'help'." << endl << endl;
did_message = true; did_message = true;
@@ -785,7 +529,7 @@ void DppcDebugger::enter_debugger() {
#ifndef _WIN32 #ifndef _WIN32
struct winsize win_size_current; struct winsize win_size_current;
ioctl(STDIN_FILENO, TIOCGWINSZ, &win_size_current); ioctl(0, TIOCGWINSZ, &win_size_current);
if (win_size_current.ws_col != win_size_previous.ws_col || win_size_current.ws_row != win_size_previous.ws_row) { if (win_size_current.ws_col != win_size_previous.ws_col || win_size_current.ws_row != win_size_previous.ws_row) {
win_size_previous = win_size_current; win_size_previous = win_size_current;
if (cmd.empty()) { if (cmd.empty()) {
@@ -798,7 +542,7 @@ void DppcDebugger::enter_debugger() {
} }
if (power_off_reason == po_signal_interrupt) { if (power_off_reason == po_signal_interrupt) {
set_power_off_reason(po_enter_debugger); power_off_reason = po_enter_debugger;
// ignore command if interrupt happens because the input line is probably incomplete. // ignore command if interrupt happens because the input line is probably incomplete.
last_cmd = ""; last_cmd = "";
continue; continue;
@@ -812,10 +556,6 @@ void DppcDebugger::enter_debugger() {
cmd_repeat = cmd.empty() && !last_cmd.empty(); cmd_repeat = cmd.empty() && !last_cmd.empty();
if (cmd_repeat) { if (cmd_repeat) {
cmd = last_cmd; cmd = last_cmd;
repeat_count++;
}
else {
repeat_count = 1;
} }
if (cmd == "help") { if (cmd == "help") {
cmd = ""; cmd = "";
@@ -823,9 +563,6 @@ void DppcDebugger::enter_debugger() {
} else if (cmd == "quit") { } else if (cmd == "quit") {
cmd = ""; cmd = "";
break; break;
} else if (cmd == "restart") {
cmd = "";
power_off(po_restart);
} else if (cmd == "profile") { } else if (cmd == "profile") {
cmd = ""; cmd = "";
ss >> sub_cmd; ss >> sub_cmd;
@@ -848,9 +585,6 @@ void DppcDebugger::enter_debugger() {
} else { } else {
print_gprs(); print_gprs();
} }
} else if (cmd == "fregs") {
cmd = "";
print_fprs();
} else if (cmd == "mregs") { } else if (cmd == "mregs") {
cmd = ""; cmd = "";
print_mmu_regs(); print_mmu_regs();
@@ -902,9 +636,6 @@ void DppcDebugger::enter_debugger() {
delete_prompt(); delete_prompt();
} }
for (; --count >= 0;) { for (; --count >= 0;) {
addr_str = "R24";
addr = static_cast<uint32_t>(get_reg(addr_str) - 2);
disasm_68k(1, addr);
exec_single_68k(); exec_single_68k();
} }
#endif #endif
@@ -913,25 +644,15 @@ void DppcDebugger::enter_debugger() {
delete_prompt(); delete_prompt();
} }
for (; --count >= 0;) { for (; --count >= 0;) {
addr = ppc_state.pc;
PPCDisasmContext ctx;
disasm_in(ctx, addr);
ppc_exec_single(); ppc_exec_single();
disasm_out(ctx);
} }
} }
} else if (cmd == "next" || cmd == "ni") { } else if (cmd == "next" || cmd == "ni") {
addr_str = "PC"; addr_str = "PC";
addr = static_cast<uint32_t>(get_reg(addr_str) + 4); addr = (uint32_t)get_reg(addr_str) + 4;
ppc_exec_until(addr); ppc_exec_until(addr);
} else if (cmd == "until") { } else if (cmd == "until") {
if (cmd_repeat) { ss >> addr_str;
delete_prompt();
cout << repeat_count << "> " << cmd << " " << addr_str << endl;
}
else {
ss >> addr_str;
}
try { try {
addr = str2addr(addr_str); addr = str2addr(addr_str);
if (context == 2) { if (context == 2) {
@@ -1005,7 +726,7 @@ void DppcDebugger::enter_debugger() {
} }
else { else {
addr_str = "R24"; addr_str = "R24";
addr = static_cast<uint32_t>(get_reg(addr_str) - 2); addr = get_reg(addr_str) - 2;
} }
next_addr_68k = disasm_68k(1, addr); next_addr_68k = disasm_68k(1, addr);
#endif #endif
@@ -1016,7 +737,7 @@ void DppcDebugger::enter_debugger() {
} }
else { else {
addr_str = "PC"; addr_str = "PC";
addr = static_cast<uint32_t>(get_reg(addr_str)); addr = (uint32_t)get_reg(addr_str);
} }
next_addr_ppc = disasm(1, addr); next_addr_ppc = disasm(1, addr);
} }
@@ -1024,36 +745,10 @@ void DppcDebugger::enter_debugger() {
cout << exc.what() << endl; 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") { } else if (cmd == "dump") {
expr_str = ""; expr_str = "";
ss >> expr_str; ss >> expr_str;
dump_mem(expr_str); dump_mem(expr_str);
} else if (cmd == "setmem") {
expr_str = "";
ss >> expr_str;
patch_mem(expr_str);
#ifdef ENABLE_68K_DEBUGGER #ifdef ENABLE_68K_DEBUGGER
} else if (cmd == "context") { } else if (cmd == "context") {
cmd = ""; cmd = "";
@@ -1067,10 +762,6 @@ void DppcDebugger::enter_debugger() {
cout << "Unknown debugging context: " << expr_str << endl; cout << "Unknown debugging context: " << expr_str << endl;
} }
#endif #endif
} else if (cmd == "regions") {
cmd = "";
if (mem_ctrl_instance)
mem_ctrl_instance->dump_regions();
} else if (cmd == "printenv") { } else if (cmd == "printenv") {
cmd = ""; cmd = "";
if (ofnvram->init()) if (ofnvram->init())
@@ -1082,15 +773,9 @@ void DppcDebugger::enter_debugger() {
ss >> var_name; ss >> var_name;
std::istream::sentry se(ss); // skip white space std::istream::sentry se(ss); // skip white space
getline(ss, value); // get everything up to eol getline(ss, value); // get everything up to eol
if (ofnvram->init()) { if (ofnvram->init())
cout << " Cannot open NVRAM" << endl;
continue; continue;
} ofnvram->setenv(var_name, value);
if (!ofnvram->setenv(var_name, value)) {
cout << " Please try again" << endl;
} else {
cout << " ok" << endl; // mimic Forth
}
#ifndef _WIN32 #ifndef _WIN32
} else if (cmd == "nvedit") { } else if (cmd == "nvedit") {
cmd = ""; cmd = "";
@@ -1167,24 +852,10 @@ void DppcDebugger::enter_debugger() {
cout << exc.what() << endl; cout << exc.what() << endl;
continue; continue;
} }
static TimerInfo viaint_timer; ViaCuda* via_obj = dynamic_cast<ViaCuda*>(gMachineObj->get_comp_by_name("ViaCuda"));
TimerManager::get_instance()->add_oneshot_timer(viaint_timer, 0, [irq_bit](uint64_t, uint64_t){ ppc_state.pc -= 4;
ViaCuda* via_obj = dynamic_cast<ViaCuda*>(gMachineObj->get_comp_by_name("ViaCuda")); via_obj->assert_int(irq_bit);
via_obj->assert_int(irq_bit);
});
#endif #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 { } else {
if (!cmd.empty()) { if (!cmd.empty()) {
cout << "Unknown command: " << cmd << endl; cout << "Unknown command: " << cmd << endl;
+4 -4
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-21 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -31,7 +31,7 @@ public:
debugger_obj = std::unique_ptr<DppcDebugger>(new DppcDebugger()); debugger_obj = std::unique_ptr<DppcDebugger>(new DppcDebugger());
} }
return debugger_obj.get(); return debugger_obj.get();
} };
void enter_debugger(); void enter_debugger();
+4 -6
View File
@@ -8,14 +8,10 @@ include_directories("${PROJECT_SOURCE_DIR}"
platform_glob(SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp" platform_glob(SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/common/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/common/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/common/adb/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/common/adb/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/common/ata/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/common/clockgen/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/common/firewire/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/common/i2c/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/common/i2c/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/common/nubus/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/common/ata/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/common/pci/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/common/pci/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/common/scsi/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/common/scsi/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/common/usb/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/ethernet/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/ethernet/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/floppy/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/floppy/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/ioctrl/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/ioctrl/*.cpp"
@@ -26,10 +22,12 @@ platform_glob(SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/video/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/video/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/common/*.h" "${CMAKE_CURRENT_SOURCE_DIR}/common/*.h"
"${CMAKE_CURRENT_SOURCE_DIR}/common/adb/*.h" "${CMAKE_CURRENT_SOURCE_DIR}/common/adb/*.h"
"${CMAKE_CURRENT_SOURCE_DIR}/common/ata/*.h" "${CMAKE_CURRENT_SOURCE_DIR}/common/firewire/*.h"
"${CMAKE_CURRENT_SOURCE_DIR}/common/i2c/*.h" "${CMAKE_CURRENT_SOURCE_DIR}/common/i2c/*.h"
"${CMAKE_CURRENT_SOURCE_DIR}/common/ata/*.h"
"${CMAKE_CURRENT_SOURCE_DIR}/common/pci/*.h" "${CMAKE_CURRENT_SOURCE_DIR}/common/pci/*.h"
"${CMAKE_CURRENT_SOURCE_DIR}/common/scsi/*.h" "${CMAKE_CURRENT_SOURCE_DIR}/common/scsi/*.h"
"${CMAKE_CURRENT_SOURCE_DIR}/common/usb/*.h"
"${CMAKE_CURRENT_SOURCE_DIR}/ethernet/*.h" "${CMAKE_CURRENT_SOURCE_DIR}/ethernet/*.h"
"${CMAKE_CURRENT_SOURCE_DIR}/floppy/*.h" "${CMAKE_CURRENT_SOURCE_DIR}/floppy/*.h"
"${CMAKE_CURRENT_SOURCE_DIR}/ioctrl/*.h" "${CMAKE_CURRENT_SOURCE_DIR}/ioctrl/*.h"
+14 -11
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -35,9 +35,9 @@ void AdbAppleJack::event_handler(const GamepadEvent& event) {
uint32_t button_bit = 1 << event.button; uint32_t button_bit = 1 << event.button;
if (event.flags & GAMEPAD_EVENT_DOWN) if (event.flags & GAMEPAD_EVENT_DOWN)
this->aj_buttons_state |= button_bit; this->buttons_state |= button_bit;
else if (event.flags & GAMEPAD_EVENT_UP) else if (event.flags & GAMEPAD_EVENT_UP)
this->aj_buttons_state &= ~button_bit; this->buttons_state &= ~button_bit;
if (button_bit & ((1 << GamepadButton::LeftTrigger) | (1 << GamepadButton::RightTrigger))) if (button_bit & ((1 << GamepadButton::LeftTrigger) | (1 << GamepadButton::RightTrigger)))
this->triggers_changed = true; this->triggers_changed = true;
@@ -47,7 +47,7 @@ void AdbAppleJack::event_handler(const GamepadEvent& event) {
void AdbAppleJack::reset() { void AdbAppleJack::reset() {
this->AdbMouse::reset(); this->AdbMouse::reset();
this->aj_buttons_state = 0; this->buttons_state = 0;
this->triggers_changed = false; this->triggers_changed = false;
this->buttons_changed = false; this->buttons_changed = false;
LOG_F(INFO, "%s: reset; in mouse emulation mode", this->name.c_str()); LOG_F(INFO, "%s: reset; in mouse emulation mode", this->name.c_str());
@@ -58,16 +58,16 @@ bool AdbAppleJack::get_register_0() {
uint8_t mouse_buttons = this->AdbMouse::get_buttons_state(); uint8_t mouse_buttons = this->AdbMouse::get_buttons_state();
// AppleJack triggers always affect the mouse button bits. // AppleJack triggers always affect the mouse button bits.
mouse_buttons |= (this->aj_buttons_state >> (GamepadButton::LeftTrigger - 0)) & 1; mouse_buttons |= (this->buttons_state >> (GamepadButton::LeftTrigger - 0)) & 1;
mouse_buttons |= (this->aj_buttons_state >> (GamepadButton::RightTrigger - 1)) & 2; mouse_buttons |= (this->buttons_state >> (GamepadButton::RightTrigger - 1)) & 2;
changed |= this->AdbMouse::get_register_0(mouse_buttons, changed); changed |= this->AdbMouse::get_register_0(mouse_buttons, changed);
this->triggers_changed = false; this->triggers_changed = false;
if (this->dev_handler_id == APPLEJACK_HANDLER_ID && this->buttons_changed) { if (this->dev_handler_id == APPLEJACK_HANDLER_ID && this->buttons_changed) {
uint8_t* out_buf = this->host_obj->get_output_buf(); uint8_t* out_buf = this->host_obj->get_output_buf();
out_buf[2] = uint8_t(~this->aj_buttons_state >> 8); out_buf[2] = ~this->buttons_state >> 8;
out_buf[3] = ~this->aj_buttons_state & 0xFF; out_buf[3] = ~this->buttons_state & 0xFF;
this->host_obj->set_output_count(4); this->host_obj->set_output_count(4);
this->buttons_changed = false; this->buttons_changed = false;
@@ -77,6 +77,9 @@ bool AdbAppleJack::get_register_0() {
} }
void AdbAppleJack::set_register_3() { void AdbAppleJack::set_register_3() {
if (this->host_obj->get_input_count() < 2) // ensure we got enough data
return;
const uint8_t* in_data = this->host_obj->get_input_buf(); const uint8_t* in_data = this->host_obj->get_input_buf();
switch (in_data[1]) { switch (in_data[1]) {
@@ -91,7 +94,7 @@ void AdbAppleJack::set_register_3() {
} }
static const DeviceDescription AdbAppleJack_Descriptor = { static const DeviceDescription AdbAppleJack_Descriptor = {
AdbAppleJack::create, {}, {}, HWCompType::ADB_DEV AdbAppleJack::create, {}, {}
}; };
REGISTER_DEVICE(AdbAppleJack, AdbAppleJack_Descriptor); REGISTER_DEVICE(AdbAppleJack, AdbAppleJack_Descriptor);
+4 -4
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -52,7 +52,7 @@ public:
void set_register_3() override; void set_register_3() override;
private: private:
uint32_t aj_buttons_state = 0; uint32_t buttons_state = 0;
bool triggers_changed = false; bool triggers_changed = false;
bool buttons_changed = false; bool buttons_changed = false;
}; };
+4 -4
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -133,7 +133,7 @@ static const PropMap AdbBus_Properties = {
}; };
static const DeviceDescription AdbBus_Descriptor = { static const DeviceDescription AdbBus_Descriptor = {
AdbBus::create, {}, AdbBus_Properties, HWCompType::ADB_HOST AdbBus::create, {}, AdbBus_Properties
}; };
REGISTER_DEVICE(AdbBus, AdbBus_Descriptor); REGISTER_DEVICE(AdbBus, AdbBus_Descriptor);
+10 -11
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -30,7 +30,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <string> #include <string>
#include <vector> #include <vector>
constexpr auto ADB_MAX_DATA_SIZE = 8; #define ADB_MAX_DATA_SIZE 8
/** ADB status. */ /** ADB status. */
enum { enum {
@@ -38,7 +38,6 @@ enum {
ADB_STAT_SRQ_ACTIVE = 1 << 0, ADB_STAT_SRQ_ACTIVE = 1 << 0,
ADB_STAT_TIMEOUT = 1 << 1, ADB_STAT_TIMEOUT = 1 << 1,
ADB_STAT_AUTOPOLL = 1 << 6, ADB_STAT_AUTOPOLL = 1 << 6,
ADB_STAT_RESPONSE = 1 << 7,
}; };
class AdbDevice; // forward declaration to prevent compiler errors class AdbDevice; // forward declaration to prevent compiler errors
@@ -56,7 +55,7 @@ public:
void register_device(AdbDevice* dev_obj); void register_device(AdbDevice* dev_obj);
uint8_t process_command(const uint8_t* in_data, int data_size); uint8_t process_command(const uint8_t* in_data, int data_size);
uint8_t get_output_count() { return this->output_count; } uint8_t get_output_count() { return this->output_count; };
// Polls devices that have a service request flag set. Returns the talk // Polls devices that have a service request flag set. Returns the talk
// command corresponding to the first device that responded with data, or // command corresponding to the first device that responded with data, or
@@ -64,11 +63,11 @@ public:
uint8_t poll(); uint8_t poll();
// callbacks meant to be called by devices // callbacks meant to be called by devices
const uint8_t* get_input_buf() { return this->input_buf; } const uint8_t* get_input_buf() { return this->input_buf; };
uint8_t* get_output_buf() { return this->output_buf; } uint8_t* get_output_buf() { return this->output_buf; };
uint8_t get_input_count() { return this->input_count; } uint8_t get_input_count() { return this->input_count; };
void set_output_count(uint8_t count) { this->output_count = count; } void set_output_count(uint8_t count) { this->output_count = count; };
bool already_answered() { return this->got_answer; } bool already_answered() { return this->got_answer; };
private: private:
std::vector<AdbDevice*> devices; std::vector<AdbDevice*> devices;
+6 -31
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -21,7 +21,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file Base class for Apple Desktop Bus devices. */ /** @file Base class for Apple Desktop Bus devices. */
#include <loguru.hpp>
#include <core/timermanager.h> #include <core/timermanager.h>
#include <devices/common/adb/adbdevice.h> #include <devices/common/adb/adbdevice.h>
#include <devices/common/adb/adbbus.h> #include <devices/common/adb/adbbus.h>
@@ -38,7 +37,7 @@ int AdbDevice::device_postinit() {
this->host_obj->register_device(this); this->host_obj->register_device(this);
return 0; return 0;
} };
uint8_t AdbDevice::poll() { uint8_t AdbDevice::poll() {
if (!this->srq_flag) { if (!this->srq_flag) {
@@ -85,17 +84,12 @@ void AdbDevice::listen(const uint8_t dev_addr, const uint8_t reg_num) {
switch(reg_num & 3) { switch(reg_num & 3) {
case 0: case 0:
this->set_register_0(); this->set_register_0();
break;
case 1: case 1:
this->set_register_1(); this->set_register_1();
break;
case 2: case 2:
this->set_register_2(); this->set_register_2();
break;
case 3: case 3:
if (this->host_obj->get_input_count() >= 2) // ensure we got enough data this->set_register_3();
this->set_register_3();
break;
} }
} }
} }
@@ -109,25 +103,6 @@ bool AdbDevice::get_register_3() {
return true; return true;
} }
void AdbDevice::set_register_3() {
const uint8_t* in_data = this->host_obj->get_input_buf();
uint8_t new_addr = in_data[0] & 0xF;
switch (in_data[1]) {
case 0:
this->my_addr = new_addr;
this->srq_flag = !!(in_data[0] & 0x20);
break;
case 0xFE: // move to a new address if there was no collision
if (!this->got_collision) {
this->my_addr = new_addr;
}
break;
default:
LOG_F(WARNING, "ADB Device: unknown handler ID = 0x%X", in_data[1]);
}
}
uint8_t AdbDevice::gen_random_address() { uint8_t AdbDevice::gen_random_address() {
return TimerManager::get_instance()->current_time_ns() & 0xF; return (TimerManager::get_instance()->current_time_ns() + 8) & 0xF;
} }
+12 -13
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -47,7 +47,7 @@ public:
virtual void reset() = 0; virtual void reset() = 0;
virtual bool talk(const uint8_t dev_addr, const uint8_t reg_num); virtual bool talk(const uint8_t dev_addr, const uint8_t reg_num);
virtual void listen(const uint8_t dev_addr, const uint8_t reg_num); virtual void listen(const uint8_t dev_addr, const uint8_t reg_num);
virtual uint8_t get_address() { return this->my_addr; } virtual uint8_t get_address() { return this->my_addr; };
// Attempts to poll the device. Returns the talk command corresponding to // Attempts to poll the device. Returns the talk command corresponding to
// the device if it has data, 0 otherwise. // the device if it has data, 0 otherwise.
@@ -56,19 +56,18 @@ public:
protected: protected:
uint8_t gen_random_address(); uint8_t gen_random_address();
virtual bool get_register_0() { return false; } virtual bool get_register_0() { return false; };
virtual bool get_register_1() { return false; } virtual bool get_register_1() { return false; };
virtual bool get_register_2() { return false; } virtual bool get_register_2() { return false; };
virtual bool get_register_3(); virtual bool get_register_3();
virtual void set_register_0() {} virtual void set_register_0() {};
virtual void set_register_1() {} virtual void set_register_1() {};
virtual void set_register_2() {} virtual void set_register_2() {};
virtual void set_register_3(); virtual void set_register_3() {};
uint8_t exc_event_flag = 0; uint8_t exc_event_flag = 0;
uint8_t srq_flag = 0; uint8_t srq_flag = 0;
uint8_t led_state = 0;
uint8_t my_addr = 0; uint8_t my_addr = 0;
uint8_t dev_handler_id = 0; uint8_t dev_handler_id = 0;
bool got_collision = false; bool got_collision = false;
+25 -66
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -34,22 +34,15 @@ AdbKeyboard::AdbKeyboard(std::string name) : AdbDevice(name) {
} }
void AdbKeyboard::event_handler(const KeyboardEvent& event) { void AdbKeyboard::event_handler(const KeyboardEvent& event) {
this->keys_down.set(event.key, !(event.flags & KEYBOARD_EVENT_UP));
this->pending_events.push_back(std::make_unique<KeyboardEvent>(event)); this->pending_events.push_back(std::make_unique<KeyboardEvent>(event));
if (this->pending_events.size() == 1) {
this->srq_flag = 1;
}
} }
void AdbKeyboard::reset() { void AdbKeyboard::reset() {
this->my_addr = ADB_ADDR_KBD; this->my_addr = ADB_ADDR_KBD;
this->dev_handler_id = 2; // Extended ADB keyboard this->dev_handler_id = 2; // Extended ADB keyboard
this->exc_event_flag = 1; this->exc_event_flag = 1;
this->srq_flag = 0; // don't process keyboard service requests yet this->srq_flag = 1; // enable service requests
this->led_state = 7; // LEDs off (active low)
this->pending_events.clear(); this->pending_events.clear();
this->keys_down.reset();
} }
bool AdbKeyboard::get_register_0() { bool AdbKeyboard::get_register_0() {
@@ -60,11 +53,6 @@ bool AdbKeyboard::get_register_0() {
out_buf[0] = this->consume_pending_event(); out_buf[0] = this->consume_pending_event();
out_buf[1] = this->consume_pending_event(); out_buf[1] = this->consume_pending_event();
this->host_obj->set_output_count(2); this->host_obj->set_output_count(2);
if (this->pending_events.empty()) {
this->srq_flag = 0;
}
return true; return true;
} }
@@ -80,79 +68,50 @@ uint8_t AdbKeyboard::consume_pending_event() {
std::unique_ptr<KeyboardEvent> event = std::move(this->pending_events.front()); std::unique_ptr<KeyboardEvent> event = std::move(this->pending_events.front());
this->pending_events.pop_front(); this->pending_events.pop_front();
uint8_t key_state = (event->flags & KEYBOARD_EVENT_UP) ? 1 : 0; uint8_t key_state = 0;
if (event->flags & KEYBOARD_EVENT_DOWN) {
if (this->dev_handler_id != 3) { key_state = 0;
switch (event->key) { } else if (event->flags & KEYBOARD_EVENT_UP) {
case AdbKey_RightControl : event->key = AdbKey_Control; break; key_state = 1;
case AdbKey_RightShift : event->key = AdbKey_Shift ; break; } else {
case AdbKey_RightOption : event->key = AdbKey_Option ; break; LOG_F(WARNING, "%s: unknown keyboard event flags %x", this->name.c_str(), event->flags);
}
} }
return (key_state << 7) | (event->key & 0x7F); return (key_state << 7) | (event->key & 0x7F);
} }
bool AdbKeyboard::get_register_2() { void AdbKeyboard::set_register_2() {
// Register 2 reflects the current modifier keys, and a zero value means
// that the key is held down.
static const struct {
uint8_t key;
uint8_t bit;
} reg2_keys[] = {
{ AdbKey_Delete, 14 },
{ AdbKey_CapsLock, 13 },
{ AdbKey_Power, 12 },
{ AdbKey_Control, 11 },
{ AdbKey_RightControl, 11 },
{ AdbKey_Shift, 10 },
{ AdbKey_RightShift, 10 },
{ AdbKey_Option, 9 },
{ AdbKey_RightOption, 9 },
{ AdbKey_Command, 8 },
{ AdbKey_KeypadClear, 7 },
{ AdbKey_F14, 6 }, // Scroll Lock
};
uint16_t reg2 = 0xFFF8 | this->led_state;
for (const auto& key : reg2_keys) {
if (this->keys_down[key.key])
reg2 &= ~(1 << key.bit);
}
uint8_t* out_buf = this->host_obj->get_output_buf();
out_buf[0] = reg2 >> 8;
out_buf[1] = reg2 & 0xFF;
this->host_obj->set_output_count(2);
return true;
} }
void AdbKeyboard::set_register_2() { void AdbKeyboard::set_register_3() {
if (this->host_obj->get_input_count() < 2) if (this->host_obj->get_input_count() < 2) // ensure we got enough data
return; return;
const uint8_t* in_data = this->host_obj->get_input_buf(); const uint8_t* in_data = this->host_obj->get_input_buf();
this->led_state = in_data[1] & 0x07;
}
void AdbKeyboard::set_register_3() {
const uint8_t* in_data = this->host_obj->get_input_buf();
switch (in_data[1]) { switch (in_data[1]) {
case 0:
this->my_addr = in_data[0] & 0xF;
this->srq_flag = !!(in_data[0] & 0x20);
break;
case 1: case 1:
case 2: case 2:
this->dev_handler_id = in_data[1]; this->dev_handler_id = in_data[1];
break; break;
case 3: // extended keyboard protocol isn't supported yet case 3: // extended keyboard protocol isn't supported yet
break; break;
case 0xFE: // move to a new address if there was no collision
if (!this->got_collision) {
this->my_addr = in_data[0] & 0xF;
}
break;
default: default:
this->AdbDevice::set_register_3(); LOG_F(WARNING, "%s: unknown handler ID = 0x%X", this->name.c_str(), in_data[1]);
} }
} }
static const DeviceDescription AdbKeyboard_Descriptor = { static const DeviceDescription AdbKeyboard_Descriptor = {
AdbKeyboard::create, {}, {}, HWCompType::ADB_DEV AdbKeyboard::create, {}, {}
}; };
REGISTER_DEVICE(AdbKeyboard, AdbKeyboard_Descriptor); REGISTER_DEVICE(AdbKeyboard, AdbKeyboard_Descriptor);
+3 -11
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -27,7 +27,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <devices/common/adb/adbdevice.h> #include <devices/common/adb/adbdevice.h>
#include <devices/common/hwcomponent.h> #include <devices/common/hwcomponent.h>
#include <bitset>
#include <deque> #include <deque>
#include <memory> #include <memory>
#include <string> #include <string>
@@ -47,14 +46,12 @@ public:
void event_handler(const KeyboardEvent& event); void event_handler(const KeyboardEvent& event);
bool get_register_0() override; bool get_register_0() override;
bool get_register_2() override;
void set_register_2() override; void set_register_2() override;
void set_register_3() override; void set_register_3() override;
private: private:
std::deque<std::unique_ptr<KeyboardEvent>> pending_events; std::deque<std::unique_ptr<KeyboardEvent>> pending_events;
std::bitset<128> keys_down;
uint8_t consume_pending_event(); uint8_t consume_pending_event();
}; };
@@ -130,11 +127,6 @@ enum AdbKey {
AdbKey_Option = 0x3a, AdbKey_Option = 0x3a,
AdbKey_Command = 0x37, AdbKey_Command = 0x37,
AdbKey_CapsLock = 0x39, AdbKey_CapsLock = 0x39,
AdbKey_Power = 0x7f,
AdbKey_RightControl = 0x7d,
AdbKey_RightShift = 0x7b,
AdbKey_RightOption = 0x7c,
AdbKey_ArrowUp = 0x3e, AdbKey_ArrowUp = 0x3e,
AdbKey_ArrowDown = 0x3d, AdbKey_ArrowDown = 0x3d,
+30 -22
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -21,17 +21,15 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file Apple Desktop Bus Mouse emulation. */ /** @file Apple Desktop Bus Mouse emulation. */
#include <core/memaccess.h>
#include <devices/common/adb/adbmouse.h> #include <devices/common/adb/adbmouse.h>
#include <devices/common/adb/adbbus.h> #include <devices/common/adb/adbbus.h>
#include <devices/deviceregistry.h> #include <devices/deviceregistry.h>
#include <core/hostevents.h> #include <core/hostevents.h>
#include <memaccess.h>
#include <loguru.hpp> #include <loguru.hpp>
AdbMouse::AdbMouse( AdbMouse::AdbMouse(
std::string name, uint8_t device_class, int num_buttons, int num_bits, uint16_t resolution std::string name, uint8_t device_class, int num_buttons, int num_bits, uint16_t resolution) : AdbDevice(name), device_class(device_class), num_buttons(num_buttons), num_bits(num_bits), resolution(resolution) {
) : AdbDevice(name), device_class(device_class), num_buttons(num_buttons), num_bits(num_bits), resolution(resolution)
{
EventManager::get_instance()->add_mouse_handler(this, &AdbMouse::event_handler); EventManager::get_instance()->add_mouse_handler(this, &AdbMouse::event_handler);
this->reset(); this->reset();
@@ -66,7 +64,7 @@ void AdbMouse::reset() {
this->changed = false; this->changed = false;
} }
bool AdbMouse::get_register_0(uint8_t buttons, bool force) { bool AdbMouse::get_register_0(uint8_t buttons_state, bool force) {
bool should_update = this->x_rel || this->y_rel || this->changed || force; bool should_update = this->x_rel || this->y_rel || this->changed || force;
if (should_update) { if (should_update) {
@@ -75,19 +73,10 @@ bool AdbMouse::get_register_0(uint8_t buttons, bool force) {
static const uint8_t buttons_to_bits[] = {0, 7, 7, 10, 10, 13, 13, 16, 16}; static const uint8_t buttons_to_bits[] = {0, 7, 7, 10, 10, 13, 13, 16, 16};
static const uint8_t bits_to_bits[] = {0, 7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 13, 13, 13, 16, 16, 16}; static const uint8_t bits_to_bits[] = {0, 7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 13, 13, 13, 16, 16, 16};
int num_bits, total_bits; int total_bits = std::max(buttons_to_bits[this->num_buttons], bits_to_bits[this->num_bits]);
// if the mouse is in standard protocol then only send first 2 bytes
// BUGBUG: what should tablet do here?
if (this->device_class == MOUSE && this->dev_handler_id == 1) {
num_bits = total_bits = 7;
} else {
num_bits = this->num_bits;
total_bits = std::max(buttons_to_bits[this->num_buttons], bits_to_bits[num_bits]);
}
buttons = ~buttons;
for (int axis = 0; axis < 2; axis++) { for (int axis = 0; axis < 2; axis++) {
int bits = num_bits; int bits = this->num_bits;
int32_t val = axis ? this->device_class == TABLET ? this->x_abs : this->x_rel int32_t val = axis ? this->device_class == TABLET ? this->x_abs : this->x_rel
: this->device_class == TABLET ? this->y_abs : this->y_rel; : this->device_class == TABLET ? this->y_abs : this->y_rel;
if (val < (-1 << (bits - 1))) if (val < (-1 << (bits - 1)))
@@ -100,7 +89,7 @@ bool AdbMouse::get_register_0(uint8_t buttons, bool force) {
bits = 7; bits = 7;
while (bits_remaining > 0) { while (bits_remaining > 0) {
*p = uint8_t((val & ((1 << bits) - 1)) | (((buttons >> button) & 1) << bits) | (*p << (bits + 1))); *p = (val & ((1 << bits) - 1)) | (((buttons_state >> button) ^ 1) << bits) | (*p << (bits + 1));
val >>= bits; val >>= bits;
bits_remaining -= bits; bits_remaining -= bits;
p = bits == 7 ? &out_buf[2] : p + 1; p = bits == 7 ? &out_buf[2] : p + 1;
@@ -115,6 +104,13 @@ bool AdbMouse::get_register_0(uint8_t buttons, bool force) {
this->changed = false; this->changed = false;
uint8_t count = (uint8_t)(p - out_buf); uint8_t count = (uint8_t)(p - out_buf);
// should never happen, but check just in case
if (((size_t)p - (size_t)out_buf) > UINT8_MAX)
count = UINT8_MAX;
// if the mouse is in standard protocol then only send first 2 bytes
// BUGBUG: what should tablet do here?
if (this->device_class == MOUSE && this->dev_handler_id == 1)
count = 2;
this->host_obj->set_output_count(count); this->host_obj->set_output_count(count);
return should_update; return should_update;
} }
@@ -142,16 +138,28 @@ bool AdbMouse::get_register_1() {
} }
void AdbMouse::set_register_3() { void AdbMouse::set_register_3() {
if (this->host_obj->get_input_count() < 2) // ensure we got enough data
return;
const uint8_t* in_data = this->host_obj->get_input_buf(); const uint8_t* in_data = this->host_obj->get_input_buf();
switch (in_data[1]) { switch (in_data[1]) {
case 0:
this->my_addr = in_data[0] & 0xF;
this->srq_flag = !!(in_data[0] & 0x20);
break;
case 1: case 1:
case 2: case 2:
case 4: // switch over to extended mouse protocol case 4: // switch over to extended mouse protocol
this->dev_handler_id = in_data[1]; this->dev_handler_id = in_data[1];
break; break;
case 0xFE: // move to a new address if there was no collision
if (!this->got_collision) {
this->my_addr = in_data[0] & 0xF;
}
break;
default: default:
this->AdbDevice::set_register_3(); LOG_F(WARNING, "%s: unknown handler ID = 0x%X", this->name.c_str(), in_data[1]);
} }
} }
@@ -160,7 +168,7 @@ uint8_t AdbMouse::get_buttons_state() const {
} }
static const DeviceDescription AdbMouse_Descriptor = { static const DeviceDescription AdbMouse_Descriptor = {
AdbMouse::create, {}, {}, HWCompType::ADB_DEV AdbMouse::create, {}, {}
}; };
REGISTER_DEVICE(AdbMouse, AdbMouse_Descriptor); REGISTER_DEVICE(AdbMouse, AdbMouse_Descriptor);
+4 -4
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -70,7 +70,7 @@ enum DeviceClass {
void set_register_3() override; void set_register_3() override;
protected: protected:
bool get_register_0(uint8_t buttons, bool force); bool get_register_0(uint8_t buttons_state, bool force);
uint8_t get_buttons_state() const; uint8_t get_buttons_state() const;
private: private:
+9 -104
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -21,13 +21,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file Basic ATA device emulation. */ /** @file Basic ATA device emulation. */
#include <core/timermanager.h>
#include <devices/common/ata/atabasedevice.h> #include <devices/common/ata/atabasedevice.h>
#include <devices/common/ata/atadefs.h> #include <devices/common/ata/atadefs.h>
#include <devices/common/ata/idechannel.h> #include <devices/common/ata/idechannel.h>
#include <loguru.hpp> #include <loguru.hpp>
#include <cstring>
#include <cinttypes> #include <cinttypes>
using namespace ata_interface; using namespace ata_interface;
@@ -77,14 +75,7 @@ uint16_t AtaBaseDevice::read(const uint8_t reg_addr) {
this->r_status &= ~DRQ; this->r_status &= ~DRQ;
} else { } else {
this->chunk_cnt = std::min(this->xfer_cnt, this->chunk_size); this->chunk_cnt = std::min(this->xfer_cnt, this->chunk_size);
if (!this->read_data_timer.active) { this->update_intrq(1);
TimerManager::get_instance()->add_oneshot_timer(this->read_data_timer,
USECS_TO_NSECS(100), [this](uint64_t, uint64_t) {
this->read_data_timer.active = 0;
this->update_intrq(1);
}
);
}
} }
} }
return ret_data; return ret_data;
@@ -117,7 +108,7 @@ uint16_t AtaBaseDevice::read(const uint8_t reg_addr) {
void AtaBaseDevice::write(const uint8_t reg_addr, const uint16_t value) { void AtaBaseDevice::write(const uint8_t reg_addr, const uint16_t value) {
switch (reg_addr) { switch (reg_addr) {
case ATA_Reg::DATA: case ATA_Reg::DATA:
if (this->is_selected() && this->has_data()) { if (is_selected() && this->has_data()) {
*this->cur_data_ptr++ = BYTESWAP_16(value); *this->cur_data_ptr++ = BYTESWAP_16(value);
this->chunk_cnt -= 2; this->chunk_cnt -= 2;
if (this->chunk_cnt <= 0) { if (this->chunk_cnt <= 0) {
@@ -126,28 +117,12 @@ void AtaBaseDevice::write(const uint8_t reg_addr, const uint16_t value) {
if (this->xfer_cnt <= 0) { // transfer complete? if (this->xfer_cnt <= 0) { // transfer complete?
this->xfer_cnt = 0; this->xfer_cnt = 0;
this->r_status &= ~DRQ; this->r_status &= ~DRQ;
//LOG_F(INFO, "%s: write complete", name.c_str()); this->r_status &= ~BSY;
if (this->write_done_timer.active) this->update_intrq(1);
LOG_F(ERROR, "%s: write_done_timer is already active", this->get_name().c_str());
TimerManager::get_instance()->add_oneshot_timer(write_done_timer,
USECS_TO_NSECS(100), [this](uint64_t, uint64_t) {
write_done_timer.active = 0;
this->r_status &= ~BSY;
this->update_intrq(1);
}
);
} else { } else {
this->cur_data_ptr = this->data_ptr; this->cur_data_ptr = this->data_ptr;
this->chunk_cnt = std::min(this->xfer_cnt, this->chunk_size); this->chunk_cnt = std::min(this->xfer_cnt, this->chunk_size);
//LOG_F(INFO, "%s: write needs more data (left: 0x%x)", name.c_str(), xfer_cnt); this->signal_data_ready();
if (this->write_more_timer.active)
LOG_F(ERROR, "%s: write_more_timer is already active", this->get_name().c_str());
TimerManager::get_instance()->add_oneshot_timer(this->write_more_timer,
USECS_TO_NSECS(100), [this](uint64_t, uint64_t) {
this->write_more_timer.active = 0;
this->signal_data_ready();
}
);
} }
} }
} }
@@ -171,12 +146,8 @@ void AtaBaseDevice::write(const uint8_t reg_addr, const uint16_t value) {
this->r_dev_head = value; this->r_dev_head = value;
break; break;
case ATA_Reg::COMMAND: case ATA_Reg::COMMAND:
if ((this->r_status & BSY) != 0) {
LOG_F(ERROR, "%s: tried to perform command %x when busy", name.c_str(), value);
break;
}
this->r_command = value; this->r_command = value;
if (this->is_selected() || this->r_command == DIAGNOSTICS) { if (is_selected() || this->r_command == DIAGNOSTICS) {
perform_command(); perform_command();
} }
break; break;
@@ -208,72 +179,6 @@ void AtaBaseDevice::device_control(const uint8_t new_ctrl) {
this->r_dev_ctrl = new_ctrl; this->r_dev_ctrl = new_ctrl;
} }
int AtaBaseDevice::pull_data(uint8_t *buf, int len) {
if (!this->xfer_cnt || !this->is_dma_xfer)
return 0;
int xfer_size = std::min(this->xfer_cnt, len);
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;
if (this->dma_pull_timer.active)
LOG_F(ERROR, "%s: dma_pull_timer is already active", this->get_name().c_str());
TimerManager::get_instance()->add_oneshot_timer(dma_pull_timer, 500, [this](uint64_t, uint64_t) {
dma_pull_timer.active = 0;
this->r_status &= ~(BSY | DRQ);
this->update_intrq(1);
});
} else {
this->r_status &= ~BSY;
this->r_status |= DRQ;
}
return xfer_size;
}
int AtaBaseDevice::push_data(uint8_t *buf, int len) {
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;
if (this->dma_push_timer.active)
LOG_F(ERROR, "%s: dma_push_timer is already active", this->get_name().c_str());
TimerManager::get_instance()->add_oneshot_timer(dma_push_timer, 500, [this](uint64_t, uint64_t) {
dma_push_timer.active = 0;
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) { void AtaBaseDevice::update_intrq(uint8_t new_intrq_state) {
if (!this->is_selected() || (this->r_dev_ctrl & IEN)) if (!this->is_selected() || (this->r_dev_ctrl & IEN))
return; return;
+10 -22
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -24,10 +24,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef ATA_BASE_DEVICE_H #ifndef ATA_BASE_DEVICE_H
#define ATA_BASE_DEVICE_H #define ATA_BASE_DEVICE_H
#include <core/endianswap.h>
#include <core/timermanager.h>
#include <devices/common/ata/atadefs.h> #include <devices/common/ata/atadefs.h>
#include <devices/common/hwcomponent.h> #include <devices/common/hwcomponent.h>
#include "endianswap.h"
#include <cinttypes> #include <cinttypes>
#include <string> #include <string>
@@ -44,20 +43,18 @@ public:
void set_host(IdeChannel* host, uint8_t dev_id) { void set_host(IdeChannel* host, uint8_t dev_id) {
this->host_obj = host; this->host_obj = host;
this->my_dev_id = dev_id; this->my_dev_id = dev_id;
} };
uint16_t read(const uint8_t reg_addr) override; uint16_t read(const uint8_t reg_addr) override;
void write(const uint8_t reg_addr, const uint16_t value) override; void write(const uint8_t reg_addr, const uint16_t value) override;
int pull_data(uint8_t *buf, int len) override;
int push_data(uint8_t *buf, int len) override;
virtual int perform_command() = 0; virtual int perform_command() = 0;
int get_device_id() override { return this->my_dev_id; } int get_device_id() override { return this->my_dev_id; };
void pdiag_callback() override { void pdiag_callback() override {
this->r_error &= 0x7F; this->r_error &= 0x7F;
} };
virtual void device_reset(bool is_soft_reset); virtual void device_reset(bool is_soft_reset);
virtual void device_set_signature(); virtual void device_set_signature();
@@ -65,7 +62,7 @@ public:
void update_intrq(uint8_t new_intrq_state); void update_intrq(uint8_t new_intrq_state);
void signal_data_ready(); void signal_data_ready();
bool has_data() const { bool has_data() {
return data_ptr && xfer_cnt; return data_ptr && xfer_cnt;
} }
@@ -74,9 +71,7 @@ public:
} }
protected: protected:
bool is_selected() const { bool is_selected() { return ((this->r_dev_head >> 4) & 1) == this->my_dev_id; };
return ((this->r_dev_head >> 4) & 1) == this->my_dev_id;
}
void prepare_xfer(int xfer_size, int block_size); void prepare_xfer(int xfer_size, int block_size);
@@ -87,7 +82,7 @@ protected:
IdeChannel* host_obj = nullptr; IdeChannel* host_obj = nullptr;
// IDE aka task file registers // IDE aka task file registers
uint8_t r_error = 0; uint8_t r_error;
uint8_t r_features; uint8_t r_features;
uint8_t r_sect_count; uint8_t r_sect_count;
uint8_t r_sect_num; uint8_t r_sect_num;
@@ -106,15 +101,8 @@ protected:
int xfer_cnt = 0; int xfer_cnt = 0;
int chunk_cnt = 0; int chunk_cnt = 0;
int chunk_size = 0; int chunk_size = 0;
bool is_dma_xfer = false;
std::function<void()> post_xfer_action = nullptr; std::function<void()> post_xfer_action = nullptr;
TimerInfo read_data_timer;
TimerInfo write_done_timer;
TimerInfo write_more_timer;
TimerInfo dma_pull_timer;
TimerInfo dma_push_timer;
}; };
#endif // ATA_BASE_DEVICE_H #endif // ATA_BASE_DEVICE_H
+11 -19
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -56,8 +56,7 @@ enum ATA_Reg : int {
COMMAND = 0x07, // command (write) COMMAND = 0x07, // command (write)
ALT_STATUS = 0x16, // alt status (read) ALT_STATUS = 0x16, // alt status (read)
DEV_CTRL = 0x16, // device control (write) DEV_CTRL = 0x16, // device control (write)
TIME_CONFIG = 0x20, // Apple ASIC specific timing configuration TIME_CONFIG = 0x20 // Apple ASIC specific timing configuration
INT_REG = 0x30, // Interrupt Register (read) 0x40 = int request (KeyLargo only)
}; };
/** ATAPI specific register offsets. */ /** ATAPI specific register offsets. */
@@ -132,7 +131,7 @@ enum ATA_Cmd : uint8_t {
READ_VERIFY = 0x40, READ_VERIFY = 0x40,
ATAPI_COMMAND_GET_CONFIG = 0x46, ATAPI_COMMAND_GET_CONFIG = 0x46,
FORMAT_TRACKS = 0x50, FORMAT_TRACKS = 0x50,
SEEK = 0x70, IDE_SEEK = 0x70,
DIAGNOSTICS = 0x90, DIAGNOSTICS = 0x90,
INIT_DEV_PARAM = 0x91, INIT_DEV_PARAM = 0x91,
ATAPI_PACKET = 0xA0, ATAPI_PACKET = 0xA0,
@@ -143,13 +142,8 @@ enum ATA_Cmd : uint8_t {
WRITE_MULTIPLE = 0xC5, WRITE_MULTIPLE = 0xC5,
SET_MULTIPLE_MODE = 0xC6, SET_MULTIPLE_MODE = 0xC6,
READ_DMA = 0xC8, READ_DMA = 0xC8,
READ_DMA_NR = 0xC9,
WRITE_DMA = 0xCA, WRITE_DMA = 0xCA,
WRITE_DMA_NR = 0xCB, STANDBY_IMMEDIATE_E0 = 0xE0,
STANDBY_IMMEDIATE = 0xE0,
IDLE_IMMEDIATE = 0xE1,
CHECK_POWER_MODE = 0xE5,
SLEEP = 0xE6,
FLUSH_CACHE = 0xE7, // ATA-5 FLUSH_CACHE = 0xE7, // ATA-5
WRITE_BUFFER_DMA = 0xE9, WRITE_BUFFER_DMA = 0xE9,
READ_BUFFER_DMA = 0xEB, READ_BUFFER_DMA = 0xEB,
@@ -157,7 +151,7 @@ enum ATA_Cmd : uint8_t {
SET_FEATURES = 0xEF, SET_FEATURES = 0xEF,
}; };
} // namespace ata_interface }; // namespace ata_interface
/** Interface for ATA devices. */ /** Interface for ATA devices. */
class AtaInterface { class AtaInterface {
@@ -166,11 +160,9 @@ public:
virtual ~AtaInterface() = default; virtual ~AtaInterface() = default;
virtual uint16_t read(const uint8_t reg_addr) = 0; virtual uint16_t read(const uint8_t reg_addr) = 0;
virtual void write(const uint8_t reg_addr, const uint16_t val) = 0; virtual void write(const uint8_t reg_addr, const uint16_t val) = 0;
virtual int pull_data(uint8_t *buf, int len) { return 0; };
virtual int push_data(uint8_t *buf, int len) { return 0; };
virtual int get_device_id() = 0; virtual int get_device_id() = 0;
virtual void pdiag_callback() {} virtual void pdiag_callback() {};
}; };
/** Dummy ATA device. */ /** Dummy ATA device. */
@@ -186,12 +178,12 @@ public:
// to prevent the software from waiting for a long time // to prevent the software from waiting for a long time
// for empty slots // for empty slots
return 0xFF7FU; return 0xFF7FU;
} };
void write(const uint8_t reg_addr, const uint16_t val) override {} void write(const uint8_t reg_addr, const uint16_t val) override {};
// invalid device ID means no real device is present // invalid device ID means no real device is present
int get_device_id() override { return ata_interface::DEVICE_ID_INVALID; } int get_device_id() override { return ata_interface::DEVICE_ID_INVALID; };
}; };
#endif // ATA_INTERFACE_H #endif // ATA_INTERFACE_H
+35 -94
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -21,12 +21,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file ATA hard disk emulation. */ /** @file ATA hard disk emulation. */
#include <core/memaccess.h>
#include <devices/common/ata/atahd.h> #include <devices/common/ata/atahd.h>
#include <devices/deviceregistry.h> #include <devices/deviceregistry.h>
#include <devices/common/ata/idechannel.h> #include <devices/common/ata/idechannel.h>
#include <loguru.hpp> #include <loguru.hpp>
#include <machines/machinebase.h> #include <machines/machinebase.h>
#include <memaccess.h>
#include <bitset> #include <bitset>
#include <cstring> #include <cstring>
@@ -99,15 +99,11 @@ int AtaHardDisk::perform_command() {
break; break;
case READ_MULTIPLE: case READ_MULTIPLE:
case READ_SECTOR: 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; uint16_t sec_count = this->r_sect_count ? this->r_sect_count : 256;
int xfer_size = sec_count * ATA_HD_SEC_SIZE; int xfer_size = sec_count * ATA_HD_SEC_SIZE;
uint64_t offset = this->get_lba() * ATA_HD_SEC_SIZE; uint64_t offset = this->get_lba() * ATA_HD_SEC_SIZE;
bool is_dma_cmd = this->r_command == READ_DMA || uint32_t ints_size = ATA_HD_SEC_SIZE;
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->r_command == READ_MULTIPLE) {
if (!this->sectors_per_int) { if (!this->sectors_per_int) {
LOG_F(ERROR, "%s: READ_MULTIPLE disabled", this->name.c_str()); LOG_F(ERROR, "%s: READ_MULTIPLE disabled", this->name.c_str());
@@ -119,34 +115,20 @@ int AtaHardDisk::perform_command() {
} }
hdd_img.read(buffer, offset, xfer_size); hdd_img.read(buffer, offset, xfer_size);
this->data_ptr = (uint16_t *)this->buffer; this->data_ptr = (uint16_t *)this->buffer;
// those commands should generate IRQ for each sector
this->prepare_xfer(xfer_size, ints_size); this->prepare_xfer(xfer_size, ints_size);
if (is_dma_cmd) { this->signal_data_ready();
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; break;
case WRITE_MULTIPLE: case WRITE_MULTIPLE:
case WRITE_SECTOR: 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; uint16_t sec_count = this->r_sect_count ? this->r_sect_count : 256;
uint32_t xfer_size = sec_count * ATA_HD_SEC_SIZE; this->cur_fpos = this->get_lba() * ATA_HD_SEC_SIZE;
bool is_dma_cmd = this->r_command == WRITE_DMA || this->data_ptr = (uint16_t *)this->buffer;
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; 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;
if (this->r_command == WRITE_MULTIPLE) { if (this->r_command == WRITE_MULTIPLE) {
if (!this->sectors_per_int) { if (!this->sectors_per_int) {
LOG_F(ERROR, "%s: WRITE_MULTIPLE disabled", this->name.c_str()); LOG_F(ERROR, "%s: WRITE_MULTIPLE disabled", this->name.c_str());
@@ -162,29 +144,10 @@ int AtaHardDisk::perform_command() {
this->hdd_img.write(this->data_ptr, this->cur_fpos, write_len); this->hdd_img.write(this->data_ptr, this->cur_fpos, write_len);
this->cur_fpos += write_len; this->cur_fpos += write_len;
}; };
if (is_dma_cmd) { this->r_status |= DRQ;
this->is_dma_xfer = true; this->r_status &= ~BSY;
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; 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: case DIAGNOSTICS:
this->r_error = 1; // device 0 passed, device 1 passed or not present this->r_error = 1; // device 0 passed, device 1 passed or not present
this->device_set_signature(); this->device_set_signature();
@@ -228,11 +191,7 @@ int AtaHardDisk::perform_command() {
this->signal_data_ready(); this->signal_data_ready();
break; break;
case SET_FEATURES: case SET_FEATURES:
switch (this->r_features) { if (this->r_features == 3) {
case 2:
LOG_F(INFO, "%s: write cache enabled", this->name.c_str());
break;
case 3:
switch(this->r_sect_count >> 3) { switch(this->r_sect_count >> 3) {
case 0: case 0:
LOG_F(INFO, "%s: default transfer mode requested", this->name.c_str()); LOG_F(INFO, "%s: default transfer mode requested", this->name.c_str());
@@ -242,9 +201,8 @@ int AtaHardDisk::perform_command() {
this->r_sect_count & 7); this->r_sect_count & 7);
break; break;
case 4: case 4:
this->cur_dma_mode = this->r_sect_count & 7;
LOG_F(INFO, "%s: Multiword DMA mode set to 0x%X", this->name.c_str(), LOG_F(INFO, "%s: Multiword DMA mode set to 0x%X", this->name.c_str(),
this->cur_dma_mode); this->r_sect_count & 7);
break; break;
default: default:
LOG_F(ERROR, "%s: unsupported transfer mode 0x%X", this->name.c_str(), LOG_F(ERROR, "%s: unsupported transfer mode 0x%X", this->name.c_str(),
@@ -252,28 +210,18 @@ int AtaHardDisk::perform_command() {
this->r_error |= ATA_Error::ABRT; this->r_error |= ATA_Error::ABRT;
this->r_status |= ATA_Status::ERR; this->r_status |= ATA_Status::ERR;
} }
break; } else {
case 0xAA:
LOG_F(INFO, "%s: read look-ahead enabled", this->name.c_str());
break;
default:
LOG_F(WARNING, "%s: unsupported SET_FEATURES subcommand code 0x%X", LOG_F(WARNING, "%s: unsupported SET_FEATURES subcommand code 0x%X",
this->name.c_str(), this->r_features); this->name.c_str(), this->r_features);
} }
this->r_status &= ~BSY; this->r_status &= ~BSY;
this->update_intrq(1); this->update_intrq(1);
break; break;
case STANDBY_IMMEDIATE: case STANDBY_IMMEDIATE_E0:
LOG_F(INFO, "%s: immediate standby requested", this->name.c_str()); LOG_F(INFO, "%s: STANDBY_IMMEDIATE_E0", this->name.c_str());
this->r_status &= ~BSY; this->r_status &= ~BSY;
this->update_intrq(1); this->update_intrq(1);
break; 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: default:
LOG_F(ERROR, "%s: unknown ATA command 0x%x", this->name.c_str(), this->r_command); LOG_F(ERROR, "%s: unknown ATA command 0x%x", this->name.c_str(), this->r_command);
this->r_status &= ~BSY; this->r_status &= ~BSY;
@@ -288,42 +236,35 @@ void AtaHardDisk::prepare_identify_info() {
std::memset(this->data_buf, 0, sizeof(this->data_buf)); std::memset(this->data_buf, 0, sizeof(this->data_buf));
WRITE_WORD_LE_A(&buf_ptr[ 0], 0x0040); // ATA device, non-removable media, non-removable drive buf_ptr[ 0] = 0x0040; // ATA device, non-removable media, non-removable drive
WRITE_WORD_LE_A(&buf_ptr[49], 0x0300); // report DMA and LBA support buf_ptr[49] = 0x0200; // report LBA support
// Maximum number of logical sectors per data block that the device supports // Maximum number of logical sectors per data block that the device supports
// for READ_MULTIPLE/WRITE_MULTIPLE commands. // for READ_MULTIPLE/WRITE_MULTIPLE commands.
WRITE_WORD_LE_A(&buf_ptr[47], 0x8000 | SECTORS_PER_INT); buf_ptr[47] = 0x8000 | SECTORS_PER_INT;
// If bit 8 of word 59 is set to one, then bits 7:0 indicate the number of // If bit 8 of word 59 is set to one, then bits 7:0 indicate the number of
// logical sectors that shall be transferred per data block for // logical sectors that shall be transferred per data block for
// READ_MULTIPLE/WRITE_MULTIPLE commands. // READ_MULTIPLE/WRITE_MULTIPLE commands.
if (this->sectors_per_int) if (this->sectors_per_int)
WRITE_WORD_LE_A(&buf_ptr[59], 0x100 | this->sectors_per_int); buf_ptr[59] = 0x100 | this->sectors_per_int;
WRITE_WORD_LE_A(&buf_ptr[ 1], this->cylinders); buf_ptr[ 1] = this->cylinders;
WRITE_WORD_LE_A(&buf_ptr[ 3], this->heads); buf_ptr[ 3] = this->heads;
WRITE_WORD_LE_A(&buf_ptr[ 6], this->sectors); buf_ptr[ 6] = this->sectors;
WRITE_WORD_LE_A(&buf_ptr[51], 0x0200); // max. PIO mode for a basic device buf_ptr[57] = this->total_sectors & 0xFFFFU;
buf_ptr[58] = (this->total_sectors >> 16) & 0xFFFFU;
// report validity for the MWDMA fields
WRITE_WORD_LE_A(&buf_ptr[53], 0x0002);
WRITE_DWORD_LE_A(&buf_ptr[57], this->total_sectors);
// report LBA capacity // report LBA capacity
WRITE_DWORD_LE_A(&buf_ptr[60], this->total_sectors); WRITE_WORD_LE_A(&buf_ptr[60], (this->total_sectors & 0xFFFFU));
WRITE_WORD_LE_A(&buf_ptr[61], (this->total_sectors >> 16) & 0xFFFFU);
WRITE_WORD_LE_A(&buf_ptr[63], ((1 << this->cur_dma_mode) << 8) | 7);
WRITE_WORD_LE_A(&buf_ptr[65], 120); // minimum MWDMA cycle time (ns)
WRITE_WORD_LE_A(&buf_ptr[66], 120); // recommended MWDMA cycle time (ns)
} }
uint64_t AtaHardDisk::get_lba() { uint64_t AtaHardDisk::get_lba() {
if (this->r_dev_head & ATA_Dev_Head::LBA) { if (this->r_dev_head & ATA_Dev_Head::LBA) {
return uint64_t(((this->r_dev_head & 0xF) << 24) | (this->r_cylinder_hi << 16) | return ((this->r_dev_head & 0xF) << 24) | (this->r_cylinder_hi << 16) |
(this->r_cylinder_lo << 8) | (this->r_sect_num)); (this->r_cylinder_lo << 8) | (this->r_sect_num);
} else { // translate old fashioned CHS addressing to LBA } else { // translate old fashioned CHS addressing to LBA
uint16_t c = (this->r_cylinder_hi << 8) + this->r_cylinder_lo; uint16_t c = (this->r_cylinder_hi << 8) + this->r_cylinder_lo;
uint8_t h = this->r_dev_head & 0xF; uint8_t h = this->r_dev_head & 0xF;
@@ -333,7 +274,7 @@ uint64_t AtaHardDisk::get_lba() {
LOG_F(ERROR, "%s: zero sector number is not allowed!", this->name.c_str()); LOG_F(ERROR, "%s: zero sector number is not allowed!", this->name.c_str());
return -1ULL; return -1ULL;
} else } else
return uint64_t((this->heads * c + h) * this->sectors + s - 1); return (this->heads * c + h) * this->sectors + s - 1;
} }
} }
@@ -390,7 +331,7 @@ static const PropMap AtaHardDisk_Properties = {
}; };
static const DeviceDescription AtaHardDisk_Descriptor = { static const DeviceDescription AtaHardDisk_Descriptor = {
AtaHardDisk::create, {}, AtaHardDisk_Properties, HWCompType::IDE_DEV AtaHardDisk::create, {}, AtaHardDisk_Properties
}; };
REGISTER_DEVICE(AtaHardDisk, AtaHardDisk_Descriptor); REGISTER_DEVICE(AtaHardDisk, AtaHardDisk_Descriptor);
+8 -12
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -24,21 +24,20 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef ATA_HARD_DISK_H #ifndef ATA_HARD_DISK_H
#define ATA_HARD_DISK_H #define ATA_HARD_DISK_H
#include <core/timermanager.h>
#include <devices/common/ata/atabasedevice.h> #include <devices/common/ata/atabasedevice.h>
#include <utils/imgfile.h> #include <utils/imgfile.h>
#include <string> #include <string>
constexpr auto ATA_HD_SEC_SIZE = 512; #define ATA_HD_SEC_SIZE 512
constexpr auto SECTORS_PER_INT = 16; #define SECTORS_PER_INT 16
// C:16383 x H:16 x S:63 = C:1032 x H:254 x S:63 = 8063.5078125 MiB = 8.46 GB // C:16383 x H:16 x S:63 = C:1032 x H:254 x S:63 = 8063.5078125 MiB = 8.46 GB
constexpr auto ATA_BIOS_LIMIT = 16514064; #define ATA_BIOS_LIMIT 16514064
// C:65535 x H:16 x S:255 = 127.498 GiB = 136.900 GB = largest identify // C:65535 x H:16 x S:255 = 127.498 GiB = 136.900 GB = largest identify
constexpr auto REAL_CHS_LIMIT = 267382800; #define REAL_CHS_LIMIT 267382800
// C:65536 x H:16 x S:255 = 127.500 GiB = 136.902 GB = largest address // C:65536 x H:16 x S:255 = 127.500 GiB = 136.902 GB = largest address
constexpr auto CHS_LIMIT = 267386880; #define CHS_LIMIT 267386880
class AtaHardDisk : public AtaBaseDevice class AtaHardDisk : public AtaBaseDevice
{ {
@@ -72,11 +71,8 @@ private:
uint8_t sectors; uint8_t sectors;
uint8_t sectors_per_int = 0; // sectors per interrupt for READ_MULTIPLE/WRITE_MULTIPLE uint8_t sectors_per_int = 0; // sectors per interrupt for READ_MULTIPLE/WRITE_MULTIPLE
uint8_t cur_dma_mode = 2; // current multi-word DMA mode
char * buffer = new char[1 <<17]; char * buffer = new char[1 <<17];
TimerInfo signal_ready_timer;
}; };
#endif // ATA_HARD_DISK_H #endif // ATA_HARD_DISK_H
+21 -69
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -21,10 +21,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file Basic ATAPI interface emulation. */ /** @file Basic ATAPI interface emulation. */
#include <core/endianswap.h>
#include <devices/common/ata/atabasedevice.h> #include <devices/common/ata/atabasedevice.h>
#include <devices/common/ata/atapibasedevice.h> #include <devices/common/ata/atapibasedevice.h>
#include <devices/common/ata/atadefs.h> #include <devices/common/ata/atadefs.h>
#include <endianswap.h>
#include <loguru.hpp> #include <loguru.hpp>
#include <cinttypes> #include <cinttypes>
@@ -33,7 +33,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
using namespace ata_interface; using namespace ata_interface;
AtapiBaseDevice::AtapiBaseDevice(const std::string name) AtapiBaseDevice::AtapiBaseDevice(const std::string name)
: AtaBaseDevice(name, DEVICE_TYPE_ATAPI), ScsiPhysInterface(PHY_ID_ATAPI) { : AtaBaseDevice(name, DEVICE_TYPE_ATAPI) {
} }
void AtapiBaseDevice::device_set_signature() { void AtapiBaseDevice::device_set_signature() {
@@ -62,9 +62,7 @@ uint16_t AtapiBaseDevice::read(const uint8_t reg_addr) {
if (this->data_available()) { if (this->data_available()) {
this->r_status &= ~DRQ; this->r_status &= ~DRQ;
this->r_status |= BSY; this->r_status |= BSY;
// Is this going to work here? this->update_intrq(1); // Is this going to work here? The interrupt happens before returning ret_data.
// The interrupt happens before returning ret_data.
this->update_intrq(1);
} }
else if (this->status_expected) { else if (this->status_expected) {
this->present_status(); this->present_status();
@@ -89,15 +87,15 @@ uint16_t AtapiBaseDevice::read(const uint8_t reg_addr) {
return this->r_dev_head; return this->r_dev_head;
case ATA_Reg::STATUS: case ATA_Reg::STATUS:
this->update_intrq(0); this->update_intrq(0);
return this->r_status;
case ATA_Reg::ALT_STATUS: 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->r_byte_count = this->request_data();
this->data_in_phase(); this->data_out_phase();
} }
return this->r_status; return this->r_status;
default: default:
LOG_F(WARNING, "%s: read from unknown register 0x%X", this->name.c_str(), LOG_F(WARNING, "Attempted to read unknown register: %x", reg_addr);
reg_addr);
return 0; return 0;
} }
} }
@@ -105,22 +103,13 @@ uint16_t AtapiBaseDevice::read(const uint8_t reg_addr) {
void AtapiBaseDevice::write(const uint8_t reg_addr, const uint16_t value) { void AtapiBaseDevice::write(const uint8_t reg_addr, const uint16_t value) {
switch (reg_addr) { switch (reg_addr) {
case ATA_Reg::DATA: case ATA_Reg::DATA:
if (!(this->r_int_reason & ATAPI_Int_Reason::IO)) { // host --> device? if (has_data()) {
if (this->r_int_reason & ATAPI_Int_Reason::CoD) { // command phase? *this->data_ptr++ = BYTESWAP_16(value);
if (this->xfer_cnt > 0) { this->xfer_cnt -= 2;
*this->data_ptr++ = BYTESWAP_16(value); if (this->xfer_cnt <= 0) {
this->xfer_cnt -= 2; this->r_status &= ~DRQ;
if (this->xfer_cnt <= 0) { if (this->r_int_reason & CoD) {
this->r_status &= ~DRQ; this->perform_packet_command();
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;
} }
} }
} }
@@ -150,7 +139,7 @@ void AtapiBaseDevice::write(const uint8_t reg_addr, const uint16_t value) {
this->device_control(value); this->device_control(value);
break; break;
default: default:
LOG_F(WARNING, "%s: write to unknown register 0x%X", this->name.c_str(), reg_addr); LOG_F(WARNING, "Attempted to write unknown IDE register: %x", reg_addr);
} }
} }
@@ -180,7 +169,7 @@ int AtapiBaseDevice::perform_command() {
this->data_ptr = (uint16_t *)this->data_buf; this->data_ptr = (uint16_t *)this->data_buf;
this->xfer_cnt = 512; this->xfer_cnt = 512;
this->status_expected = false; this->status_expected = false;
this->data_in_phase(); this->data_out_phase();
break; break;
case SET_FEATURES: case SET_FEATURES:
switch (this->r_features) { switch (this->r_features) {
@@ -201,14 +190,12 @@ int AtapiBaseDevice::perform_command() {
LOG_F(ERROR, "%s: unsupported command 0x%X", this->name.c_str(), this->r_command); LOG_F(ERROR, "%s: unsupported command 0x%X", this->name.c_str(), this->r_command);
this->r_error |= ATA_Error::ABRT; this->r_error |= ATA_Error::ABRT;
this->r_status |= ATA_Status::ERR; this->r_status |= ATA_Status::ERR;
this->r_status &= ~BSY;
this->update_intrq(1);
} }
return 0; return 0;
} }
void AtapiBaseDevice::data_in_phase() { void AtapiBaseDevice::data_out_phase() {
this->r_int_reason |= ATAPI_Int_Reason::IO; // device->host this->r_int_reason |= ATAPI_Int_Reason::IO; // device->host
this->r_int_reason &= ~ATAPI_Int_Reason::CoD; // data this->r_int_reason &= ~ATAPI_Int_Reason::CoD; // data
this->signal_data_ready(); this->signal_data_ready();
} }
@@ -220,38 +207,3 @@ void AtapiBaseDevice::present_status() {
this->r_status &= ~BSY; this->r_status &= ~BSY;
this->update_intrq(1); 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);
}
}
+5 -26
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -25,13 +25,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#define ATAPI_BASE_DEVICE_H #define ATAPI_BASE_DEVICE_H
#include <devices/common/ata/atabasedevice.h> #include <devices/common/ata/atabasedevice.h>
#include <devices/common/scsi/scsi.h>
#include <devices/common/scsi/scsiphysinterface.h>
#include <cinttypes> #include <cinttypes>
#include <string> #include <string>
class AtapiBaseDevice : public AtaBaseDevice, public ScsiPhysInterface class AtapiBaseDevice : public AtaBaseDevice
{ {
public: public:
AtapiBaseDevice(const std::string name); AtapiBaseDevice(const std::string name);
@@ -42,33 +40,14 @@ public:
uint16_t read(const uint8_t reg_addr) override; uint16_t read(const uint8_t reg_addr) override;
void write(const uint8_t reg_addr, const uint16_t value) 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 // methods to be implemented in the particular device
int perform_command() override; int perform_command() override;
virtual void perform_packet_command() = 0; virtual void perform_packet_command() = 0;
virtual int get_config(uint8_t* pkt, uint8_t* buf) = 0;
virtual int request_data() = 0; virtual int request_data() = 0;
virtual bool data_available() = 0; virtual bool data_available() = 0;
// methods with default implementation // methods with default implementation
virtual void data_in_phase(); virtual void data_out_phase();
virtual void present_status(); virtual void present_status();
protected: protected:
+157 -100
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -21,37 +21,25 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file ATAPI CDROM implementation. */ /** @file ATAPI CDROM implementation. */
#include <core/memaccess.h>
#include <devices/common/ata/atadefs.h> #include <devices/common/ata/atadefs.h>
#include <devices/common/ata/atapicdrom.h> #include <devices/common/ata/atapicdrom.h>
#include <devices/common/ata/idechannel.h> #include <devices/common/ata/idechannel.h>
#include <devices/common/scsi/scsi.h> // ATAPI CDROM reuses SCSI commands (sic!)
#include <devices/deviceregistry.h> #include <devices/deviceregistry.h>
#include <machines/machinebase.h> #include <machines/machinebase.h>
#include <machines/machineproperties.h> #include <machines/machineproperties.h>
#include <memaccess.h>
#include <cstring>
#include <string> #include <string>
#include <core/timermanager.h>
using namespace ata_interface; using namespace ata_interface;
static char cdrom_vendor_id[] = "DINGUS "; AtapiCdrom::AtapiCdrom(std::string name) : CdromDrive(), AtapiBaseDevice(name) {
static char cdrom_product_id[] = "DINGUS CD-ROM "; this->set_error_callback(
static char cdrom_revision_id[] = "1.0 "; [this](uint8_t sense_key, uint8_t asc) {
this->status_error(sense_key, asc);
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() { int AtapiCdrom::device_postinit() {
@@ -71,8 +59,7 @@ int AtapiCdrom::device_postinit() {
std::string cdr_image_path = GET_STR_PROP("cdr_img"); std::string cdr_image_path = GET_STR_PROP("cdr_img");
if (!cdr_image_path.empty()) { if (!cdr_image_path.empty()) {
if (!this->insert_image(cdr_image_path)) this->insert_image(cdr_image_path);
return -1;
} }
return 0; return 0;
@@ -88,32 +75,134 @@ void AtapiCdrom::perform_packet_command() {
LOG_F(WARNING, "%s: doing_sector_areas reset", this->name.c_str()); 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]) { 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_10:
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 (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:
lba = READ_DWORD_BE_U(&this->cmd_pkt[2]);
xfer_len = READ_WORD_BE_U(&this->cmd_pkt[7]);
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_12:
lba = READ_DWORD_BE_U(&this->cmd_pkt[2]);
xfer_len = READ_DWORD_BE_U(&this->cmd_pkt[6]);
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: case ScsiCommand::READ_CD:
{ {
lba = READ_DWORD_BE_U(&this->cmd_pkt[2]); lba = READ_DWORD_BE_U(&this->cmd_pkt[2]);
xfer_len = (this->cmd_pkt[6] << 16) | READ_WORD_BE_U(&this->cmd_pkt[7]); xfer_len = (this->cmd_pkt[6] << 16) | READ_WORD_BE_U(&this->cmd_pkt[7]);
if (this->cmd_pkt[9] == 0 && (this->cmd_pkt[10] & 7) == 0) {
// Treat as a non-data command.
xfer_len = 0;
}
// if transfer length is zero then just complete command
if (xfer_len == 0) {
this->status_good();
this->present_status();
break;
}
if (this->cmd_pkt[1] || (this->cmd_pkt[9] & ~0xf8) || ((this->cmd_pkt[9] & 0xf8) == 0) || this->cmd_pkt[10]) if (this->cmd_pkt[1] || (this->cmd_pkt[9] & ~0xf8) || ((this->cmd_pkt[9] & 0xf8) == 0) || this->cmd_pkt[10])
LOG_F(WARNING, "%s: unsupported READ_CD params: %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X", LOG_F(WARNING, "%s: unsupported READ_CD params: %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X",
this->name.c_str(), this->name.c_str(),
@@ -152,8 +241,7 @@ void AtapiCdrom::perform_packet_command() {
else { else {
disk_image_byte_count = (this->r_byte_count / bytes_per_block) * this->block_size; // whole blocks disk_image_byte_count = (this->r_byte_count / bytes_per_block) * this->block_size; // whole blocks
if ((this->r_byte_count % bytes_per_block) > bytes_prolog) { // partial block if ((this->r_byte_count % bytes_per_block) > bytes_prolog) { // partial block
int disk_image_byte_count_partial_block = int disk_image_byte_count_partial_block = (this->r_byte_count % bytes_per_block) - bytes_prolog; // remove prolog from partial block
(this->r_byte_count % bytes_per_block) - bytes_prolog; // remove prolog from partial block
if (disk_image_byte_count_partial_block > this->block_size) { // partial block includes some epilog? if (disk_image_byte_count_partial_block > this->block_size) { // partial block includes some epilog?
disk_image_byte_count_partial_block = this->block_size; // // remove epilog from partial block disk_image_byte_count_partial_block = this->block_size; // // remove epilog from partial block
} }
@@ -164,8 +252,7 @@ void AtapiCdrom::perform_packet_command() {
int disk_image_bytes_received = this->read_begin(xfer_len, disk_image_byte_count); int disk_image_bytes_received = this->read_begin(xfer_len, disk_image_byte_count);
int bytes_received = (disk_image_bytes_received / this->block_size) * bytes_per_block + bytes_prolog + int bytes_received = (disk_image_bytes_received / this->block_size) * bytes_per_block + bytes_prolog + (disk_image_bytes_received % this->block_size); // whole blocks + prolog + partial block
(disk_image_bytes_received % this->block_size); // whole blocks + prolog + partial block
if (bytes_received > this->r_byte_count) { // if partial epilog or partial prolog if (bytes_received > this->r_byte_count) { // if partial epilog or partial prolog
bytes_received = this->r_byte_count; // confine to r_byte_count bytes_received = this->r_byte_count; // confine to r_byte_count
} }
@@ -174,49 +261,17 @@ void AtapiCdrom::perform_packet_command() {
this->data_ptr = (uint16_t*)this->data_cache.get(); this->data_ptr = (uint16_t*)this->data_cache.get();
this->status_good(); this->status_good();
this->data_in_phase(); this->data_out_phase();
break;
}
case ScsiCommand::GET_CONFIG: {
this->xfer_cnt = this->get_config(this->cmd_pkt, this->data_buf);
if (this->xfer_cnt == 0) {
this->present_status();
} else {
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_in_phase();
}
break; break;
} }
default: default:
ScsiCdromCmds::process_command(); 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();
} }
} }
int AtapiCdrom::get_config(uint8_t* pkt, uint8_t* buf) {
std::memset(buf, 0, 16);
// Data length (4 bytes header + 8 bytes for one feature descriptor - 4 bytes for length field)
uint32_t data_len = 8;
buf[0] = (data_len >> 24) & 0xFF;
buf[1] = (data_len >> 16) & 0xFF;
buf[2] = (data_len >> 8) & 0xFF;
buf[3] = data_len & 0xFF;
// Feature Descriptor 1 - Set profile to CD-ROM
buf[6] = 0;
buf[7] = 0x08;
// Feature Descriptor 2 - Feature Code, Version 0
buf[8] = 0x00;
buf[9] = 0x01; // Core Feature Code
buf[10] = 0x03; // Persist and Current bits set
buf[11] = 0x04; // Additional Length
return 12;
}
int AtapiCdrom::request_data() { int AtapiCdrom::request_data() {
// continuation of READ_CD above // continuation of READ_CD above
@@ -252,12 +307,11 @@ uint16_t AtapiCdrom::get_data() {
area_end += 4; // Header area_end += 4; // Header
if (this->current_block_byte >= area_start && this->current_block_byte < area_end) { if (this->current_block_byte >= area_start && this->current_block_byte < area_end) {
AddrMsf msf = lba_to_msf(this->current_block + 150); AddrMsf msf = lba_to_msf(this->current_block + 150);
uint8_t header[4]{ uint8_t header[4];
(uint8_t)msf.min, header[0] = msf.min;
(uint8_t)msf.sec, header[1] = msf.sec;
(uint8_t)msf.frm, header[2] = msf.frm;
0x01 // Mode 1 header[3] = 0x01; // Mode 1
};
ret_data = BYTESWAP_16(*((uint16_t*)(&header[current_block_byte - area_start]))); ret_data = BYTESWAP_16(*((uint16_t*)(&header[current_block_byte - area_start])));
} }
} }
@@ -314,22 +368,25 @@ uint16_t AtapiCdrom::get_data() {
} }
void AtapiCdrom::status_good() { void AtapiCdrom::status_good() {
this->status_expected = true;
this->r_error = 0;
this->sense_key = 0; this->sense_key = 0;
this->set_status(ScsiStatus::GOOD, this->sense_key); this->r_status &= ~ATA_Status::ERR;
} }
void AtapiCdrom::status_error(uint8_t sense_key, uint8_t asc) { void AtapiCdrom::status_error(uint8_t sense_key, uint8_t asc) {
this->status_expected = true;
this->sense_key = sense_key; this->sense_key = sense_key;
this->asc = asc; this->asc = asc;
this->set_status(ScsiStatus::CHECK_CONDITION, this->sense_key); this->r_error = (sense_key << 4) | ATA_Error::ABRT;
this->r_status |= ATA_Status::ERR;
} }
static const PropMap AtapiCdrom_Properties = { static const PropMap AtapiCdromProperties = {
{"cdr_img", new StrProperty("")}, {"cdr_img", new StrProperty("")},
}; };
static const DeviceDescription AtapiCdrom_Descriptor = { static const DeviceDescription AtapiCdromDescriptor =
AtapiCdrom::create, {}, AtapiCdrom_Properties, HWCompType::IDE_DEV {AtapiCdrom::create, {}, AtapiCdromProperties};
};
REGISTER_DEVICE(AtapiCdrom, AtapiCdrom_Descriptor); REGISTER_DEVICE(AtapiCdrom, AtapiCdromDescriptor);
+9 -15
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -25,11 +25,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#define ATAPI_CDROM_H #define ATAPI_CDROM_H
#include <devices/common/ata/atapibasedevice.h> #include <devices/common/ata/atapibasedevice.h>
#include <devices/common/scsi/scsicdromcmds.h> #include <devices/storage/cdromdrive.h>
#include <string> #include <string>
class AtapiCdrom : public AtapiBaseDevice, public ScsiCdromCmds { class AtapiCdrom : public CdromDrive, public AtapiBaseDevice {
public: public:
AtapiCdrom(std::string name); AtapiCdrom(std::string name);
~AtapiCdrom() = default; ~AtapiCdrom() = default;
@@ -38,19 +38,10 @@ public:
return std::unique_ptr<AtapiCdrom>(new AtapiCdrom("ATAPI-CDROM")); return std::unique_ptr<AtapiCdrom>(new AtapiCdrom("ATAPI-CDROM"));
} }
bool is_device_ready() override { return this->medium_present(); }
uint8_t not_ready_reason() override { return ScsiError::MEDIUM_NOT_PRESENT; }
int device_postinit() override; int device_postinit() override;
void perform_packet_command() 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; int request_data() override;
bool data_available() override { bool data_available() override {
@@ -61,8 +52,11 @@ public:
void status_error(uint8_t sense_key, uint8_t asc); void status_error(uint8_t sense_key, uint8_t asc);
uint16_t get_data(); uint16_t get_data();
private: private:
uint8_t sense_key = 0;
uint8_t asc = 0;
uint8_t ascq = 0;
bool doing_sector_areas = false; bool doing_sector_areas = false;
uint8_t sector_areas; uint8_t sector_areas;
uint32_t current_block; uint32_t current_block;
+4 -4
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -139,7 +139,7 @@ bool CmdIdeCtrl::pci_io_write(uint32_t offset, uint32_t value, uint32_t size) {
return false; return false;
return true; return true;
} };
uint8_t CmdIdeCtrl::read_config_reg(uint32_t reg_offset) { uint8_t CmdIdeCtrl::read_config_reg(uint32_t reg_offset) {
switch(reg_offset) { switch(reg_offset) {
+7 -7
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -31,14 +31,14 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <memory> #include <memory>
constexpr auto DEV_ID_CMD646 = 0x646; #define DEV_ID_CMD646 0x646
constexpr auto MY_DEV_CLASS = 0x010180; // mass storage | IDE controller | IDE master #define MY_DEV_CLASS 0x010180 // mass storage | IDE controller | IDE master
constexpr auto MY_REV_ID = 7; #define MY_REV_ID 7
// Offset for converting addresses of the device control block registers // Offset for converting addresses of the device control block registers
// defined in the PCI IDE Controller specification, rev. 1.0 3/4/94 // defined in the PCI IDE Controller specification, rev. 1.0 3/4/94
// to the addresses used in IdeChannel // to the addresses used in IdeChannel
constexpr auto DEV_CTRL_BLK_OFFSET = 0x14; #define DEV_CTRL_BLK_OFFSET 0x14
/** CMD646 control/status registers. */ /** CMD646 control/status registers. */
enum { enum {
+5 -24
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -30,7 +30,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
and interrupt handling. and interrupt handling.
*/ */
#include <core/timermanager.h>
#include <devices/common/ata/atabasedevice.h> #include <devices/common/ata/atabasedevice.h>
#include <devices/common/ata/atadefs.h> #include <devices/common/ata/atadefs.h>
#include <devices/common/ata/idechannel.h> #include <devices/common/ata/idechannel.h>
@@ -82,24 +81,6 @@ void IdeChannel::write(const uint8_t reg_addr, const uint32_t val, const int siz
} }
} }
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(DmaChannel *ch_obj, uint8_t *buf, int len) {
return this->devices[this->cur_dev]->push_data(buf, len);
}
void IdeChannel::assert_dmareq(uint64_t delay) {
if (this->dmareq_timer.active)
LOG_F(WARNING, "%s: dmareq_timer is already active", this->get_name().c_str());
TimerManager::get_instance()->add_oneshot_timer(this->dmareq_timer, delay, [this](uint64_t, uint64_t) {
//LOG_F(INFO, "%s: DMAREQ asserted", this->name.c_str());
this->dmareq_timer.active = false;
this->channel_obj->xfer_retry();
});
}
int MacioIdeChannel::device_postinit() { int MacioIdeChannel::device_postinit() {
this->int_ctrl = dynamic_cast<InterruptCtrl*>( this->int_ctrl = dynamic_cast<InterruptCtrl*>(
gMachineObj->get_comp_by_type(HWCompType::INT_CTRL)); gMachineObj->get_comp_by_type(HWCompType::INT_CTRL));
@@ -136,11 +117,11 @@ void MacioIdeChannel::write(const uint8_t reg_addr, const uint32_t val, const in
} }
static const DeviceDescription Ide0_Descriptor = { static const DeviceDescription Ide0_Descriptor = {
MacioIdeChannel::create_first, {}, {}, HWCompType::IDE_BUS MacioIdeChannel::create_first, {}, {}
}; };
static const DeviceDescription Ide1_Descriptor = { static const DeviceDescription Ide1_Descriptor = {
MacioIdeChannel::create_second, {}, {}, HWCompType::IDE_BUS MacioIdeChannel::create_second, {}, {}
}; };
REGISTER_DEVICE(Ide0, Ide0_Descriptor); REGISTER_DEVICE(Ide0, Ide0_Descriptor);
+10 -19
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -24,9 +24,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef IDE_CHANNEL_H #ifndef IDE_CHANNEL_H
#define IDE_CHANNEL_H #define IDE_CHANNEL_H
#include <core/timermanager.h>
#include <devices/common/ata/atadefs.h> #include <devices/common/ata/atadefs.h>
#include <devices/common/dmacore.h>
#include <devices/common/hwcomponent.h> #include <devices/common/hwcomponent.h>
#include <devices/common/hwinterrupt.h> #include <devices/common/hwinterrupt.h>
@@ -35,7 +33,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <memory> #include <memory>
#include <string> #include <string>
class IdeChannel : public HWComponent, public DmaDevice class IdeChannel : public HWComponent
{ {
public: public:
IdeChannel(const std::string name); IdeChannel(const std::string name);
@@ -43,11 +41,8 @@ public:
void register_device(int id, AtaInterface* dev_obj); void register_device(int id, AtaInterface* dev_obj);
virtual uint32_t read(const uint8_t reg_addr, const int size); 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); void write(const uint8_t reg_addr, const uint32_t val, const int size);
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() { void assert_pdiag() {
this->devices[0]->pdiag_callback(); this->devices[0]->pdiag_callback();
@@ -65,8 +60,6 @@ public:
this->irq_callback(intrq_state); this->irq_callback(intrq_state);
} }
void assert_dmareq(uint64_t delay);
protected: protected:
std::function<void(const uint8_t intrq_state)> irq_callback = nullptr; std::function<void(const uint8_t intrq_state)> irq_callback = nullptr;
@@ -75,15 +68,13 @@ private:
AtaInterface* devices[2]; AtaInterface* devices[2];
std::unique_ptr<AtaInterface> device_stub; std::unique_ptr<AtaInterface> device_stub;
TimerInfo dmareq_timer;
}; };
/** This class models an IDE channel specific to MacIO ASICs. */ /** This class models an IDE channel specific to MacIO ASICs. */
class MacioIdeChannel : public IdeChannel class MacioIdeChannel : public IdeChannel
{ {
public: public:
MacioIdeChannel(const std::string name) : IdeChannel(name) {} MacioIdeChannel(const std::string name) : IdeChannel(name) {};
~MacioIdeChannel() = default; ~MacioIdeChannel() = default;
static std::unique_ptr<HWComponent> create_first() { static std::unique_ptr<HWComponent> create_first() {
@@ -96,15 +87,15 @@ public:
int device_postinit() override; int device_postinit() override;
virtual uint32_t read(const uint8_t reg_addr, const int size) override; 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) override; void write(const uint8_t reg_addr, const uint32_t val, const int size);
private: private:
uint32_t ch_config = 0; // timing configuration for this channel uint32_t ch_config = 0; // timing configuration for this channel
// interrupt stuff // interrupt stuff
InterruptCtrl* int_ctrl = nullptr; InterruptCtrl* int_ctrl = nullptr;
uint64_t irq_id = 0; uint32_t irq_id = 0;
}; };
#endif // IDE_CHANNEL_H #endif // IDE_CHANNEL_H
+204 -219
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -21,15 +21,14 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file Descriptor-based direct memory access emulation. */ /** @file Descriptor-based direct memory access emulation. */
#include <core/endianswap.h>
#include <core/memaccess.h>
#include <core/timermanager.h> #include <core/timermanager.h>
#include <cpu/ppc/ppcmmu.h> #include <cpu/ppc/ppcmmu.h>
#include <devices/common/dbdma.h> #include <devices/common/dbdma.h>
#include <devices/common/dmacore.h> #include <devices/common/dmacore.h>
#include <devices/common/hwinterrupt.h> #include <devices/common/hwinterrupt.h>
#include <devices/common/mmiodevice.h> #include <devices/common/mmiodevice.h>
#include <devices/memctrl/memctrlbase.h> #include <endianswap.h>
#include <memaccess.h>
#include <cinttypes> #include <cinttypes>
#include <cstring> #include <cstring>
@@ -40,6 +39,12 @@ void DMAChannel::set_callbacks(DbdmaCallback start_cb, DbdmaCallback stop_cb) {
this->stop_cb = stop_cb; this->stop_cb = stop_cb;
} }
void DMAChannel::set_data_callbacks(DbdmaCallback in_cb, DbdmaCallback out_cb, DbdmaCallback flush_cb) {
this->in_cb = in_cb;
this->out_cb = out_cb;
this->flush_cb = flush_cb;
}
/* Load DMACmd from physical memory. */ /* Load DMACmd from physical memory. */
DMACmd* DMAChannel::fetch_cmd(uint32_t cmd_addr, DMACmd* p_cmd, bool *is_writable) { DMACmd* DMAChannel::fetch_cmd(uint32_t cmd_addr, DMACmd* p_cmd, bool *is_writable) {
MapDmaResult res = mmu_map_dma_mem(cmd_addr, 16, false); MapDmaResult res = mmu_map_dma_mem(cmd_addr, 16, false);
@@ -55,21 +60,20 @@ DMACmd* DMAChannel::fetch_cmd(uint32_t cmd_addr, DMACmd* p_cmd, bool *is_writabl
return cmd_host; return cmd_host;
} }
void DMAChannel::interpret_cmd() { uint8_t DMAChannel::interpret_cmd() {
DMACmd cmd_struct; DMACmd cmd_struct;
MapDmaResult res; MapDmaResult res;
if (this->cmd_in_progress) { if (this->cmd_in_progress) {
// if there is data remaining to transfer then the command is not finished // return current command if there is data to transfer
if (this->queue_len) if (this->queue_len)
return; return this->cur_cmd;
// 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(); this->finish_cmd();
} }
this->cur_host = fetch_cmd(this->cmd_ptr, &cmd_struct, &this->cur_is_writable); bool cmd_is_writable;
DMACmd *cmd_host = fetch_cmd(this->cmd_ptr, &cmd_struct, &cmd_is_writable);
this->ch_stat &= ~CH_STAT_WAKE; // clear wake bit (DMA spec, 5.5.3.4) this->ch_stat &= ~CH_STAT_WAKE; // clear wake bit (DMA spec, 5.5.3.4)
@@ -84,40 +88,43 @@ void DMAChannel::interpret_cmd() {
LOG_F(ERROR, "%s: Key > 0 not implemented", this->get_name().c_str()); LOG_F(ERROR, "%s: Key > 0 not implemented", this->get_name().c_str());
break; break;
} }
if (cmd_struct.req_count) { this->queue_len = cmd_struct.req_count;
if (this->queue_len) {
res = mmu_map_dma_mem(cmd_struct.address, cmd_struct.req_count, false); res = mmu_map_dma_mem(cmd_struct.address, cmd_struct.req_count, false);
this->queue_data = res.host_va; this->queue_data = res.host_va;
this->res_count = cmd_struct.req_count; this->res_count = 0;
this->queue_len = cmd_struct.req_count; // don't set queue_len until all the other fields are set
this->cmd_in_progress = true; this->cmd_in_progress = true;
switch (this->cur_cmd) { switch (this->cur_cmd) {
case DBDMA_Cmd::OUTPUT_MORE: case DBDMA_Cmd::OUTPUT_MORE:
case DBDMA_Cmd::OUTPUT_LAST: case DBDMA_Cmd::OUTPUT_LAST:
this->xfer_to_device(); this->xfer_to_device();
if (this->out_cb)
this->out_cb();
break; break;
case DBDMA_Cmd::INPUT_MORE: case DBDMA_Cmd::INPUT_MORE:
case DBDMA_Cmd::INPUT_LAST: case DBDMA_Cmd::INPUT_LAST:
this->xfer_from_device(); this->xfer_from_device();
if (this->in_cb)
this->in_cb();
break; break;
} }
} else { } else
this->queue_len = 0;
this->res_count = 0;
this->finish_cmd(); this->finish_cmd();
}
break; break;
case DBDMA_Cmd::STORE_QUAD: case DBDMA_Cmd::STORE_QUAD:
if ((cmd_struct.cmd_key & 7) != 6) if ((cmd_struct.cmd_key & 7) != 6)
LOG_F(ERROR, "%s: Invalid key %d in STORE_QUAD", this->get_name().c_str(), LOG_F(ERROR, "%s: Invalid key %d in STORE_QUAD", this->get_name().c_str(),
cmd_struct.cmd_key & 7); cmd_struct.cmd_key & 7);
this->xfer_quad(true); this->xfer_quad(&cmd_struct, nullptr);
break; break;
case DBDMA_Cmd::LOAD_QUAD: case DBDMA_Cmd::LOAD_QUAD:
if ((cmd_struct.cmd_key & 7) != 6) { if ((cmd_struct.cmd_key & 7) != 6) {
LOG_F(ERROR, "%s: Invalid key %d in LOAD_QUAD", this->get_name().c_str(), LOG_F(ERROR, "%s: Invalid key %d in LOAD_QUAD", this->get_name().c_str(),
cmd_struct.cmd_key & 7); cmd_struct.cmd_key & 7);
} }
this->xfer_quad(false); if (!cmd_is_writable)
LOG_F(ERROR, "%s: DMACmd is not writeable!", this->get_name().c_str());
this->xfer_quad(&cmd_struct, cmd_host);
break; break;
case DBDMA_Cmd::NOP: case DBDMA_Cmd::NOP:
this->finish_cmd(); this->finish_cmd();
@@ -133,45 +140,30 @@ void DMAChannel::interpret_cmd() {
this->ch_stat |= CH_STAT_DEAD; this->ch_stat |= CH_STAT_DEAD;
this->ch_stat &= ~CH_STAT_ACTIVE; this->ch_stat &= ~CH_STAT_ACTIVE;
} }
}
void DMAChannel::interpret_until_blocked() { return this->cur_cmd;
// Execute ready commands until a transfer is queued or the channel becomes idle/dead.
while (this->is_active()) {
this->interpret_cmd();
if (this->cmd_in_progress)
break;
}
}
void DMAChannel::update_cmd() {
if (this->cur_is_writable) {
if (this->cur_cmd < DBDMA_Cmd::STOP)
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() { void DMAChannel::finish_cmd() {
bool branch_taken = false; bool branch_taken = false;
// save interrupt bits from the completing command before cmd_ptr may change // obtain real pointer to the descriptor of the command to be finished
uint8_t saved_cmd_bits = this->cur_host->cmd_bits; 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;
// all commands except STOP update cmd.xferStatus and // all commands except STOP update cmd.xferStatus and
// perform actions under control of "i" interrupt, "b" branch, and "w" wait bits // perform actions under control of "i" interrupt, "b" branch, and "w" wait bits
if (this->cur_cmd < DBDMA_Cmd::STOP) { if (this->cur_cmd < DBDMA_Cmd::STOP) {
// react to cmd.w (wait) bits // react to cmd.w (wait) bits
if (saved_cmd_bits & 3) { if (cmd_desc[2] & 3) {
bool cond = true; bool cond = true;
if ((saved_cmd_bits & 3) != 3) { if ((cmd_desc[2] & 3) != 3) {
uint16_t wt_mask = this->wait_select >> 16; uint16_t wt_mask = this->wait_select >> 16;
cond = (this->ch_stat & wt_mask) == (this->wait_select & wt_mask); cond = (this->ch_stat & wt_mask) == (this->wait_select & wt_mask);
if ((saved_cmd_bits & 3) == 2) { if ((cmd_desc[2] & 3) == 2) {
cond = !cond; // wait if cond = false cond = !cond; // wait if cond = false
} }
} }
@@ -183,44 +175,50 @@ void DMAChannel::finish_cmd() {
this->ch_stat &= ~CH_STAT_BT; this->ch_stat &= ~CH_STAT_BT;
// react to cmd.b (branch) bits // react to cmd.b (branch) bits
if (saved_cmd_bits & 0xC) { if (cmd_desc[2] & 0xC) {
bool cond = true; bool cond = true;
if ((saved_cmd_bits & 0xC) != 0xC) { if ((cmd_desc[2] & 0xC) != 0xC) {
uint16_t br_mask = this->branch_select >> 16; uint16_t br_mask = this->branch_select >> 16;
cond = (this->ch_stat & br_mask) == (this->branch_select & br_mask); cond = (this->ch_stat & br_mask) == (this->branch_select & br_mask);
if ((saved_cmd_bits & 0xC) == 0x8) { if ((cmd_desc[2] & 0xC) == 0x8) {
cond = !cond; // branch if cond = false cond = !cond; // branch if cond = false
} }
} }
if (cond) { if (cond) {
this->cmd_ptr = READ_DWORD_LE_A(&this->cur_host->cmd_arg); this->cmd_ptr = READ_DWORD_LE_A(&cmd_desc[8]);
branch_taken = true; branch_taken = true;
this->ch_stat |= CH_STAT_BT; this->ch_stat |= CH_STAT_BT;
} }
} }
if (res.is_writable)
WRITE_WORD_LE_A(&cmd_desc[14], this->ch_stat | CH_STAT_ACTIVE);
} }
this->update_cmd(); 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;
}
if (this->cur_cmd < DBDMA_Cmd::STOP && !branch_taken) if (this->cur_cmd < DBDMA_Cmd::STOP && !branch_taken)
this->cmd_ptr += 16; this->cmd_ptr += 16;
// use the interrupt bits saved before cmd_ptr was advanced or branched
if (this->cur_cmd < DBDMA_Cmd::STOP) { if (this->cur_cmd < DBDMA_Cmd::STOP) {
this->update_irq(saved_cmd_bits); this->update_irq();
} }
this->cmd_in_progress = false; this->cmd_in_progress = false;
} }
void DMAChannel::xfer_quad(bool is_store) { void DMAChannel::xfer_quad(const DMACmd *cmd_desc, DMACmd *cmd_host) {
MapDmaResult res; MapDmaResult res;
uint32_t addr = READ_DWORD_LE_A(&this->cur_host->address); uint32_t addr;
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 // parse and fix reqCount
uint32_t xfer_size = req_count & 7; uint32_t xfer_size = cmd_desc->req_count & 7;
if (xfer_size & 4) { if (xfer_size & 4) {
xfer_size = 4; xfer_size = 4;
} else if (xfer_size & 2) { } else if (xfer_size & 2) {
@@ -228,8 +226,9 @@ void DMAChannel::xfer_quad(bool is_store) {
} else { } else {
xfer_size = 1; xfer_size = 1;
} }
this->res_count = req_count; // this is the value that gets written to cmd.resCount this->res_count = cmd_desc->req_count; // this is the value that gets written to cmd.resCount
addr = cmd_desc->address;
if (addr & (xfer_size - 1)) { if (addr & (xfer_size - 1)) {
LOG_F(ERROR, "%s: QUAD address 0x%08x is not aligned!", this->get_name().c_str(), addr); LOG_F(ERROR, "%s: QUAD address 0x%08x is not aligned!", this->get_name().c_str(), addr);
addr &= ~(xfer_size - 1); addr &= ~(xfer_size - 1);
@@ -238,15 +237,14 @@ void DMAChannel::xfer_quad(bool is_store) {
res = mmu_map_dma_mem(addr, xfer_size, true); res = mmu_map_dma_mem(addr, xfer_size, true);
// prepare data pointers and perform data transfer // prepare data pointers and perform data transfer
if (is_store) { if (!cmd_host) {
if (res.type & RT_MMIO) { if (res.type & RT_MMIO) {
res.dev_obj->write(res.dev_base, addr - res.dev_base, res.dev_obj->write(res.dev_base, addr - res.dev_base, cmd_desc->cmd_arg, xfer_size);
BYTESWAP_SIZED(cmd_arg, xfer_size), xfer_size);
} else if (res.is_writable) { } else if (res.is_writable) {
switch (xfer_size) { switch (xfer_size) {
case 1: *res.host_va = cmd_arg; break; case 1: *res.host_va = cmd_desc->cmd_arg; break;
case 2: WRITE_WORD_LE_A(res.host_va, 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_arg); break; case 4: WRITE_DWORD_LE_A(res.host_va, cmd_desc->cmd_arg); break;
} }
} else { } else {
LOG_F(ERROR, "SOS: DMA access is not to RAM %08X!\n", addr); LOG_F(ERROR, "SOS: DMA access is not to RAM %08X!\n", addr);
@@ -263,40 +261,38 @@ void DMAChannel::xfer_quad(bool is_store) {
default: value = 0; break; default: value = 0; break;
} }
} }
if (!this->cur_is_writable) WRITE_DWORD_LE_A(&cmd_host->cmd_arg, value);
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 (this->cur_host->cmd_bits & 0xC) if (cmd_desc->cmd_bits & 0xC)
ABORT_F("%s: cmd_bits.b should be zero for LOAD/STORE_QUAD!", ABORT_F("%s: cmd_bits.b should be zero for LOAD/STORE_QUAD!",
this->get_name().c_str()); this->get_name().c_str());
this->finish_cmd(); this->finish_cmd();
} }
void DMAChannel::update_irq(uint8_t cmd_bits) { 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;
// STOP doesn't generate interrupts // STOP doesn't generate interrupts
if (this->cur_cmd < DBDMA_Cmd::STOP) { if (this->cur_cmd < DBDMA_Cmd::STOP) {
// react to cmd.i (interrupt) bits // react to cmd.i (interrupt) bits
if (cmd_bits & 0x30) { if (cmd_desc[2] & 0x30) {
bool cond = true; bool cond = true;
if ((cmd_bits & 0x30) != 0x30) { if ((cmd_desc[2] & 0x30) != 0x30) {
uint16_t int_mask = this->int_select >> 16; uint16_t int_mask = this->int_select >> 16;
cond = (this->ch_stat & int_mask) == (this->int_select & int_mask); cond = (this->ch_stat & int_mask) == (this->int_select & int_mask);
if ((cmd_bits & 0x30) == 0x20) { if ((cmd_desc[2] & 0x30) == 0x20) {
cond = !cond; // generate interrupt if cond = false cond = !cond; // generate interrupt if cond = false
} }
} }
if (cond) { if (cond) {
if (this->int_ctrl) { if (int_ctrl) {
if (!this->interrupt_timer.active) { TimerManager::get_instance()->add_immediate_timer([this] {
TimerManager::get_instance()->add_immediate_timer(this->interrupt_timer, [this](uint64_t, uint64_t) { this->int_ctrl->ack_dma_int(this->irq_id, 1);
this->interrupt_timer.active = 0; });
this->int_ctrl->ack_dma_int(this->irq_id, 1);
});
}
} else } else
LOG_F(ERROR, "%s Interrupt ignored", this->get_name().c_str()); LOG_F(ERROR, "%s Interrupt ignored", this->get_name().c_str());
} }
@@ -317,15 +313,6 @@ uint32_t DMAChannel::reg_read(uint32_t offset, int size) {
case DMAReg::CMD_PTR_LO: case DMAReg::CMD_PTR_LO:
result = this->cmd_ptr; result = this->cmd_ptr;
break; break;
case DMAReg::INT_SELECT:
result = this->int_select;
break;
case DMAReg::BRANCH_SELECT:
result = this->branch_select;
break;
case DMAReg::WAIT_SELECT:
result = this->wait_select;
break;
default: default:
LOG_F(WARNING, "%s: Unsupported DMA channel register read at 0x%X", LOG_F(WARNING, "%s: Unsupported DMA channel register read at 0x%X",
this->get_name().c_str(), offset); this->get_name().c_str(), offset);
@@ -338,88 +325,69 @@ uint32_t DMAChannel::reg_read(uint32_t offset, int size) {
} }
void DMAChannel::reg_write(uint32_t offset, uint32_t value, int size) { void DMAChannel::reg_write(uint32_t offset, uint32_t value, int size) {
uint16_t mask, data; uint16_t mask, old_stat, new_stat;
if (size != 4) { if (size != 4) {
ABORT_F("%s: non-DWORD writes to a DMA channel not supported", ABORT_F("%s: non-DWORD writes to a DMA channel not supported",
this->get_name().c_str()); this->get_name().c_str());
} }
value = BYTESWAP_32(value); value = BYTESWAP_32(value);
old_stat = this->ch_stat;
switch (offset) { switch (offset) {
case DMAReg::CH_CTRL: case DMAReg::CH_CTRL:
mask = value >> 16; mask = value >> 16;
data = value & 0xFFFF; 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);
// update general purpose channel status & control bits s0...s7 // update ch_stat.s0...s7 if requested (needed for interrupt generation)
// if requested (needed for interrupt generation) if ((new_stat & 0xFF) != (old_stat & 0xFF)) {
if (mask & 0xFF) this->ch_stat |= new_stat & 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. // flush bit can be set at the same time the run bit is cleared.
// That means we need to update memory before channel operation // That means we need to update memory before channel operation
// is aborted to prevent data loss. // is aborted to prevent data loss.
if (mask & CH_STAT_FLUSH) { if (new_stat & CH_STAT_FLUSH) {
// FLUSH=1 should update memory for INPUT_MORE & INPUT_LAST commands if (this->cur_cmd <= DBDMA_Cmd::INPUT_LAST &&
// when the channel is active and not dead. this->flush_cb && (new_stat & CH_STAT_ACTIVE) &&
// Setting FLUSH to 0 has no effect. !(this->ch_stat & CH_STAT_DEAD)) {
if (data & CH_STAT_FLUSH) { this->flush_cb();
if ( } else {
(this->cur_cmd == DBDMA_Cmd::INPUT_MORE || this->cur_cmd == DBDMA_Cmd::INPUT_LAST) && // NOTE: because this implementation doesn't currently support
this->is_active() // partial memory updates no special action is taken here
) { new_stat &= ~CH_STAT_FLUSH;
this->ch_stat |= CH_STAT_FLUSH;
if (this->dev_obj != nullptr)
this->dev_obj->notify(this, DMA_MSG_FLUSH);
this->update_cmd();
}
} }
this->ch_stat &= ~CH_STAT_FLUSH; this->ch_stat = new_stat;
} }
if (mask & CH_STAT_RUN) { if ((new_stat & CH_STAT_RUN) != (old_stat & CH_STAT_RUN)) {
if (data & CH_STAT_RUN) { if (new_stat & CH_STAT_RUN) {
// some drivers clear the PAUSE bit while setting the RUN bit. new_stat |= CH_STAT_ACTIVE;
// Clear the PAUSE bit without resuming the channel operation this->ch_stat = new_stat;
// in this case. this->start();
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 { } else {
if (this->ch_stat & CH_STAT_ACTIVE) { this->abort();
this->abort(); this->update_irq();
this->update_irq(this->cur_host->cmd_bits); new_stat &= ~CH_STAT_ACTIVE;
this->cmd_in_progress = false; new_stat &= ~CH_STAT_DEAD;
} this->cmd_in_progress = false;
this->ch_stat &= ~(CH_STAT_RUN | CH_STAT_ACTIVE | CH_STAT_DEAD); this->ch_stat = new_stat;
} }
} else if (mask & CH_STAT_PAUSE) { } else if ((new_stat & CH_STAT_WAKE) != (old_stat & CH_STAT_WAKE)) {
if (data & CH_STAT_PAUSE) { if (new_stat & CH_STAT_WAKE) {
if (this->ch_stat & CH_STAT_ACTIVE) new_stat |= CH_STAT_ACTIVE;
this->pause(); this->ch_stat = new_stat;
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(); 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; break;
@@ -432,12 +400,11 @@ void DMAChannel::reg_write(uint32_t offset, uint32_t value, int size) {
} }
break; break;
case DMAReg::CMD_PTR_LO: case DMAReg::CMD_PTR_LO:
if (!(this->ch_stat & CH_STAT_ACTIVE)) { // DBDMA spec 5.5.4 (disagrees with 2.9.1.3) if (!(this->ch_stat & CH_STAT_RUN) && !(this->ch_stat & CH_STAT_ACTIVE)) {
this->cmd_ptr = value; this->cmd_ptr = value;
LOG_F(9, "%s: CommandPtrLo set to 0x%X%s", this->get_name().c_str(), LOG_F(9, "%s: CommandPtrLo set to 0x%X", this->get_name().c_str(),
this->cmd_ptr, (this->ch_stat & CH_STAT_RUN) ? " while running!" : ""); this->cmd_ptr);
} else }
LOG_F(WARNING, "%s: CommandPtrLo update skipped", this->get_name().c_str());
break; break;
case DMAReg::INT_SELECT: case DMAReg::INT_SELECT:
this->int_select = value & 0xFF00FFUL; this->int_select = value & 0xFF00FFUL;
@@ -460,18 +427,12 @@ void DMAChannel::xfer_from_device() {
this->xfer_dir = DMA_DIR_FROM_DEV; this->xfer_dir = DMA_DIR_FROM_DEV;
int got_bytes = this->dev_obj->xfer_from(this, this->queue_data, this->queue_len); if (!this->dev_obj->xfer_from(this->queue_data, this->queue_len)) {
this->queue_data += got_bytes; this->queue_len = 0;
this->res_count -= got_bytes;
this->queue_len -= got_bytes;
if (!this->queue_len) {
this->finish_cmd(); this->finish_cmd();
} else if (got_bytes) {
LOG_F(WARNING, "%s: got unexpected amount of data in xfer_from_device",
this->get_name().c_str());
} }
this->interpret_until_blocked(); this->interpret_cmd();
} }
void DMAChannel::xfer_to_device() { void DMAChannel::xfer_to_device() {
@@ -480,48 +441,28 @@ void DMAChannel::xfer_to_device() {
this->xfer_dir = DMA_DIR_TO_DEV; this->xfer_dir = DMA_DIR_TO_DEV;
int got_bytes = this->dev_obj->xfer_to(this, this->queue_data, this->queue_len); if (!this->dev_obj->xfer_to(this->queue_data, this->queue_len)) {
this->queue_data += got_bytes; this->queue_len = 0;
this->res_count -= got_bytes;
this->queue_len -= got_bytes;
if (!this->queue_len) {
this->finish_cmd(); this->finish_cmd();
} }
this->interpret_until_blocked(); this->interpret_cmd();
}
void DMAChannel::xfer_retry() {
if (this->xfer_dir == DMA_DIR_UNDEF)
return;
if (this->xfer_dir == DMA_DIR_FROM_DEV)
this->xfer_from_device();
else
this->xfer_to_device();
}
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;
} }
DmaPullResult DMAChannel::pull_data(uint32_t req_len, uint32_t *avail_len, uint8_t **p_data) DmaPullResult DMAChannel::pull_data(uint32_t req_len, uint32_t *avail_len, uint8_t **p_data)
{ {
*avail_len = 0; *avail_len = 0;
if (!this->is_active()) { if (this->ch_stat & CH_STAT_DEAD || !(this->ch_stat & CH_STAT_ACTIVE)) {
// dead or idle channel? -> no more data // dead or idle channel? -> no more data
LOG_F(WARNING, "%s: Dead/idle channel -> no more data", this->get_name().c_str()); LOG_F(WARNING, "%s: Dead/idle channel -> no more data", this->get_name().c_str());
return DmaPullResult::NoMoreData; return DmaPullResult::NoMoreData;
} }
// interpret DBDMA program until we get data or become idle // interpret DBDMA program until we get data or become idle
this->interpret_until_blocked(); while ((this->ch_stat & CH_STAT_ACTIVE) && !this->queue_len) {
this->interpret_cmd();
}
// dequeue data if any // dequeue data if any
if (this->queue_len) { if (this->queue_len) {
@@ -530,14 +471,14 @@ DmaPullResult DMAChannel::pull_data(uint32_t req_len, uint32_t *avail_len, uint8
*p_data = this->queue_data; *p_data = this->queue_data;
*avail_len = req_len; *avail_len = req_len;
this->queue_len -= req_len; this->queue_len -= req_len;
this->res_count -= req_len; this->res_count += req_len;
this->queue_data += req_len; this->queue_data += req_len;
} else { // return less data than req_len } else { // return less data than req_len
LOG_F(9, "%s: Return queue_len = %d data", this->get_name().c_str(), LOG_F(9, "%s: Return queue_len = %d data", this->get_name().c_str(),
this->queue_len); this->queue_len);
*p_data = this->queue_data; *p_data = this->queue_data;
*avail_len = this->queue_len; *avail_len = this->queue_len;
this->res_count -= this->queue_len; this->res_count += this->queue_len;
this->queue_len = 0; this->queue_len = 0;
} }
return DmaPullResult::MoreData; // tell the caller there is more data return DmaPullResult::MoreData; // tell the caller there is more data
@@ -546,42 +487,80 @@ DmaPullResult DMAChannel::pull_data(uint32_t req_len, uint32_t *avail_len, uint8
return DmaPullResult::NoMoreData; // tell the caller there is no more data return DmaPullResult::NoMoreData; // tell the caller there is no more data
} }
DmaPushResult DMAChannel::push_data(const char* src_ptr, int len) { int DMAChannel::push_data(const char* src_ptr, int len) {
if (!this->is_active()) { 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", LOG_F(WARNING, "%s: attempt to push data to dead/idle channel",
this->get_name().c_str()); this->get_name().c_str());
return DmaPushResult::NoData; return -1;
} }
// interpret DBDMA program until we get buffer to fill in or become idle // interpret DBDMA program until we get buffer to fill in or become idle
this->interpret_until_blocked(); while ((this->ch_stat & CH_STAT_ACTIVE) && !this->queue_len) {
this->interpret_cmd();
}
if (this->queue_len) { if (this->queue_len) {
len = std::min((int)this->queue_len, len); len = std::min((int)this->queue_len, len);
std::memcpy(this->queue_data, src_ptr, len); std::memcpy(this->queue_data, src_ptr, len);
this->queue_data += len; this->queue_data += len;
this->res_count -= len; this->res_count += len;
this->queue_len -= len; this->queue_len -= len;
} }
// proceed with the DBDMA program if the buffer became exhausted // proceed with the DBDMA program if the buffer became exhausted
if (!this->queue_len) { if (!this->queue_len) {
this->interpret_until_blocked(); this->interpret_cmd();
} }
return DmaPushResult::PushedData; return 0;
}
void DMAChannel::end_pull_data() {
if (this->ch_stat & CH_STAT_DEAD || !(this->ch_stat & CH_STAT_ACTIVE)) {
// dead or idle channel? -> no more data
LOG_F(WARNING, "%s: Ending Dead/idle channel -> no more data",
this->get_name().c_str());
return;
}
if (this->queue_len) {
this->queue_len = 0;
} else {
this->ch_stat &= ~CH_STAT_FLUSH;
}
// proceed with the DBDMA program
this->interpret_cmd();
}
void DMAChannel::end_push_data() {
if (this->ch_stat & CH_STAT_DEAD || !(this->ch_stat & CH_STAT_ACTIVE)) {
LOG_F(WARNING, "%s: Attempt to end push data to dead/idle channel",
this->get_name().c_str());
return;
}
if (this->queue_len) {
this->queue_len = 0;
} else {
this->ch_stat &= ~CH_STAT_FLUSH;
}
// proceed with the DBDMA program
this->interpret_cmd();
} }
bool DMAChannel::is_out_active() { bool DMAChannel::is_out_active() {
return this->is_active(); if (this->ch_stat & CH_STAT_DEAD || !(this->ch_stat & CH_STAT_ACTIVE)) {
return false;
}
else {
return true;
}
} }
bool DMAChannel::is_in_active() { bool DMAChannel::is_in_active() {
return this->is_active(); if (this->ch_stat & CH_STAT_DEAD || !(this->ch_stat & CH_STAT_ACTIVE)) {
}
bool DMAChannel::is_active() {
if ((this->ch_stat & CH_STAT_DEAD) || !(this->ch_stat & CH_STAT_ACTIVE)) {
return false; return false;
} }
else { else {
@@ -601,13 +580,17 @@ void DMAChannel::start() {
this->cmd_in_progress = false; this->cmd_in_progress = false;
if (this->dev_obj != nullptr)
this->dev_obj->notify(this, DMA_MSG_START);
if (this->start_cb) if (this->start_cb)
this->start_cb(); this->start_cb();
this->interpret_until_blocked(); // some DBDMA programs contain commands that don't transfer data
// between a device and memory (LOAD_QUAD, STORE_QUAD, NOP and STOP).
// We thus interprete the DBDMA program until a data transfer between
// a device and memory is queued or the channel becomes idle/dead.
while (!this->cmd_in_progress && !(this->ch_stat & CH_STAT_DEAD) &&
(this->ch_stat & CH_STAT_ACTIVE)) {
this->interpret_cmd();
}
} }
void DMAChannel::resume() { void DMAChannel::resume() {
@@ -619,22 +602,24 @@ void DMAChannel::resume() {
LOG_F(INFO, "%s: Resuming DMA channel", this->get_name().c_str()); LOG_F(INFO, "%s: Resuming DMA channel", this->get_name().c_str());
this->interpret_until_blocked(); // some DBDMA programs contain commands that don't transfer data
// between a device and memory (LOAD_QUAD, STORE_QUAD, NOP and STOP).
// We thus interprete the DBDMA program until a data transfer between
// a device and memory is queued or the channel becomes idle/dead.
while (!this->cmd_in_progress && !(this->ch_stat & CH_STAT_DEAD) &&
(this->ch_stat & CH_STAT_ACTIVE)) {
this->interpret_cmd();
}
} }
void DMAChannel::abort() { void DMAChannel::abort() {
LOG_F(9, "%s: Aborting DMA channel", this->get_name().c_str()); 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) if (this->stop_cb)
this->stop_cb(); this->stop_cb();
} }
void DMAChannel::pause() { void DMAChannel::pause() {
LOG_F(INFO, "%s: Pausing DMA channel", this->get_name().c_str()); 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) if (this->stop_cb)
this->stop_cb(); this->stop_cb();
this->is_paused = true;
} }
+23 -34
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -29,7 +29,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef DB_DMA_H #ifndef DB_DMA_H
#define DB_DMA_H #define DB_DMA_H
#include <core/timermanager.h>
#include <devices/common/dmacore.h> #include <devices/common/dmacore.h>
#include <cinttypes> #include <cinttypes>
@@ -100,7 +99,7 @@ namespace DBDMA_Cmd {
NOP = 6, NOP = 6,
STOP = 7 STOP = 7
}; };
} };
typedef std::function<void(void)> DbdmaCallback; typedef std::function<void(void)> DbdmaCallback;
@@ -110,38 +109,31 @@ public:
~DMAChannel() = default; ~DMAChannel() = default;
void set_callbacks(DbdmaCallback start_cb, DbdmaCallback stop_cb); void set_callbacks(DbdmaCallback start_cb, DbdmaCallback stop_cb);
void set_data_callbacks(DbdmaCallback in_cb, DbdmaCallback out_cb, DbdmaCallback flush_cb);
uint32_t reg_read(uint32_t offset, int size); uint32_t reg_read(uint32_t offset, int size);
void reg_write(uint32_t offset, uint32_t value, 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) { bool is_out_active();
this->ch_stat = (this->ch_stat & 0xff00) | new_stat; bool is_in_active();
} DmaPullResult pull_data(uint32_t req_len, uint32_t *avail_len, uint8_t **p_data);
int push_data(const char* src_ptr, int len);
int get_pull_data_remaining() { return this->queue_len; }
int get_push_data_remaining() { return this->queue_len; }
void end_pull_data();
void end_push_data();
void update_ch_stat(uint8_t mask, uint8_t new_val) { void register_dma_int(InterruptCtrl* int_ctrl_obj, uint32_t irq_id) {
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;
DmaPushResult push_data(const char* src_ptr, int len) override;
bool dma_is_ready() override;
void xfer_retry() override;
void register_dma_int(InterruptCtrl* int_ctrl_obj, uint64_t irq_id) {
this->int_ctrl = int_ctrl_obj; this->int_ctrl = int_ctrl_obj;
this->irq_id = irq_id; this->irq_id = irq_id;
} };
protected: protected:
DMACmd* fetch_cmd(uint32_t cmd_addr, DMACmd* p_cmd, bool *is_writable); DMACmd* fetch_cmd(uint32_t cmd_addr, DMACmd* p_cmd, bool *is_writable);
void interpret_cmd(void); uint8_t interpret_cmd(void);
void interpret_until_blocked();
void update_cmd();
void finish_cmd(); void finish_cmd();
void xfer_quad(bool is_store); void xfer_quad(const DMACmd *cmd_desc, DMACmd *cmd_host);
void update_irq(uint8_t cmd_bits); void update_irq();
void xfer_from_device(); void xfer_from_device();
void xfer_to_device(); void xfer_to_device();
@@ -150,11 +142,12 @@ protected:
void abort(void); void abort(void);
void pause(void); void pause(void);
bool is_active();
private: private:
std::function<void(void)> start_cb = nullptr; // DMA channel start callback std::function<void(void)> start_cb = nullptr; // DMA channel start callback
std::function<void(void)> stop_cb = nullptr; // DMA channel stop callback std::function<void(void)> stop_cb = nullptr; // DMA channel stop callback
std::function<void(void)> in_cb = nullptr; // DMA channel in callback
std::function<void(void)> out_cb = nullptr; // DMA channel out callback
std::function<void(void)> flush_cb = nullptr; // DMA channel flush callback
uint16_t ch_stat = 0; uint16_t ch_stat = 0;
uint32_t cmd_ptr = 0; uint32_t cmd_ptr = 0;
@@ -166,15 +159,11 @@ private:
uint32_t wait_select = 0; uint32_t wait_select = 0;
bool cmd_in_progress = false; bool cmd_in_progress = false;
bool is_paused = false;
uint8_t cur_cmd; 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 // Interrupt related stuff
InterruptCtrl* int_ctrl = nullptr; InterruptCtrl* int_ctrl = nullptr;
uint64_t irq_id = 0; uint32_t irq_id = 0;
TimerInfo interrupt_timer;
}; };
#endif // DB_DMA_H #endif // DB_DMA_H
+28 -55
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -33,20 +33,17 @@ enum DmaPullResult : int {
NoMoreData, // data source has no more data to be pulled 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 { class DmaOutChannel {
public: public:
DmaOutChannel(std::string name) { this->name = name; } DmaOutChannel(std::string name) { this->name = name; };
virtual bool is_out_active() { return true; } virtual bool is_out_active() { return true; };
virtual DmaPullResult pull_data(uint32_t req_len, uint32_t *avail_len, virtual DmaPullResult pull_data(uint32_t req_len, uint32_t *avail_len,
uint8_t **p_data) = 0; uint8_t **p_data) = 0;
virtual int get_pull_data_remaining() { return 1; };
virtual void end_pull_data() { };
std::string get_name(void) { return this->name; } std::string get_name(void) { return this->name; };
private: private:
std::string name; std::string name;
@@ -54,12 +51,14 @@ private:
class DmaInChannel { class DmaInChannel {
public: public:
DmaInChannel(std::string name) { this->name = name; } DmaInChannel(std::string name) { this->name = name; };
virtual bool is_in_active() { return true; } virtual bool is_in_active() { return true; };
virtual DmaPushResult push_data(const char* src_ptr, int len) = 0; virtual int push_data(const char* src_ptr, int len) = 0;
virtual int get_push_data_remaining() { return 1; };
virtual void end_push_data() { };
std::string get_name(void) { return this->name; } std::string get_name(void) { return this->name; };
private: private:
std::string name; std::string name;
@@ -69,32 +68,21 @@ private:
class DmaBidirChannel : public DmaOutChannel, public DmaInChannel { class DmaBidirChannel : public DmaOutChannel, public DmaInChannel {
public: public:
DmaBidirChannel(std::string name) : DmaOutChannel(name + " Out"), DmaBidirChannel(std::string name) : DmaOutChannel(name + " Out"),
DmaInChannel(name + std::string(" In")) { this->name = name; } DmaInChannel(name + std::string(" In")) { this->name = name; };
std::string get_name(void) { return this->name; } std::string get_name(void) { return this->name; };
private: private:
std::string name; std::string name;
}; };
// ---------------------- New DMA API ------------------------- // ---------------------- New DMA API -------------------------
/** 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 { enum DmaMsg : unsigned {
DMA_MSG_START = 1, CH_START = 1,
DMA_MSG_STOP, CH_STOP,
DMA_MSG_FLUSH, DATA_AVAIL,
DMA_MSG_DATA_AVAIL,
}; };
/** DMA transfer direction constants. */
enum XferDir : unsigned { enum XferDir : unsigned {
DMA_DIR_UNDEF = 0, DMA_DIR_UNDEF = 0,
DMA_DIR_TO_DEV, DMA_DIR_TO_DEV,
@@ -108,11 +96,10 @@ public:
DmaDevice() = default; DmaDevice() = default;
~DmaDevice() = default; ~DmaDevice() = default;
virtual void connect(DmaChannel *ch_obj) { this->channel_obj = ch_obj; } void connect(DmaChannel *ch_obj) { this->channel_obj = ch_obj; };
virtual void notify(DmaChannel *ch_obj, DmaMsg msg) {} void notify(DmaMsg msg) {};
virtual int xfer_from(DmaChannel *ch_obj, uint8_t *buf, int len) { return len; } virtual int xfer_from(uint8_t *buf, int len) { return len; };
virtual int xfer_to(DmaChannel *ch_obj, uint8_t *buf, int len) { return len; } virtual int xfer_to(uint8_t *buf, int len) { return len; };
virtual int tell_xfer_size(DmaChannel *ch_obj) { return 0; }
protected: protected:
DmaChannel* channel_obj = nullptr; DmaChannel* channel_obj = nullptr;
@@ -120,29 +107,15 @@ protected:
class DmaChannel { class DmaChannel {
public: public:
DmaChannel(const uint32_t id = 1) { this->ch_id = id; } DmaChannel() = default;
DmaChannel(const DmaChannelType type, const uint32_t id = 1) {
this->ch_type = type;
this->ch_id = id;
}
~DmaChannel() = default; ~DmaChannel() = default;
// setters/getters void connect(DmaDevice *dev_obj) { this->dev_obj = dev_obj; };
void set_id(const uint32_t id) { this->ch_id = id; } void notify(DmaMsg msg) {};
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 dma_is_ready() { return false; }
virtual void xfer_retry() {}
protected: protected:
DmaDevice* dev_obj = nullptr; DmaDevice* dev_obj = nullptr;
uint32_t ch_id = 0; // support for several channels per device XferDir xfer_dir = DMA_DIR_UNDEF;
DmaChannelType ch_type = DMA_CH_TYPE_BIDIR;
XferDir xfer_dir = DMA_DIR_UNDEF;
}; };
/* /*
+8 -10
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -35,7 +35,6 @@ enum HWCompType : uint64_t {
MMIO_DEV = 1ULL << 4, // memory mapped I/O device MMIO_DEV = 1ULL << 4, // memory mapped I/O device
PCI_HOST = 1ULL << 5, // PCI host PCI_HOST = 1ULL << 5, // PCI host
PCI_DEV = 1ULL << 6, // PCI device PCI_DEV = 1ULL << 6, // PCI device
NUBUS_DEV = 1ULL << 7, // Nubus device
I2C_HOST = 1ULL << 8, // I2C host I2C_HOST = 1ULL << 8, // I2C host
I2C_DEV = 1ULL << 9, // I2C device I2C_DEV = 1ULL << 9, // I2C device
ADB_HOST = 1ULL << 12, // ADB host ADB_HOST = 1ULL << 12, // ADB host
@@ -54,7 +53,6 @@ enum HWCompType : uint64_t {
FLOPPY_CTRL = 1ULL << 32, // floppy disk controller FLOPPY_CTRL = 1ULL << 32, // floppy disk controller
FLOPPY_DRV = 1ULL << 33, // floppy disk drive FLOPPY_DRV = 1ULL << 33, // floppy disk drive
ETHER_MAC = 1ULL << 40, // Ethernet media access controller ETHER_MAC = 1ULL << 40, // Ethernet media access controller
MACHINE = 1ULL << 41, // machine root
}; };
/** Base class for HW components. */ /** Base class for HW components. */
@@ -65,22 +63,22 @@ public:
virtual std::string get_name(void) { virtual std::string get_name(void) {
return this->name; return this->name;
} };
virtual void set_name(std::string name) { virtual void set_name(std::string name) {
this->name = name; this->name = name;
} };
virtual bool supports_type(HWCompType type) { virtual bool supports_type(HWCompType type) {
return !!(this->supported_types & type); return !!(this->supported_types & type);
} };
virtual void supports_types(uint64_t types) { virtual void supports_types(uint64_t types) {
this->supported_types = types; this->supported_types = types;
} };
virtual int device_postinit() { virtual int device_postinit() {
return 0; return 0;
} };
protected: protected:
std::string name; std::string name;
+8 -22
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -30,11 +30,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
enum IntSrc : uint32_t { enum IntSrc : uint32_t {
INT_UNKNOWN = 0, INT_UNKNOWN = 0,
VIA_CUDA, VIA_CUDA,
VIA2,
SCSI_MESH, SCSI_MESH,
SCSI_CURIO, SCSI_CURIO,
SWIM3, SWIM3,
ESCC,
SCCA, SCCA,
SCCB, SCCB,
ETHERNET, ETHERNET,
@@ -60,7 +58,6 @@ enum IntSrc : uint32_t {
PLANB, PLANB,
VCI, VCI,
PLATINUM, PLATINUM,
DMA_ALL,
DMA_SCSI_MESH, DMA_SCSI_MESH,
DMA_SCSI_CURIO, DMA_SCSI_CURIO,
DMA_SWIM3, DMA_SWIM3,
@@ -83,17 +80,6 @@ enum IntSrc : uint32_t {
USB, USB,
PIPPIN_E, PIPPIN_E,
PIPPIN_F, PIPPIN_F,
ZIVA,
PCI_CARDBUS,
MEDIA_BAY,
SLOT_ALL,
SLOT_0,
SLOT_1,
SLOT_2,
SLOT_PDS,
SLOT_VDS,
VBL,
VALKYRIE,
}; };
/** Base class for interrupt controllers. */ /** Base class for interrupt controllers. */
@@ -103,17 +89,17 @@ public:
virtual ~InterruptCtrl() = default; virtual ~InterruptCtrl() = default;
// register interrupt sources for a device // register interrupt sources for a device
virtual uint64_t register_dev_int(IntSrc src_id) = 0; virtual uint32_t register_dev_int(IntSrc src_id) = 0;
virtual uint64_t register_dma_int(IntSrc src_id) = 0; virtual uint32_t register_dma_int(IntSrc src_id) = 0;
// acknowledge HW interrupt // acknowledge HW interrupt
virtual void ack_int(uint64_t irq_id, uint8_t irq_line_state) = 0; virtual void ack_int(uint32_t irq_id, uint8_t irq_line_state) = 0;
virtual void ack_dma_int(uint64_t irq_id, uint8_t irq_line_state) = 0; virtual void ack_dma_int(uint32_t irq_id, uint8_t irq_line_state) = 0;
}; };
typedef struct { typedef struct {
InterruptCtrl *int_ctrl_obj; InterruptCtrl *int_ctrl_obj;
uint64_t irq_id; uint32_t irq_id;
} IntDetails; } IntDetails;
#endif // HW_INTERRUPT_H #endif // HW_INTERRUPT_H
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -31,15 +31,17 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
This is helpful especially for calculating video parameters. This is helpful especially for calculating video parameters.
*/ */
#include <devices/common/clockgen/athens.h> #include <devices/common/i2c/athens.h>
#include <loguru.hpp> #include <loguru.hpp>
#include <algorithm> #include <algorithm>
#include <cinttypes> #include <cinttypes>
#include <vector> #include <vector>
AthensClocks::AthensClocks(uint8_t dev_addr) : I2CDevice() { AthensClocks::AthensClocks(uint8_t dev_addr)
{
set_name("Athens"); set_name("Athens");
supports_types(HWCompType::I2C_DEV);
this->my_addr = dev_addr; this->my_addr = dev_addr;
@@ -73,9 +75,10 @@ bool AthensClocks::send_subaddress(uint8_t sub_addr)
bool AthensClocks::send_byte(uint8_t data) bool AthensClocks::send_byte(uint8_t data)
{ {
switch (this->pos++) { switch (this->pos) {
case 0: case 0:
this->reg_num = data; this->reg_num = data;
this->pos++;
break; break;
case 1: case 1:
if (this->reg_num >= ATHENS_NUM_REGS) { if (this->reg_num >= ATHENS_NUM_REGS) {
@@ -87,7 +90,7 @@ bool AthensClocks::send_byte(uint8_t data)
break; break;
default: default:
LOG_F(WARNING, "%s: too much data received!", this->name.c_str()); LOG_F(WARNING, "%s: too much data received!", this->name.c_str());
//return false; // return NACK return false; // return NACK
} }
return true; return true;
} }
@@ -100,8 +103,6 @@ bool AthensClocks::receive_byte(uint8_t* p_data)
int AthensClocks::get_sys_freq() int AthensClocks::get_sys_freq()
{ {
LOG_F(ERROR, "%s: sys clock calculation not implemented yet", this->name.c_str());
return 0; return 0;
} }
@@ -117,7 +118,7 @@ int AthensClocks::get_dot_freq()
return 0; return 0;
} }
float out_freq = 50000000.0; // for 800x600 72Hz float out_freq = 0.0f;
int d2 = this->regs[AthensRegs::D2]; int d2 = this->regs[AthensRegs::D2];
int n2 = this->regs[AthensRegs::N2]; int n2 = this->regs[AthensRegs::N2];
@@ -149,7 +150,7 @@ int AthensClocks::get_dot_freq()
break; break;
} }
LOG_F(INFO, "%s: dot clock frequency set to %f MHz", this->name.c_str(), out_freq / 1000000.0); LOG_F(INFO, "%s: dot clock frequency set to %f Hz", this->name.c_str(), out_freq);
return static_cast<int>(out_freq + 0.5f); return static_cast<int>(out_freq + 0.5f);
} }
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -24,11 +24,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef ATHENS_H #ifndef ATHENS_H
#define ATHENS_H #define ATHENS_H
#include <devices/common/hwcomponent.h>
#include <devices/common/i2c/i2c.h> #include <devices/common/i2c/i2c.h>
#include <cinttypes> #include <cinttypes>
constexpr auto ATHENS_NUM_REGS = 8; #define ATHENS_NUM_REGS 8
/** Default external crystal oscillator frequency. */ /** Default external crystal oscillator frequency. */
constexpr auto ATHENS_XTAL = 31334400.0f; constexpr auto ATHENS_XTAL = 31334400.0f;
@@ -46,9 +47,10 @@ enum AthensRegs: uint8_t {
P1 = 7 P1 = 7
}; };
} // namespace AthensRegs }; // namespace AthensRegs
class AthensClocks : public I2CDevice { class AthensClocks : public I2CDevice, public HWComponent
{
public: public:
AthensClocks(uint8_t dev_addr); AthensClocks(uint8_t dev_addr);
AthensClocks(uint8_t dev_addr, const float crystal_freq); AthensClocks(uint8_t dev_addr, const float crystal_freq);
+14 -22
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-21 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -27,22 +27,14 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef I2C_H #ifndef I2C_H
#define I2C_H #define I2C_H
#include <devices/common/hwcomponent.h> #include <stdexcept>
#include <cstring>
#include <string>
#include <loguru.hpp> #include <loguru.hpp>
#include <cinttypes>
#include <cstring>
#include <stdexcept>
#include <string>
/** Base class for I2C devices */ /** Base class for I2C devices */
class I2CDevice : virtual public HWComponent { class I2CDevice {
public: public:
I2CDevice() {
supports_types(HWCompType::I2C_DEV);
}
virtual ~I2CDevice() = default;
virtual void start_transaction() = 0; virtual void start_transaction() = 0;
virtual bool send_subaddress(uint8_t sub_addr) = 0; virtual bool send_subaddress(uint8_t sub_addr) = 0;
virtual bool send_byte(uint8_t data) = 0; virtual bool send_byte(uint8_t data) = 0;
@@ -50,11 +42,11 @@ public:
}; };
/** Base class for I2C hosts */ /** Base class for I2C hosts */
class I2CBus : virtual public HWComponent { class I2CBus {
public: public:
I2CBus() { I2CBus() {
std::memset(this->dev_list, 0, sizeof(this->dev_list)); std::memset(this->dev_list, 0, sizeof(this->dev_list));
} };
virtual ~I2CBus() = default; virtual ~I2CBus() = default;
virtual void register_device(uint8_t dev_addr, I2CDevice* dev_obj) { virtual void register_device(uint8_t dev_addr, I2CDevice* dev_obj) {
@@ -63,7 +55,7 @@ public:
} }
this->dev_list[dev_addr] = dev_obj; this->dev_list[dev_addr] = dev_obj;
LOG_F(INFO, "New I2C device, address = 0x%X", dev_addr); LOG_F(INFO, "New I2C device, address = 0x%X", dev_addr);
} };
virtual bool start_transaction(uint8_t dev_addr) { virtual bool start_transaction(uint8_t dev_addr) {
if (this->dev_list[dev_addr]) { if (this->dev_list[dev_addr]) {
@@ -72,28 +64,28 @@ public:
} else { } else {
return false; return false;
} }
} };
virtual bool send_subaddress(uint8_t dev_addr, uint8_t sub_addr) { virtual bool send_subaddress(uint8_t dev_addr, uint8_t sub_addr) {
if (!this->dev_list[dev_addr]) { if (!this->dev_list[dev_addr]) {
return false; /* no device -> no acknowledge */ return false; /* no device -> no acknowledge */
} }
return this->dev_list[dev_addr]->send_subaddress(sub_addr); return this->dev_list[dev_addr]->send_subaddress(sub_addr);
} };
virtual bool send_byte(uint8_t dev_addr, uint8_t data) { virtual bool send_byte(uint8_t dev_addr, uint8_t data) {
if (!this->dev_list[dev_addr]) { if (!this->dev_list[dev_addr]) {
return false; /* no device -> no acknowledge */ return false; /* no device -> no acknowledge */
} }
return this->dev_list[dev_addr]->send_byte(data); return this->dev_list[dev_addr]->send_byte(data);
} };
virtual bool receive_byte(uint8_t dev_addr, uint8_t* p_data) { virtual bool receive_byte(uint8_t dev_addr, uint8_t* p_data) {
if (!this->dev_list[dev_addr]) { if (!this->dev_list[dev_addr]) {
return false; /* no device -> no acknowledge */ return false; /* no device -> no acknowledge */
} }
return this->dev_list[dev_addr]->receive_byte(p_data); return this->dev_list[dev_addr]->receive_byte(p_data);
} };
protected: protected:
I2CDevice* dev_list[128]; /* list of registered I2C devices */ I2CDevice* dev_list[128]; /* list of registered I2C devices */
+7 -7
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-22 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -54,17 +54,17 @@ void I2CProm::set_memory(int start, const uint8_t* in_data, int size)
void I2CProm::start_transaction() { void I2CProm::start_transaction() {
this->pos = 0; this->pos = 0;
} };
bool I2CProm::send_subaddress(uint8_t sub_addr) { bool I2CProm::send_subaddress(uint8_t sub_addr) {
this->pos = sub_addr; this->pos = sub_addr;
return true; return true;
} };
bool I2CProm::send_byte(uint8_t data) { bool I2CProm::send_byte(uint8_t data) {
LOG_F(9, "I2CRom: 0x%X received", data); LOG_F(9, "I2CRom: 0x%X received", data);
return true; return true;
} };
bool I2CProm::receive_byte(uint8_t* p_data) { bool I2CProm::receive_byte(uint8_t* p_data) {
if (this->pos >= this->rom_size) { if (this->pos >= this->rom_size) {
@@ -72,4 +72,4 @@ bool I2CProm::receive_byte(uint8_t* p_data) {
} }
*p_data = this->data[this->pos++]; *p_data = this->data[this->pos++];
return true; return true;
} };
+6 -4
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-22 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -24,12 +24,14 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef I2C_PROM_H #ifndef I2C_PROM_H
#define I2C_PROM_H #define I2C_PROM_H
#include <devices/common/hwcomponent.h>
#include <devices/common/i2c/i2c.h> #include <devices/common/i2c/i2c.h>
#include <cinttypes> #include <cinttypes>
#include <memory> #include <memory>
class I2CProm : public I2CDevice { class I2CProm : public I2CDevice, public HWComponent
{
public: public:
I2CProm(uint8_t dev_addr, int size); I2CProm(uint8_t dev_addr, int size);
~I2CProm() = default; ~I2CProm() = default;
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -21,10 +21,13 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file SAA7187 Digital video encoder emulation. */ /** @file SAA7187 Digital video encoder emulation. */
#include <devices/video/saa7187.h> #include <devices/common/i2c/saa7187.h>
#include <loguru.hpp> #include <loguru.hpp>
Saa7187VideoEncoder::Saa7187VideoEncoder(uint8_t dev_addr) : I2CDevice() { Saa7187VideoEncoder::Saa7187VideoEncoder(uint8_t dev_addr)
{
supports_types(HWCompType::I2C_DEV);
this->my_addr = dev_addr; this->my_addr = dev_addr;
} }
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -24,6 +24,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef SAA7187_H #ifndef SAA7187_H
#define SAA7187_H #define SAA7187_H
#include <devices/common/hwcomponent.h>
#include <devices/common/i2c/i2c.h> #include <devices/common/i2c/i2c.h>
namespace Saa7187Regs { namespace Saa7187Regs {
@@ -115,9 +116,10 @@ enum Saa7187Regs : uint8_t { // i2c address is 0x44; fatman is at 0x46?
last_reg = 0x7e, last_reg = 0x7e,
}; };
} // namespace Saa7187Regs }; // namespace Saa7187Regs
class Saa7187VideoEncoder : public I2CDevice { class Saa7187VideoEncoder : public I2CDevice, public HWComponent
{
public: public:
Saa7187VideoEncoder(uint8_t dev_addr); Saa7187VideoEncoder(uint8_t dev_addr);
~Saa7187VideoEncoder() = default; ~Saa7187VideoEncoder() = default;
+15 -15
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -40,10 +40,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
/** /**
Machine ID register for NuBus Power Macs. Machine ID register for Nubus Power Macs.
It's located at physical address 0x5FFFFFFC and contains four bytes: It's located at physical address 0x5FFFFFFC and contains four bytes:
+0 uint16_t signature = 0xA55A +0 uint16_t signature = 0xA55A
+1 uint8_t machine_type (0x30 - Power Mac) +1 uint8_t machine_type (3 - Power Mac)
+2 uint8_t model (0x10 = PDM, 0x12 = Carl Sagan, 0x13 = Cold Fusion) +2 uint8_t model (0x10 = PDM, 0x12 = Carl Sagan, 0x13 = Cold Fusion)
*/ */
class NubusMacID : public MMIODevice { class NubusMacID : public MMIODevice {
@@ -55,7 +55,7 @@ public:
this->id[2] = (id >> 8) & 0xFF; this->id[2] = (id >> 8) & 0xFF;
this->id[3] = id & 0xFF; this->id[3] = id & 0xFF;
supports_types(HWCompType::MMIO_DEV); supports_types(HWCompType::MMIO_DEV);
} };
~NubusMacID() = default; ~NubusMacID() = default;
uint32_t read(uint32_t rgn_start, uint32_t offset, int size) { uint32_t read(uint32_t rgn_start, uint32_t offset, int size) {
@@ -67,10 +67,10 @@ public:
} }
ABORT_F("NubusMacID: invalid read size %d, offset %d!", size, offset); ABORT_F("NubusMacID: invalid read size %d, offset %d!", size, offset);
return 0; return 0;
} };
/* not writable */ /* not writable */
void write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size) {} void write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size) {};
private: private:
uint8_t id[4]; uint8_t id[4];
@@ -88,19 +88,19 @@ public:
this->set_name(name); this->set_name(name);
supports_types(HWCompType::IOBUS_DEV); supports_types(HWCompType::IOBUS_DEV);
this->data = data; this->data = data;
} };
~BoardRegister() = default; ~BoardRegister() = default;
uint16_t iodev_read(uint32_t address) { uint16_t iodev_read(uint32_t address) {
return this->data; return this->data;
} };
// appears read-only to guest // appears read-only to guest
void iodev_write(uint32_t address, uint16_t value) {} void iodev_write(uint32_t address, uint16_t value) {};
void update_bits(const uint16_t val, const uint16_t mask) { void update_bits(const uint16_t val, const uint16_t mask) {
this->data = (this->data & ~mask) | (val & mask); this->data = (this->data & ~mask) | (val & mask);
} };
private: private:
uint16_t data; uint16_t data;
@@ -118,15 +118,15 @@ public:
this->id = id; this->id = id;
this->name = "Machine-id"; this->name = "Machine-id";
supports_types(HWCompType::MMIO_DEV); supports_types(HWCompType::MMIO_DEV);
} };
~GossamerID() = default; ~GossamerID() = default;
uint32_t read(uint32_t rgn_start, uint32_t offset, int size) { uint32_t read(uint32_t rgn_start, uint32_t offset, int size) {
return ((offset == 4 && size == 2) ? this->id : 0); return ((offset == 4 && size == 2) ? this->id : 0);
} };
/* not writable */ /* not writable */
void write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size) {} void write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size) {};
private: private:
uint16_t id; uint16_t id;
+3 -3
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-21 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
-156
View File
@@ -1,156 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team
(See CREDITS.MD for more details)
(You may also contact divingkxt or powermax2286 on Discord)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#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 <cinttypes>
#include <fstream>
#include <sstream>
uint32_t calculate_rom_crc(uint8_t *data_ptr, int length)
{
uint32_t sum = 0;
for (int i = 0; i < length; i++) {
// rotate sum left by one bit
if (sum & 0x80000000UL)
sum = (sum << 1) | 1;
else
sum = (sum << 1) | 0;
sum += data_ptr[i];
}
return sum;
}
int load_declaration_rom(const std::string rom_path, int slot_num)
{
std::ifstream rom_file;
int result = 0;
try {
rom_file.open(rom_path, std::ios::in | std::ios::binary);
if (rom_file.fail())
throw std::runtime_error("could not open declaration ROM image " + rom_path);
// determine image size
rom_file.seekg(0, std::ios::end);
uint64_t rom_size = rom_file.tellg();
if (rom_size > 16 * 1024 * 1024)
throw std::runtime_error("declaration ROM image " + rom_path + " size " +
std::to_string(rom_size) + " is too large");
// load it
auto rom_data = std::unique_ptr<uint8_t[]> (new uint8_t[rom_size]);
rom_file.seekg(0, std::ios::beg);
rom_file.read((char *)rom_data.get(), rom_size);
// verify image data
uint8_t byte_lane = rom_data[rom_size - 1];
if ((byte_lane & 0xF) != ((byte_lane >> 4) ^ 0xF))
throw std::runtime_error("declaration ROM image " + rom_path +
" has invalid byte lane value");
if (READ_DWORD_BE_A(&rom_data[rom_size - 6]) != 0x5A932BC7UL)
throw std::runtime_error("declaration ROM image " + rom_path +
" has invalid test pattern");
if (rom_data[rom_size - 7] != 1)
throw std::runtime_error("declaration ROM image " + rom_path +
" has unsupported format");
uint32_t crc = READ_DWORD_BE_A(&rom_data[rom_size - 12]);
int hdr_length = READ_DWORD_BE_A(&rom_data[rom_size - 16]);
// patch the CRC field of the format header to 0
WRITE_DWORD_BE_A(&rom_data[rom_size - 12], 0);
uint32_t test_crc = calculate_rom_crc(rom_data.get(), hdr_length);
// restore the CRC field value
WRITE_DWORD_BE_A(&rom_data[rom_size - 12], crc);
if (test_crc != crc) {
std::stringstream err;
err << "declaration ROM image " + rom_path + " has invalid CRC, expected = 0x"
<< std::hex << crc << ", got = 0x" << std::hex << test_crc;
throw std::runtime_error(err.str());
}
int lanes_used = 0;
// count meaningful lanes in a data quad
for (int i = 0; i < 4; i++) {
if (byte_lane & (1 << i))
lanes_used++;
}
// padded_len is the size in bytes of all pages needed to contain all the bytes of the ROM
uint32_t padded_len =
uint32_t(((rom_size * 4 + lanes_used - 1) / lanes_used + 4095) / 4096 * 4096);
if (padded_len > 16 * 1024 * 1024)
throw std::runtime_error("declaration ROM image " + rom_path + " size " +
std::to_string(rom_size) + " is too large");
// calculate starting physical address of the ROM
uint32_t rom_phys_start = (0xF0FFFFFFUL | ((slot_num & 0xF) << 24)) - padded_len + 1;
auto mem_crtl = dynamic_cast<MemCtrlBase*>(gMachineObj->get_comp_by_type(HWCompType::MEM_CTRL));
if (!mem_crtl->add_rom_region(rom_phys_start, padded_len))
throw std::runtime_error("could not allocate ROM space for declaration ROM image " +
rom_path);
int data_pos = int(rom_size) - 1;
auto new_data = std::unique_ptr<uint8_t[]> (new uint8_t[padded_len]);
// prepare new ROM data by copying over used lanes
// and padding unused lanes with 0xFF
// NOTE: speed uncritical - don't optimize!
for (int i = padded_len - 1; i >= 0; ) {
for (int b = 8; i>= 0 && b != 0; b >>= 1) {
if (data_pos >= 0 && (byte_lane & b))
new_data[i--] = rom_data[data_pos--];
else
new_data[i--] = 0xFF;
}
}
// move padded ROM data to the memory region
mem_crtl->set_data(rom_phys_start, new_data.get(), padded_len);
}
catch (const std::exception& exc) {
LOG_F(ERROR, "load_declaration_rom failed: %s", exc.what());
result = -1;
}
rom_file.close();
return result;
}
-30
View File
@@ -1,30 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team
(See CREDITS.MD for more details)
(You may also contact divingkxt or powermax2286 on Discord)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef NUBUS_UTILS_H
#define NUBUS_UTILS_H
#include <cinttypes>
#include <string>
int load_declaration_rom(const std::string rom_path, int slot_num);
#endif // NUBUS_UTILS_H
+4 -8
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -22,7 +22,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cpu/ppc/ppcemu.h> #include <cpu/ppc/ppcemu.h>
#include <devices/common/hwcomponent.h> #include <devices/common/hwcomponent.h>
#include <devices/common/nvram.h> #include <devices/common/nvram.h>
#include <devices/common/ofnvram.h>
#include <devices/deviceregistry.h> #include <devices/deviceregistry.h>
#include <cinttypes> #include <cinttypes>
@@ -47,9 +46,6 @@ NVram::NVram(std::string file_name, uint32_t ram_size)
this->file_name = file_name; this->file_name = file_name;
this->ram_size = ram_size; this->ram_size = ram_size;
if (ram_size == 8192)
this->of_nvram_offset = OF_NVRAM_OFFSET;
// allocate memory storage and fill it with zeroes // allocate memory storage and fill it with zeroes
this->storage = std::unique_ptr<uint8_t[]>(new uint8_t[ram_size] ()); this->storage = std::unique_ptr<uint8_t[]>(new uint8_t[ram_size] ());
@@ -103,7 +99,7 @@ void NVram::save() {
} }
static const DeviceDescription Nvram_Descriptor = { static const DeviceDescription Nvram_Descriptor = {
NVram::create, {}, {}, HWCompType::NVRAM NVram::create, {}, {}
}; };
REGISTER_DEVICE(NVRAM, Nvram_Descriptor); REGISTER_DEVICE(NVRAM, Nvram_Descriptor);
+3 -5
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -45,13 +45,11 @@ public:
uint8_t read_byte(uint32_t offset); uint8_t read_byte(uint32_t offset);
void write_byte(uint32_t offset, uint8_t value); void write_byte(uint32_t offset, uint8_t value);
uint32_t get_of_nvram_offset() { return of_nvram_offset; }
private: private:
std::string file_name; // file name for the backing file std::string file_name; // file name for the backing file
uint16_t ram_size; // NVRAM size uint16_t ram_size; // NVRAM size
std::unique_ptr<uint8_t[]> storage; std::unique_ptr<uint8_t[]> storage;
uint32_t of_nvram_offset = 0;
void init(); void init();
void save(); void save();
+33 -33
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -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. */ /** 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/ofnvram.h>
#include <devices/common/nvram.h> #include <devices/common/nvram.h>
#include <endianswap.h>
#include <machines/machinebase.h> #include <machines/machinebase.h>
#include <memaccess.h>
#include <cinttypes> #include <cinttypes>
#include <cstring> #include <cstring>
@@ -41,7 +41,7 @@ using namespace std;
static std::string hex2str(uint32_t n) static std::string hex2str(uint32_t n)
{ {
std::stringstream ss; std::stringstream ss;
ss << setw(8) << right << setfill('0') << hex << n; ss << setw(8) << setfill('0') << hex << n;
return ss.str(); return ss.str();
} }
@@ -67,7 +67,7 @@ bool OfConfigAppl::validate() {
// read OF partition header // read OF partition header
for (i = 0; i < sizeof(OfConfigHdrAppl); i++) { for (i = 0; i < sizeof(OfConfigHdrAppl); i++) {
((uint8_t*)&hdr)[i] = this->nvram_obj->read_byte(this->nvram_obj->get_of_nvram_offset() + i); ((uint8_t*)&hdr)[i] = this->nvram_obj->read_byte(OF_NVRAM_OFFSET + i);
} }
// validate partition signature and version // validate partition signature and version
@@ -81,11 +81,11 @@ bool OfConfigAppl::validate() {
// read the entire partition into the local buffer // read the entire partition into the local buffer
for (i = 0; i < this->size; i++) { for (i = 0; i < this->size; i++) {
this->buf[i] = this->nvram_obj->read_byte(this->nvram_obj->get_of_nvram_offset() + i); this->buf[i] = this->nvram_obj->read_byte(OF_NVRAM_OFFSET + i);
} }
// verify partition checksum // verify partition checksum
if (this->checksum_partition() != 0xFFFFU) if (this->checksum_partition() ^ 0xFFFFU)
return false; return false;
return true; return true;
@@ -101,7 +101,7 @@ uint16_t OfConfigAppl::checksum_partition() {
return acc + (acc >> 16); return acc + (acc >> 16);
} }
static const string flag_names[] = { static const string flag_names[8] = {
"little-endian?", "little-endian?",
"real-mode?", "real-mode?",
"auto-boot?", "auto-boot?",
@@ -109,10 +109,8 @@ static const string flag_names[] = {
"fcode-debug?", "fcode-debug?",
"oem-banner?", "oem-banner?",
"oem-logo?", "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 = { static const map<string, std::tuple<int, uint16_t>> of_vars = {
// name, type, offset // name, type, offset
@@ -143,12 +141,12 @@ const OfConfigImpl::config_dict& OfConfigAppl::get_config_vars() {
if (!this->validate()) if (!this->validate())
return _config_vars; return _config_vars;
uint32_t of_flags = READ_DWORD_BE_A(&this->buf[12]); uint8_t of_flags = this->buf[12];
// populate flags // populate flags
for (unsigned i = 0; i < num_flags; i++) { for (int i = 0; i < 8; i++) {
_config_vars.push_back(std::make_pair(flag_names[i], _config_vars.push_back(std::make_pair(flag_names[i],
(int32_t(of_flags << i) < 0) ? "true" : "false")); ((of_flags << i) & 0x80) ? "true" : "false"));
} }
// populate the remaining variables // populate the remaining variables
@@ -163,7 +161,7 @@ const OfConfigImpl::config_dict& OfConfigAppl::get_config_vars() {
hex2str(READ_DWORD_BE_A(&this->buf[offset])))); hex2str(READ_DWORD_BE_A(&this->buf[offset]))));
break; break;
case OF_VAR_TYPE_STR: case OF_VAR_TYPE_STR:
uint16_t str_offset = READ_WORD_BE_A(&this->buf[offset]) - this->nvram_obj->get_of_nvram_offset(); uint16_t str_offset = READ_WORD_BE_A(&this->buf[offset]) - OF_NVRAM_OFFSET;
uint16_t str_len = READ_WORD_BE_A(&this->buf[offset+2]); uint16_t str_len = READ_WORD_BE_A(&this->buf[offset+2]);
if ((str_offset + str_len) > OF_CFG_SIZE) { if ((str_offset + str_len) > OF_CFG_SIZE) {
@@ -189,14 +187,14 @@ void OfConfigAppl::update_partition() {
// calculate new checksum // calculate new checksum
uint16_t checksum = this->checksum_partition(); uint16_t checksum = this->checksum_partition();
checksum = ~checksum; checksum = checksum ? ~checksum : 0xFFFFU;
// stuff checksum into the header // stuff checksum into the header
WRITE_WORD_BE_A(&this->buf[4], checksum); WRITE_WORD_BE_A(&this->buf[4], checksum);
// write the entire partition back to NVRAM // write the entire partition back to NVRAM
for (int i = 0; i < this->size; i++) { for (int i = 0; i < this->size; i++) {
this->nvram_obj->write_byte(this->nvram_obj->get_of_nvram_offset() + i, this->buf[i]); this->nvram_obj->write_byte(OF_NVRAM_OFFSET + i, this->buf[i]);
} }
} }
@@ -207,7 +205,7 @@ bool OfConfigAppl::set_var(std::string& var_name, std::string& value) {
return false; return false;
// check if the user tries to change a flag // check if the user tries to change a flag
for (i = 0; i < num_flags; i++) { for (i = 0; i < 8; i++) {
if (var_name == flag_names[i]) { if (var_name == flag_names[i]) {
if (value == "true") if (value == "true")
flag = 1; flag = 1;
@@ -217,15 +215,15 @@ bool OfConfigAppl::set_var(std::string& var_name, std::string& value) {
cout << "Invalid property value: " << value << endl; cout << "Invalid property value: " << value << endl;
return false; return false;
} }
uint32_t flag_bit = 0x80000000U >> i; uint8_t flag_bit = 0x80U >> i;
uint32_t of_flags = READ_DWORD_BE_A(&this->buf[12]); uint8_t of_flags = this->buf[12];
if (flag) if (flag)
of_flags |= flag_bit; of_flags |= flag_bit;
else else
of_flags &= ~flag_bit; of_flags &= ~flag_bit;
WRITE_DWORD_BE_A(&this->buf[12], of_flags); this->buf[12] = of_flags;
this->update_partition(); this->update_partition();
return true; return true;
} }
@@ -250,6 +248,7 @@ bool OfConfigAppl::set_var(std::string& var_name, std::string& value) {
} }
WRITE_DWORD_BE_A(&this->buf[offset], num); WRITE_DWORD_BE_A(&this->buf[offset], num);
this->update_partition(); this->update_partition();
cout << " ok" << endl; // mimic Forth
} else { } else {
uint16_t str_offset = READ_WORD_BE_A(&this->buf[offset]); uint16_t str_offset = READ_WORD_BE_A(&this->buf[offset]);
uint16_t str_len = READ_WORD_BE_A(&this->buf[offset+2]); uint16_t str_len = READ_WORD_BE_A(&this->buf[offset+2]);
@@ -267,8 +266,8 @@ bool OfConfigAppl::set_var(std::string& var_name, std::string& value) {
} }
// remove the old string // remove the old string
std::memmove(&this->buf[top + str_len - this->nvram_obj->get_of_nvram_offset()], std::memmove(&this->buf[top + str_len - OF_NVRAM_OFFSET],
&this->buf[top - this->nvram_obj->get_of_nvram_offset()], str_offset - top); &this->buf[top - OF_NVRAM_OFFSET], str_offset - top);
for (auto& var : of_vars) { for (auto& var : of_vars) {
auto type = std::get<0>(var.second); auto type = std::get<0>(var.second);
@@ -285,7 +284,7 @@ bool OfConfigAppl::set_var(std::string& var_name, std::string& value) {
// copy new string into NVRAM buffer char by char // copy new string into NVRAM buffer char by char
i = 0; i = 0;
for(char& ch : value) { for(char& ch : value) {
this->buf[top + i - this->nvram_obj->get_of_nvram_offset()] = ch == '\x0A' ? '\x0D' : ch; this->buf[top + i - OF_NVRAM_OFFSET] = ch == '\x0A' ? '\x0D' : ch;
i++; i++;
} }
@@ -323,9 +322,6 @@ bool OfConfigChrp::validate()
bool wip = true; bool wip = true;
bool of_part_found = false; bool of_part_found = false;
if (this->nvram_obj == nullptr)
return false;
// search the entire 8KB NVRAM for CHRP OF config partition. // search the entire 8KB NVRAM for CHRP OF config partition.
// Bail out if an unknown partition or free space is encountered. // Bail out if an unknown partition or free space is encountered.
// Skip over known partitions. // Skip over known partitions.
@@ -592,16 +588,20 @@ void OfConfigUtils::printenv() {
ReplaceAll(val, "\r\n", "\n"); ReplaceAll(val, "\r\n", "\n");
ReplaceAll(val, "\r", "\n"); ReplaceAll(val, "\r", "\n");
ReplaceAll(val, "\n", "\n "); // 34 spaces ReplaceAll(val, "\n", "\n "); // 34 spaces
cout << setw(34) << left << var.first << val << right << endl; // name column has width 34 cout << setw(34) << left << var.first << val << endl; // name column has width 34
} }
} }
bool OfConfigUtils::setenv(string var_name, string value) void OfConfigUtils::setenv(string var_name, string value)
{ {
if (!this->open_container()) if (!this->open_container())
return false; return;
OfConfigImpl::config_dict vars = this->cfg_impl->get_config_vars(); OfConfigImpl::config_dict vars = this->cfg_impl->get_config_vars();
return this->cfg_impl->set_var(var_name, value); if (!this->cfg_impl->set_var(var_name, value)) {
cout << " Please try again" << endl;
} else {
cout << " ok" << endl; // mimic Forth
}
} }
+9 -9
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -33,9 +33,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
class NVram; class NVram;
/** ========== Apple Open Firmware 1.x/2.x partition definitions. ========== */ /** ========== Apple Open Firmware 1.x/2.x partition definitions. ========== */
constexpr auto OF_NVRAM_OFFSET = 0x1800; #define OF_NVRAM_OFFSET 0x1800
constexpr auto OF_NVRAM_SIG = 0x1275; #define OF_NVRAM_SIG 0x1275
constexpr auto OF_CFG_SIZE = 0x800; #define OF_CFG_SIZE 0x800
// OF Variable types // OF Variable types
enum { enum {
@@ -87,7 +87,7 @@ public:
// Old World implementation // Old World implementation
class OfConfigAppl : public OfConfigImpl { class OfConfigAppl : public OfConfigImpl {
public: public:
OfConfigAppl(NVram* nvram_obj) { this->nvram_obj = nvram_obj; } OfConfigAppl(NVram* nvram_obj) { this->nvram_obj = nvram_obj; };
~OfConfigAppl() = default; ~OfConfigAppl() = default;
bool validate(); bool validate();
@@ -108,7 +108,7 @@ private:
// New World implementation // New World implementation
class OfConfigChrp : public OfConfigImpl { class OfConfigChrp : public OfConfigImpl {
public: public:
OfConfigChrp(NVram* nvram_obj) { this->nvram_obj = nvram_obj; } OfConfigChrp(NVram* nvram_obj) { this->nvram_obj = nvram_obj; };
~OfConfigChrp() = default; ~OfConfigChrp() = default;
bool validate(); bool validate();
@@ -134,7 +134,7 @@ public:
int init(); int init();
void printenv(); void printenv();
bool setenv(std::string var_name, std::string value); void setenv(std::string var_name, std::string value);
protected: protected:
bool open_container(); bool open_container();
+9 -13
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -21,10 +21,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** Bandit/Chaos ARBus-to-PCI Bridge emulation. */ /** Bandit/Chaos ARBus-to-PCI Bridge emulation. */
#include <core/endianswap.h>
#include <devices/common/pci/bandit.h> #include <devices/common/pci/bandit.h>
#include <devices/deviceregistry.h> #include <devices/deviceregistry.h>
#include <devices/memctrl/memctrlbase.h> #include <devices/memctrl/memctrlbase.h>
#include <endianswap.h>
#include <loguru.hpp> #include <loguru.hpp>
#include <machines/machinebase.h> #include <machines/machinebase.h>
@@ -389,28 +389,24 @@ static const PropMap PsxPci1_Properties = {
new StrProperty("")}, new StrProperty("")},
}; };
static const std::vector<std::string> Chaos_Subdevices = {
"ControlVideo"
};
static const DeviceDescription Bandit1_Descriptor = { static const DeviceDescription Bandit1_Descriptor = {
Bandit::create_first, {}, Bandit1_Properties, HWCompType::PCI_HOST Bandit::create_first, {}, Bandit1_Properties
}; };
static const DeviceDescription Bandit2_Descriptor = { static const DeviceDescription Bandit2_Descriptor = {
Bandit::create_second, {}, Bandit2_Properties, HWCompType::PCI_HOST Bandit::create_second, {}, Bandit2_Properties
}; };
static const DeviceDescription PsxPci1_Descriptor = { static const DeviceDescription PsxPci1_Descriptor = {
Bandit::create_psx_first, {}, PsxPci1_Properties, HWCompType::PCI_HOST Bandit::create_psx_first, {}, PsxPci1_Properties
}; };
static const DeviceDescription Chaos_Descriptor = { static const DeviceDescription Chaos_Descriptor = {
Chaos::create, Chaos_Subdevices, Chaos_Properties, HWCompType::PCI_HOST Chaos::create, {}, Chaos_Properties
}; };
static const DeviceDescription AspenPci1_Descriptor = { static const DeviceDescription AspenPci1_Descriptor = {
AspenPci::create, {}, Bandit1_Properties, HWCompType::PCI_HOST AspenPci::create, {}, Bandit1_Properties
}; };
REGISTER_DEVICE(Bandit1, Bandit1_Descriptor); REGISTER_DEVICE(Bandit1, Bandit1_Descriptor);
+11 -11
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -46,8 +46,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <memory> #include <memory>
#include <string> #include <string>
constexpr auto BANDIT_DEV = 11; // Bandit's own device number #define BANDIT_DEV (11) // Bandit's own device number
constexpr auto BANDIT_CAR_TYPE = 1 << 0; // Bandit config address type bit #define BANDIT_CAR_TYPE (1 << 0) // Bandit config address type bit
/* Convenient macros for parsing CONFIG_ADDR fields. */ /* Convenient macros for parsing CONFIG_ADDR fields. */
#define BUS_NUM() ((this->config_addr >> 16) & 0xFFU) #define BUS_NUM() ((this->config_addr >> 16) & 0xFFU)
@@ -71,7 +71,7 @@ enum {
*/ */
class BanditHost : public PCIHost, public MMIODevice { class BanditHost : public PCIHost, public MMIODevice {
public: public:
BanditHost(int bridge_num) { this->bridge_num = bridge_num; } BanditHost(int bridge_num) { this->bridge_num = bridge_num; };
// MMIODevice methods // MMIODevice methods
uint32_t read(uint32_t rgn_start, uint32_t offset, int size) override; uint32_t read(uint32_t rgn_start, uint32_t offset, int size) override;
@@ -121,15 +121,15 @@ public:
static std::unique_ptr<HWComponent> create_first() { static std::unique_ptr<HWComponent> create_first() {
return std::unique_ptr<Bandit>(new Bandit(1, "Bandit-PCI1")); return std::unique_ptr<Bandit>(new Bandit(1, "Bandit-PCI1"));
} };
static std::unique_ptr<HWComponent> create_second() { static std::unique_ptr<HWComponent> create_second() {
return std::unique_ptr<Bandit>(new Bandit(2, "Bandit-PCI2")); return std::unique_ptr<Bandit>(new Bandit(2, "Bandit-PCI2"));
} };
static std::unique_ptr<HWComponent> create_psx_first() { static std::unique_ptr<HWComponent> create_psx_first() {
return std::unique_ptr<Bandit>(new Bandit(1, "PSX-PCI1", 8, 0)); return std::unique_ptr<Bandit>(new Bandit(1, "PSX-PCI1", 8, 0));
} };
private: private:
std::unique_ptr<BanditPciDevice> my_pci_device; std::unique_ptr<BanditPciDevice> my_pci_device;
@@ -146,7 +146,7 @@ public:
static std::unique_ptr<HWComponent> create() { static std::unique_ptr<HWComponent> create() {
return std::unique_ptr<Chaos>(new Chaos("VCI0")); return std::unique_ptr<Chaos>(new Chaos("VCI0"));
} };
}; };
/** /**
@@ -159,7 +159,7 @@ public:
static std::unique_ptr<HWComponent> create() { static std::unique_ptr<HWComponent> create() {
return std::unique_ptr<AspenPci>(new AspenPci("Aspen-PCI1")); return std::unique_ptr<AspenPci>(new AspenPci("Aspen-PCI1"));
} };
}; };
#endif // BANDIT_PCI_H #endif // BANDIT_PCI_H
+7 -24
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -28,10 +28,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cinttypes> #include <cinttypes>
enum YosemiteGpioMask: uint8_t {
GPIO_FWDET = 2, // FireWire detect
};
DecPciBridge::DecPciBridge(std::string name) : PCIBridge(name) DecPciBridge::DecPciBridge(std::string name) : PCIBridge(name)
{ {
supports_types(HWCompType::PCI_HOST | HWCompType::PCI_DEV); supports_types(HWCompType::PCI_HOST | HWCompType::PCI_DEV);
@@ -55,7 +51,7 @@ uint32_t DecPciBridge::pci_cfg_read(uint32_t reg_offs, AccessDetails &details)
case CHIP_CTRL: case CHIP_CTRL:
return (this->arb_ctrl << 16) | (this-> diag_ctrl << 8) | this->chip_ctrl; return (this->arb_ctrl << 16) | (this-> diag_ctrl << 8) | this->chip_ctrl;
case PSERR_EVENT_DIS: case PSERR_EVENT_DIS:
return (this->gpio_out_en << 16) | (this->gpio_out_data << 8) | this->pserr_event_dis; return (this->gpio_out_en << 16) | this->pserr_event_dis;
case SEC_CLK_CTRL: case SEC_CLK_CTRL:
return this->sec_clock_ctrl; return this->sec_clock_ctrl;
default: default:
@@ -79,21 +75,8 @@ void DecPciBridge::pci_cfg_write(uint32_t reg_offs, uint32_t value, AccessDetail
this->arb_ctrl = value >> 16; this->arb_ctrl = value >> 16;
break; break;
case PSERR_EVENT_DIS: case PSERR_EVENT_DIS:
this->pserr_event_dis = value & 0x7EU; this->pserr_event_dis = value & 0xFFU;
this->gpio_out_data = (value >> 8) & 0xFFU;
this->gpio_out_en = (value >> 16) & 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; break;
case SEC_CLK_CTRL: case SEC_CLK_CTRL:
this->sec_clock_ctrl = value & 0xFFFFU; this->sec_clock_ctrl = value & 0xFFFFU;
@@ -119,11 +102,11 @@ static const PropMap Dec21154Yosemite_Properties = {
}; };
static const DeviceDescription Dec21154_Descriptor = { static const DeviceDescription Dec21154_Descriptor = {
DecPciBridge::create, {}, {}, HWCompType::PCI_HOST | HWCompType::PCI_DEV DecPciBridge::create, {}, {}
}; };
static const DeviceDescription Dec21154Yosemite_Descriptor = { static const DeviceDescription Dec21154Yosemite_Descriptor = {
DecPciBridge::create_yosemite, {}, Dec21154Yosemite_Properties, HWCompType::PCI_HOST | HWCompType::PCI_DEV DecPciBridge::create_yosemite, {}, Dec21154Yosemite_Properties
}; };
REGISTER_DEVICE(Dec21154, Dec21154_Descriptor); REGISTER_DEVICE(Dec21154, Dec21154_Descriptor);
+3 -5
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -61,8 +61,6 @@ private:
uint8_t gpio_out_en = 0; uint8_t gpio_out_en = 0;
uint8_t gpio_in_data = 0; uint8_t gpio_in_data = 0;
uint16_t sec_clock_ctrl = 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 #endif // DEC_P2P_H
+9 -14
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -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/>. 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 <devices/common/pci/pcibase.h>
#include <endianswap.h>
#include <loguru.hpp> #include <loguru.hpp>
#include <memaccess.h>
#include <cinttypes> #include <cinttypes>
#include <fstream> #include <fstream>
@@ -41,10 +41,7 @@ PCIBase::PCIBase(std::string name, PCIHeaderType hdr_type, int num_bars)
this->pci_rd_lat_timer = [this]() { return this->lat_timer; }; this->pci_rd_lat_timer = [this]() { return this->lat_timer; };
this->pci_rd_cache_lnsz = [this]() { return this->cache_ln_sz; }; this->pci_rd_cache_lnsz = [this]() { return this->cache_ln_sz; };
this->pci_wr_stat = [this](uint16_t val) { this->pci_wr_stat = [](uint16_t val) {};
this->status &= ~(0b1111100100000000 & val);
};
this->pci_wr_cmd = [this](uint16_t cmd) { this->pci_wr_cmd = [this](uint16_t cmd) {
/* /*
FIXME: should register or unregister BAR mmio regions if (cmd & 2) changes. FIXME: should register or unregister BAR mmio regions if (cmd & 2) changes.
@@ -57,7 +54,7 @@ PCIBase::PCIBase(std::string name, PCIHeaderType hdr_type, int num_bars)
this->pci_wr_cache_lnsz = [this](uint8_t val) { this->cache_ln_sz = val; }; this->pci_wr_cache_lnsz = [this](uint8_t val) { this->cache_ln_sz = val; };
this->pci_notify_bar_change = [](int bar_num) {}; this->pci_notify_bar_change = [](int bar_num) {};
} };
uint32_t PCIBase::pci_cfg_read(uint32_t reg_offs, AccessDetails &details) uint32_t PCIBase::pci_cfg_read(uint32_t reg_offs, AccessDetails &details)
{ {
@@ -194,8 +191,7 @@ void PCIBase::set_bar_value(int bar_num, uint32_t value)
case PCIBarType::Io_32_Bit: case PCIBarType::Io_32_Bit:
this->bars[bar_num] = (value & bar_cfg & ~3) | (bar_cfg & 3); this->bars[bar_num] = (value & bar_cfg & ~3) | (bar_cfg & 3);
if (value != 0xFFFFFFFFUL && (value & ~3) != (value & bar_cfg & ~3)) { if (value != 0xFFFFFFFFUL && (value & ~3) != (value & bar_cfg & ~3)) {
LOG_F(ERROR, "%s: BAR %d cannot be 0x%08x (set to 0x%08x)", LOG_F(ERROR, "%s: BAR %d cannot be 0x%08x (set to 0x%08x)", this->get_name().c_str(), bar_num, (value & ~3), (value & bar_cfg & ~3));
this->get_name().c_str(), bar_num, (value & ~3), (value & bar_cfg & ~3));
} }
break; break;
@@ -204,8 +200,7 @@ void PCIBase::set_bar_value(int bar_num, uint32_t value)
case PCIBarType::Mem_64_Bit_Lo: case PCIBarType::Mem_64_Bit_Lo:
this->bars[bar_num] = (value & bar_cfg & ~0xF) | (bar_cfg & 0xF); this->bars[bar_num] = (value & bar_cfg & ~0xF) | (bar_cfg & 0xF);
if (value != 0xFFFFFFFFUL && (value & ~0xF) != (value & bar_cfg & ~0xF)) { if (value != 0xFFFFFFFFUL && (value & ~0xF) != (value & bar_cfg & ~0xF)) {
LOG_F(ERROR, "%s: BAR %d cannot be 0x%08x (set to 0x%08x)", LOG_F(ERROR, "%s: BAR %d cannot be 0x%08x (set to 0x%08x)", this->get_name().c_str(), bar_num, (value & ~0xF), (value & bar_cfg & ~0xF));
this->get_name().c_str(), bar_num, (value & ~0xF), (value & bar_cfg & ~0xF));
} }
break; break;
+7 -9
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -47,9 +47,7 @@ enum {
PCI_CFG_BAR0 = 0x10, // base address register 0 (type 0, 1, and 2) PCI_CFG_BAR0 = 0x10, // base address register 0 (type 0, 1, and 2)
PCI_CFG_BAR1 = 0x14, // base address register 1 (type 0 and 1) PCI_CFG_BAR1 = 0x14, // base address register 1 (type 0 and 1)
PCI_CFG_DWORD_13 = 0x34, // capabilities pointer (type 0 and 1) PCI_CFG_DWORD_13 = 0x34, // capabilities pointer (type 0 and 1)
PCI_CFG_DWORD_15 = 0x3C, // Max_Lat, Min_Gnt (Type 0) PCI_CFG_DWORD_15 = 0x3C, // Max_Lat, Min_Gnt (Type 0); Bridge Control (Type 1 and 2); Int_Pin and Int_Line registers (type 0, 1, and 2)
// Bridge Control (Type 1 and 2)
// Int_Pin and Int_Line registers (type 0, 1, and 2)
}; };
/** PCI Vendor IDs for devices used in Power Macintosh computers. */ /** PCI Vendor IDs for devices used in Power Macintosh computers. */
@@ -86,16 +84,16 @@ public:
virtual bool supports_io_space() { virtual bool supports_io_space() {
return has_io_space; return has_io_space;
} };
/* I/O space access methods */ /* I/O space access methods */
virtual bool pci_io_read(uint32_t offset, uint32_t size, uint32_t* res) { virtual bool pci_io_read(uint32_t offset, uint32_t size, uint32_t* res) {
return false; return false;
} };
virtual bool pci_io_write(uint32_t offset, uint32_t value, uint32_t size) { virtual bool pci_io_write(uint32_t offset, uint32_t value, uint32_t size) {
return false; return false;
} };
// configuration space access methods // configuration space access methods
virtual uint32_t pci_cfg_read(uint32_t reg_offs, AccessDetails &details); virtual uint32_t pci_cfg_read(uint32_t reg_offs, AccessDetails &details);
+12 -14
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -39,12 +39,12 @@ PCIBridge::PCIBridge(std::string name) : PCIBridgeBase(name, PCI_HEADER_TYPE_1,
this->pci_wr_memory_base = [this](uint16_t val) { this->pci_wr_memory_base = [this](uint16_t val) {
this->memory_base = (val & this->memory_cfg) | (this->memory_cfg & 15); this->memory_base = (val & this->memory_cfg) | (this->memory_cfg & 15);
this->memory_base_32 = (((uint64_t)this->memory_base & 0xfff0) << 16); this->memory_base_32 = ((this->memory_base & 0xfff0) << 16);
}; };
this->pci_wr_memory_limit = [this](uint16_t val) { this->pci_wr_memory_limit = [this](uint16_t val) {
this->memory_limit = (val & this->memory_cfg) | (this->memory_cfg & 15); this->memory_limit = (val & this->memory_cfg) | (this->memory_cfg & 15);
this->memory_limit_32 = (((uint64_t)this->memory_limit & 0xfff0) << 16) + 0x100000; this->memory_limit_32 = ((this->memory_limit & 0xfff0) << 16) + 0x100000;
}; };
this->pci_wr_io_base = [this](uint8_t val) { this->pci_wr_io_base = [this](uint8_t val) {
@@ -61,13 +61,12 @@ PCIBridge::PCIBridge(std::string name) : PCIBridgeBase(name, PCI_HEADER_TYPE_1,
this->pci_wr_pref_mem_base = [this](uint16_t val) { this->pci_wr_pref_mem_base = [this](uint16_t val) {
this->pref_mem_base = (val & this->pref_mem_cfg) | (this->pref_mem_cfg & 15); this->pref_mem_base = (val & this->pref_mem_cfg) | (this->pref_mem_cfg & 15);
this->pref_mem_base_64 = ((uint64_t)this->pref_base_upper32 << 32) | this->pref_mem_base_64 = ((uint64_t)this->pref_base_upper32 << 32) |
(((uint64_t)this->pref_mem_base & 0xfff0) << 16); ((this->pref_mem_base & 0xfff0) << 16);
}; };
this->pci_wr_pref_mem_limit = [this](uint16_t val) { this->pci_wr_pref_mem_limit = [this](uint16_t val) {
this->pref_mem_limit = (val & this->pref_mem_cfg) | (this->pref_mem_cfg & 15); this->pref_mem_limit = (val & this->pref_mem_cfg) | (this->pref_mem_cfg & 15);
this->pref_mem_limit_64 = (((uint64_t)this->pref_limit_upper32 << 32) | \ this->pref_mem_limit_64 = (((uint64_t)this->pref_limit_upper32 << 32) |
(((uint64_t)this->pref_mem_limit & 0xfff0) << 16)) + \ ((this->pref_mem_limit & 0xfff0) << 16)) + 0x100000;
0x100000;
}; };
this->pci_wr_io_base_upper16 = [this](uint16_t val) { this->pci_wr_io_base_upper16 = [this](uint16_t val) {
if ((this->io_base & 15) == 1) if ((this->io_base & 15) == 1)
@@ -86,17 +85,16 @@ PCIBridge::PCIBridge(std::string name) : PCIBridgeBase(name, PCI_HEADER_TYPE_1,
if ((this->pref_mem_cfg & 15) == 1) if ((this->pref_mem_cfg & 15) == 1)
this->pref_base_upper32 = val; this->pref_base_upper32 = val;
this->pref_mem_base_64 = ((uint64_t)this->pref_base_upper32 << 32) | this->pref_mem_base_64 = ((uint64_t)this->pref_base_upper32 << 32) |
(((uint64_t)this->pref_mem_base & 0xfff0) << 16); ((this->pref_mem_base & 0xfff0) << 16);
}; };
this->pci_wr_pref_limit_upper32 = [this](uint32_t val) { this->pci_wr_pref_limit_upper32 = [this](uint32_t val) {
if ((this->pref_mem_cfg & 15) == 1) if ((this->pref_mem_cfg & 15) == 1)
this->pref_limit_upper32 = val; this->pref_limit_upper32 = val;
this->pref_mem_limit_64 = (((uint64_t)this->pref_limit_upper32 << 32) | \ this->pref_mem_limit_64 = (((uint64_t)this->pref_limit_upper32 << 32) |
(((uint64_t)this->pref_mem_limit & 0xfff0) << 16)) + \ ((this->pref_mem_limit & 0xfff0) << 16)) + 0x100000;
0x100000;
}; };
} };
uint32_t PCIBridge::pci_cfg_read(uint32_t reg_offs, AccessDetails &details) uint32_t PCIBridge::pci_cfg_read(uint32_t reg_offs, AccessDetails &details)
{ {
+3 -3
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
+6 -6
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -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/>. along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
#include <core/memaccess.h>
#include <devices/common/pci/pcibridgebase.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) PCIBridgeBase::PCIBridgeBase(std::string name, PCIHeaderType hdr_type, int num_bars) : PCIBase(name, hdr_type, num_bars)
{ {
@@ -40,9 +40,9 @@ PCIBridgeBase::PCIBridgeBase(std::string name, PCIHeaderType hdr_type, int num_b
}; };
this->pci_wr_sec_status = [this](uint16_t val) {}; this->pci_wr_sec_status = [this](uint16_t val) {};
this->pci_wr_bridge_control = [this](uint16_t val) { this->bridge_control = val; }; this->pci_wr_bridge_control = [this](uint16_t val) { this->bridge_control = val; };
} };
AddressMapEntry* PCIBridgeBase::pci_register_mmio_region(uint32_t start_addr, uint32_t size, PCIBase* obj) bool PCIBridgeBase::pci_register_mmio_region(uint32_t start_addr, uint32_t size, PCIBase* obj)
{ {
// FIXME: constrain region to memory range // FIXME: constrain region to memory range
return this->host_instance->pci_register_mmio_region(start_addr, size, obj); return this->host_instance->pci_register_mmio_region(start_addr, size, obj);
+10 -10
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -43,16 +43,16 @@ public:
~PCIBridgeBase() = default; ~PCIBridgeBase() = default;
// PCIHost methods // PCIHost methods
virtual AddressMapEntry* pci_register_mmio_region(uint32_t start_addr, uint32_t size, PCIBase* obj) override; virtual bool pci_register_mmio_region(uint32_t start_addr, uint32_t size, PCIBase* obj);
virtual bool pci_unregister_mmio_region(uint32_t start_addr, uint32_t size, PCIBase* obj) override; virtual bool pci_unregister_mmio_region(uint32_t start_addr, uint32_t size, PCIBase* obj);
// PCIBase methods // PCIBase methods
virtual uint32_t pci_cfg_read(uint32_t reg_offs, AccessDetails &details) override; virtual uint32_t pci_cfg_read(uint32_t reg_offs, AccessDetails &details);
virtual void pci_cfg_write(uint32_t reg_offs, uint32_t value, AccessDetails &details) override; virtual void pci_cfg_write(uint32_t reg_offs, uint32_t value, AccessDetails &details);
bool supports_io_space() override { bool supports_io_space() {
return true; return true;
} };
// plugin interface for using in the derived classes // plugin interface for using in the derived classes
std::function<uint8_t()> pci_rd_primary_bus; std::function<uint8_t()> pci_rd_primary_bus;
@@ -69,7 +69,7 @@ public:
std::function<void(uint16_t)> pci_wr_bridge_control; std::function<void(uint16_t)> pci_wr_bridge_control;
// HWComponent methods // HWComponent methods
virtual int device_postinit() override; virtual int device_postinit();
protected: protected:
// PCI configuration space state // PCI configuration space state
+8 -26
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -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/>. along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
#include <core/memaccess.h>
#include <devices/common/pci/pcicardbusbridge.h> #include <devices/common/pci/pcicardbusbridge.h>
#include <memaccess.h>
typedef struct { typedef struct {
// CardBus Registers // CardBus Registers
@@ -126,7 +126,7 @@ PCICardbusBridge::PCICardbusBridge(std::string name) : PCIBridgeBase(name, PCI_H
this->io_limit_1 = (val & this->io_1_cfg); this->io_limit_1 = (val & this->io_1_cfg);
this->io_limit_1_32 = this->io_limit_1 + 4; this->io_limit_1_32 = this->io_limit_1 + 4;
}; };
} };
uint32_t PCICardbusBridge::pci_cfg_read(uint32_t reg_offs, AccessDetails &details) uint32_t PCICardbusBridge::pci_cfg_read(uint32_t reg_offs, AccessDetails &details)
{ {
@@ -155,10 +155,6 @@ uint32_t PCICardbusBridge::pci_cfg_read(uint32_t reg_offs, AccessDetails &detail
return (this->subsys_id << 16) | (this->subsys_vndr); return (this->subsys_id << 16) | (this->subsys_vndr);
case PCI_CFG_CB_LEGACY_MODE_BASE: case PCI_CFG_CB_LEGACY_MODE_BASE:
return this->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: default:
return PCIBridgeBase::pci_cfg_read(reg_offs, details); return PCIBridgeBase::pci_cfg_read(reg_offs, details);
} }
@@ -197,19 +193,11 @@ void PCICardbusBridge::pci_cfg_write(uint32_t reg_offs, uint32_t value, AccessDe
case PCI_CFG_CB_IO_LIMIT_1: case PCI_CFG_CB_IO_LIMIT_1:
this->pci_wr_io_limit_0(value); this->pci_wr_io_limit_0(value);
break; break;
#if 0 /*
// FIXME: handle legacy_mode_base and dma_base changes here
case PCI_CFG_CB_LEGACY_MODE_BASE: case PCI_CFG_CB_LEGACY_MODE_BASE:
this->legacy_mode_base = value; this->legacy_mode_base = value;
break; 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: default:
PCIBridgeBase::pci_cfg_write(reg_offs, value, details); PCIBridgeBase::pci_cfg_write(reg_offs, value, details);
break; break;
@@ -222,9 +210,6 @@ 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) && 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) (offset < this->io_base_1_32 || offset + size >= this->io_limit_1_32)
) return false; ) return false;
#if 0
// FIXME: check legacy_mode_base and dma_base here
#endif
return this->pci_io_read_loop(offset, size, *res); return this->pci_io_read_loop(offset, size, *res);
} }
@@ -234,8 +219,5 @@ 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) && 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) (offset < this->io_base_1_32 || offset + size >= this->io_limit_1_32)
) return false; ) return false;
#if 0 return this->pci_io_read_loop(offset, size, value);
// FIXME: check legacy_mode_base and dma_base here
#endif
return this->pci_io_write_loop(offset, size, value);
} }
+3 -27
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -44,28 +44,6 @@ enum {
PCI_CFG_CB_IO_LIMIT_1 = 0x38, 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_SUBSYSTEM_IDS = 0x40, // CB_SUBSYSTEM_VENDOR_ID.w, CB_SUBSYSTEM_ID.w
PCI_CFG_CB_LEGACY_MODE_BASE = 0x44, 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 { class PCICardbusBridge : public PCIBridgeBase {
@@ -111,8 +89,6 @@ protected:
uint16_t subsys_id = 0; uint16_t subsys_id = 0;
uint16_t subsys_vndr = 0; uint16_t subsys_vndr = 0;
uint32_t legacy_mode_base = 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 // 0 = not writable
uint32_t memory_0_cfg = 0xfffff000; uint32_t memory_0_cfg = 0xfffff000;
+4 -4
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -29,7 +29,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
PCIDevice::PCIDevice(std::string name) : PCIBase(name, PCI_HEADER_TYPE_0, 6) PCIDevice::PCIDevice(std::string name) : PCIBase(name, PCI_HEADER_TYPE_0, 6)
{ {
} };
uint32_t PCIDevice::pci_cfg_read(uint32_t reg_offs, AccessDetails &details) uint32_t PCIDevice::pci_cfg_read(uint32_t reg_offs, AccessDetails &details)
{ {
+3 -3
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-23 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
+8 -8
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -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/>. along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
#include <core/endianswap.h>
#include <devices/common/hwcomponent.h> #include <devices/common/hwcomponent.h>
#include <devices/common/pci/pcibridge.h> #include <devices/common/pci/pcibridge.h>
#include <devices/common/pci/pcihost.h> #include <devices/common/pci/pcihost.h>
#include <devices/deviceregistry.h> #include <devices/deviceregistry.h>
#include <devices/memctrl/memctrlbase.h>
#include <machines/machinefactory.h> #include <machines/machinefactory.h>
#include <machines/machinebase.h> #include <machines/machinebase.h>
#include <endianswap.h>
#include <loguru.hpp> #include <loguru.hpp>
#include <cinttypes> #include <cinttypes>
@@ -80,8 +81,7 @@ void PCIHost::pci_unregister_device(int dev_fun_num)
HWComponent *hwc = dynamic_cast<HWComponent*>(this); HWComponent *hwc = dynamic_cast<HWComponent*>(this);
LOG_F( LOG_F(
// FIXME: need destructors to remove memory regions and downstream devices. // FIXME: need destructors to remove memory regions and downstream devices.
ERROR, "%s: pci_unregister_device(%s) not supported yet (every PCI device needs " ERROR, "%s: pci_unregister_device(%s) not supported yet (every PCI device needs a working destructor to unregister memory and downstream devices etc.)",
"a working destructor to unregister memory and downstream devices etc.)",
hwc ? hwc->get_name().c_str() : "PCIHost", dev_instance->get_name().c_str() hwc ? hwc->get_name().c_str() : "PCIHost", dev_instance->get_name().c_str()
); );
@@ -89,7 +89,7 @@ void PCIHost::pci_unregister_device(int dev_fun_num)
gMachineObj->remove_device(dev_instance); // calls destructor of dev_instance since it is a unique_ptr in the device_map. gMachineObj->remove_device(dev_instance); // calls destructor of dev_instance since it is a unique_ptr in the device_map.
} }
AddressMapEntry* PCIHost::pci_register_mmio_region(uint32_t start_addr, uint32_t size, PCIBase* obj) bool PCIHost::pci_register_mmio_region(uint32_t start_addr, uint32_t size, PCIBase* obj)
{ {
MemCtrlBase *mem_ctrl = dynamic_cast<MemCtrlBase *> MemCtrlBase *mem_ctrl = dynamic_cast<MemCtrlBase *>
(gMachineObj->get_comp_by_type(HWCompType::MEM_CTRL)); (gMachineObj->get_comp_by_type(HWCompType::MEM_CTRL));
@@ -229,7 +229,7 @@ uint32_t PCIHost::pci_io_read_broadcast(uint32_t offset, int size)
SIZE_ARG(size) SIZE_ARG(size)
); );
// machine check exception (DEFAULT CATCH!, code=FFF00200) // machine check exception (DEFAULT CATCH!, code=FFF00200)
ppc_exception_handler(Except_Type::EXC_MACHINE_CHECK, 0); ppc_exception_handler(Except_Type::EXC_MACHINE_CHECK, 0, 0);
return 0; return 0;
} }
+10 -22
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -23,9 +23,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#define PCI_HOST_H #define PCI_HOST_H
#include <core/bitops.h> #include <core/bitops.h>
#include <core/endianswap.h>
#include <devices/common/hwinterrupt.h> #include <devices/common/hwinterrupt.h>
#include <devices/memctrl/memctrlbase.h> #include <endianswap.h>
#include <cinttypes> #include <cinttypes>
#include <string> #include <string>
@@ -65,14 +64,14 @@ public:
PCIHost() { PCIHost() {
this->dev_map.clear(); this->dev_map.clear();
io_space_devs.clear(); io_space_devs.clear();
} };
~PCIHost() = default; ~PCIHost() = default;
virtual bool pci_register_device(int dev_fun_num, PCIBase* dev_instance); virtual bool pci_register_device(int dev_fun_num, PCIBase* dev_instance);
virtual void pci_unregister_device(int dev_fun_num); virtual void pci_unregister_device(int dev_fun_num);
virtual AddressMapEntry* pci_register_mmio_region(uint32_t start_addr, uint32_t size, PCIBase* obj); virtual bool pci_register_mmio_region(uint32_t start_addr, uint32_t size, PCIBase* obj);
virtual bool pci_unregister_mmio_region(uint32_t start_addr, uint32_t size, PCIBase* obj); virtual bool pci_unregister_mmio_region(uint32_t start_addr, uint32_t size, PCIBase* obj);
virtual void attach_pci_device(const std::string& dev_name, int slot_id); virtual void attach_pci_device(const std::string& dev_name, int slot_id);
PCIBase *attach_pci_device(const std::string& dev_name, int slot_id, PCIBase *attach_pci_device(const std::string& dev_name, int slot_id,
@@ -89,13 +88,13 @@ public:
virtual void set_irq_map(const std::vector<PciIrqMap> &irq_map) { virtual void set_irq_map(const std::vector<PciIrqMap> &irq_map) {
this->my_irq_map = irq_map; this->my_irq_map = irq_map;
} };
virtual int pcihost_device_postinit(); virtual int pcihost_device_postinit();
virtual bool register_pci_int(PCIBase* dev_instance); virtual bool register_pci_int(PCIBase* dev_instance);
virtual void set_interrupt_controller(InterruptCtrl * int_ctrl_obj) { virtual void set_interrupt_controller(InterruptCtrl * int_ctrl_obj) {
this->int_ctrl = int_ctrl_obj; this->int_ctrl = int_ctrl_obj;
} };
virtual InterruptCtrl *get_interrupt_controller(); virtual InterruptCtrl *get_interrupt_controller();
protected: protected:
@@ -110,8 +109,7 @@ protected:
// Helpers for data conversion in the PCI Configuration space. // Helpers for data conversion in the PCI Configuration space.
/** /**
Perform size dependent endian swapping for value that is dword from PCI config Perform size dependent endian swapping for value that is dword from PCI config or any other dword little endian register.
or any other dword little endian register.
Unaligned data is handled properly by using bytes from the next dword. Unaligned data is handled properly by using bytes from the next dword.
*/ */
@@ -199,14 +197,4 @@ 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 */ #endif /* PCI_HOST_H */
+8 -32
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -37,7 +37,7 @@ using namespace MeshScsi;
int MeshController::device_postinit() { int MeshController::device_postinit() {
this->bus_obj = dynamic_cast<ScsiBus*>(gMachineObj->get_comp_by_name("ScsiMesh")); this->bus_obj = dynamic_cast<ScsiBus*>(gMachineObj->get_comp_by_name("ScsiMesh"));
if (bus_obj) { if (bus_obj) {
bus_obj->register_device(7, static_cast<ScsiPhysDevice*>(this)); bus_obj->register_device(7, static_cast<ScsiDevice*>(this));
bus_obj->attach_scsi_devices("2"); bus_obj->attach_scsi_devices("2");
} }
@@ -51,16 +51,10 @@ int MeshController::device_postinit() {
void MeshController::reset(bool is_hard_reset) { void MeshController::reset(bool is_hard_reset) {
this->cur_cmd = SeqCmd::NoOperation; this->cur_cmd = SeqCmd::NoOperation;
this->fifo_pos = 0; this->fifo_pos = 0;
this->to_xfer = 0;
this->int_stat = 0;
this->int_mask = 0; this->int_mask = 0;
this->exception = 0; this->exception = 0;
this->xfer_count = 0; this->xfer_count = 0;
this->src_id = 7; this->src_id = 7;
this->check_parity = true;
this->cur_state = Scsi_Bus_Controller::SeqState::BUS_FREE;
update_irq();
if (is_hard_reset) { if (is_hard_reset) {
this->bus_stat = 0; this->bus_stat = 0;
@@ -129,7 +123,6 @@ void MeshController::write(uint8_t reg_offset, uint8_t value) {
break; break;
case MeshReg::IntMask: case MeshReg::IntMask:
this->int_mask = value; this->int_mask = value;
update_irq();
break; break;
case MeshReg::Interrupt: case MeshReg::Interrupt:
this->int_stat &= ~(value & INT_MASK); // clear requested interrupt bits this->int_stat &= ~(value & INT_MASK); // clear requested interrupt bits
@@ -216,16 +209,7 @@ void MeshController::perform_command(const uint8_t cmd) {
this->sequencer(); this->sequencer();
break; break;
case SeqCmd::BusFree: case SeqCmd::BusFree:
// Don't release ACK if ATN is asserted. This condition indicates this->bus_obj->release_ctrl_line(this->src_id, SCSI_CTRL_ACK);
// that the initiator wants to reject last message.
if (!this->bus_obj->test_ctrl_lines(SCSI_CTRL_ATN))
this->bus_obj->release_ctrl_line(this->src_id, SCSI_CTRL_ACK);
// Let the target switch to next bus phase if
// - both ACK and ATN are asserted so the target will reject last message
// - when in MESSAGE_IN phase to tell the target the initiator accepts last message
if (this->is_initiator && (this->bus_obj->test_ctrl_lines(SCSI_CTRL_ATN) ||
this->bus_obj->current_phase() == ScsiPhase::MESSAGE_IN))
this->bus_obj->target_next_step();
// generate phase mismatch exception // generate phase mismatch exception
// if the target is still connected // if the target is still connected
if (this->bus_obj->test_ctrl_lines(SCSI_CTRL_BSY)) { if (this->bus_obj->test_ctrl_lines(SCSI_CTRL_BSY)) {
@@ -298,11 +282,7 @@ void MeshController::step_completed() {
} }
void MeshController::report_error(const int error) { void MeshController::report_error(const int error) {
switch (error) { switch(error) {
case ARB_LOST:
this->exception |= EXC_ARB_LOST;
this->int_stat |= INT_EXCEPTION;
break;
case SEL_TIMEOUT: case SEL_TIMEOUT:
this->exception |= EXC_SEL_TIMEOUT; this->exception |= EXC_SEL_TIMEOUT;
this->int_stat |= INT_EXCEPTION; this->int_stat |= INT_EXCEPTION;
@@ -319,16 +299,12 @@ static const PropMap Mesh_properties = {
{"cdr_img2", new StrProperty("")}, {"cdr_img2", new StrProperty("")},
}; };
static const std::vector<std::string> Mesh_Subdevices = {
"ScsiMesh"
};
static const DeviceDescription Mesh_Tnt_Descriptor = { static const DeviceDescription Mesh_Tnt_Descriptor = {
MeshController::create_for_tnt, Mesh_Subdevices, Mesh_properties, HWCompType::SCSI_HOST | HWCompType::SCSI_DEV MeshController::create_for_tnt, {}, Mesh_properties
}; };
static const DeviceDescription Mesh_Heathrow_Descriptor = { static const DeviceDescription Mesh_Heathrow_Descriptor = {
MeshController::create_for_heathrow, Mesh_Subdevices, Mesh_properties, HWCompType::SCSI_HOST | HWCompType::SCSI_DEV MeshController::create_for_heathrow, {}, Mesh_properties
}; };
REGISTER_DEVICE(MeshTnt, Mesh_Tnt_Descriptor); REGISTER_DEVICE(MeshTnt, Mesh_Tnt_Descriptor);
+7 -7
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -91,7 +91,7 @@ namespace MeshScsi {
INT_ERROR = 1 << 2, INT_ERROR = 1 << 2,
INT_MASK = INT_CMD_DONE | INT_EXCEPTION | INT_ERROR INT_MASK = INT_CMD_DONE | INT_EXCEPTION | INT_ERROR
}; };
} // namespace MeshScsi }; // namespace MeshScsi
class MeshBase { class MeshBase {
public: public:
@@ -107,8 +107,8 @@ public:
~MeshStub() = default; ~MeshStub() = default;
// registers access // registers access
uint8_t read(uint8_t reg_offset) override { return 0; } uint8_t read(uint8_t reg_offset) override { return 0; };
void write(uint8_t reg_offset, uint8_t value) override {} void write(uint8_t reg_offset, uint8_t value) override {};
}; };
class MeshController : public ScsiBusController, public MeshBase { class MeshController : public ScsiBusController, public MeshBase {
@@ -116,7 +116,7 @@ public:
MeshController(uint8_t mesh_id) : ScsiBusController("MESH", 7) { MeshController(uint8_t mesh_id) : ScsiBusController("MESH", 7) {
this->chip_id = mesh_id; this->chip_id = mesh_id;
this->reset(true); this->reset(true);
} };
~MeshController() = default; ~MeshController() = default;
static std::unique_ptr<HWComponent> create_for_tnt() { static std::unique_ptr<HWComponent> create_for_tnt() {
+224 -287
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -33,7 +33,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cinttypes> #include <cinttypes>
#include <cstring> #include <cstring>
Sc53C94::Sc53C94(uint8_t chip_id, uint8_t my_id) : ScsiPhysDevice("SC53C94", my_id), DmaDevice() Sc53C94::Sc53C94(uint8_t chip_id, uint8_t my_id) : ScsiDevice("SC53C94", my_id), DmaDevice()
{ {
this->chip_id = chip_id; this->chip_id = chip_id;
this->my_bus_id = my_id; this->my_bus_id = my_id;
@@ -45,7 +45,7 @@ int Sc53C94::device_postinit()
{ {
ScsiBus* bus = dynamic_cast<ScsiBus*>(gMachineObj->get_comp_by_name("ScsiCurio")); ScsiBus* bus = dynamic_cast<ScsiBus*>(gMachineObj->get_comp_by_name("ScsiCurio"));
if (bus) { if (bus) {
bus->register_device(7, static_cast<ScsiPhysDevice*>(this)); bus->register_device(7, static_cast<ScsiDevice*>(this));
bus->attach_scsi_devices(""); bus->attach_scsi_devices("");
} }
@@ -72,79 +72,50 @@ void Sc53C94::reset_device()
this->data_fifo_pos = 0; this->data_fifo_pos = 0;
this->data_fifo[0] = 0; this->data_fifo[0] = 0;
this->sync_period = 5;
this->sync_offset = 0;
this->cur_step = 0;
this->seq_step = 0; this->seq_step = 0;
this->status &= STAT_PHASE_MASK; // reset doesn't affect bus phase bits this->status = 0;
this->int_status = 0;
} }
uint8_t Sc53C94::read(uint8_t reg_offset) uint8_t Sc53C94::read(uint8_t reg_offset)
{ {
uint8_t value; uint8_t status, int_status;
switch (reg_offset) { switch (reg_offset) {
case Read::Reg53C94::Xfer_Cnt_LSB: case Read::Reg53C94::Xfer_Cnt_LSB:
value = this->xfer_count & 0xFFU; return this->xfer_count & 0xFFU;
break;
case Read::Reg53C94::Xfer_Cnt_MSB: case Read::Reg53C94::Xfer_Cnt_MSB:
value = (this->xfer_count >> 8) & 0xFFU; return (this->xfer_count >> 8) & 0xFFU;
break;
case Read::Reg53C94::FIFO: case Read::Reg53C94::FIFO:
value = this->fifo_pop(); return this->fifo_pop();
break;
case Read::Reg53C94::Command: case Read::Reg53C94::Command:
value = this->cmd_fifo[0]; return this->cmd_fifo[0];
break; case Read::Reg53C94::Status:
case Read::Reg53C94::Status: { status = bus_obj->test_ctrl_lines(SCSI_CTRL_MSG | SCSI_CTRL_CD | SCSI_CTRL_IO);
uint8_t bus_phase; return (this->status & 0xF8) | status;
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);
value = (this->status & 0xF8) | bus_phase;
break;
}
case Read::Reg53C94::Int_Status: case Read::Reg53C94::Int_Status:
value = this->int_status; int_status = this->int_status;
if (this->irq) { this->seq_step = 0;
this->status &= ~(STAT_GE | STAT_PE | STAT_GCV); this->int_status = 0;
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(); this->update_irq();
break; return int_status;
case Read::Reg53C94::Seq_Step: case Read::Reg53C94::Seq_Step:
value = this->seq_step; return this->seq_step;
break;
case Read::Reg53C94::FIFO_Flags: case Read::Reg53C94::FIFO_Flags:
value = (this->cur_step << 5) | (this->data_fifo_pos & 0x1F); return (this->seq_step << 5) | (this->data_fifo_pos & 0x1F);
break;
case Read::Reg53C94::Config_1: case Read::Reg53C94::Config_1:
value = this->config1; return this->config1;
break;
case Read::Reg53C94::Config_3: case Read::Reg53C94::Config_3:
value = this->config3; return this->config3;
break;
case Read::Reg53C94::Config_4:
value = this->config4;
break;
case Read::Reg53C94::Xfer_Cnt_Hi: case Read::Reg53C94::Xfer_Cnt_Hi:
if (this->config2 & CFG2_ENF) { if (this->config2 & CFG2_ENF) {
value = (this->xfer_count >> 16) & 0xFFU; return (this->xfer_count >> 16) & 0xFFU;
} else {
value = 0;
} }
break; break;
default: default:
LOG_F(INFO, "%s: reading from register %d", this->name.c_str(), reg_offset); LOG_F(INFO, "%s: reading from register %d", this->name.c_str(), reg_offset);
} }
return value; return 0;
} }
void Sc53C94::write(uint8_t reg_offset, uint8_t value) void Sc53C94::write(uint8_t reg_offset, uint8_t value)
@@ -168,9 +139,6 @@ void Sc53C94::write(uint8_t reg_offset, uint8_t value)
case Write::Reg53C94::Sel_Timeout: case Write::Reg53C94::Sel_Timeout:
this->sel_timeout = value; this->sel_timeout = value;
break; break;
case Write::Reg53C94::Sync_Period:
this->sync_period = value;
break;
case Write::Reg53C94::Sync_Offset: case Write::Reg53C94::Sync_Offset:
this->sync_offset = value; this->sync_offset = value;
break; break;
@@ -189,13 +157,8 @@ void Sc53C94::write(uint8_t reg_offset, uint8_t value)
case Write::Reg53C94::Config_3: case Write::Reg53C94::Config_3:
this->config3 = value; this->config3 = value;
break; 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: default:
LOG_F(INFO, "%s: writing 0x%X to register # %d", this->name.c_str(), value, LOG_F(INFO, "%s: writing 0x%X to %d register", this->name.c_str(), value,
reg_offset); reg_offset);
} }
} }
@@ -252,7 +215,7 @@ void Sc53C94::pseudo_dma_write(uint16_t data) {
void Sc53C94::update_command_reg(uint8_t cmd) void Sc53C94::update_command_reg(uint8_t cmd)
{ {
if (this->on_reset && (cmd & CMD_OPCODE) != CMD_NOP && (cmd & CMD_OPCODE) != CMD_CLEAR_FIFO) { if (this->on_reset && (cmd & CMD_OPCODE) != CMD_NOP) {
LOG_F(WARNING, "%s: command register blocked after RESET!", this->name.c_str()); LOG_F(WARNING, "%s: command register blocked after RESET!", this->name.c_str());
return; return;
} }
@@ -280,9 +243,9 @@ void Sc53C94::update_command_reg(uint8_t cmd)
void Sc53C94::exec_command() void Sc53C94::exec_command()
{ {
uint8_t cmd = this->cur_cmd = this->cmd_fifo[0] & CMD_OPCODE; uint8_t cmd = this->cur_cmd = this->cmd_fifo[0] & 0x7F;
this->is_dma_cmd = !!(this->cmd_fifo[0] & CMD_ISDMA); this->is_dma_cmd = !!(this->cmd_fifo[0] & 0x80);
if (this->is_dma_cmd) { if (this->is_dma_cmd) {
if (this->config2 & CFG2_ENF) { // extended mode: 24-bit if (this->config2 & CFG2_ENF) { // extended mode: 24-bit
@@ -295,8 +258,6 @@ void Sc53C94::exec_command()
} }
} }
this->cmd_steps = nullptr; // assume a single-step command for now
// simple commands will be executed immediately // simple commands will be executed immediately
// complex commands will be broken into multiple steps // complex commands will be broken into multiple steps
// and handled by the sequencer // and handled by the sequencer
@@ -306,7 +267,6 @@ void Sc53C94::exec_command()
exec_next_command(); exec_next_command();
break; break;
case CMD_CLEAR_FIFO: case CMD_CLEAR_FIFO:
this->on_reset = false; // unblock the command register
this->data_fifo_pos = 0; // set the bottom of the data FIFO to zero this->data_fifo_pos = 0; // set the bottom of the data FIFO to zero
this->data_fifo[0] = 0; this->data_fifo[0] = 0;
exec_next_command(); exec_next_command();
@@ -314,27 +274,25 @@ void Sc53C94::exec_command()
case CMD_RESET_DEVICE: case CMD_RESET_DEVICE:
reset_device(); reset_device();
this->on_reset = true; // block the command register this->on_reset = true; // block the command register
this->update_irq();
return; return;
case CMD_RESET_BUS: case CMD_RESET_BUS:
LOG_F(INFO, "%s: resetting SCSI bus...", this->name.c_str()); LOG_F(INFO, "%s: resetting SCSI bus...", this->name.c_str());
// assert RST line // assert RST line
this->bus_obj->assert_ctrl_line(this->my_bus_id, SCSI_CTRL_RST); this->bus_obj->assert_ctrl_line(this->my_bus_id, SCSI_CTRL_RST);
// release RST line after 25 us // release RST line after 25 us
if (my_timer.active) { if (my_timer_id) {
TimerManager::get_instance()->cancel_timer(this->my_timer); TimerManager::get_instance()->cancel_timer(this->my_timer_id);
my_timer.active = 0; my_timer_id = 0;
} }
TimerManager::get_instance()->add_oneshot_timer(my_timer, my_timer_id = TimerManager::get_instance()->add_oneshot_timer(
USECS_TO_NSECS(25), USECS_TO_NSECS(25),
[this](uint64_t, uint64_t) { [this]() {
my_timer.active = 0; my_timer_id = 0;
this->bus_obj->release_ctrl_line(this->my_bus_id, SCSI_CTRL_RST); this->bus_obj->release_ctrl_line(this->my_bus_id, SCSI_CTRL_RST);
}); });
if (!(config1 & CFG1_DISR)) { if (!(config1 & 0x40)) {
LOG_F(INFO, "%s: reset interrupt issued", this->name.c_str()); LOG_F(INFO, "%s: reset interrupt issued", this->name.c_str());
this->int_status = INTSTAT_SRST; this->int_status = INTSTAT_SRST;
this->update_irq();
} }
exec_next_command(); exec_next_command();
break; break;
@@ -345,88 +303,61 @@ void Sc53C94::exec_command()
this->int_status = INTSTAT_ICMD; this->int_status = INTSTAT_ICMD;
this->update_irq(); this->update_irq();
} else { } else {
this->seq_step = 0;
this->cmd_steps = nullptr;
this->cur_state = SeqState::XFER_BEGIN; this->cur_state = SeqState::XFER_BEGIN;
this->sequencer(); this->sequencer();
} }
break; break;
case CMD_COMPLETE_STEPS: case CMD_COMPLETE_STEPS:
static SeqDesc * complete_steps_desc = new SeqDesc[3]{
{(CMD_COMPLETE_STEPS << 8) + 1, SeqState::RCV_STATUS, 0, 0},
{(CMD_COMPLETE_STEPS << 8) + 2, SeqState::RCV_MESSAGE, 0, 0},
{(CMD_COMPLETE_STEPS << 8) + 3, SeqState::CMD_COMPLETE, 0, INTSTAT_SR | INTSTAT_SO}
};
if (this->bus_obj->current_phase() != ScsiPhase::STATUS) { if (this->bus_obj->current_phase() != ScsiPhase::STATUS) {
ABORT_F("%s: complete steps only works in the STATUS phase", this->name.c_str()); ABORT_F("%s: complete steps only works in the STATUS phase", this->name.c_str());
} }
this->cur_state = SeqState::RCV_STATUS; this->seq_step = 0;
this->cmd_steps = complete_steps_desc;
this->cur_state = this->cmd_steps->next_step;
this->sequencer(); this->sequencer();
break; break;
case CMD_MSG_ACCEPTED: case CMD_MSG_ACCEPTED:
// Don't release ACK if ATN is asserted.
// Executing this command with ATN true means that
// the initiator wants to reject the current message.
// That should be recognized and handled by the target.
if (!this->bus_obj->test_ctrl_lines(SCSI_CTRL_ATN))
this->bus_obj->release_ctrl_line(this->my_bus_id, SCSI_CTRL_ACK);
if (this->is_initiator) { if (this->is_initiator) {
this->bus_obj->target_next_step(); this->bus_obj->target_next_step();
} }
// SCSI Manager expects this function to generate an interrupt. this->bus_obj->release_ctrl_line(this->my_bus_id, SCSI_CTRL_ACK);
// Don't set INTSTAT_SR or INISTAT_SO bits - that will confuse this->int_status = INTSTAT_DIS; // TODO: handle target disconnection properly
// the SCSI driver in Open Firmware! this->update_irq();
// Let's hope the target hung up already causing INTSTAT_DIS to be set.
exec_next_command();
break;
case CMD_XFER_PAD_BYTES:
if (this->bus_obj->current_phase() != ScsiPhase::COMMAND)
ABORT_F("%s: unsupported phase %d in CMD_XFER_PAD_BYTES",
this->name.c_str(), this->bus_obj->current_phase());
std::memset(this->data_fifo, 0, DATA_FIFO_MAX);
// FIXME: does the non-DMA version of this command use the transfer counter?
this->data_fifo_pos = std::min((int)this->set_xfer_count, DATA_FIFO_MAX);
this->cur_state = SeqState::SEND_CMD;
this->sequencer();
if (this->bus_obj->current_phase() != ScsiPhase::COMMAND) {
this->int_status |= INTSTAT_SR;
this->update_irq();
exec_next_command();
}
break;
case CMD_RESET_ATN:
this->bus_obj->release_ctrl_line(this->my_bus_id, SCSI_CTRL_ATN);
exec_next_command(); exec_next_command();
break; break;
case CMD_SELECT_NO_ATN: case CMD_SELECT_NO_ATN:
static SeqDesc * sel_no_atn_desc = new SeqDesc[2]{ static SeqDesc * sel_no_atn_desc = new SeqDesc[3]{
{2, ScsiPhase::COMMAND, SeqState::SEND_CMD, INTSTAT_SR | INTSTAT_SO}, {(CMD_SELECT_NO_ATN << 8) + 1, SeqState::SEL_BEGIN, 0, INTSTAT_DIS },
{4, -1, SeqState::CMD_COMPLETE, INTSTAT_SR | INTSTAT_SO}, {(CMD_SELECT_NO_ATN << 8) + 2, SeqState::SEND_CMD, 3, INTSTAT_SR | INTSTAT_SO},
{(CMD_SELECT_NO_ATN << 8) + 3, SeqState::CMD_COMPLETE, 4, INTSTAT_SR | INTSTAT_SO},
}; };
this->seq_step = this->cur_step = 0; this->seq_step = 0;
this->cmd_steps = sel_no_atn_desc; this->cmd_steps = sel_no_atn_desc;
this->cur_state = SeqState::BUS_FREE; this->cur_state = SeqState::BUS_FREE;
this->sequencer(); this->sequencer();
LOG_F(9, "%s: SELECT W/O ATN command started", this->name.c_str()); LOG_F(9, "%s: SELECT W/O ATN command started", this->name.c_str());
break; break;
case CMD_SELECT_WITH_ATN: case CMD_SELECT_WITH_ATN:
static SeqDesc * sel_with_atn_desc = new SeqDesc[3]{ static SeqDesc * sel_with_atn_desc = new SeqDesc[4]{
{0, ScsiPhase::MESSAGE_OUT, SeqState::SEND_MSG, INTSTAT_SR | INTSTAT_SO}, {(CMD_SELECT_WITH_ATN << 8) + 1, SeqState::SEL_BEGIN, 0, INTSTAT_DIS },
{2, ScsiPhase::COMMAND, SeqState::SEND_CMD, INTSTAT_SR | INTSTAT_SO}, {(CMD_SELECT_WITH_ATN << 8) + 2, SeqState::SEND_MSG, 2, INTSTAT_SR | INTSTAT_SO},
{4, -1, SeqState::CMD_COMPLETE, INTSTAT_SR | INTSTAT_SO}, {(CMD_SELECT_WITH_ATN << 8) + 3, SeqState::SEND_CMD, 3, INTSTAT_SR | INTSTAT_SO},
{(CMD_SELECT_WITH_ATN << 8) + 4, SeqState::CMD_COMPLETE, 4, INTSTAT_SR | INTSTAT_SO},
}; };
this->seq_step = this->cur_step = 0; this->seq_step = 0;
this->bytes_out = 1; // set message length this->bytes_out = 1; // set message length
this->cmd_steps = sel_with_atn_desc; this->cmd_steps = sel_with_atn_desc;
this->cur_state = SeqState::BUS_FREE; this->cur_state = SeqState::BUS_FREE;
this->sequencer(); this->sequencer();
LOG_F(9, "%s: SELECT WITH ATN command started", this->name.c_str()); LOG_F(9, "%s: SELECT WITH ATN command started", this->name.c_str());
break; break;
case CMD_SELECT_WITH_ATN_AND_STOP:
static SeqDesc * sel_with_atn_stop_desc = new SeqDesc[3]{
{0, ScsiPhase::MESSAGE_OUT, SeqState::SEND_MSG_EX, INTSTAT_SR | INTSTAT_SO},
{1, -1, SeqState::CMD_COMPLETE, INTSTAT_SR | INTSTAT_SO},
};
this->seq_step = this->cur_step = 0;
this->bytes_out = 1; // set message length
this->cmd_steps = sel_with_atn_stop_desc;
this->cur_state = SeqState::BUS_FREE;
this->sequencer();
LOG_F(9, "%s: SELECT WITH ATN AND STOP command started", this->name.c_str());
break;
case CMD_ENA_SEL_RESEL: case CMD_ENA_SEL_RESEL:
exec_next_command(); exec_next_command();
break; break;
@@ -449,6 +380,8 @@ void Sc53C94::exec_next_command()
} }
} }
#define DATA_FIFO_MAX 16
void Sc53C94::fifo_push(const uint8_t data) void Sc53C94::fifo_push(const uint8_t data)
{ {
if (this->data_fifo_pos < DATA_FIFO_MAX) { if (this->data_fifo_pos < DATA_FIFO_MAX) {
@@ -477,29 +410,19 @@ uint8_t Sc53C94::fifo_pop()
void Sc53C94::seq_defer_state(uint64_t delay_ns) void Sc53C94::seq_defer_state(uint64_t delay_ns)
{ {
if (this->seq_timer.active) { if (seq_timer_id) {
TimerManager::get_instance()->cancel_timer(this->seq_timer); TimerManager::get_instance()->cancel_timer(this->seq_timer_id);
this->seq_timer.active = 0; seq_timer_id = 0;
} }
if (delay_ns) { seq_timer_id = TimerManager::get_instance()->add_oneshot_timer(
TimerManager::get_instance()->add_oneshot_timer(this->seq_timer, delay_ns,
delay_ns, [this]() {
[this](uint64_t, uint64_t) { // re-enter the sequencer with the state specified in next_state
// re-enter the sequencer with the state specified in next_state this->seq_timer_id = 0;
this->seq_timer.active = 0; this->cur_state = this->next_state;
this->cur_state = this->next_state; this->sequencer();
this->sequencer(); });
});
} else {
TimerManager::get_instance()->add_immediate_timer(this->seq_timer,
[this](uint64_t, uint64_t) {
// re-enter the sequencer with the state specified in next_state
this->seq_timer.active = 0;
this->cur_state = this->next_state;
this->sequencer();
});
}
} }
void Sc53C94::sequencer() void Sc53C94::sequencer()
@@ -529,7 +452,7 @@ void Sc53C94::sequencer()
break; break;
case SeqState::ARB_END: case SeqState::ARB_END:
if (this->bus_obj->end_arbitration(this->my_bus_id)) { // arbitration won if (this->bus_obj->end_arbitration(this->my_bus_id)) { // arbitration won
this->next_state = SeqState::SEL_BEGIN; this->next_state = this->cmd_steps->next_step;
this->seq_defer_state(BUS_CLEAR_DELAY + BUS_SETTLE_DELAY); this->seq_defer_state(BUS_CLEAR_DELAY + BUS_SETTLE_DELAY);
} else { // arbitration lost } else { // arbitration lost
LOG_F(INFO, "%s: arbitration lost!", this->name.c_str()); LOG_F(INFO, "%s: arbitration lost!", this->name.c_str());
@@ -550,8 +473,8 @@ void Sc53C94::sequencer()
this->bus_obj->release_ctrl_line(this->my_bus_id, SCSI_CTRL_SEL); this->bus_obj->release_ctrl_line(this->my_bus_id, SCSI_CTRL_SEL);
LOG_F(9, "%s: selection completed", this->name.c_str()); LOG_F(9, "%s: selection completed", this->name.c_str());
} else { // selection timeout } else { // selection timeout
this->seq_step = 0; this->seq_step = this->cmd_steps->step_num;
this->int_status = INTSTAT_DIS; this->int_status = this->cmd_steps->status;
this->bus_obj->disconnect(this->my_bus_id); this->bus_obj->disconnect(this->my_bus_id);
this->cur_state = SeqState::IDLE; this->cur_state = SeqState::IDLE;
this->update_irq(); this->update_irq();
@@ -559,85 +482,62 @@ void Sc53C94::sequencer()
} }
break; break;
case SeqState::SEND_MSG: 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->data_fifo_pos < 1 && this->is_dma_cmd) {
if (this->drq_cb) if (this->drq_cb)
this->drq_cb(1); this->drq_cb(1);
} else { this->int_status = INTSTAT_SR;
this->bus_obj->target_xfer_data(); this->update_irq();
if (this->cur_state == SeqState::SEND_MSG_EX) { break;
this->notify(ScsiNotification::BUS_PHASE_CHANGE, ScsiPhase::MESSAGE_OUT);
} else {
this->bus_obj->release_ctrl_line(this->my_bus_id, SCSI_CTRL_ATN);
if (this->cmd_steps)
this->bus_obj->target_next_step();
}
} }
this->bus_obj->target_xfer_data();
this->bus_obj->release_ctrl_line(this->my_bus_id, SCSI_CTRL_ATN);
break; break;
case SeqState::SEND_CMD: case SeqState::SEND_CMD:
this->is_dma_xfer = this->is_dma_cmd;
if (this->data_fifo_pos < 1 && this->is_dma_cmd) { if (this->data_fifo_pos < 1 && this->is_dma_cmd) {
if (this->drq_cb) if (this->drq_cb)
this->drq_cb(1); this->drq_cb(1);
} else this->int_status |= INTSTAT_SR;
this->bus_obj->target_xfer_data(); this->update_irq();
break;
}
this->bus_obj->target_xfer_data();
break; break;
case SeqState::CMD_COMPLETE: case SeqState::CMD_COMPLETE:
this->is_dma_xfer = false; this->seq_step = this->cmd_steps->step_num;
this->int_status = this->cmd_steps->status;
this->cur_state = SeqState::IDLE; this->cur_state = SeqState::IDLE;
this->update_phase_latch();
this->update_irq(); this->update_irq();
exec_next_command(); exec_next_command();
break; break;
case SeqState::XFER_BEGIN: case SeqState::XFER_BEGIN:
this->is_dma_xfer = this->is_dma_cmd;
this->cur_bus_phase = this->bus_obj->current_phase(); this->cur_bus_phase = this->bus_obj->current_phase();
switch (this->cur_bus_phase) { switch (this->cur_bus_phase) {
case ScsiPhase::DATA_OUT: case ScsiPhase::DATA_OUT:
if (this->is_dma_cmd) { if (this->is_dma_cmd) {
if (this->channel_obj->dma_is_ready()) this->cur_state = SeqState::SEND_DATA;
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();
}
break;
case ScsiPhase::DATA_IN:
if (this->is_dma_cmd && this->channel_obj->dma_is_ready()) {
this->channel_obj->xfer_retry();
break; break;
} }
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:
this->bus_obj->negotiate_xfer(this->data_fifo_pos, this->bytes_out);
this->cur_state = SeqState::RCV_DATA; this->cur_state = SeqState::RCV_DATA;
this->rcv_data(); this->rcv_data();
if (!(this->is_dma_cmd)) { if (!(this->is_dma_cmd)) {
this->cur_state = SeqState::XFER_END; this->cur_state = SeqState::XFER_END;
this->sequencer(); this->sequencer();
} }
break;
case ScsiPhase::MESSAGE_IN:
case ScsiPhase::MESSAGE_OUT:
this->cur_state = (this->cur_bus_phase == ScsiPhase::MESSAGE_OUT) ?
SeqState::SEND_MSG : SeqState::RCV_MESSAGE;
this->sequencer();
this->cur_state = SeqState::XFER_END;
this->sequencer();
break;
default:
ABORT_F("%s: unsupported phase %d in XFER_BEGIN", this->name.c_str(),
this->cur_bus_phase);
} }
break; break;
case SeqState::XFER_END: case SeqState::XFER_END:
this->is_dma_xfer = false;
if (this->is_initiator) { if (this->is_initiator) {
this->bus_obj->target_next_step(); this->bus_obj->target_next_step();
} }
this->cur_state = SeqState::IDLE;
this->update_phase_latch();
this->int_status = INTSTAT_SR; this->int_status = INTSTAT_SR;
this->cur_state = SeqState::IDLE;
this->update_irq(); this->update_irq();
exec_next_command(); exec_next_command();
break; break;
@@ -650,29 +550,21 @@ void Sc53C94::sequencer()
this->int_status = INTSTAT_SR; this->int_status = INTSTAT_SR;
this->update_irq(); this->update_irq();
} else { } else {
this->is_dma_xfer = this->is_dma_cmd;
this->rcv_data(); this->rcv_data();
} }
break; break;
case SeqState::RCV_STATUS: case SeqState::RCV_STATUS:
case SeqState::RCV_MESSAGE: case SeqState::RCV_MESSAGE:
this->is_dma_xfer = this->is_dma_cmd; this->bus_obj->negotiate_xfer(this->data_fifo_pos, this->bytes_out);
this->rcv_data(); this->rcv_data();
if (this->is_initiator) { if (this->is_initiator) {
if (this->cur_state == SeqState::RCV_STATUS) { if (this->cur_state == SeqState::RCV_STATUS) {
this->bus_obj->target_next_step(); this->bus_obj->target_next_step();
if (this->cur_bus_phase == ScsiPhase::MESSAGE_IN) {
this->bus_obj->assert_ctrl_line(this->my_bus_id, SCSI_CTRL_REQ);
this->cur_state = SeqState::RCV_MESSAGE;
this->sequencer();
}
} else if (this->cur_state == SeqState::RCV_MESSAGE) { } else if (this->cur_state == SeqState::RCV_MESSAGE) {
this->bus_obj->assert_ctrl_line(this->my_bus_id, SCSI_CTRL_ACK); this->bus_obj->assert_ctrl_line(this->my_bus_id, SCSI_CTRL_ACK);
if (this->cur_cmd == CMD_COMPLETE_STEPS) { this->cmd_steps++;
this->int_status = INTSTAT_SO; this->cur_state = this->cmd_steps->next_step;
this->cur_state = SeqState::CMD_COMPLETE; this->sequencer();
this->sequencer();
}
} }
} }
break; break;
@@ -691,61 +583,32 @@ void Sc53C94::update_irq()
} }
} }
void Sc53C94::update_phase_latch() { void Sc53C94::notify(ScsiMsg msg_type, int param)
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) { switch (msg_type) {
case ScsiNotification::CONFIRM_SEL: case ScsiMsg::CONFIRM_SEL:
if (this->target_id == param) { if (this->target_id == param) {
// cancel selection timeout timer // cancel selection timeout timer
TimerManager::get_instance()->cancel_timer(this->seq_timer); TimerManager::get_instance()->cancel_timer(this->seq_timer_id);
this->seq_timer.active = 0; seq_timer_id = 0;
this->cur_state = SeqState::SEL_END; this->cur_state = SeqState::SEL_END;
this->sequencer(); this->sequencer();
} else { } else {
LOG_F(WARNING, "%s: invalid selection confirmation message ignored", LOG_F(WARNING, "%s: ignore invalid selection confirmation message",
this->name.c_str()); this->name.c_str());
} }
break; break;
case ScsiNotification::BUS_PHASE_CHANGE: case ScsiMsg::BUS_PHASE_CHANGE:
this->cur_bus_phase = param; this->cur_bus_phase = param;
if (param == ScsiPhase::BUS_FREE) { // target want to disconnect if (param != ScsiPhase::BUS_FREE && this->cmd_steps != nullptr) {
this->int_status = INTSTAT_DIS; this->cmd_steps++;
this->update_irq(); this->cur_state = this->cmd_steps->next_step;
this->cur_state = SeqState::IDLE; this->sequencer();
}
if (this->cmd_steps != nullptr) {
if (this->cur_bus_phase == this->cmd_steps->expected_phase) {
this->next_state = this->cmd_steps->next_state;
this->cmd_steps++;
this->seq_defer_state(0);
} else {
this->cur_step = this->cmd_steps->step_num;
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) {
this->update_phase_latch();
this->exec_next_command();
}
}
} }
break; break;
default: default:
LOG_F(9, "%s: ignore notification message, type: %d", this->name.c_str(), LOG_F(9, "%s: ignore notification message, type: %d", this->name.c_str(),
notif_type); msg_type);
} }
} }
@@ -765,7 +628,8 @@ int Sc53C94::send_data(uint8_t* dst_ptr, int count)
if (this->data_fifo_pos > 0) { if (this->data_fifo_pos > 0) {
std::memmove(this->data_fifo, &this->data_fifo[actual_count], this->data_fifo_pos); std::memmove(this->data_fifo, &this->data_fifo[actual_count], this->data_fifo_pos);
} else if (this->cur_bus_phase == ScsiPhase::DATA_OUT) { } else if (this->cur_bus_phase == ScsiPhase::DATA_OUT) {
ABORT_F("%s: don't know what to do next!", this->name.c_str()); this->cmd_steps++;
this->cur_state = this->cmd_steps->next_step;
this->sequencer(); this->sequencer();
} }
@@ -792,56 +656,134 @@ bool Sc53C94::rcv_data()
return true; return true;
} }
int Sc53C94::xfer_from(DmaChannel *ch_obj, uint8_t *buf, int len) { void Sc53C94::real_dma_xfer_out()
int bytes_moved = 0; {
// transfer data from host's memory to target
if (this->cur_cmd != CMD_XFER || !this->is_dma_cmd || if (this->xfer_count) {
this->cur_bus_phase != ScsiPhase::DATA_IN) { uint32_t got_bytes;
LOG_F(9, "%s: ignoring DMA data transfer request", this->name.c_str()); uint8_t* src_ptr;
return 0; 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();
}
} }
len = std::min(len, (int)(this->xfer_count)); 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) {
if (len > this->xfer_count + this->data_fifo_pos)
LOG_F(WARNING, "%s: DMA xfer len > command xfer len", this->name.c_str());
// see if there are data bytes in the FIFO we want to grab first
if (this->data_fifo_pos) { if (this->data_fifo_pos) {
int fifo_bytes = std::min(this->data_fifo_pos, len); int fifo_bytes = std::min(this->data_fifo_pos, len);
std::memcpy(buf, this->data_fifo, fifo_bytes); std::memcpy(buf, this->data_fifo, fifo_bytes);
this->data_fifo_pos -= fifo_bytes; this->data_fifo_pos -= fifo_bytes;
this->xfer_count -= fifo_bytes; this->xfer_count -= fifo_bytes;
len -= fifo_bytes; len -= fifo_bytes;
bytes_moved += fifo_bytes;
buf += fifo_bytes; buf += fifo_bytes;
if (!this->xfer_count) { if (!this->xfer_count) {
this->status |= STAT_TC; // signal zero transfer count this->status |= STAT_TC; // signal zero transfer count
this->cur_state = SeqState::XFER_END; this->cur_state = SeqState::XFER_END;
this->sequencer(); this->sequencer();
return bytes_moved; return 0;
} }
} }
if (this->bus_obj->pull_data(this->target_id, buf, len)) { if (this->bus_obj->pull_data(this->target_id, buf, this->xfer_count)) {
bytes_moved += len; this->xfer_count = 0;
this->xfer_count -= len; this->status |= STAT_TC; // signal zero transfer count
if (!this->xfer_count) { this->cur_state = SeqState::XFER_END;
this->status |= STAT_TC; // signal zero transfer count this->sequencer();
this->cur_state = SeqState::XFER_END;
this->sequencer();
}
}
return bytes_moved;
}
int Sc53C94::xfer_to(DmaChannel *ch_obj, uint8_t *buf, int len) {
int bytes_moved = 0;
if (!this->xfer_count || !this->is_dma_xfer) {
LOG_F(9, "%s: ignoring DMA data transfer request", this->name.c_str());
return 0; return 0;
} }
len = std::min(len, (int)(this->xfer_count)); return len;
}
int Sc53C94::xfer_to(uint8_t *buf, int len) {
if (!this->xfer_count)
return len;
// Being in the DATA_OUT phase means that we're about to move // Being in the DATA_OUT phase means that we're about to move
// a big chunk of data. The real device uses its FIFO as buffer. // a big chunk of data. The real device uses its FIFO as buffer.
@@ -850,7 +792,6 @@ int Sc53C94::xfer_to(DmaChannel *ch_obj, uint8_t *buf, int len) {
if (this->cur_bus_phase == ScsiPhase::DATA_OUT) { if (this->cur_bus_phase == ScsiPhase::DATA_OUT) {
if (this->bus_obj->push_data(this->target_id, buf, len)) { if (this->bus_obj->push_data(this->target_id, buf, len)) {
this->xfer_count -= len; this->xfer_count -= len;
bytes_moved += len;
if (!this->xfer_count) { if (!this->xfer_count) {
this->status |= STAT_TC; // signal zero transfer count this->status |= STAT_TC; // signal zero transfer count
this->cur_state = SeqState::XFER_END; this->cur_state = SeqState::XFER_END;
@@ -865,16 +806,16 @@ int Sc53C94::xfer_to(DmaChannel *ch_obj, uint8_t *buf, int len) {
// fill in the data FIFO first // fill in the data FIFO first
uint32_t fifo_bytes = std::min(len, DATA_FIFO_MAX - this->data_fifo_pos); uint32_t fifo_bytes = std::min(len, DATA_FIFO_MAX - this->data_fifo_pos);
std::memcpy(&this->data_fifo[this->data_fifo_pos], buf, fifo_bytes); std::memcpy(&this->data_fifo[this->data_fifo_pos], buf, fifo_bytes);
len -= fifo_bytes;
this->data_fifo_pos += fifo_bytes; this->data_fifo_pos += fifo_bytes;
this->xfer_count -= fifo_bytes; this->xfer_count -= fifo_bytes;
bytes_moved += fifo_bytes;
if (!this->xfer_count) { if (!this->xfer_count) {
this->status |= STAT_TC; // signal zero transfer count this->status |= STAT_TC; // signal zero transfer count
this->sequencer(); this->sequencer();
} }
} }
return bytes_moved; return len;
} }
static const PropMap Sc53C94_properties = { static const PropMap Sc53C94_properties = {
@@ -882,12 +823,8 @@ static const PropMap Sc53C94_properties = {
{"cdr_img", new StrProperty("")}, {"cdr_img", new StrProperty("")},
}; };
static const std::vector<std::string> Sc53C94_Subdevices = {
"ScsiCurio"
};
static const DeviceDescription Sc53C94_Descriptor = { static const DeviceDescription Sc53C94_Descriptor = {
Sc53C94::create, Sc53C94_Subdevices, Sc53C94_properties, HWCompType::SCSI_HOST | HWCompType::SCSI_DEV Sc53C94::create, {}, Sc53C94_properties
}; };
REGISTER_DEVICE(Sc53C94, Sc53C94_Descriptor); REGISTER_DEVICE(Sc53C94, Sc53C94_Descriptor);
+58 -58
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -29,7 +29,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef SC_53C94_H #ifndef SC_53C94_H
#define SC_53C94_H #define SC_53C94_H
#include <core/timermanager.h>
#include <devices/common/scsi/scsi.h> #include <devices/common/scsi/scsi.h>
#include <devices/common/dbdma.h> #include <devices/common/dbdma.h>
@@ -55,11 +54,11 @@ namespace Read {
// //
Config_2 = 0xB, // Control Register 2 Config_2 = 0xB, // Control Register 2
Config_3 = 0xC, // Control Register 3 Config_3 = 0xC, // Control Register 3
Config_4 = 0xD, // Control Register 4 ; Am53CF94 extension Config_4 = 0xD, // Control Register 4
Xfer_Cnt_Hi = 0xE, // Current Transfer Count Register High ; Am53CF94 extension Xfer_Cnt_Hi = 0xE, // Current Transfer Count Register High ; Am53CF94 extension
// //
}; };
} };
/** 53C94 write registers */ /** 53C94 write registers */
namespace Write { namespace Write {
@@ -81,7 +80,7 @@ namespace Write {
Xfer_Cnt_Hi = 0xE, // Start Transfer Count Register High ; Am53CF94 extension Xfer_Cnt_Hi = 0xE, // Start Transfer Count Register High ; Am53CF94 extension
Data_Align = 0xF, // Data Alignment Register Data_Align = 0xF, // Data Alignment Register
}; };
} };
/** NCR53C94/Am53CF94 commands. */ /** NCR53C94/Am53CF94 commands. */
enum { enum {
@@ -95,9 +94,9 @@ enum {
CMD_XFER = 0x10, CMD_XFER = 0x10,
CMD_COMPLETE_STEPS = 0x11, CMD_COMPLETE_STEPS = 0x11,
CMD_MSG_ACCEPTED = 0x12, CMD_MSG_ACCEPTED = 0x12,
CMD_XFER_PAD_BYTES = 0x18, //CMD_TRANSFER_PAD_BYTES = 0x18,
CMD_SET_ATN = 0x1A, // no interrupt CMD_SET_ATN = 0x1A, // no interrupt
CMD_RESET_ATN = 0x1B, // no interrupt //CMD_RESET_ATN = 0x1B, // no interrupt
// Target commands // Target commands
//CMD_SEND_MESSAGE = 0x20, //CMD_SEND_MESSAGE = 0x20,
@@ -112,13 +111,13 @@ enum {
//CMD_RECEIVE_DATA = 0x2A, //CMD_RECEIVE_DATA = 0x2A,
//CMD_RECEIVE_COMMAND_STEPS = 0x2B, //CMD_RECEIVE_COMMAND_STEPS = 0x2B,
CMD_DMA_STOP = 0x04, // no interrupt CMD_DMA_STOP = 0x04, // no interrupt
//CMD_ACCESS_FIFO_COMMAND = 0x05, CMD_ACCESS_FIFO_COMMAND = 0x05,
// Idle Commands // Idle Commands
//CMD_RESELECT_STEPS = 0x40, //CMD_RESELECT_STEPS = 0x40,
CMD_SELECT_NO_ATN = 0x41, CMD_SELECT_NO_ATN = 0x41,
CMD_SELECT_WITH_ATN = 0x42, CMD_SELECT_WITH_ATN = 0x42,
CMD_SELECT_WITH_ATN_AND_STOP = 0x43, //CMD_SELECT_WITH_ATN_AND_STOP = 0x43,
CMD_ENA_SEL_RESEL = 0x44, // no interrupt CMD_ENA_SEL_RESEL = 0x44, // no interrupt
//CMD_DISABLE_SEL_RESEL = 0x45, //CMD_DISABLE_SEL_RESEL = 0x45,
//CMD_SELECT_WITH_ATN3_STEPS = 0x46, //CMD_SELECT_WITH_ATN3_STEPS = 0x46,
@@ -129,12 +128,14 @@ enum {
CMD_ISDMA = 0x80, CMD_ISDMA = 0x80,
}; };
/** Status register bits. */ /** Status register bits. **/
enum { enum {
STAT_PHASE_MASK = 0x07, // mask for I/O, Command and Message bits //SCSI_CTRL_IO = 0x01, // Input/Output
STAT_GCV = 0x08, // Group Code Valid //SCSI_CTRL_CD = 0x02, // Command/Data
//SCSI_CTRL_MSG = 0x04, // Message
//STAT_GCV = 0x08, // Group Code Valid
STAT_TC = 0x10, // Terminal count (NCR) / count to zero (AMD) STAT_TC = 0x10, // Terminal count (NCR) / count to zero (AMD)
STAT_PE = 0x20, // Parity Error //STAT_PE = 0x20, // Parity Error
STAT_GE = 0x40, // Gross Error (NCR) / Illegal Operation Error (AMD) STAT_GE = 0x40, // Gross Error (NCR) / Illegal Operation Error (AMD)
STAT_INT = 0x80, // Interrupt STAT_INT = 0x80, // Interrupt
}; };
@@ -151,16 +152,8 @@ enum {
INTSTAT_SEL = 0x01, // selected as a target without attention INTSTAT_SEL = 0x01, // selected as a target without attention
}; };
/** Configuration register 1 bit definitions. */ enum {
enum : uint8_t { CFG2_ENF = 0x40, // Am53CF94: enable features (ENF) bit
CFG1_DISR = 0x40, // disable interrupt on SCSI reset
};
/** 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. */ /** Sequencer states. */
@@ -173,7 +166,6 @@ namespace SeqState {
SEL_BEGIN, SEL_BEGIN,
SEL_END, SEL_END,
SEND_MSG, SEND_MSG,
SEND_MSG_EX,
SEND_CMD, SEND_CMD,
CMD_COMPLETE, CMD_COMPLETE,
XFER_BEGIN, XFER_BEGIN,
@@ -183,21 +175,19 @@ namespace SeqState {
RCV_STATUS, RCV_STATUS,
RCV_MESSAGE, RCV_MESSAGE,
}; };
} };
constexpr auto DATA_FIFO_MAX = 16; /** Sequence descriptor for sequencer commands. */
/** Sequence descriptor for multistep commands. */
typedef struct { typedef struct {
int seq_id;
int next_step;
int step_num; int step_num;
int expected_phase;
int next_state;
int status; int status;
} SeqDesc; } SeqDesc;
typedef std::function<void(const uint8_t drq_state)> DrqCb; typedef std::function<void(const uint8_t drq_state)> DrqCb;
class Sc53C94 : public ScsiPhysDevice, public DmaDevice { class Sc53C94 : public ScsiDevice, public DmaDevice {
public: public:
Sc53C94(uint8_t chip_id=12, uint8_t my_id=7); Sc53C94(uint8_t chip_id=12, uint8_t my_id=7);
~Sc53C94() = default; ~Sc53C94() = default;
@@ -207,7 +197,7 @@ public:
} }
// HWComponent methods // HWComponent methods
int device_postinit() override; int device_postinit();
// 53C94 registers access // 53C94 registers access
uint8_t read(uint8_t reg_offset); uint8_t read(uint8_t reg_offset);
@@ -215,27 +205,43 @@ public:
uint16_t pseudo_dma_read(); uint16_t pseudo_dma_read();
void pseudo_dma_write(uint16_t data); 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) { void set_drq_callback(DrqCb cb) {
this->drq_cb = cb; this->drq_cb = cb;
} }
// ScsiPhysDevice methods // ScsiDevice methods
void notify(ScsiNotification notif_type, int param) override; void notify(ScsiMsg msg_type, int param);
bool has_data() override { return this->data_fifo_pos != 0; } bool prepare_data() { return false; };
int send_data(uint8_t* dst_ptr, int count) override; bool get_more_data() { return false; };
void process_command() override {} bool has_data() { return this->data_fifo_pos != 0; };
int send_data(uint8_t* dst_ptr, int count);
void process_command() {};
// DmaDevice methods // DmaChannel methods
int xfer_from(DmaChannel *ch_obj, uint8_t *buf, int len) override; int xfer_from(uint8_t *buf, int len); // Must be marked override!
int xfer_to(DmaChannel *ch_obj, uint8_t *buf, int len) override; int xfer_to(uint8_t *buf, int len); // Must be marked override!
int tell_xfer_size(DmaChannel *ch_obj) override {
return this->xfer_count;
}
protected: protected:
void reset_device(); void reset_device();
void update_command_reg(uint8_t cmd); void update_command_reg(uint8_t cmd);
void update_phase_latch();
void exec_command(); void exec_command();
void exec_next_command(); void exec_next_command();
void fifo_push(const uint8_t data); void fifo_push(const uint8_t data);
@@ -251,10 +257,10 @@ protected:
private: private:
uint8_t chip_id = 0; uint8_t chip_id = 0;
uint8_t my_bus_id = 0; uint8_t my_bus_id = 0;
TimerInfo my_timer; uint32_t my_timer_id = 0;
uint8_t cmd_fifo[2]; uint8_t cmd_fifo[2];
uint8_t data_fifo[DATA_FIFO_MAX]; uint8_t data_fifo[16];
int cmd_fifo_pos = 0; int cmd_fifo_pos = 0;
int data_fifo_pos = 0; int data_fifo_pos = 0;
int bytes_out = 0; int bytes_out = 0;
@@ -266,37 +272,31 @@ private:
uint8_t int_status = 0; uint8_t int_status = 0;
uint8_t seq_step = 0; uint8_t seq_step = 0;
uint8_t sel_timeout = 0; uint8_t sel_timeout = 0;
uint8_t sync_period = 5;
uint8_t sync_offset = 0; uint8_t sync_offset = 0;
uint8_t clk_factor = 0; uint8_t clk_factor = 0;
uint8_t config1 = 0; uint8_t config1 = 0;
uint8_t config2 = 0; uint8_t config2 = 0;
uint8_t config3 = 0; uint8_t config3 = 0;
uint8_t config4 = 0;
// bus phase latch
bool phase_latch_closed = false;
uint8_t phase_latch = 0;
// sequencer state // sequencer state
TimerInfo seq_timer; uint32_t seq_timer_id = 0;
uint32_t cur_state = 0; uint32_t cur_state = 0;
uint32_t next_state = 0; uint32_t next_state = 0;
SeqDesc* cmd_steps = nullptr; SeqDesc* cmd_steps = nullptr;
bool is_initiator = false; bool is_initiator = false;
uint8_t cur_cmd = 0; uint8_t cur_cmd = 0;
bool is_dma_cmd = false; bool is_dma_cmd = false;
bool is_dma_xfer = false;
int cur_bus_phase = 0; int cur_bus_phase = 0;
uint8_t cur_step = 0; // internal step counter for multistep commands
// interrupt related stuff // interrupt related stuff
InterruptCtrl* int_ctrl = nullptr; InterruptCtrl* int_ctrl = nullptr;
uint64_t irq_id = 0; uint32_t irq_id = 0;
uint8_t irq = 0; uint8_t irq = 0;
// DMA related stuff // DMA related stuff
DmaBidirChannel* dma_ch = nullptr;
DrqCb drq_cb = nullptr; DrqCb drq_cb = nullptr;
uint32_t dma_timer_id = 0;
}; };
#endif // SC_53C94_H #endif // SC_53C94_H
+57 -211
View File
@@ -1,9 +1,9 @@
/* /*
DingusPPC - The Experimental PowerPC Macintosh emulator DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team Copyright (C) 2018-24 divingkatae and maximum
(See CREDITS.MD for more details) (theweirdo) spatium
(You may also contact divingkxt or powermax2286 on Discord) (Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@@ -24,9 +24,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef SCSI_H #ifndef SCSI_H
#define SCSI_H #define SCSI_H
#include <core/timermanager.h>
#include <devices/common/hwcomponent.h> #include <devices/common/hwcomponent.h>
#include <devices/common/scsi/scsiphysinterface.h>
#include <array> #include <array>
#include <cinttypes> #include <cinttypes>
@@ -49,7 +47,6 @@ enum {
SCSI_CTRL_RST = 1 << 15, SCSI_CTRL_RST = 1 << 15,
}; };
/** SCSI bus phases. */
namespace ScsiPhase { namespace ScsiPhase {
enum : int { enum : int {
BUS_FREE = 0, BUS_FREE = 0,
@@ -64,70 +61,34 @@ namespace ScsiPhase {
MESSAGE_OUT, MESSAGE_OUT,
RESET, RESET,
}; };
} };
/** SCSI status codes. */
namespace ScsiStatus { namespace ScsiStatus {
enum : uint8_t { enum : uint8_t {
GOOD = 0, GOOD = 0,
CHECK_CONDITION = 2, CHECK_CONDITION = 2,
}; };
} };
/** Standard message codes. */
namespace ScsiMessage { namespace ScsiMessage {
enum : uint8_t { enum : uint8_t {
COMMAND_COMPLETE = 0x00, COMMAND_COMPLETE = 0,
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, TARGET_ROUTINE_NUMBER_MASK = 0x07,
LOGICAL_UNIT_NUMBER_MASK = 0x07, LOGICAL_UNIT_NUMBER_MASK = 0x07,
IS_TARGET_ROUTINE_NUMBER = 0x20, IS_TARGET_ROUTINE_NuMBER = 0x20,
HAS_DISCONNECT_PRIVILEDGE = 0x40, HAS_DISCONNECT_PRIVILEDGE = 0x40,
IDENTIFY = 0x80, IDENTIFY = 0x80,
}; };
} };
/** Extended message codes. */ enum ScsiMsg : int {
namespace ScsiExtMessage {
enum : uint8_t {
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,
};
}
/** Internal notification codes for our SCSI implementation. */
enum ScsiNotification : int {
CONFIRM_SEL = 1, CONFIRM_SEL = 1,
BUS_PHASE_CHANGE, BUS_PHASE_CHANGE,
SEND_CMD_BEGIN,
SEND_CMD_END,
MESSAGE_BEGIN,
MESSAGE_END,
}; };
enum ScsiCommand : uint8_t { enum ScsiCommand : uint8_t {
@@ -135,8 +96,7 @@ enum ScsiCommand : uint8_t {
REWIND = 0x01, REWIND = 0x01,
REQ_SENSE = 0x03, REQ_SENSE = 0x03,
FORMAT_UNIT = 0x04, FORMAT_UNIT = 0x04,
READ_BLOCK_LIMITS = 0x05, READ_BLK_LIMITS = 0x05,
REASSIGN_BLOCKS = 0x07,
READ_6 = 0x08, READ_6 = 0x08,
WRITE_6 = 0x0A, WRITE_6 = 0x0A,
SEEK_6 = 0x0B, SEEK_6 = 0x0B,
@@ -147,44 +107,26 @@ enum ScsiCommand : uint8_t {
ERASE_6 = 0x19, ERASE_6 = 0x19,
MODE_SENSE_6 = 0x1A, MODE_SENSE_6 = 0x1A,
START_STOP_UNIT = 0x1B, START_STOP_UNIT = 0x1B,
RECEIVE_DIAG_RESULTS = 0x1C, DIAG_RESULTS = 0x1C,
SEND_DIAGNOSTIC = 0x1D, SEND_DIAGS = 0x1D,
PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1E, PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1E,
READ_CAPACITY = 0x25, READ_CAPACITY_10 = 0x25,
READ_10 = 0x28, READ_10 = 0x28,
WRITE_10 = 0x2A, WRITE_10 = 0x2A,
SEEK_10 = 0x2B,
WRITE_AND_VERIFY = 0x2E,
VERIFY_10 = 0x2F, VERIFY_10 = 0x2F,
SYNC_CACHE = 0x35, READ_LONG_10 = 0x35,
WRITE_BUFFER = 0x3B, WRITE_BUFFER = 0x3B,
READ_BUFFER = 0x3C, READ_BUFFER = 0x3C,
GET_CONFIG = 0x46,
GET_EVENT_STATUS_NOTIFY = 0x4A,
READ_DISC_INFO = 0x51,
MODE_SELECT_10 = 0x55,
MODE_SENSE_10 = 0x5A, MODE_SENSE_10 = 0x5A,
READ_12 = 0xA8, READ_12 = 0xA8,
WRITE_12 = 0xAA,
READ_DVD_STRUCTURE = 0xAD,
SET_SPEED = 0xBB,
// CD-ROM specific commands // CD-ROM specific commands
READ_TOC = 0x43, READ_TOC = 0x43,
SET_CD_SPEED = 0xBB, SET_CD_SPEED = 0xBB,
PLAY_CD = 0xBC,
READ_CD = 0xBE, READ_CD = 0xBE,
}; };
/** START STOP UNIT command flags in CDB byte 4. */ enum ScsiSense : int {
namespace ScsiStartStopUnit {
enum : uint8_t {
START = 1 << 0,
LOAD_EJECT = 1 << 1,
};
}
enum ScsiSense : uint8_t {
NO_SENSE = 0x0, NO_SENSE = 0x0,
RECOVERED = 0x1, RECOVERED = 0x1,
NOT_READY = 0x2, NOT_READY = 0x2,
@@ -199,7 +141,7 @@ enum ScsiSense : uint8_t {
COMPLETED = 0xF COMPLETED = 0xF
}; };
enum ScsiError : uint8_t { enum ScsiError : int {
NO_ERROR = 0x00, NO_ERROR = 0x00,
NO_SECTOR = 0x01, NO_SECTOR = 0x01,
WRITE_FAULT = 0x03, WRITE_FAULT = 0x03,
@@ -209,141 +151,57 @@ enum ScsiError : uint8_t {
INVALID_CDB = 0x24, INVALID_CDB = 0x24,
INVALID_LUN = 0x25, INVALID_LUN = 0x25,
WRITE_PROTECT = 0x27, WRITE_PROTECT = 0x27,
MEDIUM_CHANGED = 0x28,
SAVING_NOT_SUPPORTED = 0x39, SAVING_NOT_SUPPORTED = 0x39,
MEDIUM_NOT_PRESENT = 0x3A, MEDIUM_NOT_PRESENT = 0x3A,
REMOVAL_PREVENTED = 0x53,
};
/** SCSI device types used in INQUIRY. */
namespace ScsiDevType {
enum : uint8_t {
DIRECT_ACCESS = 0,
SEQ_ACCESS = 1,
PRINTER = 2,
PROCESSOR = 3,
WRITE_ONCE = 4,
CD_ROM = 5,
SCANNER = 6,
OPT_MEMORY = 7,
MEDIUM_CHANGER = 8,
COMMUNICATION = 9,
UNKNOWN = 0x1F
};
};
/** SCSI device capacity flags. */
enum : uint8_t {
CAP_REL_ADDR = 1 << 7, // device supports relative addressing
CAP_W32_XFER = 1 << 6, // device supports 32-bit wide transfers
CAP_W16_XFER = 1 << 5, // device supports 16-bit wide transfers
CAP_SYNC_XFER = 1 << 4, // device supports synchronous transfers
CAP_LINKED_CMDS = 1 << 3, // device supports linked commands
CAP_CMD_QUEUE = 1 << 1, // device supports command queuing
CAP_CMD_SRST = 1 << 0, // device supports soft resets
};
/** Page control values for MODE SENSE. */
namespace PageControl {
enum : uint8_t {
CURRENT_VALUES = 0,
CHANGEABLE_VALUES = 1,
DEFAULT_VALUES = 2,
SAVED_VALUES = 3
};
};
/** Page numbers for MODE SENSE and MODE SELECT. */
enum ModePage : uint8_t {
ERROR_RECOVERY = 0x1,
DEV_FORMAT_PARAMS = 0x3,
RIGID_DISK_GEOMETRY = 0x4,
CDROM_PARAMS = 0xD,
CDROM_AUDIO_CONTROL = 0xE,
POWER_CONDITION = 0x1A,
CDROM_CAPABILITIES = 0x2A,
VENDOR_PAGE_31 = 0x31,
ALL_PAGES = 0x3F,
}; };
/** Standard SCSI bus timing values measured in ns. */ /** Standard SCSI bus timing values measured in ns. */
constexpr uint64_t BUS_SETTLE_DELAY = 400; #define BUS_SETTLE_DELAY 400
constexpr uint64_t BUS_FREE_DELAY = 800; #define BUS_FREE_DELAY 800
constexpr uint64_t BUS_CLEAR_DELAY = 800; #define BUS_CLEAR_DELAY 800
constexpr uint64_t ARB_DELAY = 2400; #define ARB_DELAY 2400
constexpr uint64_t SEL_ABORT_TIME = 200000; #define SEL_ABORT_TIME 200000
constexpr uint64_t SEL_TIME_OUT = 250000000; #define SEL_TIME_OUT 250000000
constexpr auto SCSI_MAX_DEVS = 8; #define SCSI_MAX_DEVS 8
class ScsiBus; class ScsiBus;
class ScsiPhysDevice : public ScsiPhysInterface, public HWComponent { typedef std::function<void()> action_callback;
class ScsiDevice : public HWComponent {
public: public:
ScsiPhysDevice(std::string name, int my_id) : ScsiPhysInterface(PHY_ID_SCSI) { ScsiDevice(std::string name, int my_id) {
this->set_name(name); this->set_name(name);
supports_types(HWCompType::SCSI_DEV); supports_types(HWCompType::SCSI_DEV);
this->scsi_id = my_id; this->scsi_id = my_id;
this->lun = 0, this->lun = 0,
this->cur_phase = ScsiPhase::BUS_FREE; this->cur_phase = ScsiPhase::BUS_FREE;
} };
~ScsiPhysDevice() = default; ~ScsiDevice() = default;
// ScsiPhysInterface methods virtual void notify(ScsiMsg msg_type, int param);
bool last_sel_has_attention() override {
return this->last_selection_has_attention;
}
uint8_t last_sel_msg() override {
return this->last_selection_message;
}
void set_xfer_len(uint64_t len) override {
this->xfer_len = len;
}
void set_buffer(uint8_t *bptr) override {
this->buf_ptr = bptr;
}
void set_read_more_data_cb(more_data_cb_t cb) override {
this->read_more_data = cb;
}
void set_write_more_data_cb(more_data_cb_t cb) override {
this->write_more_data = cb;
}
void set_post_xfer_action(action_callback cb) override {
this->post_xfer_action = cb;
}
void set_status(uint8_t status_code, uint8_t sense_key) override {
this->status = status_code;
}
void set_lock_state(bool is_locked) override {
this->eject_allowed = !is_locked;
}
virtual void notify(ScsiNotification notif_type, int param);
virtual void next_step(); virtual void next_step();
virtual void prepare_xfer(); virtual void prepare_xfer(ScsiBus* bus_obj, int& bytes_in, int& bytes_out);
virtual void switch_phase(const int new_phase) override; virtual void switch_phase(const int new_phase);
virtual bool allow_phase_change();
virtual bool has_data() { return this->data_size != 0; } virtual bool has_data() { return this->data_size != 0; };
virtual int xfer_data(); virtual int xfer_data();
virtual int send_data(uint8_t* dst_ptr, int count); virtual int send_data(uint8_t* dst_ptr, int count);
virtual int rcv_data(const uint8_t* src_ptr, const int count); virtual int rcv_data(const uint8_t* src_ptr, const int count);
virtual bool check_lun();
void illegal_command(const uint8_t* cmd);
virtual bool prepare_data() = 0;
virtual bool get_more_data() = 0;
virtual void process_command() = 0; virtual void process_command() = 0;
virtual void process_message();
void set_bus_object_ptr(ScsiBus *bus_obj_ptr) { void set_bus_object_ptr(ScsiBus *bus_obj_ptr) {
this->bus_obj = bus_obj_ptr; this->bus_obj = bus_obj_ptr;
} }
void report_error(uint8_t sense_key, uint8_t asc);
protected: protected:
uint8_t cmd_buf[16] = {}; uint8_t cmd_buf[16] = {};
uint8_t msg_buf[16] = {}; // TODO: clarify how big this one should be uint8_t msg_buf[16] = {}; // TODO: clarify how big this one should be
@@ -352,26 +210,22 @@ protected:
int initiator_id; int initiator_id;
int cur_phase; int cur_phase;
uint8_t* data_ptr = nullptr; uint8_t* data_ptr = nullptr;
uint8_t* buf_ptr = nullptr;
int xfer_len;
int data_size; int data_size;
int incoming_size; int incoming_size;
uint8_t status; uint8_t status;
bool eject_allowed = true; int sense;
bool last_selection_has_attention = false; int asc;
int ascq;
int sksv;
int field;
bool last_selection_has_atention = false;
uint8_t last_selection_message = 0; uint8_t last_selection_message = 0;
ScsiBus* bus_obj; ScsiBus* bus_obj;
int *seq_steps = nullptr;
action_callback pre_xfer_action = nullptr; action_callback pre_xfer_action = nullptr;
action_callback post_xfer_action = nullptr; action_callback post_xfer_action = nullptr;
more_data_cb_t read_more_data = {};
more_data_cb_t write_more_data = {};
TimerInfo bus_settle_timer;
}; };
/** This class provides a higher level abstraction for the SCSI bus. */ /** This class provides a higher level abstraction for the SCSI bus. */
@@ -391,19 +245,10 @@ public:
void attach_scsi_devices(const std::string bus_suffix); void attach_scsi_devices(const std::string bus_suffix);
// low-level state management // low-level state management
void register_device(int id, ScsiPhysDevice* dev_obj); void register_device(int id, ScsiDevice* dev_obj);
int current_phase() { return this->cur_phase; };
int current_phase() const { int get_initiator_id() { return this->initiator_id; };
return this->cur_phase; int get_target_id() { return this->target_id; };
}
int get_initiator_id() const {
return this->initiator_id;
}
int get_target_id() const {
return this->target_id;
}
// reading/writing control lines // reading/writing control lines
void assert_ctrl_line(int id, uint16_t mask); void assert_ctrl_line(int id, uint16_t mask);
@@ -412,7 +257,7 @@ public:
uint16_t test_ctrl_lines(uint16_t mask); uint16_t test_ctrl_lines(uint16_t mask);
// reading/writing data lines // reading/writing data lines
uint8_t get_data_lines() { return this->data_lines; } uint8_t get_data_lines() { return this->data_lines; };
// high-level control/status // high-level control/status
int switch_phase(int id, int new_phase); int switch_phase(int id, int new_phase);
@@ -426,13 +271,14 @@ public:
bool push_data(const int id, const uint8_t* src_ptr, const int size); bool push_data(const int id, const uint8_t* src_ptr, const int size);
int target_xfer_data(); int target_xfer_data();
void target_next_step(); void target_next_step();
bool negotiate_xfer(int& bytes_in, int& bytes_out);
protected: protected:
void change_bus_phase(int initiator_id); void change_bus_phase(int initiator_id);
private: private:
// SCSI devices registered with this bus // SCSI devices registered with this bus
std::array<ScsiPhysDevice*, SCSI_MAX_DEVS> devices; std::array<ScsiDevice*, SCSI_MAX_DEVS> devices;
// per-device state of the control lines // per-device state of the control lines
uint16_t dev_ctrl_lines[SCSI_MAX_DEVS] = {}; uint16_t dev_ctrl_lines[SCSI_MAX_DEVS] = {};
Loaded 100 of 234 files, more files were not shown because too many files have changed in this diff. Show more