Compare commits

..
1 Commits
Author SHA1 Message Date
dingusdev 3040d86f1f Initial implementation of VERIFY 6/10 2026-07-25 15:01:30 -07:00
122 changed files with 2307 additions and 4919 deletions

No files matched your search

-6
View File
@@ -228,11 +228,6 @@ jobs:
- uses: actions/checkout@v5
with:
submodules: recursive
# Configures MSVC/Clang environment natively for all subsequent steps
- name: Setup MSVC Developer Command Prompt
uses: TheMrMilchmann/setup-msvc-dev@v4
with:
arch: x64
- name: Setup msbuild
uses: microsoft/setup-msbuild@v3
- name: Install vcpkg packages
@@ -271,7 +266,6 @@ jobs:
if %errorlevel% neq 0 echo ccache stats unavailable
- name: Test
working-directory: ${{github.workspace}}/build
shell: cmd
run: ctest -C ${{env.BUILD_TYPE}} --output-on-failure
- name: Upload logs on failure
if: failure()
+24 -29
View File
@@ -183,20 +183,13 @@ if (APPLE)
set_target_properties(dingusppc PROPERTIES
MACOSX_BUNDLE_GUI_IDENTIFIER "${BUNDLE_ID}"
MACOSX_BUNDLE_BUNDLE_NAME "DingusPPC"
MACOSX_BUNDLE_BUNDLE_VERSION "alpha 1.0.4c"
MACOSX_BUNDLE_SHORT_VERSION_STRING "a1.0.4c"
MACOSX_BUNDLE_BUNDLE_VERSION "alpha 1.0.4b"
MACOSX_BUNDLE_SHORT_VERSION_STRING "a1.0.4b"
MACOSX_BUNDLE_EXECUTABLE_NAME "DingusPPC"
# Placeholder for the icon file:
# MACOSX_BUNDLE_ICON_FILE "icon.icns"
)
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)
@@ -265,26 +258,28 @@ if (DPPC_BUILD_PPC_TESTS)
endif()
if (DPPC_BUILD_BENCHMARKS)
file(GLOB BENCH_CPU_SOURCES "${PROJECT_SOURCE_DIR}/cpu/ppc/*.cpp"
"${PROJECT_SOURCE_DIR}/cpu/ppc/*.h")
foreach(BENCHMARK bench1 bench2)
add_executable(${BENCHMARK} "benchmark/${BENCHMARK}.cpp" ${BENCH_CPU_SOURCES}
$<TARGET_OBJECTS:core>
$<TARGET_OBJECTS:debugger>
$<TARGET_OBJECTS:devices>
$<TARGET_OBJECTS:machines>
$<TARGET_OBJECTS:utils>
$<TARGET_OBJECTS:loguru>)
target_compile_definitions(${BENCHMARK} PRIVATE PPC_BENCHMARKS)
target_link_libraries(${BENCHMARK} PRIVATE cubeb SDL2::SDL2 ${CMAKE_DL_LIBS}
${CMAKE_THREAD_LIBS_INIT})
if (WIN32)
target_compile_definitions(${BENCHMARK} PRIVATE SDL_MAIN_HANDLED)
endif()
if (DPPC_68K_DEBUGGER)
target_link_libraries(${BENCHMARK} PRIVATE capstone)
endif()
endforeach()
add_compile_options("-DPPC_BENCHMARKS")
file(GLOB BENCH_SOURCES "${PROJECT_SOURCE_DIR}/benchmark/*.cpp"
"${PROJECT_SOURCE_DIR}/cpu/ppc/*.cpp"
"${PROJECT_SOURCE_DIR}/cpu/ppc/*.h"
)
add_executable(bench1 ${BENCH_SOURCES} $<TARGET_OBJECTS:core>
# $<TARGET_OBJECTS:cpu_ppc>
$<TARGET_OBJECTS:debugger>
$<TARGET_OBJECTS:devices>
$<TARGET_OBJECTS:machines>
$<TARGET_OBJECTS:utils>
$<TARGET_OBJECTS:loguru>)
target_link_libraries(bench1 PRIVATE cubeb SDL2::SDL2 ${CMAKE_DL_LIBS}
${CMAKE_THREAD_LIBS_INIT})
if (WIN32)
target_compile_definitions(bench1 PRIVATE SDL_MAIN_HANDLED)
endif()
if (DPPC_68K_DEBUGGER)
target_link_libraries(bench1 PRIVATE capstone)
endif()
endif()
if (DPPC_BUILD_PPC_TESTS)
-5
View File
@@ -4,12 +4,7 @@ General
* Test your contributions to assure they do not break existing functionality.
* Commits to the repo should be done by portions; that is, by individual functionalities of the program.
* Don't use any disrespectful language.
AI Usage
=======
* Do not use artificial intelligence to make contributions. This is due to authorship issues and licensing issues regarding AI usage.
* Do not use artificial intelligence to write up issues or pull requests.
Code
=======
-2
View File
@@ -31,7 +31,6 @@
- lefp
- mathstuf
- mrpapersonic
- probonopd
- Randrianasulu
- roytam1
- sdkmap
@@ -59,7 +58,6 @@
- Blitter.net
- Emaculation
- GitHub
- pagetable.com
- PenguinPPC
- VirtuallyFun
- The makers of Loguru, SDL2, Capstone, and CLI11
+2 -2
View File
@@ -29,10 +29,10 @@ This program currently uses the command prompt to work.
There are a few command line arguments one can enter when starting the program.
```
-r, --run
-r, --realtime
```
Run the emulator. Currently only goes to an interpreter.
Run the emulator in runtime.
```
-d, --debugger
+2 -1
View File
@@ -29,7 +29,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#if defined(PPC_BENCHMARKS)
void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
power_off(po_benchmark_exception);
power_on = false;
power_off_reason = po_benchmark_exception;
}
#endif
-119
View File
@@ -1,119 +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/>.
*/
// Replay floating-point instructions and input registers captured while BeOS
// PR1 GLTeapot renders. This measures the real opcode dispatcher and handlers,
// including FPSCR maintenance, without guest boot, display, or timer overhead.
#include <cpu/ppc/ppcemu.h>
#include <thirdparty/loguru/loguru.hpp>
#include <algorithm>
#include <cfenv>
#include <chrono>
#include <cinttypes>
#include <cstdio>
#include <cstring>
#include <vector>
#include "bench2_data.h"
#if defined(PPC_BENCHMARKS)
void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
power_off(po_benchmark_exception);
}
#endif
static void replay_sample(const FpuSample& sample) {
if ((ppc_state.fpscr ^ sample.fpscr) & FPSCR::RN_MASK)
set_host_rounding_mode(sample.fpscr & FPSCR::RN_MASK);
ppc_state.fpscr = sample.fpscr;
ppc_state.cr = sample.cr;
ppc_state.fpr[(sample.opcode >> 21) & 31].int64_r = sample.d;
ppc_state.fpr[(sample.opcode >> 16) & 31].int64_r = sample.a;
ppc_state.fpr[(sample.opcode >> 11) & 31].int64_r = sample.b;
ppc_state.fpr[(sample.opcode >> 6) & 31].int64_r = sample.c;
ppc_main_opcode(ppc_opcode_grabber, sample.opcode);
}
static uint64_t check_replay() {
uint64_t hash = 1469598103934665603ULL;
auto mix = [&hash](uint64_t value) { hash = (hash ^ value) * 1099511628211ULL; };
std::feclearexcept(FE_ALL_EXCEPT);
for (const auto& sample : fpu_samples) {
replay_sample(sample);
mix(ppc_state.fpr[(sample.opcode >> 21) & 31].int64_r);
mix(ppc_state.fpscr);
mix(ppc_state.cr);
}
return hash;
}
int main(int argc, char** argv) {
if (argc > 2 || (argc == 2 && std::strcmp(argv[1], "--check"))) {
fprintf(stderr, "Usage: %s [--check]\n", argv[0]);
return 2;
}
loguru::g_stderr_verbosity = loguru::Verbosity_ERROR;
is_601 = false;
initialize_ppc_opcode_table();
ppc_msr_did_change(ppc_state.msr, MSR::ME | MSR::IP | MSR::FP, false);
set_host_rounding_mode(0);
power_on = true;
const uint64_t expected = check_replay();
constexpr size_t sample_count = sizeof(fpu_samples) / sizeof(fpu_samples[0]);
printf("GLTeapot FPU replay: %zu samples, checksum %016" PRIx64 "\n", sample_count, expected);
if (!power_on)
return 1;
if (argc == 2 && !std::strcmp(argv[1], "--check"))
return 0;
constexpr unsigned passes = 10000;
constexpr unsigned trials = 9;
// Warm the dispatcher, handlers and captured input data.
for (unsigned pass = 0; pass < 100; pass++)
for (const auto& sample : fpu_samples)
replay_sample(sample);
std::vector<double> times;
for (unsigned trial = 0; trial < trials; trial++) {
std::feclearexcept(FE_ALL_EXCEPT);
auto start = std::chrono::steady_clock::now();
for (unsigned pass = 0; pass < passes; pass++)
for (const auto& sample : fpu_samples)
replay_sample(sample);
auto end = std::chrono::steady_clock::now();
if (!power_on || check_replay() != expected) {
fprintf(stderr, "FPU replay changed its result during timing\n");
return 1;
}
double ns = std::chrono::duration<double, std::nano>(end - start).count() /
(uint64_t(passes) * sample_count);
times.push_back(ns);
printf("Trial %u: %.3f ns/FPU instruction, %.3f million FPU instructions/s\n",
trial + 1, ns, 1000.0 / ns);
}
std::sort(times.begin(), times.end());
double median = times[times.size() / 2];
printf("Median: %.3f ns/FPU instruction, %.3f million FPU instructions/s\n",
median, 1000.0 / median);
return 0;
}
File diff suppressed because it is too large. Load diff
-70
View File
@@ -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>
+2 -2
View File
@@ -52,7 +52,7 @@ public:
}
// Calls all connected slots.
void emit(Args... args) const {
void emit(Args... args) {
if (!_is_enabled) {
return;
}
@@ -77,7 +77,7 @@ public:
_is_enabled = true;
}
bool is_enabled() const {
bool is_enabled() {
return _is_enabled;
}
-25
View File
@@ -25,7 +25,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <core/coresignal.h>
#include <cinttypes>
#include <string>
class WindowEvent {
public:
@@ -120,20 +119,6 @@ public:
uint8_t button;
};
enum class CdromInsertionResult {
SUCCESS,
NO_DRIVE,
MEDIA_PRESENT,
IMAGE_OPEN_FAILED,
};
class CdromImageEvent {
public:
std::string image_path;
CdromInsertionResult result = CdromInsertionResult::NO_DRIVE;
bool handled = false;
};
class EventManager {
public:
static EventManager* get_instance() {
@@ -146,9 +131,6 @@ public:
void poll_events();
void set_keyboard_locale(uint32_t keyboard_id);
void post_keyboard_state_events();
void post_cdrom_event(CdromImageEvent& event) {
_cdrom_signal.emit(event);
}
template <typename T>
void add_window_handler(T *inst, void (T::*func)(const WindowEvent&)) {
@@ -170,11 +152,6 @@ public:
_gamepad_signal.connect_method(inst, func);
}
template <typename T>
void add_cdrom_handler(T* inst, void (T::*func)(CdromImageEvent&)) {
_cdrom_signal.connect_method(inst, func);
}
template <typename T>
void add_post_handler(T *inst, void (T::*func)()) {
_post_signal.connect_method(inst, func);
@@ -185,7 +162,6 @@ public:
_mouse_signal.disconnect_all();
_keyboard_signal.disconnect_all();
_gamepad_signal.disconnect_all();
_cdrom_signal.disconnect_all();
_post_signal.disconnect_all();
}
@@ -203,7 +179,6 @@ private:
CoreSignal<const MouseEvent&> _mouse_signal;
CoreSignal<const KeyboardEvent&> _keyboard_signal;
CoreSignal<const GamepadEvent&> _gamepad_signal;
CoreSignal<CdromImageEvent&> _cdrom_signal;
CoreSignal<> _post_signal;
uint64_t events_captured = 0;
+38 -126
View File
@@ -32,20 +32,6 @@ static int get_sdl_event_key_code(const SDL_KeyboardEvent& event, uint32_t kbd_l
constexpr int KMOD_ALL = KMOD_LSHIFT | KMOD_RSHIFT | KMOD_LCTRL | KMOD_RCTRL | KMOD_LALT | KMOD_RALT | KMOD_LGUI | KMOD_RGUI;
bool g_swap_command_option = false;
static AdbKey swap_command_option(AdbKey key)
{
if (!g_swap_command_option)
return key;
switch (key) {
case AdbKey_Option: return AdbKey_Command;
case AdbKey_RightOption: return AdbKey_Command;
case AdbKey_Command: return AdbKey_Option;
default: return key;
}
}
void EventManager::set_keyboard_locale(uint32_t keyboard_id) {
this->kbd_locale = keyboard_id;
}
@@ -58,7 +44,8 @@ void EventManager::poll_events() {
switch (event.type) {
case SDL_QUIT:
power_off(po_quit);
power_on = false;
power_off_reason = po_quit;
break;
case SDL_WINDOWEVENT: {
@@ -138,56 +125,21 @@ void EventManager::poll_events() {
}
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");
}
return;
}
// 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;
loguru::g_stderr_verbosity = loguru::g_stderr_verbosity == loguru::Verbosity_MAX ?
loguru::Verbosity_INFO
:
loguru::Verbosity_MAX;
}
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);
power_on = false;
power_off_reason = po_enter_debugger;
}
return;
}
@@ -323,35 +275,6 @@ void EventManager::poll_events() {
}
break;
case SDL_DROPFILE: {
const char* path = event.drop.file;
// TODO: Distinguish CD-ROM and floppy images once dynamic
// floppy insertion is supported.
CdromImageEvent cdrom_event{};
cdrom_event.image_path = path;
this->post_cdrom_event(cdrom_event);
switch (cdrom_event.result) {
case CdromInsertionResult::SUCCESS:
LOG_F(INFO, "Inserted CD-ROM image: %s", path);
break;
case CdromInsertionResult::NO_DRIVE:
LOG_F(ERROR, "Cannot insert CD-ROM image; no CD-ROM drive is available: %s",
path);
break;
case CdromInsertionResult::MEDIA_PRESENT:
LOG_F(ERROR, "Cannot insert CD-ROM image; eject the current media first: %s",
path);
break;
case CdromInsertionResult::IMAGE_OPEN_FAILED:
LOG_F(ERROR, "Cannot insert CD-ROM image: %s", path);
break;
}
SDL_free(event.drop.file);
}
break;
default:
unhandled_events++;
}
@@ -362,7 +285,6 @@ void EventManager::poll_events() {
}
void EventManager::post_keyboard_state_events() {
int count;
int numkeys;
const Uint8 *states = SDL_GetKeyboardState(&numkeys);
int modstate = SDL_GetModState();
@@ -378,54 +300,46 @@ void EventManager::post_keyboard_state_events() {
} Modifier_t;
static Modifier_t modifiers[] = {
{ SDL_SCANCODE_LSHIFT , KMOD_LSHIFT , AdbKey_Shift },
{ SDL_SCANCODE_RSHIFT , KMOD_RSHIFT , AdbKey_RightShift },
{ SDL_SCANCODE_LCTRL , KMOD_LCTRL , AdbKey_Control },
{ SDL_SCANCODE_RCTRL , KMOD_RCTRL , AdbKey_RightControl },
{ SDL_SCANCODE_LALT , KMOD_LALT , AdbKey_Option },
{ SDL_SCANCODE_RALT , KMOD_RALT , AdbKey_RightOption },
{ SDL_SCANCODE_LGUI , KMOD_LGUI , AdbKey_Command },
{ SDL_SCANCODE_RGUI , KMOD_RGUI , AdbKey_Command },
// { SDL_SCANCODE_NUMLOCKCLEAR , KMOD_NUM , AdbKey_KeypadClear },
{ SDL_SCANCODE_CAPSLOCK , KMOD_CAPS , AdbKey_CapsLock },
// { SDL_SCANCODE_MODE , KMOD_MODE , AdbKey_???? },
// { SDL_SCANCODE_SCROLLLOCK , KMOD_SCROLL , AdbKey_F14 },
{ SDL_SCANCODE_UNKNOWN },
SDL_SCANCODE_LSHIFT , KMOD_LSHIFT , AdbKey_Shift ,
SDL_SCANCODE_RSHIFT , KMOD_RSHIFT , AdbKey_RightShift ,
SDL_SCANCODE_LCTRL , KMOD_LCTRL , AdbKey_Control ,
SDL_SCANCODE_RCTRL , KMOD_RCTRL , AdbKey_RightControl,
SDL_SCANCODE_LALT , KMOD_LALT , AdbKey_Option ,
SDL_SCANCODE_RALT , KMOD_RALT , AdbKey_RightOption ,
SDL_SCANCODE_LGUI , KMOD_LGUI , AdbKey_Command ,
SDL_SCANCODE_RGUI , KMOD_RGUI , AdbKey_Command ,
// SDL_SCANCODE_NUMLOCKCLEAR , KMOD_NUM , AdbKey_KeypadClear ,
SDL_SCANCODE_CAPSLOCK , KMOD_CAPS , AdbKey_CapsLock ,
// SDL_SCANCODE_MODE , KMOD_MODE , AdbKey_???? ,
// SDL_SCANCODE_SCROLLLOCK , KMOD_SCROLL , AdbKey_F14 ,
SDL_SCANCODE_UNKNOWN
};
LOG_F(INFO, "Current keyboard state:");
LOG_F(INFO, " Modifiers:");
count = 0;
for (Modifier_t *mod = modifiers; mod->scancode != SDL_SCANCODE_UNKNOWN; mod++) {
if (!(modstate & mod->keymod))
continue;
LOG_F(INFO, " Modifier: %s", SDL_GetScancodeName(mod->scancode));
count++;
ke.key = swap_command_option(mod->adbkey);
LOG_F(INFO, " mod:%s", SDL_GetScancodeName(mod->scancode));
ke.key = mod->adbkey;
ke.flags = KEYBOARD_EVENT_DOWN;
this->_keyboard_signal.emit(ke);
}
if (!count)
LOG_F(INFO, " (none)");
LOG_F(INFO, " Keys and Modifiers:");
count = 0;
for (int i = 0; i < numkeys; i++) {
if (!states[i])
continue;
count++;
scancode = (SDL_Scancode)i;
Modifier_t *mod = modifiers;
for (; mod->scancode != SDL_SCANCODE_UNKNOWN && mod->scancode != scancode; mod++);
if (mod->scancode == scancode) {
LOG_F(INFO, " Modifier: %s", SDL_GetScancodeName(scancode));
LOG_F(INFO, " ignore:%s", SDL_GetScancodeName(scancode));
continue;
}
LOG_F(INFO, " Key: %s", SDL_GetScancodeName(scancode));
LOG_F(INFO, " key:%s", SDL_GetScancodeName(scancode));
keyevent.keysym.scancode = scancode;
keyevent.keysym.sym = SDL_GetKeyFromScancode(scancode);
keyevent.keysym.mod = modstate;
@@ -436,11 +350,9 @@ void EventManager::post_keyboard_state_events() {
ke.flags = KEYBOARD_EVENT_DOWN;
this->_keyboard_signal.emit(ke);
} else {
LOG_F(WARNING, " Unknown key %x pressed", keyevent.keysym.sym);
LOG_F(WARNING, "Unknown key %x pressed", keyevent.keysym.sym);
}
}
if (!count)
LOG_F(INFO, " (none)");
}
static int get_sdl_event_key_code(const SDL_KeyboardEvent &event, uint32_t kbd_locale)
@@ -527,10 +439,10 @@ static int get_sdl_event_key_code(const SDL_KeyboardEvent &event, uint32_t kbd_l
case SDLK_RCTRL: return AdbKey_RightControl;
case SDLK_LSHIFT: return AdbKey_Shift;
case SDLK_RSHIFT: return AdbKey_RightShift;
case SDLK_LALT: return swap_command_option(AdbKey_Option);
case SDLK_RALT: return swap_command_option(AdbKey_RightOption);
case SDLK_LGUI: return swap_command_option(AdbKey_Command);
case SDLK_RGUI: return swap_command_option(AdbKey_Command);
case SDLK_LALT: return AdbKey_Option;
case SDLK_RALT: return AdbKey_RightOption;
case SDLK_LGUI: return AdbKey_Command;
case SDLK_RGUI: return AdbKey_Command;
case SDLK_MENU: return AdbKey_Grave;
case SDLK_CAPSLOCK: return AdbKey_CapsLock;
@@ -574,9 +486,9 @@ static int get_sdl_event_key_code(const SDL_KeyboardEvent &event, uint32_t kbd_l
case SDLK_SCROLLLOCK: return AdbKey_F14;
case SDLK_PAUSE: return AdbKey_F15;
// International keyboard support
//International keyboard support
// Japanese keyboard
//Japanese keyboard
case SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_INTERNATIONAL3):
if (kbd_locale == Jpn_JPN)
return AdbKey_JIS_Yen;
@@ -591,18 +503,18 @@ static int get_sdl_event_key_code(const SDL_KeyboardEvent &event, uint32_t kbd_l
case SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_INTERNATIONAL2):
return AdbKey_JIS_Kana;
// German keyboard
//German keyboard
case 0XB4: return AdbKey_Slash;
case 0X5E: return AdbKey_ISO1;
case 0XDF: return AdbKey_Minus; // Eszett
case 0XE4: return AdbKey_LeftBracket; // A-umlaut
case 0XF6: return AdbKey_Semicolon; // O-umlaut
case 0XFC: return AdbKey_LeftBracket; // U-umlaut
case 0XDF: return AdbKey_Minus; //Eszett
case 0XE4: return AdbKey_LeftBracket; //A-umlaut
case 0XF6: return AdbKey_Semicolon; //O-umlaut
case 0XFC: return AdbKey_LeftBracket; //U-umlaut
// French keyboard
case 0X29: return AdbKey_Minus; // Right parenthesis
case 0X43: return AdbKey_KeypadMultiply; // Star/Mu
// 0XB2 is superscript 2. Which Mac key should this one map to?
//0XB2 is superscript 2. Which Mac key should this one map to?
case 0XF9: return AdbKey_Quote; // U-grave
// Italian keyboard
+30 -38
View File
@@ -30,49 +30,51 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
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_absolute_timer(uint64_t timeout_ns, uint64_t interval, timer_cb cb)
{
if (ti.active)
LOG_F(ERROR, "Timer %p is already active; cancel it before rescheduling", (void*)&ti);
TimerInfo* ti = new TimerInfo;
ti.timeout_ns = timeout_ns;
ti.interval_ns = interval;
ti.active = true;
ti.cb = cb;
ti->id = ++this->id;
ti->timeout_ns = timeout_ns;
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(&ti);
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_oneshot_timer(TimerInfo &ti, uint64_t timeout, timer_cb cb)
uint32_t TimerManager::add_oneshot_timer(uint64_t timeout, timer_cb cb)
{
TimerManager::add_absolute_timer(ti, this->get_time_now() + timeout, 0, cb);
return TimerManager::add_absolute_timer(this->get_time_now() + timeout, 0, cb);
}
void TimerManager::add_immediate_timer(TimerInfo &ti, timer_cb cb)
uint32_t TimerManager::add_immediate_timer(timer_cb cb)
{
TimerManager::add_absolute_timer(ti, 0, 0, cb);
return TimerManager::add_absolute_timer(0, 0, cb);
}
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, uint64_t delay, timer_cb cb)
{
TimerManager::add_absolute_timer(ti, this->get_time_now() + delay, interval, cb);
return TimerManager::add_absolute_timer(this->get_time_now() + delay, interval, cb);
}
void TimerManager::add_cyclic_timer(TimerInfo &ti, uint64_t interval, timer_cb cb)
uint32_t TimerManager::add_cyclic_timer(uint64_t interval, timer_cb cb)
{
this->add_cyclic_timer(ti, interval, interval, cb);
return this->add_cyclic_timer(interval, interval, cb);
}
void TimerManager::cancel_timer(TimerInfo &ti)
void TimerManager::cancel_timer(uint32_t id)
{
this->timer_queue.remove_by_id(&ti);
ti.active = false;
this->timer_queue.remove_by_id(id);
if (!this->cb_active) {
this->notify_timer_changes();
}
@@ -80,7 +82,7 @@ void TimerManager::cancel_timer(TimerInfo &ti)
uint64_t TimerManager::process_timers()
{
TimerInfo *cur_timer;
std::shared_ptr<TimerInfo> cur_timer;
uint64_t time_now = get_time_now();
{ // mtx scope
@@ -93,7 +95,7 @@ uint64_t TimerManager::process_timers()
cur_timer = this->timer_queue.top();
} // ] mtx scope
while (cur_timer->timeout_ns <= time_now) {
this->timer_queue.remove_by_id(cur_timer);
this->timer_queue.remove_by_id(cur_timer->id);
uint64_t timeout_ns = cur_timer->timeout_ns;
timer_cb cb = cur_timer->cb;
@@ -101,25 +103,16 @@ uint64_t TimerManager::process_timers()
if (cur_timer->interval_ns) {
std::lock_guard<std::recursive_mutex> lk(this->timer_queue.get_mtx());
uint64_t timeout_ns_new = timeout_ns + cur_timer->interval_ns;
if (timeout_ns_new <= time_now) {
// Skip missed periods without changing the timer's phase.
// Rebasing deadlines on time_now would align timers that
// have the same period.
const uint64_t periods_to_skip =
((time_now - timeout_ns_new) / cur_timer->interval_ns) + 1;
timeout_ns_new += periods_to_skip * cur_timer->interval_ns;
}
if (timeout_ns_new <= time_now)
timeout_ns_new = time_now + cur_timer->interval_ns;
cur_timer->timeout_ns = timeout_ns_new;
this->timer_queue.push(cur_timer);
} else {
// One-shot callbacks may immediately reuse their TimerInfo.
cur_timer->active = false;
}
this->cb_active = true;
// invoke timer callback
cb(time_now, timeout_ns);
cb();
this->cb_active = false;
@@ -134,17 +127,16 @@ uint64_t TimerManager::process_timers()
} // ] mtx scope
}
// return next timer's expiry
return cur_timer->timeout_ns;
// return time slice in nanoseconds until next timer's expiry
return cur_timer->timeout_ns - time_now;
}
void TimerManager::cancel_all_timers()
{
TimerInfo *cur_timer;
std::shared_ptr<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);
LOG_F(WARNING, "Canceling timer id:%u ns:%llu", cur_timer->id, cur_timer->timeout_ns);
this->timer_queue.pop();
cur_timer->active = false;
}
}
+19 -19
View File
@@ -40,7 +40,7 @@ constexpr auto ONE_BILLION_NS = 1000000000;
#define USECS_TO_NSECS(us) (us) * NS_PER_USEC
#define MSECS_TO_NSECS(ms) (ms) * NS_PER_MSEC
typedef std::function<void(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:
@@ -50,17 +50,17 @@ typedef std::function<void()> notify_changes_cb;
template <typename T, class Container = std::vector<T>, class Compare = std::less<typename Container::value_type>>
class my_priority_queue : public std::priority_queue<T, Container, Compare> {
public:
bool remove_by_id(T id){
bool remove_by_id(const uint32_t id){
std::lock_guard<std::recursive_mutex> lk(mtx);
if (this->empty())
return false;
auto el = this->top();
if (el == id) {
if (el->id == id) {
std::priority_queue<T, Container, Compare>::pop();
return true;
}
auto it = std::find_if(
this->c.begin(), this->c.end(), [id](const T& el) { return el == id; });
this->c.begin(), this->c.end(), [id](const T& el) { return el->id == id; });
if (it != this->c.end()) {
this->c.erase(it);
std::make_heap(this->c.begin(), this->c.end(), this->comp);
@@ -93,18 +93,18 @@ private:
};
typedef struct TimerInfo {
uint32_t id;
uint64_t timeout_ns; // timer expiry
uint64_t interval_ns; // 0 for one-shot timers
bool active = false; // maintained by TimerManager while queued
timer_cb cb; // timer callback
} TimerInfo;
// Custom comparator for sorting our timer queue in ascending order
class MyGtComparator {
public:
bool operator()(const TimerInfo *l, const TimerInfo *r) const {
return l->timeout_ns > r->timeout_ns ||
(l->timeout_ns == r->timeout_ns && l > r);
bool operator()(const std::shared_ptr<TimerInfo>& l, const std::shared_ptr<TimerInfo>& r) {
return l.get()->timeout_ns > r.get()->timeout_ns ||
(l.get()->timeout_ns == r.get()->timeout_ns && l.get()->id > r.get()->id);
}
};
@@ -128,17 +128,15 @@ public:
}
// 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(); }
// Adding requires an inactive timer; cancel before rescheduling.
// One-shot timers become inactive before their callback runs.
// Cyclic timers remain active until canceled, including during callbacks.
void add_absolute_timer(TimerInfo &ti, uint64_t timeout_ns, uint64_t interval, timer_cb cb);
void add_oneshot_timer(TimerInfo &ti, uint64_t timeout, timer_cb cb);
void add_immediate_timer(TimerInfo &ti, timer_cb cb);
void add_cyclic_timer(TimerInfo &ti, uint64_t interval, timer_cb cb);
void add_cyclic_timer(TimerInfo &ti, uint64_t interval, uint64_t delay, timer_cb cb);
void cancel_timer(TimerInfo &ti);
// creating and cancelling timers
uint32_t add_absolute_timer(uint64_t timeout_ns, uint64_t interval, timer_cb cb);
uint32_t add_oneshot_timer(uint64_t timeout, timer_cb cb);
uint32_t add_immediate_timer(timer_cb cb);
uint32_t add_cyclic_timer(uint64_t interval, timer_cb cb);
uint32_t add_cyclic_timer(uint64_t interval, uint64_t delay, timer_cb cb);
void cancel_timer(uint32_t id);
void cancel_all_timers();
uint64_t process_timers();
@@ -148,11 +146,13 @@ private:
TimerManager(){} // private constructor to implement a singleton
// 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<void()> notify_timer_changes;
std::atomic<uint32_t> id{0};
// FIXME: Do we need this? It gets written in main thread and read in audio thread.
bool cb_active = false; // true if a timer callback is executing
};
+3 -4
View File
@@ -23,10 +23,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
// Any shared opcodes are in ppcopcodes.cpp
#include <core/bitops.h>
#include <cpu/ppc/ppcdechelpers.h>
#include <cpu/ppc/ppcemu.h>
#include <cpu/ppc/ppcmmu.h>
#include "ppcemu.h"
#include "ppcmacros.h"
#include "ppcmmu.h"
#include <stdint.h>
/** mask generator for rotate and shift instructions (§ 4.2.1.4 PowerpC PEM) */
-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
+1 -8
View File
@@ -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 */
void opc_illegal(PPCDisasmContext* ctx) {
@@ -529,7 +522,7 @@ void opc_rlwimi(PPCDisasmContext* ctx) {
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) {
+12 -39
View File
@@ -126,9 +126,6 @@ enum SPR : int {
SDA = 959,
HID0 = 1008,
HID1 = 1009,
THRM1 = 1020,
THRM2 = 1021,
THRM3 = 1022,
};
/** symbolic names for common PPC processors */
@@ -324,22 +321,17 @@ enum FPOP : int {
/** PowerPC exception types. */
enum class Except_Type {
EXC_SYSTEM_RESET = 0x01,
EXC_MACHINE_CHECK = 0x02,
EXC_DSI = 0x03,
EXC_ISI = 0x04,
EXC_EXT_INT = 0x05,
EXC_ALIGNMENT = 0x06,
EXC_PROGRAM = 0x07,
EXC_NO_FPU = 0x08,
EXC_DECR = 0x09,
EXC_SYSCALL = 0x0C,
EXC_TRACE = 0x0D,
EXC_FP_ASSIST = 0x0E,
EXC_PERF_MON_INT = 0x0F,
EXC_INST_ADDR_BP = 0x13,
EXC_SYS_MGMT_INT = 0x14,
EXC_THRM_MGMT_INT = 0x17,
EXC_SYSTEM_RESET = 1,
EXC_MACHINE_CHECK,
EXC_DSI,
EXC_ISI,
EXC_EXT_INT,
EXC_ALIGNMENT,
EXC_PROGRAM,
EXC_NO_FPU,
EXC_DECR,
EXC_SYSCALL = 12,
EXC_TRACE = 13
};
/** Program Exception subclasses. */
@@ -374,14 +366,8 @@ enum Po_Cause : int {
extern bool power_on;
extern Po_Cause power_off_reason;
void p_set_power_off_reason(const char* file, int line, Po_Cause new_reason);
void p_power_off(const char* file, int line, Po_Cause new_reason);
#define set_power_off_reason(r) p_set_power_off_reason(__FILE__, __LINE__, r)
#define power_off(r) p_power_off(__FILE__, __LINE__, r)
extern bool int_pin;
extern bool dec_exception_pending;
extern bool thrm_exception_pending;
extern bool is_601; // For PowerPC 601 Emulation
extern bool include_601; // For non-PowerPC 601 emulation with 601 extras
@@ -398,8 +384,7 @@ enum class PPCPowMode : uint8_t {
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.
// Make execution deterministic (ignore external input, used a fixed date, etc.)
extern bool is_deterministic;
// Important Addressing Integers
@@ -729,18 +714,6 @@ extern void ppc_change_endian(bool newLE);
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 */
/* icnt_factor control */
extern int increment_icnt_factor();
extern int decrement_icnt_factor();
extern int get_icnt_factor();
/* realtime clock control */
extern bool 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;
+38 -16
View File
@@ -39,11 +39,8 @@ void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
switch (exception_type) {
case Except_Type::EXC_SYSTEM_RESET:
case Except_Type::EXC_DSI:
case Except_Type::EXC_ALIGNMENT:
case Except_Type::EXC_PROGRAM:
case Except_Type::EXC_NO_FPU:
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0100;
break;
case Except_Type::EXC_MACHINE_CHECK:
@@ -51,6 +48,12 @@ void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
/* TODO: handle internal checkstop */
}
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0200;
break;
case Except_Type::EXC_DSI:
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFC;
ppc_next_instruction_address = 0x0300;
break;
case Except_Type::EXC_ISI:
@@ -59,28 +62,56 @@ void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
} else {
ppc_state.spr[SPR::SRR0] = ppc_state.pc & 0xFFFFFFFCUL;
}
ppc_next_instruction_address = 0x0400;
break;
case Except_Type::EXC_EXT_INT:
case Except_Type::EXC_DECR:
case Except_Type::EXC_THRM_MGMT_INT:
if (exec_flags & ~EXEF_OPC_DECODER) {
ppc_state.spr[SPR::SRR0] = ppc_next_instruction_address;
} else {
ppc_state.spr[SPR::SRR0] = (ppc_state.pc & 0xFFFFFFFCUL) + 4;
}
ppc_next_instruction_address = 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 & ~EXEF_OPC_DECODER) {
ppc_state.spr[SPR::SRR0] = ppc_next_instruction_address;
} else {
ppc_state.spr[SPR::SRR0] = (ppc_state.pc & 0xFFFFFFFCUL) + 4;
}
ppc_next_instruction_address = 0x0900;
break;
case Except_Type::EXC_SYSCALL:
ppc_state.spr[SPR::SRR0] = (ppc_state.pc & 0xFFFFFFFC) + 4;
ppc_next_instruction_address = 0x0C00;
break;
case Except_Type::EXC_TRACE:
ppc_state.spr[SPR::SRR0] = (ppc_state.pc & 0xFFFFFFFC) + 4;
ppc_next_instruction_address = 0x0D00;
break;
default:
ABORT_F("Unknown exception occurred: %X\n", (unsigned)exception_type);
break;
}
ppc_next_instruction_address = uint32_t(exception_type) << 8;
ppc_state.spr[SPR::SRR1] = (ppc_state.msr & 0x0000FF73) | srr1_bits;
uint32_t old_msr_val = ppc_state.msr;
@@ -171,15 +202,6 @@ void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
case Except_Type::EXC_TRACE:
exc_descriptor = "Trace exception occurred";
break;
case Except_Type::EXC_THRM_MGMT_INT:
exc_descriptor = "Thermal management interrupt exception occurred";
break;
default:
char buffer[100];
snprintf(buffer, sizeof(buffer), "Exception 0x%X occurred", int(exception_type));
exc_descriptor = buffer;
}
throw std::invalid_argument(exc_descriptor);
+37 -132
View File
@@ -36,7 +36,19 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <string>
#ifdef __APPLE__
#include <ctime>
#include <mach/mach_time.h>
#undef EXC_SYSCALL
static struct mach_timebase_info timebase_info;
static uint64_t
ConvertHostTimeToNanos2(uint64_t host_time)
{
if (timebase_info.numer == timebase_info.denom)
return host_time;
long double answer = host_time;
answer *= timebase_info.numer;
answer /= timebase_info.denom;
return (uint64_t)answer;
}
#endif
using namespace std;
@@ -61,43 +73,6 @@ bool is_deterministic = false;
bool power_on = false;
Po_Cause power_off_reason = po_enter_debugger;
const char * get_po_name(Po_Cause reason) {
#define onename(x) case x: return #x;
switch (reason) {
onename(po_none)
onename(po_starting_up)
onename(po_quit)
onename(po_quitting)
onename(po_shut_down)
onename(po_shutting_down)
onename(po_restart)
onename(po_restarting)
onename(po_disassemble_on)
onename(po_disassemble_off)
onename(po_enter_debugger)
onename(po_entered_debugger)
onename(po_signal_interrupt)
onename(po_benchmark_exception)
onename(po_endian_switch)
default: return "unknown";
}
#undef onename
}
void p_set_power_off_reason(const char* file, int line, Po_Cause new_reason) {
if (new_reason != power_off_reason) {
power_off_reason = new_reason;
#if 1
LOG_F(INFO, "power_off_reason changed to %s at \"%s\":%d", get_po_name(new_reason), file, line);
#endif
}
}
void p_power_off(const char* file, int line, Po_Cause new_reason) {
power_on = false;
p_set_power_off_reason(file, line, new_reason);
}
SetPRS ppc_state;
#ifdef LOG_INSTRUCTIONS
uint32_t pcp;
@@ -116,10 +91,14 @@ unsigned exec_flags; // execution control flags
volatile bool exec_timer;
bool int_pin = false; // interrupt request pin state: true - asserted
bool dec_exception_pending = false;
bool thrm_exception_pending = false;
/* 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 */
bool g_realtime = false;
const bool g_realtime = false;
uint64_t g_nanoseconds_base;
uint64_t g_icycles;
int icnt_factor;
@@ -250,7 +229,8 @@ void ppc_msr_did_change(uint32_t old_msr_val, uint32_t new_msr_val, bool set_nex
ppc_next_instruction_address = ppc_state.pc + 4;
}
#else
power_off(po_endian_switch);
power_on = false;
power_off_reason = po_endian_switch;
#endif
}
}
@@ -260,12 +240,14 @@ void ppc_change_endian(bool newLE) {
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);
power_on = false;
power_off_reason = po_endian_switch;
}
#else
if (newLE) {
LOG_F(ERROR, "unsupported endian %s", newLE ? "LE" : "BE");
power_off(po_enter_debugger);
power_on = false;
power_off_reason = po_enter_debugger;
}
#endif
}
@@ -275,18 +257,6 @@ PPCOpcode* ppc_opcode_grabber = OpcodeGrabberNoFPU;
/** Exception helpers. */
void ppc_illegalop(uint32_t opcode) {
// Zero values are used as sentinels in the TNT ROM and are thus somewhat
// common, don't log them.
// Example: ciexit in Old World Open Firmware uses opcode 0.
if (opcode) {
PPCDisasmContext ctx;
ctx.instr_code = opcode;
ctx.instr_addr = 0;
ctx.simplified = false;
auto op_name = disassemble_single(&ctx);
LOG_F(WARNING, "Illegal opcode exception raised for 0x%08x (decoded as %s). The PC was 0x%08x.", opcode, op_name.c_str(), ppc_state.pc);
}
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
@@ -345,7 +315,7 @@ void ppc_main_opcode(PPCOpcode *opcodeGrabber, uint32_t opcode)
static long long cpu_now_ns() {
#ifdef __APPLE__
return clock_gettime_nsec_np(CLOCK_UPTIME_RAW);
return ConvertHostTimeToNanos2(mach_absolute_time());
#else
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch()).count();
@@ -361,49 +331,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 constexpr uint64_t TIMER_POLL_INTERVAL_NS = 500'000;
static uint64_t process_events()
{
exec_timer = false;
uint64_t next_ns = TimerManager::get_instance()->process_timers();
if (g_realtime) {
uint64_t time_now = get_virt_time_ns();
uint64_t delay_ns;
if (next_ns) {
delay_ns = next_ns > time_now ? next_ns - time_now : 0;
} else {
delay_ns = TIMER_POLL_INTERVAL_NS;
}
// Host time and the instruction counter advance independently. Schedule
// a relative instruction batch, capped so long deadlines still poll.
// Comparing an absolute wall-time deadline with g_icycles can otherwise
// make a fast interpreter process timers after every instruction.
return g_icycles + (std::min(delay_ns, TIMER_POLL_INTERVAL_NS) >> icnt_factor) + 1;
uint64_t slice_ns = TimerManager::get_instance()->process_timers();
if (slice_ns == 0) {
// execute 25.000 cycles
// if there are no pending timers
return g_icycles + 25000;
}
return (
(
next_ns ?
next_ns
:
get_virt_time_ns() + TIMER_POLL_INTERVAL_NS
) >> icnt_factor
) + 1;
return g_icycles + (slice_ns >> icnt_factor) + 1;
}
static void force_cycle_counter_reload()
@@ -412,40 +349,6 @@ static void force_cycle_counter_reload()
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 {
main,
until,
@@ -1052,6 +955,9 @@ void ppc_cpu_init(MemCtrlBase* mem_ctrl, uint32_t cpu_version, bool do_include_6
TimerManager::get_instance()->set_notify_changes_cb(&force_cycle_counter_reload);
// initialize time base facility
#ifdef __APPLE__
mach_timebase_info(&timebase_info);
#endif
g_nanoseconds_base = cpu_now_ns();
g_icycles = 0;
@@ -1124,14 +1030,13 @@ static map<string, int> SPRName2Num = {
{"DBAT2L", 541}, {"DBAT3U", 542}, {"DBAT3L", 543},
{"HID0", SPR::HID0}, {"HID1", SPR::HID1}, {"IABR", 1010},
{"DABR", 1013}, {"L2CR", 1017}, {"ICTC", 1019},
{"THRM1", SPR::THRM1}, {"THRM2", SPR::THRM2}, {"THRM3", SPR::THRM3},
{"THRM1", 1020}, {"THRM2", 1021}, {"THRM3", 1022},
{"PIR", 1023}, {"TBL", SPR::TBL_S}, {"TBU", SPR::TBU_S},
{"SDR1", SPR::SDR1}, {"MQ", SPR::MQ}, {"RTCU", SPR::RTCU_S},
{"RTCL", SPR::RTCL_S}, {"DSISR", SPR::DSISR}, {"DAR", SPR::DAR},
{"MMCR0", SPR::MMCR0}, {"PMC1", SPR::PMC1}, {"PMC2", SPR::PMC2},
{"SDA", SPR::SDA}, {"SIA", SPR::SIA}, {"MMCR1", SPR::MMCR1},
{"PMC3", SPR::PMC3}, {"PMC4", SPR::PMC4}, {"EAR", SPR::EAR},
{"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},
};
+22 -58
View File
@@ -21,19 +21,14 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
// The floating point opcodes for the processor - ppcfpopcodes.cpp
#include <cpu/ppc/ppcdechelpers.h>
#include <cpu/ppc/ppcemu.h>
#include <cpu/ppc/ppcmmu.h>
#include "ppcemu.h"
#include "ppcmacros.h"
#include "ppcmmu.h"
#include <stdlib.h>
#include <cfenv>
#include <cfloat>
#include <cinttypes>
#include <cmath>
#include <stdlib.h>
#if defined(__APPLE__) && defined(__aarch64__)
#include <arm_acle.h>
#endif
#include <cfloat>
inline static void ppc_update_cr1() {
// copy FPSCR[FX|FEX|VX|OX] to CR1
@@ -121,26 +116,6 @@ static double set_endresult_nan() {
return std::numeric_limits<double>::quiet_NaN();
}
#if FE_ALL_EXCEPT
static int test_and_clear_fp_exceptions() {
#if defined(__APPLE__) && defined(__aarch64__)
// Darwin's FE_* masks match the ARM64 FPSR exception bits. Preserve
// other status bits and avoid a second register read when clearing.
uint64_t fpsr = __arm_rsr64("fpsr");
int exceptions = fpsr & FE_ALL_EXCEPT;
if (exceptions) {
fpsr &= ~uint64_t(FE_ALL_EXCEPT);
__arm_wsr64("fpsr", fpsr);
}
#else
int exceptions = std::fetestexcept(FE_ALL_EXCEPT);
if (exceptions)
std::feclearexcept(FE_ALL_EXCEPT);
#endif
return exceptions;
}
#endif
static void fpresult_update(double set_result) {
if (std::isnan(set_result)) {
ppc_state.fpscr |= FPCC_FUNAN | FPRCD;
@@ -152,18 +127,18 @@ static void fpresult_update(double set_result) {
} else {
ppc_state.fpscr |= FPCC_ZERO;
}
#if FE_ALL_EXCEPT
int exceptions = test_and_clear_fp_exceptions();
if (exceptions & FE_OVERFLOW) {
if (std::fetestexcept(FE_OVERFLOW)) {
ppc_state.fpscr |= (OX + FX);
}
if (exceptions & FE_UNDERFLOW) {
if (std::fetestexcept(FE_UNDERFLOW)) {
ppc_state.fpscr |= (UX + FX);
}
if (exceptions & FE_DIVBYZERO) {
if (std::fetestexcept(FE_DIVBYZERO)) {
ppc_state.fpscr |= (ZX + FX);
}
#endif
std::feclearexcept(FE_ALL_EXCEPT);
if (std::isinf(set_result))
ppc_state.fpscr |= FPCC_FUNAN;
@@ -445,7 +420,7 @@ void dppc_interpreter::ppc_fnmadd(uint32_t opcode) {
if (snan_single_check(reg_a) || snan_single_check(reg_b) || snan_single_check(reg_c)) {
uint64_t qnan = 0x7FFC000000000000;
ppc_store_fpresult_int(reg_d, qnan);
}
}
else {
ppc_store_fpresult_flt(reg_d, ppc_dblresult64_d);
}
@@ -1049,7 +1024,7 @@ void dppc_interpreter::ppc_lfsu(uint32_t opcode) {
ppc_store_iresult_reg(reg_a, ea);
}
else {
ppc_illegalop(opcode);
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
}
@@ -1070,7 +1045,7 @@ void dppc_interpreter::ppc_lfsux(uint32_t opcode) {
ppc_store_iresult_reg(reg_a, ea);
}
else {
ppc_illegalop(opcode);
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
return;
}
}
@@ -1094,7 +1069,7 @@ void dppc_interpreter::ppc_lfdu(uint32_t opcode) {
ppc_store_iresult_reg(reg_a, ea);
}
else {
ppc_illegalop(opcode);
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
}
@@ -1115,7 +1090,7 @@ void dppc_interpreter::ppc_lfdux(uint32_t opcode) {
ppc_store_iresult_reg(reg_a, ea);
}
else {
ppc_illegalop(opcode);
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
}
@@ -1138,7 +1113,7 @@ void dppc_interpreter::ppc_stfsu(uint32_t opcode) {
ppc_store_iresult_reg(reg_a, ea);
}
else {
ppc_illegalop(opcode);
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
}
@@ -1159,7 +1134,7 @@ void dppc_interpreter::ppc_stfsux(uint32_t opcode) {
ppc_store_iresult_reg(reg_a, ea);
}
else {
ppc_illegalop(opcode);
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
}
@@ -1180,7 +1155,7 @@ void dppc_interpreter::ppc_stfdu(uint32_t opcode) {
ppc_store_iresult_reg(reg_a, ea);
}
else {
ppc_illegalop(opcode);
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
}
@@ -1199,7 +1174,7 @@ void dppc_interpreter::ppc_stfdux(uint32_t opcode) {
ppc_store_iresult_reg(reg_a, ea);
}
else {
ppc_illegalop(opcode);
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
}
@@ -1264,9 +1239,6 @@ void dppc_interpreter::ppc_mtfsf(uint32_t opcode) {
// copy FPR[reg_b] to FPSCR under control of cr_mask
ppc_state.fpscr = (ppc_state.fpscr & ~cr_mask) | (FPR_INT(reg_b) & cr_mask);
ppc_update_vx();
ppc_update_fex();
if (rec)
ppc_update_cr1();
}
@@ -1303,9 +1275,6 @@ void dppc_interpreter::ppc_mtfsb0(uint32_t opcode) {
ppc_state.fpscr &= ~(0x80000000UL >> crf_d);
}
ppc_update_vx();
ppc_update_fex();
if (rec)
ppc_update_cr1();
}
@@ -1320,9 +1289,6 @@ void dppc_interpreter::ppc_mtfsb1(uint32_t opcode) {
ppc_state.fpscr |= (0x80000000UL >> crf_d);
}
ppc_update_vx();
ppc_update_fex();
if (rec)
ppc_update_cr1();
}
@@ -1343,10 +1309,8 @@ void dppc_interpreter::ppc_mcrfs(uint32_t opcode) {
FPSCR::UX | FPSCR::ZX | FPSCR::XX | FPSCR::VXSNAN |
FPSCR::VXISI | FPSCR::VXIDI | FPSCR::VXZDZ | FPSCR::VXIMZ |
FPSCR::VXVC |
FPSCR::VXSOFT | FPSCR::VXSQRT | FPSCR::VXCVI));
ppc_update_vx();
ppc_update_fex();
FPSCR::VXSOFT | FPSCR::VXSQRT | FPSCR::VXCVI
));
}
// Floating Point Comparisons
+213
View File
@@ -0,0 +1,213 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-26 The DingusPPC Development Team
(See CREDITS.MD for more details)
(You may also contact divingkxt or powermax2286 on Discord)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef PPC_MACROS_H
#define PPC_MACROS_H
#include <cinttypes>
#define ppc_grab_regsdasimm(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int32_t simm = int32_t(int16_t(opcode)); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsdauimm(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
uint32_t uimm = uint16_t(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsasimm(opcode) \
int reg_a = (opcode >> 16) & 31; \
int32_t simm = int32_t(int16_t(opcode)); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssauimm(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
uint32_t uimm = uint16_t(opcode); \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_crfd_regsauimm(opcode) \
int crf_d = (opcode >> 21) & 0x1C; \
int reg_a = (opcode >> 16) & 31; \
uint32_t uimm = uint16_t(opcode); \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_da(opcode)\
int reg_d = (opcode >> 21) & 31;\
int reg_a = (opcode >> 16) & 31;\
#define ppc_grab_dab(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31;
#define ppc_grab_s(opcode) \
int reg_s = (opcode >> 21) & 31; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s];
#define ppc_grab_regsdab(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regssab(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b]; \
#define ppc_grab_regssab_stswx(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regsab(opcode) \
int reg_a = (opcode >> 16) & 31;\
int reg_b = (opcode >> 11) & 31;\
uint32_t ppc_result_a = ppc_state.gpr[reg_a];\
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_grab_regssa(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssa_stmw(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssash(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
unsigned rot_sh = (opcode >> 11) & 31; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssash_stswi(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
unsigned rot_sh = (opcode >> 11) & 31; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regssb(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_b = (opcode >> 11) & 31; \
uint32_t ppc_result_d = ppc_state.gpr[reg_s]; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b]; \
#define ppc_grab_regsda(opcode) \
int reg_d = (opcode >> 21) & 31; \
uint32_t reg_a = (opcode >> 16) & 31; \
uint32_t ppc_result_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsdb(opcode) \
int reg_d = (opcode >> 21) & 31; \
uint32_t reg_b = (opcode >> 11) & 31; \
uint32_t ppc_result_b = ppc_state.gpr[reg_b];
#define ppc_store_iresult_reg(reg, ppc_result)\
ppc_state.gpr[reg] = ppc_result
#define ppc_store_fpresult_int(reg, ppc_result64_d)\
ppc_state.fpr[(reg)].int64_r = ppc_result64_d
#define ppc_store_fpresult_flt(reg, ppc_dblresult64_d)\
ppc_state.fpr[(reg)].dbl64_r = ppc_dblresult64_d
#define ppc_grab_regsfpdb(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_b = (opcode >> 11) & 31;
#define GET_FPR(reg) \
ppc_state.fpr[(reg)].dbl64_r
#define FPR_INT(reg) \
ppc_state.fpr[reg].int64_r
#define ppc_grab_regsfpdiab(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
uint32_t val_reg_a = ppc_state.gpr[reg_a]; \
uint32_t val_reg_b = ppc_state.gpr[reg_b];
#define ppc_grab_regsfpdia(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
uint32_t val_reg_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsfpsia(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
uint32_t val_reg_a = ppc_state.gpr[reg_a];
#define ppc_grab_regsfpsiab(opcode) \
int reg_s = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
uint32_t val_reg_a = ppc_state.gpr[reg_a]; \
uint32_t val_reg_b = ppc_state.gpr[reg_b];
#define ppc_grab_regsfpsab(opcode) \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
int crf_d = (opcode >> 21) & 0x1C; \
double db_test_a = GET_FPR(reg_a); \
double db_test_b = GET_FPR(reg_b);
#define ppc_grab_regsfpdab(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
double val_reg_a = GET_FPR(reg_a); \
double val_reg_b = GET_FPR(reg_b);
#define ppc_grab_regsfpdac(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_c = (opcode >> 6) & 31; \
double val_reg_a = GET_FPR(reg_a); \
double val_reg_c = GET_FPR(reg_c);
#define ppc_grab_regsfpdabc(opcode) \
int reg_d = (opcode >> 21) & 31; \
int reg_a = (opcode >> 16) & 31; \
int reg_b = (opcode >> 11) & 31; \
int reg_c = (opcode >> 6) & 31; \
double val_reg_a = GET_FPR(reg_a); \
double val_reg_b = GET_FPR(reg_b); \
double val_reg_c = GET_FPR(reg_c);
#endif // PPC_MACROS_H
+287 -329
View File
@@ -31,7 +31,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cinttypes>
#include <loguru.hpp>
#include <stdexcept>
#include <vector>
//#define MMU_PROFILING // uncomment this to enable MMU profiling
//#define TLB_PROFILING // uncomment this to enable SoftTLB profiling
@@ -57,7 +56,6 @@ uint64_t iomem_writes_total = 0; // counts I/O memory writes
uint64_t exec_reads_total = 0; // counts reads from executable memory
uint64_t bat_transl_total = 0; // counts BAT translations
uint64_t ptab_transl_total = 0; // counts page table translations
uint64_t pat_flushes_total = 0; // counts full page-translation TLB flushes
uint64_t unaligned_reads = 0; // counts unaligned reads
uint64_t unaligned_writes = 0; // counts unaligned writes
uint64_t unaligned_crossp_r = 0; // counts unaligned crosspage reads
@@ -79,6 +77,9 @@ uint64_t num_entry_replacements = 0; // number of entry replacements
#endif // TLB_PROFILING
/** remember recently used physical memory regions for quicker translation. */
AddressMapEntry last_read_area;
AddressMapEntry last_write_area;
AddressMapEntry last_exec_area;
AddressMapEntry last_ptab_area;
/** Dummy pages for catching writes to physical read-only pages */
@@ -378,9 +379,7 @@ static PATResult page_address_translation(uint32_t la, bool is_instr_fetch,
};
}
MapDmaResult mmu_map_dma_mem(uint32_t addr, uint32_t size,
bool allow_mmio, bool allow_partial, bool is_dbg)
{
MapDmaResult mmu_map_dma_mem(uint32_t addr, uint32_t size, bool allow_mmio, bool is_dbg) {
MMIODevice *devobj = nullptr;
uint8_t *host_va = nullptr;
uint32_t dev_base = 0;
@@ -434,18 +433,10 @@ MapDmaResult mmu_map_dma_mem(uint32_t addr, uint32_t size,
addr, addr + size - 1
);
} else {
if (allow_partial) {
if (!is_dbg)
LOG_F(INFO, "DMA access to physical memory 0x%08X..0x%08X spans regions!",
addr, addr + size - 1
);
size = cur_dma_rgn->end - addr + 1;
} else {
if (is_dbg) goto fail;
ABORT_F("DMA access to physical memory 0x%08X..0x%08X spans regions!",
addr, addr + size - 1
);
}
if (is_dbg) goto fail;
ABORT_F("SOS: DMA access to unmapped physical memory 0x%08X..0x%08X because size extends outside region!",
addr, addr + size - 1
);
}
}
@@ -465,145 +456,9 @@ MapDmaResult mmu_map_dma_mem(uint32_t addr, uint32_t size,
is_writable = true; // all MMIO devices must provide a write method
}
return MapDmaResult{
.type = cur_dma_rgn->type,
.size = size,
.is_writable = is_writable,
.host_va = host_va,
.dev_obj = devobj,
.dev_base = dev_base,
};
return MapDmaResult{cur_dma_rgn->type, is_writable, host_va, devobj, dev_base};
fail:
return MapDmaResult{
.type = RT_NONE
};
}
constexpr uint32_t TLB_SIZE = 4096;
constexpr uint32_t TLB2_WAYS = 4;
constexpr uint32_t TLB_INVALID_TAG = 0xFFFFFFFF;
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
TLBE_CTX_TRACKED = 1 << 7, // entry pointer is in gTrackedIEntries or gTrackedDEntries
};
constexpr uint16_t TLBE_FROM_TRANSLATION =
TLBFlags::TLBE_FROM_BAT | TLBFlags::TLBE_FROM_PAT;
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;
// Track slots populated by either page or block address translation. Context
// changes can then invalidate only populated slots without adding a generation
// check to every TLB lookup.
static std::vector<TLBEntry *> gTrackedIEntries;
static std::vector<TLBEntry *> gTrackedDEntries;
// TLBE_FROM_* sources awaiting invalidation at the next context sync.
static uint16_t gPendingIInvalidationSources = 0;
static uint16_t gPendingDInvalidationSources = 0;
template <const TLBType tlb_type>
static void track_translated_entry(TLBEntry *tlb_entry)
{
if (!(tlb_entry->flags & TLBE_FROM_TRANSLATION) ||
(tlb_entry->flags & TLBFlags::TLBE_CTX_TRACKED))
return;
tlb_entry->flags |= TLBFlags::TLBE_CTX_TRACKED;
if (tlb_type == TLBType::ITLB)
gTrackedIEntries.push_back(tlb_entry);
else
gTrackedDEntries.push_back(tlb_entry);
}
static void tlb_invalidate_tracked_entries(std::vector<TLBEntry *> &tracked_entries,
uint16_t sources)
{
size_t retained_count = 0;
for (TLBEntry *tlb_entry : tracked_entries) {
uint16_t source = tlb_entry->flags & TLBE_FROM_TRANSLATION;
if (source & sources) {
tlb_entry->tag = TLB_INVALID_TAG;
tlb_entry->flags &= ~TLBFlags::TLBE_CTX_TRACKED;
} else if (source) {
tracked_entries[retained_count++] = tlb_entry;
} else {
tlb_entry->flags &= ~TLBFlags::TLBE_CTX_TRACKED;
}
}
tracked_entries.resize(retained_count);
}
template <const TLBType tlb_type>
static void tlb_invalidate_tracked_entries()
{
uint16_t *pending_sources;
std::vector<TLBEntry *> *tracked_entries;
if (tlb_type == TLBType::ITLB) {
pending_sources = &gPendingIInvalidationSources;
tracked_entries = &gTrackedIEntries;
} else {
pending_sources = &gPendingDInvalidationSources;
tracked_entries = &gTrackedDEntries;
}
if (!*pending_sources)
return;
tlb_invalidate_tracked_entries(*tracked_entries, *pending_sources);
*pending_sources = 0;
}
static void schedule_tlb_invalidation(TLBType tlb_type, uint16_t sources_to_invalidate)
{
uint16_t *pending_sources;
if (tlb_type == TLBType::ITLB)
pending_sources = &gPendingIInvalidationSources;
else
pending_sources = &gPendingDInvalidationSources;
if (!*pending_sources) {
if (tlb_type == TLBType::ITLB)
add_ctx_sync_action(&tlb_invalidate_tracked_entries<TLBType::ITLB>);
else
add_ctx_sync_action(&tlb_invalidate_tracked_entries<TLBType::DTLB>);
}
*pending_sources |= sources_to_invalidate;
}
template <const TLBType tlb_type>
static void promote_tlb_entry(TLBEntry *tlb1_entry, const TLBEntry *tlb2_entry)
{
uint16_t tracked = tlb1_entry->flags & TLBFlags::TLBE_CTX_TRACKED;
*tlb1_entry = *tlb2_entry;
tlb1_entry->flags &= ~TLBFlags::TLBE_CTX_TRACKED;
tlb1_entry->flags |= tracked;
track_translated_entry<tlb_type>(tlb1_entry);
return MapDmaResult{RT_NONE, false, nullptr, nullptr, 0};
}
// primary ITLB for all MMU modes
@@ -691,27 +546,6 @@ void mmu_change_mode()
}
}
template <uint32_t way>
static inline void tlb2_touch_way(TLBEntry *tlb_entry)
{
static_assert(way < TLB2_WAYS);
// Each pair is one branch of the four-way tree-based LRU. Mark the
// selected way as most recently used, its sibling as the next replacement
// candidate, and the other pair as less recently used.
if constexpr (way < 2) {
tlb_entry[0].lru_bits = way == 0 ? 0x3 : 0x2;
tlb_entry[1].lru_bits = way == 1 ? 0x3 : 0x2;
tlb_entry[2].lru_bits &= 0x1;
tlb_entry[3].lru_bits &= 0x1;
} else {
tlb_entry[0].lru_bits &= 0x1;
tlb_entry[1].lru_bits &= 0x1;
tlb_entry[2].lru_bits = way == 2 ? 0x3 : 0x2;
tlb_entry[3].lru_bits = way == 3 ? 0x3 : 0x2;
}
}
template <const TLBType tlb_type>
static TLBEntry* tlb2_target_entry(uint32_t gp_va)
{
@@ -725,32 +559,64 @@ static TLBEntry* tlb2_target_entry(uint32_t gp_va)
// select the target from invalid blocks first
if (tlb_entry[0].tag == TLB_INVALID_TAG) {
tlb2_touch_way<0>(tlb_entry);
// update LRU bits
tlb_entry[0].lru_bits = 0x3;
tlb_entry[1].lru_bits = 0x2;
tlb_entry[2].lru_bits &= 0x1;
tlb_entry[3].lru_bits &= 0x1;
return tlb_entry;
} else if (tlb_entry[1].tag == TLB_INVALID_TAG) {
tlb2_touch_way<1>(tlb_entry);
// update LRU bits
tlb_entry[0].lru_bits = 0x2;
tlb_entry[1].lru_bits = 0x3;
tlb_entry[2].lru_bits &= 0x1;
tlb_entry[3].lru_bits &= 0x1;
return &tlb_entry[1];
} else if (tlb_entry[2].tag == TLB_INVALID_TAG) {
tlb2_touch_way<2>(tlb_entry);
// update LRU bits
tlb_entry[0].lru_bits &= 0x1;
tlb_entry[1].lru_bits &= 0x1;
tlb_entry[2].lru_bits = 0x3;
tlb_entry[3].lru_bits = 0x2;
return &tlb_entry[2];
} else if (tlb_entry[3].tag == TLB_INVALID_TAG) {
tlb2_touch_way<3>(tlb_entry);
// update LRU bits
tlb_entry[0].lru_bits &= 0x1;
tlb_entry[1].lru_bits &= 0x1;
tlb_entry[2].lru_bits = 0x2;
tlb_entry[3].lru_bits = 0x3;
return &tlb_entry[3];
} else { // no free entries, replace an existing one according with the hLRU policy
#ifdef TLB_PROFILING
num_entry_replacements++;
#endif
if (tlb_entry[0].lru_bits == 0) {
tlb2_touch_way<0>(tlb_entry);
// update LRU bits
tlb_entry[0].lru_bits = 0x3;
tlb_entry[1].lru_bits = 0x2;
tlb_entry[2].lru_bits &= 0x1;
tlb_entry[3].lru_bits &= 0x1;
return tlb_entry;
} else if (tlb_entry[1].lru_bits == 0) {
tlb2_touch_way<1>(tlb_entry);
// update LRU bits
tlb_entry[0].lru_bits = 0x2;
tlb_entry[1].lru_bits = 0x3;
tlb_entry[2].lru_bits &= 0x1;
tlb_entry[3].lru_bits &= 0x1;
return &tlb_entry[1];
} else if (tlb_entry[2].lru_bits == 0) {
tlb2_touch_way<2>(tlb_entry);
// update LRU bits
tlb_entry[0].lru_bits &= 0x1;
tlb_entry[1].lru_bits &= 0x1;
tlb_entry[2].lru_bits = 0x3;
tlb_entry[3].lru_bits = 0x2;
return &tlb_entry[2];
} else {
tlb2_touch_way<3>(tlb_entry);
// update LRU bits
tlb_entry[0].lru_bits &= 0x1;
tlb_entry[1].lru_bits &= 0x1;
tlb_entry[2].lru_bits = 0x2;
tlb_entry[3].lru_bits = 0x3;
return &tlb_entry[3];
}
}
@@ -799,12 +665,10 @@ static TLBEntry* itlb2_refill(uint32_t guest_va)
const uint32_t tag = guest_va & ~0xFFFUL;
tlb_entry = tlb2_target_entry<TLBType::ITLB>(tag);
tlb_entry->tag = tag;
tlb_entry->flags = flags | TLBFlags::PAGE_MEM |
(tlb_entry->flags & TLBFlags::TLBE_CTX_TRACKED);
tlb_entry->flags = flags | TLBFlags::PAGE_MEM;
tlb_entry->host_va_offs_r = (int64_t)rgn_desc->mem_ptr - guest_va +
(phys_addr - rgn_desc->start);
tlb_entry->phys_tag = phys_addr & ~0xFFFUL;
track_translated_entry<TLBType::ITLB>(tlb_entry);
} else {
ABORT_F("Instruction fetch from unmapped memory at 0x%08X!\n", phys_addr);
}
@@ -833,9 +697,9 @@ static TLBEntry* dtlb2_refill(uint32_t guest_va, int is_write, bool is_dbg = fal
// check block protection
if (!bat_res.prot || ((bat_res.prot & 1) && is_write)) {
if (!is_dbg)
LOG_F(9, "BAT DSI exception in TLB2 refill!");
LOG_F(9, "BAT DSI exception in TLB2 refill!");
if (!is_dbg)
LOG_F(9, "Attempt to write to read-only region, LA=0x%08X, PC=0x%08X!", guest_va, ppc_state.pc);
LOG_F(9, "Attempt to write to read-only region, LA=0x%08X, PC=0x%08X!", guest_va, ppc_state.pc);
ppc_state.spr[SPR::DSISR] = 0x08000000 | (is_write << 25);
ppc_state.spr[SPR::DAR] = guest_va;
mmu_exception_handler(Except_Type::EXC_DSI, 0);
@@ -873,16 +737,14 @@ static TLBEntry* dtlb2_refill(uint32_t guest_va, int is_write, bool is_dbg = fal
tlb_entry = tlb2_target_entry<TLBType::DTLB>(tag);
tlb_entry->tag = tag;
if (rgn_desc->type & RT_MMIO) { // MMIO region
tlb_entry->flags = flags | TLBFlags::PAGE_IO |
(tlb_entry->flags & TLBFlags::TLBE_CTX_TRACKED);
tlb_entry->flags = flags | TLBFlags::PAGE_IO;
tlb_entry->rgn_desc = rgn_desc;
tlb_entry->dev_base_va = guest_va - (phys_addr - rgn_desc->start);
} else { // memory region backed by host memory
tlb_entry->flags = flags | TLBFlags::PAGE_MEM |
(tlb_entry->flags & TLBFlags::TLBE_CTX_TRACKED);
tlb_entry->flags = flags | TLBFlags::PAGE_MEM;
tlb_entry->host_va_offs_r = (int64_t)rgn_desc->mem_ptr - guest_va +
(phys_addr - rgn_desc->start);
if (rgn_desc->type & RT_ROM) {
if (rgn_desc->type == RT_ROM) {
// redirect writes to the dummy page for ROM regions
tlb_entry->host_va_offs_w = (int64_t)&dummy_page - tag;
} else {
@@ -890,7 +752,6 @@ static TLBEntry* dtlb2_refill(uint32_t guest_va, int is_write, bool is_dbg = fal
}
}
tlb_entry->phys_tag = phys_addr & ~0xFFFUL;
track_translated_entry<TLBType::DTLB>(tlb_entry);
return tlb_entry;
} else {
if (!is_dbg) {
@@ -919,16 +780,32 @@ static inline TLBEntry* lookup_secondary_tlb(uint32_t guest_va, uint32_t tag) {
tlb_entry = &pCurDTLB2[((guest_va >> PPC_PAGE_SIZE_BITS) & tlb_size_mask) * TLB2_WAYS];
}
if (tlb_entry[0].tag == tag) {
tlb2_touch_way<0>(tlb_entry);
if (tlb_entry->tag == tag) {
// update LRU bits
tlb_entry[0].lru_bits = 0x3;
tlb_entry[1].lru_bits = 0x2;
tlb_entry[2].lru_bits &= 0x1;
tlb_entry[3].lru_bits &= 0x1;
} else if (tlb_entry[1].tag == tag) {
tlb2_touch_way<1>(tlb_entry);
// update LRU bits
tlb_entry[0].lru_bits = 0x2;
tlb_entry[1].lru_bits = 0x3;
tlb_entry[2].lru_bits &= 0x1;
tlb_entry[3].lru_bits &= 0x1;
tlb_entry = &tlb_entry[1];
} else if (tlb_entry[2].tag == tag) {
tlb2_touch_way<2>(tlb_entry);
// update LRU bits
tlb_entry[0].lru_bits &= 0x1;
tlb_entry[1].lru_bits &= 0x1;
tlb_entry[2].lru_bits = 0x3;
tlb_entry[3].lru_bits = 0x2;
tlb_entry = &tlb_entry[2];
} else if (tlb_entry[3].tag == tag) {
tlb2_touch_way<3>(tlb_entry);
// update LRU bits
tlb_entry[0].lru_bits &= 0x1;
tlb_entry[1].lru_bits &= 0x1;
tlb_entry[2].lru_bits = 0x2;
tlb_entry[3].lru_bits = 0x3;
tlb_entry = &tlb_entry[3];
} else {
return nullptr;
@@ -936,80 +813,6 @@ static inline TLBEntry* lookup_secondary_tlb(uint32_t guest_va, uint32_t tag) {
return tlb_entry;
}
struct TLBLookupResult {
TLBEntry *primary_entry;
TLBEntry *matched_entry; // nullptr if both TLBs missed
bool primary_hit;
};
template <const TLBType tlb_type>
static inline TLBLookupResult lookup_tlb(uint32_t guest_va, uint32_t tag)
{
TLBEntry *primary_entry;
if constexpr (tlb_type == TLBType::ITLB) {
primary_entry = &pCurITLB1[(guest_va >> PPC_PAGE_SIZE_BITS) & tlb_size_mask];
} else {
primary_entry = &pCurDTLB1[(guest_va >> PPC_PAGE_SIZE_BITS) & tlb_size_mask];
}
if (primary_entry->tag == tag) {
return TLBLookupResult{primary_entry, primary_entry, true};
}
return TLBLookupResult{
primary_entry,
lookup_secondary_tlb<tlb_type>(guest_va, tag),
false
};
}
// Returns true when the PTE.C bit was updated. Callers writing through a
// primary entry use this to mirror the update into the secondary TLB.
static inline bool prepare_dtlb_write(TLBEntry *tlb_entry, uint32_t guest_va)
{
if (!(tlb_entry->flags & TLBFlags::PAGE_WRITABLE)) {
ppc_state.spr[SPR::DSISR] = 0x08000000 | (1 << 25);
ppc_state.spr[SPR::DAR] = guest_va;
mmu_exception_handler(Except_Type::EXC_DSI, 0);
}
if (tlb_entry->flags & TLBFlags::PTE_SET_C) {
return false;
}
// Perform full page address translation to update the PTE.C bit.
page_address_translation(guest_va, false, !!(ppc_state.msr & MSR::PR), true);
tlb_entry->flags |= TLBFlags::PTE_SET_C;
return true;
}
void mmu_dcbz(uint32_t opcode, uint32_t guest_va)
{
const uint32_t tag = guest_va & ~0xFFFUL;
TLBEntry *tlb_entry = lookup_tlb<TLBType::DTLB>(guest_va, tag).matched_entry;
if (tlb_entry == nullptr) {
// perform full address translation and refill the secondary TLB
tlb_entry = dtlb2_refill(guest_va, 1);
}
// Check if this was in a MMIO region, in which case we avoid doing the
// write, so that this intermediate state is not visible to the device
// (usually a dcbz is done to prepare a cache line as a write buffer, and
// the real values are written later).
if (tlb_entry->flags & TLBFlags::PAGE_IO) {
// Still do the same checks that mmu_write_vmem would have done to
// disallow writes to read-only regions.
prepare_dtlb_write(tlb_entry, guest_va);
return;
}
// the following is not especially efficient but necessary
// to make BlockZero under Mac OS 8.x and later to work
mmu_write_vmem<uint64_t>(opcode, guest_va + 0, 0);
mmu_write_vmem<uint64_t>(opcode, guest_va + 8, 0);
mmu_write_vmem<uint64_t>(opcode, guest_va + 16, 0);
mmu_write_vmem<uint64_t>(opcode, guest_va + 24, 0);
}
uint8_t *mmu_translate_imem(uint32_t vaddr, uint32_t *paddr)
{
#if SUPPORTS_PPC_LITTLE_ENDIAN_MODE
@@ -1027,15 +830,16 @@ uint8_t *mmu_translate_imem(uint32_t vaddr, uint32_t *paddr)
const uint32_t tag = vaddr & ~0xFFFUL;
TLBLookupResult tlb_lookup = lookup_tlb<TLBType::ITLB>(vaddr, tag);
tlb1_entry = tlb_lookup.primary_entry;
if (tlb_lookup.primary_hit) { // primary ITLB hit -> fast path
// look up guest virtual address in the primary ITLB
tlb1_entry = &pCurITLB1[(vaddr >> PPC_PAGE_SIZE_BITS) & tlb_size_mask];
if (tlb1_entry->tag == tag) { // primary ITLB hit -> fast path
#ifdef TLB_PROFILING
num_primary_itlb_hits++;
#endif
host_va = (uint8_t *)(tlb1_entry->host_va_offs_r + vaddr);
} else {
tlb2_entry = tlb_lookup.matched_entry;
// primary ITLB miss -> look up address in the secondary ITLB
tlb2_entry = lookup_secondary_tlb<TLBType::ITLB>(vaddr, tag);
if (tlb2_entry == nullptr) {
#ifdef TLB_PROFILING
num_itlb_refills++;
@@ -1050,7 +854,10 @@ uint8_t *mmu_translate_imem(uint32_t vaddr, uint32_t *paddr)
}
#endif
// refill the primary ITLB
promote_tlb_entry<TLBType::ITLB>(tlb1_entry, tlb2_entry);
tlb1_entry->tag = tag;
tlb1_entry->flags = tlb2_entry->flags;
tlb1_entry->host_va_offs_r = tlb2_entry->host_va_offs_r;
tlb1_entry->phys_tag = tlb2_entry->phys_tag;
host_va = (uint8_t *)(tlb1_entry->host_va_offs_r + vaddr);
}
@@ -1060,14 +867,135 @@ uint8_t *mmu_translate_imem(uint32_t vaddr, uint32_t *paddr)
return host_va;
}
void tlb_flush_all_pat()
static void tlb_flush_primary_entry(std::array<TLBEntry, TLB_SIZE> &tlb1, uint32_t tag)
{
#ifdef MMU_PROFILING
pat_flushes_total++;
#endif
TLBEntry *tlb_entry = &tlb1[(tag >> PPC_PAGE_SIZE_BITS) & tlb_size_mask];
if (tlb_entry->tag != TLB_INVALID_TAG && (tlb_entry->tag & TLB_VPS_MASK) == tag) {
tlb_entry->tag = TLB_INVALID_TAG;
//LOG_F(INFO, "Invalidated primary TLB entry at 0x%X", tag);
}
}
tlb_invalidate_tracked_entries(gTrackedIEntries, TLBE_FROM_PAT);
tlb_invalidate_tracked_entries(gTrackedDEntries, TLBE_FROM_PAT);
static void tlb_flush_secondary_entry(std::array<TLBEntry, TLB_SIZE*TLB2_WAYS> &tlb2, uint32_t tag)
{
TLBEntry *tlb_entry = &tlb2[((tag >> PPC_PAGE_SIZE_BITS) & tlb_size_mask) * TLB2_WAYS];
for (int i = 0; i < TLB2_WAYS; i++) {
if (tlb_entry[i].tag != TLB_INVALID_TAG && (tlb_entry[i].tag & TLB_VPS_MASK) == tag) {
tlb_entry[i].tag = TLB_INVALID_TAG;
//LOG_F(INFO, "Invalidated secondary TLB entry at 0x%X", tag);
}
}
}
void tlb_flush_entry(uint32_t ea)
{
const uint32_t tag = ea & TLB_VPS_MASK;
tlb_flush_primary_entry(itlb1_mode1, tag);
tlb_flush_secondary_entry(itlb2_mode1, tag);
tlb_flush_primary_entry(itlb1_mode2, tag);
tlb_flush_secondary_entry(itlb2_mode2, tag);
tlb_flush_primary_entry(itlb1_mode3, tag);
tlb_flush_secondary_entry(itlb2_mode3, tag);
tlb_flush_primary_entry(dtlb1_mode1, tag);
tlb_flush_secondary_entry(dtlb2_mode1, tag);
tlb_flush_primary_entry(dtlb1_mode2, tag);
tlb_flush_secondary_entry(dtlb2_mode2, tag);
tlb_flush_primary_entry(dtlb1_mode3, tag);
tlb_flush_secondary_entry(dtlb2_mode3, tag);
}
template <std::size_t N>
static void tlb_flush_entries(std::array<TLBEntry, N> &tlb, TLBFlags type) {
for (auto &tlb_el : tlb) {
if (tlb_el.tag != TLB_INVALID_TAG && tlb_el.flags & type) {
tlb_el.tag = TLB_INVALID_TAG;
}
}
}
template <const TLBType tlb_type>
void tlb_flush_entries(TLBFlags type)
{
// Mode 1 is real addressing and thus can't contain any PAT entries by definition.
bool flush_mode1 = type != TLBE_FROM_PAT;
if (tlb_type == TLBType::ITLB) {
if (flush_mode1) {
tlb_flush_entries(itlb1_mode1, type);
}
tlb_flush_entries(itlb1_mode2, type);
tlb_flush_entries(itlb1_mode3, type);
if (flush_mode1) {
tlb_flush_entries(itlb2_mode1, type);
}
tlb_flush_entries(itlb2_mode2, type);
tlb_flush_entries(itlb2_mode3, type);
} else {
if (flush_mode1) {
tlb_flush_entries(dtlb1_mode1, type);
}
tlb_flush_entries(dtlb1_mode2, type);
tlb_flush_entries(dtlb1_mode3, type);
if (flush_mode1) {
tlb_flush_entries(dtlb2_mode1, type);
}
tlb_flush_entries(dtlb2_mode2, type);
tlb_flush_entries(dtlb2_mode3, type);
}
}
bool gTLBFlushIBatEntries = false;
bool gTLBFlushDBatEntries = false;
bool gTLBFlushIPatEntries = false;
bool gTLBFlushDPatEntries = false;
template <const TLBType tlb_type>
void tlb_flush_bat_entries()
{
if (tlb_type == TLBType::ITLB) {
if (!gTLBFlushIBatEntries)
return;
tlb_flush_entries<TLBType::ITLB>(TLBE_FROM_BAT);
gTLBFlushIBatEntries = false;
} else {
if (!gTLBFlushDBatEntries)
return;
tlb_flush_entries<TLBType::DTLB>(TLBE_FROM_BAT);
gTLBFlushDBatEntries = false;
}
}
template <const TLBType tlb_type>
void tlb_flush_pat_entries()
{
if (tlb_type == TLBType::ITLB) {
if (!gTLBFlushIPatEntries)
return;
tlb_flush_entries<TLBType::ITLB>(TLBE_FROM_PAT);
gTLBFlushIPatEntries = false;
} else {
if (!gTLBFlushDPatEntries)
return;
tlb_flush_entries<TLBType::DTLB>(TLBE_FROM_PAT);
gTLBFlushDPatEntries = false;
}
}
template <const TLBType tlb_type>
void tlb_flush_all_entries()
{
if (tlb_type == TLBType::ITLB) {
if (!gTLBFlushIBatEntries && !gTLBFlushIPatEntries)
return;
tlb_flush_entries<TLBType::ITLB>((TLBFlags)(TLBE_FROM_BAT | TLBE_FROM_PAT));
gTLBFlushIBatEntries = false;
gTLBFlushIPatEntries = false;
} else {
if (!gTLBFlushDBatEntries && !gTLBFlushDPatEntries)
return;
tlb_flush_entries<TLBType::DTLB>((TLBFlags)(TLBE_FROM_BAT | TLBE_FROM_PAT));
gTLBFlushDBatEntries = false;
gTLBFlushDPatEntries = false;
}
}
static void mpc601_bat_update(uint32_t bat_reg)
@@ -1095,19 +1023,25 @@ static void mpc601_bat_update(uint32_t bat_reg)
// copy IBAT entry to DBAT entry
*dbat_entry = *ibat_entry;
} else {
// disable the corresponding BAT pairs
// disable the corresponding BAT paars
ibat_entry->valid = false;
dbat_entry->valid = false;
}
// MPC601 has unified BATs, so they affect both translation contexts.
schedule_tlb_invalidation(TLBType::ITLB, TLBE_FROM_TRANSLATION);
schedule_tlb_invalidation(TLBType::DTLB, TLBE_FROM_TRANSLATION);
// MPC601 has unified BATs so we're going to flush both ITLB and DTLB
if (!gTLBFlushIBatEntries || !gTLBFlushIPatEntries || !gTLBFlushDBatEntries || !gTLBFlushDPatEntries) {
gTLBFlushIBatEntries = true;
gTLBFlushIPatEntries = true;
gTLBFlushDBatEntries = true;
gTLBFlushDPatEntries = true;
add_ctx_sync_action(&tlb_flush_all_entries<TLBType::ITLB>);
add_ctx_sync_action(&tlb_flush_all_entries<TLBType::DTLB>);
}
}
static void mpc601_dbat_update(uint32_t /*bat_reg*/)
{
// ppc_illegalop(opcode);
// ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
static void ppc_ibat_update(uint32_t bat_reg)
@@ -1128,8 +1062,11 @@ static void ppc_ibat_update(uint32_t bat_reg)
bat_entry->phys_hi = ppc_state.spr[upper_reg_num + 1] & hi_mask;
bat_entry->bepi = ppc_state.spr[upper_reg_num] & hi_mask;
// A new IBAT can shadow an existing page translation.
schedule_tlb_invalidation(TLBType::ITLB, TLBE_FROM_TRANSLATION);
if (!gTLBFlushIBatEntries || !gTLBFlushIPatEntries) {
gTLBFlushIBatEntries = true;
gTLBFlushIPatEntries = true;
add_ctx_sync_action(&tlb_flush_all_entries<TLBType::ITLB>);
}
}
static void ppc_dbat_update(uint32_t bat_reg)
@@ -1150,16 +1087,23 @@ static void ppc_dbat_update(uint32_t bat_reg)
bat_entry->phys_hi = ppc_state.spr[upper_reg_num + 1] & hi_mask;
bat_entry->bepi = ppc_state.spr[upper_reg_num] & hi_mask;
// A new DBAT can shadow an existing page translation.
schedule_tlb_invalidation(TLBType::DTLB, TLBE_FROM_TRANSLATION);
if (!gTLBFlushDBatEntries || !gTLBFlushDPatEntries) {
gTLBFlushDBatEntries = true;
gTLBFlushDPatEntries = true;
add_ctx_sync_action(&tlb_flush_all_entries<TLBType::DTLB>);
}
}
void mmu_pat_ctx_changed()
{
// Page address translation context changed so invalidate all PAT entries
// from both ITLB and DTLB.
schedule_tlb_invalidation(TLBType::ITLB, TLBFlags::TLBE_FROM_PAT);
schedule_tlb_invalidation(TLBType::DTLB, TLBFlags::TLBE_FROM_PAT);
// Page address translation context changed so we need to flush
// all PAT entries from both ITLB and DTLB
if (!gTLBFlushIPatEntries || !gTLBFlushDPatEntries) {
gTLBFlushIPatEntries = true;
gTLBFlushDPatEntries = true;
add_ctx_sync_action(&tlb_flush_pat_entries<TLBType::ITLB>);
add_ctx_sync_action(&tlb_flush_pat_entries<TLBType::DTLB>);
}
}
#if SUPPORTS_PPC_LITTLE_ENDIAN_MODE
@@ -1204,13 +1148,12 @@ inline T mmu_read_vmem(uint32_t opcode, uint32_t guest_va)
const uint32_t tag = guest_va & ~0xFFFUL;
// look up guest virtual address in the primary and secondary TLBs
// look up guest virtual address in the primary TLB
#if SUPPORTS_MEMORY_CTRL_ENDIAN_MODE
bool needs_swap = false;
#endif
TLBLookupResult tlb_lookup = lookup_tlb<TLBType::DTLB>(guest_va, tag);
tlb1_entry = tlb_lookup.primary_entry;
if (tlb_lookup.primary_hit) { // primary TLB hit -> fast path
tlb1_entry = &pCurDTLB1[(guest_va >> PPC_PAGE_SIZE_BITS) & tlb_size_mask];
if (tlb1_entry->tag == tag) { // primary TLB hit -> fast path
#ifdef TLB_PROFILING
num_primary_dtlb_hits++;
#endif
@@ -1225,7 +1168,8 @@ inline T mmu_read_vmem(uint32_t opcode, uint32_t guest_va)
host_va = (uint8_t *)(tlb1_entry->host_va_offs_r + guest_va);
} else {
tlb2_entry = tlb_lookup.matched_entry;
// primary TLB miss -> look up address in the secondary TLB
tlb2_entry = lookup_secondary_tlb<TLBType::DTLB>(guest_va, tag);
if (tlb2_entry == nullptr) {
#ifdef TLB_PROFILING
num_dtlb_refills++;
@@ -1245,7 +1189,7 @@ inline T mmu_read_vmem(uint32_t opcode, uint32_t guest_va)
if (tlb2_entry->flags & TLBFlags::PAGE_MEM) { // is it a real memory region?
// refill the primary TLB
promote_tlb_entry<TLBType::DTLB>(tlb1_entry, tlb2_entry);
*tlb1_entry = *tlb2_entry;
#if SUPPORTS_MEMORY_CTRL_ENDIAN_MODE
needs_swap = mem_ctrl_instance->needs_swap_endian(false);
@@ -1375,17 +1319,25 @@ inline void mmu_write_vmem(uint32_t opcode, uint32_t guest_va, T value)
const uint32_t tag = guest_va & ~0xFFFUL;
// look up guest virtual address in the primary and secondary TLBs
// look up guest virtual address in the primary TLB
#if SUPPORTS_MEMORY_CTRL_ENDIAN_MODE
bool needs_swap = false;
#endif
TLBLookupResult tlb_lookup = lookup_tlb<TLBType::DTLB>(guest_va, tag);
tlb1_entry = tlb_lookup.primary_entry;
if (tlb_lookup.primary_hit) { // primary TLB hit -> fast path
tlb1_entry = &pCurDTLB1[(guest_va >> PPC_PAGE_SIZE_BITS) & tlb_size_mask];
if (tlb1_entry->tag == tag) { // primary TLB hit -> fast path
#ifdef TLB_PROFILING
num_primary_dtlb_hits++;
#endif
if (prepare_dtlb_write(tlb1_entry, guest_va)) {
if (!(tlb1_entry->flags & TLBFlags::PAGE_WRITABLE)) {
ppc_state.spr[SPR::DSISR] = 0x08000000 | (1 << 25);
ppc_state.spr[SPR::DAR] = guest_va;
mmu_exception_handler(Except_Type::EXC_DSI, 0);
}
if (!(tlb1_entry->flags & TLBFlags::PTE_SET_C)) {
// perform full page address translation to update PTE.C bit
page_address_translation(guest_va, false, !!(ppc_state.msr & MSR::PR), true);
tlb1_entry->flags |= TLBFlags::PTE_SET_C;
// don't forget to update the secondary TLB as well
tlb2_entry = lookup_secondary_tlb<TLBType::DTLB>(guest_va, tag);
if (tlb2_entry != nullptr) {
@@ -1401,7 +1353,8 @@ inline void mmu_write_vmem(uint32_t opcode, uint32_t guest_va, T value)
#endif
host_va = (uint8_t *)(tlb1_entry->host_va_offs_w + guest_va);
} else {
tlb2_entry = tlb_lookup.matched_entry;
// primary TLB miss -> look up address in the secondary TLB
tlb2_entry = lookup_secondary_tlb<TLBType::DTLB>(guest_va, tag);
if (tlb2_entry == nullptr) {
#ifdef TLB_PROFILING
num_dtlb_refills++;
@@ -1418,11 +1371,22 @@ inline void mmu_write_vmem(uint32_t opcode, uint32_t guest_va, T value)
num_secondary_dtlb_hits++;
}
#endif
prepare_dtlb_write(tlb2_entry, guest_va);
if (!(tlb2_entry->flags & TLBFlags::PAGE_WRITABLE)) {
ppc_state.spr[SPR::DSISR] = 0x08000000 | (1 << 25);
ppc_state.spr[SPR::DAR] = guest_va;
mmu_exception_handler(Except_Type::EXC_DSI, 0);
}
if (!(tlb2_entry->flags & TLBFlags::PTE_SET_C)) {
// perform full page address translation to update PTE.C bit
page_address_translation(guest_va, false, !!(ppc_state.msr & MSR::PR), true);
tlb2_entry->flags |= TLBFlags::PTE_SET_C;
}
if (tlb2_entry->flags & TLBFlags::PAGE_MEM) { // is it a real memory region?
// refill the primary TLB
promote_tlb_entry<TLBType::DTLB>(tlb1_entry, tlb2_entry);
*tlb1_entry = *tlb2_entry;
#if SUPPORTS_MEMORY_CTRL_ENDIAN_MODE
needs_swap = mem_ctrl_instance->needs_swap_endian(false);
@@ -1556,8 +1520,8 @@ static T read_unaligned(uint32_t opcode, uint32_t guest_va, uint8_t *host_va ARG
} else
#endif
{
result = (result << 8) | mmu_read_vmem<uint8_t>(opcode, guest_va);
}
result = (result << 8) | mmu_read_vmem<uint8_t>(opcode, guest_va);
}
}
#if SUPPORTS_PPC_LITTLE_ENDIAN_MODE || SUPPORTS_MEMORY_CTRL_ENDIAN_MODE
} else if (sizeof(T) == sizeof(uint64_t) && munged) {
@@ -1736,10 +1700,6 @@ public:
.format = ProfileVarFmt::DEC,
.value = ptab_transl_total});
vars.push_back({.name = "Full PAT TLB Flushes Total",
.format = ProfileVarFmt::DEC,
.value = pat_flushes_total});
vars.push_back({.name = "Unaligned Reads Total",
.format = ProfileVarFmt::DEC,
.value = unaligned_reads});
@@ -1765,7 +1725,6 @@ public:
exec_reads_total = 0;
bat_transl_total = 0;
ptab_transl_total = 0;
pat_flushes_total = 0;
unaligned_reads = 0;
unaligned_writes = 0;
unaligned_crossp_r = 0;
@@ -1935,12 +1894,13 @@ bool mmu_translate_dbg(uint32_t guest_va, uint32_t &guest_pa) {
const uint32_t tag = guest_va & ~0xFFFUL;
TLBLookupResult tlb_lookup = lookup_tlb<TLBType::DTLB>(guest_va, tag);
tlb1_entry = tlb_lookup.primary_entry;
// look up guest virtual address in the primary TLB
tlb1_entry = &pCurDTLB1[(guest_va >> PPC_PAGE_SIZE_BITS) & tlb_size_mask];
do {
if (!tlb_lookup.primary_hit) {
tlb2_entry = tlb_lookup.matched_entry;
if (tlb1_entry->tag != tag) {
// primary TLB miss -> look up address in the secondary TLB
tlb2_entry = lookup_secondary_tlb<TLBType::DTLB>(guest_va, tag);
if (tlb2_entry == nullptr) {
// secondary TLB miss ->
// perform full address translation and refill the secondary TLB
@@ -1953,7 +1913,7 @@ bool mmu_translate_dbg(uint32_t guest_va, uint32_t &guest_pa) {
if (tlb2_entry->flags & TLBFlags::PAGE_MEM) { // is it a real memory region?
// refill the primary TLB
promote_tlb_entry<TLBType::DTLB>(tlb1_entry, tlb2_entry);
*tlb1_entry = *tlb2_entry;
}
else {
tlb1_entry = tlb2_entry;
@@ -1995,11 +1955,9 @@ static void invalidate_tlb_entries(std::array<TLBEntry, N> &tlb) {
void ppc_mmu_init()
{
gPendingIInvalidationSources = 0;
gPendingDInvalidationSources = 0;
gTrackedIEntries.clear();
gTrackedDEntries.clear();
last_read_area = {0xFFFFFFFF, 0xFFFFFFFF, 0, 0, nullptr, nullptr};
last_write_area = {0xFFFFFFFF, 0xFFFFFFFF, 0, 0, nullptr, nullptr};
last_exec_area = {0xFFFFFFFF, 0xFFFFFFFF, 0, 0, nullptr, nullptr};
last_ptab_area = {0xFFFFFFFF, 0xFFFFFFFF, 0, 0, nullptr, nullptr};
mmu_exception_handler = ppc_exception_handler;
+36 -5
View File
@@ -24,6 +24,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef PPCMMU_H
#define PPCMMU_H
#include <devices/memctrl/memctrlbase.h>
#include <cinttypes>
#include <functional>
@@ -71,7 +73,6 @@ typedef struct PATResult {
/** DMA memory mapping result. */
typedef struct MapDmaResult {
uint32_t type;
uint32_t size;
bool is_writable;
// for memory regions
uint8_t* host_va;
@@ -83,6 +84,38 @@ typedef struct MapDmaResult {
constexpr uint32_t PPC_PAGE_SIZE_BITS = 12;
constexpr uint32_t PPC_PAGE_SIZE = (1 << PPC_PAGE_SIZE_BITS);
constexpr uint32_t PPC_PAGE_MASK = ~(PPC_PAGE_SIZE - 1);
constexpr uint32_t TLB_SIZE = 4096;
constexpr uint32_t TLB2_WAYS = 4;
constexpr uint32_t TLB_INVALID_TAG = 0xFFFFFFFF;
constexpr uint32_t TLB_VPS_MASK = 0x0FFFF000; // mask for TLB invalidation
typedef struct TLBEntry {
uint32_t tag;
uint16_t flags;
uint16_t lru_bits;
union {
struct { // for memory pages
int64_t host_va_offs_r;
int64_t host_va_offs_w;
};
struct { // for MMIO pages
AddressMapEntry* rgn_desc;
int64_t dev_base_va;
};
};
uint32_t phys_tag;
uint32_t reserved;
} TLBEntry;
enum TLBFlags : uint16_t {
PAGE_MEM = 1 << 0, // memory page backed by host memory
PAGE_IO = 1 << 1, // memory mapped I/O page
PAGE_NOPHYS = 1 << 2, // no physical storage for this page (unmapped)
TLBE_FROM_BAT = 1 << 3, // TLB entry has been translated with BAT
TLBE_FROM_PAT = 1 << 4, // TLB entry has been translated with PAT
PAGE_WRITABLE = 1 << 5, // page is writable
PTE_SET_C = 1 << 6, // tells if C bit of the PTE needs to be updated
};
extern std::function<void(uint32_t bat_reg)> ibat_update;
extern std::function<void(uint32_t bat_reg)> dbat_update;
@@ -90,13 +123,11 @@ extern std::function<void(uint32_t bat_reg)> dbat_update;
extern PPC_BAT_entry ibat_array[4];
extern PPC_BAT_entry dbat_array[4];
extern MapDmaResult mmu_map_dma_mem(uint32_t addr, uint32_t size,
bool allow_mmio = false, bool allow_partial = false, bool is_dbg = false);
extern MapDmaResult mmu_map_dma_mem(uint32_t addr, uint32_t size, bool allow_mmio = false, bool is_dbg = false);
extern void mmu_change_mode(void);
extern void mmu_pat_ctx_changed();
extern void tlb_flush_all_pat();
extern void mmu_dcbz(uint32_t opcode, uint32_t guest_va);
extern void tlb_flush_entry(uint32_t ea);
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);
+156 -215
View File
@@ -24,16 +24,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <core/bitops.h>
#include <core/timermanager.h>
#include <core/mathutils.h>
#include <cpu/ppc/ppcdechelpers.h>
#include <cpu/ppc/ppcemu.h>
#include <cpu/ppc/ppcmmu.h>
#include "ppcemu.h"
#include "ppcmacros.h"
#include "ppcmmu.h"
#include <cinttypes>
#include <vector>
static int junction_temperature = 24;
static TimerInfo thermal_timer;
//Extract the registers desired and the values of the registers.
// Affects CR Field 0 - For integer operations
@@ -52,14 +48,30 @@ void ppc_changecrf0(uint32_t set_result) {
}
// Affects the XER register's Carry Bit
inline static void ppc_carry(uint64_t ppc_result_l) {
ppc_state.spr[SPR::XER] = (ppc_state.spr[SPR::XER] & ~XER::CA) | ((ppc_result_l >> (32 - 29)) & XER::CA);
inline static void ppc_carry(uint32_t a, uint32_t b) {
if (b < a) {
ppc_state.spr[SPR::XER] |= XER::CA;
} else {
ppc_state.spr[SPR::XER] &= ~XER::CA;
}
}
inline static void ppc_carry_sub(uint32_t a, uint32_t b) {
if (b >= a) {
ppc_state.spr[SPR::XER] |= XER::CA;
} else {
ppc_state.spr[SPR::XER] &= ~XER::CA;
}
}
// Affects the XER register's SO and OV Bits
inline static void ppc_setsoov(uint32_t a, uint32_t b, uint32_t d) {
ppc_state.spr[SPR::XER] = (ppc_state.spr[SPR::XER] & ~XER::OV) |
((int32_t((a ^ b) & (a ^ d)) < 0) ? (XER::SO | XER::OV) : 0);
if (int32_t((a ^ b) & (a ^ d)) < 0) {
ppc_state.spr[SPR::XER] |= XER::SO | XER::OV;
} else {
ppc_state.spr[SPR::XER] &= ~XER::OV;
}
}
typedef std::function<void()> CtxSyncCallback;
@@ -99,9 +111,8 @@ template void dppc_interpreter::ppc_addi<SHFT1>(uint32_t opcode);
template <field_rc rec>
void dppc_interpreter::ppc_addic(uint32_t opcode) {
ppc_grab_regsdasimm(opcode);
uint64_t ppc_result_l = uint64_t(ppc_result_a) + uint32_t(simm);
uint32_t ppc_result_d = uint32_t(ppc_result_l);
ppc_carry(ppc_result_l);
uint32_t ppc_result_d = (ppc_result_a + simm);
ppc_carry(ppc_result_a, ppc_result_d);
if (rec)
ppc_changecrf0(ppc_result_d);
ppc_store_iresult_reg(reg_d, ppc_result_d);
@@ -113,10 +124,10 @@ template void dppc_interpreter::ppc_addic<RC1>(uint32_t opcode);
template <field_carry carry, field_rc rec, field_ov ov>
void dppc_interpreter::ppc_add(uint32_t opcode) {
ppc_grab_regsdab(opcode);
uint64_t ppc_result_l = uint64_t(ppc_result_a) + ppc_result_b;
uint32_t ppc_result_d = uint32_t(ppc_result_l);
uint32_t ppc_result_d = ppc_result_a + ppc_result_b;
if (carry)
ppc_carry(ppc_result_l);
ppc_carry(ppc_result_a, ppc_result_d);
if (ov)
ppc_setsoov(ppc_result_a, ~ppc_result_b, ppc_result_d);
if (rec)
@@ -137,9 +148,14 @@ template <field_rc rec, field_ov ov>
void dppc_interpreter::ppc_adde(uint32_t opcode) {
ppc_grab_regsdab(opcode);
uint32_t xer_ca = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint64_t ppc_result_l = uint64_t(ppc_result_a) + ppc_result_b + xer_ca;
uint32_t ppc_result_d = uint32_t(ppc_result_l);
ppc_carry(ppc_result_l);
uint32_t ppc_result_d = ppc_result_a + ppc_result_b + xer_ca;
if ((ppc_result_d < ppc_result_a) || (xer_ca && (ppc_result_d == ppc_result_a))) {
ppc_state.spr[SPR::XER] |= XER::CA;
} else {
ppc_state.spr[SPR::XER] &= ~XER::CA;
}
if (ov)
ppc_setsoov(ppc_result_a, ~ppc_result_b, ppc_result_d);
if (rec)
@@ -157,9 +173,14 @@ template <field_rc rec, field_ov ov>
void dppc_interpreter::ppc_addme(uint32_t opcode) {
ppc_grab_regsda(opcode);
uint32_t xer_ca = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint64_t ppc_result_l = uint64_t(ppc_result_a) + xer_ca + uint32_t(-1);
uint32_t ppc_result_d = uint32_t(ppc_result_l);
ppc_carry(ppc_result_l);
uint32_t ppc_result_d = ppc_result_a + xer_ca - 1;
if (((xer_ca - 1) < 0xFFFFFFFFUL) || (ppc_result_d < ppc_result_a)) {
ppc_state.spr[SPR::XER] |= XER::CA;
} else {
ppc_state.spr[SPR::XER] &= ~XER::CA;
}
if (ov)
ppc_setsoov(ppc_result_a, 0, ppc_result_d);
if (rec)
@@ -176,10 +197,15 @@ template void dppc_interpreter::ppc_addme<RC1, OV1>(uint32_t opcode);
template <field_rc rec, field_ov ov>
void dppc_interpreter::ppc_addze(uint32_t opcode) {
ppc_grab_regsda(opcode);
uint32_t xer_ca = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint64_t ppc_result_l = uint64_t(ppc_result_a) + xer_ca;
uint32_t ppc_result_d = uint32_t(ppc_result_l);
ppc_carry(ppc_result_l);
uint32_t grab_xer = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint32_t ppc_result_d = ppc_result_a + grab_xer;
if (ppc_result_d < ppc_result_a) {
ppc_state.spr[SPR::XER] |= XER::CA;
} else {
ppc_state.spr[SPR::XER] &= ~XER::CA;
}
if (ov)
ppc_setsoov(ppc_result_a, 0xFFFFFFFFUL, ppc_result_d);
if (rec)
@@ -195,19 +221,21 @@ template void dppc_interpreter::ppc_addze<RC1, OV1>(uint32_t opcode);
void dppc_interpreter::ppc_subfic(uint32_t opcode) {
ppc_grab_regsdasimm(opcode);
uint64_t ppc_result_l = uint64_t(uint32_t(~ppc_result_a)) + uint32_t(simm) + 1;
uint32_t ppc_result_d = uint32_t(ppc_result_l);
ppc_carry(ppc_result_l);
uint32_t ppc_result_d = simm - ppc_result_a;
if (simm == -1)
ppc_state.spr[SPR::XER] |= XER::CA;
else
ppc_carry(~ppc_result_a, ppc_result_d);
ppc_store_iresult_reg(reg_d, ppc_result_d);
}
template <field_carry carry, field_rc rec, field_ov ov>
void dppc_interpreter::ppc_subf(uint32_t opcode) {
ppc_grab_regsdab(opcode);
uint64_t ppc_result_l = uint64_t(uint32_t(~ppc_result_a)) + ppc_result_b + 1;
uint32_t ppc_result_d = uint32_t(ppc_result_l);
uint32_t ppc_result_d = ppc_result_b - ppc_result_a;
if (carry)
ppc_carry(ppc_result_l);
ppc_carry_sub(ppc_result_a, ppc_result_b);
if (ov)
ppc_setsoov(ppc_result_b, ppc_result_a, ppc_result_d);
if (rec)
@@ -228,10 +256,13 @@ template void dppc_interpreter::ppc_subf<CARRY1, RC1, OV1>(uint32_t opcode);
template <field_rc rec, field_ov ov>
void dppc_interpreter::ppc_subfe(uint32_t opcode) {
ppc_grab_regsdab(opcode);
uint32_t xer_ca = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint64_t ppc_result_l = uint64_t(uint32_t(~ppc_result_a)) + ppc_result_b + xer_ca;
uint32_t ppc_result_d = uint32_t(ppc_result_l);
ppc_carry(ppc_result_l);
uint32_t grab_ca = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint32_t ppc_result_d = ~ppc_result_a + ppc_result_b + grab_ca;
if (grab_ca && ppc_result_b == 0xFFFFFFFFUL)
ppc_state.spr[SPR::XER] |= XER::CA;
else
ppc_carry(~ppc_result_a, ppc_result_d);
if (ov)
ppc_setsoov(ppc_result_b, ppc_result_a, ppc_result_d);
if (rec)
@@ -248,10 +279,14 @@ template void dppc_interpreter::ppc_subfe<RC1, OV1>(uint32_t opcode);
template <field_rc rec, field_ov ov>
void dppc_interpreter::ppc_subfme(uint32_t opcode) {
ppc_grab_regsda(opcode);
uint32_t xer_ca = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint64_t ppc_result_l = uint64_t(uint32_t(~ppc_result_a)) + xer_ca + uint32_t(-1);
uint32_t ppc_result_d = uint32_t(ppc_result_l);
ppc_carry(ppc_result_l);
uint32_t grab_ca = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint32_t ppc_result_d = ~ppc_result_a + grab_ca - 1;
if (ppc_result_a == 0xFFFFFFFFUL && !grab_ca)
ppc_state.spr[SPR::XER] &= ~XER::CA;
else
ppc_state.spr[SPR::XER] |= XER::CA;
if (ov) {
if (ppc_result_d == ppc_result_a && int32_t(ppc_result_d) > 0)
ppc_state.spr[SPR::XER] |= XER::SO | XER::OV;
@@ -273,10 +308,14 @@ template void dppc_interpreter::ppc_subfme<RC1, OV1>(uint32_t opcode);
template <field_rc rec, field_ov ov>
void dppc_interpreter::ppc_subfze(uint32_t opcode) {
ppc_grab_regsda(opcode);
uint32_t xer_ca = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint64_t ppc_result_l = uint64_t(uint32_t(~ppc_result_a)) + xer_ca;
uint32_t ppc_result_d = uint32_t(ppc_result_l);
ppc_carry(ppc_result_l);
uint32_t grab_ca = !!(ppc_state.spr[SPR::XER] & XER::CA);
uint32_t ppc_result_d = ~ppc_result_a + grab_ca;
if (!ppc_result_d && grab_ca) // special case: ppc_result_d = 0 and CA=1
ppc_state.spr[SPR::XER] |= XER::CA;
else
ppc_state.spr[SPR::XER] &= ~XER::CA;
if (ov) {
if (ppc_result_d && ppc_result_d == ppc_result_a)
ppc_state.spr[SPR::XER] |= XER::SO | XER::OV;
@@ -691,12 +730,11 @@ void dppc_interpreter::ppc_mtsr(uint32_t opcode) {
#endif
if (ppc_state.msr & MSR::PR) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::NOT_ALLOWED);
return;
}
ppc_grab_s(opcode);
int reg_s = (opcode >> 21) & 0x1F;
uint32_t grab_sr = (opcode >> 16) & 0x0F;
if (ppc_state.sr[grab_sr] != ppc_result_d) {
ppc_state.sr[grab_sr] = ppc_result_d;
if (ppc_state.sr[grab_sr] != ppc_state.gpr[reg_s]) {
ppc_state.sr[grab_sr] = ppc_state.gpr[reg_s];
mmu_pat_ctx_changed();
}
}
@@ -707,7 +745,6 @@ void dppc_interpreter::ppc_mtsrin(uint32_t opcode) {
#endif
if (ppc_state.msr & MSR::PR) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::NOT_ALLOWED);
return;
}
ppc_grab_regssb(opcode);
uint32_t grab_sr = ppc_result_b >> 28;
@@ -723,7 +760,6 @@ void dppc_interpreter::ppc_mfsr(uint32_t opcode) {
#endif
if (ppc_state.msr & MSR::PR) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::NOT_ALLOWED);
return;
}
int reg_d = (opcode >> 21) & 0x1F;
uint32_t grab_sr = (opcode >> 16) & 0x0F;
@@ -736,7 +772,6 @@ void dppc_interpreter::ppc_mfsrin(uint32_t opcode) {
#endif
if (ppc_state.msr & MSR::PR) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::NOT_ALLOWED);
return;
}
ppc_grab_regsdb(opcode);
uint32_t grab_sr = ppc_result_b >> 28;
@@ -749,7 +784,6 @@ void dppc_interpreter::ppc_mfmsr(uint32_t opcode) {
#endif
if (ppc_state.msr & MSR::PR) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::NOT_ALLOWED);
return;
}
uint32_t reg_d = (opcode >> 21) & 0x1F;
ppc_state.gpr[reg_d] = ppc_state.msr;
@@ -761,11 +795,10 @@ void dppc_interpreter::ppc_mtmsr(uint32_t opcode) {
#endif
if (ppc_state.msr & MSR::PR) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::NOT_ALLOWED);
return;
}
ppc_grab_s(opcode);
uint32_t reg_s = (opcode >> 21) & 0x1F;
uint32_t old_msr_val = ppc_state.msr;
uint32_t new_msr_val = ppc_result_d;
uint32_t new_msr_val = ppc_state.gpr[reg_s];
if (!is_601) {
ppc_change_endian((new_msr_val & MSR::LE) != 0);
}
@@ -780,9 +813,6 @@ void dppc_interpreter::ppc_mtmsr(uint32_t opcode) {
dec_exception_pending = false;
//LOG_F(WARNING, "MTMSR: decrementer exception triggered");
ppc_exception_handler(Except_Type::EXC_DECR, 0);
} else if ((ppc_state.msr & MSR::EE) && thrm_exception_pending) {
thrm_exception_pending = false;
ppc_exception_handler(Except_Type::EXC_THRM_MGMT_INT, 0);
} else if (ppc_state.msr & MSR::POW) [[unlikely]] {
bool enter_sleep = false;
@@ -872,11 +902,11 @@ static void update_timebase(uint64_t mask, uint64_t new_val)
tbr_wr_timestamp = get_virt_time_ns();
}
static TimerInfo decrementer_timer;
static uint32_t decrementer_timer_id = 0;
static void update_decrementer(bool update_time_stamp, uint32_t oldval, uint32_t newval);
static void trigger_decrementer_exception(uint64_t = 0, uint64_t = 0) {
static void trigger_decrementer_exception() {
if (ppc_state.msr & MSR::EE) {
dec_exception_pending = false;
//LOG_F(WARNING, "decrementer exception triggered");
@@ -888,7 +918,8 @@ static void trigger_decrementer_exception(uint64_t = 0, uint64_t = 0) {
}
}
static void trigger_timed_decrementer_exception(uint64_t, uint64_t) {
static void trigger_timed_decrementer_exception() {
decrementer_timer_id = 0;
uint32_t new_val = calc_dec_value();
if (new_val >= 0 && new_val != uint32_t(-1)) {
new_val = -1;
@@ -897,7 +928,8 @@ static void trigger_timed_decrementer_exception(uint64_t, uint64_t) {
trigger_decrementer_exception();
}
static void trigger_immediate_decrementer_exception(uint64_t, uint64_t) {
static void trigger_immediate_decrementer_exception() {
decrementer_timer_id = 0;
update_decrementer(false, ppc_state.spr[SPR::DEC_S], ppc_state.spr[SPR::DEC_S]);
trigger_decrementer_exception();
}
@@ -910,12 +942,12 @@ static void update_decrementer(bool update_time_stamp, uint32_t oldval, uint32_t
dec_exception_pending = false;
if (decrementer_timer.active) {
TimerManager::get_instance()->cancel_timer(decrementer_timer);
if (decrementer_timer_id) {
TimerManager::get_instance()->cancel_timer(decrementer_timer_id);
}
if (bit_changed(oldval, newval, 31) && bit_set(newval, 31)) {
TimerManager::get_instance()->add_immediate_timer(decrementer_timer,
decrementer_timer_id = TimerManager::get_instance()->add_immediate_timer(
trigger_immediate_decrementer_exception
);
return;
@@ -935,53 +967,12 @@ static void update_decrementer(bool update_time_stamp, uint32_t oldval, uint32_t
uint32_t time_out_lo;
_u32xu64(newval, tbr_period_ns, time_out, time_out_lo);
//LOG_F(WARNING, "new decrementer value: 0x%08X, interrupt after %llu ns", newval, time_out);
TimerManager::get_instance()->add_oneshot_timer(decrementer_timer,
decrementer_timer_id = TimerManager::get_instance()->add_oneshot_timer(
time_out,
trigger_timed_decrementer_exception
);
}
static void update_thermal(uint64_t, uint64_t) {
uint32_t val = ppc_state.spr[SPR::THRM3];
auto sampled_interval_timer_value = (val >> 1) & 0x1FFF;
auto enabled = val & 1;
bool interrupt = false;
for (int the_reg = 0; the_reg < 2; the_reg++) {
val = ppc_state.spr[SPR::THRM1 + the_reg];
uint32_t t_interrupt; // = (val >> 31) & 1;
uint32_t t_int_valid; // = (val >> 30) & 1;
uint32_t threshold = (val >> 23) & 0x7F;
uint32_t t_int_direction = (val >> 2) & 1;
uint32_t t_int_enable = (val >> 1) & 1;
uint32_t valid = (val >> 0) & 1;
if (!valid) {
t_interrupt = 0;
t_int_valid = 0;
} else {
t_interrupt = t_int_direction ?
junction_temperature < threshold
:
junction_temperature > threshold;
t_int_valid = 1;
interrupt |= t_int_enable && t_interrupt;
}
ppc_state.spr[SPR::THRM1 + the_reg] = (t_interrupt << 31) | (t_int_valid << 30) | (val & 0x3FFFFFFF);
}
if (interrupt && enabled) {
if (ppc_state.msr & MSR::EE) {
thrm_exception_pending = false;
ppc_exception_handler(Except_Type::EXC_THRM_MGMT_INT, 0);
}
else {
thrm_exception_pending = true;
}
}
}
void dppc_interpreter::ppc_mfspr(uint32_t opcode) {
ppc_grab_dab(opcode);
uint32_t ref_spr = (reg_b << 5) | reg_a;
@@ -999,15 +990,13 @@ void dppc_interpreter::ppc_mfspr(uint32_t opcode) {
switch (ref_spr) {
case SPR::MQ:
if (!(is_601 || include_601)) {
ppc_illegalop(opcode);
return;
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
ppc_state.gpr[reg_d] = ppc_state.spr[ref_spr];
break;
case SPR::RTCL_U:
if (!is_601) {
ppc_illegalop(opcode);
return;
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
calc_rtcl_value();
ppc_state.gpr[reg_d] =
@@ -1016,8 +1005,7 @@ void dppc_interpreter::ppc_mfspr(uint32_t opcode) {
break;
case SPR::RTCU_U:
if (!is_601) {
ppc_illegalop(opcode);
return;
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
calc_rtcl_value();
ppc_state.gpr[reg_d] =
@@ -1026,8 +1014,7 @@ void dppc_interpreter::ppc_mfspr(uint32_t opcode) {
break;
case SPR::DEC_U:
if (!is_601) {
ppc_illegalop(opcode);
return;
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
// fallthrough
case SPR::DEC_S:
@@ -1054,15 +1041,6 @@ void dppc_interpreter::ppc_mfspr(uint32_t opcode) {
ppc_state.spr[TBL_S] = uint32_t(tbr_value);
break;
}
case SPR::THRM1:
case SPR::THRM2: {
uint32_t val = ppc_state.spr[ref_spr];
ppc_state.gpr[reg_d] = val;
break;
}
case SPR::THRM3:
ppc_state.gpr[reg_d] = ppc_state.spr[ref_spr];
break;
default:
// FIXME: Unknown SPR should be noop or illegal instruction.
ppc_state.gpr[reg_d] = ppc_state.spr[ref_spr];
@@ -1090,13 +1068,13 @@ void dppc_interpreter::ppc_mtspr(uint32_t opcode) {
if (is_601 || include_601)
ppc_state.spr[ref_spr] = val;
else
ppc_illegalop(opcode);
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
break;
case SPR::RTCL_U:
case SPR::RTCU_U:
case SPR::DEC_U:
if (!is_601) {
ppc_illegalop(opcode);
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
break;
case SPR::XER:
@@ -1144,10 +1122,8 @@ void dppc_interpreter::ppc_mtspr(uint32_t opcode) {
case 533:
case 534:
case 535:
if (ppc_state.spr[ref_spr] != val) {
ppc_state.spr[ref_spr] = val;
ibat_update(ref_spr);
}
ppc_state.spr[ref_spr] = val;
ibat_update(ref_spr);
break;
case 536:
case 537:
@@ -1157,10 +1133,8 @@ void dppc_interpreter::ppc_mtspr(uint32_t opcode) {
case 541:
case 542:
case 543:
if (ppc_state.spr[ref_spr] != val) {
ppc_state.spr[ref_spr] = val;
dbat_update(ref_spr);
}
ppc_state.spr[ref_spr] = val;
dbat_update(ref_spr);
break;
case SPR::HID0:
ppc_state.spr[ref_spr] = val;
@@ -1168,25 +1142,6 @@ void dppc_interpreter::ppc_mtspr(uint32_t opcode) {
ppc_change_endian((val & 0x10000000) != 0);
}
break;
case SPR::THRM1:
case SPR::THRM2: {
ppc_state.spr[ref_spr] = val & 0x3F800007;
if (thermal_timer.active)
TimerManager::get_instance()->cancel_timer(thermal_timer);
TimerManager::get_instance()->add_oneshot_timer(thermal_timer, USECS_TO_NSECS(20), update_thermal);
break;
}
case SPR::THRM3: {
ppc_state.spr[ref_spr] = val & 0x00003FFF;
ppc_state.spr[SPR::THRM1] &= ~(3<<30);
ppc_state.spr[SPR::THRM2] &= ~(3<<30);
if (thermal_timer.active)
TimerManager::get_instance()->cancel_timer(thermal_timer);
TimerManager::get_instance()->add_oneshot_timer(thermal_timer, USECS_TO_NSECS(20), update_thermal);
break;
}
default:
// FIXME: Unknown SPR should be noop or illegal instruction.
ppc_state.spr[ref_spr] = val;
@@ -1211,7 +1166,7 @@ void dppc_interpreter::ppc_mftb(uint32_t opcode) {
ppc_state.spr[TBL_S] = uint32_t(tbr_value);
break;
default:
ppc_illegalop(opcode);
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
}
@@ -1548,18 +1503,14 @@ void dppc_interpreter::ppc_rfi(uint32_t opcode) {
ppc_msr_did_change(ppc_state.msr, new_msr_val);
// setting MSR[EE] may enable pending exceptions
if ((ppc_state.msr & MSR::EE) && (int_pin || dec_exception_pending || thrm_exception_pending)) {
if ((ppc_state.msr & MSR::EE) && (int_pin || dec_exception_pending)) {
uint32_t save_srr0 = ppc_state.spr[SPR::SRR0] & ~3UL;
if (int_pin) // check for pending external exceptions (higher priority)
ppc_exception_handler(Except_Type::EXC_EXT_INT, 0);
else if (dec_exception_pending) {
else {
dec_exception_pending = false;
ppc_exception_handler(Except_Type::EXC_DECR, 0);
}
else if (thrm_exception_pending) {
thrm_exception_pending = false;
ppc_exception_handler(Except_Type::EXC_THRM_MGMT_INT, 0);
}
ppc_state.spr[SPR::SRR0] = save_srr0;
return;
}
@@ -1579,25 +1530,27 @@ void dppc_interpreter::ppc_sc(uint32_t opcode) {
}
void dppc_interpreter::ppc_tw(uint32_t opcode) {
ppc_grab_regsab(opcode);
uint32_t reg_a = (opcode >> 11) & 0x1F;
uint32_t reg_b = (opcode >> 16) & 0x1F;
uint32_t ppc_to = (opcode >> 21) & 0x1F;
if (((int32_t(ppc_result_a) < int32_t(ppc_result_b)) && (ppc_to & 0x10)) ||
((int32_t(ppc_result_a) > int32_t(ppc_result_b)) && (ppc_to & 0x08)) ||
((int32_t(ppc_result_a) == int32_t(ppc_result_b)) && (ppc_to & 0x04)) ||
((ppc_result_a < ppc_result_b) && (ppc_to & 0x02)) ||
((ppc_result_a > ppc_result_b) && (ppc_to & 0x01))) {
if (((int32_t(ppc_state.gpr[reg_a]) < int32_t(ppc_state.gpr[reg_b])) && (ppc_to & 0x10)) ||
((int32_t(ppc_state.gpr[reg_a]) > int32_t(ppc_state.gpr[reg_b])) && (ppc_to & 0x08)) ||
((int32_t(ppc_state.gpr[reg_a]) == int32_t(ppc_state.gpr[reg_b])) && (ppc_to & 0x04)) ||
((ppc_state.gpr[reg_a] < ppc_state.gpr[reg_b]) && (ppc_to & 0x02)) ||
((ppc_state.gpr[reg_a] > ppc_state.gpr[reg_b]) && (ppc_to & 0x01))) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::TRAP);
}
}
void dppc_interpreter::ppc_twi(uint32_t opcode) {
ppc_grab_regsasimm(opcode);
int32_t simm = int32_t(int16_t(opcode));
uint32_t reg_a = (opcode >> 16) & 0x1F;
uint32_t ppc_to = (opcode >> 21) & 0x1F;
if (((int32_t(ppc_result_a) < simm) && (ppc_to & 0x10)) ||
((int32_t(ppc_result_a) > simm) && (ppc_to & 0x08)) ||
((int32_t(ppc_result_a) == simm) && (ppc_to & 0x04)) ||
(ppc_result_a < uint32_t(simm) && (ppc_to & 0x02)) ||
(ppc_result_a > uint32_t(simm) && (ppc_to & 0x01))) {
if (((int32_t(ppc_state.gpr[reg_a]) < simm) && (ppc_to & 0x10)) ||
((int32_t(ppc_state.gpr[reg_a]) > simm) && (ppc_to & 0x08)) ||
((int32_t(ppc_state.gpr[reg_a]) == simm) && (ppc_to & 0x04)) ||
(ppc_state.gpr[reg_a] < uint32_t(simm) && (ppc_to & 0x02)) ||
(ppc_state.gpr[reg_a] > uint32_t(simm) && (ppc_to & 0x01))) {
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::TRAP);
}
}
@@ -1653,7 +1606,12 @@ void dppc_interpreter::ppc_dcbz(uint32_t opcode) {
ea &= 0xFFFFFFE0UL; // align EA on a 32-byte boundary
mmu_dcbz(opcode, ea);
// the following is not especially efficient but necessary
// to make BlockZero under Mac OS 8.x and later to work
mmu_write_vmem<uint64_t>(opcode, ea + 0, 0);
mmu_write_vmem<uint64_t>(opcode, ea + 8, 0);
mmu_write_vmem<uint64_t>(opcode, ea + 16, 0);
mmu_write_vmem<uint64_t>(opcode, ea + 24, 0);
}
@@ -1696,17 +1654,13 @@ void dppc_interpreter::ppc_stu(uint32_t opcode) {
ppc_grab_regssa(opcode);
if (reg_a != 0) {
uint32_t ea = ppc_result_a + int32_t(int16_t(opcode));
uint32_t ea = int32_t(int16_t(opcode));
ea += ppc_result_a;
mmu_write_vmem<T>(opcode, ea, ppc_result_d);
ppc_state.gpr[reg_a] = ea;
}
else if (is_601) {
// MPC601 permits RA=0 for POWER compatibility and suppresses the update.
uint32_t ea = int32_t(int16_t(opcode));
mmu_write_vmem<T>(opcode, ea, ppc_result_d);
}
else {
ppc_illegalop(opcode);
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
}
@@ -1727,13 +1681,8 @@ void dppc_interpreter::ppc_stux(uint32_t opcode) {
mmu_write_vmem<T>(opcode, ea, ppc_result_d);
ppc_state.gpr[reg_a] = ea;
}
else if (is_601) {
// MPC601 permits RA=0 for POWER compatibility and suppresses the update.
uint32_t ea = ppc_result_b;
mmu_write_vmem<T>(opcode, ea, ppc_result_d);
}
else {
ppc_illegalop(opcode);
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
}
@@ -1800,8 +1749,8 @@ void dppc_interpreter::ppc_lz(uint32_t opcode) {
#ifdef CPU_PROFILING
num_int_loads++;
#endif
ppc_grab_regsdasimm(opcode);
uint32_t ea = simm;
ppc_grab_regsda(opcode);
uint32_t ea = int32_t(int16_t(opcode));
ea += reg_a ? ppc_result_a : 0;
uint32_t ppc_result_d = mmu_read_vmem<T>(opcode, ea);
ppc_store_iresult_reg(reg_d, ppc_result_d);
@@ -1816,16 +1765,16 @@ void dppc_interpreter::ppc_lzu(uint32_t opcode) {
#ifdef CPU_PROFILING
num_int_loads++;
#endif
ppc_grab_regsdasimm(opcode);
uint32_t ea = simm;
if ((reg_a != reg_d) && (reg_a != 0)) {
ppc_grab_regsda(opcode);
uint32_t ea = int32_t(int16_t(opcode));
if ((reg_a != reg_d) && reg_a != 0) {
ea += ppc_result_a;
uint32_t ppc_result_d = mmu_read_vmem<T>(opcode, ea);
ppc_store_iresult_reg(reg_d, ppc_result_d);
ppc_result_a = ea;
uint32_t ppc_result_a = ea;
ppc_store_iresult_reg(reg_a, ppc_result_a);
} else {
ppc_illegalop(opcode);
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
}
@@ -1861,7 +1810,7 @@ void dppc_interpreter::ppc_lzux(uint32_t opcode) {
ppc_result_a = ea;
ppc_store_iresult_reg(reg_a, ppc_result_a);
} else {
ppc_illegalop(opcode);
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
}
@@ -1873,8 +1822,8 @@ void dppc_interpreter::ppc_lha(uint32_t opcode) {
#ifdef CPU_PROFILING
num_int_loads++;
#endif
ppc_grab_regsdasimm(opcode);
uint32_t ea = simm;
ppc_grab_regsda(opcode);
uint32_t ea = int32_t(int16_t(opcode));
ea += (reg_a ? ppc_result_a : 0);
int16_t val = mmu_read_vmem<uint16_t>(opcode, ea);
ppc_store_iresult_reg(reg_d, int32_t(val));
@@ -1884,16 +1833,16 @@ void dppc_interpreter::ppc_lhau(uint32_t opcode) {
#ifdef CPU_PROFILING
num_int_loads++;
#endif
ppc_grab_regsdasimm(opcode);
ppc_grab_regsda(opcode);
if ((reg_a != reg_d) && reg_a != 0) {
uint32_t ea = simm;
uint32_t ea = int32_t(int16_t(opcode));
ea += ppc_result_a;
int16_t val = mmu_read_vmem<uint16_t>(opcode, ea);
ppc_store_iresult_reg(reg_d, int32_t(val));
ppc_result_a = ea;
uint32_t ppc_result_a = ea;
ppc_store_iresult_reg(reg_a, ppc_result_a);
} else {
ppc_illegalop(opcode);
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
}
@@ -1906,11 +1855,11 @@ void dppc_interpreter::ppc_lhaux(uint32_t opcode) {
uint32_t ea = ppc_result_a + ppc_result_b;
int16_t val = mmu_read_vmem<uint16_t>(opcode, ea);
ppc_store_iresult_reg(reg_d, int32_t(val));
ppc_result_a = ea;
uint32_t ppc_result_a = ea;
ppc_store_iresult_reg(reg_a, ppc_result_a);
}
else {
ppc_illegalop(opcode);
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
}
@@ -1960,8 +1909,8 @@ void dppc_interpreter::ppc_lmw(uint32_t opcode) {
#ifdef CPU_PROFILING
num_int_loads++;
#endif
ppc_grab_regsdasimm(opcode);
uint32_t ea = simm;
ppc_grab_regsda(opcode);
uint32_t ea = int32_t(int16_t(opcode));
ea += (reg_a ? ppc_result_a : 0);
// How many words to load in memory - using a do-while for this
do {
@@ -2018,7 +1967,7 @@ void dppc_interpreter::ppc_lswx(uint32_t opcode) {
if ((reg_d == 0 && reg_a == 0) || (reg_d == reg_a) || (reg_d == reg_b)) {
// UNTESTED! Does invalid form really cause exception?
// G4 doesn't do exception
ppc_illegalop(opcode);
ppc_exception_handler(Except_Type::EXC_PROGRAM, Exc_Cause::ILLEGAL_OP);
}
*/
@@ -2125,7 +2074,6 @@ void dppc_interpreter::ppc_eciwx(uint32_t opcode) {
// error if EAR[E] != 1
if (!(ppc_state.spr[SPR::EAR] & ear_enable)) {
ppc_exception_handler(Except_Type::EXC_DSI, 0x0);
return;
}
ppc_grab_regsdab(opcode);
@@ -2147,7 +2095,6 @@ void dppc_interpreter::ppc_ecowx(uint32_t opcode) {
if (!(ppc_state.spr[SPR::EAR] & ear_enable)) {
ppc_state.spr[SPR::DSISR] = 0x00100000;
ppc_exception_handler(Except_Type::EXC_DSI, 0x0);
return;
}
ppc_grab_regssab(opcode);
@@ -2171,13 +2118,7 @@ void dppc_interpreter::ppc_tlbie(uint32_t opcode) {
return;
}
// Ideally we would get the effective address via ppc_state.gpr[(opcode >> 11) & 0x1F]
// and use that to identify entries to flush. But that is CPU-dependent (e.g.
// on the 750 only bits 14-19 are used to find matching entries) and does not
// map cleanly to the layout of our virtual TLB. The PowerPC specification
// allows an implementation to be more lax and flush the entire TLB, so we
// do that instead.
tlb_flush_all_pat();
tlb_flush_entry(ppc_state.gpr[(opcode >> 11) & 0x1F]);
}
void dppc_interpreter::ppc_tlbia(uint32_t opcode) {
+10 -26
View File
@@ -58,8 +58,6 @@ using namespace std;
#define COUT08X COUT0_X(8)
#define COUT04X COUT0_X(4)
extern bool g_auto_grab_mouse;
static uint32_t str2addr(string& addr_str) {
try {
return static_cast<uint32_t>(stoul(addr_str, NULL, 0));
@@ -118,8 +116,6 @@ static void show_help() {
cout << " printenv -- print current NVRAM settings." << endl;
cout << " setenv V N -- set NVRAM variable V to value N." << endl;
cout << endl;
cout << " autograbmouse H -- auto grab the mouse if H is not zero." << endl;
cout << endl;
cout << " restart -- restart the machine" << endl;
cout << " quit -- quit the debugger" << endl;
cout << endl;
@@ -730,21 +726,21 @@ void DppcDebugger::enter_debugger() {
while (1) {
if (power_off_reason == po_shut_down) {
set_power_off_reason(po_shutting_down);
power_off_reason = po_shutting_down;
break;
}
if (power_off_reason == po_restart) {
set_power_off_reason(po_restarting);
power_off_reason = po_restarting;
break;
}
if (power_off_reason == po_quit) {
set_power_off_reason(po_quitting);
power_off_reason = po_quitting;
break;
}
power_on = true;
if (power_off_reason == po_starting_up) {
set_power_off_reason(po_none);
power_off_reason = po_none;
cmd = "go";
}
else if (power_off_reason == po_disassemble_on) {
@@ -755,13 +751,13 @@ void DppcDebugger::enter_debugger() {
ss >> cmd;
}
else if (power_off_reason == po_disassemble_off) {
set_power_off_reason(po_none);
power_off_reason = po_none;
cmd = "go";
}
else
{
if (power_off_reason == po_enter_debugger) {
set_power_off_reason(po_entered_debugger);
power_off_reason = po_entered_debugger;
}
if (!did_message) {
cout << endl;
@@ -798,7 +794,7 @@ void DppcDebugger::enter_debugger() {
}
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.
last_cmd = "";
continue;
@@ -825,7 +821,8 @@ void DppcDebugger::enter_debugger() {
break;
} else if (cmd == "restart") {
cmd = "";
power_off(po_restart);
power_on = false;
power_off_reason = po_restart;
} else if (cmd == "profile") {
cmd = "";
ss >> sub_cmd;
@@ -1167,24 +1164,11 @@ void DppcDebugger::enter_debugger() {
cout << exc.what() << endl;
continue;
}
static TimerInfo viaint_timer;
TimerManager::get_instance()->add_oneshot_timer(viaint_timer, 0, [irq_bit](uint64_t, uint64_t){
TimerManager::get_instance()->add_oneshot_timer(0, [irq_bit](){
ViaCuda* via_obj = dynamic_cast<ViaCuda*>(gMachineObj->get_comp_by_name("ViaCuda"));
via_obj->assert_int(irq_bit);
});
#endif
} else if (cmd == "autograbmouse") {
cmd = "";
string value;
int num;
ss >> value;
try {
num = str2num(value);
} catch (invalid_argument& exc) {
cout << exc.what() << endl;
continue;
}
g_auto_grab_mouse = num;
} else {
if (!cmd.empty()) {
cout << "Unknown command: " << cmd << endl;
+3
View File
@@ -77,6 +77,9 @@ bool AdbAppleJack::get_register_0() {
}
void AdbAppleJack::set_register_3() {
if (this->host_obj->get_input_count() < 2) // ensure we got enough data
return;
const uint8_t* in_data = this->host_obj->get_input_buf();
switch (in_data[1]) {
+1 -22
View File
@@ -21,7 +21,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file Base class for Apple Desktop Bus devices. */
#include <loguru.hpp>
#include <core/timermanager.h>
#include <devices/common/adb/adbdevice.h>
#include <devices/common/adb/adbbus.h>
@@ -93,8 +92,7 @@ void AdbDevice::listen(const uint8_t dev_addr, const uint8_t reg_num) {
this->set_register_2();
break;
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 +107,6 @@ bool AdbDevice::get_register_3() {
return true;
}
void AdbDevice::set_register_3() {
const uint8_t* in_data = this->host_obj->get_input_buf();
uint8_t new_addr = in_data[0] & 0xF;
switch (in_data[1]) {
case 0:
this->my_addr = new_addr;
this->srq_flag = !!(in_data[0] & 0x20);
break;
case 0xFE: // move to a new address if there was no collision
if (!this->got_collision) {
this->my_addr = new_addr;
}
break;
default:
LOG_F(WARNING, "ADB Device: unknown handler ID = 0x%X", in_data[1]);
}
}
uint8_t AdbDevice::gen_random_address() {
return TimerManager::get_instance()->current_time_ns() & 0xF;
}
+1 -1
View File
@@ -64,7 +64,7 @@ protected:
virtual void set_register_0() {}
virtual void set_register_1() {}
virtual void set_register_2() {}
virtual void set_register_3();
virtual void set_register_3() {}
uint8_t exc_event_flag = 0;
uint8_t srq_flag = 0;
+26 -32
View File
@@ -34,7 +34,6 @@ AdbKeyboard::AdbKeyboard(std::string name) : AdbDevice(name) {
}
void AdbKeyboard::event_handler(const KeyboardEvent& event) {
this->keys_down.set(event.key, !(event.flags & KEYBOARD_EVENT_UP));
this->pending_events.push_back(std::make_unique<KeyboardEvent>(event));
if (this->pending_events.size() == 1) {
@@ -47,9 +46,8 @@ void AdbKeyboard::reset() {
this->dev_handler_id = 2; // Extended ADB keyboard
this->exc_event_flag = 1;
this->srq_flag = 0; // don't process keyboard service requests yet
this->led_state = 7; // LEDs off (active low)
this->led_state = 0; // LEDs off
this->pending_events.clear();
this->keys_down.reset();
}
bool AdbKeyboard::get_register_0() {
@@ -94,35 +92,9 @@ uint8_t AdbKeyboard::consume_pending_event() {
}
bool AdbKeyboard::get_register_2() {
// Register 2 reflects the current modifier keys, and a zero value means
// that the key is held down.
static const struct {
uint8_t key;
uint8_t bit;
} reg2_keys[] = {
{ AdbKey_Delete, 14 },
{ AdbKey_CapsLock, 13 },
{ AdbKey_Power, 12 },
{ AdbKey_Control, 11 },
{ AdbKey_RightControl, 11 },
{ AdbKey_Shift, 10 },
{ AdbKey_RightShift, 10 },
{ AdbKey_Option, 9 },
{ AdbKey_RightOption, 9 },
{ AdbKey_Command, 8 },
{ AdbKey_KeypadClear, 7 },
{ AdbKey_F14, 6 }, // Scroll Lock
};
uint16_t reg2 = 0xFFF8 | this->led_state;
for (const auto& key : reg2_keys) {
if (this->keys_down[key.key])
reg2 &= ~(1 << key.bit);
}
uint8_t* out_buf = this->host_obj->get_output_buf();
out_buf[0] = reg2 >> 8;
out_buf[1] = reg2 & 0xFF;
out_buf[0] = 0;
out_buf[1] = this->led_state & 0x07;
this->host_obj->set_output_count(2);
return true;
}
@@ -136,18 +108,40 @@ void AdbKeyboard::set_register_2() {
this->led_state = in_data[1] & 0x07;
}
bool AdbKeyboard::get_register_3() {
uint8_t* out_buf = this->host_obj->get_output_buf();
out_buf[0] = (this->my_addr << 4) | (1 << 1) | 1; // Address + SRQ Enable + Exc Event
out_buf[1] = this->dev_handler_id;
this->host_obj->set_output_count(2);
return true;
}
void AdbKeyboard::set_register_3() {
if (this->host_obj->get_input_count() < 2) // ensure we got enough data
return;
const uint8_t* in_data = this->host_obj->get_input_buf();
switch (in_data[1]) {
case 0:
this->my_addr = in_data[0] & 0xF;
this->srq_flag = !!(in_data[0] & 0x20);
break;
case 1:
case 2:
this->dev_handler_id = in_data[1];
break;
case 3: // extended keyboard protocol isn't supported yet
break;
case 0xFE: // move to a new address if there was no collision
if (!this->got_collision) {
this->my_addr = in_data[0] & 0xF;
}
break;
default:
this->AdbDevice::set_register_3();
LOG_F(WARNING, "%s: unknown handler ID = 0x%X", this->name.c_str(), in_data[1]);
}
}
+1 -3
View File
@@ -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/hwcomponent.h>
#include <bitset>
#include <deque>
#include <memory>
#include <string>
@@ -48,13 +47,13 @@ public:
bool get_register_0() override;
bool get_register_2() override;
bool get_register_3() override;
void set_register_2() override;
void set_register_3() override;
private:
std::deque<std::unique_ptr<KeyboardEvent>> pending_events;
std::bitset<128> keys_down;
uint8_t consume_pending_event();
};
@@ -130,7 +129,6 @@ enum AdbKey {
AdbKey_Option = 0x3a,
AdbKey_Command = 0x37,
AdbKey_CapsLock = 0x39,
AdbKey_Power = 0x7f,
AdbKey_RightControl = 0x7d,
AdbKey_RightShift = 0x7b,
+13 -1
View File
@@ -142,16 +142,28 @@ bool AdbMouse::get_register_1() {
}
void AdbMouse::set_register_3() {
if (this->host_obj->get_input_count() < 2) // ensure we got enough data
return;
const uint8_t* in_data = this->host_obj->get_input_buf();
switch (in_data[1]) {
case 0:
this->my_addr = in_data[0] & 0xF;
this->srq_flag = !!(in_data[0] & 0x20);
break;
case 1:
case 2:
case 4: // switch over to extended mouse protocol
this->dev_handler_id = in_data[1];
break;
case 0xFE: // move to a new address if there was no collision
if (!this->got_collision) {
this->my_addr = in_data[0] & 0xF;
}
break;
default:
this->AdbDevice::set_register_3();
LOG_F(WARNING, "%s: unknown handler ID = 0x%X", this->name.c_str(), in_data[1]);
}
}
+11 -28
View File
@@ -77,13 +77,8 @@ uint16_t AtaBaseDevice::read(const uint8_t reg_addr) {
this->r_status &= ~DRQ;
} else {
this->chunk_cnt = std::min(this->xfer_cnt, this->chunk_size);
if (!this->read_data_timer.active) {
TimerManager::get_instance()->add_oneshot_timer(this->read_data_timer,
USECS_TO_NSECS(100), [this](uint64_t, uint64_t) {
this->update_intrq(1);
}
);
}
TimerManager::get_instance()->add_oneshot_timer(
USECS_TO_NSECS(100), [this]() { this->update_intrq(1); });
}
}
return ret_data;
@@ -126,25 +121,17 @@ void AtaBaseDevice::write(const uint8_t reg_addr, const uint16_t value) {
this->xfer_cnt = 0;
this->r_status &= ~DRQ;
//LOG_F(INFO, "%s: write complete", name.c_str());
if (this->write_done_timer.active)
LOG_F(ERROR, "%s: write_done_timer is already active", this->get_name().c_str());
TimerManager::get_instance()->add_oneshot_timer(write_done_timer,
USECS_TO_NSECS(100), [this](uint64_t, uint64_t) {
this->r_status &= ~BSY;
this->update_intrq(1);
}
);
TimerManager::get_instance()->add_oneshot_timer(USECS_TO_NSECS(100), [this]() {
this->r_status &= ~BSY;
this->update_intrq(1);
});
} else {
this->cur_data_ptr = this->data_ptr;
this->chunk_cnt = std::min(this->xfer_cnt, this->chunk_size);
//LOG_F(INFO, "%s: write needs more data (left: 0x%x)", name.c_str(), xfer_cnt);
if (this->write_more_timer.active)
LOG_F(ERROR, "%s: write_more_timer is already active", this->get_name().c_str());
TimerManager::get_instance()->add_oneshot_timer(this->write_more_timer,
USECS_TO_NSECS(100), [this](uint64_t, uint64_t) {
this->signal_data_ready();
}
);
TimerManager::get_instance()->add_oneshot_timer(USECS_TO_NSECS(100), [this]() {
this->signal_data_ready();
});
}
}
}
@@ -226,9 +213,7 @@ int AtaBaseDevice::pull_data(uint8_t *buf, int len) {
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) {
TimerManager::get_instance()->add_oneshot_timer(500, [this]() {
this->r_status &= ~(BSY | DRQ);
this->update_intrq(1);
});
@@ -255,9 +240,7 @@ int AtaBaseDevice::push_data(uint8_t *buf, int len) {
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) {
TimerManager::get_instance()->add_oneshot_timer(500, [this]() {
this->r_status &= ~(BSY | DRQ);
this->update_intrq(1);
});
-7
View File
@@ -25,7 +25,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#define ATA_BASE_DEVICE_H
#include <core/endianswap.h>
#include <core/timermanager.h>
#include <devices/common/ata/atadefs.h>
#include <devices/common/hwcomponent.h>
@@ -109,12 +108,6 @@ protected:
bool is_dma_xfer = false;
std::function<void()> post_xfer_action = nullptr;
TimerInfo read_data_timer;
TimerInfo write_done_timer;
TimerInfo write_more_timer;
TimerInfo dma_pull_timer;
TimerInfo dma_push_timer;
};
#endif // ATA_BASE_DEVICE_H
+3 -5
View File
@@ -289,7 +289,7 @@ void AtaHardDisk::prepare_identify_info() {
std::memset(this->data_buf, 0, sizeof(this->data_buf));
WRITE_WORD_LE_A(&buf_ptr[ 0], 0x0040); // ATA device, non-removable media, non-removable drive
WRITE_WORD_LE_A(&buf_ptr[49], 0x0300); // report DMA and LBA support
WRITE_WORD_LE_A(&buf_ptr[49], 0x0200); // report LBA support
// Maximum number of logical sectors per data block that the device supports
// for READ_MULTIPLE/WRITE_MULTIPLE commands.
@@ -307,8 +307,8 @@ void AtaHardDisk::prepare_identify_info() {
WRITE_WORD_LE_A(&buf_ptr[51], 0x0200); // max. PIO mode for a basic device
// report validity for the MWDMA fields
WRITE_WORD_LE_A(&buf_ptr[53], 0x0002);
// report validity for the advanced PIO and MWDMA fields
//WRITE_WORD_LE_A(&buf_ptr[53], 0x0003);
WRITE_DWORD_LE_A(&buf_ptr[57], this->total_sectors);
@@ -316,8 +316,6 @@ void AtaHardDisk::prepare_identify_info() {
WRITE_DWORD_LE_A(&buf_ptr[60], this->total_sectors);
WRITE_WORD_LE_A(&buf_ptr[63], ((1 << this->cur_dma_mode) << 8) | 7);
WRITE_WORD_LE_A(&buf_ptr[65], 120); // minimum MWDMA cycle time (ns)
WRITE_WORD_LE_A(&buf_ptr[66], 120); // recommended MWDMA cycle time (ns)
}
uint64_t AtaHardDisk::get_lba() {
-3
View File
@@ -24,7 +24,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef ATA_HARD_DISK_H
#define ATA_HARD_DISK_H
#include <core/timermanager.h>
#include <devices/common/ata/atabasedevice.h>
#include <utils/imgfile.h>
@@ -75,8 +74,6 @@ private:
uint8_t cur_dma_mode = 2; // current multi-word DMA mode
char * buffer = new char[1 <<17];
TimerInfo signal_ready_timer;
};
#endif // ATA_HARD_DISK_H
+3 -40
View File
@@ -33,7 +33,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
using namespace ata_interface;
AtapiBaseDevice::AtapiBaseDevice(const std::string name)
: AtaBaseDevice(name, DEVICE_TYPE_ATAPI), ScsiPhysInterface(PHY_ID_ATAPI) {
: AtaBaseDevice(name, DEVICE_TYPE_ATAPI) {
}
void AtapiBaseDevice::device_set_signature() {
@@ -90,7 +90,7 @@ uint16_t AtapiBaseDevice::read(const uint8_t reg_addr) {
case ATA_Reg::STATUS:
this->update_intrq(0);
case ATA_Reg::ALT_STATUS:
if ((this->r_status & BSY) && this->data_available()) {
if (this->r_status & BSY && this->data_available()) {
this->r_byte_count = this->request_data();
this->data_in_phase();
}
@@ -201,14 +201,12 @@ int AtapiBaseDevice::perform_command() {
LOG_F(ERROR, "%s: unsupported command 0x%X", this->name.c_str(), this->r_command);
this->r_error |= ATA_Error::ABRT;
this->r_status |= ATA_Status::ERR;
this->r_status &= ~BSY;
this->update_intrq(1);
}
return 0;
}
void AtapiBaseDevice::data_in_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->signal_data_ready();
}
@@ -220,38 +218,3 @@ void AtapiBaseDevice::present_status() {
this->r_status &= ~BSY;
this->update_intrq(1);
}
void AtapiBaseDevice::switch_phase(const int new_phase) {
switch(new_phase) {
case ScsiPhase::DATA_IN:
this->data_in_phase();
break;
case ScsiPhase::DATA_OUT:
this->r_int_reason &= ATAPI_Int_Reason::IO; // host->device
this->r_int_reason &= ~ATAPI_Int_Reason::CoD; // data
this->signal_data_ready();
break;
case ScsiPhase::STATUS:
this->present_status();
break;
default:
LOG_F(WARNING, "ATAPI PHY: unsupported phase %d switch_phase", new_phase);
}
}
void AtapiBaseDevice::set_status(uint8_t status_code, uint8_t sense_key) {
switch(status_code) {
case ScsiStatus::GOOD:
this->status_expected = true;
this->r_error = 0;
this->r_status &= ~ATA_Status::ERR;
break;
case ScsiStatus::CHECK_CONDITION:
this->status_expected = true;
this->r_error = (sense_key << 4) | ATA_Error::ABRT;
this->r_status |= ATA_Status::ERR;
break;
default:
LOG_F(WARNING, "ATAPI PHY: unsupported status %d set_status", status_code);
}
}
+1 -21
View File
@@ -25,13 +25,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#define ATAPI_BASE_DEVICE_H
#include <devices/common/ata/atabasedevice.h>
#include <devices/common/scsi/scsi.h>
#include <devices/common/scsi/scsiphysinterface.h>
#include <cinttypes>
#include <string>
class AtapiBaseDevice : public AtaBaseDevice, public ScsiPhysInterface
class AtapiBaseDevice : public AtaBaseDevice
{
public:
AtapiBaseDevice(const std::string name);
@@ -42,24 +40,6 @@ public:
uint16_t read(const uint8_t reg_addr) override;
void write(const uint8_t reg_addr, const uint16_t value) override;
// ScsiPhysInterface methods
void set_lock_state(bool is_locked) override {};
void set_xfer_len(uint64_t len) override {
this->xfer_cnt = len;
this->r_byte_count = len;
}
void set_buffer(uint8_t *buf_ptr) override {
this->data_ptr = (uint16_t*)buf_ptr;
}
void set_status(uint8_t status_code, uint8_t sense_key) override;
void switch_phase(const int new_phase) override;
void set_read_more_data_cb(more_data_cb_t cb) override {};
void set_write_more_data_cb(more_data_cb_t cb) override {};
void set_post_xfer_action(action_callback cb) override {};
// methods to be implemented in the particular device
int perform_command() override;
virtual void perform_packet_command() = 0;
+175 -40
View File
@@ -25,6 +25,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <devices/common/ata/atadefs.h>
#include <devices/common/ata/atapicdrom.h>
#include <devices/common/ata/idechannel.h>
#include <devices/common/scsi/scsi.h> // ATAPI CDROM reuses SCSI commands (sic!)
#include <devices/deviceregistry.h>
#include <machines/machinebase.h>
#include <machines/machineproperties.h>
@@ -35,23 +36,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
using namespace ata_interface;
static char cdrom_vendor_id[] = "DINGUS ";
static char cdrom_product_id[] = "DINGUS CD-ROM ";
static char cdrom_revision_id[] = "1.0 ";
AtapiCdrom::AtapiCdrom(std::string name) : AtapiBaseDevice(name) {
this->set_phys_dev(this);
this->set_cdb_ptr(this->cmd_pkt);
this->set_buf_ptr(this->data_buf);
// populate device info for INQUIRY
this->dev_type = ScsiDevType::CD_ROM;
this->is_removable = true; // removable medium
this->std_versions = 2; // ANSI version: SCSI-2
this->resp_fmt = 0x21; // ATAPI Version + response data format
this->set_vendor_id(cdrom_vendor_id);
this->set_product_id(cdrom_product_id);
this->set_revision_id(cdrom_revision_id);
AtapiCdrom::AtapiCdrom(std::string name) : CdromDrive(), AtapiBaseDevice(name) {
this->set_error_callback(
[this](uint8_t sense_key, uint8_t asc) {
this->status_error(sense_key, asc);
}
);
}
int AtapiCdrom::device_postinit() {
@@ -67,17 +57,11 @@ int AtapiCdrom::device_postinit() {
parse_device_path(cdr_config, bus_id, dev_num);
auto bus_obj = dynamic_cast<IdeChannel*>(gMachineObj->get_comp_by_name(bus_id));
if (!bus_obj) {
LOG_F(ERROR, "%s: cdr_config device path %s does not specify a known IDE bus",
this->name.c_str(), cdr_config.c_str());
return -1;
}
bus_obj->register_device(dev_num, this);
std::string cdr_image_path = GET_STR_PROP("cdr_img");
if (!cdr_image_path.empty()) {
if (!this->insert_image(cdr_image_path))
return -1;
this->insert_image(cdr_image_path);
}
return 0;
@@ -93,24 +77,168 @@ void AtapiCdrom::perform_packet_command() {
LOG_F(WARNING, "%s: doing_sector_areas reset", this->name.c_str());
}
// Assume successful command execution
if (this->cmd_pkt[0] == ScsiCommand::REQ_SENSE) {
// For REQ_SENSE we only set the status, status_good() also resets
// sense_key, which we'll need to return.
this->set_status(ScsiStatus::GOOD, 0);
} else {
this->status_good();
}
switch (this->cmd_pkt[0]) {
case ScsiCommand::READ_CD:
{
// READ_CD currently bypasses the shared CD-ROM command dispatcher.
if (!this->ready_for_command()) {
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_in_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_in_phase();
break;
case ScsiCommand::START_STOP_UNIT:
if ((this->cmd_pkt[4] & 3) == 2) {
LOG_F(WARNING, "CD-ROM eject requested");
}
this->status_good();
this->present_status();
break;
case ScsiCommand::PREVENT_ALLOW_MEDIUM_REMOVAL:
LOG_F(INFO, "%s: medium removal %s", this->name.c_str(),
this->cmd_pkt[4] & 1 ? "prevented" : "allowed");
this->status_good();
this->present_status();
break;
case ScsiCommand::READ_CAPACITY:
this->xfer_cnt = this->report_capacity(this->data_buf);
this->r_byte_count = this->xfer_cnt;
this->data_ptr = (uint16_t*)this->data_buf;
this->status_good();
this->data_in_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_in_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_in_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_in_phase();
}
break;
case ScsiCommand::READ_6:
lba = this->cmd_pkt[1] << 16 | READ_WORD_BE_U(&this->cmd_pkt[2]);
xfer_len = this->cmd_pkt[4];
// if transfer length is zero then just complete command
if (xfer_len == 0) {
this->status_good();
this->present_status();
break;
}
if (this->r_features & ATAPI_Features::DMA) {
LOG_F(WARNING, "ATAPI DMA transfer requsted");
}
this->set_fpos(lba);
this->xfer_cnt = this->read_begin(xfer_len, this->r_byte_count);
this->r_byte_count = this->xfer_cnt;
this->data_ptr = (uint16_t*)this->data_cache.get();
this->status_good();
this->data_in_phase();
break;
case ScsiCommand::READ_10:
if (this->xfer_cnt > 0) {
LOG_F(ERROR, "%s: READ(10) when transfer already in progress", name.c_str());
this->status_error(ScsiSense::NOT_READY, ScsiError::DEV_NOT_READY);
this->present_status();
break;
}
lba = READ_DWORD_BE_U(&this->cmd_pkt[2]);
xfer_len = READ_WORD_BE_U(&this->cmd_pkt[7]);
// if transfer length is zero then just complete command
if (xfer_len == 0) {
this->status_good();
this->present_status();
break;
}
if (this->r_features & ATAPI_Features::DMA) {
LOG_F(WARNING, "ATAPI DMA transfer requsted");
}
this->set_fpos(lba);
this->xfer_cnt = this->read_begin(xfer_len, this->r_byte_count);
this->r_byte_count = this->xfer_cnt;
this->data_ptr = (uint16_t*)this->data_cache.get();
this->status_good();
#if 0
TimerManager::get_instance()->add_oneshot_timer(
USECS_TO_NSECS(100), [this]() { this->data_in_phase(); });
#else
this->data_in_phase();
#endif
break;
case ScsiCommand::READ_12:
lba = READ_DWORD_BE_U(&this->cmd_pkt[2]);
xfer_len = READ_DWORD_BE_U(&this->cmd_pkt[6]);
// if transfer length is zero then just complete command
if (xfer_len == 0) {
this->status_good();
this->present_status();
break;
}
if (this->r_features & ATAPI_Features::DMA) {
LOG_F(WARNING, "ATAPI DMA transfer requsted");
}
this->set_fpos(lba);
this->xfer_cnt = this->read_begin(xfer_len, this->r_byte_count);
this->r_byte_count = this->xfer_cnt;
this->data_ptr = (uint16_t*)this->data_cache.get();
this->status_good();
this->data_in_phase();
break;
case ScsiCommand::SET_CD_SPEED:
LOG_F(INFO, "%s: speed set to %d kBps", this->name.c_str(),
READ_WORD_BE_U(&this->cmd_pkt[2]));
this->status_good();
this->present_status();
break;
case ScsiCommand::READ_CD:
{
lba = READ_DWORD_BE_U(&this->cmd_pkt[2]);
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) {
@@ -201,7 +329,10 @@ void AtapiCdrom::perform_packet_command() {
break;
}
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();
}
}
@@ -325,14 +456,18 @@ uint16_t AtapiCdrom::get_data() {
}
void AtapiCdrom::status_good() {
this->status_expected = true;
this->r_error = 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) {
this->status_expected = true;
this->sense_key = sense_key;
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 = {
+6 -10
View File
@@ -25,11 +25,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#define ATAPI_CDROM_H
#include <devices/common/ata/atapibasedevice.h>
#include <devices/common/scsi/scsicdromcmds.h>
#include <devices/storage/cdromdrive.h>
#include <string>
class AtapiCdrom : public AtapiBaseDevice, public ScsiCdromCmds {
class AtapiCdrom : public CdromDrive, public AtapiBaseDevice {
public:
AtapiCdrom(std::string name);
~AtapiCdrom() = default;
@@ -38,17 +38,10 @@ public:
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;
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;
@@ -61,8 +54,11 @@ public:
void status_error(uint8_t sense_key, uint8_t asc);
uint16_t get_data();
private:
uint8_t sense_key = 0;
uint8_t asc = 0;
uint8_t ascq = 0;
bool doing_sector_areas = false;
uint8_t sector_areas;
uint32_t current_block;
+1 -3
View File
@@ -91,9 +91,7 @@ int IdeChannel::xfer_to(DmaChannel *ch_obj, uint8_t *buf, int 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) {
TimerManager::get_instance()->add_oneshot_timer(delay, [this]() {
//LOG_F(INFO, "%s: DMAREQ asserted", this->name.c_str());
this->channel_obj->xfer_retry();
});
-3
View File
@@ -24,7 +24,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef IDE_CHANNEL_H
#define IDE_CHANNEL_H
#include <core/timermanager.h>
#include <devices/common/ata/atadefs.h>
#include <devices/common/dmacore.h>
#include <devices/common/hwcomponent.h>
@@ -75,8 +74,6 @@ private:
AtaInterface* devices[2];
std::unique_ptr<AtaInterface> device_stub;
TimerInfo dmareq_timer;
};
/** This class models an IDE channel specific to MacIO ASICs. */
+89 -43
View File
@@ -29,7 +29,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <devices/common/dmacore.h>
#include <devices/common/hwinterrupt.h>
#include <devices/common/mmiodevice.h>
#include <devices/memctrl/memctrlbase.h>
#include <cinttypes>
#include <cstring>
@@ -40,6 +39,12 @@ void DMAChannel::set_callbacks(DbdmaCallback start_cb, DbdmaCallback stop_cb) {
this->stop_cb = stop_cb;
}
void DMAChannel::set_data_callbacks(DbdmaCallback in_cb, DbdmaCallback out_cb, DbdmaCallback flush_cb) {
this->in_cb = in_cb;
this->out_cb = out_cb;
this->flush_cb = flush_cb;
}
/* Load DMACmd from physical memory. */
DMACmd* DMAChannel::fetch_cmd(uint32_t cmd_addr, DMACmd* p_cmd, bool *is_writable) {
MapDmaResult res = mmu_map_dma_mem(cmd_addr, 16, false);
@@ -94,10 +99,14 @@ void DMAChannel::interpret_cmd() {
case DBDMA_Cmd::OUTPUT_MORE:
case DBDMA_Cmd::OUTPUT_LAST:
this->xfer_to_device();
if (this->out_cb)
this->out_cb();
break;
case DBDMA_Cmd::INPUT_MORE:
case DBDMA_Cmd::INPUT_LAST:
this->xfer_from_device();
if (this->in_cb)
this->in_cb();
break;
}
} else {
@@ -110,14 +119,14 @@ void DMAChannel::interpret_cmd() {
if ((cmd_struct.cmd_key & 7) != 6)
LOG_F(ERROR, "%s: Invalid key %d in STORE_QUAD", this->get_name().c_str(),
cmd_struct.cmd_key & 7);
this->xfer_quad(true);
this->xfer_quad(false);
break;
case DBDMA_Cmd::LOAD_QUAD:
if ((cmd_struct.cmd_key & 7) != 6) {
LOG_F(ERROR, "%s: Invalid key %d in LOAD_QUAD", this->get_name().c_str(),
cmd_struct.cmd_key & 7);
}
this->xfer_quad(false);
this->xfer_quad(true);
break;
case DBDMA_Cmd::NOP:
this->finish_cmd();
@@ -135,27 +144,6 @@ void DMAChannel::interpret_cmd() {
}
}
void DMAChannel::interpret_until_blocked() {
// Execute ready commands until a transfer is queued or the channel becomes idle/dead.
while (this->is_active()) {
this->interpret_cmd();
if (this->cmd_in_progress)
break;
}
}
void DMAChannel::update_cmd() {
if (this->cur_is_writable) {
if (this->cur_cmd < DBDMA_Cmd::STOP)
WRITE_WORD_LE_A(&this->cur_host->xfer_stat, this->ch_stat | CH_STAT_ACTIVE);
// all INPUT and OUTPUT commands including LOAD_QUAD and STORE_QUAD update cmd.resCount
if (this->cur_cmd < DBDMA_Cmd::NOP)
WRITE_WORD_LE_A(&this->cur_host->res_count, this->res_count);
}
this->ch_stat &= ~(CH_STAT_FLUSH | CH_STAT_BT);
}
void DMAChannel::finish_cmd() {
bool branch_taken = false;
@@ -198,9 +186,17 @@ void DMAChannel::finish_cmd() {
this->ch_stat |= CH_STAT_BT;
}
}
if (this->cur_is_writable)
WRITE_WORD_LE_A(&this->cur_host->xfer_stat, 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 && this->cur_is_writable) {
WRITE_WORD_LE_A(&this->cur_host->res_count, this->res_count);
}
if (this->cur_cmd < DBDMA_Cmd::STOP && !branch_taken)
this->cmd_ptr += 16;
@@ -290,12 +286,10 @@ void DMAChannel::update_irq(uint8_t cmd_bits) {
}
}
if (cond) {
if (this->int_ctrl) {
if (!this->interrupt_timer.active) {
TimerManager::get_instance()->add_immediate_timer(this->interrupt_timer, [this](uint64_t, uint64_t) {
this->int_ctrl->ack_dma_int(this->irq_id, 1);
});
}
if (int_ctrl) {
TimerManager::get_instance()->add_immediate_timer([this] {
this->int_ctrl->ack_dma_int(this->irq_id, 1);
});
} else
LOG_F(ERROR, "%s Interrupt ignored", this->get_name().c_str());
}
@@ -344,7 +338,7 @@ void DMAChannel::reg_write(uint32_t offset, uint32_t value, int size) {
this->get_name().c_str());
}
value = BYTESWAP_32(value);
value = BYTESWAP_32(value);
switch (offset) {
case DMAReg::CH_CTRL:
@@ -371,7 +365,8 @@ void DMAChannel::reg_write(uint32_t offset, uint32_t value, int size) {
this->ch_stat |= CH_STAT_FLUSH;
if (this->dev_obj != nullptr)
this->dev_obj->notify(this, DMA_MSG_FLUSH);
this->update_cmd();
if (this->flush_cb)
this->flush_cb();
}
}
this->ch_stat &= ~CH_STAT_FLUSH;
@@ -431,10 +426,10 @@ void DMAChannel::reg_write(uint32_t offset, uint32_t value, int size) {
}
break;
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_ACTIVE)) {
this->cmd_ptr = value;
LOG_F(9, "%s: CommandPtrLo set to 0x%X%s", this->get_name().c_str(),
this->cmd_ptr, (this->ch_stat & CH_STAT_RUN) ? " while running!" : "");
LOG_F(9, "%s: CommandPtrLo set to 0x%X", this->get_name().c_str(),
this->cmd_ptr);
} else
LOG_F(WARNING, "%s: CommandPtrLo update skipped", this->get_name().c_str());
break;
@@ -470,7 +465,7 @@ void DMAChannel::xfer_from_device() {
this->get_name().c_str());
}
this->interpret_until_blocked();
this->interpret_cmd();
}
void DMAChannel::xfer_to_device() {
@@ -487,7 +482,7 @@ void DMAChannel::xfer_to_device() {
this->finish_cmd();
}
this->interpret_until_blocked();
this->interpret_cmd();
}
void DMAChannel::xfer_retry() {
@@ -520,7 +515,9 @@ DmaPullResult DMAChannel::pull_data(uint32_t req_len, uint32_t *avail_len, uint8
}
// 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
if (this->queue_len) {
@@ -553,7 +550,9 @@ DmaPushResult DMAChannel::push_data(const char* src_ptr, int len) {
}
// 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) {
len = std::min((int)this->queue_len, len);
@@ -565,12 +564,47 @@ DmaPushResult DMAChannel::push_data(const char* src_ptr, int len) {
// proceed with the DBDMA program if the buffer became exhausted
if (!this->queue_len) {
this->interpret_until_blocked();
this->interpret_cmd();
}
return DmaPushResult::PushedData;
}
void DMAChannel::end_pull_data() {
if (!this->is_active()) {
// dead or idle channel? -> no more data
LOG_F(WARNING, "%s: Ending Dead/idle channel -> no more data",
this->get_name().c_str());
return;
}
if (this->queue_len) {
this->queue_len = 0;
} else {
this->ch_stat &= ~CH_STAT_FLUSH;
}
// proceed with the DBDMA program
this->interpret_cmd();
}
void DMAChannel::end_push_data() {
if (!this->is_active()) {
LOG_F(WARNING, "%s: Attempt to end push data to dead/idle channel",
this->get_name().c_str());
return;
}
if (this->queue_len) {
this->queue_len = 0;
} else {
this->ch_stat &= ~CH_STAT_FLUSH;
}
// proceed with the DBDMA program
this->interpret_cmd();
}
bool DMAChannel::is_out_active() {
return this->is_active();
}
@@ -606,7 +640,13 @@ void DMAChannel::start() {
if (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->is_active()) {
this->interpret_cmd();
}
}
void DMAChannel::resume() {
@@ -618,7 +658,13 @@ void DMAChannel::resume() {
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->is_active()) {
this->interpret_cmd();
}
}
void DMAChannel::abort() {
+8 -4
View File
@@ -29,7 +29,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef DB_DMA_H
#define DB_DMA_H
#include <core/timermanager.h>
#include <devices/common/dmacore.h>
#include <cinttypes>
@@ -110,6 +109,7 @@ public:
~DMAChannel() = default;
void set_callbacks(DbdmaCallback start_cb, DbdmaCallback stop_cb);
void set_data_callbacks(DbdmaCallback in_cb, DbdmaCallback out_cb, DbdmaCallback flush_cb);
uint32_t reg_read(uint32_t offset, int size);
void reg_write(uint32_t offset, uint32_t value, int size);
@@ -125,6 +125,10 @@ public:
bool is_in_active() override;
DmaPullResult pull_data(uint32_t req_len, uint32_t *avail_len, uint8_t **p_data) override;
DmaPushResult push_data(const char* src_ptr, int len) override;
int get_pull_data_remaining() override { return this->queue_len; }
int get_push_data_remaining() override { return this->queue_len; }
void end_pull_data() override;
void end_push_data() override;
bool dma_is_ready() override;
void xfer_retry() override;
@@ -137,8 +141,6 @@ public:
protected:
DMACmd* fetch_cmd(uint32_t cmd_addr, DMACmd* p_cmd, bool *is_writable);
void interpret_cmd(void);
void interpret_until_blocked();
void update_cmd();
void finish_cmd();
void xfer_quad(bool is_store);
void update_irq(uint8_t cmd_bits);
@@ -155,6 +157,9 @@ protected:
private:
std::function<void(void)> start_cb = nullptr; // DMA channel start callback
std::function<void(void)> stop_cb = nullptr; // DMA channel stop callback
std::function<void(void)> in_cb = nullptr; // DMA channel in callback
std::function<void(void)> out_cb = nullptr; // DMA channel out callback
std::function<void(void)> flush_cb = nullptr; // DMA channel flush callback
uint16_t ch_stat = 0;
uint32_t cmd_ptr = 0;
@@ -174,7 +179,6 @@ private:
// Interrupt related stuff
InterruptCtrl* int_ctrl = nullptr;
uint64_t irq_id = 0;
TimerInfo interrupt_timer;
};
#endif // DB_DMA_H
+4
View File
@@ -45,6 +45,8 @@ public:
virtual bool is_out_active() { return true; }
virtual DmaPullResult pull_data(uint32_t req_len, uint32_t *avail_len,
uint8_t **p_data) = 0;
virtual int get_pull_data_remaining() { return 1; }
virtual void end_pull_data() {}
std::string get_name(void) { return this->name; }
@@ -58,6 +60,8 @@ public:
virtual bool is_in_active() { return true; }
virtual DmaPushResult push_data(const char* src_ptr, int len) = 0;
virtual int get_push_data_remaining() { return 1; }
virtual void end_push_data() {}
std::string get_name(void) { return this->name; }
+1 -3
View File
@@ -32,8 +32,6 @@ enum YosemiteGpioMask: uint8_t {
GPIO_FWDET = 2, // FireWire detect
};
constexpr uint32_t my_rev_id = 2;
DecPciBridge::DecPciBridge(std::string name) : PCIBridge(name)
{
supports_types(HWCompType::PCI_HOST | HWCompType::PCI_DEV);
@@ -41,7 +39,7 @@ DecPciBridge::DecPciBridge(std::string name) : PCIBridge(name)
// initialize PCI config header
this->vendor_id = PCI_VENDOR_DEC;
this->device_id = 0x0026;
this->class_rev = DEVTYPE_PCI2PCI_BRIDGE | my_rev_id;
this->class_rev = 0x06040002;
this->cache_ln_sz = 0;
this->command = 0;
this->status = 0x2B0;
+10 -1
View File
@@ -23,7 +23,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#define PCI_BASE_H
#include <devices/common/mmiodevice.h>
#include <devices/common/pci/pcidefs.h>
#include <devices/common/pci/pcihost.h>
#include <cinttypes>
@@ -53,6 +52,16 @@ enum {
// Int_Pin and Int_Line registers (type 0, 1, and 2)
};
/** PCI Vendor IDs for devices used in Power Macintosh computers. */
enum {
PCI_VENDOR_ATI = 0x1002,
PCI_VENDOR_DEC = 0x1011,
PCI_VENDOR_MOTOROLA = 0x1057,
PCI_VENDOR_APPLE = 0x106B,
PCI_VENDOR_SILICON_IMAGE = 0x1095,
PCI_VENDOR_NVIDIA = 0x10DE,
};
/** PCI BAR types */
enum PCIBarType : uint32_t {
Unused = 0,
-72
View File
@@ -1,72 +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 PCI_DEFS_H
#define PCI_DEFS_H
#include <cinttypes>
/** PCI device class/subclass/programming interface definitions. */
enum : uint8_t {
DEVCLASS_UNCLASSIFIED = 0x00, // unclassified/legacy devices
DEVCLASS_MASS_STORAGE_CTRL = 0x01, // mass storage controllers
SUBCLASS_IDE_CTRL = 0x01, // IDE controller
PROGIF_BUS_MASTER = 0x80, // bus master (DMA) capable
DEVCLASS_DISPLAY_CTRL = 0x03, // display controllers
SUBCLASS_VGA_COMPAT = 0x00, // VGA-compatible display controller
SUBCLASS_NON_VGA = 0x80, // non-VGA display controller
DEVCLASS_BRIDGE_DEVICE = 0x06, // various bridge devices
SUBCLASS_HOST_BRIDGE = 0x00, // host-to-PCI bridge
SUBCLASS_PCI2PCI_BRIDGE = 0x04, // PCI-to-PCI bridge
DEVCLASS_SERIAL_BUS_CTRL = 0x0C, // serial bus controllers
SUBCLASS_USB_CTRL = 0x03, // Universal serial bus (USB) controller
PROGIF_OHCI = 0x10, // conforms to the OpenHCI specification
DEVCLASS_UNASSIGNED = 0xFF
};
/** Some common PCI device type definitions. */
enum : uint32_t {
DEVTYPE_HOST2PCI_BRIDGE = (DEVCLASS_BRIDGE_DEVICE << 24) |
(SUBCLASS_HOST_BRIDGE << 16),
DEVTYPE_PCI2PCI_BRIDGE = (DEVCLASS_BRIDGE_DEVICE << 24) |
(SUBCLASS_PCI2PCI_BRIDGE << 16),
DEVTYPE_VGA_COMPAT_VIDCTRL = (DEVCLASS_DISPLAY_CTRL << 24) |
(SUBCLASS_VGA_COMPAT << 16),
DEVTYPE_IDE_CTRL_BUS_MASTER = (DEVCLASS_MASS_STORAGE_CTRL << 24) |
(SUBCLASS_IDE_CTRL << 16) | (PROGIF_BUS_MASTER << 8),
DEVTYPE_USB_OHCI_CTRL = (DEVCLASS_SERIAL_BUS_CTRL << 24) |
(SUBCLASS_USB_CTRL << 16) | (PROGIF_OHCI << 8),
};
/** PCI Vendor IDs for devices used in Power Macintosh computers. */
enum : uint16_t {
PCI_VENDOR_ATI = 0x1002,
PCI_VENDOR_DEC = 0x1011,
PCI_VENDOR_OPTi = 0x1045,
PCI_VENDOR_TI = 0x104C, // common abbreviation for Texas Instruments
PCI_VENDOR_MOTOROLA = 0x1057,
PCI_VENDOR_APPLE = 0x106B,
PCI_VENDOR_SILICON_IMAGE = 0x1095,
PCI_VENDOR_NVIDIA = 0x10DE,
PCI_VENDOR_IXMICRO = 0x10E0, // also known as Integrated Micro Solutions
};
#endif // PCI_DEFS_H
-7
View File
@@ -51,16 +51,10 @@ int MeshController::device_postinit() {
void MeshController::reset(bool is_hard_reset) {
this->cur_cmd = SeqCmd::NoOperation;
this->fifo_pos = 0;
this->to_xfer = 0;
this->int_stat = 0;
this->int_mask = 0;
this->exception = 0;
this->xfer_count = 0;
this->src_id = 7;
this->check_parity = true;
this->cur_state = Scsi_Bus_Controller::SeqState::BUS_FREE;
update_irq();
if (is_hard_reset) {
this->bus_stat = 0;
@@ -129,7 +123,6 @@ void MeshController::write(uint8_t reg_offset, uint8_t value) {
break;
case MeshReg::IntMask:
this->int_mask = value;
update_irq();
break;
case MeshReg::Interrupt:
this->int_stat &= ~(value & INT_MASK); // clear requested interrupt bits
+19 -15
View File
@@ -78,7 +78,7 @@ void Sc53C94::reset_device()
this->cur_step = 0;
this->seq_step = 0;
this->status &= STAT_PHASE_MASK; // reset doesn't affect bus phase bits
this->status &= STAT_PHASE_MASK; // reset doesn't affect bus phase bits
this->int_status = 0;
}
@@ -252,7 +252,7 @@ void Sc53C94::pseudo_dma_write(uint16_t data) {
void Sc53C94::update_command_reg(uint8_t cmd)
{
if (this->on_reset && (cmd & CMD_OPCODE) != CMD_NOP && (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());
return;
}
@@ -306,7 +306,6 @@ void Sc53C94::exec_command()
exec_next_command();
break;
case CMD_CLEAR_FIFO:
this->on_reset = false; // unblock the command register
this->data_fifo_pos = 0; // set the bottom of the data FIFO to zero
this->data_fifo[0] = 0;
exec_next_command();
@@ -314,19 +313,20 @@ void Sc53C94::exec_command()
case CMD_RESET_DEVICE:
reset_device();
this->on_reset = true; // block the command register
this->update_irq();
return;
case CMD_RESET_BUS:
LOG_F(INFO, "%s: resetting SCSI bus...", this->name.c_str());
// assert RST line
this->bus_obj->assert_ctrl_line(this->my_bus_id, SCSI_CTRL_RST);
// release RST line after 25 us
if (my_timer.active) {
TimerManager::get_instance()->cancel_timer(this->my_timer);
if (my_timer_id) {
TimerManager::get_instance()->cancel_timer(this->my_timer_id);
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),
[this](uint64_t, uint64_t) {
[this]() {
my_timer_id = 0;
this->bus_obj->release_ctrl_line(this->my_bus_id, SCSI_CTRL_RST);
});
if (!(config1 & CFG1_DISR)) {
@@ -475,22 +475,25 @@ uint8_t Sc53C94::fifo_pop()
void Sc53C94::seq_defer_state(uint64_t delay_ns)
{
if (this->seq_timer.active) {
TimerManager::get_instance()->cancel_timer(this->seq_timer);
if (this->seq_timer_id) {
TimerManager::get_instance()->cancel_timer(this->seq_timer_id);
this->seq_timer_id = 0;
}
if (delay_ns) {
TimerManager::get_instance()->add_oneshot_timer(this->seq_timer,
this->seq_timer_id = TimerManager::get_instance()->add_oneshot_timer(
delay_ns,
[this](uint64_t, uint64_t) {
[this]() {
// re-enter the sequencer with the state specified in next_state
this->seq_timer_id = 0;
this->cur_state = this->next_state;
this->sequencer();
});
} else {
TimerManager::get_instance()->add_immediate_timer(this->seq_timer,
[this](uint64_t, uint64_t) {
this->seq_timer_id = TimerManager::get_instance()->add_immediate_timer(
[this]() {
// re-enter the sequencer with the state specified in next_state
this->seq_timer_id = 0;
this->cur_state = this->next_state;
this->sequencer();
});
@@ -705,7 +708,8 @@ void Sc53C94::notify(ScsiNotification notif_type, int param)
case ScsiNotification::CONFIRM_SEL:
if (this->target_id == param) {
// cancel selection timeout timer
TimerManager::get_instance()->cancel_timer(this->seq_timer);
TimerManager::get_instance()->cancel_timer(this->seq_timer_id);
this->seq_timer_id = 0;
this->cur_state = SeqState::SEL_END;
this->sequencer();
} else {
+2 -3
View File
@@ -29,7 +29,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef SC_53C94_H
#define SC_53C94_H
#include <core/timermanager.h>
#include <devices/common/scsi/scsi.h>
#include <devices/common/dbdma.h>
@@ -251,7 +250,7 @@ protected:
private:
uint8_t chip_id = 0;
uint8_t my_bus_id = 0;
TimerInfo my_timer;
uint32_t my_timer_id = 0;
uint8_t cmd_fifo[2];
uint8_t data_fifo[DATA_FIFO_MAX];
@@ -279,7 +278,7 @@ private:
uint8_t phase_latch = 0;
// sequencer state
TimerInfo seq_timer;
uint32_t seq_timer_id = 0;
uint32_t cur_state = 0;
uint32_t next_state = 0;
SeqDesc* cmd_steps = nullptr;
+4 -17
View File
@@ -24,7 +24,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef SCSI_H
#define SCSI_H
#include <core/timermanager.h>
#include <devices/common/hwcomponent.h>
#include <devices/common/scsi/scsiphysinterface.h>
@@ -176,14 +175,6 @@ enum ScsiCommand : uint8_t {
READ_CD = 0xBE,
};
/** START STOP UNIT command flags in CDB byte 4. */
namespace ScsiStartStopUnit {
enum : uint8_t {
START = 1 << 0,
LOAD_EJECT = 1 << 1,
};
}
enum ScsiSense : uint8_t {
NO_SENSE = 0x0,
RECOVERED = 0x1,
@@ -209,10 +200,8 @@ enum ScsiError : uint8_t {
INVALID_CDB = 0x24,
INVALID_LUN = 0x25,
WRITE_PROTECT = 0x27,
MEDIUM_CHANGED = 0x28,
SAVING_NOT_SUPPORTED = 0x39,
MEDIUM_NOT_PRESENT = 0x3A,
REMOVAL_PREVENTED = 0x53,
};
/** SCSI device types used in INQUIRY. */
@@ -259,7 +248,7 @@ enum ModePage : uint8_t {
DEV_FORMAT_PARAMS = 0x3,
RIGID_DISK_GEOMETRY = 0x4,
CDROM_PARAMS = 0xD,
CDROM_AUDIO_CONTROL = 0xE,
CDROM_AUDIO = 0xE,
POWER_CONDITION = 0x1A,
CDROM_CAPABILITIES = 0x2A,
VENDOR_PAGE_31 = 0x31,
@@ -318,12 +307,12 @@ public:
this->post_xfer_action = cb;
}
void set_status(uint8_t status_code, uint8_t sense_key) override {
void set_status(uint8_t status_code) override {
this->status = status_code;
}
void set_lock_state(bool is_locked) override {
this->eject_allowed = !is_locked;
void set_eject_state(bool eject_allowed) override {
this->eject_allowed = eject_allowed;
}
virtual void notify(ScsiNotification notif_type, int param);
@@ -370,8 +359,6 @@ protected:
more_data_cb_t read_more_data = {};
more_data_cb_t write_more_data = {};
TimerInfo bus_settle_timer;
};
/** This class provides a higher level abstraction for the SCSI bus. */
+56 -21
View File
@@ -30,6 +30,8 @@ ScsiBlockCmds::ScsiBlockCmds() {
this->enable_cmd(ScsiCommand::WRITE_6);
this->enable_cmd(ScsiCommand::WRITE_10);
this->enable_cmd(ScsiCommand::WRITE_12);
this->enable_cmd(ScsiCommand::VERIFY_6);
this->enable_cmd(ScsiCommand::VERIFY_10);
this->enable_cmd(ScsiCommand::START_STOP_UNIT);
this->enable_cmd(ScsiCommand::PREVENT_ALLOW_MEDIUM_REMOVAL);
this->enable_cmd(ScsiCommand::READ_CAPACITY);
@@ -79,11 +81,6 @@ void ScsiBlockCmds::init_block_device(uint8_t medium_type, uint8_t dev_flags,
}
void ScsiBlockCmds::process_command() {
if (!this->ready_for_command()) {
phy_impl->switch_phase(ScsiPhase::STATUS);
return;
}
int next_phase;
// use non-disk buffer by default
@@ -93,18 +90,22 @@ void ScsiBlockCmds::process_command() {
case ScsiCommand::READ_6:
case ScsiCommand::READ_10:
case ScsiCommand::READ_12:
next_phase = this->read();
next_phase = this->read_new();
break;
case ScsiCommand::WRITE_6:
case ScsiCommand::WRITE_10:
case ScsiCommand::WRITE_12:
next_phase = this->write();
next_phase = this->write_new();
break;
case ScsiCommand::VERIFY_6:
case ScsiCommand::VERIFY_10:
next_phase = this->verify_sector();
break;
case ScsiCommand::START_STOP_UNIT:
next_phase = this->start_stop_unit();
break;
case ScsiCommand::PREVENT_ALLOW_MEDIUM_REMOVAL:
phy_impl->set_lock_state((this->cdb_ptr[4] & 1) != 0);
phy_impl->set_eject_state((this->cdb_ptr[4] & 1) == 0);
next_phase = ScsiPhase::STATUS;
break;
case ScsiCommand::READ_CAPACITY:
@@ -118,7 +119,7 @@ void ScsiBlockCmds::process_command() {
phy_impl->switch_phase(next_phase);
}
int ScsiBlockCmds::read() {
int ScsiBlockCmds::read_new() {
int nblocks = this->get_xfer_len();
// special case: zero transfer length means 256 blocks for READ_6
@@ -127,7 +128,7 @@ int ScsiBlockCmds::read() {
nblocks = 256;
} else {
if ((this->cdb_ptr[1] & 1) && !this->linked_cmds_supported()) {
LOG_F(WARNING, "READ: RelAdr bit set but it should not be");
LOG_F(WARNING, "READ: RelAdr bit set");
this->set_field_pointer(1);
this->set_bit_pointer(0);
this->invalid_cdb();
@@ -148,7 +149,7 @@ int ScsiBlockCmds::read() {
return ScsiPhase::DATA_IN;
}
int ScsiBlockCmds::write() {
int ScsiBlockCmds::write_new() {
int nblocks = this->get_xfer_len();
// special case: zero transfer length means 256 blocks for WRITE_6
@@ -157,7 +158,7 @@ int ScsiBlockCmds::write() {
nblocks = 256;
} else {
if ((this->cdb_ptr[1] & 1) && !this->linked_cmds_supported()) {
LOG_F(WARNING, "WRITE: RelAdr bit set but it should not be");
LOG_F(WARNING, "WRITE: RelAdr bit set");
this->set_field_pointer(1);
this->set_bit_pointer(0);
this->invalid_cdb();
@@ -183,26 +184,60 @@ int ScsiBlockCmds::write() {
return ScsiPhase::DATA_OUT;
}
int ScsiBlockCmds::start_stop_unit() {
if (this->cdb_ptr[4] & ScsiStartStopUnit::START) {
if (this->cdb_ptr[4] & ScsiStartStopUnit::LOAD_EJECT)
LOG_F(INFO, "START_STOP_UNIT: medium load requested");
int ScsiBlockCmds::verify_sector() {
//TODO: implement the IMMED, BYTCMP, or FIXED bits
int nblocks = this->get_xfer_len();
// special case: zero transfer length means 256 blocks for VERIFY_6
if (this->cdb_ptr[0] == ScsiCommand::VERIFY_6) {
if (!nblocks)
nblocks = 256;
} else {
if (this->cdb_ptr[4] & ScsiStartStopUnit::LOAD_EJECT)
this->eject_medium();
if ((this->cdb_ptr[1] & 1) && !this->linked_cmds_supported()) {
LOG_F(WARNING, "VERIFY: RelAdr bit set");
this->set_field_pointer(1);
this->set_bit_pointer(0);
this->invalid_cdb();
return ScsiPhase::STATUS;
}
}
// go directly to the STATUS phase if nblocks = 0
if (!nblocks) {
LOG_F(WARNING, "VERIFY: skip because nblocks = 0");
return ScsiPhase::STATUS;
}
auto lba = this->get_lba();
auto size = this->blk_dev->get_size_in_blocks();
if (lba >= size || (uint64_t)lba + (uint64_t)nblocks > size) {
LOG_F(WARNING, "VERIFY: out of range");
this->invalid_cdb();
return ScsiPhase::STATUS;
}
return ScsiPhase::STATUS;
}
void ScsiBlockCmds::eject_medium() {
LOG_F(INFO, "START_STOP_UNIT: medium eject requested");
int ScsiBlockCmds::start_stop_unit() {
if (this->cdb_ptr[4] & 1) {
if (this->cdb_ptr[4] & 2)
LOG_F(INFO, "START_STOP_UNIT: medium load requested");
} else {
if (this->cdb_ptr[4] & 2) {
LOG_F(INFO, "START_STOP_UNIT: medium eject requested");
}
}
return ScsiPhase::STATUS;
}
int ScsiBlockCmds::read_capacity() {
uint32_t lba = this->get_lba();
if ((this->cdb_ptr[1] & 1) && !this->linked_cmds_supported()) {
LOG_F(WARNING, "READ_CAPACITY: RelAdr bit set but it should not be");
LOG_F(WARNING, "READ_CAPACITY: RelAdr bit set");
this->set_field_pointer(1);
this->set_bit_pointer(0);
this->invalid_cdb();
+3 -3
View File
@@ -41,8 +41,9 @@ public:
void init_block_device(uint8_t medium_type, uint8_t dev_flags,
uint8_t density_code, bool is_apple_compliant);
virtual int read();
virtual int write();
virtual int read_new();
virtual int write_new();
virtual int verify_sector();
virtual int start_stop_unit();
virtual int read_capacity();
@@ -63,7 +64,6 @@ public:
protected:
virtual void process_command() override;
virtual void eject_medium();
uint32_t get_lba();
+17 -55
View File
@@ -31,7 +31,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cinttypes>
#include <sstream>
#include <vector>
ScsiBus::ScsiBus(const std::string name)
{
@@ -339,65 +338,28 @@ void ScsiBus::attach_scsi_devices(const std::string bus_suffix)
}
}
int default_cdrom_id = -1;
std::string cdr_config = GET_STR_PROP("cdr_config");
if (!cdr_config.empty()) {
std::string bus_id;
uint32_t dev_num;
parse_device_path(cdr_config, bus_id, dev_num);
// Only consume SCSI paths; other buses handle their own CD-ROM configuration.
if (bus_id.starts_with("Scsi")) {
auto bus_obj = dynamic_cast<ScsiBus*>(gMachineObj->get_comp_by_name_optional(bus_id));
if (!bus_obj)
ABORT_F("cdr_config device path %s does not specify a known SCSI bus", cdr_config.c_str());
if (dev_num >= SCSI_MAX_DEVS)
ABORT_F("Invalid SCSI ID in cdr_config device path %s", cdr_config.c_str());
if (bus_obj == this) {
if (this->devices[dev_num])
ABORT_F("%s: cdr_config SCSI ID %u is already occupied", bus_id.c_str(), dev_num);
default_cdrom_id = dev_num;
}
}
}
image_path = GET_STR_PROP("cdr_img" + bus_suffix);
std::vector<std::string> cdrom_paths;
if (!image_path.empty()) {
// Keep empty entries, including the last one, as empty CD-ROM drives.
size_t start = 0;
size_t end;
do {
end = image_path.find(':', start);
cdrom_paths.push_back(image_path.substr(start, end - start));
start = end + 1;
} while (end != std::string::npos);
} else if (default_cdrom_id >= 0) {
cdrom_paths.push_back("");
}
for (const auto& path : cdrom_paths) {
if (default_cdrom_id >= 0) {
scsi_id = default_cdrom_id;
default_cdrom_id = -1;
} else {
// do two passes because we start at ID 3.
std::istringstream image_stream(image_path);
while (std::getline(image_stream, path, ':')) {
// do two passes because we start at ID 3.
for (scsi_id = 3; scsi_id < SCSI_MAX_DEVS * 2 &&
this->devices[scsi_id % SCSI_MAX_DEVS]; scsi_id++) {}
}
if (scsi_id < SCSI_MAX_DEVS * 2) {
scsi_id = scsi_id % SCSI_MAX_DEVS;
std::string scsi_device_name = "ScsiCdrom" + bus_suffix + "," +
std::to_string(scsi_id);
ScsiCdrom *scsi_device = new ScsiCdrom(scsi_device_name, scsi_id);
gMachineObj->add_device(scsi_device_name,
std::unique_ptr<ScsiCdrom>(scsi_device));
this->register_device(scsi_id, scsi_device);
if (!path.empty() && !scsi_device->insert_image(path))
ABORT_F("Could not insert CD-ROM image, %s", path.c_str());
}
else {
LOG_F(ERROR, "%s: Too many devices. CD-ROM \"%s\" was not added.",
this->get_name().c_str(), path.c_str());
if (scsi_id < SCSI_MAX_DEVS * 2) {
scsi_id = scsi_id % SCSI_MAX_DEVS;
std::string scsi_device_name = "ScsiCdrom" + bus_suffix + "," +
std::to_string(scsi_id);
ScsiCdrom *scsi_device = new ScsiCdrom(scsi_device_name, scsi_id);
gMachineObj->add_device(scsi_device_name,
std::unique_ptr<ScsiCdrom>(scsi_device));
this->register_device(scsi_id, scsi_device);
scsi_device->insert_image(path);
}
else {
LOG_F(ERROR, "%s: Too many devices. CD-ROM \"%s\" was not added.",
this->get_name().c_str(), path.c_str());
}
}
}
}
+4 -6
View File
@@ -31,12 +31,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
using namespace Scsi_Bus_Controller;
void ScsiBusController::seq_defer_state(uint64_t delay_ns) {
if (this->seq_timer.active) {
TimerManager::get_instance()->cancel_timer(this->seq_timer);
}
TimerManager::get_instance()->add_oneshot_timer(this->seq_timer,
seq_timer_id = TimerManager::get_instance()->add_oneshot_timer(
delay_ns,
[this](uint64_t, uint64_t) {
[this]() {
// re-enter the sequencer with the state specified in next_state
this->cur_state = this->next_state;
this->sequencer();
@@ -173,7 +170,8 @@ void ScsiBusController::notify(ScsiNotification notif_type, int param) {
case ScsiNotification::CONFIRM_SEL:
if (this->dst_id == param) {
// cancel selection timeout timer
TimerManager::get_instance()->cancel_timer(this->seq_timer);
TimerManager::get_instance()->cancel_timer(this->seq_timer_id);
seq_timer_id = 0;
this->cur_state = SeqState::SEL_END;
this->sequencer();
} else {
+1 -2
View File
@@ -24,7 +24,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef SCSI_BUS_CTRL_H
#define SCSI_BUS_CTRL_H
#include <core/timermanager.h>
#include <devices/common/dmacore.h>
#include <devices/common/hwinterrupt.h>
#include <devices/common/scsi/scsi.h>
@@ -105,7 +104,7 @@ protected:
uint8_t data_fifo[DATA_FIFO_DEPTH] = {};
// Sequencer state
TimerInfo seq_timer;
uint32_t seq_timer_id = 0;
uint32_t cur_state = Scsi_Bus_Controller::SeqState::IDLE;
uint32_t next_state = Scsi_Bus_Controller::SeqState::IDLE;
int cur_bus_phase = 0;
+28
View File
@@ -47,6 +47,8 @@ ScsiCdrom::ScsiCdrom(std::string name, int my_id) : ScsiPhysDevice(name, my_id)
this->set_vendor_id(my_vendor_id);
this->set_product_id(my_product_id);
this->set_revision_id(my_revision_id);
this->add_page_getter(this, 49, &ScsiCdrom::get_apple_page_49);
}
void ScsiCdrom::process_command() {
@@ -78,6 +80,32 @@ void ScsiCdrom::process_command() {
// Apple SCSI/ATAPI driver requests this page in the case of a device error.
// PearPC implements it under the name "Apple Features".
// I couldn't find any drive whose firmware supports it.
int ScsiCdrom::get_apple_page_49(uint8_t subpage, uint8_t ctrl, uint8_t *out_ptr,
int avail_len)
{
LOG_F(WARNING, "Page 0x31 requested");
if (subpage && subpage != 0xFFU)
return FORMAT_ERR_BAD_SUBPAGE;
if (ctrl == 3)
return FORMAT_ERR_BAD_CONTROL;
int page_size = 6;
if (page_size > avail_len)
return FORMAT_ERR_DATA_TOO_BIG;
std::memset(out_ptr, 0, page_size);
out_ptr[0] = '.';
out_ptr[1] = 'A';
out_ptr[2] = 'p';
out_ptr[3] = 'p';
return page_size;
}
void ScsiCdrom::mode_select_6(uint8_t param_len)
{
if (!param_len)
+4 -7
View File
@@ -37,14 +37,11 @@ public:
virtual void process_command() override;
void set_lock_state(bool is_locked) override {
this->drive_locked = is_locked ? 1 : 0;
ScsiPhysDevice::set_lock_state(is_locked);
}
protected:
bool is_device_ready() override { return this->medium_present(); }
uint8_t not_ready_reason() override { return ScsiError::MEDIUM_NOT_PRESENT; }
bool is_device_ready() override { return this->is_ready; }
int get_apple_page_49(uint8_t subpage, uint8_t ctrl, uint8_t *out_ptr,
int avail_len);
void mode_select_6(uint8_t param_len);
+2 -155
View File
@@ -29,24 +29,9 @@ ScsiCdromCmds::ScsiCdromCmds() {
this->set_phys_block_dev(this);
this->enable_cmd(ScsiCommand::READ_TOC);
this->enable_cmd(ScsiCommand::SET_CD_SPEED);
this->add_page_getter(this, ModePage::CDROM_AUDIO_CONTROL,
&ScsiCdromCmds::get_cdrom_audio_control_page);
this->add_page_getter(this, ModePage::CDROM_CAPABILITIES,
&ScsiCdromCmds::get_cd_capabilities_page);
this->add_page_getter(this, ModePage::VENDOR_PAGE_31,
&ScsiCdromCmds::get_apple_page_49);
}
void ScsiCdromCmds::process_command() {
if (!this->ready_for_command()) {
phy_impl->switch_phase(ScsiPhase::STATUS);
return;
}
int next_phase;
// use non-disk buffer by default
@@ -54,10 +39,7 @@ void ScsiCdromCmds::process_command() {
switch(this->cdb_ptr[0]) {
case ScsiCommand::READ_TOC:
next_phase = this->read_toc();
break;
case ScsiCommand::SET_CD_SPEED:
next_phase = this->set_cd_speed();
next_phase = this->read_toc_new();
break;
default:
ScsiBlockCmds::process_command();
@@ -67,31 +49,7 @@ void ScsiCdromCmds::process_command() {
phy_impl->switch_phase(next_phase);
}
int ScsiCdromCmds::test_unit_ready() {
if (this->consume_media_change()) {
this->sense_key = ScsiSense::UNIT_ATTENTION;
this->asc = ScsiError::MEDIUM_CHANGED;
this->ascq = 0;
phy_impl->set_status(ScsiStatus::CHECK_CONDITION, this->sense_key);
return ScsiPhase::STATUS;
}
return ScsiCommonCmds::test_unit_ready();
}
void ScsiCdromCmds::eject_medium() {
if (this->drive_locked) {
LOG_F(INFO, "START_STOP_UNIT: medium eject prevented");
this->field_ptr_valid = false;
this->bit_ptr_valid = false;
this->illegal_request(ScsiError::REMOVAL_PREVENTED, 2, false);
} else {
LOG_F(INFO, "START_STOP_UNIT: medium eject requested");
this->eject_image();
}
}
int ScsiCdromCmds:: read_toc() {
int ScsiCdromCmds:: read_toc_new() {
uint8_t start_track, session_num;
int tot_tracks, resp_len = 0;
@@ -254,114 +212,3 @@ int ScsiCdromCmds:: read_toc() {
return ScsiPhase::DATA_IN;
}
int ScsiCdromCmds::set_cd_speed() {
phy_impl->set_status(ScsiStatus::GOOD);
uint16_t new_rd_speed = READ_WORD_BE_U(&this->cdb_ptr[2]);
if (new_rd_speed == 0xFFFFU || new_rd_speed > this->max_rd_speed)
this->cur_rd_speed = this->max_rd_speed;
else
this->cur_rd_speed = new_rd_speed;
LOG_F(INFO, "SET_CD_SPEED: drive speed set to %d kBps", this->cur_rd_speed);
return ScsiPhase::STATUS;
}
int ScsiCdromCmds::get_cd_capabilities_page(uint8_t subpage, uint8_t ctrl,
uint8_t *out_ptr, int avail_len)
{
if (subpage && subpage != 0xFFU)
return FORMAT_ERR_BAD_SUBPAGE;
if (ctrl == 3)
return FORMAT_ERR_BAD_CONTROL;
int page_size = 28; // min length defined in MMC-3
if (page_size > avail_len)
return FORMAT_ERR_DATA_TOO_BIG;
std::memset(out_ptr, 0, page_size); // clear everything
out_ptr[ 0] = this->read_cap;
out_ptr[ 1] = this->write_cap;
out_ptr[ 2] = this->fmt_support;
out_ptr[ 3] = this->ext_support;
out_ptr[ 4] = (this->mech_type << 5) | this->sw_lock_sup |
(this->drive_locked << 1) | (this->prevent_jump << 2) |
(this->sw_eject_sup << 3);
out_ptr[ 5] = this->more_support;
out_ptr[15] = this->dgt_out_desc;
WRITE_WORD_BE_A(&out_ptr[ 6], this->max_rd_speed); // max read speed
WRITE_WORD_BE_A(&out_ptr[ 8], this->max_vol_levs); // max of volume levels
WRITE_WORD_BE_A(&out_ptr[10], (this->cache_size / 1024)); // buffer size kB
WRITE_WORD_BE_A(&out_ptr[12], this->cur_rd_speed); // current read speed
return page_size;
}
int ScsiCdromCmds::get_cdrom_audio_control_page(uint8_t subpage, uint8_t ctrl,
uint8_t *out_ptr, int avail_len)
{
if (subpage && subpage != 0xFFU)
return FORMAT_ERR_BAD_SUBPAGE;
if (ctrl == 3)
return FORMAT_ERR_BAD_CONTROL;
int page_size = 14;
if (page_size > avail_len)
return FORMAT_ERR_DATA_TOO_BIG;
std::memset(out_ptr, 0, page_size); // clear everything
out_ptr[ 0] = (1 << 2); // Immed defaults to 1, SOTC defaults to 0
// logical block per second of audio playback defaults to 75
WRITE_WORD_BE_A(&out_ptr[4], 75);
out_ptr[ 6] = 0x01; // Left Channel
out_ptr[ 7] = 0xFF; // Volume (0-255)
out_ptr[ 8] = 0x02; // Right Channel
out_ptr[ 9] = 0xFF; // Volume (0-255)
out_ptr[10] = 0x04; // Output Port 2
out_ptr[11] = 0x00; // Volume (0-255)
out_ptr[12] = 0x08; // Output Port 3
out_ptr[13] = 0x00; // Volume (0-255)
return page_size;
}
// Apple SCSI/ATAPI driver requests this page in the case of a device error.
// PearPC implements it under the name "Apple Features".
int ScsiCdromCmds::get_apple_page_49(uint8_t subpage, uint8_t ctrl,
uint8_t *out_ptr, int avail_len)
{
LOG_F(WARNING, "Page 0x31 requested");
if (subpage && subpage != 0xFFU)
return FORMAT_ERR_BAD_SUBPAGE;
if (ctrl == 3)
return FORMAT_ERR_BAD_CONTROL;
int page_size = 6;
if (page_size > avail_len)
return FORMAT_ERR_DATA_TOO_BIG;
std::memset(out_ptr, 0, page_size);
out_ptr[0] = '.';
out_ptr[1] = 'A';
out_ptr[2] = 'p';
out_ptr[3] = 'p';
return page_size;
}
+1 -13
View File
@@ -35,20 +35,8 @@ public:
protected:
virtual void process_command() override;
int test_unit_ready() override;
void eject_medium() override;
int get_apple_page_49(uint8_t subpage, uint8_t ctrl,
uint8_t *out_ptr, int avail_len);
int read_toc();
int set_cd_speed();
int get_cd_capabilities_page(uint8_t subpage, uint8_t ctrl,
uint8_t *out_ptr, int avail_len);
int get_cdrom_audio_control_page(uint8_t subpage, uint8_t ctrl,
uint8_t *out_ptr, int avail_len);
int read_toc_new();
};
#endif // SCSI_CDROM_COMMANDS_H
+11 -28
View File
@@ -39,10 +39,10 @@ void ScsiCommonCmds::process_command() {
next_phase = this->test_unit_ready();
break;
case ScsiCommand::REQ_SENSE:
next_phase = this->request_sense();
next_phase = this->request_sense_new();
break;
case ScsiCommand::INQUIRY:
next_phase = this->inquiry();
next_phase = this->inquiry_new();
break;
case ScsiCommand::MODE_SENSE_6:
case ScsiCommand::MODE_SENSE_10:
@@ -85,7 +85,7 @@ int ScsiCommonCmds::verify_cdb() {
if (!this->lun_supported(lun)) {
LOG_F(ERROR, "unsupported LUN 0x%X", lun);
this->invalid_lun();
phy_impl->set_status(ScsiStatus::CHECK_CONDITION, this->sense_key);
phy_impl->set_status(ScsiStatus::CHECK_CONDITION);
return -1;
}
} else if (this->cdb_ptr[1] >> 5)
@@ -109,36 +109,19 @@ int ScsiCommonCmds::verify_cdb() {
}
int ScsiCommonCmds::test_unit_ready() {
this->ready_for_command(true);
return ScsiPhase::STATUS;
}
bool ScsiCommonCmds::ready_for_command(bool force_check) {
// TUR forces a check from its handler; dispatch lets it and media-independent
// commands through to ScsiCommonCmds.
if (!force_check) {
switch (this->cdb_ptr[0]) {
case ScsiCommand::INQUIRY:
case ScsiCommand::REQ_SENSE:
case ScsiCommand::TEST_UNIT_READY:
case ScsiCommand::MODE_SENSE_6:
case ScsiCommand::MODE_SENSE_10:
return true;
}
}
// Assume that LUN is okay and the status has been set to GOOD
if (!phy_impl->is_device_ready()) {
this->sense_key = ScsiSense::NOT_READY;
this->asc = phy_impl->not_ready_reason();
this->ascq = 0;
phy_impl->set_status(ScsiStatus::CHECK_CONDITION, this->sense_key);
return false;
phy_impl->set_status(ScsiStatus::CHECK_CONDITION);
}
return true;
return ScsiPhase::STATUS;
}
int ScsiCommonCmds::inquiry() {
int ScsiCommonCmds::inquiry_new() {
int alloc_len = this->get_xfer_len();
int resp_len = 36; // standard response length
@@ -195,7 +178,7 @@ int ScsiCommonCmds::inquiry() {
return ScsiPhase::DATA_IN;
}
int ScsiCommonCmds::request_sense() {
int ScsiCommonCmds::request_sense_new() {
int alloc_len = this->get_xfer_len();
int resp_len = 18; // standard response length
@@ -437,7 +420,7 @@ void ScsiCommonCmds::invalid_cdb() {
this->ascq = 0;
this->is_cdb_err = true;
phy_impl->set_status(ScsiStatus::CHECK_CONDITION, this->sense_key);
phy_impl->set_status(ScsiStatus::CHECK_CONDITION);
}
void ScsiCommonCmds::invalid_command() {
@@ -450,7 +433,7 @@ void ScsiCommonCmds::invalid_command() {
this->field_ptr_valid = true;
this->field_ptr = 0; // error in the 1st byte
phy_impl->set_status(ScsiStatus::CHECK_CONDITION, this->sense_key);
phy_impl->set_status(ScsiStatus::CHECK_CONDITION);
}
void ScsiCommonCmds::illegal_request(uint8_t asc, uint8_t ascq, bool is_cdb) {
@@ -459,5 +442,5 @@ void ScsiCommonCmds::illegal_request(uint8_t asc, uint8_t ascq, bool is_cdb) {
this->ascq = ascq;
this->is_cdb_err = is_cdb;
phy_impl->set_status(ScsiStatus::CHECK_CONDITION, this->sense_key);
phy_impl->set_status(ScsiStatus::CHECK_CONDITION);
}
+2 -4
View File
@@ -87,8 +87,8 @@ public:
protected:
virtual void process_command();
virtual int test_unit_ready();
virtual int inquiry();
virtual int request_sense();
virtual int inquiry_new();
virtual int request_sense_new();
virtual int mode_sense();
virtual uint8_t get_lun();
virtual uint32_t get_xfer_len();
@@ -98,8 +98,6 @@ protected:
virtual void invalid_command();
virtual void illegal_request(uint8_t asc, uint8_t ascq, bool is_cdb = true);
bool ready_for_command(bool force_check = false);
int get_one_page(uint8_t ctrl, uint8_t page, uint8_t subpage, uint8_t* out_ptr,
int avail_len);
+2 -4
View File
@@ -56,7 +56,7 @@ ScsiHardDisk::ScsiHardDisk(std::string name, int my_id) : ScsiPhysDevice(name, m
}
void ScsiHardDisk::insert_image(std::string filename) {
if (!this->attach_image(filename))
if (this->set_host_file(filename) < 0)
ABORT_F("%s: could not open image file %s", this->name.c_str(), filename.c_str());
this->is_writeable = true;
@@ -177,9 +177,7 @@ void ScsiHardDisk::format() {
if (this->cmd_buf[1] & 0x10)
ABORT_F("%s: defect list isn't supported yet", this->name.c_str());
if (this->phase_switch_timer.active)
LOG_F(WARNING, "%s: phase_switch_timer is already active", this->get_name().c_str());
TimerManager::get_instance()->add_oneshot_timer(this->phase_switch_timer, NS_PER_SEC, [this](uint64_t, uint64_t) {
TimerManager::get_instance()->add_oneshot_timer(NS_PER_SEC, [this]() {
this->switch_phase(ScsiPhase::STATUS);
});
}
+1 -3
View File
@@ -24,7 +24,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef SCSI_HD_H
#define SCSI_HD_H
#include <core/timermanager.h>
#include <devices/common/scsi/scsi.h>
#include <devices/common/scsi/scsiblockcmds.h>
#include <devices/storage/blockstoragedevice.h>
@@ -41,7 +40,7 @@ public:
void process_command() override;
protected:
bool is_device_ready() override { return this->image_attached(); }
bool is_device_ready() override { return this->is_ready; }
void mode_select_6(uint8_t param_len);
@@ -56,7 +55,6 @@ protected:
private:
uint8_t data_buf[2048] = {};
TimerInfo phase_switch_timer;
};
#endif // SCSI_HD_H
+3 -5
View File
@@ -31,17 +31,15 @@ void ScsiPhysDevice::notify(ScsiNotification notif_type, int param)
if (notif_type == ScsiNotification::BUS_PHASE_CHANGE) {
switch (param) {
case ScsiPhase::RESET:
LOG_F(9, "device %d: bus reset acknowledged", this->scsi_id);
LOG_F(9, "device %d: bus reset aknowledged", this->scsi_id);
break;
case ScsiPhase::SELECTION:
// check if something tries to select us
if (this->bus_obj->get_data_lines() & (1 << scsi_id)) {
LOG_F(9, "device %d selected", this->scsi_id);
if (this->bus_settle_timer.active)
LOG_F(ERROR, "%s: bus_settle_timer already active", this->get_name().c_str());
TimerManager::get_instance()->add_oneshot_timer(bus_settle_timer,
TimerManager::get_instance()->add_oneshot_timer(
BUS_SETTLE_DELAY,
[this](uint64_t, uint64_t) {
[this]() {
// don't confirm selection if BSY or I/O are asserted
if (this->bus_obj->test_ctrl_lines(SCSI_CTRL_BSY | SCSI_CTRL_IO))
return;
+2 -2
View File
@@ -47,13 +47,13 @@ public:
virtual int get_phy_id() { return this->phy_id; };
virtual bool is_device_ready() { return true; }
virtual void set_lock_state(bool is_locked) = 0;
virtual void set_eject_state(bool eject_allowed) = 0;
virtual uint8_t not_ready_reason() { return 0; }
virtual bool last_sel_has_attention() { return false; }
virtual uint8_t last_sel_msg() { return 0; }
virtual void set_xfer_len(uint64_t len) = 0;
virtual void set_buffer(uint8_t *buf_ptr) = 0;
virtual void set_status(uint8_t status_code, uint8_t sense_key = 0) = 0;
virtual void set_status(uint8_t status_code) = 0;
virtual void switch_phase(const int new_phase) = 0;
virtual void set_read_more_data_cb(more_data_cb_t cb) = 0;
virtual void set_write_more_data_cb(more_data_cb_t cb) = 0;
+70 -98
View File
@@ -36,15 +36,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <machines/machinebase.h>
#include <cinttypes>
#include <optional>
#include <string>
#include <vector>
using namespace std;
static std::optional<uint32_t> rtc_start_time;
static std::chrono::steady_clock::time_point rtc_start_host_time;
ViaCuda::ViaCuda() : I2CBus() {
this->name = "ViaCuda";
@@ -103,17 +99,21 @@ ViaCuda::ViaCuda() : I2CBus() {
ViaCuda::~ViaCuda()
{
if (this->sr_timer.active) {
TimerManager::get_instance()->cancel_timer(this->sr_timer);
if (this->sr_timer_id) {
TimerManager::get_instance()->cancel_timer(this->sr_timer_id);
this->sr_timer_id = 0;
}
if (this->t1_timer.active) {
TimerManager::get_instance()->cancel_timer(this->t1_timer);
if (this->t1_timer_id) {
TimerManager::get_instance()->cancel_timer(this->t1_timer_id);
this->t1_timer_id = 0;
}
if (this->t2_timer.active) {
TimerManager::get_instance()->cancel_timer(this->t2_timer);
if (this->t2_timer_id) {
TimerManager::get_instance()->cancel_timer(this->t2_timer_id);
this->t2_timer_id = 0;
}
if (this->treq_timer.active) {
TimerManager::get_instance()->cancel_timer(this->treq_timer);
if (this->treq_timer_id) {
TimerManager::get_instance()->cancel_timer(this->treq_timer_id);
this->treq_timer_id = 0;
}
}
@@ -160,12 +160,10 @@ uint8_t ViaCuda::read(int reg) {
case VIA_T1LH:
return this->via_t1lh;
case VIA_T2CL:
this->check_t2();
this->_via_ifr &= ~VIA_IF_T2;
update_irq();
return this->calc_counter_val(this->t2_counter, this->t2_start_time) & 0xFFU;
case VIA_T2CH:
this->check_t2();
return this->calc_counter_val(this->t2_counter, this->t2_start_time) >> 8;
case VIA_SR:
value = this->via_sr;
@@ -177,7 +175,6 @@ uint8_t ViaCuda::read(int reg) {
case VIA_PCR:
return this->via_pcr;
case VIA_IFR:
this->check_t2();
return this->_via_ifr;
case VIA_IER:
return (this->_via_ier | 0x80); // bit 7 always reads as "1"
@@ -213,8 +210,9 @@ void ViaCuda::write(int reg, uint8_t value) {
break;
case VIA_T1CH:
// cancel active T1 timer task
if (this->t1_timer.active) {
TimerManager::get_instance()->cancel_timer(this->t1_timer);
if (this->t1_timer_id) {
TimerManager::get_instance()->cancel_timer(this->t1_timer_id);
this->t1_timer_id = 0;
}
// clear T1 flag in IFR
this->_via_ifr &= ~VIA_IF_T1;
@@ -223,7 +221,7 @@ void ViaCuda::write(int reg, uint8_t value) {
this->via_t1lh = value;
// load the T1 counter from the corresponding latches
this->t1_counter = (this->via_t1lh << 8) | this->via_t1ll;
this->activate_t1(TimerManager::get_instance()->current_time_ns());
this->activate_t1();
break;
case VIA_T1LL:
this->via_t1ll = value;
@@ -239,15 +237,26 @@ void ViaCuda::write(int reg, uint8_t value) {
break;
case VIA_T2CH:
// cancel active T2 timer task
if (this->t2_timer.active) {
TimerManager::get_instance()->cancel_timer(this->t2_timer);
if (this->t2_timer_id) {
TimerManager::get_instance()->cancel_timer(this->t2_timer_id);
this->t2_timer_id = 0;
}
// clear T2 flag in IFR
this->_via_ifr &= ~VIA_IF_T2;
update_irq();
// load initial value into counter 2
this->t2_counter = (value << 8) | this->via_t2ll;
this->activate_t2(TimerManager::get_instance()->current_time_ns());
// TODO: delay for one phase 2 clock
// sample current vCPU time and remember it
this->t2_start_time = TimerManager::get_instance()->current_time_ns();
// set up timeout timer for T2
this->t2_timer_id = TimerManager::get_instance()->add_oneshot_timer(
(this->via_clk_dur * (this->t2_counter + 3) + (uint64_t(1) << 36)) >> 37,
[this]() {
this->t2_timer_id = 0;
this->assert_t2_int();
}
);
break;
case VIA_SR:
this->via_sr = value;
@@ -284,58 +293,30 @@ uint16_t ViaCuda::calc_counter_val(const uint16_t last_val, const uint64_t &star
{
// calculate current counter value based on elapsed time and timer frequency
uint64_t cur_time = TimerManager::get_instance()->current_time_ns();
// The loaded value remains visible during the initial half-clock delay.
if (cur_time <= start_time)
return last_val;
uint64_t diff_hi;
uint32_t diff_lo;
_u32xu64(this->via_clk_freq, cur_time - start_time, diff_hi, diff_lo);
return last_val - (diff_hi >> 10);
}
void ViaCuda::activate_t1(uint64_t start_time) {
void ViaCuda::activate_t1() {
// TODO: delay for one phase 2 clock
this->t1_start_time = start_time;
uint64_t timeout = start_time +
((this->via_clk_dur * (this->t1_counter + 3) + (uint64_t(1) << 36)) >> 37);
// sample current vCPU time and remember it
this->t1_start_time = TimerManager::get_instance()->current_time_ns();
// set up timout timer for T1
TimerManager::get_instance()->add_absolute_timer(this->t1_timer,
timeout, 0,
[this](uint64_t timeout_ns, uint64_t /*time_now*/) {
this->t1_timer_id = TimerManager::get_instance()->add_oneshot_timer(
(this->via_clk_dur * (this->t1_counter + 3) + (uint64_t(1) << 36)) >> 37,
[this]() {
// reload the T1 counter from the corresponding latches
this->t1_counter = (this->via_t1lh << 8) | this->via_t1ll;
this->t1_timer_id = 0;
this->assert_t1_int();
if (this->via_acr & 0x40)
this->activate_t1(timeout_ns);
this->activate_t1();
}
);
}
void ViaCuda::activate_t2(uint64_t start_time) {
// T2's one-shot interrupt occurs N + 1.5 VIA clocks after loading N.
// Timer begins counting after 0.5 VIA clocks
start_time += (this->via_clk_dur + (uint64_t(1) << 37)) >> 38;
this->t2_start_time = start_time;
// Timer ends N + 1 VIA clocks after start time.
uint64_t timeout = start_time +
((this->via_clk_dur * (this->t2_counter + 1) + (uint64_t(1) << 36)) >> 37);
TimerManager::get_instance()->add_absolute_timer(
this->t2_timer, timeout, 0, [this](uint64_t, uint64_t) { this->assert_t2_int(); });
}
void ViaCuda::check_t2() {
// The process_events is where assert_t2_int is supposed to happen,
// but if a register read doesn't see that an interrupt happened
// when the counter wraps, then Microseconds in classic Mac OS will
// fail, so we call assert_t2_int here which sets the IFR register
// makes the interrupt happen as soon as possible.
auto tm = TimerManager::get_instance();
if (this->t2_timer.active && tm->current_time_ns() >= this->t2_timer.timeout_ns) {
tm->cancel_timer(this->t2_timer);
this->assert_t2_int();
}
}
void ViaCuda::print_enabled_ints() {
const char* via_int_src[] = {"CA2", "CA1", "SR", "CB2", "CB1", "T2", "T1"};
@@ -401,12 +382,14 @@ void ViaCuda::assert_ctrl_line(ViaLine line)
}
void ViaCuda::schedule_sr_int(uint64_t timeout_ns) {
if (this->sr_timer.active) {
TimerManager::get_instance()->cancel_timer(this->sr_timer);
if (this->sr_timer_id) {
TimerManager::get_instance()->cancel_timer(this->sr_timer_id);
this->sr_timer_id = 0;
}
TimerManager::get_instance()->add_oneshot_timer(this->sr_timer,
this->sr_timer_id = TimerManager::get_instance()->add_oneshot_timer(
timeout_ns,
[this](uint64_t, uint64_t) {
[this]() {
this->sr_timer_id = 0;
this->assert_sr_int();
}
);
@@ -437,13 +420,12 @@ void ViaCuda::write(uint8_t new_state) {
process_packet();
// start response transaction
if (this->treq_timer.active)
LOG_F(ERROR, "Cuda: treq_timer is already active");
TimerManager::get_instance()->add_oneshot_timer(this->treq_timer,
this->treq_timer_id = TimerManager::get_instance()->add_oneshot_timer(
USECS_TO_NSECS(13), // delay TREQ assertion for New World
[this](uint64_t, uint64_t) {
[this]() {
this->via_portb &= ~CUDA_TREQ; // assert TREQ
this->treq = 0;
this->treq_timer_id = 0;
});
}
@@ -636,7 +618,7 @@ void ViaCuda::autopoll_handler() {
// Don't send one-second packets if a command response is pending.
// Unlike autopoll, time packets are not urgent enough to preempt.
if (!this->treq || this->treq_timer.active || this->sr_timer.active) {
if (!this->treq || this->treq_timer_id || this->sr_timer_id) {
// ERS: track missed ticks for mode $02/$03 fallback
if (this_time != this->last_time)
this->one_sec_missed = true;
@@ -808,8 +790,7 @@ void ViaCuda::pseudo_command() {
response_header(CUDA_PKT_PSEUDO, 0);
break;
case CUDA_SET_POWER_MESSAGES:
this->power_messages_enabled = !!this->in_buf[2];
LOG_F(INFO, "Cuda: power messages %s", this->power_messages_enabled ? "enabled" : "disabled");
LOG_F(WARNING, "Cuda: unsupported pseudo command 0x%X SET_POWER_MESSAGES", cmd);
response_header(CUDA_PKT_PSEUDO, 0);
break;
case CUDA_READ_WRITE_I2C:
@@ -817,18 +798,7 @@ void ViaCuda::pseudo_command() {
i2c_simple_transaction(this->in_buf[2], &this->in_buf[3], this->in_count - 3);
break;
case CUDA_TIMER_TICKLE:
// The guest re-arms the Cuda shutdown watchdog on every tickle; the
// firmware counts it down at 16 counts/sec and powers the machine off
// when it reaches zero. We track the count so an arm value change is
// visible in the log, but never act on expiry to avoid spurious
// power-offs if the guest stops tickling.
if (this->tickle_value != this->in_buf[2]) {
this->tickle_value = this->in_buf[2];
LOG_F(INFO, "Cuda: timer tickle set to %d counts (%.1f s)", this->tickle_value,
(double)this->tickle_value / 16.0);
} else {
LOG_F(9, "Cuda: timer tickle");
}
LOG_F(WARNING, "Cuda: unsupported pseudo command 0x%X TIMER_TICKLE - Byte Sent: 0x%02x", cmd, this->in_buf[2]);
response_header(CUDA_PKT_PSEUDO, 0);
break;
case CUDA_COMB_FMT_I2C:
@@ -844,11 +814,13 @@ void ViaCuda::pseudo_command() {
break;
case CUDA_RESTART_SYSTEM:
LOG_F(INFO, "Cuda: system restart");
power_off(po_restart);
power_on = false;
power_off_reason = po_restart;
break;
case CUDA_POWER_DOWN:
LOG_F(INFO, "Cuda: system shutdown");
power_off(po_shut_down);
power_on = false;
power_off_reason = po_shut_down;
break;
case CUDA_SET_POWER_UPTIME: {
uint32_t alarm_time = READ_DWORD_BE_U(&this->in_buf[2]);
@@ -876,24 +848,24 @@ void ViaCuda::pseudo_command() {
}
}
void ViaCuda::set_start_time(std::chrono::local_seconds start_time)
{
// The Macintosh RTC counts local calendar seconds since January 1, 1904.
auto mac_epoch = std::chrono::local_days{std::chrono::year{1904}/1/1};
rtc_start_time = uint32_t((start_time - mac_epoch).count());
rtc_start_host_time = std::chrono::steady_clock::now();
}
uint32_t ViaCuda::calc_real_time() {
if (rtc_start_time) {
// We still want to advance time in deterministic mode, but tie it to
// virtual time so that it's reproducible.
uint64_t elapsed_seconds = is_deterministic ? get_virt_time_ns() / NS_PER_SEC :
std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::steady_clock::now() - rtc_start_host_time).count();
return uint32_t(*rtc_start_time + elapsed_seconds);
std::chrono::time_point<std::chrono::system_clock> end;
if (is_deterministic) {
// March 24, 2001 was the public release date of Mac OS X.
std::tm tm = {
.tm_sec = 0,
.tm_min = 0,
.tm_hour = 12,
.tm_mday = 24,
.tm_mon = 3 - 1,
.tm_year = 2001 - 1900,
.tm_isdst = 0
};
end = std::chrono::system_clock::from_time_t(std::mktime(&tm));
} else {
end = std::chrono::system_clock::now();
}
auto elapsed_systemclock = std::chrono::system_clock::now() - this->mac_epoch;
auto elapsed_systemclock = end - this->mac_epoch;
auto elapsed_seconds = std::chrono::duration_cast<std::chrono::seconds>(elapsed_systemclock);
return uint32_t(elapsed_seconds.count());
}
+7 -16
View File
@@ -42,7 +42,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef VIACUDA_H
#define VIACUDA_H
#include <core/timermanager.h>
#include <devices/common/i2c/i2c.h>
#include <devices/common/nvram.h>
@@ -173,10 +172,6 @@ public:
return std::unique_ptr<ViaCuda>(new ViaCuda());
}
// Configure the initial RTC from a fixed time. If not set the current
// wall time is used.
static void set_start_time(std::chrono::local_seconds start_time);
// HWComponent methods
int device_postinit();
@@ -203,20 +198,20 @@ private:
uint32_t via_clk_freq; // 0.00078336 VIA clock periods per ns; 0 integer bits, 42 fraction bits (first 10 are implicit zeros)
// VIA internal state
TimerInfo sr_timer;
uint32_t sr_timer_id = 0;
uint8_t last_orb = 0; // last value written to the ORB register.
// timer 1 state
uint8_t via_t1ll; // low-order latch
uint8_t via_t1lh; // high-order latch
uint16_t t1_counter; // internal counter
TimerInfo t1_timer;
uint32_t t1_timer_id = 0;
uint64_t t1_start_time = 0;
// timer 2 state
uint8_t via_t2ll; // low-order latch (write-only)
uint16_t t2_counter; // internal counter
TimerInfo t2_timer;
uint32_t t2_timer_id = 0;
uint64_t t2_start_time = 0;
// VIA interrupt related stuff
@@ -230,7 +225,7 @@ private:
uint8_t old_byteack;
uint8_t treq;
bool is_sync_state = false;
TimerInfo treq_timer;
uint32_t treq_timer_id = 0;
uint8_t in_buf[CUDA_IN_BUF_SIZE];
int32_t in_count;
int max_in_count = 0;
@@ -244,10 +239,8 @@ private:
uint8_t one_sec_mode = 0;
bool one_sec_first_pkt = true; // ERS: first one-sec pkt always mode $01
bool one_sec_missed = false; // ERS: missed pkt -> fallback to mode $01
bool file_server = false;
bool mono_stable = false;
bool power_messages_enabled = false;
uint8_t tickle_value = 0; // last shutdown watchdog count from the guest
bool file_server = false;
bool mono_stable = false;
uint8_t ipl_level = 0;
uint16_t device_mask = 0;
@@ -273,9 +266,7 @@ private:
void assert_t2_int();
void schedule_sr_int(uint64_t timeout_ns);
uint16_t calc_counter_val(const uint16_t last_val, const uint64_t &start_time);
void activate_t1(uint64_t start_time);
void activate_t2(uint64_t start_time);
void check_t2();
void activate_t1();
// CUDA methods
void cuda_init();
+28 -27
View File
@@ -70,14 +70,17 @@ void Swim3Ctrl::reset()
this->timer_val = 0;
this->phase_lines = 0;
if (this->one_us_timer.active) {
TimerManager::get_instance()->cancel_timer(this->one_us_timer);
if (this->one_us_timer_id) {
TimerManager::get_instance()->cancel_timer(this->one_us_timer_id);
this->one_us_timer_id = 0;
}
if (this->step_timer.active) {
TimerManager::get_instance()->cancel_timer(this->step_timer);
if (this->step_timer_id) {
TimerManager::get_instance()->cancel_timer(this->step_timer_id);
this->step_timer_id = 0;
}
if (this->access_timer.active) {
TimerManager::get_instance()->cancel_timer(this->access_timer);
if (this->access_timer_id) {
TimerManager::get_instance()->cancel_timer(this->access_timer_id);
this->access_timer_id = 0;
}
}
@@ -112,8 +115,6 @@ uint8_t Swim3Ctrl::read(uint8_t reg_offset)
return this->phase_lines;
case Swim3Reg::Setup:
return this->setup_reg;
case Swim3Reg::Status_Mode0:
return this->mode_reg;
case Swim3Reg::Handshake_Mode1:
if (this->mode_reg & SWIM3_DRIVE_1) { // internal drive?
status_addr = ((this->mode_reg & SWIM3_HEAD_SELECT) >> 2) | (this->phase_lines & 7);
@@ -236,7 +237,7 @@ void Swim3Ctrl::do_step()
// instruct the drive to perform single step in current direction
this->int_drive->command(MacSuperdrive::CommandAddr::Do_Step, 0);
if (--this->step_count == 0) {
if (this->step_timer.active) {
if (this->step_timer_id) {
this->stop_stepping();
}
this->int_flags |= INT_STEP_DONE;
@@ -252,12 +253,12 @@ void Swim3Ctrl::start_stepping()
return;
}
if (this->mode_reg & SWIM3_GO_STEP || this->step_timer.active) {
if (this->mode_reg & SWIM3_GO_STEP || this->step_timer_id) {
LOG_F(ERROR, "SWIM3: another stepping action is running!");
return;
}
if (this->mode_reg & SWIM3_GO || this->access_timer.active) {
if (this->mode_reg & SWIM3_GO || this->access_timer_id) {
LOG_F(ERROR, "SWIM3: stepping attempt while disk access is in progress!");
return;
}
@@ -272,9 +273,9 @@ void Swim3Ctrl::start_stepping()
// step count > 1 requires periodic task
if (this->step_count > 1) {
TimerManager::get_instance()->add_cyclic_timer(this->step_timer,
this->step_timer_id = TimerManager::get_instance()->add_cyclic_timer(
USECS_TO_NSECS(80),
[this](uint64_t, uint64_t) {
[this]() {
this->do_step();
}
);
@@ -287,20 +288,21 @@ void Swim3Ctrl::start_stepping()
void Swim3Ctrl::stop_stepping()
{
// cancel stepping task
if (this->step_timer.active) {
TimerManager::get_instance()->cancel_timer(this->step_timer);
if (this->step_timer_id) {
TimerManager::get_instance()->cancel_timer(this->step_timer_id);
this->step_timer_id = 0;
}
this->step_count = 0; // not sure this one is required
}
void Swim3Ctrl::start_disk_access()
{
if (this->mode_reg & SWIM3_GO || this->access_timer.active) {
if (this->mode_reg & SWIM3_GO || this->access_timer_id) {
LOG_F(ERROR, "SWIM3: another disk access is running!");
return;
}
if (this->mode_reg & SWIM3_GO_STEP || this->step_timer.active) {
if (this->mode_reg & SWIM3_GO_STEP || this->step_timer_id) {
LOG_F(ERROR, "SWIM3: disk access attempt while stepping is in progress!");
return;
}
@@ -315,9 +317,9 @@ void Swim3Ctrl::start_disk_access()
this->target_sect = this->first_sec;
TimerManager::get_instance()->add_oneshot_timer(this->access_timer,
this->access_timer_id = TimerManager::get_instance()->add_oneshot_timer(
this->int_drive->sync_to_disk(),
[this](uint64_t, uint64_t) {
[this]() {
this->cur_state = SWIM3_ADDR_MARK_SEARCH;
this->disk_access();
}
@@ -367,9 +369,9 @@ void Swim3Ctrl::disk_access()
return;
}
TimerManager::get_instance()->add_oneshot_timer(this->access_timer,
this->access_timer_id = TimerManager::get_instance()->add_oneshot_timer(
delay,
[this](uint64_t, uint64_t) {
[this]() {
this->disk_access();
}
);
@@ -378,8 +380,9 @@ void Swim3Ctrl::disk_access()
void Swim3Ctrl::stop_disk_access()
{
// cancel disk access timer
if (this->access_timer.active) {
TimerManager::get_instance()->cancel_timer(this->access_timer);
if (this->access_timer_id) {
TimerManager::get_instance()->cancel_timer(this->access_timer_id);
this->access_timer_id = 0;
}
}
@@ -396,11 +399,9 @@ void Swim3Ctrl::init_timer(const uint8_t start_val)
this->one_us_timer_start = TimerManager::get_instance()->current_time_ns();
if( this->one_us_timer.active)
LOG_F(ERROR, "SWIM3: one_us_timer is already active");
TimerManager::get_instance()->add_oneshot_timer(this->one_us_timer,
this->one_us_timer_id = TimerManager::get_instance()->add_oneshot_timer(
uint32_t(this->timer_val) * NS_PER_USEC,
[this](uint64_t, uint64_t) {
[this]() {
this->timer_val = 0;
this->int_flags |= INT_TIMER_DONE;
update_irq();
+3 -3
View File
@@ -140,9 +140,9 @@ private:
uint8_t rd_line;
int cur_state;
TimerInfo one_us_timer;
TimerInfo step_timer;
TimerInfo access_timer;
int one_us_timer_id = 0;
int step_timer_id = 0;
int access_timer_id = 0;
uint64_t one_us_timer_start = 0;
+27 -42
View File
@@ -96,8 +96,9 @@ AMIC::AMIC() : MMIODevice()
AMIC::~AMIC()
{
if (this->pseudo_vbl_timer.active) {
TimerManager::get_instance()->cancel_timer(this->pseudo_vbl_timer);
if (this->pseudo_vbl_tid) {
TimerManager::get_instance()->cancel_timer(this->pseudo_vbl_tid);
this->pseudo_vbl_tid = 0;
}
}
@@ -112,9 +113,9 @@ int AMIC::device_postinit()
}
// AMIC drives the VIA CA1 internally to generate 60.15 Hz interrupts
TimerManager::get_instance()->add_cyclic_timer(pseudo_vbl_timer,
this->pseudo_vbl_tid = TimerManager::get_instance()->add_cyclic_timer(
static_cast<uint64_t>((1.0f/60.15) * NS_PER_SEC + 0.5f),
[this](uint64_t, uint64_t) {
[this]() {
this->viacuda->assert_ctrl_line(ViaLine::CA1);
});
@@ -634,9 +635,7 @@ void AmicSndOutDma::update_irq() {
uint8_t new_level = !!((this->dma_out_ctrl >> 4) & this->dma_out_ctrl);
if (new_level != this->irq_level) {
this->irq_level = new_level;
if (this->interrupt_timer.active)
LOG_F(ERROR, "AMIC: interrupt_timer is already active");
TimerManager::get_instance()->add_immediate_timer(interrupt_timer, [this](uint64_t, uint64_t) {
TimerManager::get_instance()->add_immediate_timer([this] {
this->int_ctrl->ack_dma_int(this->snd_dma_irq_id, this->irq_level);
});
}
@@ -688,10 +687,10 @@ DmaPullResult AmicSndOutDma::pull_data(uint32_t req_len, uint32_t *avail_len,
MapDmaResult res = mmu_map_dma_mem(
(this->snd_buf_num ? this->out_buf1 : this->out_buf0) + this->cur_buf_pos,
len, false, true);
len, false);
*p_data = res.host_va;
this->cur_buf_pos += res.size;
*avail_len = res.size;
this->cur_buf_pos += len;
*avail_len = len;
return DmaPullResult::MoreData;
}
@@ -724,19 +723,15 @@ DmaPushResult AmicFloppyDma::push_data(const char* src_ptr, int len)
{
len = std::min((int)this->byte_count, len);
do {
MapDmaResult res = mmu_map_dma_mem(this->addr_ptr, len, false, true);
uint8_t *p_data = res.host_va;
if (!res.is_writable) {
ABORT_F("AMIC: attempting DMA write to read-only memory");
}
std::memcpy(p_data, src_ptr, res.size);
MapDmaResult res = mmu_map_dma_mem(this->addr_ptr, len, false);
uint8_t *p_data = res.host_va;
if (!res.is_writable) {
ABORT_F("AMIC: attempting DMA write to read-only memory");
}
std::memcpy(p_data, src_ptr, len);
this->addr_ptr += res.size;
this->byte_count -= res.size;
src_ptr += res.size;
len -= res.size;
} while (len > 0);
this->addr_ptr += len;
this->byte_count -= len;
if (!this->byte_count) {
LOG_F(WARNING, "AMIC: DMA interrupts not implemented yet");
}
@@ -787,17 +782,12 @@ void AmicScsiDma::xfer_from_device() {
uint32_t len = this->dev_obj->tell_xfer_size(this);
do {
MapDmaResult res = mmu_map_dma_mem(this->addr_ptr, len, false, true);
MapDmaResult res = mmu_map_dma_mem(this->addr_ptr, len, false);
int got_bytes = this->dev_obj->xfer_from(this, res.host_va, res.size);
if (got_bytes > 0) {
this->addr_ptr += got_bytes;
}
if (got_bytes < res.size)
break;
len -= res.size;
} while (len > 0);
int got_bytes = this->dev_obj->xfer_from(this, res.host_va, len);
if (got_bytes > 0) {
this->addr_ptr += got_bytes;
}
}
void AmicScsiDma::xfer_to_device() {
@@ -808,17 +798,12 @@ void AmicScsiDma::xfer_to_device() {
uint32_t len = this->dev_obj->tell_xfer_size(this);
do {
MapDmaResult res = mmu_map_dma_mem(this->addr_ptr, len, false, true);
MapDmaResult res = mmu_map_dma_mem(this->addr_ptr, len, false);
int got_bytes = this->dev_obj->xfer_to(this, res.host_va, res.size);
if (got_bytes > 0) {
this->addr_ptr += got_bytes;
}
if (got_bytes < res.size)
break;
len -= res.size;
} while (len > 0);
int got_bytes = this->dev_obj->xfer_to(this, res.host_va, len);
if (got_bytes > 0) {
this->addr_ptr += got_bytes;
}
}
void AmicScsiDma::xfer_retry() {
+1 -3
View File
@@ -24,7 +24,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef AMIC_H
#define AMIC_H
#include <core/timermanager.h>
#include <devices/common/dmacore.h>
#include <devices/common/hwinterrupt.h>
#include <devices/common/mmiodevice.h>
@@ -134,7 +133,6 @@ private:
InterruptCtrl *int_ctrl = nullptr;
uint64_t snd_dma_irq_id = 0;
uint8_t irq_level = 0;
TimerInfo interrupt_timer;
};
/** AMIC-specific floppy DMA implementation. */
@@ -413,7 +411,7 @@ private:
uint8_t via2_slot_ifr = 0x7F; // reverse logic
uint8_t via2_slot_irq = 0; // normal logic
TimerInfo pseudo_vbl_timer; // the pseudo-VBL timer
uint32_t pseudo_vbl_tid = 0; // ID for the pseudo-VBL timer
// AMIC subdevice instances
Sc53C94* scsi;
+13 -20
View File
@@ -41,14 +41,13 @@ NvramDev::NvramDev(NvramAddrHiDev *addr_hi) {
GrandCentral::GrandCentral() : PCIDevice("mac-io_grandcentral"), InterruptCtrl()
{
supports_types(HWCompType::IOBUS_HOST | HWCompType::MMIO_DEV |
HWCompType::PCI_DEV | HWCompType::INT_CTRL);
supports_types(HWCompType::IOBUS_HOST | HWCompType::MMIO_DEV | HWCompType::PCI_DEV | HWCompType::INT_CTRL);
// populate my PCI config header
this->vendor_id = PCI_VENDOR_APPLE;
this->device_id = MIO_DEV_ID_GRANDCENTRAL;
this->status = 0x0200; // 9:DEVSEL
this->class_rev = MACIO_DEVCLASS_ID | 2; // hardcoded revision = 2
this->class_rev = 0xFF000002;
this->cache_ln_sz = 8;
this->setup_bars({{0, 0xFFFE0000UL}}); // declare 128Kb of memory-mapped I/O space
@@ -296,7 +295,7 @@ uint32_t GrandCentral::read(uint32_t rgn_start, uint32_t offset, int size)
} else { // Interrupt related registers
switch (offset) {
case MIO_INT_EVENTS1:
return BYTESWAP_32(this->int_events & this->int_mask);
return BYTESWAP_32(this->int_events);
case MIO_INT_MASK1:
return BYTESWAP_32(this->int_mask);
case MIO_INT_CLEAR1:
@@ -304,7 +303,7 @@ uint32_t GrandCentral::read(uint32_t rgn_start, uint32_t offset, int size)
// so we return zero here as real HW does
return 0;
case MIO_INT_LEVELS1:
return BYTESWAP_32(this->int_levels | (1<<0x0B));
return BYTESWAP_32(this->int_levels);
}
}
@@ -434,7 +433,6 @@ void GrandCentral::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
switch (offset) {
case MIO_INT_MASK1:
this->int_mask = BYTESWAP_32(value);
this->clear_cpu_int();
this->signal_cpu_int();
break;
case MIO_INT_CLEAR1:
@@ -525,11 +523,15 @@ uint64_t GrandCentral::register_dma_int(IntSrc src_id) {
}
void GrandCentral::ack_int_common(uint64_t irq_id, uint8_t irq_line_state) {
// MACIO_INT_MODE is 0: native mode: set IRQ bits in int_events on a 0-to-1 transition
// MACIO_INT_MODE is 1: emulated mode: set IRQ bits in int_events on all transitions
// native mode: set IRQ bits in int_events on a 0-to-1 transition
// emulated mode: set IRQ bits in int_events on all transitions
uint32_t old_levels = this->int_levels;
uint32_t old_events = this->int_events;
if ((this->int_mask & MACIO_INT_MODE) ||
(irq_line_state && !(this->int_levels & irq_id))) {
this->int_events |= (uint32_t)irq_id;
} else {
this->int_events &= ~(uint32_t)irq_id;
}
// update IRQ line state
if (irq_line_state) {
@@ -538,16 +540,7 @@ void GrandCentral::ack_int_common(uint64_t irq_id, uint8_t irq_line_state) {
this->int_levels &= ~(uint32_t)irq_id;
}
if (
irq_line_state != !!(old_levels & irq_id)
&& (irq_line_state || (this->int_mask & MACIO_INT_MODE))
) {
this->int_events |= (uint32_t)irq_id;
// Events remain latched until software writes InterruptClear.
if (old_events != this->int_events) {
this->signal_cpu_int();
}
}
this->signal_cpu_int();
}
void GrandCentral::ack_int(uint64_t irq_id, uint8_t irq_line_state) {
+4 -7
View File
@@ -44,9 +44,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <memory>
#include <string>
/** MacIO ASICs report themselves as devices with unassigned PCI class code. */
constexpr uint32_t MACIO_DEVCLASS_ID = DEVCLASS_UNASSIGNED << 24;
/** PCI device IDs for various MacIO ASICs. */
enum {
MIO_DEV_ID_GRANDCENTRAL = 0x0002,
@@ -362,10 +359,10 @@ private:
uint32_t feat_ctrl = 0; // features control register
uint32_t aux_ctrl = 0; // aux features control register
uint8_t cpu_id = 0xF0; // CPUID field (LSB of the MIO_OHARE_ID)
uint8_t mb_id = 0x70; // Media Bay ID (bits 15:8 of the MIO_OHARE_ID)
uint8_t mon_id = 0x10; // Monitor ID (bits 23:16 of the MIO_OHARE_ID)
uint8_t fp_id = 0x70; // Flat panel ID (MSB of the MIO_OHARE_ID)
uint8_t cpu_id = 0xF0; // CPUID field (LSB of the MIO_HEAT_ID)
uint8_t mb_id = 0x70; // Media Bay ID (bits 15:8 of the MIO_HEAT_ID)
uint8_t mon_id = 0x10; // Monitor ID (bits 23:16 of the MIO_HEAT_ID)
uint8_t fp_id = 0x70; // Flat panel ID (MSB of the MIO_HEAT_ID)
// Subdevice object pointers
NVram* nvram; // NVRAM
+10 -16
View File
@@ -38,7 +38,7 @@ MacIoBase::MacIoBase(std::string name, uint16_t dev_id, uint8_t rev) :
// populate my PCI config header
this->vendor_id = PCI_VENDOR_APPLE;
this->device_id = dev_id;
this->class_rev = MACIO_DEVCLASS_ID + rev;
this->class_rev = 0xFF000000 + rev;
this->cache_ln_sz = 8;
// select memory mapped I/O size: 128Kb for Grand Central, 512Kb for others
@@ -133,8 +133,8 @@ uint64_t MacIoBase::register_dma_int(IntSrc src_id) {
}
void MacIoBase::ack_int_common(uint64_t irq_id, uint8_t irq_line_state) {
// MACIO_INT_MODE is 0: native mode: set IRQ bits in int_events on a 0-to-1 transition
// MACIO_INT_MODE is 1: emulated mode: set IRQ bits in int_events on all transitions
// native mode: set IRQ bits in int_events on a 0-to-1 transition
// emulated mode: set IRQ bits in int_events on all transitions
#if 0
LOG_F(INTERRUPT, "%s: native interrupt events:%08x.%08x levels:%08x.%08x change:%08x.%08x state:%d",
this->name.c_str(), uint32_t(this->int_events >> 32), uint32_t(this->int_events),
@@ -142,9 +142,12 @@ void MacIoBase::ack_int_common(uint64_t irq_id, uint8_t irq_line_state) {
uint32_t(irq_id >> 32), uint32_t(irq_id), irq_line_state
);
#endif
uint64_t old_levels = this->int_levels;
uint64_t old_events = this->int_events;
if ((this->int_mask & MACIO_INT_MODE) ||
(irq_line_state && !(this->int_levels & irq_id))) {
this->int_events |= irq_id;
} else {
this->int_events &= ~irq_id;
}
// update IRQ line state
if (irq_line_state) {
this->int_levels |= irq_id;
@@ -152,16 +155,7 @@ void MacIoBase::ack_int_common(uint64_t irq_id, uint8_t irq_line_state) {
this->int_levels &= ~irq_id;
}
if (
irq_line_state != !!(old_levels & irq_id)
&& (irq_line_state || (this->int_mask & MACIO_INT_MODE))
) {
this->int_events |= irq_id;
// Events remain latched until software writes InterruptClear.
if (old_events != this->int_events) {
this->signal_cpu_int();
}
}
this->signal_cpu_int();
}
void MacIoBase::ack_int(uint64_t irq_id, uint8_t irq_line_state) {
+3 -7
View File
@@ -291,7 +291,7 @@ uint32_t MacIoTwo::mio_ctrl_read(uint32_t offset, int size) {
switch (offset & ~3) {
case MIO_INT_EVENTS2:
value = (this->int_events & this->int_mask) >> 32;
value = this->int_events >> 32;
break;
case MIO_INT_MASK2:
value = this->int_mask >> 32;
@@ -300,7 +300,7 @@ uint32_t MacIoTwo::mio_ctrl_read(uint32_t offset, int size) {
value = this->int_levels >> 32;
break;
case MIO_INT_EVENTS1:
value = uint32_t(this->int_events & this->int_mask);
value = uint32_t(this->int_events);
break;
case MIO_INT_MASK1:
value = uint32_t(this->int_mask);
@@ -366,10 +366,7 @@ void MacIoTwo::mio_ctrl_write(uint32_t offset, uint32_t value, int size) {
switch (offset & ~3) {
case MIO_INT_MASK2:
// Preserve the first bank and the read-only IntMode bit.
this->int_mask = (this->int_mask & 0x80000000FFFFFFFFULL) |
(uint64_t(value & ~MACIO_INT_MODE) << 32);
this->clear_cpu_int();
this->int_mask |= uint64_t(value & ~MACIO_INT_MODE) << 32;
this->signal_cpu_int();
break;
case MIO_INT_CLEAR2:
@@ -380,7 +377,6 @@ void MacIoTwo::mio_ctrl_write(uint32_t offset, uint32_t value, int size) {
this->int_mask = (this->int_mask & 0x7FFFFFFF00000000ULL) | value;
// copy IntMode bit to InterruptMask2 register
this->int_mask |= uint64_t(this->int_mask & MACIO_INT_MODE) << 32;
this->clear_cpu_int();
this->signal_cpu_int();
break;
case MIO_INT_CLEAR1:
+17 -34
View File
@@ -40,7 +40,7 @@ MPC106::MPC106() : MemCtrlBase(), PCIDevice("Grackle"), PCIHost()
// populate PCI config header
this->vendor_id = PCI_VENDOR_MOTOROLA;
this->device_id = 0x0002;
this->class_rev = DEVTYPE_HOST2PCI_BRIDGE | GRACKLE_REV_4_0;
this->class_rev = 0x06000040;
this->cache_ln_sz = 8;
this->command = 6;
this->status = 0x80;
@@ -314,41 +314,24 @@ void MPC106::setup_ram() {
}
}
static const PropMap GrackleGossamer_Properties = {
{"pci_PERCH", new StrProperty("")},
{"pci_A1" , new StrProperty("")},
{"pci_B1" , new StrProperty("")},
{"pci_C1" , new StrProperty("")},
// {"pci_GPU" , new StrProperty("")},
static const PropMap Grackle_Properties = {
{"pci_PERCH",
new StrProperty("")},
{"pci_A1",
new StrProperty("")},
{"pci_B1",
new StrProperty("")},
{"pci_C1",
new StrProperty("")},
//{"pci_GPU",
// new StrProperty("")},
{"pci_J12",
new StrProperty("")},
};
static const PropMap GrackleYosemite_Properties = {
// {"pci_J12", new StrProperty("")},
};
static const PropMap GrackleBondi_Properties = {
{"pci_A1" , new StrProperty("")},
{"pci_B1" , new StrProperty("")},
{"pci_C1" , new StrProperty("")},
// {"pci_GPU" , new StrProperty("")},
{"pci_PERCH", new StrProperty("")},
};
static const DeviceDescription GrackleGossamer_Descriptor = {
MPC106::create, {}, GrackleGossamer_Properties,
static const DeviceDescription Grackle_Descriptor = {
MPC106::create, {}, Grackle_Properties,
HWCompType::MEM_CTRL | HWCompType::MMIO_DEV | HWCompType::PCI_HOST | HWCompType::PCI_DEV
};
static const DeviceDescription GrackleYosemite_Descriptor = {
MPC106::create, {}, GrackleYosemite_Properties,
HWCompType::MEM_CTRL | HWCompType::MMIO_DEV | HWCompType::PCI_HOST | HWCompType::PCI_DEV
};
static const DeviceDescription GrackleBondi_Descriptor = {
MPC106::create, {}, GrackleBondi_Properties,
HWCompType::MEM_CTRL | HWCompType::MMIO_DEV | HWCompType::PCI_HOST | HWCompType::PCI_DEV
};
REGISTER_DEVICE(GrackleGossamer, GrackleGossamer_Descriptor);
REGISTER_DEVICE(GrackleYosemite, GrackleYosemite_Descriptor);
REGISTER_DEVICE(GrackleBondi , GrackleBondi_Descriptor );
REGISTER_DEVICE(Grackle, Grackle_Descriptor);
+1 -2
View File
@@ -42,8 +42,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cinttypes>
#include <memory>
/** Grackle ASIC revisions. */
constexpr uint8_t GRACKLE_REV_4_0 = 0x40;
class InterruptCtrl;
/** Grackle configuration space registers. */
enum GrackleReg : uint32_t {
+26 -55
View File
@@ -58,15 +58,7 @@ PlatinumCtrl::PlatinumCtrl() : MemCtrlBase(), VideoCtrlBase() {
// initialize the CPUID register with the following CPU:
// PowerPC 601 @ 90 MHz, bus frequency: 45 MHz
this->cpu_id =
( 0x3 << 28) | // Design Center: 3 = High-End RISC Design Center
( 0 << 24) | // Upper ID: 0 = machine with registers wider than 8-bit
(0x01 << 16) | // Lower ID: 1 = Platinum-based machine
ClkSrc2 | // Clock Source: bits 15 and 6
( 0 << 12) | // Motherboard ID: Catalyst motherboard with 1 MB of VRAM
(CpuSpeed2::CPU_90_BUS_45 << 8)
| // System/CPU Speed
( 0 << 7) ; // CPU Type: 0 = 601, 1 = 603/604
this->cpu_id = (0x3001 << 16) | ClkSrc2 | (CpuSpeed2::CPU_90_BUS_45 << 8);
this->display_id = std::unique_ptr<DisplayID> (new DisplayID());
@@ -78,10 +70,8 @@ PlatinumCtrl::PlatinumCtrl() : MemCtrlBase(), VideoCtrlBase() {
};
this->dacula->set_clut_entry_cb = [this](uint8_t index, uint8_t *colors) {
this->set_palette_color(index, colors[0], colors[1], colors[2], 0xFF);
this->draw_fb = true;
};
this->dacula->cursor_ctrl_cb = [this](bool cursor_on) {
this->draw_fb = true;
if (cursor_on) {
this->dacula->measure_hw_cursor(this->fb_ptr - 16);
this->cursor_ovl_cb = [this](uint8_t *dst_buf, int dst_pitch) {
@@ -92,14 +82,6 @@ PlatinumCtrl::PlatinumCtrl() : MemCtrlBase(), VideoCtrlBase() {
this->cursor_ovl_cb = nullptr;
}
};
this->dacula->cursor_update_cb = [this]() {
this->draw_fb = true;
};
this->dacula->video_mode_ctrl_cb = [this]() {
this->change_display();
};
this->draw_fb_is_dynamic = true;
}
int PlatinumCtrl::device_postinit() {
@@ -132,7 +114,7 @@ uint32_t PlatinumCtrl::read(uint32_t rgn_start, uint32_t offset, int size) {
return read_mem(&this->vram_ptr[offset], size);
} else {
LOG_F(WARNING, "%s: read from unmapped aperture address 0x%X",
this->name.c_str(), VRAM_REGION_BASE + offset);
this->name.c_str(), this->fb_addr + offset);
return (uint32_t)-1;
}
}
@@ -233,12 +215,11 @@ void PlatinumCtrl::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
uint8_t mon_levels = 0;
if (rgn_start == VRAM_REGION_BASE) {
if (offset < this->vram_size) {
this->draw_fb = true;
if (offset < this->vram_size)
write_mem(&this->vram_ptr[offset], value, size);
} else
else
LOG_F(WARNING, "%s: write to unmapped aperture address 0x%X",
this->name.c_str(), VRAM_REGION_BASE + offset);
this->name.c_str(), this->fb_addr + offset);
return;
}
@@ -247,10 +228,10 @@ void PlatinumCtrl::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
this->rom_timing = value;
break;
case PlatinumReg::DRAM_TIMING:
this->dram_timing = value & 0x1FFF;
this->dram_timing = value;
break;
case PlatinumReg::DRAM_REFRESH:
this->dram_refresh = value & 0x7FF;
this->dram_refresh = value;
break;
case PlatinumReg::BANK_0_BASE:
case PlatinumReg::BANK_1_BASE:
@@ -260,22 +241,20 @@ void PlatinumCtrl::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
case PlatinumReg::BANK_5_BASE:
case PlatinumReg::BANK_6_BASE:
case PlatinumReg::BANK_7_BASE:
this->bank_base[(offset >> 4) - PlatinumReg::BANK_0_BASE] = value & 0xFF700000U;
this->bank_base[(offset >> 4) - PlatinumReg::BANK_0_BASE] = value;
this->map_phys_ram();
break;
case PlatinumReg::FB_BASE_ADDR:
if (this->fb_addr != value) {
this->fb_addr = value;
this->fb_offset = value & 0x3FFFFF;
this->change_display();
}
this->fb_addr = value;
this->fb_offset = value & 0x3FFFFF;
this->change_display();
break;
case PlatinumReg::ROW_WORDS:
this->row_words = value & 0x7FF8;
this->row_words = value & ~7;
this->change_display();
break;
case PlatinumReg::CLOCK_DIVISOR:
this->clock_divisor = value & 0xFFU;
this->clock_divisor = value;
this->change_display();
break;
case PlatinumReg::FB_CONFIG_1:
@@ -286,10 +265,10 @@ void PlatinumCtrl::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
this->half_bank = !!(this->vram_megs == 1 && (value & CFG1_FULL_BANKS));
break;
case PlatinumReg::FB_CONFIG_2:
this->fb_config_2 = value & 0x1FFF;
this->fb_config_2 = value;
break;
case PlatinumReg::VMEM_PAGE_MODE:
this->vmem_fp_mode = value & 1;
this->vmem_fp_mode = value;
break;
case PlatinumReg::MON_ID_SENSE:
value &= 7;
@@ -300,7 +279,6 @@ void PlatinumCtrl::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
(this->display_id->read_monitor_sense(mon_levels, mon_dirs) ^ 7);
break;
case PlatinumReg::FB_RESET:
value &= 7;
if (value == 7 && this->crtc_on) {
LOG_F(INFO, "%s: video disabled", this->name.c_str());
this->reset_step = 0;
@@ -336,10 +314,10 @@ void PlatinumCtrl::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
(value & (SENSE_LINE_OUTPUT_DATA | SYNCS_OUTPUT_ENABLE | FORCED_SYNC_LEVELS));
break;
case PlatinumReg::VRAM_REFRESH:
this->vram_refresh = value & 0x7FF;
this->vram_refresh = value;
break;
case PlatinumReg::SWATCH_CONFIG:
this->swatch_config = (this->swatch_config & ~0xFFU) | (value & 0xFFU);
this->swatch_config = value;
break;
case PlatinumReg::SWATCH_INT_MASK:
this->swatch_int_mask = value;
@@ -347,7 +325,7 @@ void PlatinumCtrl::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
LOG_F(INFO, "%s: VBL interrupt enabled", this->name.c_str());
break;
case PlatinumReg::CURSOR_LINE:
this->cursor_line = value & 0x7FF;
this->cursor_line = value;
if (this->swatch_int_mask & SWATCH_INT_CURSOR)
this->enable_cursor_int();
break;
@@ -360,6 +338,7 @@ void PlatinumCtrl::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
//break;
case PlatinumReg::SWATCH_HSERR:
case PlatinumReg::SWATCH_HLFLN:
case PlatinumReg::SWATCH_HEQ:
case PlatinumReg::SWATCH_HSP:
case PlatinumReg::SWATCH_HBWAY:
case PlatinumReg::SWATCH_HBRST:
@@ -374,15 +353,11 @@ void PlatinumCtrl::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
case PlatinumReg::SWATCH_VAL:
case PlatinumReg::SWATCH_VFP:
case PlatinumReg::SWATCH_VFPEQ:
this->swatch_params[REG_TO_INDEX(offset >> 4)] = value & 0xFFF;
this->change_display();
break;
case PlatinumReg::SWATCH_HEQ:
this->swatch_params[REG_TO_INDEX(offset >> 4)] = value & 0xFF;
this->swatch_params[REG_TO_INDEX(offset >> 4)] = value;
this->change_display();
break;
case PlatinumReg::TIMING_ADJUST:
this->timing_adjust = value & 0xFFF;
this->timing_adjust = value;
break;
case PlatinumReg::IRIDIUM_CONFIG:
if (!(value & 1))
@@ -539,19 +514,16 @@ void PlatinumCtrl::enable_display() {
switch (this->pixel_depth) {
case 8:
this->convert_fb_cb = [this](uint8_t *dst_buf, int dst_pitch) {
this->draw_fb = false;
this->convert_frame_8bpp_indexed(dst_buf, dst_pitch);
};
break;
case 16:
this->convert_fb_cb = [this](uint8_t *dst_buf, int dst_pitch) {
this->draw_fb = false;
this->convert_frame_15bpp<BE>(dst_buf, dst_pitch);
};
break;
case 32:
this->convert_fb_cb = [this](uint8_t *dst_buf, int dst_pitch) {
this->draw_fb = false;
this->convert_frame_32bpp<BE>(dst_buf, dst_pitch);
};
break;
@@ -592,7 +564,6 @@ void PlatinumCtrl::enable_display() {
this->blank_on = false;
this->crtc_on = true;
this->draw_fb = true;
}
void PlatinumCtrl::disable_display() {
@@ -615,12 +586,12 @@ void PlatinumCtrl::enable_cursor_int() {
LOG_F(INFO, "%s: cursor interrupt frequency %lld ns", this->name.c_str(),
cursor_int_freq);
if (this->cursor_timer.active)
TimerManager::get_instance()->cancel_timer(this->cursor_timer);
if (this->cursor_task_id)
TimerManager::get_instance()->cancel_timer(this->cursor_task_id);
TimerManager::get_instance()->add_cyclic_timer(this->cursor_timer,
this->cursor_task_id = TimerManager::get_instance()->add_cyclic_timer(
cursor_int_freq,
[this](uint64_t, uint64_t) {
[this]() {
this->update_irq(1, SWATCH_INT_CURSOR); // generate cursor interrupt
}
);
@@ -641,7 +612,7 @@ void PlatinumCtrl::update_irq(uint8_t irq_line_state, uint8_t irq_mask) {
// ========================== Device registry stuff ==========================
static const PropMap Platinum_Properties = {
{"gfxmem_size",
new IntProperty(4, std::vector<uint32_t>({1, 2, 4}))},
new IntProperty(1, std::vector<uint32_t>({1, 2, 4}))},
{"mon_id",
new StrProperty("HiRes12-14in")},
};
+1 -1
View File
@@ -363,7 +363,7 @@ private:
uint32_t swatch_int_mask = 0;
uint32_t swatch_int_stat = 0;
uint32_t cursor_line = 0;
TimerInfo cursor_timer;
uint32_t cursor_task_id = 0;
std::unique_ptr<uint8_t[]> vram_ptr = nullptr;
std::unique_ptr<DisplayID> display_id = nullptr;
+1
View File
@@ -38,6 +38,7 @@ PsxCtrl::PsxCtrl(int bridge_num, std::string name)
// add MMIO region for the PSX control registers
this->add_mmio_region(0xF8000000, 0x70, this);
this->sys_id = 0x10000000; // PSX register dump from a 6500 at 68kmla
this->set_revision_id(0x10); // PSX register dump from a 6500 at 68kmla
this->set_bus_speed(PSX_BUS_SPEED_50); // set bus speed to 50 MHz by default
}
+7 -7
View File
@@ -92,13 +92,13 @@ public:
void map_phys_ram();
private:
uint32_t sys_id = 0x10000000; // PSX register dump from a 6500 at 68kmla
uint32_t chip_rev = 0;
uint32_t sys_config = 0;
uint32_t rom_cfg = 0x000009D8;
uint32_t dram_cfg = 0x00E18534;
uint32_t dram_refresh = 0x001F0180;
uint32_t flash_cfg = 0x00000038;
uint32_t sys_id;
uint32_t chip_rev;
uint32_t sys_config;
uint32_t rom_cfg;
uint32_t dram_cfg;
uint32_t dram_refresh;
uint32_t flash_cfg;
uint32_t pages_cfg[5] = {0x88888888,0x88888888,0x88888888,0x88888888,0x88888888};
uint32_t bank_size[5] = {};
std::unique_ptr<uint8_t[]> dram_ptr = nullptr;
+8 -7
View File
@@ -114,12 +114,11 @@ void AwacsBase::dma_in_data() {
dbdma_ch->set_stat(sound_in_status);
LOG_F(INFO, "%s: status:%x", this->name.c_str(), sound_in_status);
if (this->dma_in_timer.active)
LOG_F(ERROR, "%s: dma_in_timer is already active", this->name.c_str());
TimerManager::get_instance()->add_oneshot_timer(this->dma_in_timer,
this->dma_in_timer_id = TimerManager::get_instance()->add_oneshot_timer(
10000,
[this](uint64_t, uint64_t) {
[this]() {
// re-enter the sequencer with the state specified in next_state
this->dma_in_timer_id = 0;
this->dma_in_data();
});
}
@@ -131,8 +130,9 @@ void AwacsBase::dma_in_start() {
}
void AwacsBase::dma_in_stop() {
if (this->dma_in_timer.active) {
TimerManager::get_instance()->cancel_timer(this->dma_in_timer);
if (this->dma_in_timer_id) {
TimerManager::get_instance()->cancel_timer(this->dma_in_timer_id);
this->dma_in_timer_id = 0;
}
LOG_F(ERROR, "%s: dma_in_stop", this->name.c_str());
}
@@ -199,7 +199,7 @@ uint32_t AwacsScreamer::snd_ctrl_read(uint32_t offset, int size) {
(AWAC_REV_SCREAMER << 20);
break;
case AWAC_CLIP_COUNT:
value = this->clip_count;
value = this->clip_count;
this->clip_count = 0;
break;
case AWAC_BYTE_SWAP:
@@ -221,6 +221,7 @@ void AwacsScreamer::snd_ctrl_write(uint32_t offset, uint32_t value, int size) {
this->snd_ctrl_reg = BYTESWAP_32(value);
this->set_sample_rate((this->snd_ctrl_reg >> 8) & 7);
break;
case AWAC_CODEC_CTRL_REG: {
if (this->is_busy)
return;
+1 -1
View File
@@ -66,7 +66,7 @@ protected:
SoundServer *snd_server; // SoundServer instance pointer
DmaOutChannel *dma_out_ch; // DMA output channel instance pointer
DmaInChannel *dma_in_ch; // DMA input channel instance pointer
TimerInfo dma_in_timer;
uint32_t dma_in_timer_id = 0;
int *sr_table; // pointer to the table of supported sample rates
int max_sr_id; // maximum value for sample rate ID
+28 -64
View File
@@ -28,7 +28,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <devices/sound/burgundy.h>
#include <loguru.hpp>
BurgundyCodec::BurgundyCodec(std::string name) : MacioSndCodec(name) {
BurgundyCodec::BurgundyCodec(std::string name) : MacioSndCodec(name)
{
supports_types(HWCompType::SND_CODEC);
static int burgundy_sample_rates[1] = { 44100 };
@@ -38,96 +39,59 @@ BurgundyCodec::BurgundyCodec(std::string name) : MacioSndCodec(name) {
this->max_sr_id = 1;
this->set_sample_rate(0); // set default sample rate
this->reg_array[0x01] = 0x01010000; // ID 1 (Burgundy), Vendor 1 (Crystal), Version 0, Revision 0
}
uint32_t BurgundyCodec::snd_ctrl_read(uint32_t offset, int size) {
uint32_t value = 0;
uint32_t result = 0;
switch (offset) {
case AWAC_SOUND_CTRL_REG:
value = this->snd_ctrl_reg;
break;
case AWAC_CODEC_CTRL_REG:
value = this->last_ctrl_data;
result = this->last_ctrl_data;
break;
case AWAC_CODEC_STATUS_REG:
value =
(
(
9 |
CODEC_STATUS::SENSE_MIC |
CODEC_STATUS::SENSE_HEADPHONES
) << CODEC_STATUS::SENSE_POS
) |
(this->data_byte << CODEC_STATUS::DATA_POS) |
(this->read_pos << CODEC_STATUS::CURRENTBYTE_POS) |
(this->byte_counter << CODEC_STATUS::BYTECOUNTER_POS) |
(0 << CODEC_STATUS::INDICATOR_POS) |
CODEC_STATUS::READY |
(this->first_valid ? CODEC_STATUS::FIRST_VALID_BYTE : 0);
break;
case AWAC_FRAME_COUNT:
value = (uint32_t)(
(
(TimerManager::get_instance()->current_time_ns() - frame_count_start_time) * this->sr_table[0]
+ 500000000
) / 1000000000 + this->frame_count
);
result = (this->first_valid << 23) | BURGUNDY_READY |
(this->byte_counter << 14) | (this->read_pos << 12) |
(this->data_byte << 4);
break;
default:
LOG_F(ERROR, "%s: read from unsupported register 0x%X", this->name.c_str(),
offset);
}
return BYTESWAP_32(value);
return BYTESWAP_32(result);
}
void BurgundyCodec::snd_ctrl_write(uint32_t offset, uint32_t value, int size) {
uint8_t reg_addr;
uint8_t cur_byte;
//uint8_t last_byte;
value = BYTESWAP_32(value);
switch (offset) {
case AWAC_SOUND_CTRL_REG:
this->snd_ctrl_reg = value;
//this->set_sample_rate((this->snd_ctrl_reg & SOUND_CONTROL::RATE_MASK) >> SOUND_CONTROL::RATE_POS);
break;
case AWAC_CODEC_CTRL_REG:
{
this->last_ctrl_data = value & ~CODEC_CONTROL::BUSY;
uint8_t write_byte = (value & CODEC_CONTROL::DATA_MASK) >> CODEC_CONTROL::DATA_POS;
uint8_t reg_addr = (value & CODEC_CONTROL::ADDR_MASK) >> CODEC_CONTROL::ADDR_POS;
uint8_t cur_byte = (value & CODEC_CONTROL::CURRENTBYTE_MASK) >> CODEC_CONTROL::CURRENTBYTE_POS;
uint8_t last_byte = (value & CODEC_CONTROL::LASTBYTE_MASK) >> CODEC_CONTROL::LASTBYTE_POS;
bool reset = value & CODEC_CONTROL::RESET;
bool write = value & CODEC_CONTROL::WRITE;
if (write) {
if (reg_addr < BURGUNDY_NUM_REGS) {
uint32_t mask = 0xFFU << (cur_byte * 8);
this->reg_array[reg_addr] = (this->reg_array[reg_addr] & ~mask) |
(write_byte << (cur_byte * 8));
}
this->last_ctrl_data = value;
reg_addr = (value >> 12) & 0xFF;
cur_byte = (value >> 8) & 3;
//last_byte = (value >> 10) & 3;
if (value & BURGUNDY_REG_WR) {
uint32_t mask = 0xFFU << (cur_byte * 8);
this->reg_array[reg_addr] = (this->reg_array[reg_addr] & ~mask) |
((value & 0xFFU) << (cur_byte * 8));
} else {
this->reg_addr = reg_addr;
this->read_pos = cur_byte;
this->data_byte = ((reg_addr < BURGUNDY_NUM_REGS ? this->reg_array[reg_addr] : 0) >> (cur_byte * 8)) & 0xFFU;
this->first_valid = true;
this->reg_addr = reg_addr;
this->read_pos = cur_byte;
this->data_byte = (this->reg_array[reg_addr] >> (cur_byte * 8)) & 0xFFU;
this->first_valid = 1;
if (this->first_valid_timer.active)
LOG_F(ERROR, "%s: first_valid_timer is already active", this->name.c_str());
TimerManager::get_instance()->add_oneshot_timer(this->first_valid_timer,
USECS_TO_NSECS(22), // average is approximately 22.6 µs on a real B&W G3
[this](uint64_t, uint64_t) {
this->first_valid = false;
TimerManager::get_instance()->add_oneshot_timer(
USECS_TO_NSECS(10), // not sure if this is the correct delay
[this]() {
this->first_valid = 0;
this->byte_counter = (this->byte_counter + 1) & 3;
});
}
break;
}
case AWAC_FRAME_COUNT:
this->frame_count = value;
this->frame_count_start_time = TimerManager::get_instance()->current_time_ns();
break;
default:
LOG_F(ERROR, "%s: write to unsupported register 0x%X", this->name.c_str(),
offset);
+6 -81
View File
@@ -24,91 +24,20 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef BURGUNDY_H
#define BURGUNDY_H
#include <core/timermanager.h>
#include <devices/common/hwcomponent.h>
#include <devices/sound/awacs.h>
#include <cinttypes>
#include <string>
enum {
BURGUNDY_REG_WR = 1 << 21,
BURGUNDY_READY = 1 << 22,
};
/** Number of internal registers implemented in Burgundy. */
constexpr auto BURGUNDY_NUM_REGS = 123;
namespace SOUND_CONTROL { // 0x00
enum {
INSUBFRAME_MASK = 0x0000000F,
INSUBFRAME_POS = 0,
INSUBFRAME0 = 0x1,
INSUBFRAME1 = 0x2,
INSUBFRAME2 = 0x4,
INSUBFRAME3 = 0x8,
OUTSUBFRAME_MASK = 0x000000F0,
OUTSUBFRAME_POS = 4,
OUTSUBFRAME0 = 0x1,
OUTSUBFRAME1 = 0x2,
OUTSUBFRAME2 = 0x4,
OUTSUBFRAME3 = 0x8,
RATE_MASK = 0x00000700,
RATE_POS = 8,
RATE_44100 = 0x0,
ERROR = 0x00000800,
PORTCHANGE = 0x00001000,
ERRORINT = 0x00002000,
STATUSSUBFRAME_MASK = 0x00018000,
STATUSSUBFRAME_POS = 15,
STATUSSUBFRAME0 = 0x0,
STATUSSUBFRAME1 = 0x1,
STATUSSUBFRAME2 = 0x2,
STATUSSUBFRAME3 = 0x3,
};
}
namespace CODEC_CONTROL { // 0x10
enum {
DATA_MASK = 0x000000FF,
DATA_POS = 0,
CURRENTBYTE_MASK = 0x00000300,
CURRENTBYTE_POS = 8,
LASTBYTE_MASK = 0x00000C00,
LASTBYTE_POS = 10,
ADDR_MASK = 0x000FF000,
ADDR_POS = 12,
RESET = 0x00100000, // should be set when current byte is 0
WRITE = 0x00200000, // READ = 0
BUSY = 0x01000000, // set when writing to CODEC_CONTROL, clear when done
};
}
namespace CODEC_STATUS { // 0x20
enum {
SENSE_MASK = 0x0000000F,
SENSE_POS = 0,
SENSE_MIC = 0x2,
SENSE_HEADPHONES = 0x4,
SENSE_HEADPHONES2 = 0x8, // 1 = line level mic (default) 0 = powered mic
DATA_MASK = 0x00000FF0,
DATA_POS = 4,
CURRENTBYTE_MASK = 0x00003000,
CURRENTBYTE_POS = 12,
BYTECOUNTER_MASK = 0x0000C000,
BYTECOUNTER_POS = 14,
INDICATOR_MASK = 0x000F0000,
INDICATOR_POS = 16,
INDICATOR_TONECONTROL = 0x1,
INDICATOR_OVERFLOW0 = 0x2,
INDICATOR_OVERFLOW1 = 0x3,
INDICATOR_OVERFLOW2 = 0x4,
INDICATOR_INPUTLINECHG = 0x6,
INDICATOR_THRESHOLD0 = 0xB,
INDICATOR_THRESHOLD1 = 0xC,
INDICATOR_THRESHOLD2 = 0xD,
INDICATOR_THRESHOLD3 = 0xE,
INDICATOR_TWILIGHTCMP = 0xF,
READY = 0x00400000,
FIRST_VALID_BYTE = 0x00800000, // wait for set, then wait for clear before reading data
};
}
class BurgundyCodec : public MacioSndCodec {
public:
BurgundyCodec(std::string name);
@@ -122,16 +51,12 @@ public:
}
private:
uint32_t snd_ctrl_reg = 0x1011;
uint32_t last_ctrl_data = 0;
uint8_t byte_counter = 0;
uint8_t reg_addr = 0;
bool first_valid = false;
TimerInfo first_valid_timer;
uint8_t first_valid = 0;
uint8_t read_pos = 0;
uint8_t data_byte = 0;
uint32_t frame_count = 0;
uint64_t frame_count_start_time = 0;
uint32_t reg_array[BURGUNDY_NUM_REGS] = {};
};
+26 -43
View File
@@ -51,7 +51,7 @@ public:
cubeb *cubeb_ctx;
cubeb_stream *out_stream;
TimerInfo deterministic_poll_timer;
uint32_t deterministic_poll_timer = 0;
timer_cb deterministic_poll_cb;
};
@@ -134,7 +134,7 @@ static long sound_out_callback(cubeb_stream* stream, void* user_data,
out_frames = 0;
while (req_frames > 0) {
if (DmaPullResult::MoreData == dma_ch->pull_data((uint32_t)req_frames << 2, &got_len, &p_in)) {
if (!dma_ch->pull_data((uint32_t)req_frames << 2, &got_len, &p_in)) {
if ((in_buf = (int16_t*)p_in)) {
frames = got_len >> 2;
@@ -167,26 +167,23 @@ static void status_callback(cubeb_stream *stream, void *user_data, cubeb_state s
int SoundServer::open_out_stream(uint32_t sample_rate, DmaOutChannel *dma_ch)
{
// Set up a cyclic-timer DMA drain callback. It keeps the guest sound DMA
// advancing even if the host audio stream cannot be started, otherwise
// the guest sound driver would stall forever waiting for DMA interrupts.
impl->deterministic_poll_cb = [dma_ch](uint64_t, uint64_t) {
if (!dma_ch->is_out_active()) {
return;
}
// Drain the DMA buffer, but don't do anything else.
while(1) {
uint8_t *chunk;
uint32_t chunk_size;
if (DmaPullResult::MoreData == dma_ch->pull_data(1024, &chunk_size, &chunk)) {
;
} else {
break;
}
}
};
if (is_deterministic) {
impl->deterministic_poll_cb = [dma_ch] {
if (!dma_ch->is_out_active()) {
return;
}
// Drain the DMA buffer, but don't do anything else.
int req_size = std::max(dma_ch->get_pull_data_remaining(), 1024);
while (req_size > 0) {
uint8_t *chunk;
uint32_t chunk_size;
if (!dma_ch->pull_data(req_size, &chunk_size, &chunk)) {
req_size -= chunk_size;
} else {
break;
}
}
};
impl->status = SND_STREAM_OPENED;
LOG_F(9, "Deterministic sound output callback set up.");
return 0;
@@ -227,35 +224,21 @@ int SoundServer::open_out_stream(uint32_t sample_rate, DmaOutChannel *dma_ch)
int SoundServer::start_out_stream()
{
if (is_deterministic) {
// DMA can restart after a STOP command without closing the output
// stream; the timer may already be running.
if (!impl->deterministic_poll_timer.active) {
LOG_F(9, "Starting sound output deterministic polling.");
TimerManager::get_instance()->add_cyclic_timer(
impl->deterministic_poll_timer, MSECS_TO_NSECS(10), impl->deterministic_poll_cb);
}
LOG_F(9, "Starting sound output deterministic polling.");
impl->deterministic_poll_timer =
TimerManager::get_instance()->add_cyclic_timer(MSECS_TO_NSECS(10), impl->deterministic_poll_cb);
return 0;
}
int res = cubeb_stream_start(impl->out_stream);
if (res != CUBEB_OK) {
// Fall back to draining the guest sound DMA via a cyclic timer so
// that the guest sound driver does not stall waiting for DMA progress
// that the failed host stream will never provide.
if (!impl->deterministic_poll_timer.active) {
TimerManager::get_instance()->add_cyclic_timer(
impl->deterministic_poll_timer, MSECS_TO_NSECS(10), impl->deterministic_poll_cb);
LOG_F(9, "Host sound output stream start failed; falling back to cyclic DMA drain.");
}
}
return res;
return cubeb_stream_start(impl->out_stream);
}
void SoundServer::close_out_stream()
{
if (impl->deterministic_poll_timer.active) {
if (!impl->out_stream)
return;
if (is_deterministic) {
LOG_F(9, "Stopping sound output deterministic polling.");
TimerManager::get_instance()->cancel_timer(impl->deterministic_poll_timer);
}
if (!impl->out_stream) {
impl->status = SND_STREAM_CLOSED;
return;
}
+8 -31
View File
@@ -39,45 +39,22 @@ BlockStorageDevice::BlockStorageDevice(const uint32_t cache_blocks,
}
BlockStorageDevice::~BlockStorageDevice() {
this->detach_image();
this->img_file.close();
}
bool BlockStorageDevice::attach_image(const std::string& file_path) {
if (!this->img_file.open(file_path))
return false;
int BlockStorageDevice::set_host_file(std::string file_path) {
this->is_ready = false;
this->is_ready = false;
this->size_bytes = this->img_file.size();
this->remain_size = 0;
this->write_size = 0;
this->data_offset = 0;
if (!this->img_file.open(file_path))
return -1;
this->size_bytes = this->img_file.size();
this->set_fpos(0);
this->is_ready = true;
if (this->set_block_size(this->block_size) < 0) {
this->detach_image();
return false;
}
return true;
}
bool BlockStorageDevice::detach_image() {
if (!this->is_ready)
return false;
this->is_ready = false;
this->img_file.close();
this->size_bytes = 0;
this->size_blocks = 0;
this->cur_fpos = 0;
this->write_size = 0;
this->remain_size = 0;
return true;
return this->set_block_size(this->block_size);
}
int BlockStorageDevice::set_block_size(const int blk_size) {
+1 -4
View File
@@ -36,10 +36,7 @@ public:
const uint64_t max_blocks=UINT64_MAX);
~BlockStorageDevice();
bool attach_image(const std::string& file_path);
bool detach_image();
bool image_attached() const { return this->is_ready; }
int set_host_file(std::string file_path);
int set_block_size(const int blk_size);
int set_fpos(const uint64_t lba);
+293 -51
View File
@@ -21,7 +21,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file Virtual CD-ROM device implementation. */
#include <core/hostevents.h>
#include <core/memaccess.h>
#include <devices/common/scsi/scsi.h> // reuse SCSI definitions
#include <devices/storage/cdromdrive.h>
#include <loguru.hpp>
@@ -30,46 +31,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <string>
CdromDrive::CdromDrive() : BlockStorageDevice(31, CDR_STD_DATA_SIZE, 0xfffffffe) {
EventManager::get_instance()->add_cdrom_handler(
this, &CdromDrive::insert_image_event_handler);
this->is_writeable = false;
}
void CdromDrive::insert_image_event_handler(CdromImageEvent& event) {
if (event.handled)
return;
if (this->medium_present()) {
event.result = CdromInsertionResult::MEDIA_PRESENT;
return;
}
event.handled = true;
if (this->insert_image(event.image_path)) {
this->media_change_pending = true;
event.result = CdromInsertionResult::SUCCESS;
} else {
event.result = CdromInsertionResult::IMAGE_OPEN_FAILED;
}
}
bool CdromDrive::consume_media_change() {
bool pending = this->media_change_pending;
this->media_change_pending = false;
return pending;
}
bool CdromDrive::insert_image(const std::string& filename) {
if (this->medium_present()) {
LOG_F(ERROR, "Cannot insert CD-ROM image while media is present");
return false;
}
if (!this->attach_image(filename)) {
LOG_F(ERROR, "Could not open CD-ROM image file, %s", filename.c_str());
return false;
}
void CdromDrive::insert_image(std::string filename) {
if (this->set_host_file(filename) < 0)
ABORT_F("Could not open CD-ROM image file, %s", filename.c_str());
this->detect_raw_image();
@@ -80,19 +47,6 @@ bool CdromDrive::insert_image(const std::string& filename) {
// create Lead-out descriptor containing all data
this->tracks[1] = {LEAD_OUT_TRK_NUM, /*.trk_num*/ 0x14, /*.adr_ctrl*/
static_cast<uint32_t>(this->size_blocks + 1) /*.start_lba*/};
return true;
}
bool CdromDrive::eject_image() {
if (!this->detach_image())
return false;
this->num_tracks = 0;
this->media_change_pending = false;
std::memset(this->tracks, 0, sizeof(this->tracks));
return true;
}
bool CdromDrive::detect_raw_image() {
@@ -118,6 +72,152 @@ bool CdromDrive::detect_raw_image() {
return false;
}
static char cdrom_vendor_dingus_id[] = "DINGUS ";
static char cdrom_product_id[] = "DINGUS CD-ROM ";
static char cdrom_revision_id[] = "1.0 ";
uint32_t CdromDrive::inquiry(uint8_t *cmd_ptr, uint8_t *data_ptr) {
int page_num = cmd_ptr[2];
int alloc_len = cmd_ptr[4];
if (page_num) {
ABORT_F("%s: invalid page number in INQUIRY", "CdromDrive");
}
if (alloc_len > 36) {
LOG_F(WARNING, "%s: more than 36 bytes requested in INQUIRY", "CdromDrive");
}
data_ptr[0] = 5; // device type: CD-ROM
data_ptr[1] = 0x80; // removable media
data_ptr[2] = 2; // ANSI version: SCSI-2
data_ptr[3] = 0x21; // ATAPI Version + response data format
data_ptr[4] = 0x1F; // additional length
data_ptr[5] = 0;
data_ptr[6] = 0;
data_ptr[7] = 0;
std::memcpy(&data_ptr[8], cdrom_vendor_dingus_id, 8);
std::memcpy(&data_ptr[16], cdrom_product_id, 16);
std::memcpy(&data_ptr[32], cdrom_revision_id, 4);
//std::memcpy(&data_ptr[36], serial_number, 8);
//etc.
if (alloc_len < 36) {
LOG_F(ERROR, "%s: allocation length too small: %d", "CdromDrive",
alloc_len);
}
else {
memset(&data_ptr[36], 0, alloc_len - 36);
}
return alloc_len;
}
uint32_t CdromDrive::mode_sense_ex(bool is_sense_6, uint8_t* cmd_ptr, uint8_t* data_ptr) {
uint8_t *resp_ptr;
uint8_t page_code = cmd_ptr[2] & 0x3F;
uint8_t alloc_len = is_sense_6 ? READ_WORD_BE_U(&cmd_ptr[4]) : READ_WORD_BE_U(&cmd_ptr[7]);
std::memset(data_ptr, 0, alloc_len);
data_ptr[0] = 0; // initial data size MSB
data_ptr[1] = 6; // initial data size LSB
data_ptr[2] = 1; // medium type: 120mm CD-ROM
data_ptr[3] = 0; // device-specific parameter
data_ptr[4] = 0;
data_ptr[5] = 0;
data_ptr[6] = 0; // block description length MSB
data_ptr[7] = 0; // block description length LSB
resp_ptr = data_ptr + 8;
resp_ptr[0] = page_code;
switch (page_code) {
case ModePage::ERROR_RECOVERY:
resp_ptr[1] = 6; // data size
std::memset(&resp_ptr[2], 0, 6);
data_ptr[1] += 8; // adjust overall length
break;
case ModePage::CDROM_AUDIO:
resp_ptr[1] = 16; // page length
std::memset(&resp_ptr[2], 0, 16);
resp_ptr[2] = (1 << 2); //immediately return status
WRITE_WORD_BE_A(&resp_ptr[6], 75); // logical block per second of audio playback
resp_ptr[8] = 0x01; // Left Channel
resp_ptr[9] = 0xFF; // Volume (0-255)
resp_ptr[10] = 0x02; // Right Channel
resp_ptr[11] = 0xFF; // Volume (0-255)
resp_ptr[12] = 0x04; // Output Port 2
resp_ptr[13] = 0x00; // Volume (0-255)
resp_ptr[14] = 0x08; // Output Port 3
resp_ptr[15] = 0x00; // Volume (0-255)
data_ptr[1] += 8; // adjust overall length
break;
case ModePage::POWER_CONDITION:
resp_ptr[1] = 10; // page length
std::memset(&resp_ptr[2], 0, 10);
resp_ptr[3] = 0; //idle and standby off
WRITE_DWORD_BE_A(&resp_ptr[4], 0); // Idle Timer (100ms units)
WRITE_DWORD_BE_A(&resp_ptr[8], 0); // Standby Timer (100ms units)
data_ptr[1] += 12; // adjust overall length
break;
case ModePage::CDROM_CAPABILITIES:
resp_ptr[1] = 18; // page data length
std::memset(&resp_ptr[2], 0, 18);
resp_ptr[2] = 0x03; // supports reading CD-R and CD-E
resp_ptr[3] = 0x00; // doesn't support writing to CD-R and CD-E
resp_ptr[6] = (1 << 5) | (1 << 3) | (1 << 0); // tray type + eject + lock support
WRITE_WORD_BE_A(&resp_ptr[ 8], 706); // report 4x speed
WRITE_WORD_BE_A(&resp_ptr[10], 2); // supports audio on/off only
WRITE_WORD_BE_A(&resp_ptr[12], 512); // 512Kb cache
WRITE_WORD_BE_A(&resp_ptr[14], 706); // report current speed (4x)
data_ptr[1] += 20; // adjust overall length
break;
case ModePage::VENDOR_PAGE_31:
resp_ptr[1] = 14; // page data length
std::memset(&resp_ptr[2], 0, 14);
resp_ptr[8] = 0x31;
resp_ptr[9] = 6;
resp_ptr[10] = '.';
resp_ptr[11] = 'A';
resp_ptr[12] = 'p';
resp_ptr[13] = 'p';
data_ptr[1] += 2; // adjust overall length
break;
default:
LOG_F(ERROR, "ATAPI CD-ROM: Invalid Page Code 0x%x", page_code);
this->set_error(ScsiSense::ILLEGAL_REQ, ScsiError::INVALID_CDB);
return 0;
}
return data_ptr[1] + 2; // return total response length
}
uint32_t CdromDrive::request_sense(uint8_t *data_ptr, uint8_t sense_key,
uint8_t asc, uint8_t ascq) {
std::memset(data_ptr, 0, 18);
data_ptr[ 0] = 0x80 | 0x70; // valid + current error
data_ptr[ 2] = sense_key;
data_ptr[ 7] = 10; // additional sense length
data_ptr[12] = asc;
data_ptr[13] = ascq;
return 18;
}
uint32_t CdromDrive::report_capacity(uint8_t *data_ptr) {
WRITE_DWORD_BE_A(data_ptr, static_cast<uint32_t>(this->size_blocks));
WRITE_DWORD_BE_A(&data_ptr[4], this->block_size);
return 8;
}
uint8_t CdromDrive::hex_to_bcd(const uint8_t val) {
uint8_t hi = val / 10;
uint8_t lo = val % 10;
@@ -130,3 +230,145 @@ AddrMsf CdromDrive::lba_to_msf(const int lba) {
hex_to_bcd( lba % 75) /*.frm*/
};
}
uint32_t CdromDrive::read_toc(uint8_t *cmd_ptr, uint8_t *data_ptr) {
int tot_tracks, data_len;
uint8_t start_track, session_num;
uint8_t* out_ptr;
uint16_t alloc_len = READ_WORD_BE_U(&cmd_ptr[7]);
bool is_msf = !!(cmd_ptr[1] & 2);
// ATAPI specific handling of the format field
uint8_t format = cmd_ptr[2] & 7;
if (!format) {
format = cmd_ptr[9] >> 6;
}
if (!alloc_len)
return 0;
switch(format) {
case 0: // Formatted TOC
start_track = cmd_ptr[6];
if (!start_track) { // special case: track zero (lead-in) as starting track
// return all tracks starting with track 1 plus lead-out
start_track = 1;
tot_tracks = this->num_tracks + 1;
} else if (start_track == LEAD_OUT_TRK_NUM) {
start_track = this->num_tracks + 1;
tot_tracks = 1;
} else if (start_track <= this->num_tracks) {
tot_tracks = (this->num_tracks - start_track) + 2;
} else {
LOG_F(ERROR, "CDROM: invalid starting track %d in READ_TOC", start_track);
this->set_error(ScsiSense::ILLEGAL_REQ, ScsiError::INVALID_CDB);
return 0;
}
out_ptr = data_ptr;
data_len = (tot_tracks * 8) + 4;
// write TOC data header
WRITE_WORD_BE_A(out_ptr, data_len - 2);
out_ptr[2] = 1; // 1st track number
out_ptr[3] = this->num_tracks; // last track number
out_ptr += 4;
for (int tx = 0; tx < tot_tracks; tx++) {
if ((out_ptr - data_ptr + 8) > alloc_len)
break; // exit the loop if the output buffer length is exhausted
TrackDescriptor& td = this->tracks[start_track + tx - 1];
*out_ptr++ = 0; // reserved
*out_ptr++ = td.adr_ctrl;
*out_ptr++ = td.trk_num;
*out_ptr++ = 0; // reserved
if (is_msf) {
AddrMsf msf = lba_to_msf(td.start_lba + 150);
*out_ptr++ = 0; // reserved
*out_ptr++ = msf.min;
*out_ptr++ = msf.sec;
*out_ptr++ = msf.frm;
} else {
WRITE_DWORD_BE_A(out_ptr, td.start_lba);
out_ptr += 4;
}
}
return alloc_len;
case 1: // Multi-session info
std::memset(data_ptr, 0, 12);
data_ptr[1] = 10; // TOC data length
data_ptr[2] = 1; // first session number
data_ptr[3] = 1; // last session number
data_ptr[5] = this->tracks[0].adr_ctrl;
data_ptr[6] = 1;
if (is_msf) {
AddrMsf msf = lba_to_msf(this->tracks[0].start_lba + 150);
data_ptr[ 8] = 0; // reserved
data_ptr[ 9] = msf.min;
data_ptr[10] = msf.sec;
data_ptr[11] = msf.frm;
}
return 12;
case 2: // Raw TOC
session_num = cmd_ptr[6];
if (!session_num)
session_num = 1;
if (session_num > 1) {
LOG_F(ERROR, "CDROM: invalid session number %d", session_num);
this->set_error(ScsiSense::ILLEGAL_REQ, ScsiError::INVALID_CDB);
return 0;
}
std::memset(data_ptr, 0, 48);
out_ptr = data_ptr;
// prepare data header
out_ptr[1] = 46; // TOC data length
out_ptr[2] = 1; // first session number
out_ptr[3] = 1; // last session number
out_ptr += 4;
// descriptor #1 -> first track
out_ptr[0] = session_num;
out_ptr[1] = this->tracks[0].adr_ctrl;
out_ptr[3] = 0xA0; // point -> first track
out_ptr[8] = 1; // first track number
out_ptr += 11;
// descriptor #2 -> last track
out_ptr[0] = session_num;
out_ptr[1] = this->tracks[0].adr_ctrl;
out_ptr[3] = 0xA1; // point -> last track
out_ptr[8] = 1; // last track number
out_ptr += 11;
// descriptor #3 -> lead-out
out_ptr[0] = session_num;
out_ptr[1] = this->tracks[0].adr_ctrl;
out_ptr[3] = 0xA2; // point -> lead-out
if (is_msf) {
AddrMsf msf = lba_to_msf(this->tracks[1].start_lba + 150);
out_ptr[ 7] = 0; // reserved
out_ptr[ 8] = msf.min;
out_ptr[ 9] = msf.sec;
out_ptr[10] = msf.frm;
} else {
WRITE_DWORD_BE_U(&out_ptr[7], this->tracks[1].start_lba);
}
out_ptr += 11;
// descriptor #4 -> data track
out_ptr[0] = session_num;
out_ptr[1] = this->tracks[0].adr_ctrl;
out_ptr[3] = 1; // point -> data track
if (is_msf) {
AddrMsf msf = lba_to_msf(this->tracks[0].start_lba + 150);
out_ptr[ 7] = 0; // reserved
out_ptr[ 8] = msf.min;
out_ptr[ 9] = msf.sec;
out_ptr[10] = msf.frm;
}
return 48;
default:
LOG_F(ERROR, "CDROM: unsupported format in READ_TOC");
this->set_error(ScsiSense::ILLEGAL_REQ, ScsiError::INVALID_CDB);
return 0;
}
}
+14 -52
View File
@@ -29,32 +29,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cinttypes>
#include <functional>
/** CD/DVD drive read/write capabilities. */
enum CdDriveCapabilities : uint8_t {
CDCAP_CDR_READ = 0x01,
CDCAP_CDE_READ = 0x02,
CDCAP_CDR_WRITE = 0x01,
CDCAP_CDE_WRITE = 0x02,
};
/** Support for various disk formats and outputs. */
enum CdDriveFormatSupport : uint8_t {
CDFMT_AUDIO_PLAY = 1 << 0,
CDFMT_COMPOSITE = 1 << 1,
CDFMT_PORT_1 = 1 << 2,
CDFMT_PORT_2 = 1 << 3,
CDFMT_MODE2_FORM1 = 1 << 4,
CDFMT_MODE2_FORM2 = 1 << 5,
CDFMT_MULTI_SESSION = 1 << 6,
};
/** Loading mechanism types. */
enum MechanismType : uint8_t {
LDTYPE_CADDY = 0,
LDTYPE_TRAY = 1,
LDTYPE_POPUP = 2,
};
/* Original CD-ROM addressing mode expressed
in minutes, seconds and frames */
typedef struct {
@@ -74,46 +48,34 @@ constexpr auto CDROM_MAX_TRACKS = 100;
constexpr auto LEAD_OUT_TRK_NUM = 0xAA;
constexpr auto CDR_STD_DATA_SIZE = 2048;
class CdromImageEvent;
class CdromDrive : public BlockStorageDevice {
public:
CdromDrive();
virtual ~CdromDrive() = default;
bool medium_present() const { return this->image_attached(); }
void set_error_callback(std::function<void(uint8_t, uint8_t)>&& err_cb) {
this->set_error = std::move(err_cb);
}
bool insert_image(const std::string& filename);
bool eject_image();
bool medium_present() { return this->is_ready; }
void insert_image(std::string filename);
virtual uint32_t inquiry(uint8_t *cmd_ptr, uint8_t *data_ptr);
virtual uint32_t mode_sense_ex(bool is_sense_6, uint8_t *cmd_ptr, uint8_t *data_ptr);
virtual uint32_t request_sense(uint8_t *data_ptr, uint8_t sense_key, uint8_t asc,
uint8_t ascq);
virtual uint32_t report_capacity(uint8_t *data_ptr);
virtual uint32_t read_toc(uint8_t *cmd_ptr, uint8_t *data_ptr);
protected:
void insert_image_event_handler(CdromImageEvent& event);
bool consume_media_change();
std::function<void(uint8_t, uint8_t)> set_error;
uint8_t hex_to_bcd(const uint8_t val);
AddrMsf lba_to_msf(const int lba);
bool detect_raw_image();
TrackDescriptor tracks[CDROM_MAX_TRACKS];
int num_tracks;
// drive capabilities
uint8_t read_cap = CdDriveCapabilities::CDCAP_CDE_READ |
CdDriveCapabilities::CDCAP_CDR_READ;
uint8_t write_cap = 0; // no write support
uint8_t fmt_support = 0;
uint8_t ext_support = 0;
uint8_t mech_type = MechanismType::LDTYPE_TRAY;
uint8_t sw_lock_sup = 1; // drive supports locking/unlocking via SW
uint8_t sw_eject_sup = 1; // drive supports ejecting via SW
uint8_t drive_locked = 0; // 1 - drive is currently locked
bool media_change_pending = false; // pending guest notification
uint8_t prevent_jump = 0; // prevent jumper not present
uint8_t more_support = 0;
uint16_t max_rd_speed = 706; // defaults to 4x
uint16_t max_vol_levs = 2; // audio can be only turned on and off
uint16_t cur_rd_speed = 706; // defaults to 4x
uint8_t dgt_out_desc = 0; // digital output format description
};
#endif // CD_ROM_DRIVE_H
+12 -26
View File
@@ -83,62 +83,48 @@ void AppleRamdac::iodev_write(uint32_t address, uint16_t value) {
(this->clut_color[1] << 8) | this->clut_color[2];
this->dac_addr++; // auto-increment CLUT address
this->comp_index = 0;
this->cursor_update_cb();
}
break;
case RamdacRegs::MULTI:
switch (this->dac_addr) {
case RamdacRegs::CURSOR_POS_HI:
#ifdef CURSOR_LO_DELAY // HACK: prevents artifacts in some cases, disabled by default
if (this->cursor_timer.active) {
TimerManager::get_instance()->cancel_timer(this->cursor_timer);
if (this->cursor_timer_id) {
TimerManager::get_instance()->cancel_timer(this->cursor_timer_id);
cursor_timer_id = 0;
}
this->cursor_xpos = (value << 8) | this->cursor_pos_lo;
#else
this->cursor_xpos = (value << 8) | (this->cursor_xpos & 0xff);
#endif
this->cursor_update_cb();
break;
case RamdacRegs::CURSOR_POS_LO:
#ifdef CURSOR_LO_DELAY // HACK: prevents artifacts in some cases, disabled by default
if (this->cursor_timer.active) {
TimerManager::get_instance()->cancel_timer(this->cursor_timer);
if (this->cursor_timer_id) {
TimerManager::get_instance()->cancel_timer(this->cursor_timer_id);
this->cursor_xpos = (this->cursor_xpos & 0xff00) | (this->cursor_pos_lo & 0x00ff);
cursor_timer_id = 0;
}
this->cursor_pos_lo = value;
TimerManager::get_instance()->add_oneshot_timer(this->cursor_timer,
NS_PER_SEC / 60, [this](uint64_t, uint64_t) {
this->cursor_pos_lo = value;
this->cursor_timer_id = TimerManager::get_instance()->add_oneshot_timer(
NS_PER_SEC / 60, [this]() {
this->cursor_xpos = (this->cursor_xpos & 0xff00) | (this->cursor_pos_lo & 0x00ff);
this->cursor_update_cb();
}
);
});
#else
this->cursor_xpos = (this->cursor_xpos & 0xff00) | (value & 0x00ff);
#endif
this->cursor_update_cb();
break;
case RamdacRegs::MISC_CTRL: {
case RamdacRegs::MISC_CTRL:
if (bit_changed(this->dac_cr, value, 1)) {
if (value & 2)
this->cursor_ctrl_cb(true);
else
this->cursor_ctrl_cb(false);
}
int old_pix_width = this->get_pix_width();
int old_clock_div = this->get_clock_div();
this->dac_cr = value;
int new_pix_width = this->get_pix_width();
if (old_pix_width != new_pix_width || old_clock_div != this->get_clock_div()) {
this->video_mode_ctrl_cb();
}
break;
}
case RamdacRegs::DBL_BUF_CTRL:
if (this->dbl_buf_cr != value) {
this->dbl_buf_cr = value;
if (this->buffer_update_cb)
this->buffer_update_cb();
}
this->dbl_buf_cr = value;
break;
case RamdacRegs::TEST_CTRL:
this->tst_cr = value;
+1 -5
View File
@@ -91,7 +91,6 @@ enum RamdacRegs : uint8_t {
typedef std::function<void(uint8_t index, uint8_t *colors)> GetClutEntryCallback;
typedef std::function<void(uint8_t index, uint8_t *colors)> SetClutEntryCallback;
typedef std::function<void(bool cursor_on)> CursorCtrlCallback;
typedef std::function<void()> VideoModeCtrlCallback;
class AppleRamdac : public HWComponent, public IobusDevice {
public:
@@ -118,9 +117,6 @@ public:
GetClutEntryCallback get_clut_entry_cb = nullptr;
SetClutEntryCallback set_clut_entry_cb = nullptr;
CursorCtrlCallback cursor_ctrl_cb = nullptr;
std::function<void()> cursor_update_cb = nullptr;
std::function<void()> buffer_update_cb = nullptr;
VideoModeCtrlCallback video_mode_ctrl_cb = nullptr;
protected:
DacFlavour flavour;
@@ -143,7 +139,7 @@ protected:
uint32_t fb_pitch = 0;
#ifdef CURSOR_LO_DELAY
uint8_t cursor_pos_lo = 0;
TimerInfo cursor_timer;
uint32_t cursor_timer_id = 0;
#endif
};
+11 -36
View File
@@ -41,19 +41,6 @@ enum {
ATI_PIX_FMT_ARGB8888 = 6,
};
/* Draw engine data-path values. */
enum {
ATI_DP_COLOR_SRC_BKGD_CLR = 0,
ATI_DP_COLOR_SRC_FRGD_CLR = 1,
ATI_DP_COLOR_SRC_HOST = 2,
ATI_DP_COLOR_SRC_BLIT = 3,
ATI_DP_MONO_SRC_ALWAYS_1 = 0,
ATI_DP_MIX_SRC = 7,
ATI_SRC_TRAJ_UNBOUNDED = 0,
ATI_SRC_TRAJ_PATTERN = 1,
ATI_SRC_TRAJ_ROTATED = 3,
};
/** Mach64 register offsets. */
enum {
ATI_CRTC_H_TOTAL_DISP = 0x000, // 0x0000
@@ -498,30 +485,22 @@ enum {
ATI_SRC_PITCH = 22, ATI_SRC_PITCH_size = 10,
ATI_SRC_X = 0x061, // 0x0184
ATI_SRC_X_pos = 0, ATI_SRC_X_size = 14,
ATI_SRC_X_pos = 0, ATI_SRC_X_size = 13,
ATI_SRC_Y = 0x062, // 0x0188
ATI_SRC_Y_pos = 0, ATI_SRC_Y_size = 15,
ATI_SRC_Y_X = 0x063, // 0x018C
ATI_SRC_WIDTH1 = 0x064, // 0x0190
ATI_SRC_WIDTH1_pos = 0, ATI_SRC_WIDTH1_size = 14,
ATI_SRC_HEIGHT1 = 0x065, // 0x0194
ATI_SRC_HEIGHT1_pos = 0, ATI_SRC_HEIGHT1_size = 15,
ATI_SRC_HEIGHT1_WIDTH1 = 0x066, // 0x0198
ATI_SRC_X_START = 0x067, // 0x019C
ATI_SRC_X_START_pos = 0, ATI_SRC_X_START_size = 14,
ATI_SRC_Y_START = 0x068, // 0x01A0
ATI_SRC_Y_START_pos = 0, ATI_SRC_Y_START_size = 15,
ATI_SRC_Y_X_START = 0x069, // 0x01A4
ATI_SRC_WIDTH2 = 0x06A, // 0x01A8
ATI_SRC_WIDTH2_pos = 0, ATI_SRC_WIDTH2_size = 14,
ATI_SRC_HEIGHT2 = 0x06B, // 0x01AC
ATI_SRC_HEIGHT2_pos = 0, ATI_SRC_HEIGHT2_size = 15,
ATI_SRC_HEIGHT2_WIDTH2 = 0x06C, // 0x01B0
ATI_SRC_CNTL = 0x06D, // 0x01B4
ATI_SRC_COLOR_REG_WRITE_EN = 13,
ATI_SRC_BLOCK_WRITE_EN = 14,
ATI_SCALE_OFF = 0x070, // 0x01C0
ATI_SCALE_WIDTH = 0x077, // 0x01DC
ATI_SCALE_HEIGHT = 0x078, // 0x01E0
@@ -530,8 +509,6 @@ enum {
ATI_SCALE_Y_INC = 0x07D, // 0x01F4
ATI_SCALE_VACC = 0x07E, // 0x01F8
ATI_SCALE_3D_CNTL = 0x07F, // 0x01FC
ATI_HOST_DATA0 = 0x080, // 0x0200
ATI_HOST_DATA15 = 0x08F, // 0x023C
ATI_HOST_CNTL = 0x090, // 0x0240
ATI_BM_HOSTDATA = 0x091, // 0x0244
ATI_BM_ADDR = 0x092, // 0x0248
@@ -543,10 +520,10 @@ enum {
ATI_PAT_CNTL = 0x0A2, // 0x0288
ATI_SC_LEFT = 0x0A8, // 0x02A0
ATI_SC_LEFT_pos = 0, ATI_SC_LEFT_size = 14,
ATI_SC_LEFT_pos = 0, ATI_SC_LEFT_size = 13,
ATI_SC_RIGHT = 0x0A9, // 0x02A4
ATI_SC_RIGHT_pos = 0, ATI_SC_RIGHT_size = 14,
ATI_SC_RIGHT_pos = 0, ATI_SC_RIGHT_size = 13,
ATI_SC_LEFT_RIGHT = 0x0AA, // 0x02A8
@@ -622,16 +599,14 @@ enum {
ATI_SRC_PATT_EN = 16, // VT/GT
ATI_SRC_PATT_ROT_EN = 17, // VT/GT
ATI_SRC_LINEAR_EN = 18, // VT/GT
ATI_SRC_BYTE_ALIGN = 19, // VT/GT
ATI_SRC_LINE_X_DIR = 20, // VT/GT
ATI_SRC_8x8x8_BRUSH = 21, // GT
ATI_FAST_FILL_EN = 22, // GT
ATI_SRC_TRACK_DST = 23, // VT/GT
ATI_PAT_MONO_EN = 24, // GT
ATI_PAT_CLR_4x2_EN = 25, // VT/GT
ATI_PAT_CLR_8x1_EN = 26, // VT/GT
ATI_HOST_BYTE_ALIGN = 28, // VT/GT
ATI_HOST_BIG_ENDIAN_EN = 29, // VT/GT
ATI_SRC_LINE_X_DIR = 19, // VT/GT
ATI_SRC_TRACK_DST = 20, // VT/GT
ATI_PAT_MONO_EN = 23, // GT
ATI_PAT_CLR_4x2_EN = 24, // VT/GT
ATI_PAT_CLR_8x1_EN = 25, // VT/GT
ATI_HOST_BYTE_ALIGN = 26, // VT/GT
ATI_HOST_BIG_ENDIAN_EN = 28, // VT/GT
ATI_SRC_BYTE_ALIGN = 29, // VT/GT
ATI_GUI_STAT = 0x0CE, // 0x0338
ATI_GUI_ACTIVE = 0,
+17 -20
View File
@@ -525,7 +525,6 @@ void AtiMach64Gx::write_reg(uint32_t reg_offset, uint32_t value, uint32_t size)
new_value = (old_value & bits_read_only) | (new_value & ~bits_read_only);
WRITE_VALUE_AND_LOG(ATIINTERRUPT);
this->update_interrupt();
return;
}
case ATI_CRTC_GEN_CNTL:
@@ -905,7 +904,7 @@ void AtiMach64Gx::get_cursor_position(int& x, int& y) {
int AtiMach64Gx::device_postinit()
{
this->vbl_cb = [this](uint8_t irq_line_state) {
insert_bits<uint32_t>(this->regs[ATI_CRTC_INT_CNTL], irq_line_state, ATI_CRTC_VBLANK, 1);
insert_bits<uint32_t>(this->regs[ATI_CRTC_INT_CNTL], irq_line_state, ATI_CRTC_VBLANK, irq_line_state);
if (irq_line_state) {
set_bit(this->regs[ATI_CRTC_INT_CNTL], ATI_CRTC_VBLANK_INT);
set_bit(this->regs[ATI_CRTC_INT_CNTL], ATI_CRTC_VLINE_INT);
@@ -915,28 +914,26 @@ int AtiMach64Gx::device_postinit()
#endif
}
this->update_interrupt();
bool do_interrupt =
bit_set(this->regs[ATI_CRTC_INT_CNTL], ATI_CRTC_VBLANK_INT_EN) ||
bit_set(this->regs[ATI_CRTC_INT_CNTL], ATI_CRTC_VLINE_INT_EN) ||
#if 1
#else
bit_set(this->regs[ATI_CRTC_GEN_CNTL], ATI_CRTC_VSYNC_INT_EN) ||
#endif
0;
LOG_F(ATIINTERRUPT, "%s: irq_line_state:%d do_interrupt:%d CRTC_INT_CNTL:%08x",
this->name.c_str(), irq_line_state, do_interrupt,
this->regs[ATI_CRTC_INT_CNTL]);
if (do_interrupt) {
this->pci_interrupt(irq_line_state);
}
};
return 0;
}
void AtiMach64Gx::update_interrupt()
{
uint32_t int_cntl = this->regs[ATI_CRTC_INT_CNTL];
bool new_pci_irq_line_state =
(bit_set(int_cntl, ATI_CRTC_VBLANK_INT_EN) &&
bit_set(int_cntl, ATI_CRTC_VBLANK_INT)) ||
(bit_set(int_cntl, ATI_CRTC_VLINE_INT_EN) &&
bit_set(int_cntl, ATI_CRTC_VLINE_INT));
if (new_pci_irq_line_state != this->pci_irq_line_state) {
this->pci_irq_line_state = new_pci_irq_line_state;
LOG_F(ATIINTERRUPT, "%s: pci_irq_line_state:%d CRTC_INT_CNTL:%08x",
this->name.c_str(), this->pci_irq_line_state, int_cntl);
this->pci_interrupt(this->pci_irq_line_state);
}
}
// ========================== IBM RGB514 related code ==========================
const char* AtiMach64Gx::rgb514_get_reg_name(uint32_t reg_addr)
{
-2
View File
@@ -76,10 +76,8 @@ protected:
private:
void change_one_bar(uint32_t &aperture, uint32_t aperture_size, uint32_t aperture_new, int bar_num);
void update_interrupt();
uint32_t regs[256] = {}; // internal registers
bool pci_irq_line_state = false;
int vram_size;
+54 -348
View File
@@ -37,28 +37,6 @@ static const int mach64_post_div[8] = {
3, 5, 6, 12 // alternate post dividers
};
static int32_t mach64_extract_signed(uint32_t value, int pos, int width) {
value = extract_bits<uint32_t>(value, pos, width);
return static_cast<int32_t>(value << (32 - width)) >> (32 - width);
}
static bool mach64_clip_axis(int coord, int increment, uint32_t length,
int scissor_min, int scissor_max,
int& skip, uint32_t& clipped_length) {
int first = increment > 0 ? scissor_min - coord : coord - scissor_max;
int last = increment > 0 ? scissor_max - coord : coord - scissor_min;
first = std::max(first, 0);
last = std::min(last, int(length) - 1);
if (first > last) {
return false;
}
skip = first;
clipped_length = last - first + 1;
return true;
}
/* Human readable Mach64 HW register names for easier debugging. */
static const std::map<uint16_t, std::string> mach64_reg_names = {
#define one_reg_name(x) {ATI_ ## x, #x}
@@ -288,13 +266,6 @@ uint32_t ATIRage::read_reg(uint32_t reg_offset, uint32_t size) {
case ATI_GUI_STAT:
result = uint64_t(this->cmd_fifo_size << 16); // HACK: pretend empty FIFO
break;
case ATI_GUI_TRAJ_CNTL:
result = 0;
insert_bits<uint64_t>(result, this->regs[ATI_DST_CNTL], 0, 16);
insert_bits<uint64_t>(result, this->regs[ATI_SRC_CNTL], 16, 8);
insert_bits<uint64_t>(result, this->regs[ATI_PAT_CNTL], 24, 3);
insert_bits<uint64_t>(result, this->regs[ATI_HOST_CNTL], 28, 2);
break;
case ATI_DP_BKGD_CLR:
case ATI_DP_FRGD_CLR:
uint32_t pix_fmt = extract_bits<uint32_t>(
@@ -349,11 +320,6 @@ void ATIRage::write_reg(uint32_t reg_offset, uint32_t value, uint32_t size) {
uint32_t old_value = this->regs[reg_num];
uint32_t new_value;
if (reg_num >= ATI_HOST_DATA0 && reg_num <= ATI_HOST_DATA15) {
this->write_host_data(value, size);
return;
}
if (offset || size != 4) { // slow path
if ((offset + size) > 4) {
ABORT_F("%s: unaligned DWORD writes not implemented", this->name.c_str());
@@ -443,9 +409,7 @@ void ATIRage::write_reg(uint32_t reg_offset, uint32_t value, uint32_t size) {
bits_read_only |= bits_not_AKed; // the not AKed bits will remain unchanged
new_value = (old_value & bits_read_only) | (new_value & ~bits_read_only);
WRITE_VALUE_AND_LOG(9);
this->update_interrupt();
return;
break;
}
case ATI_CRTC_GEN_CNTL:
new_value = value;
@@ -614,43 +578,12 @@ void ATIRage::write_reg(uint32_t reg_offset, uint32_t value, uint32_t size) {
break;
case ATI_SRC_HEIGHT1_WIDTH1:
new_value = value;
this->regs[ATI_SRC_HEIGHT1] = extract_bits<uint32_t>(value, 0, ATI_SRC_HEIGHT1_size);
this->regs[ATI_SRC_WIDTH1] = extract_bits<uint32_t>(value, 16, ATI_SRC_WIDTH1_size);
break;
case ATI_SRC_Y_X_START:
new_value = value;
this->regs[ATI_SRC_Y_START] = extract_bits<uint32_t>(value, 0, ATI_SRC_Y_START_size);
this->regs[ATI_SRC_X_START] = extract_bits<uint32_t>(value, 16, ATI_SRC_X_START_size);
break;
case ATI_SRC_HEIGHT2_WIDTH2:
new_value = value;
this->regs[ATI_SRC_HEIGHT2] = extract_bits<uint32_t>(value, 0, ATI_SRC_HEIGHT2_size);
this->regs[ATI_SRC_WIDTH2] = extract_bits<uint32_t>(value, 16, ATI_SRC_WIDTH2_size);
break;
case ATI_SC_LEFT_RIGHT:
new_value = value;
this->regs[ATI_SC_LEFT] = extract_bits<uint32_t>(value, 0, ATI_SC_LEFT_size);
this->regs[ATI_SC_RIGHT] = extract_bits<uint32_t>(value, 16, ATI_SC_RIGHT_size);
break;
case ATI_SC_TOP_BOTTOM:
new_value = value;
this->regs[ATI_SC_TOP] = extract_bits<uint32_t>(value, 0, ATI_SC_TOP_size);
this->regs[ATI_SC_BOTTOM] = extract_bits<uint32_t>(value, 16, ATI_SC_BOTTOM_size);
break;
case ATI_GUI_TRAJ_CNTL:
new_value = value;
insert_bits<uint32_t>(this->regs[ATI_DST_CNTL], value, 0, 16);
insert_bits<uint32_t>(this->regs[ATI_SRC_CNTL], value >> 16, 0, 8);
insert_bits<uint32_t>(this->regs[ATI_PAT_CNTL], value >> 24, 0, 3);
insert_bits<uint32_t>(this->regs[ATI_HOST_CNTL], value >> 28, 0, 2);
this->regs[ATI_SRC_HEIGHT1] = extract_bits<uint32_t>(value, 0, 16);
this->regs[ATI_SRC_WIDTH1] = extract_bits<uint32_t>(value, 16, 16);
break;
case ATI_DST_WIDTH:
case ATI_DST_HEIGHT_WIDTH:
case ATI_DST_X_WIDTH:
case ATI_DST_WIDTH_HEIGHT:
this->begin_drawing(reg_num, value);
new_value = this->regs[reg_num];
break;
case ATI_DST_BRES_LNTH:
this->begin_drawing(reg_num, value);
break;
@@ -1035,7 +968,7 @@ void ATIRage::get_cursor_position(int& x, int& y) {
int ATIRage::device_postinit()
{
this->vbl_cb = [this](uint8_t irq_line_state) {
insert_bits<uint32_t>(this->regs[ATI_CRTC_INT_CNTL], irq_line_state, ATI_CRTC_VBLANK, 1);
insert_bits<uint32_t>(this->regs[ATI_CRTC_INT_CNTL], irq_line_state, ATI_CRTC_VBLANK, irq_line_state);
if (irq_line_state) {
set_bit(this->regs[ATI_CRTC_INT_CNTL], ATI_CRTC_VBLANK_INT);
set_bit(this->regs[ATI_CRTC_INT_CNTL], ATI_CRTC_VLINE_INT);
@@ -1045,69 +978,29 @@ int ATIRage::device_postinit()
#endif
}
this->update_interrupt();
bool do_interrupt =
bit_set(this->regs[ATI_CRTC_INT_CNTL], ATI_CRTC_VBLANK_INT_EN) ||
bit_set(this->regs[ATI_CRTC_INT_CNTL], ATI_CRTC_VLINE_INT_EN) ||
#if 1
#else
bit_set(this->regs[ATI_CRTC_GEN_CNTL], ATI_CRTC_VSYNC_INT_EN) ||
#endif
0;
if (do_interrupt) {
this->pci_interrupt(irq_line_state);
}
};
return 0;
}
void ATIRage::update_interrupt()
{
uint32_t int_cntl = this->regs[ATI_CRTC_INT_CNTL];
bool new_pci_irq_line_state =
(bit_set(int_cntl, ATI_CRTC_VBLANK_INT_EN) &&
bit_set(int_cntl, ATI_CRTC_VBLANK_INT)) ||
(bit_set(int_cntl, ATI_CRTC_VLINE_INT_EN) &&
bit_set(int_cntl, ATI_CRTC_VLINE_INT));
if (new_pci_irq_line_state != this->pci_irq_line_state) {
this->pci_irq_line_state = new_pci_irq_line_state;
this->pci_interrupt(this->pci_irq_line_state);
}
}
// =================================== Draw Engine =====================================
void ATIRage::begin_drawing(uint32_t initiator, uint32_t value) {
switch(initiator) {
case ATI_DST_WIDTH: {
uint32_t width = extract_bits<uint32_t>(value, ATI_DST_WIDTH_pos, ATI_DST_WIDTH_size);
this->regs[ATI_DST_WIDTH] = width;
if (!bit_set(value, DST_WIDTH_FILL_DIS)) {
this->draw_rect(
width,
extract_bits<uint32_t>(
this->regs[ATI_DST_HEIGHT], ATI_DST_HEIGHT_pos, ATI_DST_HEIGHT_size));
}
break;
}
case ATI_DST_HEIGHT_WIDTH: {
uint32_t width = extract_bits<uint32_t>(value, 16, ATI_DST_WIDTH_size);
uint32_t height = extract_bits<uint32_t>(value, 0, ATI_DST_HEIGHT_size);
case ATI_DST_HEIGHT_WIDTH:
this->regs[ATI_DST_HEIGHT_WIDTH] = value;
this->regs[ATI_DST_WIDTH] = width;
this->regs[ATI_DST_HEIGHT] = height;
this->draw_rect(width, height);
this->draw_rect(extract_bits<uint32_t>(value, 16, 14), extract_bits<uint32_t>(value, 0, 15));
break;
}
case ATI_DST_X_WIDTH: {
uint32_t width = extract_bits<uint32_t>(value, 16, ATI_DST_WIDTH_size);
this->regs[ATI_DST_X_WIDTH] = value;
this->regs[ATI_DST_X] = extract_bits<uint32_t>(value, 0, ATI_DST_X_size);
this->regs[ATI_DST_WIDTH] = width;
this->draw_rect(
width,
extract_bits<uint32_t>(
this->regs[ATI_DST_HEIGHT], ATI_DST_HEIGHT_pos, ATI_DST_HEIGHT_size));
break;
}
case ATI_DST_WIDTH_HEIGHT: {
uint32_t width = extract_bits<uint32_t>(value, 0, ATI_DST_WIDTH_size);
uint32_t height = extract_bits<uint32_t>(value, 16, ATI_DST_HEIGHT_size);
this->regs[ATI_DST_WIDTH_HEIGHT] = value;
this->regs[ATI_DST_WIDTH] = width;
this->regs[ATI_DST_HEIGHT] = height;
this->draw_rect(width, height);
break;
}
default:
LOG_F(WARNING, "%s: unimplemented engine operation, initiator=0x%X", this->name.c_str(),
initiator);
@@ -1115,34 +1008,14 @@ void ATIRage::begin_drawing(uint32_t initiator, uint32_t value) {
}
void ATIRage::draw_rect(uint32_t width, uint32_t height) {
uint8_t frgd_src = extract_bits<uint32_t>(
this->regs[ATI_DP_SRC], ATI_DP_FRGD_SRC, ATI_DP_FRGD_SRC_size);
uint8_t mono_src = extract_bits<uint32_t>(
this->regs[ATI_DP_SRC], ATI_DP_MONO_SRC, ATI_DP_MONO_SRC_size);
uint32_t src_cntl = this->regs[ATI_SRC_CNTL];
uint8_t frgd_src = extract_bits<uint32_t>(this->regs[ATI_DP_SRC], ATI_DP_FRGD_SRC, ATI_DP_FRGD_SRC_size);
uint8_t bkgd_src = extract_bits<uint32_t>(this->regs[ATI_DP_SRC], ATI_DP_BKGD_SRC, ATI_DP_BKGD_SRC_size);
uint8_t mono_src = extract_bits<uint32_t>(this->regs[ATI_DP_SRC], ATI_DP_MONO_SRC, ATI_DP_MONO_SRC_size);
this->host_data_active = false;
// Color register blits update SGRAM state rather than VRAM.
if (bit_set(src_cntl, ATI_SRC_COLOR_REG_WRITE_EN) &&
!bit_set(src_cntl, ATI_SRC_BLOCK_WRITE_EN)) {
this->finish_rect(width, height);
return;
}
if ((frgd_src == ATI_DP_COLOR_SRC_BKGD_CLR || frgd_src == ATI_DP_COLOR_SRC_FRGD_CLR) &&
mono_src == ATI_DP_MONO_SRC_ALWAYS_1) {
uint32_t color = frgd_src == ATI_DP_COLOR_SRC_BKGD_CLR ? this->regs[ATI_DP_BKGD_CLR]
: this->regs[ATI_DP_FRGD_CLR];
this->fill_rect(width, height, color);
this->finish_rect(width, height);
} else if (frgd_src == ATI_DP_COLOR_SRC_HOST &&
mono_src == ATI_DP_MONO_SRC_ALWAYS_1) {
this->start_host_rect(width, height);
} else if (frgd_src == ATI_DP_COLOR_SRC_BLIT &&
mono_src == ATI_DP_MONO_SRC_ALWAYS_1) {
if (frgd_src == 1 && !mono_src) { // rectangle fill with foreground color
this->fill_rect(width, height);
} else if (frgd_src == 3 && !mono_src) { // rectangle copy from the blit source
this->blit_rect(width, height);
this->finish_rect(width, height);
} else {
LOG_F(WARNING, "%s: unimplemented rectangle draw op, DP_SRC=0x%08X, DP_MIX=0x%08X, "
"DP_PIX_WIDTH=0x%08X, SRC_CNTL=0x%08X", this->name.c_str(),
@@ -1151,29 +1024,14 @@ void ATIRage::draw_rect(uint32_t width, uint32_t height) {
}
}
void ATIRage::finish_rect(uint32_t width, uint32_t height) {
int dst_x = mach64_extract_signed(this->regs[ATI_DST_X], ATI_DST_X_pos, ATI_DST_X_size);
int dst_y = mach64_extract_signed(this->regs[ATI_DST_Y], ATI_DST_Y_pos, ATI_DST_Y_size);
int x_delta = int(width);
int y_delta = int(height);
void ATIRage::fill_rect(uint32_t dst_width, uint32_t dst_height) {
uint8_t frgd_mix = extract_bits<uint32_t>(this->regs[ATI_DP_MIX], ATI_DP_FRGD_MIX, ATI_DP_FRGD_MIX_size);
uint8_t bkgd_mix = extract_bits<uint32_t>(this->regs[ATI_DP_MIX], ATI_DP_BKGD_MIX, ATI_DP_BKGD_MIX_size);
if (bit_set(this->regs[ATI_DST_CNTL], ATI_DST_X_TILE)) {
dst_x += bit_set(this->regs[ATI_DST_CNTL], ATI_DST_X_DIR) ? x_delta : -x_delta;
insert_bits<uint32_t>(this->regs[ATI_DST_X], dst_x, ATI_DST_X_pos, ATI_DST_X_size);
}
if (bit_set(this->regs[ATI_DST_CNTL], ATI_DST_Y_TILE)) {
dst_y += bit_set(this->regs[ATI_DST_CNTL], ATI_DST_Y_DIR) ? y_delta : -y_delta;
insert_bits<uint32_t>(this->regs[ATI_DST_Y], dst_y, ATI_DST_Y_pos, ATI_DST_Y_size);
}
}
void ATIRage::fill_rect(uint32_t dst_width, uint32_t dst_height, uint32_t color) {
uint8_t frgd_mix = extract_bits<uint32_t>(this->regs[ATI_DP_MIX], ATI_DP_FRGD_MIX,
ATI_DP_FRGD_MIX_size);
if (frgd_mix != ATI_DP_MIX_SRC) {
LOG_F(WARNING, "%s: unimplemented rectangle fill op, DP_FRGD_MIX=0x%X",
this->name.c_str(), frgd_mix);
// check for non-trivial operations
if (frgd_mix != 7 || bkgd_mix != 3) {
LOG_F(WARNING, "%s: unimplemented rectangle fill op, DP_FRGD_MIX=0x%X, DP_BKGD_MIX=0x%X",
this->name.c_str(), frgd_mix, bkgd_mix);
return;
}
@@ -1219,31 +1077,16 @@ void ATIRage::fill_rect(uint32_t dst_width, uint32_t dst_height, uint32_t color)
// grab trajectory params
int dst_offs = extract_bits<uint32_t>(this->regs[ATI_DST_OFF_PITCH], ATI_DST_OFFSET, ATI_DST_OFFSET_size);
int dst_pitch = extract_bits<uint32_t>(this->regs[ATI_DST_OFF_PITCH], ATI_DST_PITCH, ATI_DST_PITCH_size);
int dst_x = mach64_extract_signed(this->regs[ATI_DST_X], ATI_DST_X_pos, ATI_DST_X_size);
int dst_y = mach64_extract_signed(this->regs[ATI_DST_Y], ATI_DST_Y_pos, ATI_DST_Y_size);
int dst_x = extract_bits<uint32_t>(this->regs[ATI_DST_X], ATI_DST_X_pos, ATI_DST_X_size);
int dst_y = extract_bits<uint32_t>(this->regs[ATI_DST_Y], ATI_DST_Y_pos, ATI_DST_Y_size);
dst_offs *= 8;
dst_pitch *= 8 * bytes_per_pixel;
int x_inc = bit_set(this->regs[ATI_DST_CNTL], ATI_DST_X_DIR) ? 1 : -1;
int y_inc = bit_set(this->regs[ATI_DST_CNTL], ATI_DST_Y_DIR) ? 1 : -1;
int x_inc = (this->regs[ATI_DST_CNTL] & 1) ? 1 : -1;
int y_inc = (this->regs[ATI_DST_CNTL] & 2) ? 1 : -1;
int sc_left = mach64_extract_signed(this->regs[ATI_SC_LEFT], ATI_SC_LEFT_pos, ATI_SC_LEFT_size);
int sc_right = mach64_extract_signed(
this->regs[ATI_SC_RIGHT], ATI_SC_RIGHT_pos, ATI_SC_RIGHT_size);
int sc_top = mach64_extract_signed(this->regs[ATI_SC_TOP], ATI_SC_TOP_pos, ATI_SC_TOP_size);
int sc_bottom = mach64_extract_signed(
this->regs[ATI_SC_BOTTOM], ATI_SC_BOTTOM_pos, ATI_SC_BOTTOM_size);
int x_skip, y_skip;
if (!mach64_clip_axis(dst_x, x_inc, dst_width, sc_left, sc_right, x_skip, dst_width) ||
!mach64_clip_axis(dst_y, y_inc, dst_height, sc_top, sc_bottom, y_skip, dst_height)) {
return;
}
dst_x += x_skip * x_inc;
dst_y += y_skip * y_inc;
uint32_t pix = color & this->regs[ATI_DP_WRITE_MSK];
uint32_t pix = this->regs[ATI_DP_FRGD_CLR] & this->regs[ATI_DP_WRITE_MSK];
switch (dst_pix_fmt) {
case ATI_PIX_FMT_8BPP:
@@ -1297,74 +1140,6 @@ void ATIRage::fill_rect(uint32_t dst_width, uint32_t dst_height, uint32_t color)
this->draw_fb = true;
}
void ATIRage::start_host_rect(uint32_t dst_width, uint32_t dst_height) {
uint8_t frgd_mix = extract_bits<uint32_t>(this->regs[ATI_DP_MIX], ATI_DP_FRGD_MIX,
ATI_DP_FRGD_MIX_size);
uint8_t host_pix_fmt = extract_bits<uint32_t>(this->regs[ATI_DP_PIX_WIDTH], ATI_DP_HOST_PIX_WIDTH,
ATI_DP_HOST_PIX_WIDTH_size);
uint8_t dst_pix_fmt = extract_bits<uint32_t>(this->regs[ATI_DP_PIX_WIDTH], ATI_DP_DST_PIX_WIDTH,
ATI_DP_DST_PIX_WIDTH_size);
if (frgd_mix != ATI_DP_MIX_SRC || host_pix_fmt != ATI_PIX_FMT_8BPP ||
dst_pix_fmt != ATI_PIX_FMT_8BPP || this->regs[ATI_CLR_CMP_CNTL]) {
LOG_F(WARNING, "%s: unsupported color host rectangle, DP_MIX=0x%08X, "
"DP_PIX_WIDTH=0x%08X, CLR_CMP_CNTL=0x%08X", this->name.c_str(),
this->regs[ATI_DP_MIX], this->regs[ATI_DP_PIX_WIDTH],
this->regs[ATI_CLR_CMP_CNTL]);
return;
}
this->host_dst_width = dst_width;
this->host_dst_height = dst_height;
this->host_dst_col = 0;
this->host_dst_row = 0;
this->host_data_active = true;
}
void ATIRage::write_host_data(uint32_t value, uint32_t size) {
if (!this->host_data_active) {
return;
}
int dst_offs = extract_bits<uint32_t>(
this->regs[ATI_DST_OFF_PITCH], ATI_DST_OFFSET, ATI_DST_OFFSET_size) *
8;
int dst_pitch =
extract_bits<uint32_t>(this->regs[ATI_DST_OFF_PITCH], ATI_DST_PITCH, ATI_DST_PITCH_size) * 8;
int dst_x = mach64_extract_signed(this->regs[ATI_DST_X], ATI_DST_X_pos, ATI_DST_X_size);
int dst_y = mach64_extract_signed(this->regs[ATI_DST_Y], ATI_DST_Y_pos, ATI_DST_Y_size);
int sc_left = mach64_extract_signed(this->regs[ATI_SC_LEFT], ATI_SC_LEFT_pos, ATI_SC_LEFT_size);
int sc_right = mach64_extract_signed(
this->regs[ATI_SC_RIGHT], ATI_SC_RIGHT_pos, ATI_SC_RIGHT_size);
int sc_top = mach64_extract_signed(this->regs[ATI_SC_TOP], ATI_SC_TOP_pos, ATI_SC_TOP_size);
int sc_bottom = mach64_extract_signed(
this->regs[ATI_SC_BOTTOM], ATI_SC_BOTTOM_pos, ATI_SC_BOTTOM_size);
int x_inc = bit_set(this->regs[ATI_DST_CNTL], ATI_DST_X_DIR) ? 1 : -1;
int y_inc = bit_set(this->regs[ATI_DST_CNTL], ATI_DST_Y_DIR) ? 1 : -1;
uint8_t write_mask = this->regs[ATI_DP_WRITE_MSK];
for (uint32_t byte = 0; byte < size && this->host_data_active; byte++) {
int shift = x_inc > 0 ? int(byte) * 8 : int(size - byte - 1) * 8;
uint8_t pixel = value >> shift;
int x = dst_x + int(this->host_dst_col) * x_inc;
int y = dst_y + int(this->host_dst_row) * y_inc;
if (x >= sc_left && x <= sc_right && y >= sc_top && y <= sc_bottom) {
uint8_t* dst = &this->vram_ptr[dst_offs + y * dst_pitch + x];
*dst = (*dst & ~write_mask) | (pixel & write_mask);
this->draw_fb = true;
}
if (++this->host_dst_col >= this->host_dst_width) {
this->host_dst_col = 0;
if (++this->host_dst_row >= this->host_dst_height) {
this->host_data_active = false;
this->finish_rect(this->host_dst_width, this->host_dst_height);
}
}
}
}
void ATIRage::blit_rect(uint32_t dst_width, uint32_t dst_height) {
uint8_t frgd_mix = extract_bits<uint32_t>(this->regs[ATI_DP_MIX], ATI_DP_FRGD_MIX,
ATI_DP_FRGD_MIX_size);
@@ -1393,11 +1168,7 @@ void ATIRage::blit_rect(uint32_t dst_width, uint32_t dst_height) {
uint32_t pixel_mask = bytes_per_pixel == 4 ? 0xFFFFFFFFU :
((1U << (bytes_per_pixel * 8)) - 1);
uint32_t src_cntl = this->regs[ATI_SRC_CNTL];
bool supported_src_trajectory = src_cntl == ATI_SRC_TRAJ_UNBOUNDED ||
src_cntl == ATI_SRC_TRAJ_PATTERN || src_cntl == ATI_SRC_TRAJ_ROTATED;
if (frgd_mix != ATI_DP_MIX_SRC || !supported_src_trajectory || this->regs[ATI_CLR_CMP_CNTL] ||
if (frgd_mix != 7 || this->regs[ATI_SRC_CNTL] || this->regs[ATI_CLR_CMP_CNTL] ||
src_pix_fmt != dst_pix_fmt || !bytes_per_pixel ||
(this->regs[ATI_DP_WRITE_MSK] & pixel_mask) != pixel_mask) {
LOG_F(WARNING, "%s: unsupported rectangle blit, DP_SRC=0x%08X, DP_MIX=0x%08X, "
@@ -1408,92 +1179,27 @@ void ATIRage::blit_rect(uint32_t dst_width, uint32_t dst_height) {
return;
}
int src_offs = extract_bits<uint32_t>(
this->regs[ATI_SRC_OFF_PITCH], ATI_SRC_OFFSET, ATI_SRC_OFFSET_size) *
8;
int src_pitch = extract_bits<uint32_t>(
this->regs[ATI_SRC_OFF_PITCH], ATI_SRC_PITCH, ATI_SRC_PITCH_size) *
8 * bytes_per_pixel;
int src_x = mach64_extract_signed(this->regs[ATI_SRC_X], ATI_SRC_X_pos, ATI_SRC_X_size);
int src_y = mach64_extract_signed(this->regs[ATI_SRC_Y], ATI_SRC_Y_pos, ATI_SRC_Y_size);
int src_x_start = mach64_extract_signed(
this->regs[ATI_SRC_X_START], ATI_SRC_X_START_pos, ATI_SRC_X_START_size);
int src_y_start = mach64_extract_signed(
this->regs[ATI_SRC_Y_START], ATI_SRC_Y_START_pos, ATI_SRC_Y_START_size);
uint32_t src_width1 = extract_bits<uint32_t>(
this->regs[ATI_SRC_WIDTH1], ATI_SRC_WIDTH1_pos, ATI_SRC_WIDTH1_size);
uint32_t src_height1 = extract_bits<uint32_t>(
this->regs[ATI_SRC_HEIGHT1], ATI_SRC_HEIGHT1_pos, ATI_SRC_HEIGHT1_size);
uint32_t src_width2 = extract_bits<uint32_t>(
this->regs[ATI_SRC_WIDTH2], ATI_SRC_WIDTH2_pos, ATI_SRC_WIDTH2_size);
uint32_t src_height2 = extract_bits<uint32_t>(
this->regs[ATI_SRC_HEIGHT2], ATI_SRC_HEIGHT2_pos, ATI_SRC_HEIGHT2_size);
int src_offs = extract_bits<uint32_t>(this->regs[ATI_SRC_OFF_PITCH], ATI_SRC_OFFSET,
ATI_SRC_OFFSET_size) * 8;
int src_pitch = extract_bits<uint32_t>(this->regs[ATI_SRC_OFF_PITCH], ATI_SRC_PITCH,
ATI_SRC_PITCH_size) * 8 * bytes_per_pixel;
int src_x = extract_bits<uint32_t>(this->regs[ATI_SRC_X], ATI_SRC_X_pos, ATI_SRC_X_size);
int src_y = extract_bits<uint32_t>(this->regs[ATI_SRC_Y], ATI_SRC_Y_pos, ATI_SRC_Y_size);
if ((src_cntl == ATI_SRC_TRAJ_PATTERN && (!src_width1 || !src_height1)) ||
(src_cntl == ATI_SRC_TRAJ_ROTATED &&
(!src_width1 || !src_height1 || !src_width2 || !src_height2))) {
LOG_F(WARNING, "%s: invalid rectangle blit source trajectory, SRC_CNTL=0x%08X, "
"SRC_HEIGHT1_WIDTH1=0x%08X, SRC_HEIGHT2_WIDTH2=0x%08X", this->name.c_str(),
src_cntl, this->regs[ATI_SRC_HEIGHT1_WIDTH1],
this->regs[ATI_SRC_HEIGHT2_WIDTH2]);
return;
}
int dst_offs = extract_bits<uint32_t>(this->regs[ATI_DST_OFF_PITCH], ATI_DST_OFFSET,
ATI_DST_OFFSET_size) * 8;
int dst_pitch = extract_bits<uint32_t>(this->regs[ATI_DST_OFF_PITCH], ATI_DST_PITCH,
ATI_DST_PITCH_size) * 8 * bytes_per_pixel;
int dst_x = extract_bits<uint32_t>(this->regs[ATI_DST_X], ATI_DST_X_pos, ATI_DST_X_size);
int dst_y = extract_bits<uint32_t>(this->regs[ATI_DST_Y], ATI_DST_Y_pos, ATI_DST_Y_size);
int dst_offs = extract_bits<uint32_t>(
this->regs[ATI_DST_OFF_PITCH], ATI_DST_OFFSET, ATI_DST_OFFSET_size) *
8;
int dst_pitch = extract_bits<uint32_t>(
this->regs[ATI_DST_OFF_PITCH], ATI_DST_PITCH, ATI_DST_PITCH_size) *
8 * bytes_per_pixel;
int dst_x = mach64_extract_signed(this->regs[ATI_DST_X], ATI_DST_X_pos, ATI_DST_X_size);
int dst_y = mach64_extract_signed(this->regs[ATI_DST_Y], ATI_DST_Y_pos, ATI_DST_Y_size);
int x_inc = bit_set(this->regs[ATI_DST_CNTL], ATI_DST_X_DIR) ? 1 : -1;
int y_inc = bit_set(this->regs[ATI_DST_CNTL], ATI_DST_Y_DIR) ? 1 : -1;
int sc_left = mach64_extract_signed(this->regs[ATI_SC_LEFT], ATI_SC_LEFT_pos, ATI_SC_LEFT_size);
int sc_right = mach64_extract_signed(
this->regs[ATI_SC_RIGHT], ATI_SC_RIGHT_pos, ATI_SC_RIGHT_size);
int sc_top = mach64_extract_signed(this->regs[ATI_SC_TOP], ATI_SC_TOP_pos, ATI_SC_TOP_size);
int sc_bottom = mach64_extract_signed(
this->regs[ATI_SC_BOTTOM], ATI_SC_BOTTOM_pos, ATI_SC_BOTTOM_size);
int x_skip, y_skip;
if (!mach64_clip_axis(dst_x, x_inc, dst_width, sc_left, sc_right, x_skip, dst_width) ||
!mach64_clip_axis(dst_y, y_inc, dst_height, sc_top, sc_bottom, y_skip, dst_height)) {
return;
}
dst_x += x_skip * x_inc;
dst_y += y_skip * y_inc;
int x_inc = (this->regs[ATI_DST_CNTL] & 1) ? 1 : -1;
int y_inc = (this->regs[ATI_DST_CNTL] & 2) ? 1 : -1;
for (uint32_t y = 0; y < dst_height; y++) {
uint32_t src_row_index = y_skip + y;
int sy;
if (src_cntl == ATI_SRC_TRAJ_PATTERN) {
sy = src_y + int(src_row_index % src_height1) * y_inc;
} else if (src_cntl == ATI_SRC_TRAJ_ROTATED && src_row_index >= src_height1) {
sy = src_y_start + int((src_row_index - src_height1) % src_height2) * y_inc;
} else {
sy = src_y + int(src_row_index) * y_inc;
}
uint8_t* src_row = &this->vram_ptr[src_offs + sy * src_pitch];
int dy = dst_y + int(y) * y_inc;
uint8_t* dst_row = &this->vram_ptr[dst_offs + dy * dst_pitch];
for (uint32_t x = 0; x < dst_width; x++) {
uint32_t src_col_index = x_skip + x;
int sx;
if (src_cntl == ATI_SRC_TRAJ_PATTERN) {
sx = src_x + int(src_col_index % src_width1) * x_inc;
} else if (src_cntl == ATI_SRC_TRAJ_ROTATED && src_row_index > 0) {
sx = src_x_start + int(src_col_index % src_width2) * x_inc;
} else if (src_cntl == ATI_SRC_TRAJ_ROTATED && src_col_index >= src_width1) {
sx = src_x_start + int((src_col_index - src_width1) % src_width2) * x_inc;
} else {
sx = src_x + int(src_col_index) * x_inc;
}
int dx = dst_x + int(x) * x_inc;
uint8_t* src_row = &this->vram_ptr[src_offs + (src_y + int(y) * y_inc) * src_pitch];
uint8_t* dst_row = &this->vram_ptr[dst_offs + (dst_y + int(y) * y_inc) * dst_pitch];
for (int sx = src_x, dx = dst_x, width = dst_width; width-- > 0; sx += x_inc, dx += x_inc) {
uint8_t* src_pixel = &src_row[sx * bytes_per_pixel];
uint8_t* dst_pixel = &dst_row[dx * bytes_per_pixel];
for (int byte = 0; byte < bytes_per_pixel; byte++) {
+1 -12
View File
@@ -89,27 +89,16 @@ protected:
private:
void change_one_bar(uint32_t &aperture, uint32_t aperture_size,
uint32_t aperture_new, int bar_num);
void update_interrupt();
void begin_drawing(uint32_t initiator, uint32_t value);
void draw_rect(uint32_t width, uint32_t height);
void finish_rect(uint32_t width, uint32_t height);
void fill_rect(uint32_t dst_width, uint32_t dst_height, uint32_t color);
void fill_rect(uint32_t dst_width, uint32_t dst_height);
void blit_rect(uint32_t dst_width, uint32_t dst_height);
void start_host_rect(uint32_t dst_width, uint32_t dst_height);
void write_host_data(uint32_t value, uint32_t size);
uint32_t regs[512] = {}; // internal registers
uint8_t plls[64] = {}; // internal PLL registers
uint8_t cmd_fifo_size = 0;
bool pci_irq_line_state = false;
bool host_data_active = false;
uint32_t host_dst_width = 0;
uint32_t host_dst_height = 0;
uint32_t host_dst_col = 0;
uint32_t host_dst_row = 0;
// Video RAM variables
std::unique_ptr<uint8_t[]> vram_ptr;
+51 -143
View File
@@ -48,10 +48,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cinttypes>
// Big-endian VRAM aperture select bit; clear for the little-endian aperture.
// See Apple patent US5793996A, cols. 17-18.
constexpr uint32_t VRAM_BE_APERTURE = 0x800000;
namespace loguru {
enum : Verbosity {
Verbosity_RADACAL = loguru::Verbosity_INFO,
@@ -122,10 +118,8 @@ ControlVideo::ControlVideo()
};
this->radacal->set_clut_entry_cb = [this](uint8_t index, uint8_t *colors) {
this->set_palette_color(index, colors[0], colors[1], colors[2], 0xFF);
this->draw_fb = true;
};
this->radacal->cursor_ctrl_cb = [this](bool cursor_on) {
this->draw_fb = true;
if (cursor_on) {
this->radacal->measure_hw_cursor(this->fb_ptr - 16);
this->cursor_ovl_cb = [this](uint8_t *dst_buf, int dst_pitch) {
@@ -136,20 +130,6 @@ ControlVideo::ControlVideo()
this->cursor_ovl_cb = nullptr;
}
};
this->radacal->cursor_update_cb = [this]() {
this->draw_fb = true;
};
this->radacal->buffer_update_cb = [this]() {
this->draw_fb = true;
if (this->display_enabled) {
this->update_fb_ptr();
}
};
this->radacal->video_mode_ctrl_cb = [this]() {
if (this->display_enabled) {
this->enable_display();
}
};
// attach IOBus Device #2 0xF301B000 ; register RaDACal with the I/O controller
GrandCentral* gc_obj = dynamic_cast<GrandCentral*>(gMachineObj->get_comp_by_name("GrandCentralTnt"));
@@ -157,8 +137,6 @@ ControlVideo::ControlVideo()
// initialize display identification
this->display_id = std::unique_ptr<DisplayID> (new DisplayID());
this->draw_fb_is_dynamic = true;
}
void ControlVideo::change_one_bar(uint32_t &aperture, uint32_t aperture_size, uint32_t aperture_new, int bar_num) {
@@ -238,7 +216,7 @@ static const char * get_name_controlreg(int offset) {
uint32_t ControlVideo::read(uint32_t rgn_start, uint32_t offset, int size)
{
if (rgn_start == this->vram_base) {
if (offset & VRAM_BE_APERTURE) { // repeats every 16MB
if (offset & 0x800000) { // repeats every 16MB
// HACK: writing to VRAM in 128bit mode with only the standard
// bank populated seems to replicate the first 64bit portion of data
// in the second 64bit portion. This "feature" is used by
@@ -298,38 +276,9 @@ uint32_t ControlVideo::read(uint32_t rgn_start, uint32_t offset, int size)
} // if not VRAM_WIDE_MODE
}
// Little-endian aperture, reverse bytes within each 16/32-bit pixel.
uint32_t value;
int pixel_width = this->radacal->get_pix_width();
switch (pixel_width) {
case 8:
return this->read(rgn_start, offset | VRAM_BE_APERTURE, size);
case 16:
if (offset & (size - 1)) // unaligned access, handled below
break;
value = this->read(rgn_start,
(offset ^ (size == 1 ? 1 : 0)) | VRAM_BE_APERTURE, size);
if (size == 2)
return BYTESWAP_16(value);
if (size == 4)
return (uint32_t(BYTESWAP_16(value >> 16)) << 16) | BYTESWAP_16(value);
return value;
case 32:
if (offset & (size - 1)) // unaligned access, handled below
break;
value = this->read(rgn_start, (offset ^ (4 - size)) | VRAM_BE_APERTURE, size);
return size == 4 ? BYTESWAP_32(value) : size == 2 ? BYTESWAP_16(value) : value;
default:
LOG_F(ERROR, "%s: unsupported pixel width %d for little-endian VRAM read",
this->name.c_str(), pixel_width);
return 0;
}
// Unaligned accesses can straddle pixels or VRAM banks. Split them
// into smaller accesses so each uses the correct byte lanes.
int half_size = size >> 1;
return (this->read(rgn_start, offset, half_size) << (half_size * 8)) |
this->read(rgn_start, offset + half_size, half_size);
LOG_F(ERROR, "%s: read from little-endian aperture address 0x%X", this->name.c_str(),
this->vram_base + offset);
return 0;
}
if (rgn_start == this->regs_base) {
@@ -373,7 +322,7 @@ uint32_t ControlVideo::read(uint32_t rgn_start, uint32_t offset, int size)
case ControlRegs::MON_SENSE:
value = (this->cur_mon_id << 6) | this->mon_sense;
LOG_F(9, "%s: read MON_SENSE %03x.%c = %0*x", this->name.c_str(),
offset, SIZE_ARG(size), size * 2, value);
offset, SIZE_ARG(size), size * 2, value);
break;
case ControlRegs::MISC_ENABLES:
value = this->enables;
@@ -401,7 +350,7 @@ uint32_t ControlVideo::read(uint32_t rgn_start, uint32_t offset, int size)
uint32_t result = pci_conv_rd_data(value, value, details);
if ((offset & 3) || (size != 4)) {
LOG_F(WARNING, "%s: read %s %03x.%c = %08x -> %0*x", this->name.c_str(),
get_name_controlreg(offset), offset, SIZE_ARG(size), value, size * 2, result);
get_name_controlreg(offset), offset, SIZE_ARG(size), value, size * 2, result);
}
return result;
@@ -413,8 +362,7 @@ uint32_t ControlVideo::read(uint32_t rgn_start, uint32_t offset, int size)
void ControlVideo::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size)
{
if (rgn_start == this->vram_base) {
this->draw_fb = true;
if (offset & VRAM_BE_APERTURE) {
if (offset & 0x800000) {
if (this->enables & VRAM_WIDE_MODE) {
// Note: we ignore access to 4MB range at 0xC00000 because it is undefined for VRAM_WIDE_MODE.
// There is data there but it is not in the same order as the first 4MB.
@@ -469,36 +417,9 @@ void ControlVideo::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
}
} // switch
} // if not VRAM_WIDE_MODE
} else { // little-endian aperture
int pixel_width = this->radacal->get_pix_width();
switch (pixel_width) {
case 8:
return this->write(rgn_start, offset | VRAM_BE_APERTURE, value, size);
case 16:
if (offset & (size - 1)) // unaligned access, handled below
break;
offset ^= size == 1 ? 1 : 0;
if (size == 2)
value = BYTESWAP_16(value);
else if (size == 4)
value = (uint32_t(BYTESWAP_16(value >> 16)) << 16) | BYTESWAP_16(value);
return this->write(rgn_start, offset | VRAM_BE_APERTURE, value, size);
case 32:
if (offset & (size - 1)) // unaligned access, handled below
break;
offset ^= 4 - size;
value = size == 4 ? BYTESWAP_32(value) : size == 2 ? BYTESWAP_16(value) : value;
return this->write(rgn_start, offset | VRAM_BE_APERTURE, value, size);
default:
LOG_F(ERROR, "%s: unsupported pixel width %d for little-endian VRAM write",
this->name.c_str(), pixel_width);
return;
}
// Split unaligned accesses as in the read path.
int half_size = size >> 1;
this->write(rgn_start, offset, value >> (half_size * 8), half_size);
this->write(rgn_start, offset + half_size, value, half_size);
} else {
LOG_F(ERROR, "%s: write to little-endian aperture address 0x%X", this->name.c_str(),
this->vram_base + offset);
}
return;
}
@@ -511,10 +432,10 @@ void ControlVideo::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
this->swatch_params[(offset >> 4) - ControlRegs::VFPEQ] = value & 0x3FF;
if (value & ~0x3FF)
LOG_F(ERROR, "%s: write PIPE_DELAY %03x.%c = %0*x", this->name.c_str(),
offset, SIZE_ARG(size), size * 2, value);
offset, SIZE_ARG(size), size * 2, value);
else
LOG_F(CONTROL, "%s: write PIPE_DELAY %03x.%c = %0*x", this->name.c_str(),
offset, SIZE_ARG(size), size * 2, value);
offset, SIZE_ARG(size), size * 2, value);
if (this->display_enabled) {
this->enable_display();
}
@@ -523,10 +444,10 @@ void ControlVideo::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
this->swatch_params[(offset >> 4) - ControlRegs::VFPEQ] = value & 0xFFU;
if (value & ~0xFFU)
LOG_F(ERROR, "%s: write HEQ %03x.%c = %0*x", this->name.c_str(),
offset, SIZE_ARG(size), size * 2, value);
offset, SIZE_ARG(size), size * 2, value);
else
LOG_F(CONTROL, "%s: write HEQ %03x.%c = %0*x", this->name.c_str(),
offset, SIZE_ARG(size), size * 2, value);
offset, SIZE_ARG(size), size * 2, value);
if (this->display_enabled) {
this->enable_display();
}
@@ -548,10 +469,10 @@ void ControlVideo::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
this->swatch_params[(offset >> 4) - ControlRegs::VFPEQ] = value & 0xFFF;
if (value & ~0xFFF)
LOG_F(ERROR, "%s: write %s %03x.%c = %0*x", this->name.c_str(),
get_name_controlreg(offset), offset, SIZE_ARG(size), size * 2, value);
get_name_controlreg(offset), offset, SIZE_ARG(size), size * 2, value);
else
LOG_F(CONTROL, "%s: write %s %03x.%c = %0*x", this->name.c_str(),
get_name_controlreg(offset), offset, SIZE_ARG(size), size * 2, value);
get_name_controlreg(offset), offset, SIZE_ARG(size), size * 2, value);
if (this->display_enabled) {
this->enable_display();
}
@@ -583,17 +504,12 @@ void ControlVideo::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
} else
this->swatch_ctrl = value;
break;
case ControlRegs::GBASE:{
uint32_t old_value = this->fb_base;
uint32_t new_value = value & 0x3FFFE0;
if (new_value != old_value) {
this->fb_base = new_value;
if (this->display_enabled) {
this->enable_display();
}
case ControlRegs::GBASE:
this->fb_base = value & 0x3FFFE0;
if (this->display_enabled) {
this->enable_display();
}
break;
}
case ControlRegs::ROW_WORDS:
this->row_words = value & 0x7FE0;
if (this->display_enabled) {
@@ -601,11 +517,12 @@ void ControlVideo::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
}
break;
case ControlRegs::MON_SENSE: {
// This is a nine-bit register (bits 6-8 are read-only sense
// inputs that can be written back). Log unexpected values.
VLOG_F((value & ~0x1FF) ? loguru::Verbosity_ERROR : 9,
"%s: write MON_SENSE %03x.%c = %0*x", this->name.c_str(),
offset, SIZE_ARG(size), size * 2, value);
if (value & ~0x3F)
LOG_F(ERROR, "%s: write MON_SENSE %03x.%c = %0*x", this->name.c_str(),
offset, SIZE_ARG(size), size * 2, value);
else
LOG_F(9, "%s: write MON_SENSE %03x.%c = %0*x", this->name.c_str(),
offset, SIZE_ARG(size), size * 2, value);
uint8_t dirs = ((value >> 3) & 7) ^ 7;
uint8_t levels = ((value & 7) & dirs) | (dirs ^ 7);
this->mon_sense = value & 0x3F;
@@ -614,7 +531,6 @@ void ControlVideo::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
break;
case ControlRegs::MISC_ENABLES:
if ((this->enables ^ value) & BLANK_DISABLE) {
this->draw_fb = true;
if (value & BLANK_DISABLE)
this->blank_on = false;
else {
@@ -654,31 +570,6 @@ uint8_t* ControlVideo::GetVram()
return &this->vram_ptr[0];
}
void ControlVideo::update_fb_ptr()
{
this->fb_ptr = &this->vram_ptr[this->fb_base];
if (swatch_params[ControlRegs::HAL-1] != swatch_params[ControlRegs::PIPE_DELAY-1] + 1 ||
this->pixel_depth == 32 ||
(this->pixel_depth == 16 && this->active_width == 1280)
) {
// don't know how to calculate offset from GBASE (fb_base); it is always hard coded as + 16 in the ndrv.
this->fb_ptr += 16; // first 16 bytes are for 4 bpp HW cursor
}
else {
/*
Open Firmware frame buffer has these properties:
- GBASE == 0 // no offset from vram_ptr
- fb_ptr == vram_ptr // no offset from GBASE
- active_width == ROW_WORDS (row_words) // no offset between rows
- HAL == PIPE_DELAY + 1
- depth_mode = 0 // 8 bit indexed
*/
}
if (this->radacal->get_dbl_buf_cr() == 0 && this->vram_banks == 3) {
this->fb_ptr += 0x200000;
}
}
void ControlVideo::enable_display()
{
int new_width, new_height, clk_divisor;
@@ -701,30 +592,49 @@ void ControlVideo::enable_display()
this->active_width = new_width;
this->active_height = new_height;
// set framebuffer parameters
this->fb_ptr = &this->vram_ptr[this->fb_base];
this->fb_pitch = this->row_words;
if (~this->enables & SCAN_CONTROL) {
this->fb_pitch >>= 1;
}
// get pixel depth from RaDACal
this->pixel_depth = this->radacal->get_pix_width();
this->update_fb_ptr();
this->pixel_depth = this->radacal->get_pix_width();
if (swatch_params[ControlRegs::HAL-1] != swatch_params[ControlRegs::PIPE_DELAY-1] + 1 ||
this->pixel_depth == 32 ||
(this->pixel_depth == 16 && this->active_width == 1280)
) {
// don't know how to calculate offset from GBASE (fb_base); it is always hard coded as + 16 in the ndrv.
this->fb_ptr += 16; // first 16 bytes are for 4 bpp HW cursor
}
else {
/*
Open Firmware frame buffer has these properties:
- GBASE == 0 // no offset from vram_ptr
- fb_ptr == vram_ptr // no offset from GBASE
- active_width == ROW_WORDS (row_words) // no offset between rows
- HAL == PIPE_DELAY + 1
- depth_mode = 0 // 8 bit indexed
*/
}
if (this->radacal->get_dbl_buf_cr() == 0 && this->vram_banks == 3) {
this->fb_ptr += 0x200000;
}
// get pixel depth from RaDACal
switch (this->pixel_depth) {
case 8:
this->convert_fb_cb = [this](uint8_t *dst_buf, int dst_pitch) {
this->draw_fb = false;
this->convert_frame_8bpp_indexed(dst_buf, dst_pitch);
};
break;
case 16:
this->convert_fb_cb = [this](uint8_t *dst_buf, int dst_pitch) {
this->draw_fb = false;
this->convert_frame_15bpp<BE>(dst_buf, dst_pitch);
};
break;
case 32:
this->convert_fb_cb = [this](uint8_t *dst_buf, int dst_pitch) {
this->draw_fb = false;
this->convert_frame_32bpp<BE>(dst_buf, dst_pitch);
};
break;
@@ -772,8 +682,6 @@ void ControlVideo::enable_display()
this->blank_on = true;
this->crtc_on = false;
}
this->draw_fb = true;
}
void ControlVideo::disable_display()
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff. Show more