Compare commits

..
235 changed files with 46341 additions and 8111 deletions

No files matched your search

-10
View File
@@ -7,14 +7,8 @@ out/
*.o
*.d
# Ignore CMake system files
CMakeFiles
cmake_install.cmake
# Ignore Visual Studio configuration files
CMakeSettings.json
*.vcxproj
*.vcxproj.filters
# Ignore generated executables
dingusppc
@@ -27,8 +21,4 @@ Thumb.db
# IDE ignores
build
build-*
*.dir
*.user
DerivedData
*.xcodeproj/project.xcworkspace
*.xcodeproj/xcuserdata
+42 -41
View File
@@ -4,40 +4,18 @@ project(dingusppc)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
#set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib)
if (NOT WIN32)
find_package(SDL2 REQUIRED)
include_directories(${SDL2_INCLUDE_DIRS})
if (UNIX AND NOT APPLE)
find_package (Threads)
endif()
else() # Windows build relies on vcpkg
# pick up system wide vcpkg if exists
if (DEFINED ENV{VCPKG_ROOT} AND EXISTS $ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake)
message(STATUS "Using system vcpkg at $ENV{VCPKG_ROOT}")
set(vcpkg_toolchain_file $ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake)
# check Github Actions vcpkg installation
elseif (DEFINED ENV{VCPKG_INSTALLATION_ROOT} AND EXISTS $ENV{VCPKG_INSTALLATION_ROOT}/scripts/buildsystems/vcpkg.cmake)
message(STATUS "Using system vcpkg at $ENV{VCPKG_INSTALLATION_ROOT}")
set(vcpkg_toolchain_file $ENV{VCPKG_INSTALLATION_ROOT}/scripts/buildsystems/vcpkg.cmake)
# otherwise, fetch vcpkg from Github
else()
message(STATUS "Fetching latest vcpkg from Github...")
include(FetchContent)
FetchContent_Declare(vcpkg GIT_REPOSITORY https://github.com/microsoft/vcpkg.git)
FetchContent_MakeAvailable(vcpkg)
set(vcpkg_toolchain_file ${vcpkg_SOURCE_DIR}/scripts/buildsystems/vcpkg.cmake)
endif()
set(CMAKE_TOOLCHAIN_FILE ${vcpkg_toolchain_file})
find_package(SDL2 CONFIG REQUIRED)
add_compile_definitions(SDL_MAIN_HANDLED)
find_package(SDL2 REQUIRED)
include_directories(${SDL2_INCLUDE_DIRS})
else()
include_directories("${PROJECT_SOURCE_DIR}/thirdparty/SDL2/include/")
if (UNIX AND NOT APPLE)
find_package (Threads)
endif()
endif()
option(DPPC_BUILD_PPC_TESTS "Build PowerPC tests" OFF)
@@ -46,6 +24,9 @@ option(DPPC_BUILD_BENCHMARKS "Build benchmarking programs" OFF)
option(DPPC_68K_DEBUGGER "Enable 68k debugging" OFF)
if (DPPC_68K_DEBUGGER)
# Build capstone as static library.
set(CAPSTONE_BUILD_STATIC ON CACHE BOOL "")
# Turn off anything unnecessary.
set(CAPSTONE_BUILD_SHARED OFF CACHE BOOL "")
set(CAPSTONE_BUILD_TESTS OFF CACHE BOOL "")
@@ -83,6 +64,13 @@ add_subdirectory("${PROJECT_SOURCE_DIR}/machines/")
add_subdirectory("${PROJECT_SOURCE_DIR}/utils/")
add_subdirectory("${PROJECT_SOURCE_DIR}/thirdparty/loguru/")
#set(BUILD_EXAMPLE_PROGRAMS OFF CACHE BOOL "Build libsoundio example programs")
#set(BUILD_TESTS OFF CACHE BOOL "Build libsoundio tests")
#set(BUILD_DYNAMIC_LIBS ON CACHE BOOL "Build libsoundio dynamic libs")
#set(BUILD_STATIC_LIBS ON CACHE BOOL "Build libsoundio static libs")
#add_subdirectory("${PROJECT_SOURCE_DIR}/thirdparty/libsoundio")
set(BUILD_TESTS OFF CACHE BOOL "Build Cubeb tests")
set(BUILD_SHARED_LIBS OFF CACHE BOOL "Build shared libraries")
set(BUILD_TOOLS OFF CACHE BOOL "Build Cubeb tools")
@@ -99,13 +87,18 @@ include_directories("${PROJECT_SOURCE_DIR}"
"${PROJECT_SOURCE_DIR}/utils"
"${PROJECT_SOURCE_DIR}/thirdparty/loguru/"
"${PROJECT_SOURCE_DIR}/thirdparty/CLI11/"
"${PROJECT_SOURCE_DIR}/thirdparty/cubeb/include")
# ${SDL2_INCLUDE_DIRS})
"${PROJECT_SOURCE_DIR}/thirdparty/SDL2/")
# "${PROJECT_SOURCE_DIR}/thirdparty/cubeb/include")
# ${LIBSOUNDIO_HEADERS})
file(GLOB SOURCES "${PROJECT_SOURCE_DIR}/*.cpp"
"${PROJECT_SOURCE_DIR}/*.c"
"${PROJECT_SOURCE_DIR}/*.hpp"
"${PROJECT_SOURCE_DIR}/*.h")
#get_directory_property(LIBSOUNDIO_LIBS DIRECTORY thirdparty/libsoundio DEFINITION LIBSOUNDIO_LIBS)
file(GLOB TEST_SOURCES "${PROJECT_SOURCE_DIR}/cpu/ppc/test/*.cpp")
add_executable(dingusppc ${SOURCES} $<TARGET_OBJECTS:core>
@@ -117,14 +110,18 @@ add_executable(dingusppc ${SOURCES} $<TARGET_OBJECTS:core>
$<TARGET_OBJECTS:loguru>)
if (WIN32)
target_link_libraries(dingusppc PRIVATE SDL2::SDL2 SDL2::SDL2main cubeb)
target_link_libraries(dingusppc "${PROJECT_SOURCE_DIR}/thirdparty/SDL2/lib/x64/SDL2.lib"
"${PROJECT_SOURCE_DIR}/thirdparty/SDL2/lib/x64/SDL2main.lib"
ws2_32
cubeb)
else()
target_link_libraries(dingusppc PRIVATE SDL2::SDL2 SDL2::SDL2main cubeb
${CMAKE_DL_LIBS} ${CMAKE_THREAD_LIBS_INIT})
#target_link_libraries(dingusppc libsoundio_static ${LIBSOUNDIO_LIBS} ${SDL2_LIBRARIES})
target_link_libraries(dingusppc cubeb ${SDL2_LIBRARIES} ${CMAKE_DL_LIBS} ${CMAKE_THREAD_LIBS_INIT})
target_include_directories(dingusppc PRIVATE ${CLI11_ROOT})
endif()
if (DPPC_68K_DEBUGGER)
target_link_libraries(dingusppc PRIVATE capstone)
target_link_libraries(dingusppc capstone-static)
endif()
if (DPPC_BUILD_PPC_TESTS)
@@ -137,14 +134,18 @@ if (DPPC_BUILD_PPC_TESTS)
$<TARGET_OBJECTS:loguru>)
if (WIN32)
target_link_libraries(testppc PRIVATE SDL2::SDL2 SDL2::SDL2main cubeb)
target_link_libraries(testppc
"${PROJECT_SOURCE_DIR}/thirdparty/SDL2/lib/x64/SDL2.lib"
"${PROJECT_SOURCE_DIR}/thirdparty/SDL2/lib/x64/SDL2main.lib"
cubeb)
else()
target_link_libraries(testppc PRIVATE SDL2::SDL2 SDL2::SDL2main cubeb
${CMAKE_DL_LIBS} ${CMAKE_THREAD_LIBS_INIT})
#target_link_libraries(testppc libsoundio_static ${LIBSOUNDIO_LIBS} ${SDL2_LIBRARIES})
target_link_libraries(testppc cubeb ${SDL2_LIBRARIES} ${CMAKE_DL_LIBS}
${CMAKE_THREAD_LIBS_INIT})
endif()
if (DPPC_68K_DEBUGGER)
target_link_libraries(testppc PRIVATE capstone)
target_link_libraries(testppc capstone-static)
endif()
endif()
@@ -158,11 +159,11 @@ if (DPPC_BUILD_BENCHMARKS)
$<TARGET_OBJECTS:utils>
$<TARGET_OBJECTS:loguru>)
target_link_libraries(bench1 PRIVATE cubeb SDL2::SDL2 SDL2::SDL2main ${CMAKE_DL_LIBS}
target_link_libraries(bench1 cubeb ${SDL2_LIBRARIES} ${CMAKE_DL_LIBS}
${CMAKE_THREAD_LIBS_INIT})
if (DPPC_68K_DEBUGGER)
target_link_libraries(bench1 PRIVATE capstone)
target_link_libraries(bench1 capstone-static)
endif()
endif()
+28
View File
@@ -0,0 +1,28 @@
{
"configurations": [
{
"name": "x64-Debug",
"generator": "Ninja",
"configurationType": "Debug",
"inheritEnvironments": [ "clang_cl_x64" ],
"buildRoot": "${projectDir}\\out\\build\\${name}",
"installRoot": "${projectDir}\\out\\install\\${name}",
"cmakeCommandArgs": "",
"buildCommandArgs": "-v",
"ctestCommandArgs": "",
"variables": []
},
{
"name": "x64-Release",
"generator": "Ninja",
"configurationType": "Release",
"buildRoot": "${projectDir}\\out\\build\\${name}",
"installRoot": "${projectDir}\\out\\install\\${name}",
"cmakeCommandArgs": "",
"buildCommandArgs": "-v",
"ctestCommandArgs": "",
"inheritEnvironments": [ "clang_cl_x64" ],
"variables": []
}
]
}
+4 -6
View File
@@ -23,7 +23,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <chrono>
#include "cpu/ppc/ppcemu.h"
#include "cpu/ppc/ppcmmu.h"
#include "devices/memctrl/mpc106.h"
#include "devices/mpc106.h"
#include <thirdparty/loguru/loguru.hpp>
uint32_t cs_code[] = {
@@ -59,19 +59,17 @@ int main(int argc, char** argv) {
return -1;
}
constexpr uint64_t tbr_freq = 16705000;
ppc_cpu_init(grackle_obj, PPC_VER::MPC750, tbr_freq);
ppc_cpu_init(grackle_obj, PPC_VER::MPC750);
/* load executable code into RAM at address 0 */
for (i = 0; i < sizeof(cs_code); i++) {
mmu_write_vmem<uint32_t>(i*4, cs_code[i]);
mem_write_dword(i*4, cs_code[i]);
}
srand(0xCAFEBABE);
for (i = 0; i < 32768; i++) {
mmu_write_vmem<uint8_t>(0x1000+i, rand() % 256);
mem_write_byte(0x1000+i, rand() % 256);
}
/* prepare benchmark code execution */
+1 -1
View File
@@ -5,4 +5,4 @@ include_directories("${PROJECT_SOURCE_DIR}"
file(GLOB SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp")
add_library(core OBJECT ${SOURCES})
target_link_libraries(core PRIVATE SDL2::SDL2)
target_link_libraries(core)
-81
View File
@@ -1,81 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** Non-standard low-level bitwise operations. */
#ifndef BIT_OPS_H
#define BIT_OPS_H
#include <cinttypes>
#if defined(__GNUG__) && !defined(__clang__) // GCC, mybe ICC but not Clang
# include <x86intrin.h>
# define ROTL_32(x, n) (_rotl((x), (n)))
# define ROTR_32(x, n) (_rotr((x), (n)))
#elif defined(_MSC_VER) // MSVC
# include <intrin.h>
# define ROTL_32(x, n) (_rotl((x), (n)))
# define ROTR_32(x, n) (_rotr((x), (n)))
#else
// cyclic rotation idioms that modern compilers will
// recognize and generate very compact code for
// evolving specific machine instructions
inline unsigned ROTL_32(unsigned x, unsigned n) {
n &= 0x1F;
return (x << n) | (x >> (32 - n));
}
inline unsigned ROTR_32(unsigned x, unsigned n) {
n &= 0x1F;
return (x >> n) | (x << (32 - n));
}
#endif
template <class T>
inline T extract_bits(T val, int pos, int len) {
return (val >> pos) & (((T)1 << len) - 1);
}
template <class T>
inline void insert_bits(T &old_val, T new_val, int pos, int len) {
T mask = (((T)1 << len) - 1) << pos;
old_val = (old_val & ~mask) | ((new_val << pos) & mask);
}
/* Return true if the specified bit is different in the given numbers. */
static inline bool bit_changed(uint64_t old_val, uint64_t new_val, int bit_num) {
return (old_val ^ new_val) & (1ULL << bit_num);
}
static inline bool bit_set(const uint64_t val, const int bit_num) {
return !!(val & (1ULL << bit_num));
}
#endif // BIT_OPS_H
-65
View File
@@ -1,65 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <core/hostevents.h>
#include <cpu/ppc/ppcemu.h>
#include <loguru.hpp>
#include <SDL.h>
EventManager* EventManager::event_manager;
void EventManager::poll_events()
{
SDL_Event event;
while (SDL_PollEvent(&event)) {
events_captured++;
switch (event.type) {
case SDL_QUIT:
power_on = false;
break;
case SDL_WINDOWEVENT: {
WindowEvent we;
we.sub_type = event.window.event;
we.window_id = event.window.windowID;
this->post_event(we);
}
break;
case SDL_KEYDOWN:
key_downs++;
break;
case SDL_KEYUP:
key_ups++;
break;
case SDL_MOUSEMOTION:
mouse_motions++;
break;
default:
unhandled_events++;
}
}
}
-94
View File
@@ -1,94 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef EVENT_MANAGER_H
#define EVENT_MANAGER_H
#include <cinttypes>
#include <functional>
#include <list>
#include <map>
#include <utility>
enum EventType : uint16_t {
EVENT_UNKNOWN = 0,
EVENT_WINDOW = 100,
EVENT_KEYBOARD = 200,
EVENT_MOUSE = 300,
};
class BaseEvent {
public:
BaseEvent(EventType type) { this->type = type; };
EventType type;
};
class WindowEvent : public BaseEvent {
public:
WindowEvent() : BaseEvent(EventType::EVENT_WINDOW) {};
uint16_t sub_type;
uint32_t window_id;
};
class EventManager {
public:
static EventManager* get_instance() {
if (!event_manager) {
event_manager = new EventManager();
}
return event_manager;
};
using EventHandler = std::function<void(const BaseEvent&)>;
void poll_events();
void register_handler(const EventType event_type, EventHandler&& eh) {
this->_handlers[event_type].emplace_back(std::move(eh));
};
void post_event(const BaseEvent& event) {
auto type = event.type;
if( _handlers.find(type) == _handlers.end() )
return;
auto&& handlers = _handlers.at(type);
for(auto&& handler : handlers)
handler(event);
}
private:
static EventManager* event_manager;
EventManager() {}; // private constructor to implement a singleton
std::map<EventType, std::list<EventHandler>> _handlers;
uint64_t events_captured = 0;
uint64_t unhandled_events = 0;
uint64_t key_downs = 0;
uint64_t key_ups = 0;
uint64_t mouse_motions = 0;
};
#endif // EVENT_MANAGER_H
-49
View File
@@ -1,49 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef MATH_UTILS_H
#define MATH_UTILS_H
inline void _u32xu64(uint32_t a, uint64_t b, uint32_t &hi, uint64_t &lo)
{
uint64_t p0 = (b & 0xffffffff) * a;
uint64_t p1 = (b >> 32) * a;
lo = p0 + (p1 << 32);
hi = (p1 >> 32) + (lo < p0);
}
inline void _u32xu64(uint32_t a, uint64_t b, uint64_t &hi, uint32_t &lo)
{
uint64_t p0 = (b & 0xffffffff) * a;
uint64_t p1 = (b >> 32) * a;
lo = (uint32_t)p0;
hi = (p0 >> 32) + p1;
}
inline void _u64xu64(uint64_t a, uint64_t b, uint64_t &hi, uint64_t &lo)
{
uint32_t p0h; uint64_t p0l; _u32xu64((uint32_t)b, a, p0h, p0l);
uint64_t p1h; uint32_t p1l; _u32xu64(b >> 32, a, p1h, p1l);
lo = p0l + ((uint64_t)p1l << 32);
hi = p0h + p1h + (lo < p0l);
}
#endif // MATH_UTILS_H
+2 -2
View File
@@ -32,7 +32,7 @@ TimerManager* TimerManager::timer_manager;
uint32_t TimerManager::add_oneshot_timer(uint64_t timeout, timer_cb cb)
{
if (!timeout || timeout <= MIN_TIMEOUT_NS) {
LOG_F(WARNING, "One-shot timer too short, timeout=%llu ns", (long long unsigned)timeout);
LOG_F(WARNING, "One-shot timer too short, timeout=%llu ns", timeout);
}
TimerInfo* ti = new TimerInfo;
@@ -58,7 +58,7 @@ uint32_t TimerManager::add_oneshot_timer(uint64_t timeout, timer_cb cb)
uint32_t TimerManager::add_cyclic_timer(uint64_t interval, timer_cb cb)
{
if (!interval || interval <= MIN_TIMEOUT_NS) {
LOG_F(WARNING, "Cyclic timer interval too short, timeout=%llu ns", (long long unsigned)interval);
LOG_F(WARNING, "Cyclic timer interval too short, timeout=%llu ns", interval);
}
TimerInfo* ti = new TimerInfo;
+1 -5
View File
@@ -34,13 +34,9 @@ using namespace std;
#define MIN_TIMEOUT_NS 200
#define NS_PER_SEC 1E9
#define USEC_PER_SEC 1E6
#define NS_PER_USEC 1000UL
#define NS_PER_MSEC 1E6
#define ONE_BILLION_NS 0x3B9ACA00UL
#define USECS_TO_NSECS(us) (us) * NS_PER_USEC
#define MSECS_TO_NSECS(ms) (ms) * NS_PER_MSEC
#define USECS_TO_NSECS(us) (us) * 1000
typedef function<void()> timer_cb;
+44 -20
View File
@@ -45,7 +45,7 @@ inline void power_setsoov(uint32_t a, uint32_t b, uint32_t d) {
/** mask generator for rotate and shift instructions (§ 4.2.1.4 PowerpC PEM) */
static inline uint32_t power_rot_mask(unsigned rot_mb, unsigned rot_me) {
uint32_t m1 = 0xFFFFFFFFUL >> rot_mb;
uint32_t m2 = (uint32_t)(0xFFFFFFFFUL << (31 - rot_me));
uint32_t m2 = 0xFFFFFFFFUL << (31 - rot_me);
return ((rot_mb <= rot_me) ? m2 & m1 : m1 | m2);
}
@@ -136,40 +136,64 @@ void dppc_interpreter::power_dozi() {
void dppc_interpreter::power_lscbx() {
ppc_grab_regsdab();
ppc_effective_address = (reg_a == 0) ? ppc_result_b : ppc_result_a + ppc_result_b;
//ppc_result_d = 0xFFFFFFFF;
ppc_effective_address = (reg_a == 0) ? ppc_result_b : ppc_result_a + ppc_result_b;
uint8_t return_value = 0;
uint32_t bytes_to_load = (ppc_state.spr[SPR::XER] & 0x7f);
uint32_t bytes_copied = 0;
uint8_t matching_byte = (uint8_t)((ppc_state.spr[SPR::XER] & 0xFF00) >> 8);
uint32_t byte_offset = 0;
// for storing each byte
uint32_t bitmask = 0xFF000000;
uint8_t shift_amount = 24;
//for storing each byte
uint32_t bitmask = 0;
uint32_t shift_amount = 0;
while (bytes_to_load > 0) {
if (byte_offset == 24) {
reg_d = (reg_d + 1) % 32;
ppc_result_d = 0xFFFFFFFF;
ppc_store_result_regd();
}
switch (byte_offset) {
case 0:
bitmask = 0x00FFFFFF;
shift_amount = 24;
break;
case 8:
bitmask = 0xFF00FFFF;
shift_amount = 16;
break;
case 16:
bitmask = 0xFFFF00FF;
shift_amount = 8;
break;
case 24:
bitmask = 0xFFFFFF00;
shift_amount = 0;
break;
}
return_value = mmu_read_vmem<uint8_t>(ppc_effective_address);
// return_value = mem_grab_byte(ppc_effective_address);
ppc_result_d = (ppc_result_d & ~(bitmask)) | (return_value << shift_amount);
ppc_result_d = (ppc_result_d & bitmask) | (return_value << shift_amount);
ppc_store_result_regd();
if (bitmask == 0x000000FF) {
reg_d = (reg_d + 1) & 31;
//ppc_result_d = 0xFFFFFFFF;
bitmask = 0xFF000000;
shift_amount = 24;
}
else {
bitmask >>= 8;
shift_amount -= 8;
bytes_copied++;
if (return_value == matching_byte) {
//Match has been found - Time to break out
break;
}
byte_offset += 8;
if (byte_offset == 32) {
byte_offset = 0;
}
ppc_effective_address++;
bytes_copied++;
bytes_to_load--;
if (return_value == matching_byte)
break;
}
ppc_state.spr[SPR::XER] = (ppc_state.spr[SPR::XER] & 0xFFFFFF80) | bytes_copied;
+7 -11
View File
@@ -94,7 +94,7 @@ enum SPR : int {
DAR = 19,
RTCU_S = 20, // supervisor RTCU
RTCL_S = 21, // supervisor RTCL
DEC = 22, // decrementer
DEC = 22,
SDR1 = 25,
SRR0 = 26,
SRR1 = 27,
@@ -109,12 +109,11 @@ enum SPR : int {
/** symbolic names for common PPC processors */
enum PPC_VER : uint32_t {
MPC601 = 0x00010001,
MPC603 = 0x00030001,
MPC604 = 0x00040001,
MPC603E = 0x00060101,
MPC603EV = 0x00070101,
MPC750 = 0x00080200
MPC601 = 0x00010001,
MPC603 = 0x00030001,
MPC604 = 0x00040001,
MPC603E = 0x00060101,
MPC750 = 0x00080200
};
/**
@@ -160,11 +159,8 @@ extern uint32_t opcode_value; // used for interpreting opcodes
extern uint64_t timebase_counter;
extern uint64_t tbr_wr_timestamp;
extern uint64_t dec_wr_timestamp;
extern uint64_t rtc_timestamp;
extern uint64_t tbr_wr_value;
extern uint32_t dec_wr_value;
extern uint32_t tbr_freq_ghz;
extern uint64_t tbr_freq_hz;
extern uint32_t rtc_lo, rtc_hi;
// Additional steps to prevent overflow?
+1 -1
View File
@@ -100,7 +100,7 @@ void ppc_exception_handler(Except_Type exception_type, uint32_t srr1_bits) {
break;
default:
ABORT_F("Unknown exception occured: %X\n", (unsigned)exception_type);
ABORT_F("Unknown exception occured: %X\n", exception_type);
break;
}
+17 -20
View File
@@ -66,13 +66,11 @@ uint64_t g_icycles;
int icnt_factor;
/* global variables related to the timebase facility */
uint64_t tbr_wr_timestamp; // stores vCPU virtual time of the last TBR write
uint64_t rtc_timestamp; // stores vCPU virtual time of the last RTC write
uint64_t tbr_wr_timestamp; // stores vCPU virtual time of the last TBR/RTC write
uint64_t tbr_wr_value; // last value written to the TBR
uint32_t tbr_freq_ghz; // TBR/RTC driving frequency in GHz expressed as a 32 bit fraction less than 1.0.
uint64_t tbr_freq_hz; // TBR/RTC driving frequency in Hz
uint64_t timebase_counter; // internal timebase counter
uint64_t dec_wr_timestamp; // stores vCPU virtual time of the last DEC write
uint32_t dec_wr_value; // last value written to the DEC register
uint32_t decr; // current value of PPC DEC register
uint32_t rtc_lo; // MPC601 RTC lower, counts nanoseconds
uint32_t rtc_hi; // MPC601 RTC upper, counts seconds
@@ -765,14 +763,13 @@ void ppc_cpu_init(MemCtrlBase* mem_ctrl, uint32_t cpu_version, uint64_t tb_freq)
g_icycles = 0;
icnt_factor = 4;
tbr_wr_timestamp = 0;
rtc_timestamp = 0;
tbr_wr_value = 0;
tbr_freq_ghz = (tb_freq << 32) / NS_PER_SEC;
tbr_freq_hz = tb_freq;
exec_flags = 0;
timebase_counter = 0;
dec_wr_value = 0;
decr = 0;
/* zero all GPRs as prescribed for MPC601 */
/* For later PPC CPUs, GPR content is undefined */
@@ -850,38 +847,38 @@ uint64_t reg_op(string& reg_name, uint64_t val, bool is_write) {
try {
if (reg_name_u == "PC") {
if (is_write)
ppc_state.pc = (uint32_t)val;
ppc_state.pc = val;
return ppc_state.pc;
}
if (reg_name_u == "MSR") {
if (is_write)
ppc_state.msr = (uint32_t)val;
ppc_state.msr = val;
return ppc_state.msr;
}
if (reg_name_u == "CR") {
if (is_write)
ppc_state.cr = (uint32_t)val;
ppc_state.cr = val;
return ppc_state.cr;
}
if (reg_name_u == "FPSCR") {
if (is_write)
ppc_state.fpscr = (uint32_t)val;
ppc_state.fpscr = val;
return ppc_state.fpscr;
}
if (reg_name_u.substr(0, 1) == "R") {
reg_num_str = reg_name_u.substr(1);
reg_num = (unsigned)stoul(reg_num_str, NULL, 0);
reg_num = stoul(reg_num_str, NULL, 0);
if (reg_num < 32) {
if (is_write)
ppc_state.gpr[reg_num] = (uint32_t)val;
ppc_state.gpr[reg_num] = val;
return ppc_state.gpr[reg_num];
}
}
if (reg_name_u.substr(0, 1) == "FR") {
reg_num_str = reg_name_u.substr(2);
reg_num = (unsigned)stoul(reg_num_str, NULL, 0);
reg_num = stoul(reg_num_str, NULL, 0);
if (reg_num < 32) {
if (is_write)
ppc_state.fpr[reg_num].int64_r = val;
@@ -891,20 +888,20 @@ uint64_t reg_op(string& reg_name, uint64_t val, bool is_write) {
if (reg_name_u.substr(0, 3) == "SPR") {
reg_num_str = reg_name_u.substr(3);
reg_num = (unsigned)stoul(reg_num_str, NULL, 0);
reg_num = stoul(reg_num_str, NULL, 0);
if (reg_num < 1024) {
if (is_write)
ppc_state.spr[reg_num] = (uint32_t)val;
ppc_state.spr[reg_num] = val;
return ppc_state.spr[reg_num];
}
}
if (reg_name_u.substr(0, 2) == "SR") {
reg_num_str = reg_name_u.substr(2);
reg_num = (unsigned)stoul(reg_num_str, NULL, 0);
reg_num = stoul(reg_num_str, NULL, 0);
if (reg_num < 16) {
if (is_write)
ppc_state.sr[reg_num] = (uint32_t)val;
ppc_state.sr[reg_num] = val;
return ppc_state.sr[reg_num];
}
}
@@ -912,7 +909,7 @@ uint64_t reg_op(string& reg_name, uint64_t val, bool is_write) {
spr = SPRName2Num.find(reg_name_u);
if (spr != SPRName2Num.end()) {
if (is_write)
ppc_state.spr[spr->second] = (uint32_t)val;
ppc_state.spr[spr->second] = val;
return ppc_state.spr[spr->second];
}
} catch (...) {
+42 -45
View File
@@ -125,11 +125,11 @@ static BATResult mpc601_block_address_translation(uint32_t la)
// logical to physical translation
pa = bat_entry->phys_hi | (la & ~bat_entry->hi_mask);
return BATResult{bat_hit, prot, pa};
break;
}
}
return BATResult{bat_hit, 0, 0};
return BATResult{bat_hit, prot, pa};
}
/** PowerPC-style block address translation. */
@@ -309,11 +309,9 @@ static PATResult page_address_translation(uint32_t la, bool is_instr_fetch,
};
}
uint8_t* mmu_get_dma_mem(uint32_t addr, uint32_t size, bool* is_writable)
uint8_t* mmu_get_dma_mem(uint32_t addr, uint32_t size)
{
if (addr >= last_dma_area.start && (addr + size) <= last_dma_area.end) {
if (is_writable)
*is_writable = last_dma_area.type & RT_RAM;
return last_dma_area.mem_ptr + (addr - last_dma_area.start);
} else {
AddressMapEntry* entry = mem_ctrl_instance->find_range(addr);
@@ -321,9 +319,6 @@ uint8_t* mmu_get_dma_mem(uint32_t addr, uint32_t size, bool* is_writable)
last_dma_area.start = entry->start;
last_dma_area.end = entry->end;
last_dma_area.mem_ptr = entry->mem_ptr;
last_dma_area.type = entry->type;
if (is_writable)
*is_writable = entry->type & RT_RAM;
return last_dma_area.mem_ptr + (addr - last_dma_area.start);
} else {
ABORT_F("SOS: DMA access to unmapped memory %08X!\n", addr);
@@ -378,16 +373,16 @@ void mmu_change_mode()
if (CurITLBMode != mmu_mode) {
switch(mmu_mode) {
case 0: // real address mode
pCurITLB1 = &itlb1_mode1[0];
pCurITLB2 = &itlb2_mode1[0];
pCurITLB1 = &dtlb1_mode1[0];
pCurITLB2 = &dtlb2_mode1[0];
break;
case 2: // supervisor mode with instruction translation enabled
pCurITLB1 = &itlb1_mode2[0];
pCurITLB2 = &itlb2_mode2[0];
pCurITLB1 = &dtlb1_mode2[0];
pCurITLB2 = &dtlb2_mode2[0];
break;
case 3: // user mode with instruction translation enabled
pCurITLB1 = &itlb1_mode3[0];
pCurITLB2 = &itlb2_mode3[0];
pCurITLB1 = &dtlb1_mode3[0];
pCurITLB2 = &dtlb2_mode3[0];
break;
}
CurITLBMode = mmu_mode;
@@ -742,7 +737,6 @@ void tlb_flush_entry(uint32_t ea)
tlb1 = &dtlb1_mode2[0];
tlb2 = &dtlb2_mode2[0];
break;
default:
case 5:
tlb1 = &dtlb1_mode3[0];
tlb2 = &dtlb2_mode3[0];
@@ -879,7 +873,7 @@ static void mpc601_bat_update(uint32_t bat_reg)
dbat_entry->valid = false;
}
// MPC601 has unified BATs so we're going to flush both ITLB and DTLB
// MPC601 has unified BATs so we're going to fush both ITLB and DTLB
if (!gTLBFlushBatEntries) {
gTLBFlushBatEntries = true;
add_ctx_sync_action(&tlb_flush_bat_entries<TLBType::ITLB>);
@@ -895,19 +889,21 @@ static void ppc_ibat_update(uint32_t bat_reg)
upper_reg_num = bat_reg & 0xFFFFFFFE;
bat_entry = &ibat_array[(bat_reg - 528) >> 1];
bl = (ppc_state.spr[upper_reg_num] >> 2) & 0x7FF;
hi_mask = ~((bl << 17) | 0x1FFFF);
if (ppc_state.spr[upper_reg_num] & 3) { // is that BAT pair valid?
bat_entry = &ibat_array[(bat_reg - 528) >> 1];
bl = (ppc_state.spr[upper_reg_num] >> 2) & 0x7FF;
hi_mask = ~((bl << 17) | 0x1FFFF);
bat_entry->access = ppc_state.spr[upper_reg_num] & 3;
bat_entry->prot = ppc_state.spr[upper_reg_num + 1] & 3;
bat_entry->hi_mask = hi_mask;
bat_entry->phys_hi = ppc_state.spr[upper_reg_num + 1] & hi_mask;
bat_entry->bepi = ppc_state.spr[upper_reg_num] & hi_mask;
bat_entry->access = ppc_state.spr[upper_reg_num] & 3;
bat_entry->prot = ppc_state.spr[upper_reg_num + 1] & 3;
bat_entry->hi_mask = hi_mask;
bat_entry->phys_hi = ppc_state.spr[upper_reg_num + 1] & hi_mask;
bat_entry->bepi = ppc_state.spr[upper_reg_num] & hi_mask;
if (!gTLBFlushBatEntries) {
gTLBFlushBatEntries = true;
add_ctx_sync_action(&tlb_flush_bat_entries<TLBType::ITLB>);
if (!gTLBFlushBatEntries) {
gTLBFlushBatEntries = true;
add_ctx_sync_action(&tlb_flush_bat_entries<TLBType::ITLB>);
}
}
}
@@ -919,21 +915,22 @@ static void ppc_dbat_update(uint32_t bat_reg)
upper_reg_num = bat_reg & 0xFFFFFFFE;
bat_entry = &dbat_array[(bat_reg - 536) >> 1];
bl = (ppc_state.spr[upper_reg_num] >> 2) & 0x7FF;
hi_mask = ~((bl << 17) | 0x1FFFF);
if (ppc_state.spr[upper_reg_num] & 3) { // is that BAT pair valid?
bat_entry = &dbat_array[(bat_reg - 536) >> 1];
bl = (ppc_state.spr[upper_reg_num] >> 2) & 0x7FF;
hi_mask = ~((bl << 17) | 0x1FFFF);
bat_entry->access = ppc_state.spr[upper_reg_num] & 3;
bat_entry->prot = ppc_state.spr[upper_reg_num + 1] & 3;
bat_entry->hi_mask = hi_mask;
bat_entry->phys_hi = ppc_state.spr[upper_reg_num + 1] & hi_mask;
bat_entry->bepi = ppc_state.spr[upper_reg_num] & hi_mask;
bat_entry->access = ppc_state.spr[upper_reg_num] & 3;
bat_entry->prot = ppc_state.spr[upper_reg_num + 1] & 3;
bat_entry->hi_mask = hi_mask;
bat_entry->phys_hi = ppc_state.spr[upper_reg_num + 1] & hi_mask;
bat_entry->bepi = ppc_state.spr[upper_reg_num] & hi_mask;
if (!gTLBFlushBatEntries) {
gTLBFlushBatEntries = true;
add_ctx_sync_action(&tlb_flush_bat_entries<TLBType::DTLB>);
if (!gTLBFlushBatEntries) {
gTLBFlushBatEntries = true;
add_ctx_sync_action(&tlb_flush_bat_entries<TLBType::DTLB>);
}
}
}
void mmu_pat_ctx_changed()
@@ -968,7 +965,7 @@ void mmu_print_regs()
}
}
LOG_F(INFO, "%s", "");
LOG_F(INFO, "");
LOG_F(INFO, "SDR1 = 0x%X", ppc_state.spr[SPR::SDR1]);
LOG_F(INFO, "Segment registers:");
@@ -1008,7 +1005,7 @@ inline T mmu_read_vmem(uint32_t guest_va)
// perform full address translation and refill the secondary TLB
tlb2_entry = dtlb2_refill(guest_va, 0);
if (tlb2_entry->flags & PAGE_NOPHYS) {
return (T)UnmappedVal;
return UnmappedVal;
}
}
#ifdef TLB_PROFILING
@@ -1082,8 +1079,8 @@ inline void mmu_write_vmem(uint32_t guest_va, T value)
}
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 & 0x4000), true);
PATResult pat_res = page_address_translation(guest_va, false,
!!(ppc_state.msr & 0x4000), true);
tlb1_entry->flags |= TLBFlags::PTE_SET_C;
// don't forget to update the secondary TLB as well
@@ -1121,8 +1118,8 @@ inline void mmu_write_vmem(uint32_t guest_va, T value)
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 & 0x4000), true);
PATResult pat_res = page_address_translation(guest_va, false,
!!(ppc_state.msr & 0x4000), true);
tlb2_entry->flags |= TLBFlags::PTE_SET_C;
}
+1 -1
View File
@@ -102,7 +102,7 @@ enum TLBFlags : uint16_t {
extern std::function<void(uint32_t bat_reg)> ibat_update;
extern std::function<void(uint32_t bat_reg)> dbat_update;
extern uint8_t* mmu_get_dma_mem(uint32_t addr, uint32_t size, bool* is_writable);
extern uint8_t* mmu_get_dma_mem(uint32_t addr, uint32_t size);
extern void mmu_change_mode(void);
extern void mmu_pat_ctx_changed();
+36 -56
View File
@@ -22,7 +22,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
// General opcodes for the processor - ppcopcodes.cpp
#include <core/timermanager.h>
#include <core/mathutils.h>
#include "ppcemu.h"
#include "ppcmmu.h"
#include <array>
@@ -729,7 +728,7 @@ void dppc_interpreter::ppc_srawi() {
/** mask generator for rotate and shift instructions (§ 4.2.1.4 PowerpC PEM) */
static inline uint32_t rot_mask(unsigned rot_mb, unsigned rot_me) {
uint32_t m1 = 0xFFFFFFFFUL >> rot_mb;
uint32_t m2 = (uint32_t)(0xFFFFFFFFUL << (31 - rot_me));
uint32_t m2 = 0xFFFFFFFFUL << (31 - rot_me);
return ((rot_mb <= rot_me) ? m2 & m1 : m1 | m2);
}
@@ -856,47 +855,18 @@ void dppc_interpreter::ppc_mtmsr() {
}
}
static inline void calc_rtcl_value()
static inline uint64_t calc_rtcl_value()
{
uint64_t new_ts = get_virt_time_ns();
uint64_t rtc_l = new_ts - rtc_timestamp + rtc_lo;
uint64_t diff = get_virt_time_ns() - tbr_wr_timestamp;
uint64_t rtc_inc = diff * tbr_freq_hz / NS_PER_SEC;
uint64_t rtc_l = rtc_lo + (rtc_inc << 7);
if (rtc_l >= ONE_BILLION_NS) { // check RTCL overflow
rtc_hi += (uint32_t)(rtc_l / ONE_BILLION_NS);
rtc_hi += rtc_l / ONE_BILLION_NS;
rtc_lo = rtc_l % ONE_BILLION_NS;
tbr_wr_timestamp = get_virt_time_ns();
rtc_l = rtc_lo;
}
else {
rtc_lo = (uint32_t)rtc_l;
}
rtc_timestamp = new_ts;
}
static inline uint64_t calc_tbr_value()
{
uint64_t tbr_inc;
uint32_t tbr_inc_lo;
uint64_t diff = get_virt_time_ns() - tbr_wr_timestamp;
_u32xu64(tbr_freq_ghz, diff, tbr_inc, tbr_inc_lo);
return (tbr_wr_value + tbr_inc);
}
static inline uint32_t calc_dec_value() {
uint64_t dec_adj;
uint32_t dec_adj_lo;
uint64_t diff = get_virt_time_ns() - dec_wr_timestamp;
_u32xu64(tbr_freq_ghz, diff, dec_adj, dec_adj_lo);
return (dec_wr_value - dec_adj);
}
static void update_timebase(uint64_t mask, uint64_t new_val)
{
uint64_t tbr_value = calc_tbr_value();
tbr_wr_value = (tbr_value & mask) | new_val;
tbr_wr_timestamp = get_virt_time_ns();
}
static void update_decrementer(uint32_t val) {
dec_wr_value = val;
dec_wr_timestamp = get_virt_time_ns();
return rtc_l & 0x3FFFFF80UL;
}
void dppc_interpreter::ppc_mfspr() {
@@ -910,21 +880,30 @@ void dppc_interpreter::ppc_mfspr() {
switch (ref_spr) {
case SPR::RTCL_U:
calc_rtcl_value();
ppc_state.spr[SPR::RTCL_U] = rtc_lo & 0x3FFFFF80UL;
ppc_state.spr[SPR::RTCL_U] = calc_rtcl_value();
break;
case SPR::RTCU_U:
calc_rtcl_value();
ppc_state.spr[SPR::RTCU_U] = rtc_hi;
break;
case SPR::DEC:
ppc_state.spr[SPR::DEC] = calc_dec_value();
ppc_state.spr[SPR::RTCL_U] = rtc_hi;
break;
}
ppc_state.gpr[(ppc_cur_instruction >> 21) & 31] = ppc_state.spr[ref_spr];
}
static inline uint64_t calc_tbr_value()
{
uint64_t diff = get_virt_time_ns() - tbr_wr_timestamp;
uint64_t tbr_inc = diff * tbr_freq_hz / NS_PER_SEC;
return (tbr_wr_value + tbr_inc);
}
static void update_timebase(uint64_t mask, uint64_t new_val)
{
uint64_t tbr_value = calc_tbr_value();
tbr_wr_value = (tbr_value & mask) | new_val;
tbr_wr_timestamp = get_virt_time_ns();
}
void dppc_interpreter::ppc_mtspr() {
uint32_t ref_spr = (((ppc_cur_instruction >> 11) & 31) << 5) | ((ppc_cur_instruction >> 16) & 31);
reg_s = (ppc_cur_instruction >> 21) & 31;
@@ -947,15 +926,12 @@ void dppc_interpreter::ppc_mtspr() {
switch (ref_spr) {
case SPR::RTCL_S:
calc_rtcl_value();
rtc_lo = val & 0x3FFFFF80UL;
tbr_wr_timestamp = get_virt_time_ns();
break;
case SPR::RTCU_S:
calc_rtcl_value();
rtc_hi = val;
break;
case SPR::DEC:
update_decrementer(val);
tbr_wr_timestamp = get_virt_time_ns();
break;
case SPR::TBL_S:
update_timebase(0xFFFFFFFF00000000ULL, val);
@@ -2025,6 +2001,7 @@ void dppc_interpreter::ppc_lswi() {
ppc_effective_address = reg_a ? ppc_result_a : 0;
grab_inb = (ppc_cur_instruction >> 11) & 0x1F;
grab_inb = grab_inb ? grab_inb : 32;
uint32_t stringed_word = 0;
while (grab_inb > 0) {
switch (grab_inb) {
@@ -2037,8 +2014,9 @@ void dppc_interpreter::ppc_lswi() {
grab_inb = 0;
break;
case 3:
ppc_state.gpr[reg_d] = mmu_read_vmem<uint16_t>(ppc_effective_address) << 16;
ppc_state.gpr[reg_d] += mmu_read_vmem<uint8_t>(ppc_effective_address + 2) << 8;
stringed_word = mmu_read_vmem<uint16_t>(ppc_effective_address) << 16;
stringed_word += mmu_read_vmem<uint8_t>(ppc_effective_address + 2) << 8;
ppc_state.gpr[reg_d] = stringed_word;
grab_inb = 0;
break;
default:
@@ -2066,6 +2044,7 @@ void dppc_interpreter::ppc_lswx() {
ppc_effective_address = reg_a ? (ppc_result_a + ppc_result_b) : ppc_result_b;
grab_inb = ppc_state.spr[SPR::XER] & 0x7F;
uint32_t stringed_word = 0;
while (grab_inb > 0) {
switch (grab_inb) {
@@ -2078,9 +2057,10 @@ void dppc_interpreter::ppc_lswx() {
grab_inb = 0;
break;
case 3:
ppc_state.gpr[reg_d] = mmu_read_vmem<uint16_t>(ppc_effective_address) << 16;
ppc_state.gpr[reg_d] += mmu_read_vmem<uint8_t>(ppc_effective_address + 2) << 8;
grab_inb = 0;
stringed_word = mmu_read_vmem<uint16_t>(ppc_effective_address) << 16;
stringed_word += mmu_read_vmem<uint8_t>(ppc_effective_address + 2) << 8;
ppc_state.gpr[reg_d] = stringed_word;
grab_inb = 0;
break;
default:
ppc_state.gpr[reg_d] = mmu_read_vmem<uint32_t>(ppc_effective_address);
+5 -5
View File
@@ -52,7 +52,7 @@ using namespace std;
static uint32_t str2addr(string& addr_str) {
try {
return (uint32_t)stoul(addr_str, NULL, 0);
return stoul(addr_str, NULL, 0);
} catch (invalid_argument& exc) {
throw invalid_argument(string("Cannot convert ") + addr_str);
}
@@ -60,7 +60,7 @@ static uint32_t str2addr(string& addr_str) {
static uint32_t str2num(string& num_str) {
try {
return (uint32_t)stol(num_str, NULL, 0);
return stol(num_str, NULL, 0);
} catch (invalid_argument& exc) {
throw invalid_argument(string("Cannot convert ") + num_str);
}
@@ -410,7 +410,7 @@ void enter_debugger() {
int log_level, context;
size_t separator_pos;
unique_ptr<OfConfigUtils> ofnvram = unique_ptr<OfConfigUtils>(new OfConfigUtils);
unique_ptr<OfNvramUtils> ofnvram = unique_ptr<OfNvramUtils>(new OfNvramUtils);
context = 1; /* start with the PowerPC context */
@@ -512,7 +512,7 @@ void enter_debugger() {
}
} else if (cmd == "next" || cmd == "ni") {
addr_str = "PC";
addr = (uint32_t)get_reg(addr_str) + 4;
addr = get_reg(addr_str) + 4;
ppc_exec_until(addr);
} else if (cmd == "until") {
ss >> addr_str;
@@ -588,7 +588,7 @@ void enter_debugger() {
#endif
} else {
addr_str = "PC";
addr = (uint32_t)get_reg(addr_str);
addr = get_reg(addr_str);
disasm(1, addr);
}
} catch (invalid_argument& exc) {
+3 -3
View File
@@ -1,12 +1,12 @@
include_directories("${PROJECT_SOURCE_DIR}"
"${PROJECT_SOURCE_DIR}/thirdparty/loguru/"
)
"${PROJECT_SOURCE_DIR}/thirdparty/SDL2/")
file(GLOB SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/common/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/common/adb/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/common/i2c/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/common/ata/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/common/nubus/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/common/pci/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/common/scsi/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/ethernet/*.cpp"
@@ -19,4 +19,4 @@ file(GLOB SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp"
)
add_library(devices OBJECT ${SOURCES})
target_link_libraries(devices PRIVATE cubeb SDL2::SDL2)
target_link_libraries(devices PRIVATE cubeb)
+1 -1
View File
@@ -402,7 +402,7 @@ bool ADB_Bus::adb_keybd_listen(int reg) {
}
bool ADB_Bus::adb_mouse_listen(int reg) {
if ((reg != 0) || (reg != 3)) {
if ((reg != 0) | (reg != 3)) {
return false;
}
-129
View File
@@ -1,129 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file Heathrow hard drive controller */
#include <devices/common/ata/atabasedevice.h>
#include <devices/common/ata/atadefs.h>
#include <devices/deviceregistry.h>
#include <loguru.hpp>
#include <cinttypes>
using namespace ata_interface;
AtaBaseDevice::AtaBaseDevice(const std::string name)
{
this->set_name(name);
supports_types(HWCompType::IDE_DEV);
device_reset();
}
void AtaBaseDevice::device_reset(const uint8_t dev_head_val)
{
this->r_error = 1; // Device 0 passed, Device 1 passed or not present
this->r_sect_count = 1;
this->r_sect_num = 1;
this->r_dev_ctrl = 0;
// set protocol signature
if (this->device_type == DEVICE_TYPE_ATAPI) {
this->r_cylinder_lo = 0x14;
this->r_cylinder_hi = 0xEB;
this->r_dev_head = dev_head_val;
} else { // assume ATA by default
this->r_cylinder_lo = 0;
this->r_cylinder_hi = 0;
this->r_dev_head = 0;
this->r_status = DRDY | DSC;
}
}
uint16_t AtaBaseDevice::read(const uint8_t reg_addr) {
switch (reg_addr) {
case ATA_Reg::DATA:
LOG_F(WARNING, "Retrieving data from %s", this->name.c_str());
return 0xFFFFU;
case ATA_Reg::ERROR:
return this->r_error;
case ATA_Reg::SEC_COUNT:
return this->r_sect_count;
case ATA_Reg::SEC_NUM:
return this->r_sect_num;
case ATA_Reg::CYL_LOW:
return this->r_cylinder_lo;
case ATA_Reg::CYL_HIGH:
return this->r_cylinder_hi;
case ATA_Reg::DEVICE_HEAD:
return this->r_dev_head;
case ATA_Reg::STATUS:
// TODO: clear pending interrupt
return this->r_status;
case ATA_Reg::ALT_STATUS:
return this->r_status;
default:
LOG_F(WARNING, "Attempted to read unknown IDE register: %x", reg_addr);
return 0;
}
}
void AtaBaseDevice::write(const uint8_t reg_addr, const uint16_t value) {
switch (reg_addr) {
case ATA_Reg::DATA:
LOG_F(WARNING, "Pushing data to %s", this->name.c_str());
break;
case ATA_Reg::FEATURES:
this->r_features = value;
break;
case ATA_Reg::SEC_COUNT:
this->r_sect_count = value;
break;
case ATA_Reg::SEC_NUM:
this->r_sect_num = value;
break;
case ATA_Reg::CYL_LOW:
this->r_cylinder_lo = value;
break;
case ATA_Reg::CYL_HIGH:
this->r_cylinder_hi = value;
break;
case ATA_Reg::DEVICE_HEAD:
this->r_dev_head = value;
break;
case ATA_Reg::COMMAND:
this->r_command = value;
if (is_selected() || this->r_command == DIAGNOSTICS) {
perform_command();
}
break;
case ATA_Reg::DEV_CTRL:
if (!(this->r_dev_ctrl & SRST) && (value & SRST)) {
LOG_F(INFO, "%s: soft reset triggered", this->name.c_str());
this->r_status |= BSY;
}
this->r_dev_ctrl = value;
break;
default:
LOG_F(WARNING, "Attempted to write unknown IDE register: %x", reg_addr);
}
}
-67
View File
@@ -1,67 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file Base class for ATA devices. */
#ifndef ATA_BASE_DEVICE_H
#define ATA_BASE_DEVICE_H
#include <devices/common/ata/atadefs.h>
#include <devices/common/hwcomponent.h>
#include <cinttypes>
class AtaBaseDevice : public HWComponent, public AtaInterface
{
public:
AtaBaseDevice(const std::string name);
~AtaBaseDevice() = default;
uint16_t read(const uint8_t reg_addr);
void write(const uint8_t reg_addr, const uint16_t value);
virtual int perform_command() = 0;
int get_device_id() { return this->my_dev_id; };
void device_reset(const uint8_t dev_head_val = 0);
private:
bool is_selected() { return ((this->r_dev_head >> 4) & 1) == this->my_dev_id; };
protected:
uint8_t my_dev_id = 0; // my IDE device ID configured by the host
uint8_t device_type = ata_interface::DEVICE_TYPE_UNKNOWN;
// IDE aka task file registers
uint8_t r_error;
uint8_t r_features;
uint8_t r_sect_count;
uint8_t r_sect_num;
uint8_t r_cylinder_lo;
uint8_t r_cylinder_hi;
uint8_t r_dev_head;
uint8_t r_command;
uint8_t r_status;
uint8_t r_dev_ctrl;
};
#endif // ATA_BASE_DEVICE_H
-155
View File
@@ -1,155 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file ATA interface definitions. */
#ifndef ATA_INTERFACE_H
#define ATA_INTERFACE_H
#include <cinttypes>
namespace ata_interface {
/** Device IDs according with the Apple ATA zero/one specification. */
enum {
DEVICE_ID_INVALID = -1,
DEVICE_ID_ZERO = 0,
DEVICE_ID_ONE = 1
};
/** Device types. */
enum {
DEVICE_TYPE_UNKNOWN = -1,
DEVICE_TYPE_ATA = 0,
DEVICE_TYPE_ATAPI = 1,
};
/** ATA register offsets. */
enum ATA_Reg : int {
DATA = 0x0,
ERROR = 0x1, // error (read)
FEATURES = 0x1, // features (write)
SEC_COUNT = 0x2, // sector count
SEC_NUM = 0x3, // sector number
CYL_LOW = 0x4, // cylinder low
CYL_HIGH = 0x5, // cylinder high
DEVICE_HEAD = 0x6, // device/head
STATUS = 0x7, // status (read)
COMMAND = 0x7, // command (write)
ALT_STATUS = 0x16, // alt status (read)
DEV_CTRL = 0x16, // device control (write)
TIME_CONFIG = 0x20 // Apple ASIC specific timing configuration
};
/** Status register bits. */
enum ATA_Status : int {
ERR = 0x1,
IDX = 0x2,
CORR = 0x4,
DRQ = 0x8,
DSC = 0x10,
DWF = 0x20,
DRDY = 0x40,
BSY = 0x80
};
/** Error register bits. */
enum ATA_Error : int {
ANMF = 0x1, //no address mark
TK0NF = 0x2, //track 0 not found
ABRT = 0x4, //abort command
MCR = 0x8,
IDNF = 0x10, //id mark not found
MC = 0x20, //media change request
UNC = 0x40,
BBK = 0x80 //bad block
};
/** Bit definition for the device control register. */
enum ATA_CTRL : int{
IEN = 0x2,
SRST = 0x4,
HOB = 0x80,
};
/* ATA commands. */
enum ATA_Cmd : int {
NOP = 0x00,
RESET_ATAPI = 0x08,
RECALIBRATE = 0x10,
READ_SECTOR = 0x20,
READ_SECTOR_NR = 0x21,
READ_LONG = 0x22,
READ_SECTOR_EXT = 0x24,
WRITE_SECTOR = 0x30,
WRITE_SECTOR_NR = 0x31,
WRITE_LONG = 0x32,
READ_VERIFY = 0x40,
FORMAT_TRACKS = 0x50,
IDE_SEEK = 0x70,
DIAGNOSTICS = 0x90,
INIT_DEV_PARAM = 0x91,
PACKET = 0xA0,
IDFY_PKT_DEV = 0xA1,
READ_MULTIPLE = 0xC4,
WRITE_MULTIPLE = 0xC5,
READ_DMA = 0xC8,
WRITE_DMA = 0xCA,
WRITE_BUFFER_DMA = 0xE9,
READ_BUFFER_DMA = 0xEB,
IDENTIFY_DEVICE = 0xEC,
};
}; // namespace ata_interface
/** Interface for ATA devices. */
class AtaInterface {
public:
AtaInterface() = default;
virtual ~AtaInterface() = default;
virtual uint16_t read(const uint8_t reg_addr) = 0;
virtual void write(const uint8_t reg_addr, const uint16_t val) = 0;
virtual int get_device_id() = 0;
};
/** Dummy ATA device. */
class AtaNullDevice : public AtaInterface {
public:
AtaNullDevice() = default;
~AtaNullDevice() = default;
uint16_t read(const uint8_t reg_addr) {
// return all one's except DD7 if no device is present
// DD7 corresponds to the BSY bit of the status register
// The host should have a pull-down resistor on DD7
// to prevent the software from waiting for a long time
// for empty slots
return 0xFF7FU;
};
void write(const uint8_t reg_addr, const uint16_t val) {};
// invalid device ID means no real device is present
int get_device_id() { return ata_interface::DEVICE_ID_INVALID; };
};
#endif // ATA_INTERFACE_H
-115
View File
@@ -1,115 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file ATA hard disk emulation. */
#include <devices/common/ata/atahd.h>
#include <cstring>
#include <sys/stat.h>
#include <fstream>
#include <string>
#include <loguru.hpp>
using namespace ata_interface;
AtaHardDisk::AtaHardDisk() : AtaBaseDevice("ATA-HD")
{
}
void AtaHardDisk::insert_image(std::string filename) {
this->hdd_img.open(filename, std::fstream::out | std::fstream::in | std::fstream::binary);
struct stat stat_buf;
int rc = stat(filename.c_str(), &stat_buf);
if (!rc) {
this->img_size = stat_buf.st_size;
} else {
ABORT_F("AtaHardDisk: could not determine file size using stat()");
}
this->hdd_img.seekg(0, std::ios_base::beg);
}
int AtaHardDisk::perform_command()
{
LOG_F(INFO, "%s: command 0x%x requested", this->name.c_str(), this->r_command);
this->r_status |= BSY;
this->r_status &= ~DRDY;
switch (this->r_command) {
case NOP:
break;
case RESET_ATAPI:
device_reset();
break;
case RECALIBRATE:
hdd_img.seekg(0, std::ios::beg);
this->r_error = 0;
this->r_cylinder_lo = 0;
this->r_cylinder_hi = 0;
break;
case READ_SECTOR:
case READ_SECTOR_NR: {
this->r_status |= DRQ;
uint16_t sec_count = (this->r_sect_count == 0) ? 256 : this->r_sect_count;
uint32_t sector = (r_sect_num << 16);
sector |= ((this->r_cylinder_lo) << 8) + (this->r_cylinder_hi);
uint64_t offset = sector * ATA_HD_SEC_SIZE;
hdd_img.seekg(offset, std::ios::beg);
hdd_img.read(buffer, sec_count * ATA_HD_SEC_SIZE);
this->r_status &= ~DRQ;
}
break;
case WRITE_SECTOR:
case WRITE_SECTOR_NR: {
this->r_status |= DRQ;
uint16_t sec_count = (this->r_sect_count == 0) ? 256 : this->r_sect_count;
uint32_t sector = (r_sect_num << 16);
sector |= ((this->r_cylinder_lo) << 8) + (this->r_cylinder_hi);
uint64_t offset = sector * ATA_HD_SEC_SIZE;
hdd_img.seekg(offset, std::ios::beg);
hdd_img.write(buffer, sec_count * ATA_HD_SEC_SIZE);
this->r_status &= ~DRQ;
}
break;
case INIT_DEV_PARAM:
break;
case DIAGNOSTICS: {
this->r_status |= DRQ;
int ret_code = this->r_error;
this->r_status &= ~DRQ;
return ret_code;
}
break;
case IDENTIFY_DEVICE:
this->r_status |= DRQ;
std::memcpy(buffer, this->hd_id_data, ATA_HD_SEC_SIZE);
this->r_status &= ~DRQ;
break;
default:
LOG_F(ERROR, "%s: unknown ATA command 0x%x", this->name.c_str(), this->r_command);
this->r_status &= ~BSY;
this->r_status |= ERR;
return -1;
}
this->r_status &= ~BSY;
this->r_status |= DRDY;
return 0;
}
-90
View File
@@ -1,90 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** IDE Channel (aka IDE port) emulation.
One IDE channel is capable of controlling up to two IDE devices.
This class handles device registration and passing of messages
from and to the host.
*/
#include <devices/common/ata/atadefs.h>
#include <devices/common/ata/idechannel.h>
#include <devices/common/hwcomponent.h>
#include <devices/deviceregistry.h>
#include <cinttypes>
#include <memory>
#include <string>
using namespace ata_interface;
IdeChannel::IdeChannel(const std::string name)
{
this->set_name(name);
this->supports_types(HWCompType::IDE_BUS);
this->devices[0] = std::unique_ptr<AtaNullDevice>(new AtaNullDevice());
this->devices[1] = std::unique_ptr<AtaNullDevice>(new AtaNullDevice());
}
uint32_t IdeChannel::read(const uint8_t reg_addr, const int size)
{
if (reg_addr == TIME_CONFIG) {
if (size != 4) {
LOG_F(WARNING, "%s: non-DWORD read from the channel config", this->name.c_str());
}
return this->ch_config;
} else {
return this->devices[this->cur_dev]->read(reg_addr);
}
}
void IdeChannel::write(const uint8_t reg_addr, const uint32_t val, const int size)
{
if (reg_addr == TIME_CONFIG) {
if (size != 4) {
LOG_F(WARNING, "%s: non-DWORD write to the channel config", this->name.c_str());
}
this->ch_config = val;
} else {
// keep track of the currently selected device
if (reg_addr == DEVICE_HEAD) {
this->cur_dev = (val >> 4) & 1;
}
// redirect register writes to both devices
for (auto& dev : this->devices) {
dev->write(reg_addr, val);
}
}
}
static const DeviceDescription Ide0_Descriptor = {
IdeChannel::create_first, {}, {}
};
static const DeviceDescription Ide1_Descriptor = {
IdeChannel::create_second, {}, {}
};
REGISTER_DEVICE(Ide0, Ide0_Descriptor);
REGISTER_DEVICE(Ide1, Ide1_Descriptor);
-58
View File
@@ -1,58 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file IDE Channel (aka IDE port) definitions. */
#ifndef IDE_CHANNEL_H
#define IDE_CHANNEL_H
#include <devices/common/ata/atadefs.h>
#include <devices/common/hwcomponent.h>
#include <cinttypes>
#include <memory>
#include <string>
class IdeChannel : public HWComponent
{
public:
IdeChannel(const std::string name);
~IdeChannel() = default;
static std::unique_ptr<HWComponent> create_first() {
return std::unique_ptr<IdeChannel>(new IdeChannel("IDEO"));
}
static std::unique_ptr<HWComponent> create_second() {
return std::unique_ptr<IdeChannel>(new IdeChannel("IDE1"));
}
uint32_t read(const uint8_t reg_addr, const int size);
void write(const uint8_t reg_addr, const uint32_t val, const int size);
private:
int cur_dev = 0;
uint32_t ch_config = 0; // timing configuration for this channel
std::unique_ptr<AtaInterface> devices[2];
};
#endif // IDE_CHANNEL_H
+80 -168
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-21 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -25,152 +25,104 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <devices/common/dbdma.h>
#include <devices/common/dmacore.h>
#include <endianswap.h>
#include <memaccess.h>
#include <cinttypes>
#include <cstring>
#include <loguru.hpp>
void DMAChannel::set_callbacks(DbdmaCallback start_cb, DbdmaCallback stop_cb) {
void DMAChannel::set_callbacks(DbdmaCallback start_cb, DbdmaCallback stop_cb)
{
this->start_cb = start_cb;
this->stop_cb = stop_cb;
}
/* Load DMACmd from physical memory. */
void DMAChannel::fetch_cmd(uint32_t cmd_addr, DMACmd* p_cmd) {
memcpy((uint8_t*)p_cmd, mmu_get_dma_mem(cmd_addr, 16, nullptr), 16);
void DMAChannel::get_next_cmd(uint32_t cmd_addr, DMACmd* p_cmd) {
/* load DMACmd from physical memory */
memcpy((uint8_t*)p_cmd, mmu_get_dma_mem(cmd_addr, 16), 16);
}
uint8_t DMAChannel::interpret_cmd() {
DMACmd cmd_struct;
bool is_writable, branch_taken = false;
if (this->cmd_in_progress) {
// return current command if there is data to transfer
if (this->queue_len)
return this->cur_cmd;
get_next_cmd(this->cmd_ptr, &cmd_struct);
// obtain real pointer to the descriptor of the completed command
uint8_t *cmd_desc = mmu_get_dma_mem(this->cmd_ptr, 16, &is_writable);
this->ch_stat &= ~CH_STAT_WAKE; /* clear wake bit (DMA spec, 5.5.3.4) */
// get command code
this->cur_cmd = cmd_desc[3] >> 4;
// all commands except STOP update cmd.xferStatus and
// perform actions under control of "i", "b" and "w" bits
if (this->cur_cmd < DBDMA_Cmd::STOP) {
if (is_writable)
WRITE_WORD_LE_A(&cmd_desc[14], this->ch_stat | CH_STAT_ACTIVE);
if (cmd_desc[2] & 3) {
ABORT_F("DBDMA: cmd.w bit not implemented");
}
// react to cmd.b bit
if (cmd_desc[2] & 0xC) {
bool cond = true;
if ((cmd_desc[2] & 0xC) != 0xC) {
uint16_t br_mask = this->branch_select >> 16;
cond = (this->ch_stat & br_mask) == (this->branch_select & br_mask);
if ((cmd_desc[2] & 0xC) == 0x8) { // branch if cond cleared?
cond = !cond;
}
}
if (cond) {
this->cmd_ptr = READ_DWORD_LE_A(&cmd_desc[8]);
branch_taken = true;
}
}
this->update_irq();
}
// all INPUT and OUTPUT commands update cmd.resCount
if (this->cur_cmd < DBDMA_Cmd::STORE_QUAD && is_writable) {
WRITE_WORD_LE_A(&cmd_desc[12], this->queue_len & 0xFFFFUL);
}
if (!branch_taken)
this->cmd_ptr += 16;
this->cmd_in_progress = false;
}
fetch_cmd(this->cmd_ptr, &cmd_struct);
this->ch_stat &= ~CH_STAT_WAKE; // clear wake bit (DMA spec, 5.5.3.4)
this->cur_cmd = cmd_struct.cmd_key >> 4;
switch (this->cur_cmd) {
case DBDMA_Cmd::OUTPUT_MORE:
case DBDMA_Cmd::OUTPUT_LAST:
case DBDMA_Cmd::INPUT_MORE:
case DBDMA_Cmd::INPUT_LAST:
switch (cmd_struct.cmd_key >> 4) {
case 0:
LOG_F(9, "Executing DMA Command OUTPUT_MORE");
if (cmd_struct.cmd_key & 7) {
LOG_F(ERROR, "Key > 0 not implemented");
break;
}
this->queue_data = mmu_get_dma_mem(cmd_struct.address, cmd_struct.req_count, &is_writable);
if (cmd_struct.cmd_bits & 0x3F) {
LOG_F(ERROR, "non-zero i/b/w not implemented");
break;
}
// this->dma_cb->dma_push(
// mmu_get_dma_mem(cmd_struct.address, cmd_struct.req_count),
// cmd_struct.req_count);
this->queue_data = mmu_get_dma_mem(cmd_struct.address, cmd_struct.req_count);
this->queue_len = cmd_struct.req_count;
this->cmd_in_progress = true;
this->cmd_ptr += 16;
break;
case DBDMA_Cmd::STORE_QUAD:
case 1:
LOG_F(9, "Executing DMA Command OUTPUT_LAST");
if (cmd_struct.cmd_key & 7) {
LOG_F(ERROR, "Key > 0 not implemented");
break;
}
if (cmd_struct.cmd_bits & 0x3F) {
LOG_F(ERROR, "non-zero i/b/w not implemented");
break;
}
// this->dma_cb->dma_push(
// mmu_get_dma_mem(cmd_struct.address, cmd_struct.req_count),
// cmd_struct.req_count);
this->queue_data = mmu_get_dma_mem(cmd_struct.address, cmd_struct.req_count);
this->queue_len = cmd_struct.req_count;
this->cmd_ptr += 16;
break;
case 2:
LOG_F(ERROR, "Unsupported DMA Command INPUT_MORE");
break;
case 3:
LOG_F(ERROR, "Unsupported DMA Command INPUT_LAST");
break;
case 4:
LOG_F(ERROR, "Unsupported DMA Command STORE_QUAD");
break;
case DBDMA_Cmd::LOAD_QUAD:
case 5:
LOG_F(ERROR, "Unsupported DMA Command LOAD_QUAD");
break;
case DBDMA_Cmd::NOP:
LOG_F(ERROR, "Unsupported DMA Command NOP");
case 6:
LOG_F(INFO, "Unsupported DMA Command NOP");
break;
case DBDMA_Cmd::STOP:
case 7:
LOG_F(INFO, "DMA Command: 7 (STOP)");
this->ch_stat &= ~CH_STAT_ACTIVE;
this->cmd_in_progress = false;
break;
default:
LOG_F(ERROR, "Unsupported DMA command 0x%X", this->cur_cmd);
LOG_F(ERROR, "Unsupported DMA command 0x%X", cmd_struct.cmd_key >> 4);
this->ch_stat |= CH_STAT_DEAD;
this->ch_stat &= ~CH_STAT_ACTIVE;
}
return this->cur_cmd;
return (cmd_struct.cmd_key >> 4);
}
void DMAChannel::update_irq() {
bool is_writable;
// obtain real pointer to the descriptor of the completed command
uint8_t *cmd_desc = mmu_get_dma_mem(this->cmd_ptr, 16, &is_writable);
// STOP doesn't generate interrupts
if (this->cur_cmd < DBDMA_Cmd::STOP) {
if (cmd_desc[2] & 0x30) {
bool cond = true;
if ((cmd_desc[2] & 0x30) != 0x30) {
uint16_t int_mask = this->int_select >> 16;
cond = (this->ch_stat & int_mask) == (this->int_select & int_mask);
if ((cmd_desc[2] & 0x30) == 0x20) { // branch if cond cleared?
cond = !cond;
}
}
if (cond) {
this->int_ctrl->ack_dma_int(this->irq_id, 1);
}
}
}
}
uint32_t DMAChannel::reg_read(uint32_t offset, int size) {
uint32_t res = 0;
if (size != 4) {
ABORT_F("DBDMA: non-DWORD read from a DMA channel not supported");
LOG_F(WARNING, "Unsupported non-DWORD read from DMA channel");
return 0;
}
switch (offset) {
case DMAReg::CH_CTRL:
res = 0; // ChannelControl reads as 0 (DBDMA spec 5.5.1, table 74)
res = 0; /* ChannelControl reads as 0 (DBDMA spec 5.5.1, table 74) */
break;
case DMAReg::CH_STAT:
res = BYTESWAP_32(this->ch_stat);
@@ -186,7 +138,8 @@ void DMAChannel::reg_write(uint32_t offset, uint32_t value, int size) {
uint16_t mask, old_stat, new_stat;
if (size != 4) {
ABORT_F("DBDMA: non-DWORD writes to a DMA channel not supported");
LOG_F(WARNING, "Unsupported non-DWORD write to DMA channel");
return;
}
value = BYTESWAP_32(value);
@@ -196,22 +149,7 @@ void DMAChannel::reg_write(uint32_t offset, uint32_t value, int size) {
case DMAReg::CH_CTRL:
mask = value >> 16;
new_stat = (value & mask & 0xF0FFU) | (old_stat & ~mask);
LOG_F(9, "New ChannelStatus value = 0x%X", new_stat);
// update ch_stat.s0...s7 if requested (needed for interrupt generation)
if ((new_stat & 0xFF) != (old_stat & 0xFF)) {
this->ch_stat |= new_stat & 0xFF;
}
// flush bit can be set at the same time the run bit is cleared.
// That means we need to update memory before channel operation
// is aborted to prevent data loss.
if (new_stat & CH_STAT_FLUSH) {
// NOTE: because this implementation doesn't currently support
// partial memory updates no special action is taken here
new_stat &= ~CH_STAT_FLUSH;
this->ch_stat = new_stat;
}
LOG_F(INFO, "New ChannelStatus value = 0x%X", new_stat);
if ((new_stat & CH_STAT_RUN) != (old_stat & CH_STAT_RUN)) {
if (new_stat & CH_STAT_RUN) {
@@ -219,12 +157,10 @@ void DMAChannel::reg_write(uint32_t offset, uint32_t value, int size) {
this->ch_stat = new_stat;
this->start();
} else {
this->abort();
this->update_irq();
new_stat &= ~CH_STAT_ACTIVE;
new_stat &= ~CH_STAT_DEAD;
this->cmd_in_progress = false;
this->ch_stat = new_stat;
this->abort();
}
} else if ((new_stat & CH_STAT_WAKE) != (old_stat & CH_STAT_WAKE)) {
new_stat |= CH_STAT_ACTIVE;
@@ -237,18 +173,20 @@ void DMAChannel::reg_write(uint32_t offset, uint32_t value, int size) {
this->pause();
}
}
if (new_stat & CH_STAT_FLUSH) {
LOG_F(WARNING, "DMA flush not implemented!");
new_stat &= ~CH_STAT_FLUSH;
this->ch_stat = new_stat;
}
break;
case DMAReg::CH_STAT:
break; // ingore writes to ChannelStatus
break; /* ingore writes to ChannelStatus */
case DMAReg::CMD_PTR_LO:
if (!(this->ch_stat & CH_STAT_RUN) && !(this->ch_stat & CH_STAT_ACTIVE)) {
this->cmd_ptr = value;
LOG_F(9, "CommandPtrLo set to 0x%X", this->cmd_ptr);
LOG_F(INFO, "CommandPtrLo set to 0x%X", this->cmd_ptr);
}
break;
case DMAReg::BRANCH_SELECT:
this->branch_select = value & 0xFF00FFUL;
break;
default:
LOG_F(WARNING, "Unsupported DMA channel register 0x%X", offset);
}
@@ -259,17 +197,17 @@ DmaPullResult DMAChannel::pull_data(uint32_t req_len, uint32_t *avail_len, uint8
*avail_len = 0;
if (this->ch_stat & CH_STAT_DEAD || !(this->ch_stat & CH_STAT_ACTIVE)) {
// dead or idle channel? -> no more data
/* dead or idle channel? -> no more data */
LOG_F(WARNING, "Dead/idle channel -> no more data");
return DmaPullResult::NoMoreData;
}
// interpret DBDMA program until we get data or become idle
/* interpret DBDMA program until we get data or become idle */
while ((this->ch_stat & CH_STAT_ACTIVE) && !this->queue_len) {
this->interpret_cmd();
}
// dequeue data if any
/* dequeue data if any */
if (this->queue_len) {
if (this->queue_len >= req_len) {
LOG_F(9, "Return req_len = %d data", req_len);
@@ -277,45 +215,20 @@ DmaPullResult DMAChannel::pull_data(uint32_t req_len, uint32_t *avail_len, uint8
*avail_len = req_len;
this->queue_len -= req_len;
this->queue_data += req_len;
} else { // return less data than req_len
} else { /* return less data than req_len */
LOG_F(9, "Return queue_len = %d data", this->queue_len);
*p_data = this->queue_data;
*avail_len = this->queue_len;
this->queue_len = 0;
}
return DmaPullResult::MoreData; // tell the caller there is more data
return DmaPullResult::MoreData; /* tell the caller there is more data */
}
return DmaPullResult::NoMoreData; // tell the caller there is no more data
return DmaPullResult::NoMoreData; /* tell the caller there is no more data */
}
int DMAChannel::push_data(const char* src_ptr, int len) {
if (this->ch_stat & CH_STAT_DEAD || !(this->ch_stat & CH_STAT_ACTIVE)) {
LOG_F(WARNING, "DBDMA: attempt to push data to dead/idle channel");
return -1;
}
// interpret DBDMA program until we get buffer to fill in or become idle
while ((this->ch_stat & CH_STAT_ACTIVE) && !this->queue_len) {
this->interpret_cmd();
}
if (this->queue_len) {
len = std::min((int)this->queue_len, len);
std::memcpy(this->queue_data, src_ptr, len);
this->queue_data += len;
this->queue_len -= len;
}
// proceed with the DBDMA program if the buffer became exhausted
if (!this->queue_len) {
this->interpret_cmd();
}
return 0;
}
bool DMAChannel::is_active() {
bool DMAChannel::is_active()
{
if (this->ch_stat & CH_STAT_DEAD || !(this->ch_stat & CH_STAT_ACTIVE)) {
return false;
}
@@ -324,16 +237,18 @@ bool DMAChannel::is_active() {
}
}
void DMAChannel::start() {
void DMAChannel::start()
{
if (this->ch_stat & CH_STAT_PAUSE) {
LOG_F(WARNING, "Cannot start DMA channel, PAUSE bit is set");
return;
}
LOG_F(INFO, "Starting DMA channel, stat = 0x%X", this->ch_stat);
this->queue_len = 0;
if (this->start_cb)
this->start_cb();
this->start_cb();
}
void DMAChannel::resume() {
@@ -346,13 +261,10 @@ void DMAChannel::resume() {
}
void DMAChannel::abort() {
LOG_F(9, "Aborting DMA channel");
if (this->stop_cb)
this->stop_cb();
LOG_F(INFO, "Aborting DMA channel");
}
void DMAChannel::pause() {
LOG_F(INFO, "Pausing DMA channel");
if (this->stop_cb)
this->stop_cb();
this->stop_cb();
}
+20 -51
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-21 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -30,22 +30,19 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#define DB_DMA_H
#include <devices/common/dmacore.h>
#include <devices/common/hwinterrupt.h>
#include <cinttypes>
#include <functional>
/** DBDMA Channel registers offsets */
enum DMAReg : uint32_t {
CH_CTRL = 0,
CH_STAT = 4,
CMD_PTR_LO = 12,
INT_SELECT = 16,
BRANCH_SELECT = 20,
CH_CTRL = 0,
CH_STAT = 4,
CMD_PTR_LO = 12,
};
/** Channel Status bits (DBDMA spec, 5.5.3) */
enum : uint16_t {
enum {
CH_STAT_ACTIVE = 0x400,
CH_STAT_DEAD = 0x800,
CH_STAT_WAKE = 0x1000,
@@ -56,31 +53,18 @@ enum : uint16_t {
/** DBDMA command (DBDMA spec, 5.6.1) - all fields are little-endian! */
typedef struct DMACmd {
uint16_t req_count;
uint8_t cmd_bits;
uint8_t cmd_key;
uint32_t address;
uint32_t cmd_arg;
uint16_t res_count;
uint16_t xfer_stat;
uint16_t req_count;
uint8_t cmd_bits;
uint8_t cmd_key;
uint32_t address;
uint32_t cmd_arg;
uint16_t res_count;
uint16_t xfer_stat;
} DMACmd;
namespace DBDMA_Cmd {
enum : uint8_t {
OUTPUT_MORE = 0,
OUTPUT_LAST = 1,
INPUT_MORE = 2,
INPUT_LAST = 3,
STORE_QUAD = 4,
LOAD_QUAD = 5,
NOP = 6,
STOP = 7
};
};
typedef std::function<void(void)> DbdmaCallback;
class DMAChannel : public DmaBidirChannel {
class DMAChannel : public DmaOutChannel {
public:
DMAChannel() = default;
~DMAChannel() = default;
@@ -91,17 +75,10 @@ public:
bool is_active();
DmaPullResult pull_data(uint32_t req_len, uint32_t *avail_len, uint8_t **p_data);
int push_data(const char* src_ptr, int len);
void register_dma_int(InterruptCtrl* int_ctrl_obj, uint32_t irq_id) {
this->int_ctrl = int_ctrl_obj;
this->irq_id = irq_id;
};
protected:
void fetch_cmd(uint32_t cmd_addr, DMACmd* p_cmd);
void get_next_cmd(uint32_t cmd_addr, DMACmd* p_cmd);
uint8_t interpret_cmd(void);
void update_irq();
void start(void);
void resume(void);
@@ -109,22 +86,14 @@ protected:
void pause(void);
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)> start_cb; // DMA channel start callback
std::function<void(void)> stop_cb; // DMA channel stop callback
uint16_t ch_stat = 0;
uint32_t cmd_ptr = 0;
uint32_t queue_len = 0;
uint8_t* queue_data = 0;
uint32_t int_select = 0;
uint32_t branch_select = 0;
uint16_t ch_stat = 0;
uint32_t cmd_ptr = 0;
bool cmd_in_progress = false;
uint8_t cur_cmd;
// Interrupt related stuff
InterruptCtrl* int_ctrl = nullptr;
uint32_t irq_id = 0;
uint32_t queue_len;
uint8_t* queue_data;
};
#endif /* DB_DMA_H */
+7 -7
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
Copyright (C) 2018-21 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -38,13 +38,13 @@ public:
uint8_t **p_data) = 0;
};
class DmaInChannel {
public:
virtual int push_data(const char* src_ptr, int len) = 0;
};
// Base class for bidirectional DMA channels.
class DmaBidirChannel : public DmaOutChannel, public DmaInChannel {
class DmaBidirChannel {
public:
virtual bool is_active() { return true; };
virtual int push_data(const char* src_ptr, int len) = 0;
virtual DmaPullResult pull_data(uint32_t req_len, uint32_t *avail_len,
uint8_t **p_data) = 0;
};
#endif // DMA_CORE_H
+2 -3
View File
@@ -39,13 +39,12 @@ enum HWCompType {
I2C_DEV = 1ULL << 9, /* I2C device */
ADB_HOST = 1ULL << 12, /* ADB host */
ADB_DEV = 1ULL << 13, /* ADB device */
PDS_DEV = 1ULL << 14, /* processor direct slot (PDS) device */
NUBUS_DEV = 1ULL << 15, /* Nubus device */
INT_CTRL = 1ULL << 16, /* interrupt controller */
SCSI_BUS = 1ULL << 20, /* SCSI bus */
SCSI_HOST = 1ULL << 21, /* SCSI host adapter */
SCSI_DEV = 1ULL << 22, /* SCSI device */
IDE_BUS = 1ULL << 23, /* IDE bus */
IDE_DEV = 1ULL << 25, /* IDE device */
SND_CODEC = 1ULL << 30, /* Sound codec */
SND_SERVER = 1ULL << 31, /* host sound server */
FLOPPY_CTRL = 1ULL << 32, /* floppy disk controller */
FLOPPY_DRV = 1ULL << 33, /* floppy disk drive */
+2 -3
View File
@@ -75,14 +75,13 @@ private:
class GossamerID : public MMIODevice {
public:
GossamerID(const uint16_t id) {
this->id = id;
this->name = "Machine-id";
this->id = id, this->name = "Machine-id";
supports_types(HWCompType::MMIO_DEV);
};
~GossamerID() = default;
uint32_t read(uint32_t rgn_start, uint32_t offset, int size) {
return ((offset == 4 && size == 2) ? this->id : 0);
return ((!offset && size == 2) ? this->id : 0);
};
/* not writable */
+92
View File
@@ -0,0 +1,92 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** Houdini2 PC Compatibility card emulation. */
#include <devices/deviceregistry.h>
#include <devices/common/hwcomponent.h>
#include <devices/common/nubus/houdini2.h>
#include <devices/common/nubus/nubusutils.h>
#include <devices/memctrl/memctrlbase.h>
#include <loguru.hpp>
#include <machines/machinebase.h>
#include <cinttypes>
HoudiniCard::HoudiniCard()
{
supports_types(HWCompType::PDS_DEV);
this->pl_obj = std::unique_ptr<PretzelLogic> (new PretzelLogic());
auto mem_crtl = dynamic_cast<MemCtrlBase*>(gMachineObj->get_comp_by_type(HWCompType::MEM_CTRL));
mem_crtl->add_mmio_region(0xE0000000, 0x10000, this->pl_obj.get());
// load card's declaration ROM
if (load_declaration_rom("Houdini2_DeclROM.bin", 0xE)) {
LOG_F(ERROR, "Could not load declaration ROM, the card won't work!");
}
}
PretzelLogic::PretzelLogic()
{
supports_types(HWCompType::MMIO_DEV);
// tell the world we got some own memory
// (shared memory will be disabled)
this->air3 = Air3Bits::SIMM_INSTALLED;
this->air_reset = 1; // tell the world our PC is not currently running
}
uint32_t PretzelLogic::read(uint32_t rgn_start, uint32_t offset, int size)
{
switch (offset) {
case PretzelLogicReg::AIR_RESET:
return this->air_reset;
case PretzelLogicReg::AIR3:
return this->air3;
default:
LOG_F(WARNING, "PretzelLogic: reading from unimplemented reg at 0x%X", offset);
}
return 0xFF;
}
void PretzelLogic::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size)
{
switch (offset) {
case PretzelLogicReg::MAIN_IER:
this->main_ier = value;
if (!value) {
LOG_F(INFO, "PretzelLogic: all interrupts disabled");
}
break;
default:
LOG_F(WARNING, "PretzelLogic: writing to unimplemented reg at 0x%X", offset);
}
}
static const DeviceDescription Houdini_Descriptor = {
HoudiniCard::create, {}, {}
};
REGISTER_DEVICE(Houdini2, Houdini_Descriptor);
+75
View File
@@ -0,0 +1,75 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** Houdini2 PC Compatibility card definitions. */
#ifndef HOUDINI2_H
#define HOUDINI2_H
#include <devices/common/mmiodevice.h>
#include <cinttypes>
#include <memory>
enum PretzelLogicReg {
MAIN_IER = 0xE0,
MAIN_ISR = 0xE4,
AIR_RESET = 0xE8,
AIR3 = 0x8004,
};
enum Air3Bits {
SIMM_INSTALLED = 1 << 7, // if set, on-card memory SIMM is installed
};
// Pretzel Logic ASIC
class PretzelLogic : public MMIODevice {
public:
PretzelLogic();
~PretzelLogic() = default;
uint32_t read(uint32_t rgn_start, uint32_t offset, int size);
void write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size);
private:
uint8_t air_reset;
uint8_t air_status;
uint8_t air2;
uint8_t air3;
uint8_t port_AB_dir;
uint8_t port_AB_data;
uint8_t main_ier; // main interrupt enable register
};
class HoudiniCard : public HWComponent {
public:
HoudiniCard();
~HoudiniCard() = default;
static std::unique_ptr<HWComponent> create() {
return std::unique_ptr<HoudiniCard>(new HoudiniCard());
};
private:
std::unique_ptr<PretzelLogic> pl_obj;
};
#endif // HOUDINI2_H
+146
View File
@@ -0,0 +1,146 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <devices/common/nubus/nubusutils.h>
#include <devices/memctrl/memctrlbase.h>
#include <machines/machinebase.h>
#include <loguru.hpp>
#include "memaccess.h"
#include <cinttypes>
#include <fstream>
uint32_t calculate_rom_crc(uint8_t *data_ptr, int length)
{
uint32_t sum = 0;
for (int i = 0; i < length; i++) {
// rotate sum left by one bit
if (sum & 0x80000000UL) {
sum = (sum << 1) | 1;
} else {
sum = (sum << 1) | 0;
}
sum += data_ptr[i];
}
return sum;
}
int load_declaration_rom(const std::string rom_path, int slot_num)
{
std::ifstream rom_file;
int result = 0;
try {
rom_file.open(rom_path, std::ios::in | std::ios::binary);
if (rom_file.fail()) {
throw std::runtime_error("could not open declaration ROM image");
}
// determine image size
rom_file.seekg(0, std::ios::end);
uint32_t rom_size = rom_file.tellg();
// load it
auto rom_data = std::unique_ptr<uint8_t[]> (new uint8_t[rom_size]);
rom_file.seekg(0, std::ios::beg);
rom_file.read((char *)rom_data.get(), rom_size);
// verify image data
uint8_t byte_lane = rom_data[rom_size - 1];
if ((byte_lane & 0xF) != ((byte_lane >> 4) ^ 0xF)) {
throw std::runtime_error("invalid byte lane value");
}
if (READ_DWORD_BE_A(&rom_data[rom_size - 6]) != 0x5A932BC7UL) {
throw std::runtime_error("invalid test pattern");
}
if (rom_data[rom_size - 7] != 1) {
throw std::runtime_error("unsupported format");
}
uint32_t crc = READ_DWORD_BE_A(&rom_data[rom_size - 12]);
int hdr_length = READ_DWORD_BE_A(&rom_data[rom_size - 16]);
// patch the CRC field of the format header to 0
WRITE_DWORD_BE_A(&rom_data[rom_size - 12], 0);
uint32_t test_crc = calculate_rom_crc(rom_data.get(), hdr_length);
// restore the CRC field value
WRITE_DWORD_BE_A(&rom_data[rom_size - 12], crc);
if (test_crc != crc) {
throw std::runtime_error("invalid CRC");
}
int lanes_used = 0;
// count meaningful lanes in a data quad
for (int i = 0; i < 4; i++) {
if (byte_lane & (1 << i)) {
lanes_used++;
}
}
// calculate padded size = rom_size * (4 / lanes_used)
int padded_len = static_cast<int>((float)rom_size * (4 / (float)lanes_used) + 0.5f);
// calculate starting physical address of the ROM
uint32_t rom_phys_start = (0xF0FFFFFFUL | ((slot_num & 0xF) << 24)) - padded_len + 1;
auto mem_crtl = dynamic_cast<MemCtrlBase*>(gMachineObj->get_comp_by_type(HWCompType::MEM_CTRL));
if (!mem_crtl->add_rom_region(rom_phys_start, padded_len)) {
throw std::runtime_error("could not allocate ROM space");
}
int data_pos = 0;
auto new_data = std::unique_ptr<uint8_t[]> (new uint8_t[padded_len]);
// prepare new ROM data by copying over used lanes
// and padding unused lanes with 0xFF
// NOTE: speed uncritical - don't optimize!
for (int i = 0; i < padded_len; i += 4) {
for (int b = 0; b < 4; b++) {
if (byte_lane & (1 << b)) {
new_data[i+b] = rom_data[data_pos++];
} else {
new_data[i+b] = 0xFF;
}
}
}
// move padded ROM data to the memory region
mem_crtl->set_data(rom_phys_start, new_data.get(), padded_len);
}
catch (const std::exception& exc) {
LOG_F(ERROR, "load_declaration_rom failed: %s", exc.what());
result = -1;
}
rom_file.close();
return result;
}
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -19,32 +19,12 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file ATA hard disk definitions. */
#ifndef NUBUS_UTILS_H
#define NUBUS_UTILS_H
#ifndef ATA_HARD_DISK_H
#define ATA_HARD_DISK_H
#include <devices/common/ata/atabasedevice.h>
#include <cinttypes>
#include <string>
#include <fstream>
#define ATA_HD_SEC_SIZE 512
int load_declaration_rom(const std::string rom_path, int slot_num);
class AtaHardDisk : public AtaBaseDevice
{
public:
AtaHardDisk();
~AtaHardDisk() = default;
void insert_image(std::string filename);
int perform_command();
private:
std::fstream hdd_img;
uint64_t img_size;
char * buffer = new char[1 <<17];
uint8_t hd_id_data[ATA_HD_SEC_SIZE] = {};
};
#endif // ATA_HARD_DISK_H
#endif // NUBUS_UTILS_H
+7 -5
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-21 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -46,14 +46,15 @@ NVram::NVram(std::string file_name, uint32_t ram_size)
this->file_name = file_name;
this->ram_size = ram_size;
// allocate memory storage and fill it with zeroes
this->storage = std::unique_ptr<uint8_t[]>(new uint8_t[ram_size] ());
this->storage = new uint8_t[ram_size];
this->init();
}
NVram::~NVram() {
this->save();
if (this->storage)
delete this->storage;
}
uint8_t NVram::read_byte(uint32_t offset) {
@@ -73,8 +74,9 @@ void NVram::init() {
if (f.fail() || !f.read(sig, sizeof(NVRAM_FILE_ID)) ||
!f.read((char*)&data_size, sizeof(data_size)) ||
memcmp(sig, NVRAM_FILE_ID, sizeof(NVRAM_FILE_ID)) || data_size != this->ram_size ||
!f.read((char*)this->storage.get(), this->ram_size)) {
!f.read((char*)this->storage, this->ram_size)) {
LOG_F(WARNING, "Could not restore NVRAM content from the given file.");
memset(this->storage, 0, sizeof(this->ram_size));
}
f.close();
@@ -88,7 +90,7 @@ void NVram::save() {
f.write((char*)&this->ram_size, sizeof(this->ram_size));
/* write NVRAM content */
f.write((char*)this->storage.get(), this->ram_size);
f.write((char*)this->storage, this->ram_size);
f.close();
}
+2 -2
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-21 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -49,7 +49,7 @@ public:
private:
std::string file_name; // file name for the backing file
uint16_t ram_size; // NVRAM size
std::unique_ptr<uint8_t[]> storage;
uint8_t* storage;
void init();
void save();
+74 -336
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -19,7 +19,7 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** Utilities for working with Apple Open Firmware and CHRP NVRAM partitions. */
/** @file Utilities for working with the Apple Open Firmware NVRAM partition. */
#include <devices/common/ofnvram.h>
#include <endianswap.h>
@@ -32,22 +32,14 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <tuple>
using namespace std;
static std::string hex2str(uint32_t n)
{
std::stringstream ss;
ss << setw(8) << setfill('0') << hex << n;
return ss.str();
}
static uint32_t str2env(string& num_str) {
try {
return (uint32_t)stoul(num_str, NULL, 0);
return stoul(num_str, NULL, 0);
} catch (invalid_argument& exc) {
try {
string num_str2 = string("0x") + num_str;
@@ -58,15 +50,22 @@ static uint32_t str2env(string& num_str) {
}
}
bool OfConfigAppl::validate() {
int i;
OfConfigHdrAppl hdr;
int OfNvramUtils::init()
{
this->nvram_obj = dynamic_cast<NVram*>(gMachineObj->get_comp_by_name("NVRAM"));
return this->nvram_obj == nullptr;
}
bool OfNvramUtils::validate()
{
int i;
OfNvramHdr hdr;
if (this->nvram_obj == nullptr)
return false;
// read OF partition header
for (i = 0; i < sizeof(OfConfigHdrAppl); i++) {
for (i = 0; i < sizeof(OfNvramHdr); i++) {
((uint8_t*)&hdr)[i] = this->nvram_obj->read_byte(OF_NVRAM_OFFSET + i);
}
@@ -76,7 +75,7 @@ bool OfConfigAppl::validate() {
this->size = hdr.num_pages * 256;
if (this->size != OF_CFG_SIZE)
if (this->size != 0x800)
return false;
// read the entire partition into the local buffer
@@ -89,9 +88,10 @@ bool OfConfigAppl::validate() {
return false;
return true;
};
}
uint16_t OfConfigAppl::checksum_partition() {
uint16_t OfNvramUtils::checksum_partition()
{
uint32_t acc = 0;
for (int i = 0; i < this->size; i += 2) {
@@ -101,6 +101,25 @@ uint16_t OfConfigAppl::checksum_partition() {
return acc + (acc >> 16);
}
void OfNvramUtils::update_partition()
{
// set checksum in the header to zero
this->buf[4] = 0;
this->buf[5] = 0;
// calculate new checksum
uint16_t checksum = this->checksum_partition();
checksum = checksum ? ~checksum : 0xFFFFU;
// stuff it into the header
WRITE_WORD_BE_A(&this->buf[4], checksum);
// write the entire partition back to NVRAM
for (int i = 0; i < this->size; i++) {
this->nvram_obj->write_byte(OF_NVRAM_OFFSET + i, this->buf[i]);
}
}
static const string flag_names[8] = {
"little-endian?",
"real-mode?",
@@ -135,74 +154,58 @@ static const map<string, std::tuple<int, uint16_t>> of_vars = {
{"boot-command", {OF_VAR_TYPE_STR, 0x58}},
};
const OfConfigImpl::config_dict& OfConfigAppl::get_config_vars() {
this->_config_vars.clear();
void OfNvramUtils::printenv()
{
int i;
if (!this->validate())
return _config_vars;
if (!this->validate()) {
cout << "Invalid Open Firmware partition content!" << endl;
return;
}
uint8_t of_flags = this->buf[12];
// populate flags
for (int i = 0; i < 8; i++) {
_config_vars.push_back(std::make_pair(flag_names[i],
((of_flags << i) & 0x80) ? "true" : "false"));
cout << endl;
// print flags
for (i = 0; i < 8; i++) {
cout << setw(20) << left << flag_names[i] <<
(((of_flags << i) & 0x80) ? "true" : "false") << endl;
}
// populate the remaining variables
// print the remaining variables
for (auto& var : of_vars) {
auto name = var.first;
auto type = std::get<0>(var.second);
auto offset = std::get<1>(var.second);
cout << setw(20) << left << var.first;
switch (type) {
case OF_VAR_TYPE_INT:
_config_vars.push_back(std::make_pair(name,
hex2str(READ_DWORD_BE_A(&this->buf[offset]))));
cout << hex << READ_DWORD_BE_A(&this->buf[offset]) << endl;
break;
case OF_VAR_TYPE_STR:
uint16_t str_offset = READ_WORD_BE_A(&this->buf[offset]) - OF_NVRAM_OFFSET;
uint16_t str_len = READ_WORD_BE_A(&this->buf[offset+2]);
if ((str_offset + str_len) > OF_CFG_SIZE) {
cout << "string property too long - skip it" << endl;
break;
for (i = 0; i < str_len; i++) {
char ch = *(char *)&(this->buf[str_offset + i]);
if (ch == '\x0D') cout << endl; else cout << ch;
}
char prop_val[OF_CFG_SIZE] = "";
memcpy(prop_val, &this->buf[str_offset], str_len);
prop_val[str_len] = '\0';
_config_vars.push_back(std::make_pair(name, prop_val));
cout << endl;
}
}
return _config_vars;
};
void OfConfigAppl::update_partition() {
// set checksum in the header to zero
this->buf[4] = 0;
this->buf[5] = 0;
// calculate new checksum
uint16_t checksum = this->checksum_partition();
checksum = checksum ? ~checksum : 0xFFFFU;
// stuff checksum into the header
WRITE_WORD_BE_A(&this->buf[4], checksum);
// write the entire partition back to NVRAM
for (int i = 0; i < this->size; i++) {
this->nvram_obj->write_byte(OF_NVRAM_OFFSET + i, this->buf[i]);
}
cout << endl;
}
bool OfConfigAppl::set_var(std::string& var_name, std::string& value) {
void OfNvramUtils::setenv(string var_name, string value)
{
int i, flag;
if (!this->validate())
return false;
if (!this->validate()) {
cout << "Invalid Open Firmware partition content!" << endl;
return;
}
// check if the user tries to change a flag
for (i = 0; i < 8; i++) {
@@ -213,7 +216,7 @@ bool OfConfigAppl::set_var(std::string& var_name, std::string& value) {
flag = 0;
else {
cout << "Invalid property value: " << value << endl;
return false;
return;
}
uint8_t flag_bit = 0x80U >> i;
uint8_t of_flags = this->buf[12];
@@ -225,14 +228,15 @@ bool OfConfigAppl::set_var(std::string& var_name, std::string& value) {
this->buf[12] = of_flags;
this->update_partition();
return true;
cout << " ok" << endl; // mimic Forth
return;
}
}
// see if one of the standard properties should be changed
if (of_vars.find(var_name) == of_vars.end()) {
cout << "Attempt to change unknown variable " << var_name << endl;
return false;
return;
}
auto type = std::get<0>(of_vars.at(var_name));
@@ -244,7 +248,7 @@ bool OfConfigAppl::set_var(std::string& var_name, std::string& value) {
num = str2env(value);
} catch (invalid_argument& exc) {
cout << exc.what() << endl;
return false;
return;
}
WRITE_DWORD_BE_A(&this->buf[offset], num);
this->update_partition();
@@ -253,7 +257,7 @@ bool OfConfigAppl::set_var(std::string& var_name, std::string& value) {
uint16_t str_offset = READ_WORD_BE_A(&this->buf[offset]);
uint16_t str_len = READ_WORD_BE_A(&this->buf[offset+2]);
OfConfigHdrAppl *hdr = (OfConfigHdrAppl *)&this->buf[0];
OfNvramHdr *hdr = (OfNvramHdr *)&this->buf[0];
uint16_t here = READ_WORD_BE_A(&hdr->here);
uint16_t top = READ_WORD_BE_A(&hdr->top);
@@ -262,13 +266,11 @@ bool OfConfigAppl::set_var(std::string& var_name, std::string& value) {
uint16_t new_top = top + str_len - value.length();
if (new_top < here) {
cout << "No room in the heap!" << endl;
return false;
return;
}
// remove the old string
std::memmove(&this->buf[top + str_len - OF_NVRAM_OFFSET],
&this->buf[top - OF_NVRAM_OFFSET], str_offset - top);
std::memmove(&this->buf[top + str_len - OF_NVRAM_OFFSET], &this->buf[top - OF_NVRAM_OFFSET], str_offset - top);
for (auto& var : of_vars) {
auto type = std::get<0>(var.second);
auto offset = std::get<1>(var.second);
@@ -297,271 +299,7 @@ bool OfConfigAppl::set_var(std::string& var_name, std::string& value) {
// update physical NVRAM
this->update_partition();
}
return true;
};
uint8_t OfConfigChrp::checksum_hdr(const uint8_t* data)
{
uint16_t sum = data[0];
for (int i = 2; i < 16; i++) {
sum += data[i];
if (sum >= 256)
sum = (sum + 1) & 0xFFU;
}
return sum;
}
bool OfConfigChrp::validate()
{
int i, pos, len;
uint8_t sig;
bool wip = true;
bool of_part_found = false;
// search the entire 8KB NVRAM for CHRP OF config partition.
// Bail out if an unknown partition or free space is encountered.
// Skip over known partitions.
for (pos = 0; wip && pos < 8192;) {
sig = this->nvram_obj->read_byte(pos);
switch (sig) {
case NVRAM_SIG_OF_ENV:
of_part_found = true;
// fall-through
case NVRAM_SIG_FREE:
wip = false;
break;
case NVRAM_SIG_VPD:
case NVRAM_SIG_DIAG:
case NVRAM_SIG_OF_CFG:
case NVRAM_SIG_MAC_OS:
case NVRAM_SIG_ERR_LOG:
// skip valid partitions we're not interested in
len = (this->nvram_obj->read_byte(pos + 2) << 8) |
this->nvram_obj->read_byte(pos + 3);
if (!len || (len * 16) >= 8192)
break;
pos += len * 16;
break;
default:
wip = false;
}
}
if (!of_part_found)
return false;
OfConfigHdrChrp hdr;
// read OF partition header
for (i = 0; i < sizeof(OfConfigHdrChrp); i++) {
((uint8_t*)&hdr)[i] = this->nvram_obj->read_byte(pos + i);
}
len = BYTESWAP_16(hdr.length) * 16;
// sanity checks
if (hdr.sig != NVRAM_SIG_OF_ENV || len < 16 || len > (4096 + sizeof(OfConfigHdrChrp)))
return false;
// calculate partition header checksum
uint8_t chk_sum = this->checksum_hdr((uint8_t*)&hdr);
if (chk_sum != hdr.checksum)
return false;
len -= sizeof(OfConfigHdrChrp);
pos += sizeof(OfConfigHdrChrp);
this->data_offset = pos;
// read the entire partition into the local buffer
for (i = 0; i < len; i++) {
this->buf[i] = this->nvram_obj->read_byte(pos + i);
}
return true;
}
const OfConfigImpl::config_dict& OfConfigChrp::get_config_vars() {
int len;
this->_config_vars.clear();
if (!this->validate())
return _config_vars;
for (int pos = 0; pos < 4096;) {
char *pname = (char *)&this->buf[pos];
// scan property name until '=' is encountered
// or max length is reached
for (len = 0; len < 32; pos++, len++) {
if (pname[len] == '=' || pname[len] == '\0')
break;
}
// empty property name -> free space reached
if (!len) {
this->data_length = pos;
break;
}
if (pname[len] != '=') {
cout << "no = sign found or name > 31 chars" << endl;
break;
}
char prop_name[32];
memcpy(prop_name, pname, len);
prop_name[len] = '\0';
pos++; // skip past '='
char *pval = (char *)&this->buf[pos];
// determine property value length
for (len = 0; pos < 4096; pos++, len++) {
if (pval[len] == '\0')
break;
}
// ensure each property value is null-terminated
if (pos >= 4096) {
cout << "ran off partition end" << endl;
break;
}
this->_config_vars.push_back(std::make_pair(prop_name, pval));
pos++; // skip past null terminator
}
return this->_config_vars;
}
bool OfConfigChrp::update_partition() {
unsigned pos = 0;
memset(this->buf, 0, 4096);
for (auto& var : this->_config_vars) {
if ((var.first.length() + var.second.length() + 2) >= 4096) {
cout << "No room in the partition!" << endl;
return false;
}
memcpy(&this->buf[pos], var.first.c_str(), var.first.length());
pos += var.first.length();
this->buf[pos++] = '=';
memcpy(&this->buf[pos], var.second.c_str(), var.second.length());
pos += var.second.length();
this->buf[pos++] = '\0';
}
// write the entire partition back to NVRAM
for (int i = 0; i < 4096; i++) {
this->nvram_obj->write_byte(this->data_offset + i, this->buf[i]);
}
return true;
}
bool OfConfigChrp::set_var(std::string& var_name, std::string& value) {
if (!this->validate())
return false;
bool found = false;
// see if the user tries to change an existing property
for (auto& var : this->_config_vars) {
if (var.first == var_name) {
found = true;
// see if we're about to change a flag
if (var_name.back() == '?') {
if (value != "true" && value != "false") {
cout << "Flag value can be 'true' or 'false'" << endl;
return false;
}
}
if (value.length() > var.second.length()) {
unsigned free_space = 4096 - this->data_length;
if ((value.length() - var.second.length()) >= free_space) {
cout << "No room for new data!" << endl;
return false;
}
}
var.second = value;
break;
}
}
if (!found) {
cout << "Attempt to change unknown variable " << var_name << endl;
return false;
}
return this->update_partition();
};
int OfConfigUtils::init()
{
this->nvram_obj = dynamic_cast<NVram*>(gMachineObj->get_comp_by_name("NVRAM"));
return this->nvram_obj == nullptr;
}
bool OfConfigUtils::open_container() {
OfConfigImpl* cfg_obj;
if (this->cfg_impl == nullptr) {
cfg_obj = new OfConfigAppl(this->nvram_obj);
if (cfg_obj->validate()) {
this->cfg_impl = std::unique_ptr<OfConfigImpl>(cfg_obj);
return true;
} else {
delete(cfg_obj);
cfg_obj = new OfConfigChrp(this->nvram_obj);
if (cfg_obj->validate()) {
this->cfg_impl = std::unique_ptr<OfConfigImpl>(cfg_obj);
return true;
} else {
delete(cfg_obj);
}
}
} else {
return this->cfg_impl->validate();
}
cout << "No valid Open Firmware partition found!" << endl;
return false;
}
void OfConfigUtils::printenv() {
OfConfigImpl::config_dict vars;
if (!this->open_container())
return;
vars = this->cfg_impl->get_config_vars();
for (auto& var : vars) {
cout << setw(34) << left << var.first << var.second << endl;
}
}
void OfConfigUtils::setenv(string var_name, string value)
{
if (!this->open_container())
return;
if (!this->cfg_impl->set_var(var_name, value)) {
cout << " Please try again" << endl;
} else {
cout << " ok" << endl; // mimic Forth
return;
}
}
+14 -95
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -19,30 +19,20 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** Apple/CHRP Open Firmware NVRAM partition definitions. */
#ifndef OF_NVRAM_H
#define OF_NVRAM_H
#include <devices/common/nvram.h>
#include <cinttypes>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
/** @file Utilities for working with the Apple Open Firmware NVRAM partition. */
/** ========== Apple Open Firmware 1.x/2.x partition definitions. ========== */
#define OF_NVRAM_OFFSET 0x1800
#define OF_NVRAM_SIG 0x1275
#define OF_CFG_SIZE 0x800
// OF Variable types
enum {
OF_VAR_TYPE_INT = 1, // integer
OF_VAR_TYPE_STR = 2, // string
OF_VAR_TYPE_FLG = 3, // boolean flag
OF_VAR_TYPE_INT = 1,
OF_VAR_TYPE_STR = 2,
};
typedef struct {
@@ -52,97 +42,26 @@ typedef struct {
uint16_t checksum; // >nv.checksum partition checksum
uint16_t here; // >nv.here offset to the next free byte (offset of after last string length; = 0x185c)
uint16_t top; // >nv.top offset to the last free byte (offset of string with lowest offset; < 0x2000)
} OfConfigHdrAppl;
} OfNvramHdr;
/** ================== CHRP NVRAM partition definitions. ================== */
/** CHRP NVRAM partition signatures. */
enum {
NVRAM_SIG_OF_CFG = 0x50, // of-config (unused in Power Macintosh)
NVRAM_SIG_VPD = 0x52, // of-vpd (unused in Power Macintosh)
NVRAM_SIG_DIAG = 0x5F, // diagnostics partition
NVRAM_SIG_OF_ENV = 0x70, // common partition with OF environment vars
NVRAM_SIG_ERR_LOG = 0x72, // post-err-log
NVRAM_SIG_FREE = 0x7F, // free space
NVRAM_SIG_MAC_OS = 0xA0, // APL,MacOS75
};
typedef struct {
uint8_t sig; // partition signature, must be 0x70
uint8_t checksum; // partition header checksum (sig, length & name)
uint16_t length; // partition length in 16-byte blocks
char name[12]; // null-terminated partition name
} OfConfigHdrChrp;
// - interface
class OfConfigImpl {
class OfNvramUtils {
public:
using config_dict = std::vector<std::pair<std::string, std::string>>;
virtual ~OfConfigImpl() = default;
virtual bool validate() = 0;
virtual const config_dict& get_config_vars() = 0;
virtual bool set_var(std::string& name, std::string& val) = 0;
};
// Old World implementation
class OfConfigAppl : public OfConfigImpl {
public:
OfConfigAppl(NVram* nvram_obj) { this->nvram_obj = nvram_obj; };
~OfConfigAppl() = default;
bool validate();
const config_dict& get_config_vars();
bool set_var(std::string& var_name, std::string& value);
protected:
uint16_t checksum_partition();
void update_partition();
private:
NVram* nvram_obj = nullptr;
uint8_t buf[OF_CFG_SIZE];
int size = 0;
config_dict _config_vars;
};
// New World implementation
class OfConfigChrp : public OfConfigImpl {
public:
OfConfigChrp(NVram* nvram_obj) { this->nvram_obj = nvram_obj; };
~OfConfigChrp() = default;
bool validate();
const config_dict& get_config_vars();
bool set_var(std::string& var_name, std::string& value);
protected:
uint8_t checksum_hdr(const uint8_t* data);
bool update_partition();
private:
NVram* nvram_obj = nullptr;
uint8_t buf[4096];
unsigned data_offset = 0; // offset to the OF config data
unsigned data_length = 0; // length of the OF config data
config_dict _config_vars;
};
class OfConfigUtils {
public:
OfConfigUtils() = default;
~OfConfigUtils() = default;
OfNvramUtils() = default;
~OfNvramUtils() = default;
int init();
void printenv();
void setenv(std::string var_name, std::string value);
protected:
bool open_container();
bool validate();
uint16_t checksum_partition();
void update_partition();
private:
std::unique_ptr<OfConfigImpl> cfg_impl = nullptr;
NVram* nvram_obj = nullptr;
NVram* nvram_obj = nullptr;
int size = 0;
uint8_t buf[0x800];
};
#endif // OF_NVRAM_H
+279 -185
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -19,7 +19,7 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** Bandit/Chaos ARBus-to-PCI Bridge emulation. */
/** Bandit ARBus-to-PCI Bridge emulation. */
#include <devices/common/pci/bandit.h>
#include <devices/deviceregistry.h>
@@ -40,15 +40,27 @@ const int MultiplyDeBruijnBitPosition2[] =
/** finds the position of the bit that is set */
#define WHAT_BIT_SET(val) (MultiplyDeBruijnBitPosition2[(uint32_t)(val * 0x077CB531U) >> 27])
BanditPciDevice::BanditPciDevice(int bridge_num, std::string name, int dev_id, int rev)
: PCIDevice(name)
Bandit::Bandit(int bridge_num, std::string name) : PCIHost(), PCIDevice(name)
{
supports_types(HWCompType::PCI_DEV);
supports_types(HWCompType::PCI_HOST | HWCompType::PCI_DEV);
this->base_addr = 0xF0000000 + ((bridge_num & 3) << 25);
MemCtrlBase *mem_ctrl = dynamic_cast<MemCtrlBase *>
(gMachineObj->get_comp_by_type(HWCompType::MEM_CTRL));
// add memory mapped I/O region for Bandit control registers
// This region has the following layout:
// base_addr + 0x000000 --> I/O space
// base_addr + 0x800000 --> CONFIG_ADDR
// base_addr + 0xC00000 --> CONFIG_DATA
// base_addr + 0x1000000 --> pass-through memory space (not included below)
mem_ctrl->add_mmio_region(base_addr, 0x01000000, this);
// prepare the PCI config header
this->vendor_id = PCI_VENDOR_APPLE;
this->device_id = dev_id;
this->class_rev = 0x06000000 | (rev & 0xFFU);
this->device_id = 0x0001;
this->class_rev = 0x06000003;
this->cache_ln_sz = 8;
this->command = 0x16;
@@ -61,63 +73,182 @@ BanditPciDevice::BanditPciDevice(int bridge_num, std::string name, int dev_id, i
// This initialization is implied by the device functionality.
this->addr_mask = 3 << ((bridge_num & 3) * 2);
// initial PCI number + chip mode: big endian, interrupts & VGA space disabled
this->mode_ctrl = ((bridge_num & 3) << 2) | 3;
this->rd_hold_off_cnt = 8;
this->name = name;
}
uint32_t BanditPciDevice::pci_cfg_read(uint32_t reg_offs, AccessDetails &details)
uint32_t Bandit::pci_cfg_read(uint32_t reg_offs, uint32_t size)
{
if (reg_offs < 64) {
return PCIDevice::pci_cfg_read(reg_offs, details);
return PCIDevice::pci_cfg_read(reg_offs, size);
}
switch (reg_offs) {
case BANDIT_ADDR_MASK:
return this->addr_mask;
case BANDIT_MODE_SELECT:
return this->mode_ctrl;
case BANDIT_ARBUS_RD_HOLD_OFF:
return this->rd_hold_off_cnt;
return BYTESWAP_32(this->addr_mask);
default:
LOG_READ_UNIMPLEMENTED_CONFIG_REGISTER();
LOG_F(WARNING, "%s: reading from unimplemented config register at 0x%X",
this->pci_name.c_str(), reg_offs);
}
return 0;
}
void BanditPciDevice::pci_cfg_write(uint32_t reg_offs, uint32_t value, AccessDetails &details)
void Bandit::pci_cfg_write(uint32_t reg_offs, uint32_t value, uint32_t size)
{
if (reg_offs < 64) {
PCIDevice::pci_cfg_write(reg_offs, value, details);
PCIDevice::pci_cfg_write(reg_offs, value, size);
return;
}
switch (reg_offs) {
case BANDIT_ADDR_MASK:
this->addr_mask = value;
this->addr_mask = BYTESWAP_32(value);
this->verbose_address_space();
return;
case BANDIT_MODE_SELECT:
this->mode_ctrl = value;
return;
case BANDIT_ARBUS_RD_HOLD_OFF:
this->rd_hold_off_cnt = value & 0x1F;
return;
break;
default:
LOG_WRITE_UNIMPLEMENTED_CONFIG_REGISTER();
LOG_F(WARNING, "%s: writing to unimplemented config register at 0x%X",
this->pci_name.c_str(), reg_offs);
}
}
void BanditPciDevice::verbose_address_space()
uint32_t Bandit::read(uint32_t rgn_start, uint32_t offset, int size)
{
int bus_num, dev_num, fun_num;
uint8_t reg_offs;
uint32_t result, idsel;
if (offset & BANDIT_CONFIG_SPACE) {
if (offset & 0x00400000) {
fun_num = (this->config_addr >> 8) & 7;
reg_offs = this->config_addr & 0xFCU;
// access to the CONFIG_DATA pseudo-register causes a Config Cycle
if (this->config_addr & BANDIT_CAR_TYPE) {
bus_num = (this->config_addr >> 16) & 255;
dev_num = (this->config_addr >> 11) & 31;
LOG_F(
WARNING, "%s: read config cycle type 1 not supported yet %02x:%02x.%x @%02x.%c",
this->name.c_str(), bus_num, dev_num, fun_num, reg_offs + (offset & 3),
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size
);
return 0xFFFFFFFFUL; // PCI spec §6.1
}
idsel = (this->config_addr >> 11) & 0x1FFFFFU;
if (!SINGLE_BIT_SET(idsel)) {
LOG_F(
ERROR, "%s: read invalid IDSEL=0x%X config:0x%X ??:??.%x? @%02x?.%c",
this->name.c_str(), idsel, this->config_addr,
fun_num, reg_offs + (offset & 3),
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size
);
return 0xFFFFFFFFUL; // PCI spec §6.1
}
if (idsel == BANDIT_ID_SEL) { // access to myself
result = this->pci_cfg_read(reg_offs, size);
} else {
if (this->dev_map.count(idsel)) {
result = this->dev_map[idsel]->pci_cfg_read(reg_offs, size);
} else {
dev_num = WHAT_BIT_SET(idsel) + 11;
LOG_F(
ERROR, "%s err: read attempt from non-existing PCI device ??:%02x.%x @%02x.%c",
this->name.c_str(), dev_num, fun_num, reg_offs + (offset & 3),
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size
);
return 0xFFFFFFFFUL; // PCI spec §6.1
}
}
} else {
result = this->config_addr;
}
} else { // I/O space access
// broadcast I/O request to devices that support I/O space
// until a device returns true that means "request accepted"
for (auto& dev : this->io_space_devs) {
if (dev->pci_io_read(offset, size, &result)) {
return result;
}
}
LOG_F(ERROR, "%s: attempt to read from unmapped PCI I/O space, offset=0x%X",
this->name.c_str(), offset);
}
return result;
}
void Bandit::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size)
{
int bus_num, dev_num, fun_num;
uint8_t reg_offs;
uint32_t idsel;
if (offset & BANDIT_CONFIG_SPACE) {
if (offset & 0x00400000) {
fun_num = (this->config_addr >> 8) & 7;
reg_offs = this->config_addr & 0xFCU;
// access to the CONFIG_DATA pseudo-register causes a Config Cycle
if (this->config_addr & BANDIT_CAR_TYPE) {
bus_num = (this->config_addr >> 16) & 255;
dev_num = (this->config_addr >> 11) & 31;
LOG_F(
WARNING, "%s: write config cycle type 1 not supported yet %02x:%02x.%x @%02x.%c = %0*x",
this->name.c_str(), bus_num, dev_num, fun_num, reg_offs + (offset & 3),
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size, size * 2, value
);
return;
}
idsel = (this->config_addr >> 11) & 0x1FFFFFU;
if (!SINGLE_BIT_SET(idsel)) {
LOG_F(
ERROR, "%s: write invalid IDSEL=0x%X config:0x%X ??:??.%x? @%02x?.%c = %0*x",
this->name.c_str(), idsel, this->config_addr,
fun_num, reg_offs + (offset & 3),
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size, size * 2, value
);
return;
}
if (idsel == BANDIT_ID_SEL) { // access to myself
this->pci_cfg_write(reg_offs, value, size);
return;
}
if (this->dev_map.count(idsel)) {
this->dev_map[idsel]->pci_cfg_write(reg_offs, value, size);
} else {
dev_num = WHAT_BIT_SET(idsel) + 11;
LOG_F(
ERROR, "%s err: write attempt to non-existing PCI device ??:%02x.%x @%02x.%c = %0*x",
this->name.c_str(), dev_num, fun_num, reg_offs + (offset & 3),
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size, size * 2, value
);
}
} else {
this->config_addr = BYTESWAP_32(value);
}
} else { // I/O space access
// broadcast I/O request to devices that support I/O space
// until a device returns true that means "request accepted"
for (auto& dev : this->io_space_devs) {
if (dev->pci_io_write(offset, value, size)) {
return;
}
}
LOG_F(ERROR, "%s: attempt to write to unmapped PCI I/O space, offset=0x%X",
this->name.c_str(), offset);
}
}
void Bandit::verbose_address_space()
{
uint32_t mask;
int bit_pos;
if (!this->addr_mask) {
return;
}
LOG_F(INFO, "%s address spaces:", this->pci_name.c_str());
// verbose coarse aka 256MB memory regions
@@ -137,142 +268,8 @@ void BanditPciDevice::verbose_address_space()
}
}
uint32_t BanditHost::read(uint32_t rgn_start, uint32_t offset, int size)
Chaos::Chaos(std::string name) : PCIHost()
{
switch (offset >> 22) {
case 3: // CONFIG_DATA
int bus_num, dev_num, fun_num;
uint8_t reg_offs;
AccessDetails details;
PCIDevice *device;
cfg_setup(offset, size, bus_num, dev_num, fun_num, reg_offs, details, device);
details.flags |= PCI_CONFIG_READ;
if (device) {
return pci_conv_rd_data(device->pci_cfg_read(reg_offs, details), details);
}
LOG_READ_NON_EXISTENT_PCI_DEVICE();
return 0xFFFFFFFFUL; // PCI spec §6.1
case 2: // CONFIG_ADDR
return BYTESWAP_32(this->config_addr);
default: // I/O space
return pci_io_read_broadcast(offset, size);
}
}
void BanditHost::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size)
{
switch (offset >> 22) {
case 3: // CONFIG_DATA
int bus_num, dev_num, fun_num;
uint8_t reg_offs;
AccessDetails details;
PCIDevice *device;
cfg_setup(offset, size, bus_num, dev_num, fun_num, reg_offs, details, device);
details.flags |= PCI_CONFIG_WRITE;
if (device) {
if (size == 4 && !details.offset) { // aligned DWORD writes -> fast path
device->pci_cfg_write(reg_offs, BYTESWAP_32(value), details);
return;
}
// otherwise perform necessary data transformations -> slow path
uint32_t old_val = details.size == 4 ? 0 : device->pci_cfg_read(reg_offs, details);
uint32_t new_val = pci_conv_wr_data(old_val, value, details);
device->pci_cfg_write(reg_offs, new_val, details);
return;
}
LOG_WRITE_NON_EXISTENT_PCI_DEVICE();
break;
case 2: // CONFIG_ADDR
this->config_addr = BYTESWAP_32(value);
break;
default: // I/O space
pci_io_write_broadcast(offset, size, value);
}
}
inline void BanditHost::cfg_setup(uint32_t offset, int size, int &bus_num,
int &dev_num, int &fun_num, uint8_t &reg_offs,
AccessDetails &details, PCIDevice *&device)
{
device = NULL;
details.size = size;
details.offset = offset & 3;
fun_num = FUN_NUM();
reg_offs = REG_NUM();
if (this->config_addr & BANDIT_CAR_TYPE) { // type 1 configuration command
details.flags = PCI_CONFIG_TYPE_1;
bus_num = BUS_NUM();
dev_num = DEV_NUM();
device = pci_find_device(bus_num, dev_num, fun_num);
return;
}
details.flags = PCI_CONFIG_TYPE_0;
bus_num = 0; // use dummy value for bus number
uint32_t idsel = this->config_addr & 0xFFFFF800U;
if (!SINGLE_BIT_SET(idsel)) {
for (dev_num = -1, idsel = this->config_addr; idsel; idsel >>= 1, dev_num++) {}
LOG_F(ERROR, "%s: config_addr 0x%08x does not contain valid IDSEL",
this->name.c_str(), (uint32_t)this->config_addr);
return;
}
dev_num = WHAT_BIT_SET(idsel);
if (this->dev_map.count(DEV_FUN(dev_num, fun_num))) {
device = this->dev_map[DEV_FUN(dev_num, fun_num)];
}
}
int BanditHost::device_postinit()
{
std::string pci_dev_name;
static const std::map<std::string, int> pci_slots = {
{"pci_A1", DEV_FUN(0xD,0)}, {"pci_B1", DEV_FUN(0xE,0)}, {"pci_C1", DEV_FUN(0xF,0)}
};
for (auto& slot : pci_slots) {
pci_dev_name = GET_STR_PROP(slot.first);
if (!pci_dev_name.empty()) {
this->attach_pci_device(pci_dev_name, slot.second);
}
}
return 0;
}
Bandit::Bandit(int bridge_num, std::string name, int dev_id, int rev)
: BanditHost()
{
this->name = name;
supports_types(HWCompType::PCI_HOST);
this->base_addr = 0xF0000000 + ((bridge_num & 3) << 25);
MemCtrlBase *mem_ctrl = dynamic_cast<MemCtrlBase *>
(gMachineObj->get_comp_by_type(HWCompType::MEM_CTRL));
// add memory mapped I/O region for Bandit control registers
// This region has the following layout:
// base_addr + 0x000000 --> I/O space
// base_addr + 0x800000 --> CONFIG_ADDR
// base_addr + 0xC00000 --> CONFIG_DATA
// base_addr + 0x1000000 --> pass-through memory space (not included below)
mem_ctrl->add_mmio_region(base_addr, 0x01000000, this);
// connnect Bandit PCI device
this->my_pci_device = unique_ptr<BanditPciDevice>(
new BanditPciDevice(bridge_num, name, dev_id, rev)
);
this->pci_register_device(DEV_FUN(BANDIT_DEV,0), this->my_pci_device.get());
}
Chaos::Chaos(std::string name) : BanditHost()
{
this->name = name;
supports_types(HWCompType::PCI_HOST);
MemCtrlBase *mem_ctrl = dynamic_cast<MemCtrlBase *>
@@ -283,23 +280,121 @@ Chaos::Chaos(std::string name) : BanditHost()
// base_addr + 0x800000 --> CONFIG_ADDR
// base_addr + 0xC00000 --> CONFIG_DATA
mem_ctrl->add_mmio_region(0xF0000000UL, 0x01000000, this);
this->name = name;
}
static const PropMap Bandit_Properties = {
{"pci_A1",
new StrProperty("")},
{"pci_B1",
new StrProperty("")},
{"pci_C1",
new StrProperty("")},
};
uint32_t Chaos::read(uint32_t rgn_start, uint32_t offset, int size)
{
int bus_num, dev_num, fun_num;
uint8_t reg_offs;
uint32_t result, idsel;
if (offset & BANDIT_CONFIG_SPACE) {
if (offset & 0x00400000) {
fun_num = (this->config_addr >> 8) & 7;
reg_offs = this->config_addr & 0xFCU;
// access to the CONFIG_DATA pseudo-register causes a Config Cycle
if (this->config_addr & BANDIT_CAR_TYPE) {
bus_num = (this->config_addr >> 16) & 255;
dev_num = (this->config_addr >> 11) & 31;
LOG_F(
WARNING, "%s: read config cycle type 1 not supported yet %02x:%02x.%x @%02x.%c",
this->name.c_str(), bus_num, dev_num, fun_num, reg_offs + (offset & 3),
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size
);
return 0xFFFFFFFFUL; // PCI spec §6.1
}
idsel = (this->config_addr >> 11) & 0x1FFFFFU;
if (!SINGLE_BIT_SET(idsel)) {
LOG_F(
ERROR, "%s: read invalid IDSEL=0x%X config:0x%X ??:??.%x? @%02x?.%c",
this->name.c_str(), idsel, this->config_addr,
fun_num, reg_offs + (offset & 3),
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size
);
return 0xFFFFFFFFUL; // PCI spec §6.1
}
if (this->dev_map.count(idsel)) {
result = this->dev_map[idsel]->pci_cfg_read(reg_offs, size);
} else {
dev_num = WHAT_BIT_SET(idsel) + 11;
LOG_F(
ERROR, "%s err: read attempt from non-existing VCI device ??:%02x.%x @%02x.%c",
this->name.c_str(), dev_num, fun_num, reg_offs + (offset & 3),
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size
);
return 0xFFFFFFFFUL; // PCI spec §6.1
}
} else {
result = this->config_addr;
}
} else { // I/O space access
LOG_F(ERROR, "%s: I/O space not supported", this->name.c_str());
return 0;
}
return result;
}
void Chaos::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size)
{
int bus_num, dev_num, fun_num;
uint8_t reg_offs;
uint32_t idsel;
if (offset & BANDIT_CONFIG_SPACE) {
if (offset & 0x00400000) {
fun_num = (this->config_addr >> 8) & 7;
reg_offs = this->config_addr & 0xFCU;
// access to the CONFIG_DATA pseudo-register causes a Config Cycle
if (this->config_addr & BANDIT_CAR_TYPE) {
bus_num = (this->config_addr >> 16) & 255;
dev_num = (this->config_addr >> 11) & 31;
LOG_F(
WARNING, "%s: write config cycle type 1 not supported yet %02x:%02x.%x @%02x.%c = %0*x",
this->name.c_str(), bus_num, dev_num, fun_num, reg_offs + (offset & 3),
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size, size * 2, value
);
return;
}
idsel = (this->config_addr >> 11) & 0x1FFFFFU;
if (!SINGLE_BIT_SET(idsel)) {
LOG_F(
ERROR, "%s: write invalid IDSEL=0x%X config:0x%X ??:??.%x? @%02x?.%c = %0*x",
this->name.c_str(), idsel, this->config_addr,
fun_num, reg_offs + (offset & 3),
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size, size * 2, value
);
return;
}
if (this->dev_map.count(idsel)) {
this->dev_map[idsel]->pci_cfg_write(reg_offs, value, size);
} else {
dev_num = WHAT_BIT_SET(idsel) + 11;
LOG_F(
ERROR, "%s err: write attempt to non-existing VCI device ??:%02x.%x @%02x.%c = %0*x",
this->name.c_str(), dev_num, fun_num, reg_offs + (offset & 3),
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size, size * 2, value
);
}
} else {
this->config_addr = BYTESWAP_32(value);
}
} else { // I/O space access
LOG_F(ERROR, "%s: I/O space not supported", this->name.c_str());
}
}
static const DeviceDescription Bandit1_Descriptor = {
Bandit::create_first, {}, Bandit_Properties
};
static const DeviceDescription PsxPci1_Descriptor = {
Bandit::create_psx_first, {}, {}
Bandit::create_first, {}, {}
};
static const DeviceDescription Chaos_Descriptor = {
@@ -307,5 +402,4 @@ static const DeviceDescription Chaos_Descriptor = {
};
REGISTER_DEVICE(Bandit1, Bandit1_Descriptor);
REGISTER_DEVICE(PsxPci1, PsxPci1_Descriptor);
REGISTER_DEVICE(Chaos, Chaos_Descriptor);
REGISTER_DEVICE(Chaos, Chaos_Descriptor);
+35 -77
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -19,19 +19,10 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** Bandit/Chaos ARBus-to-PCI bridge definitions.
/** Bandit ARBus-to-PCI bridge definitions.
Bandit is a custom ARBus-to-PCI bridge used in the second generation
of the Power Macintosh computer equipped with the PCI bus.
Chaos is a custom ARBus-to-PCI bridge that provides a specialized
PCI-like bus for video called VCI. This 64-bit bus runs at the same
frequency as the CPU bus (40-50 MHz) and connects video input/output
devices with the CPU bus.
Chaos seems to be a Bandit variant without PCI configuration space.
It's assumed to be present in some PCI Power Macintosh models of the
first generation.
The Bandit ASIC is a custom ARBus-to-PCI bridge used in the second
generation of the Power Macintosh computer equipped with the PCI bus.
*/
#ifndef BANDIT_PCI_H
@@ -45,92 +36,51 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cinttypes>
#include <memory>
#include <string>
#include <unordered_map>
#define BANDIT_DEV (11) // Bandit's own device number
#define BANDIT_ID_SEL (1 << 0) // Bandit's own IDSEL
#define BANDIT_CAR_TYPE (1 << 0) // Bandit config address type bit
/* Convenient macros for parsing CONFIG_ADDR fields. */
#define BUS_NUM() ((this->config_addr >> 16) & 0xFFU)
#define DEV_NUM() ((this->config_addr >> 11) & 0x1FU)
#define FUN_NUM() ((this->config_addr >> 8) & 0x07U)
#define REG_NUM() ((this->config_addr ) & 0xFCU)
#define BANDIT_CONFIG_SPACE 0x00800000 // Bandit Config Space bit
/** Bandit specific configuration registers. */
enum {
BANDIT_ADDR_MASK = 0x48,
BANDIT_MODE_SELECT = 0x50,
BANDIT_ARBUS_RD_HOLD_OFF = 0x58,
BANDIT_ADDR_MASK = 0x48,
};
/** checks if one bit is set at time, return 0 if not */
#define SINGLE_BIT_SET(val) ((val) && !((val) & ((val)-1)))
/*
Common functionality for Bandit/Chaos PCI host bridge.
*/
class BanditHost : public PCIHost, public MMIODevice {
class Bandit : public PCIHost, public PCIDevice {
public:
// MMIODevice methods
uint32_t read(uint32_t rgn_start, uint32_t offset, int size);
void write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size);
int device_postinit();
protected:
uint32_t config_addr;
private:
void cfg_setup(uint32_t offset, int size, int &bus_num, int &dev_num,
int &fun_num, uint8_t &reg_offs, AccessDetails &details,
PCIDevice *&device);
};
/*
PCI device for Bandit (but not for Chaos).
*/
class BanditPciDevice : public PCIDevice {
public:
BanditPciDevice(int bridge_num, std::string name, int dev_id, int rev);
~BanditPciDevice() = default;
// PCIDevice methods
uint32_t pci_cfg_read(uint32_t reg_offs, AccessDetails &details);
void pci_cfg_write(uint32_t reg_offs, uint32_t value, AccessDetails &details);
protected:
void verbose_address_space();
private:
uint32_t addr_mask;
uint32_t mode_ctrl; // controls various chip modes/features
uint32_t rd_hold_off_cnt;
};
/*
Bandit HLE emulation class.
*/
class Bandit : public BanditHost {
public:
Bandit(int bridge_num, std::string name, int dev_id=1, int rev=3);
Bandit(int bridge_num, std::string name);
~Bandit() = default;
static std::unique_ptr<HWComponent> create_first() {
return std::unique_ptr<Bandit>(new Bandit(1, "Bandit-PCI1"));
};
static std::unique_ptr<HWComponent> create_psx_first() {
return std::unique_ptr<Bandit>(new Bandit(1, "PSX-PCI1", 8, 0));
};
uint32_t pci_cfg_read(uint32_t reg_offs, uint32_t size);
void pci_cfg_write(uint32_t reg_offs, uint32_t value, uint32_t size);
// MMIODevice methods
uint32_t read(uint32_t rgn_start, uint32_t offset, int size);
void write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size);
protected:
void verbose_address_space();
private:
uint32_t base_addr;
unique_ptr<BanditPciDevice> my_pci_device;
uint32_t base_addr;
uint32_t config_addr;
uint32_t addr_mask;
};
/**
Chaos HLE emulation class.
/** Chaos is a custom ARBus-to-PCI bridge that provides a specialized
PCI-like bus for video called VCI. This 64-bit bus runs at the same
frequency as the CPU bus (40-50 MHz) and provides an interface
between video input/output devices and the CPU bus.
*/
class Chaos : public BanditHost {
class Chaos : public PCIHost, public MMIODevice {
public:
Chaos(std::string name);
~Chaos() = default;
@@ -138,6 +88,14 @@ public:
static std::unique_ptr<HWComponent> create() {
return std::unique_ptr<Chaos>(new Chaos("VCI0"));
};
// MMIODevice methods
uint32_t read(uint32_t rgn_start, uint32_t offset, int size);
void write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size);
private:
std::string name;
uint32_t config_addr;
};
#endif // BANDIT_PCI_H
-94
View File
@@ -1,94 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** DEC 21154 PCI-to-PCI bridge emulation. */
#include <devices/common/hwcomponent.h>
#include <devices/common/pci/dec21154.h>
#include <devices/deviceregistry.h>
#include <endianswap.h>
#include <loguru.hpp>
#include <cinttypes>
DecPciBridge::DecPciBridge(std::string name) : PCIBridge(name)
{
supports_types(HWCompType::PCI_HOST | HWCompType::PCI_DEV);
// initialize PCI config header
this->vendor_id = PCI_VENDOR_DEC;
this->device_id = 0x0026;
this->class_rev = 0x06040002;
this->cache_ln_sz = 0;
this->command = 0;
this->status = 0x2B0;
}
uint32_t DecPciBridge::pci_cfg_read(uint32_t reg_offs, AccessDetails &details)
{
if (reg_offs < 64) {
return PCIBridge::pci_cfg_read(reg_offs, details);
}
switch (reg_offs) {
case CHIP_CTRL:
return (this->arb_ctrl << 16) | (this-> diag_ctrl << 8) | this->chip_ctrl;
case PSERR_EVENT_DIS:
return (this->gpio_out_en << 16) | this->pserr_event_dis;
case SEC_CLK_CTRL:
return this->sec_clock_ctrl;
default:
LOG_READ_UNIMPLEMENTED_CONFIG_REGISTER();
}
return 0;
}
void DecPciBridge::pci_cfg_write(uint32_t reg_offs, uint32_t value, AccessDetails &details)
{
if (reg_offs < 64) {
PCIBridge::pci_cfg_write(reg_offs, value, details);
return;
}
switch (reg_offs) {
case CHIP_CTRL:
this->chip_ctrl = value & 0xFFU;
this->diag_ctrl = (value >> 8) & 0xFFU;
this->arb_ctrl = value >> 16;
break;
case PSERR_EVENT_DIS:
this->pserr_event_dis = value & 0xFFU;
this->gpio_out_en = (value >> 16) & 0xFFU;
break;
case SEC_CLK_CTRL:
this->sec_clock_ctrl = value & 0xFFFFU;
break;
default:
LOG_WRITE_UNIMPLEMENTED_CONFIG_REGISTER();
}
}
static const DeviceDescription Dec21154_Descriptor = {
DecPciBridge::create, {}, {}
};
REGISTER_DEVICE(Dec21154, Dec21154_Descriptor);
-62
View File
@@ -1,62 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** DEC 21154 PCI-to-PCI bridge definitions. */
#ifndef DEC_P2P_H
#define DEC_P2P_H
#include <devices/common/pci/pcibridge.h>
#include <cinttypes>
#include <string>
enum {
CHIP_CTRL = 0x40,
PSERR_EVENT_DIS = 0x64,
SEC_CLK_CTRL = 0x68,
};
class DecPciBridge : public PCIBridge {
public:
DecPciBridge(std::string name);
~DecPciBridge() = default;
static std::unique_ptr<HWComponent> create() {
return std::unique_ptr<DecPciBridge>(new DecPciBridge("DEC21154"));
}
// PCIDevice methods
uint32_t pci_cfg_read(uint32_t reg_offs, AccessDetails &details);
void pci_cfg_write(uint32_t reg_offs, uint32_t value, AccessDetails &details);
private:
uint8_t chip_ctrl = 0;
uint8_t diag_ctrl = 0;
uint16_t arb_ctrl = 0x0200;
uint8_t pserr_event_dis = 0;
uint8_t gpio_out_data = 0;
uint8_t gpio_out_en = 0;
uint8_t gpio_in_data = 0;
uint16_t sec_clock_ctrl = 0;
};
#endif // DEC_P2P_H
-226
View File
@@ -1,226 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <devices/common/pci/pcibridge.h>
#include <memaccess.h>
PCIBridge::PCIBridge(std::string name) : PCIDevice(name)
{
this->num_bars = 2;
this->hdr_type = 1;
this->pci_rd_primary_bus = [this]() { return this->primary_bus; };
this->pci_rd_secondary_bus = [this]() { return this->secondary_bus; };
this->pci_rd_subordinate_bus = [this]() { return this->subordinate_bus; };
this->pci_rd_sec_latency_timer = [this]() { return this->sec_latency_timer; };
this->pci_rd_sec_status = [this]() { return this->sec_status; };
this->pci_rd_memory_base = [this]() { return this->memory_base; };
this->pci_rd_memory_limit = [this]() { return this->memory_limit; };
this->pci_rd_io_base = [this]() { return this->io_base; };
this->pci_rd_io_limit = [this]() { return this->io_limit; };
this->pci_rd_pref_mem_base = [this]() { return this->pref_mem_base; };
this->pci_rd_pref_mem_limit = [this]() { return this->pref_mem_limit; };
this->pci_rd_io_base_upper16 = [this]() { return this->io_base_upper16; };
this->pci_rd_io_limit_upper16 = [this]() { return this->io_limit_upper16; };
this->pci_rd_pref_base_upper32 = [this]() { return this->pref_base_upper32; };
this->pci_rd_pref_limit_upper32 = [this]() { return this->pref_limit_upper32; };
this->pci_rd_bridge_control = [this]() { return this->bridge_control; };
this->pci_wr_primary_bus = [this](uint8_t val) { this->primary_bus = val; };
this->pci_wr_secondary_bus = [this](uint8_t val) { this->secondary_bus = val; };
this->pci_wr_subordinate_bus = [this](uint8_t val) { this->subordinate_bus = val; };
this->pci_wr_sec_latency_timer = [this](uint8_t val) {
this->sec_latency_timer = (this->sec_latency_timer & ~this->sec_latency_timer_cfg) |
(val & this->sec_latency_timer_cfg);
};
this->pci_wr_sec_status = [this](uint16_t val) {};
this->pci_wr_memory_base = [this](uint16_t val) {
this->memory_base = (val & this->memory_cfg) | (this->memory_cfg & 15);
this->memory_base_32 = ((this->memory_base & 0xfff0) << 16);
};
this->pci_wr_memory_limit = [this](uint16_t val) {
this->memory_limit = (val & this->memory_cfg) | (this->memory_cfg & 15);
this->memory_limit_32 = ((this->memory_limit & 0xfff0) << 16) + 0x100000;
};
this->pci_wr_io_base = [this](uint8_t val) {
this->io_base = (val & this->io_cfg) | (this->io_cfg & 15);
this->io_base_32 = ((uint32_t)this->io_base_upper16 << 16) | ((this->io_base & 0xf0) << 8);
};
this->pci_wr_io_limit = [this](uint8_t val) {
this->io_limit = (val & this->io_cfg) | (this->io_cfg & 15);
this->io_limit_32 = (((uint32_t)this->io_limit_upper16 << 16) |
((this->io_limit & 0xf0) << 8)) + 0x1000;
};
this->pci_wr_pref_mem_base = [this](uint16_t val) {
this->pref_mem_base = (val & this->pref_mem_cfg) | (this->pref_mem_cfg & 15);
this->pref_mem_base_64 = ((uint64_t)this->pref_base_upper32 << 32) |
((this->pref_mem_base & 0xfff0) << 16);
};
this->pci_wr_pref_mem_limit = [this](uint16_t val) {
this->pref_mem_limit = (val & this->pref_mem_cfg) | (this->pref_mem_cfg & 15);
this->pref_mem_limit_64 = (((uint64_t)this->pref_limit_upper32 << 32) |
((this->pref_mem_limit & 0xfff0) << 16)) + 0x100000;
};
this->pci_wr_io_base_upper16 = [this](uint16_t val) {
if ((this->io_base & 15) == 1)
this->io_base_upper16 = val;
this->io_base_32 = ((uint32_t)this->io_base_upper16 << 16) |
((this->io_base & 0xf0) << 8);
};
this->pci_wr_io_limit_upper16 = [this](uint16_t val) {
if ((this->io_limit & 15) == 1)
this->io_limit_upper16 = val;
this->io_limit_32 = (((uint32_t)this->io_limit_upper16 << 16) |
((this->io_limit & 0xf0) << 8)) + 0x1000;
};
this->pci_wr_pref_base_upper32 = [this](uint32_t val) {
if ((this->pref_mem_cfg & 15) == 1)
this->pref_base_upper32 = val;
this->pref_mem_base_64 = ((uint64_t)this->pref_base_upper32 << 32) |
((this->pref_mem_base & 0xfff0) << 16);
};
this->pci_wr_pref_limit_upper32 = [this](uint32_t val) {
if ((this->pref_mem_cfg & 15) == 1)
this->pref_limit_upper32 = val;
this->pref_mem_limit_64 = (((uint64_t)this->pref_limit_upper32 << 32) |
((this->pref_mem_limit & 0xfff0) << 16)) + 0x100000;
};
this->pci_wr_bridge_control = [this](uint16_t val) { this->bridge_control = val; };
};
bool PCIBridge::pci_register_mmio_region(uint32_t start_addr, uint32_t size, PCIDevice* obj)
{
// FIXME: constrain region to memory range
return this->host_instance->pci_register_mmio_region(start_addr, size, obj);
}
bool PCIBridge::pci_unregister_mmio_region(uint32_t start_addr, uint32_t size, PCIDevice* obj)
{
return this->host_instance->pci_unregister_mmio_region(start_addr, size, obj);
}
uint32_t PCIBridge::pci_cfg_read(uint32_t reg_offs, AccessDetails &details)
{
if (reg_offs < 0x18) {
return PCIDevice::pci_cfg_read(reg_offs, details);
}
switch (reg_offs) {
case PCI_CFG_PRIMARY_BUS:
return (this->pci_rd_sec_latency_timer() << 24) |
(this->pci_rd_subordinate_bus() << 16) |
(this->pci_rd_secondary_bus() << 8) |
(this->pci_rd_primary_bus());
case PCI_CFG_IO_BASE:
return (this->pci_rd_sec_status() << 16) |
(this->pci_rd_io_limit() << 8) | (this->pci_rd_io_base());
case PCI_CFG_MEMORY_BASE:
return (this->pci_rd_memory_limit() << 16) | (this->pci_rd_memory_base());
case PCI_CFG_PREF_MEM_BASE:
return (this->pci_rd_pref_mem_limit() << 16) | (this->pci_rd_pref_mem_base());
case PCI_CFG_PREF_BASE_UPPER32:
return this->pci_rd_pref_base_upper32();
case PCI_CFG_PREF_LIMIT_UPPER32:
return this->pci_rd_pref_limit_upper32();
case PCI_CFG_IO_BASE_UPPER16:
return (this->pci_rd_io_limit_upper16() << 16) | (this->pci_rd_io_base_upper16());
case PCI_CFG_CAP_PTR:
return cap_ptr;
case PCI_CFG_BRIDGE_ROM_ADDRESS:
return exp_rom_bar;
case PCI_CFG_INTERRUPT_LINE:
return (this->pci_rd_bridge_control() << 16) | (irq_pin << 8) | irq_line;
}
LOG_READ_UNIMPLEMENTED_CONFIG_REGISTER();
return 0;
}
void PCIBridge::pci_cfg_write(uint32_t reg_offs, uint32_t value, AccessDetails &details)
{
if (reg_offs < 0x18) {
return PCIDevice::pci_cfg_write(reg_offs, value, details);
}
switch (reg_offs) {
case PCI_CFG_PRIMARY_BUS:
this->pci_wr_sec_latency_timer(value >> 24);
this->pci_wr_subordinate_bus(value >> 16);
this->pci_wr_secondary_bus(value >> 8);
this->pci_wr_primary_bus(value & 0xFFU);
break;
case PCI_CFG_IO_BASE:
this->pci_wr_sec_status(value >> 16);
this->pci_wr_io_limit(value >> 8);
this->pci_wr_io_base(value & 0xFFU);
break;
case PCI_CFG_MEMORY_BASE:
this->pci_wr_memory_limit(value >> 16);
this->pci_wr_memory_base(value & 0xFFFFU);
break;
case PCI_CFG_PREF_MEM_BASE:
this->pci_wr_pref_mem_limit(value >> 16);
this->pci_wr_pref_mem_base(value & 0xFFFFU);
break;
case PCI_CFG_PREF_BASE_UPPER32:
this->pci_wr_pref_base_upper32(value);
break;
case PCI_CFG_PREF_LIMIT_UPPER32:
this->pci_wr_pref_limit_upper32(value);
break;
case PCI_CFG_IO_BASE_UPPER16:
this->pci_wr_io_limit_upper16(value >> 16);
this->pci_wr_io_base_upper16(value & 0xFFFFU);
break;
case PCI_CFG_BRIDGE_ROM_ADDRESS:
this->pci_wr_exp_rom_bar(value);
break;
case PCI_CFG_INTERRUPT_LINE:
this->irq_line = value >> 24;
this->pci_wr_bridge_control(value >> 16);
break;
default:
LOG_WRITE_UNIMPLEMENTED_CONFIG_REGISTER();
}
}
bool PCIBridge::pci_io_read(uint32_t offset, uint32_t size, uint32_t* res)
{
if (!(this->command & 1)) return false;
if (offset < this->io_base_32 || offset + size >= this->io_limit_32) return false;
return this->pci_io_read_loop(offset, size, *res);
}
bool PCIBridge::pci_io_write(uint32_t offset, uint32_t value, uint32_t size)
{
if (!(this->command & 1)) return false;
if (offset < this->io_base_32 || offset + size >= this->io_limit_32) return false;
return this->pci_io_read_loop(offset, size, value);
}
-147
View File
@@ -1,147 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef PCI_BRIDGE_H
#define PCI_BRIDGE_H
#include <devices/deviceregistry.h>
#include <devices/common/pci/pcidevice.h>
#include <devices/common/pci/pcihost.h>
#include <cinttypes>
#include <string>
#include <unordered_map>
#include <vector>
/** PCI configuration space registers offsets */
enum {
PCI_CFG_PRIMARY_BUS = 0x18, // PRIMARY_BUS, SECONDARY_BUS, SUBORDINATE_BUS, SEC_LATENCY_TIMER
PCI_CFG_IO_BASE = 0x1C, // IO_BASE.b, IO_LIMIT.b, SEC_STATUS.w
PCI_CFG_MEMORY_BASE = 0x20, // MEMORY_BASE.w, MEMORY_LIMIT.w
PCI_CFG_PREF_MEM_BASE = 0x24, // PREF_MEMORY_BASE.w, PREF_MEMORY_LIMIT.w
PCI_CFG_PREF_BASE_UPPER32 = 0x28, // PREF_BASE_UPPER32
PCI_CFG_PREF_LIMIT_UPPER32 = 0x2c, // PREF_LIMIT_UPPER32
PCI_CFG_IO_BASE_UPPER16 = 0x30, // IO_BASE_UPPER16.w, IO_LIMIT_UPPER16.w
// PCI_CFG_CAP_PTR
PCI_CFG_BRIDGE_ROM_ADDRESS = 0x38, // BRIDGE_ROM_ADDRESS
PCI_CFG_INTERRUPT_LINE = 0x3C, // INTERRUPT_LINE.b, INTERRUPT_PIN.b, BRIDGE_CONTROL.w
};
class PCIBridge : public PCIHost, public PCIDevice {
friend class PCIHost;
public:
PCIBridge(std::string name);
~PCIBridge() = default;
// PCIHost methods
virtual bool pci_register_mmio_region(uint32_t start_addr, uint32_t size, PCIDevice* obj);
virtual bool pci_unregister_mmio_region(uint32_t start_addr, uint32_t size, PCIDevice* obj);
// PCIDevice methods
virtual uint32_t pci_cfg_read(uint32_t reg_offs, AccessDetails &details);
virtual void pci_cfg_write(uint32_t reg_offs, uint32_t value, AccessDetails &details);
virtual bool pci_io_read(uint32_t offset, uint32_t size, uint32_t* res);
virtual bool pci_io_write(uint32_t offset, uint32_t value, uint32_t size);
// MMIODevice methods
virtual uint32_t read(uint32_t rgn_start, uint32_t offset, int size) {
return 0;
};
virtual void write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size) { };
// plugin interface for using in the derived classes
std::function<uint8_t()> pci_rd_primary_bus;
std::function<void(uint8_t)> pci_wr_primary_bus;
std::function<uint8_t()> pci_rd_secondary_bus;
std::function<void(uint8_t)> pci_wr_secondary_bus;
std::function<uint8_t()> pci_rd_subordinate_bus;
std::function<void(uint8_t)> pci_wr_subordinate_bus;
std::function<uint8_t()> pci_rd_sec_latency_timer;
std::function<void(uint8_t)> pci_wr_sec_latency_timer;
std::function<uint16_t()> pci_rd_sec_status;
std::function<void(uint16_t)> pci_wr_sec_status;
std::function<uint8_t()> pci_rd_io_base;
std::function<void(uint8_t)> pci_wr_io_base;
std::function<uint8_t()> pci_rd_io_limit;
std::function<void(uint8_t)> pci_wr_io_limit;
std::function<uint16_t()> pci_rd_memory_base;
std::function<void(uint16_t)> pci_wr_memory_base;
std::function<uint16_t()> pci_rd_memory_limit;
std::function<void(uint16_t)> pci_wr_memory_limit;
std::function<uint16_t()> pci_rd_pref_mem_base;
std::function<void(uint16_t)> pci_wr_pref_mem_base;
std::function<uint16_t()> pci_rd_pref_mem_limit;
std::function<void(uint16_t)> pci_wr_pref_mem_limit;
std::function<uint32_t()> pci_rd_pref_base_upper32;
std::function<void(uint32_t)> pci_wr_pref_base_upper32;
std::function<uint32_t()> pci_rd_pref_limit_upper32;
std::function<void(uint32_t)> pci_wr_pref_limit_upper32;
std::function<uint16_t()> pci_rd_io_base_upper16;
std::function<void(uint16_t)> pci_wr_io_base_upper16;
std::function<uint16_t()> pci_rd_io_limit_upper16;
std::function<void(uint16_t)> pci_wr_io_limit_upper16;
std::function<uint16_t()> pci_rd_bridge_control;
std::function<void(uint16_t)> pci_wr_bridge_control;
protected:
// PCI configuration space state
uint8_t primary_bus = 0;
uint8_t secondary_bus = 0;
uint8_t subordinate_bus = 0;
uint8_t sec_latency_timer = 0; // if supportss r/w then must reset to 0
uint16_t sec_status = 0;
uint8_t io_base = 0;
uint8_t io_limit = 0;
uint16_t memory_base = 0;
uint16_t memory_limit = 0;
uint16_t pref_mem_base = 0;
uint16_t pref_mem_limit = 0;
uint32_t pref_base_upper32 = 0;
uint32_t pref_limit_upper32 = 0;
uint16_t io_base_upper16 = 0;
uint16_t io_limit_upper16 = 0;
uint16_t bridge_control = 0;
// 0 = not writable, 0xf8 = limits the granularity to eight PCI clocks
uint8_t sec_latency_timer_cfg = 0;
// 0 = not writable, 0xf0 = supports 16 bit io range, 0xf1 = supports 32 bit I/O range
uint8_t io_cfg = 0xf0;
// 0 = not writable, 0xfff0 = supports 32 bit memory range
uint16_t memory_cfg = 0xfff0;
// 0 = not writable, 0xfff0 = supports 32 bit prefetchable memory range,
// 0xfff1 = supports 64 bit prefetchable memory range
uint16_t pref_mem_cfg = 0xfff0;
uint32_t io_base_32 = 0;
uint32_t io_limit_32 = 0;
uint64_t memory_base_32 = 0;
uint64_t memory_limit_32 = 0;
uint64_t pref_mem_base_64 = 0;
uint64_t pref_mem_limit_64 = 0;
private:
};
#endif /* PCI_BRIDGE_H */
+112 -164
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -20,18 +20,17 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <devices/common/pci/pcidevice.h>
#include <devices/common/viacuda.h>
#include <endianswap.h>
#include <loguru.hpp>
#include <memaccess.h>
#include <cinttypes>
#include <fstream>
#include <cstring>
#include <string>
PCIDevice::PCIDevice(std::string name)
{
this->name = name;
this->pci_name = name;
this->pci_rd_stat = [this]() { return this->status; };
@@ -49,79 +48,117 @@ PCIDevice::PCIDevice(std::string name)
this->pci_notify_bar_change = [](int bar_num) {};
};
uint32_t PCIDevice::pci_cfg_read(uint32_t reg_offs, AccessDetails &details)
uint32_t PCIDevice::pci_cfg_read(uint32_t reg_offs, uint32_t size)
{
uint32_t result;
switch (reg_offs) {
case PCI_CFG_DEV_ID:
return (this->device_id << 16) | (this->vendor_id);
result = (this->device_id << 16) | (this->vendor_id);
break;
case PCI_CFG_STAT_CMD:
return (this->pci_rd_stat() << 16) | (this->pci_rd_cmd());
result = (this->pci_rd_stat() << 16) | (this->pci_rd_cmd());
break;
case PCI_CFG_CLASS_REV:
return this->class_rev;
result = this->class_rev;
break;
case PCI_CFG_DWORD_3:
return (pci_rd_bist() << 24) | (this->hdr_type << 16) |
(pci_rd_lat_timer() << 8) | pci_rd_cache_lnsz();
result = (pci_rd_bist() << 24) | (this->hdr_type << 16) |
(pci_rd_lat_timer() << 8) | pci_rd_cache_lnsz();
break;
case PCI_CFG_BAR0:
case PCI_CFG_BAR1:
case PCI_CFG_BAR2:
case PCI_CFG_BAR3:
case PCI_CFG_BAR4:
case PCI_CFG_BAR5:
return this->bars[(reg_offs - 0x10) >> 2];
result = this->bars[(reg_offs - 0x10) >> 2];
break;
case PCI_CFG_SUBSYS_ID:
return (this->subsys_id << 16) | (this->subsys_vndr);
result = (this->subsys_id << 16) | (this->subsys_vndr);
break;
case PCI_CFG_ROM_BAR:
return this->exp_rom_bar;
result = this->exp_rom_bar;
break;
case PCI_CFG_DWORD_15:
return (max_lat << 24) | (min_gnt << 16) | (irq_pin << 8) | irq_line;
result = (max_lat << 24) | (min_gnt << 16) | (irq_pin << 8) | irq_line;
break;
case PCI_CFG_CAP_PTR:
return cap_ptr;
}
LOG_READ_UNIMPLEMENTED_CONFIG_REGISTER();
return 0;
}
void PCIDevice::pci_cfg_write(uint32_t reg_offs, uint32_t value, AccessDetails &details)
{
switch (reg_offs) {
case PCI_CFG_STAT_CMD:
this->pci_wr_stat(value >> 16);
this->pci_wr_cmd(value & 0xFFFFU);
break;
case PCI_CFG_DWORD_3:
this->pci_wr_bist(value >> 24);
this->pci_wr_lat_timer((value >> 8) & 0xFF);
this->pci_wr_cache_lnsz(value & 0xFF);
break;
case PCI_CFG_BAR0:
case PCI_CFG_BAR1:
case PCI_CFG_BAR2:
case PCI_CFG_BAR3:
case PCI_CFG_BAR4:
case PCI_CFG_BAR5:
this->set_bar_value((reg_offs - 0x10) >> 2, value);
break;
case PCI_CFG_ROM_BAR:
this->pci_wr_exp_rom_bar(value);
break;
case PCI_CFG_DWORD_15:
this->irq_line = value >> 24;
result = cap_ptr;
break;
default:
LOG_WRITE_UNIMPLEMENTED_CONFIG_REGISTER();
LOG_F(
WARNING, "%s: attempt to read from reserved/unimplemented register @%02x.%c",
this->pci_name.c_str(), reg_offs,
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size
);
return 0;
}
if (size == 4) {
return BYTESWAP_32(result);
} else {
return read_mem_rev(((uint8_t *)&result) + (reg_offs & 3), size);
}
}
void PCIDevice::setup_bars(std::vector<BarConfig> cfg_data)
void PCIDevice::pci_cfg_write(uint32_t reg_offs, uint32_t value, uint32_t size)
{
for (auto cfg_entry : cfg_data) {
if (cfg_entry.bar_num > 5) {
ABORT_F("BAR number %d out of range", cfg_entry.bar_num);
}
this->bars_cfg[cfg_entry.bar_num] = cfg_entry.bar_cfg;
uint32_t data;
if (size == 4) {
data = BYTESWAP_32(value);
} else {
// get current register content as DWORD and update it partially
data = BYTESWAP_32(this->pci_cfg_read(reg_offs, 4));
write_mem_rev(((uint8_t *)&data) + (reg_offs & 3), value, size);
}
this->finish_config_bars();
switch (reg_offs) {
case PCI_CFG_STAT_CMD:
this->pci_wr_stat(data >> 16);
this->pci_wr_cmd(data & 0xFFFFU);
break;
case PCI_CFG_DWORD_3:
this->pci_wr_bist(data >> 24);
this->pci_wr_lat_timer((data >> 8) & 0xFF);
this->pci_wr_cache_lnsz(data & 0xFF);
break;
case PCI_CFG_BAR0:
case PCI_CFG_BAR1:
case PCI_CFG_BAR2:
case PCI_CFG_BAR3:
case PCI_CFG_BAR4:
case PCI_CFG_BAR5:
if (data == 0xFFFFFFFFUL) {
this->do_bar_sizing((reg_offs - 0x10) >> 2);
} else {
this->set_bar_value((reg_offs - 0x10) >> 2, data);
}
break;
case PCI_CFG_ROM_BAR:
if (data == 0xFFFFF800UL) {
this->exp_rom_bar = this->exp_bar_cfg;
} else {
this->exp_rom_bar = (data & 0xFFFFF801UL);
if (this->exp_rom_bar & 1) {
this->map_exp_rom_mem();
} else {
LOG_F(WARNING, "%s: unmapping of expansion ROM not implemented yet",
this->pci_name.c_str());
}
}
break;
case PCI_CFG_DWORD_15:
this->irq_line = data >> 24;
break;
default:
LOG_F(
WARNING, "%s: attempt to write to reserved/unimplemented register @%02x.%c = %0*x",
this->pci_name.c_str(), reg_offs,
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size, size * 2, value
);
}
}
int PCIDevice::attach_exp_rom_image(const std::string img_path)
@@ -150,13 +187,10 @@ int PCIDevice::attach_exp_rom_image(const std::string img_path)
// determine image size
img_file.seekg(0, std::ios::end);
size_t exp_rom_image_size = img_file.tellg();
if (exp_rom_image_size > 4*1024*1024) {
throw std::runtime_error("expansion ROM file too large");
}
uint32_t exp_rom_image_size = img_file.tellg();
// verify PCI struct offset
uint16_t pci_struct_offset = 0;
uint32_t pci_struct_offset = 0;
img_file.seekg(0x18, std::ios::beg);
img_file.read((char *)&pci_struct_offset, sizeof(pci_struct_offset));
@@ -182,12 +216,10 @@ int PCIDevice::attach_exp_rom_image(const std::string img_path)
memset(&this->exp_rom_data[exp_rom_image_size], 0xff, this->exp_rom_size - exp_rom_image_size);
if (exp_rom_image_size == this->exp_rom_size) {
LOG_F(INFO, "%s: loaded expansion rom (%d bytes).",
this->pci_name.c_str(), this->exp_rom_size);
LOG_F(INFO, "%s: loaded expansion rom (%d bytes).", this->pci_name.c_str(), this->exp_rom_size);
}
else {
LOG_F(WARNING, "%s: loaded expansion rom (%d bytes adjusted to %d bytes).",
this->pci_name.c_str(), (int)exp_rom_image_size, this->exp_rom_size);
LOG_F(WARNING, "%s: loaded expansion rom (%d bytes adjusted to %d bytes).", this->pci_name.c_str(), exp_rom_image_size, this->exp_rom_size);
}
this->exp_bar_cfg = ~(this->exp_rom_size - 1);
@@ -202,118 +234,34 @@ int PCIDevice::attach_exp_rom_image(const std::string img_path)
return result;
}
void PCIDevice::do_bar_sizing(int bar_num)
{
this->bars[bar_num] = this->bars_cfg[bar_num];
}
void PCIDevice::set_bar_value(int bar_num, uint32_t value)
{
uint32_t bar_cfg = this->bars_cfg[bar_num];
switch (bars_typ[bar_num]) {
case PCIBarType::Unused:
return;
case PCIBarType::Io_16_Bit:
case PCIBarType::Io_32_Bit:
this->bars[bar_num] = (value & bar_cfg & ~3) | (bar_cfg & 3);
break;
case PCIBarType::Mem_20_Bit:
case PCIBarType::Mem_32_Bit:
case PCIBarType::Mem_64_Bit_Lo:
this->bars[bar_num] = (value & bar_cfg & ~0xF) | (bar_cfg & 0xF);
break;
case PCIBarType::Mem_64_Bit_Hi:
this->bars[bar_num] = value & bar_cfg;
break;
if (bar_cfg & 1) {
this->bars[bar_num] = (value & 0xFFFFFFFCUL) | 1;
} else {
if (bar_cfg & 6) {
ABORT_F("Invalid or unsupported PCI space type: %d", (bar_cfg >> 1) & 3);
}
this->bars[bar_num] = (value & 0xFFFFFFF0UL) | (bar_cfg & 0xF);
}
if (value != 0xFFFFFFFFUL) // don't notify the device during BAR sizing
this->pci_notify_bar_change(bar_num);
}
void PCIDevice::finish_config_bars()
{
for (int bar_num = 0; bar_num < this->num_bars; bar_num++) {
uint32_t bar_cfg = this->bars_cfg[bar_num];
if (!bar_cfg) // skip unimplemented BARs
continue;
if (bar_cfg & 1) {
bars_typ[bar_num] = (bar_cfg & 0xffff0000) ? PCIBarType::Io_32_Bit :
PCIBarType::Io_16_Bit;
has_io_space = true;
}
else {
int pci_space_type = (bar_cfg >> 1) & 3;
switch (pci_space_type) {
case 0:
bars_typ[bar_num] = PCIBarType::Mem_32_Bit;
break;
case 1:
bars_typ[bar_num] = PCIBarType::Mem_20_Bit;
break;
case 2:
if (bar_num >= num_bars - 1) {
ABORT_F("%s: BAR %d cannot be 64-bit",
this->pci_name.c_str(), bar_num);
}
else if (this->bars_cfg[bar_num+1] == 0) {
ABORT_F("%s: 64-bit BAR %d has zero for upper 32 bits",
this->pci_name.c_str(), bar_num);
}
else {
bars_typ[bar_num++] = PCIBarType::Mem_64_Bit_Lo;
bars_typ[bar_num ] = PCIBarType::Mem_64_Bit_Hi;
}
break;
default:
ABORT_F("%s: invalid or unsupported PCI space type %d for BAR %d",
this->pci_name.c_str(), pci_space_type, bar_num);
} // switch pci_space_type
}
} // for bar_num
this->pci_notify_bar_change(bar_num);
}
void PCIDevice::map_exp_rom_mem()
{
uint32_t rom_addr = this->exp_rom_bar & this->exp_bar_cfg;
if (rom_addr) {
if (this->exp_rom_addr != rom_addr) {
this->unmap_exp_rom_mem();
uint32_t rom_size = ~this->exp_bar_cfg + 1;
uint32_t rom_addr, rom_size;
rom_addr = this->exp_rom_bar & 0xFFFFF800UL;
rom_size = ~this->exp_bar_cfg + 1;
if (!this->exp_rom_addr || this->exp_rom_addr != rom_addr) {
this->host_instance->pci_register_mmio_region(rom_addr, rom_size, this);
this->exp_rom_addr = rom_addr;
}
}
else {
this->unmap_exp_rom_mem();
}
}
void PCIDevice::unmap_exp_rom_mem()
{
if (this->exp_rom_addr) {
uint32_t rom_size = ~this->exp_bar_cfg + 1;
this->host_instance->pci_unregister_mmio_region(exp_rom_addr, rom_size, this);
this->exp_rom_addr = 0;
}
}
void PCIDevice::pci_wr_exp_rom_bar(uint32_t data)
{
if (!this->exp_bar_cfg) {
return;
}
if ((data & this->exp_bar_cfg) == this->exp_bar_cfg) {
// doing sizing
this->exp_rom_bar = (data & (this->exp_bar_cfg | 1));
} else {
this->exp_rom_bar = (data & (this->exp_bar_cfg | 1));
if (this->exp_rom_bar & 1) {
this->map_exp_rom_mem();
}
else {
this->unmap_exp_rom_mem();
}
}
}
+9 -118
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -29,7 +29,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <functional>
#include <memory>
#include <string>
#include <vector>
/** PCI configuration space registers offsets */
enum {
@@ -54,27 +53,10 @@ enum {
/** 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_NVIDIA = 0x10DE,
};
/** PCI BAR types */
enum PCIBarType : uint32_t {
Unused = 0,
Io_16_Bit,
Io_32_Bit,
Mem_20_Bit, // legacy type for < 1MB memory
Mem_32_Bit,
Mem_64_Bit_Lo,
Mem_64_Bit_Hi
};
typedef struct {
uint32_t bar_num;
uint32_t bar_cfg;
} BarConfig;
class PCIDevice : public MMIODevice {
public:
@@ -82,7 +64,7 @@ public:
virtual ~PCIDevice() = default;
virtual bool supports_io_space() {
return has_io_space;
return false;
};
/* I/O space access methods */
@@ -95,8 +77,8 @@ public:
};
// configuration space access methods
virtual uint32_t pci_cfg_read(uint32_t reg_offs, AccessDetails &details);
virtual void pci_cfg_write(uint32_t reg_offs, uint32_t value, AccessDetails &details);
virtual uint32_t pci_cfg_read(uint32_t reg_offs, uint32_t size);
virtual void pci_cfg_write(uint32_t reg_offs, uint32_t value, uint32_t size);
// plugin interface for using in the derived classes
std::function<uint16_t()> pci_rd_stat;
@@ -118,24 +100,10 @@ public:
this->host_instance = host_instance;
};
virtual void set_multi_function(bool is_multi_function) {
this->hdr_type = is_multi_function ? (this->hdr_type | 0x80) : (this->hdr_type & 0x7f);
}
virtual void set_irq_pin(uint8_t irq_pin) {
this->irq_pin = irq_pin;
}
// MMIODevice methods
virtual uint32_t read(uint32_t rgn_start, uint32_t offset, int size) { return 0; }
virtual void write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size) { }
protected:
void do_bar_sizing(int bar_num);
void set_bar_value(int bar_num, uint32_t value);
void setup_bars(std::vector<BarConfig> cfg_data);
void finish_config_bars();
void pci_wr_exp_rom_bar(uint32_t data);
void map_exp_rom_mem();
void unmap_exp_rom_mem();
std::string pci_name; // human-readable device name
PCIHost* host_instance; // host bridge instance to call back
@@ -143,12 +111,12 @@ protected:
// PCI configuration space state
uint16_t vendor_id;
uint16_t device_id;
uint32_t class_rev; // class code and revision id
uint32_t class_rev; // class code and revision id
uint16_t status = 0;
uint16_t command = 0;
uint8_t hdr_type = 0; // header type, single function
uint8_t lat_timer = 0; // latency timer
uint8_t cache_ln_sz = 0; // cache line size
uint8_t hdr_type = 0; // header type
uint8_t lat_timer = 0; // latency timer
uint8_t cache_ln_sz = 0; // cache line size
uint16_t subsys_id = 0;
uint16_t subsys_vndr = 0;
uint8_t cap_ptr = 0;
@@ -157,11 +125,8 @@ protected:
uint8_t irq_pin = 0;
uint8_t irq_line = 0;
bool has_io_space = false;
int num_bars = 6;
uint32_t bars[6] = { 0 }; // base address registers
uint32_t bars_cfg[6] = { 0 }; // configuration values for base address registers
PCIBarType bars_typ[6] = { PCIBarType::Unused }; // types for base address registers
uint32_t exp_bar_cfg = 0; // expansion ROM configuration
uint32_t exp_rom_bar = 0; // expansion ROM base address register
@@ -171,78 +136,4 @@ protected:
std::unique_ptr<uint8_t[]> exp_rom_data;
};
inline uint32_t pci_cfg_log(uint32_t value, AccessDetails &details) {
switch (details.size << 2 | details.offset) {
case 0x04: return (uint8_t) value;
case 0x05: return (uint8_t)(value >> 8);
case 0x06: return (uint8_t)(value >> 16);
case 0x07: return (uint8_t)(value >> 24);
case 0x08: return (uint16_t) value;
case 0x09: return (uint16_t) (value >> 8);
case 0x0a: return (uint16_t) (value >> 16);
case 0x0b: return (uint16_t)((value >> 24) | (value << 8));
case 0x10: return value;
case 0x11: return (value >> 8) | (value << 24);
case 0x12: return (value >> 16) | (value << 16);
case 0x13: return (value >> 24) | (value << 8);
default: return 0xffffffff;
}
}
#define SIZE_ARGS details.size == 4 ? 'l' : details.size == 2 ? 'w' : \
details.size == 1 ? 'b' : '0' + details.size
#define LOG_READ_UNIMPLEMENTED_CONFIG_REGISTER() \
do { if ((details.flags & PCI_CONFIG_DIRECTION) == PCI_CONFIG_READ) { \
VLOG_F( \
(~-details.size & details.offset) ? loguru::Verbosity_ERROR : loguru::Verbosity_WARNING, \
"%s: read unimplemented config register @%02x.%c", \
this->name.c_str(), reg_offs + details.offset, \
SIZE_ARGS \
); \
} } while(0)
#define LOG_NAMED_CONFIG_REGISTER(reg_verb, reg_name) \
VLOG_F( \
(~-details.size & details.offset) ? loguru::Verbosity_ERROR : loguru::Verbosity_WARNING, \
"%s: %s %s register @%02x.%c = %0*x", \
this->name.c_str(), reg_verb, reg_name, reg_offs + details.offset, \
SIZE_ARGS, \
details.size * 2, pci_cfg_log(value, details) \
)
#define LOG_READ_NAMED_CONFIG_REGISTER(reg_name) \
do { if ((details.flags & PCI_CONFIG_DIRECTION) == PCI_CONFIG_READ) { \
LOG_NAMED_CONFIG_REGISTER("read ", reg_name); \
} } while(0)
#define LOG_WRITE_NAMED_CONFIG_REGISTER(reg_name) \
LOG_NAMED_CONFIG_REGISTER("write", reg_name)
#define LOG_READ_UNIMPLEMENTED_CONFIG_REGISTER_WITH_VALUE() \
LOG_READ_NAMED_CONFIG_REGISTER("unimplemented config")
#define LOG_WRITE_UNIMPLEMENTED_CONFIG_REGISTER() \
LOG_WRITE_NAMED_CONFIG_REGISTER("unimplemented config")
#define LOG_READ_NON_EXISTENT_PCI_DEVICE() \
LOG_F( \
ERROR, \
"%s err: read attempt from non-existent PCI device %02x:%02x.%x @%02x.%c", \
this->name.c_str(), bus_num, dev_num, fun_num, reg_offs + details.offset, \
SIZE_ARGS \
)
#define LOG_WRITE_NON_EXISTENT_PCI_DEVICE() \
LOG_F( \
ERROR, \
"%s err: write attempt to non-existent PCI device %02x:%02x.%x @%02x.%c = %0*x", \
this->name.c_str(), bus_num, dev_num, fun_num, reg_offs + details.offset, \
SIZE_ARGS, \
details.size * 2, BYTESWAP_SIZED(value, details.size) \
)
#endif /* PCI_DEVICE_H */
+13 -131
View File
@@ -20,50 +20,28 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <devices/common/hwcomponent.h>
#include <devices/common/pci/pcibridge.h>
#include <devices/common/pci/pcidevice.h>
#include <devices/common/pci/pcihost.h>
#include <devices/memctrl/memctrlbase.h>
#include <machines/machinebase.h>
#include <endianswap.h>
#include <loguru.hpp>
#include <cinttypes>
bool PCIHost::pci_register_device(int dev_fun_num, PCIDevice* dev_instance)
bool PCIHost::pci_register_device(int dev_num, PCIDevice* dev_instance)
{
// return false if dev_fun_num already registered
if (this->dev_map.count(dev_fun_num))
// return false if dev_num already registered
if (this->dev_map.count(dev_num))
return false;
int fun_num = dev_fun_num & 7;
int dev_num = (dev_fun_num >> 3) & 0x1f;
bool is_multi_function = fun_num != 0;
for (int other_fun_num = 0; other_fun_num < 8; other_fun_num++) {
if (this->dev_map.count(DEV_FUN(dev_num, other_fun_num))) {
is_multi_function = true;
if (is_multi_function && other_fun_num == 0) {
this->dev_map[DEV_FUN(dev_num, other_fun_num)]->set_multi_function(true);
}
}
}
this->dev_map[dev_fun_num] = dev_instance;
this->dev_map[dev_num] = dev_instance;
dev_instance->set_host(this);
if (is_multi_function && fun_num == 0) {
dev_instance->set_multi_function(true);
}
if (dev_instance->supports_io_space()) {
this->io_space_devs.push_back(dev_instance);
}
PCIBridge *bridge = dynamic_cast<PCIBridge*>(dev_instance);
if (bridge) {
this->bridge_devs.push_back(bridge);
}
return true;
}
@@ -75,121 +53,25 @@ bool PCIHost::pci_register_mmio_region(uint32_t start_addr, uint32_t size, PCIDe
return mem_ctrl->add_mmio_region(start_addr, size, obj);
}
bool PCIHost::pci_unregister_mmio_region(uint32_t start_addr, uint32_t size, PCIDevice* obj)
{
MemCtrlBase *mem_ctrl = dynamic_cast<MemCtrlBase *>
(gMachineObj->get_comp_by_type(HWCompType::MEM_CTRL));
// FIXME: add sanity checks!
return mem_ctrl->remove_mmio_region(start_addr, size, obj);
}
void PCIHost::attach_pci_device(const std::string& dev_name, int slot_id)
{
this->attach_pci_device(dev_name, slot_id, "");
}
PCIDevice *PCIHost::attach_pci_device(const std::string& dev_name, int slot_id, const std::string& dev_suffix)
void PCIHost::attach_pci_device(std::string& dev_name, int slot_id)
{
if (!DeviceRegistry::device_registered(dev_name)) {
HWComponent *hwc = dynamic_cast<HWComponent*>(this);
LOG_F(
WARNING, "%s: specified PCI device %s doesn't exist",
hwc ? hwc->get_name().c_str() : "PCIHost", dev_name.c_str()
);
return NULL;
LOG_F(WARNING, "PCIHost: specified PCI device %s doesn't exist", dev_name.c_str());
return;
}
// attempt to create device object
auto dev_obj = DeviceRegistry::get_descriptor(dev_name).m_create_func();
if (!dev_obj->supports_type(HWCompType::PCI_DEV)) {
HWComponent *hwc = dynamic_cast<HWComponent*>(this);
LOG_F(
WARNING, "%s: cannot attach non-PCI device %s",
hwc ? hwc->get_name().c_str() : "PCIHost", dev_name.c_str()
);
return NULL;
LOG_F(WARNING, "PCIHost: cannot attach non-PCI device %s", dev_name.c_str());
return;
}
// add device to the machine object
gMachineObj->add_device(dev_name + dev_suffix, std::move(dev_obj));
PCIDevice *dev = dynamic_cast<PCIDevice*>(gMachineObj->get_comp_by_name(dev_name + dev_suffix));
gMachineObj->add_device(dev_name, std::move(dev_obj));
// register device with the PCI host
this->pci_register_device(slot_id, dev);
return dev;
}
bool PCIHost::pci_io_read_loop(uint32_t offset, int size, uint32_t &res)
{
for (auto& dev : this->io_space_devs) {
if (dev->pci_io_read(offset, size, &res)) {
return true;
}
}
return false;
}
bool PCIHost::pci_io_write_loop(uint32_t offset, int size, uint32_t value)
{
for (auto& dev : this->io_space_devs) {
if (dev->pci_io_write(offset, value, size)) {
return true;
}
}
return false;
}
uint32_t PCIHost::pci_io_read_broadcast(uint32_t offset, int size)
{
uint32_t res;
// broadcast I/O request to devices that support I/O space
// until a device returns true that means "request accepted"
if (pci_io_read_loop (offset, size, res)) {
return res;
}
HWComponent *hwc = dynamic_cast<HWComponent*>(this);
LOG_F(
ERROR, "%s: Attempt to read from unmapped PCI I/O space @%08x.%c",
hwc ? hwc->get_name().c_str() : "PCIHost", offset,
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size
);
// FIXME: add machine check exception (DEFAULT CATCH!, code=FFF00200)
return 0;
}
void PCIHost::pci_io_write_broadcast(uint32_t offset, int size, uint32_t value)
{
// broadcast I/O request to devices that support I/O space
// until a device returns true that means "request accepted"
if (pci_io_write_loop(offset, size, value)) {
return;
}
HWComponent *hwc = dynamic_cast<HWComponent*>(this);
LOG_F(
ERROR, "%s: Attempt to write to unmapped PCI I/O space @%08x.%c = %0*x",
hwc ? hwc->get_name().c_str() : "PCIHost", offset,
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size,
size * 2, BYTESWAP_SIZED(value, size)
);
}
PCIDevice *PCIHost::pci_find_device(uint8_t bus_num, uint8_t dev_num, uint8_t fun_num)
{
for (auto& bridge : this->bridge_devs) {
if (bridge->secondary_bus <= bus_num) {
if (bridge->secondary_bus == bus_num) {
if (bridge->dev_map.count(DEV_FUN(dev_num, fun_num))) {
return bridge->dev_map[DEV_FUN(dev_num, fun_num)];
}
}
else if (bridge->subordinate_bus >= bus_num) {
return bridge->pci_find_device(bus_num, dev_num, fun_num);
}
}
}
return NULL;
this->pci_register_device(
slot_id, dynamic_cast<PCIDevice*>(gMachineObj->get_comp_by_name(dev_name)));
}
+3 -133
View File
@@ -22,37 +22,14 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef PCI_HOST_H
#define PCI_HOST_H
#include <core/bitops.h>
#include <devices/deviceregistry.h>
#include <endianswap.h>
#include <array>
#include <cinttypes>
#include <string>
#include <unordered_map>
#include <vector>
enum {
PCI_CONFIG_DIRECTION = 1,
PCI_CONFIG_READ = 0,
PCI_CONFIG_WRITE = 1,
PCI_CONFIG_TYPE = 4,
PCI_CONFIG_TYPE_0 = 0,
PCI_CONFIG_TYPE_1 = 4,
};
/** PCI config space access details */
typedef struct AccessDetails {
uint8_t size;
uint8_t offset;
uint8_t flags;
} AccessDetails;
#define DEV_FUN(dev_num,fun_num) (((dev_num) << 3) | (fun_num))
class PCIDevice;
class PCIBridge;
class PCIDevice; // forward declaration to prevent errors
class PCIHost {
public:
@@ -62,122 +39,15 @@ public:
};
~PCIHost() = default;
virtual bool pci_register_device(int dev_fun_num, PCIDevice* dev_instance);
virtual bool pci_register_device(int dev_num, PCIDevice* dev_instance);
virtual bool pci_register_mmio_region(uint32_t start_addr, uint32_t size, PCIDevice* obj);
virtual bool pci_unregister_mmio_region(uint32_t start_addr, uint32_t size, PCIDevice* obj);
virtual void attach_pci_device(const std::string& dev_name, int slot_id);
PCIDevice *attach_pci_device(const std::string& dev_name, int slot_id,
const std::string& dev_suffix);
virtual bool pci_io_read_loop (uint32_t offset, int size, uint32_t &res);
virtual bool pci_io_write_loop(uint32_t offset, int size, uint32_t value);
virtual uint32_t pci_io_read_broadcast (uint32_t offset, int size);
virtual void pci_io_write_broadcast(uint32_t offset, int size, uint32_t value);
virtual PCIDevice *pci_find_device(uint8_t bus_num, uint8_t dev_num, uint8_t fun_num);
virtual uint32_t pci_t1_read(uint8_t dev, uint32_t fun, uint32_t reg, AccessDetails &details) {
return 0;
};
virtual void pci_t1_write(uint8_t dev, uint32_t fun, uint32_t reg, uint32_t value,
AccessDetails &details) {};
virtual void attach_pci_device(std::string& dev_name, int slot_id);
protected:
std::unordered_map<int, PCIDevice*> dev_map;
std::vector<PCIDevice*> io_space_devs;
std::vector<PCIBridge*> bridge_devs;
};
// Helpers for data conversion in the PCI Configuration space.
/**
Perform size dependent endian swapping for value that is dword from PCI config.
Unaligned data is handled properly by wrapping around if needed.
*/
inline uint32_t pci_conv_rd_data(uint32_t value, AccessDetails &details) {
switch (details.size << 2 | details.offset) {
// Bytes
case 0x04:
return value & 0xFF; // 0
case 0x05:
return (value >> 8) & 0xFF; // 1
case 0x06:
return (value >> 16) & 0xFF; // 2
case 0x07:
return (value >> 24) & 0xFF; // 3
// Words
case 0x08:
return BYTESWAP_16(value); // 0 1
case 0x09:
return BYTESWAP_16((value >> 8) & 0xFFFFU); // 1 2
case 0x0A:
return BYTESWAP_16((value >> 16) & 0xFFFFU); // 2 3
case 0x0B:
return ((value >> 16) & 0xFF00) | (value & 0xFF); // 3 0
// Dwords
case 0x10:
return BYTESWAP_32(value); // 0 1 2 3
case 0x11:
return ROTL_32(BYTESWAP_32(value), 8); // 1 2 3 0
case 0x12:
return ROTL_32(BYTESWAP_32(value), 16); // 2 3 0 1
case 0x13:
return ROTR_32(BYTESWAP_32(value), 8); // 3 0 1 2
default:
return 0xFFFFFFFFUL;
}
}
/**
Perform size dependent endian swapping for v2, then merge v2 with v1 under
control of a mask generated according with the size parameter.
Unaligned data is handled properly by wrapping around if needed.
*/
inline uint32_t pci_conv_wr_data(uint32_t v1, uint32_t v2, AccessDetails &details)
{
switch (details.size << 2 | details.offset) {
// Bytes
case 0x04:
return (v1 & ~0xFF) | (v2 & 0xFF); // 3 2 1 d0
case 0x05:
return (v1 & ~0xFF00) | ((v2 & 0xFF) << 8); // 3 2 d0 0
case 0x06:
return (v1 & ~0xFF0000) | ((v2 & 0xFF) << 16); // 3 d0 1 0
case 0x07:
return (v1 & 0x00FFFFFF) | ((v2 & 0xFF) << 24); // d0 2 1 0
// Words
case 0x08:
return (v1 & ~0xFFFF) | BYTESWAP_16(v2); // 3 2 d1 d0
case 0x09:
return (v1 & ~0xFFFF00) | (BYTESWAP_16(v2) << 8); // 3 d1 d0 0
case 0x0a:
return (v1 & 0x0000FFFF) | (BYTESWAP_16(v2) << 16); // d1 d0 1 0
case 0x0b:
return (v1 & 0x00FFFF00) | ((v2 & 0xFF00) << 16) |
(v2 & 0xFF); // d0 2 1 d1
// Dwords
case 0x10:
return BYTESWAP_32(v2); // d3 d2 d1 d0
case 0x11:
return ROTL_32(BYTESWAP_32(v2), 8); // d2 d1 d0 d3
case 0x12:
return ROTL_32(BYTESWAP_32(v2), 16); // d1 d0 d3 d2
case 0x13:
return ROTR_32(BYTESWAP_32(v2), 8); // d0 d3 d2 d1
default:
return 0xFFFFFFFFUL;
}
}
#endif /* PCI_HOST_H */
+14 -181
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-21 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -21,57 +21,22 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file MESH (Macintosh Enhanced SCSI Hardware) controller emulation. */
#include <core/timermanager.h>
#include <devices/common/hwinterrupt.h>
#include <devices/common/scsi/mesh.h>
#include <devices/deviceregistry.h>
#include <loguru.hpp>
#include <machines/machinebase.h>
#include <cinttypes>
#include <loguru.hpp>
using namespace MeshScsi;
int MeshController::device_postinit()
{
this->bus_obj = dynamic_cast<ScsiBus*>(gMachineObj->get_comp_by_name("SCSI0"));
this->int_ctrl = dynamic_cast<InterruptCtrl*>(
gMachineObj->get_comp_by_type(HWCompType::INT_CTRL));
this->irq_id = this->int_ctrl->register_dev_int(IntSrc::SCSI1);
return 0;
}
void MeshController::reset(bool is_hard_reset)
{
this->cur_cmd = SeqCmd::NoOperation;
this->int_mask = 0;
if (is_hard_reset) {
this->bus_stat = 0;
this->sync_params = 2; // guessed
}
}
uint8_t MeshController::read(uint8_t reg_offset)
uint8_t MESHController::read(uint8_t reg_offset)
{
switch(reg_offset) {
case MeshReg::Sequence:
return this->cur_cmd;
case MeshReg::BusStatus0:
return this->bus_obj->test_ctrl_lines(0xFFU);
case MeshReg::BusStatus1:
return this->bus_obj->test_ctrl_lines(0xE000U) >> 8;
case MeshReg::Exception:
LOG_F(9, "MESH: read from BusStatus0 register");
return 0;
case MeshReg::Error:
return 0;
case MeshReg::IntMask:
return this->int_mask;
case MeshReg::Interrupt:
return this->int_stat;
case MeshReg::MeshID:
LOG_F(INFO, "MESH: read from MeshID register");
return this->chip_id; // tell them who we are
default:
LOG_F(WARNING, "MESH: read from unimplemented register at offset 0x%x", reg_offset);
@@ -80,166 +45,34 @@ uint8_t MeshController::read(uint8_t reg_offset)
return 0;
}
void MeshController::write(uint8_t reg_offset, uint8_t value)
void MESHController::write(uint8_t reg_offset, uint8_t value)
{
uint16_t new_stat;
switch(reg_offset) {
case MeshReg::Sequence:
perform_command(value);
LOG_F(INFO, "MESH: write 0x%02X to Sequence register", value);
break;
case MeshReg::BusStatus1:
new_stat = value << 8;
if (new_stat != this->bus_stat) {
for (uint16_t mask = SCSI_CTRL_RST; mask >= SCSI_CTRL_SEL; mask >>= 1) {
if ((new_stat ^ this->bus_stat) & mask) {
if (new_stat & mask)
this->bus_obj->assert_ctrl_line(new_stat, mask);
else
this->bus_obj->release_ctrl_line(new_stat, mask);
}
}
this->bus_stat = new_stat;
}
LOG_F(INFO, "MESH: write 0x%02X to BusStatus1 register", value);
break;
case MeshReg::IntMask:
this->int_mask = value;
LOG_F(INFO, "MESH: write 0x%02X to IntMask register", value);
break;
case MeshReg::Interrupt:
this->int_stat &= ~(value & INT_MASK); // clear requested interrupt bits
update_irq();
LOG_F(INFO, "MESH: write 0x%02X to Interrupt register", value);
break;
case MeshReg::SourceID:
this->src_id = value;
break;
case MeshReg::DestID:
this->dst_id = value;
LOG_F(INFO, "MESH: write 0x%02X to SourceID register", value);
break;
case MeshReg::SyncParms:
this->sync_params = value;
break;
case MeshReg::SelTimeOut:
LOG_F(9, "MESH: selection timeout set to 0x%x", value);
LOG_F(INFO, "MESH: write 0x%02X to SyncParms register", value);
break;
default:
LOG_F(WARNING, "MESH: write to unimplemented register at offset 0x%x",
reg_offset);
}
}
void MeshController::perform_command(const uint8_t cmd)
{
this->cur_cmd = cmd;
this->int_stat &= ~INT_CMD_DONE;
switch (this->cur_cmd & 0xF) {
case SeqCmd::Arbitrate:
this->cur_state = SeqState::BUS_FREE;
this->sequencer();
break;
case SeqCmd::Select:
this->cur_state = SeqState::SEL_BEGIN;
this->sequencer();
break;
case SeqCmd::DisReselect:
LOG_F(INFO, "MESH: DisReselect command requested");
break;
case SeqCmd::ResetMesh:
this->reset(false);
this->int_stat |= INT_CMD_DONE;
break;
case SeqCmd::FlushFIFO:
LOG_F(INFO, "MESH: FlushFIFO command requested");
break;
default:
LOG_F(ERROR, "MESH: unsupported sequencer command 0x%X", this->cur_cmd);
}
}
void MeshController::seq_defer_state(uint64_t delay_ns)
{
seq_timer_id = TimerManager::get_instance()->add_oneshot_timer(
delay_ns,
[this]() {
// re-enter the sequencer with the state specified in next_state
this->cur_state = this->next_state;
this->sequencer();
});
}
void MeshController::sequencer()
{
switch (this->cur_state) {
case SeqState::IDLE:
break;
case SeqState::BUS_FREE:
if (this->bus_obj->current_phase() == ScsiPhase::BUS_FREE) {
this->next_state = SeqState::ARB_BEGIN;
this->seq_defer_state(BUS_FREE_DELAY + BUS_SETTLE_DELAY);
} else { // continue waiting
this->next_state = SeqState::BUS_FREE;
this->seq_defer_state(BUS_FREE_DELAY);
}
break;
case SeqState::ARB_BEGIN:
if (!this->bus_obj->begin_arbitration(this->src_id)) {
LOG_F(ERROR, "MESH: arbitration error, bus not free!");
this->bus_obj->release_ctrl_lines(this->src_id);
this->next_state = SeqState::BUS_FREE;
this->seq_defer_state(BUS_CLEAR_DELAY);
break;
}
this->next_state = SeqState::ARB_END;
this->seq_defer_state(ARB_DELAY);
break;
case SeqState::ARB_END:
if (this->bus_obj->end_arbitration(this->src_id) &&
!this->bus_obj->test_ctrl_lines(SCSI_CTRL_SEL)) { // arbitration won
this->bus_obj->assert_ctrl_line(this->src_id, SCSI_CTRL_SEL);
} else { // arbitration lost
LOG_F(INFO, "MESH: arbitration lost!");
this->bus_obj->release_ctrl_lines(this->src_id);
this->exception |= EXC_ARB_LOST;
this->int_stat |= INT_EXCEPTION;
}
this->int_stat |= INT_CMD_DONE;
update_irq();
break;
case SeqState::SEL_BEGIN:
this->bus_obj->begin_selection(this->src_id, this->dst_id, this->cur_cmd & 0x20);
this->next_state = SeqState::SEL_END;
this->seq_defer_state(SEL_TIME_OUT);
break;
case SeqState::SEL_END:
if (this->bus_obj->end_selection(this->src_id, this->dst_id)) {
this->bus_obj->release_ctrl_line(this->src_id, SCSI_CTRL_SEL);
LOG_F(9, "MESH: selection completed");
} else { // selection timeout
this->bus_obj->disconnect(this->src_id);
this->cur_state = SeqState::IDLE;
this->exception |= EXC_SEL_TIMEOUT;
this->int_stat |= INT_EXCEPTION;
}
this->int_stat |= INT_CMD_DONE;
update_irq();
break;
default:
ABORT_F("MESH: unimplemented sequencer state %d", this->cur_state);
}
}
void MeshController::update_irq()
{
uint8_t new_irq = !!(this->int_stat & this->int_mask);
if (new_irq != this->irq) {
this->irq = new_irq;
this->int_ctrl->ack_int(this->irq_id, new_irq);
LOG_F(WARNING, "MESH: write to unimplemented register at offset 0x%x", reg_offset);
}
}
static const DeviceDescription Mesh_Descriptor = {
MeshController::create, {}, {}
MESHController::create, {}, {}
};
REGISTER_DEVICE(Mesh, Mesh_Descriptor);
+7 -85
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-21 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -25,8 +25,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#define MESH_H
#include <devices/common/hwcomponent.h>
#include <devices/common/hwinterrupt.h>
#include <devices/common/scsi/scsi.h>
#include <cinttypes>
#include <memory>
@@ -36,7 +34,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
namespace MeshScsi {
// MESH registers offsets.
// MESH registers offsets
enum MeshReg : uint8_t {
XferCount0 = 0,
XferCount1 = 1,
@@ -56,102 +54,26 @@ enum MeshReg : uint8_t {
SelTimeOut = 0xF
};
// MESH Sequencer commands.
enum SeqCmd : uint8_t {
NoOperation = 0,
Arbitrate = 1,
Select = 2,
DisReselect = 0xD,
ResetMesh = 0xE,
FlushFIFO = 0xF,
};
// Exception register bits.
enum {
EXC_SEL_TIMEOUT = 1 << 0,
EXC_PHASE_MM = 1 << 1,
EXC_ARB_LOST = 1 << 2,
};
// Interrupt register bits.
enum {
INT_CMD_DONE = 1 << 0,
INT_EXCEPTION = 1 << 1,
INT_ERROR = 1 << 2,
INT_MASK = INT_CMD_DONE | INT_EXCEPTION | INT_ERROR
};
enum SeqState : uint32_t {
IDLE = 0,
BUS_FREE,
ARB_BEGIN,
ARB_END,
SEL_BEGIN,
SEL_END,
SEND_MSG,
SEND_CMD,
CMD_COMPLETE,
XFER_BEGIN,
XFER_END,
SEND_DATA,
RCV_DATA,
RCV_STATUS,
RCV_MESSAGE,
};
}; // namespace MeshScsi
class MeshController : public HWComponent {
class MESHController : public HWComponent {
public:
MeshController(uint8_t mesh_id) {
MESHController(uint8_t mesh_id) {
supports_types(HWCompType::SCSI_HOST | HWCompType::SCSI_DEV);
this->chip_id = mesh_id;
this->reset(true);
};
~MeshController() = default;
~MESHController() = default;
static std::unique_ptr<HWComponent> create() {
return std::unique_ptr<MeshController>(new MeshController(HeathrowMESHID));
return std::unique_ptr<MESHController>(new MESHController(HeathrowMESHID));
}
// MESH registers access
uint8_t read(uint8_t reg_offset);
void write(uint8_t reg_offset, uint8_t value);
// HWComponent methods
int device_postinit();
protected:
void reset(bool is_hard_reset);
void perform_command(const uint8_t cmd);
void seq_defer_state(uint64_t delay_ns);
void sequencer();
void update_irq();
private:
uint8_t chip_id;
uint8_t int_mask;
uint8_t int_stat = 0;
uint8_t sync_params;
uint8_t src_id;
uint8_t dst_id;
uint8_t cur_cmd;
uint8_t error;
uint8_t exception;
ScsiBus* bus_obj;
uint16_t bus_stat;
// Sequencer state
uint32_t seq_timer_id;
uint32_t cur_state;
uint32_t next_state;
// interrupt related stuff
InterruptCtrl* int_ctrl = nullptr;
uint32_t irq_id = 0;
uint8_t irq = 0;
uint8_t chip_id; // Chip ID for the MESH controller
};
#endif // MESH_H
+17 -310
View File
@@ -30,9 +30,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <machines/machinebase.h>
#include <cinttypes>
#include <cstring>
Sc53C94::Sc53C94(uint8_t chip_id, uint8_t my_id) : ScsiDevice(my_id)
Sc53C94::Sc53C94(uint8_t chip_id, uint8_t my_id)
{
this->chip_id = chip_id;
this->my_bus_id = my_id;
@@ -75,20 +74,13 @@ void Sc53C94::reset_device()
uint8_t Sc53C94::read(uint8_t reg_offset)
{
uint8_t status, int_status;
uint8_t int_status;
switch (reg_offset) {
case Read::Reg53C94::Xfer_Cnt_LSB:
return this->xfer_count & 0xFFU;
case Read::Reg53C94::Xfer_Cnt_MSB:
return (this->xfer_count >> 8) & 0xFFU;
case Read::Reg53C94::FIFO:
return this->fifo_pop();
case Read::Reg53C94::Command:
return this->cmd_fifo[0];
case Read::Reg53C94::Status:
status = bus_obj->test_ctrl_lines(SCSI_CTRL_MSG | SCSI_CTRL_CD | SCSI_CTRL_IO);
return (this->status & 0xF8) | status;
return this->status;
case Read::Reg53C94::Int_Status:
int_status = this->int_status;
this->seq_step = 0;
@@ -99,8 +91,6 @@ uint8_t Sc53C94::read(uint8_t reg_offset)
return this->seq_step;
case Read::Reg53C94::FIFO_Flags:
return (this->seq_step << 5) | (this->data_fifo_pos & 0x1F);
case Read::Reg53C94::Config_1:
return this->config1;
case Read::Reg53C94::Config_3:
return this->config3;
case Read::Reg53C94::Xfer_Cnt_Hi:
@@ -117,12 +107,6 @@ uint8_t Sc53C94::read(uint8_t reg_offset)
void Sc53C94::write(uint8_t reg_offset, uint8_t value)
{
switch (reg_offset) {
case Write::Reg53C94::Xfer_Cnt_LSB:
this->set_xfer_count = (this->set_xfer_count & ~0xFFU) | value;
break;
case Write::Reg53C94::Xfer_Cnt_MSB:
this->set_xfer_count = (this->set_xfer_count & ~0xFF00U) | (value << 8);
break;
case Write::Reg53C94::Command:
update_command_reg(value);
break;
@@ -158,37 +142,6 @@ void Sc53C94::write(uint8_t reg_offset, uint8_t value)
}
}
uint16_t Sc53C94::pseudo_dma_read()
{
uint16_t data_word;
bool is_done = false;
if (this->data_fifo_pos >= 2) {
// remove one word from FIFO
data_word = (this->data_fifo[0] << 8) | this->data_fifo[1];
this->data_fifo_pos -= 2;
std:memmove(this->data_fifo, &this->data_fifo[2], this->data_fifo_pos);
// update DMA status
if ((this->cmd_fifo[0] & 0x80)) {
this->xfer_count -= 2;
if (!this->xfer_count) {
is_done = true;
this->status |= STAT_TC; // signal zero transfer count
this->cur_state = SeqState::XFER_END;
this->sequencer();
}
}
}
// see if we need to refill FIFO
if (!this->data_fifo_pos && !is_done) {
this->sequencer();
}
return data_word;
}
void Sc53C94::update_command_reg(uint8_t cmd)
{
if (this->on_reset && (cmd & 0x7F) != CMD_NOP) {
@@ -213,13 +166,13 @@ void Sc53C94::update_command_reg(uint8_t cmd)
}
} else {
LOG_F(ERROR, "SC53C94: the top of the command FIFO overwritten!");
this->status |= STAT_GE; // signal IOE/Gross Error
this->status |= 0x40; // signal IOE/Gross Error
}
}
void Sc53C94::exec_command()
{
uint8_t cmd = this->cur_cmd = this->cmd_fifo[0] & 0x7F;
uint8_t cmd = this->cmd_fifo[0] & 0x7F;
bool is_dma_cmd = !!(this->cmd_fifo[0] & 0x80);
if (is_dma_cmd) {
@@ -227,9 +180,6 @@ void Sc53C94::exec_command()
this->xfer_count = this->set_xfer_count & 0xFFFFFFUL;
} else { // standard mode: 16-bit
this->xfer_count = this->set_xfer_count & 0xFFFFUL;
if (!this->xfer_count) {
this->xfer_count = 65536;
}
}
}
@@ -242,7 +192,7 @@ void Sc53C94::exec_command()
exec_next_command();
break;
case CMD_CLEAR_FIFO:
this->data_fifo_pos = 0; // set the bottom of the data FIFO to zero
this->data_fifo_pos = 0; // set the bottom of the FIFO to zero
this->data_fifo[0] = 0;
exec_next_command();
break;
@@ -266,77 +216,26 @@ void Sc53C94::exec_command()
}
exec_next_command();
break;
case CMD_XFER:
if (!this->is_initiator) {
// clear command FIFO
this->cmd_fifo_pos = 0;
this->int_status |= INTSTAT_ICMD;
this->update_irq();
} else {
this->seq_step = 0;
this->cmd_steps = nullptr;
this->cur_state = SeqState::XFER_BEGIN;
this->sequencer();
}
break;
case CMD_COMPLETE_STEPS:
static SeqDesc * complete_steps_desc = new SeqDesc[3]{
{SeqState::RCV_STATUS, 0, 0},
{SeqState::RCV_MESSAGE, 0, 0},
{SeqState::CMD_COMPLETE, 0, INTSTAT_SR}
};
if (this->bus_obj->current_phase() != ScsiPhase::STATUS) {
ABORT_F("Sc53C94: complete steps only works in the STATUS phase");
}
this->seq_step = 0;
this->cmd_steps = complete_steps_desc;
this->cur_state = this->cmd_steps->next_step;
this->sequencer();
break;
case CMD_MSG_ACCEPTED:
if (this->is_initiator) {
this->bus_obj->target_next_step();
}
this->bus_obj->release_ctrl_line(this->my_bus_id, SCSI_CTRL_ACK);
this->int_status |= INTSTAT_SR;
this->int_status |= INTSTAT_DIS; // TODO: handle target disconnection properly
this->update_irq();
exec_next_command();
break;
case CMD_SELECT_NO_ATN:
static SeqDesc * sel_no_atn_desc = new SeqDesc[3]{
{SeqState::SEL_BEGIN, 0, INTSTAT_DIS },
{SeqState::SEND_CMD, 3, INTSTAT_SR | INTSTAT_SO},
{SeqState::CMD_BEGIN, 3, INTSTAT_SR | INTSTAT_SO},
{SeqState::CMD_COMPLETE, 4, INTSTAT_SR | INTSTAT_SO},
};
this->seq_step = 0;
this->cmd_steps = sel_no_atn_desc;
this->cur_state = SeqState::BUS_FREE;
this->sequencer();
LOG_F(9, "SC53C94: SELECT W/O ATN command started");
break;
case CMD_SELECT_WITH_ATN:
static SeqDesc * sel_with_atn_desc = new SeqDesc[4]{
{SeqState::SEL_BEGIN, 0, INTSTAT_DIS },
{SeqState::SEND_MSG, 2, INTSTAT_SR | INTSTAT_SO},
{SeqState::SEND_CMD, 3, INTSTAT_SR | INTSTAT_SO},
{SeqState::CMD_COMPLETE, 4, INTSTAT_SR | INTSTAT_SO},
};
this->seq_step = 0;
this->bytes_out = 1; // set message length
this->cmd_steps = sel_with_atn_desc;
this->cur_state = SeqState::BUS_FREE;
this->sequencer();
LOG_F(9, "SC53C94: SELECT WITH ATN command started");
sequencer();
LOG_F(INFO, "SC53C94: SELECT W/O ATN command started");
break;
case CMD_ENA_SEL_RESEL:
LOG_F(INFO, "SC53C94: ENABLE SELECTION/RESELECTION command executed");
exec_next_command();
break;
default:
LOG_F(ERROR, "SC53C94: invalid/unimplemented command 0x%X", cmd);
this->cmd_fifo_pos--; // remove invalid command from FIFO
this->int_status |= INTSTAT_ICMD;
this->update_irq();
}
}
@@ -353,30 +252,14 @@ void Sc53C94::exec_next_command()
void Sc53C94::fifo_push(const uint8_t data)
{
if (this->data_fifo_pos < DATA_FIFO_MAX) {
if (this->data_fifo_pos < 16) {
this->data_fifo[this->data_fifo_pos++] = data;
} else {
LOG_F(ERROR, "SC53C94: data FIFO overflow!");
this->status |= STAT_GE; // signal IOE/Gross Error
this->status |= 0x40; // signal IOE/Gross Error
}
}
uint8_t Sc53C94::fifo_pop()
{
uint8_t data = 0;
if (this->data_fifo_pos < 1) {
LOG_F(ERROR, "SC53C94: data FIFO underflow!");
this->status |= STAT_GE; // signal IOE/Gross Error
} else {
data = this->data_fifo[0];
this->data_fifo_pos--;
std:memmove(this->data_fifo, &this->data_fifo[1], this->data_fifo_pos);
}
return data;
}
void Sc53C94::seq_defer_state(uint64_t delay_ns)
{
seq_timer_id = TimerManager::get_instance()->add_oneshot_timer(
@@ -433,8 +316,8 @@ void Sc53C94::sequencer()
break;
case SeqState::SEL_END:
if (this->bus_obj->end_selection(this->my_bus_id, this->target_id)) {
this->bus_obj->release_ctrl_line(this->my_bus_id, SCSI_CTRL_SEL);
LOG_F(9, "SC53C94: selection completed");
LOG_F(INFO, "SC53C94: selection completed");
this->cmd_steps++;
} else { // selection timeout
this->seq_step = this->cmd_steps->step_num;
this->int_status |= this->cmd_steps->status;
@@ -444,84 +327,6 @@ void Sc53C94::sequencer()
exec_next_command();
}
break;
case SeqState::SEND_MSG:
this->bus_obj->negotiate_xfer(this->data_fifo_pos, this->bytes_out);
this->bus_obj->push_data(this->target_id, this->data_fifo, this->bytes_out);
this->data_fifo_pos -= this->bytes_out;
if (this->data_fifo_pos > 0) {
std::memmove(this->data_fifo, &this->data_fifo[this->bytes_out], this->data_fifo_pos);
}
this->bus_obj->release_ctrl_line(this->my_bus_id, SCSI_CTRL_ATN);
break;
case SeqState::SEND_CMD:
this->bus_obj->negotiate_xfer(this->data_fifo_pos, this->bytes_out);
this->bus_obj->push_data(this->target_id, this->data_fifo, this->data_fifo_pos);
this->data_fifo_pos = 0;
break;
case SeqState::CMD_COMPLETE:
this->seq_step = this->cmd_steps->step_num;
this->int_status |= this->cmd_steps->status;
this->update_irq();
exec_next_command();
break;
case SeqState::XFER_BEGIN:
this->cur_bus_phase = this->bus_obj->current_phase();
switch (this->cur_bus_phase) {
case ScsiPhase::DATA_OUT:
if (this->cmd_fifo[0] & 0x80) {
this->cur_state = SeqState::SEND_DATA;
break;
}
this->bus_obj->push_data(this->target_id, this->data_fifo, this->data_fifo_pos);
this->data_fifo_pos = 0;
this->cur_state = SeqState::XFER_END;
this->sequencer();
break;
case ScsiPhase::DATA_IN:
this->bus_obj->negotiate_xfer(this->data_fifo_pos, this->bytes_out);
this->cur_state = SeqState::RCV_DATA;
this->rcv_data();
if (!(this->cmd_fifo[0] & 0x80)) {
this->cur_state = SeqState::XFER_END;
this->sequencer();
}
}
break;
case SeqState::XFER_END:
if (this->is_initiator) {
this->bus_obj->target_next_step();
}
this->int_status |= INTSTAT_SR;
this->update_irq();
exec_next_command();
break;
case SeqState::SEND_DATA:
break;
case SeqState::RCV_DATA:
// check for unexpected bus phase changes
if (this->bus_obj->current_phase() != this->cur_bus_phase) {
this->cmd_fifo_pos = 0; // clear command FIFO
this->int_status |= INTSTAT_SR;
this->update_irq();
} else {
this->rcv_data();
}
break;
case SeqState::RCV_STATUS:
case SeqState::RCV_MESSAGE:
this->bus_obj->negotiate_xfer(this->data_fifo_pos, this->bytes_out);
this->rcv_data();
if (this->is_initiator) {
if (this->cur_state == SeqState::RCV_STATUS) {
this->bus_obj->target_next_step();
} else if (this->cur_state == SeqState::RCV_MESSAGE) {
this->bus_obj->assert_ctrl_line(this->my_bus_id, SCSI_CTRL_ACK);
this->cmd_steps++;
this->cur_state = this->cmd_steps->next_step;
this->sequencer();
}
}
break;
default:
ABORT_F("SC53C94: unimplemented sequencer state %d", this->cur_state);
}
@@ -537,7 +342,7 @@ void Sc53C94::update_irq()
}
}
void Sc53C94::notify(ScsiBus* bus_obj, ScsiMsg msg_type, int param)
void Sc53C94::notify(ScsiMsg msg_type, int param)
{
switch (msg_type) {
case ScsiMsg::CONFIRM_SEL:
@@ -545,111 +350,13 @@ void Sc53C94::notify(ScsiBus* bus_obj, ScsiMsg msg_type, int param)
// cancel selection timeout timer
TimerManager::get_instance()->cancel_timer(this->seq_timer_id);
this->cur_state = SeqState::SEL_END;
this->sequencer();
sequencer();
} else {
LOG_F(WARNING, "SC53C94: ignore invalid selection confirmation message");
}
break;
case ScsiMsg::BUS_PHASE_CHANGE:
if (param != ScsiPhase::BUS_FREE && this->cmd_steps != nullptr) {
this->cmd_steps++;
this->cur_state = this->cmd_steps->next_step;
this->sequencer();
}
break;
default:
LOG_F(9, "SC53C94: ignore notification message, type: %d", msg_type);
}
}
int Sc53C94::send_data(uint8_t* dst_ptr, int count)
{
if (dst_ptr == nullptr || !count) {
return 0;
}
int actual_count = std::min(this->data_fifo_pos, count);
// move data out of the data FIFO
std::memcpy(dst_ptr, this->data_fifo, actual_count);
// remove the just readed data from the data FIFO
this->data_fifo_pos -= actual_count;
if (this->data_fifo_pos > 0) {
std::memmove(this->data_fifo, &this->data_fifo[actual_count], this->data_fifo_pos);
} else {
this->cmd_steps++;
this->cur_state = this->cmd_steps->next_step;
this->sequencer();
}
return actual_count;
}
bool Sc53C94::rcv_data()
{
int req_count;
// return if REQ line is negated
if (!this->bus_obj->test_ctrl_lines(SCSI_CTRL_REQ)) {
return false;
}
if ((this->cmd_fifo[0] & 0x80) && this->cur_bus_phase == ScsiPhase::DATA_IN) {
req_count = std::min((int)this->xfer_count, DATA_FIFO_MAX - this->data_fifo_pos);
} else {
req_count = 1;
}
this->bus_obj->pull_data(this->target_id, &this->data_fifo[this->data_fifo_pos], req_count);
this->data_fifo_pos += req_count;
return true;
}
void Sc53C94::real_dma_xfer(int direction)
{
bool is_done = false;
if (direction) {
uint32_t got_bytes;
uint8_t* src_ptr;
while (this->xfer_count) {
this->dma_ch->pull_data(std::min((int)this->xfer_count, DATA_FIFO_MAX),
&got_bytes, &src_ptr);
std::memcpy(this->data_fifo, src_ptr, got_bytes);
this->data_fifo_pos = got_bytes;
this->bus_obj->push_data(this->target_id, this->data_fifo, this->data_fifo_pos);
this->xfer_count -= this->data_fifo_pos;
this->data_fifo_pos = 0;
if (!this->xfer_count) {
is_done = true;
this->status |= STAT_TC; // signal zero transfer count
this->cur_state = SeqState::XFER_END;
this->sequencer();
}
}
} else { // transfer data from target to host's memory
while (this->xfer_count) {
if (this->data_fifo_pos) {
this->dma_ch->push_data((char*)this->data_fifo, this->data_fifo_pos);
this->xfer_count -= this->data_fifo_pos;
this->data_fifo_pos = 0;
if (!this->xfer_count) {
is_done = true;
this->status |= STAT_TC; // signal zero transfer count
this->cur_state = SeqState::XFER_END;
this->sequencer();
}
}
// see if we need to refill FIFO
if (!this->data_fifo_pos && !is_done) {
this->sequencer();
}
}
LOG_F(WARNING, "SC53C94: ignore notification message, type: %d", msg_type);
}
}
+11 -51
View File
@@ -29,15 +29,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef SC_53C94_H
#define SC_53C94_H
#include <devices/common/dmacore.h>
#include <devices/common/scsi/scsi.h>
#include <devices/common/hwinterrupt.h>
#include <cinttypes>
#include <memory>
#define DATA_FIFO_MAX 16
/** 53C94 read registers */
namespace Read {
enum Reg53C94 : uint8_t {
@@ -81,23 +78,13 @@ namespace Write {
/** NCR53C94/Am53CF94 commands. */
enum {
CMD_NOP = 0,
CMD_CLEAR_FIFO = 1,
CMD_RESET_DEVICE = 2,
CMD_RESET_BUS = 3,
CMD_DMA_STOP = 4,
CMD_XFER = 0x10,
CMD_COMPLETE_STEPS = 0x11,
CMD_MSG_ACCEPTED = 0x12,
CMD_SELECT_NO_ATN = 0x41,
CMD_SELECT_WITH_ATN = 0x42,
CMD_ENA_SEL_RESEL = 0x44,
};
/** Status register bits. **/
enum {
STAT_TC = 1 << 4, // Terminal count (NCR) / count to zero (AMD)
STAT_GE = 1 << 6, // Gross Error (NCR) / Illegal Operation Error (AMD)
CMD_NOP = 0,
CMD_CLEAR_FIFO = 1,
CMD_RESET_DEVICE = 2,
CMD_RESET_BUS = 3,
CMD_DMA_STOP = 4,
CMD_SELECT_NO_ATN = 0x41,
CMD_ENA_SEL_RESEL = 0x44,
};
/** Interrupt status register bits. */
@@ -125,15 +112,8 @@ namespace SeqState {
ARB_END,
SEL_BEGIN,
SEL_END,
SEND_MSG,
SEND_CMD,
CMD_BEGIN,
CMD_COMPLETE,
XFER_BEGIN,
XFER_END,
SEND_DATA,
RCV_DATA,
RCV_STATUS,
RCV_MESSAGE,
};
};
@@ -157,23 +137,11 @@ public:
int device_postinit();
// 53C94 registers access
uint8_t read(uint8_t reg_offset);
void write(uint8_t reg_offset, uint8_t value);
uint16_t pseudo_dma_read();
// real DMA control
void real_dma_xfer(int direction);
void set_dma_channel(DmaBidirChannel *dma_ch) {
this->dma_ch = dma_ch;
};
uint8_t read(uint8_t reg_offset);
void write(uint8_t reg_offset, uint8_t value);
// ScsiDevice methods
void notify(ScsiBus* bus_obj, ScsiMsg msg_type, int param);
bool prepare_data() { return false; };
bool has_data() { return this->data_fifo_pos != 0; };
int send_data(uint8_t* dst_ptr, int count);
void process_command() {};
void notify(ScsiMsg msg_type, int param);
protected:
void reset_device();
@@ -181,13 +149,10 @@ protected:
void exec_command();
void exec_next_command();
void fifo_push(const uint8_t data);
uint8_t fifo_pop();
void sequencer();
void seq_defer_state(uint64_t delay_ns);
bool rcv_data();
void update_irq();
private:
@@ -200,7 +165,6 @@ private:
uint8_t data_fifo[16];
int cmd_fifo_pos;
int data_fifo_pos;
int bytes_out;
bool on_reset = false;
uint32_t xfer_count;
uint32_t set_xfer_count;
@@ -222,15 +186,11 @@ private:
SeqDesc* cmd_steps;
bool is_initiator;
uint8_t cur_cmd;
int cur_bus_phase;
// interrupt related stuff
InterruptCtrl* int_ctrl = nullptr;
uint32_t irq_id = 0;
uint8_t irq = 0;
// DMA related stuff
DmaBidirChannel* dma_ch;
};
#endif // SC_53C94_H
+22 -145
View File
@@ -28,7 +28,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <array>
#include <cinttypes>
#include <functional>
#include <string>
/** SCSI control signals.
@@ -41,102 +40,22 @@ enum {
SCSI_CTRL_ATN = 1 << 3,
SCSI_CTRL_ACK = 1 << 4,
SCSI_CTRL_REQ = 1 << 5,
SCSI_CTRL_SEL = 1 << 13,
SCSI_CTRL_BSY = 1 << 14,
SCSI_CTRL_RST = 1 << 15,
SCSI_CTRL_SEL = 1 << 6,
SCSI_CTRL_BSY = 1 << 7,
SCSI_CTRL_RST = 1 << 8,
};
namespace ScsiPhase {
enum : int {
BUS_FREE = 0,
ARBITRATION,
SELECTION,
RESELECTION,
COMMAND,
DATA_IN,
DATA_OUT,
STATUS,
MESSAGE_IN,
MESSAGE_OUT,
RESET,
};
};
namespace ScsiStatus {
enum : uint8_t {
GOOD = 0,
CHECK_CONDITION = 2,
};
};
namespace ScsiMessage {
enum : uint8_t {
COMMAND_COMPLETE = 0,
};
enum ScsiPhase : int {
BUS_FREE = 0,
ARBITRATION,
SELECTION,
RESELECTION,
RESET,
};
enum ScsiMsg : int {
CONFIRM_SEL = 1,
BUS_PHASE_CHANGE,
SEND_CMD_BEGIN,
SEND_CMD_END,
MESSAGE_BEGIN,
MESSAGE_END,
};
enum ScsiCommand : int {
TEST_UNIT_READY = 0x0,
REWIND = 0x1,
REQ_SENSE = 0x3,
FORMAT = 0x4,
READ_BLK_LIMITS = 0x5,
READ_6 = 0x8,
WRITE_6 = 0xA,
SEEK_6 = 0xB,
INQUIRY = 0x12,
VERIFY_6 = 0x13,
MODE_SELECT_6 = 0x15,
RELEASE_UNIT = 0x17,
ERASE_6 = 0x19,
MODE_SENSE_6 = 0x1A,
DIAG_RESULTS = 0x1C,
SEND_DIAGS = 0x1D,
PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1E,
READ_CAPACITY_10 = 0x25,
READ_10 = 0x28,
WRITE_10 = 0x2A,
VERIFY_10 = 0x2F,
READ_LONG_10 = 0x35,
// CD-ROM specific commands
READ_TOC = 0x43,
};
enum ScsiSense : int {
NO_SENSE = 0x0,
RECOVERED = 0x1,
NOT_READY = 0x2,
MEDIUM_ERR = 0x3,
HW_ERROR = 0x4,
ILLEGAL_REQ = 0x5,
UNIT_ATTENTION = 0x6,
DATA_PROTECT = 0x7,
BLANK_CHECK = 0x8,
VOL_OVERFLOW = 0xD,
MISCOMPARE = 0xE,
COMPLETED = 0xF
};
enum ScsiError : int {
NO_ERROR = 0x0,
NO_SECTOR = 0x1,
WRITE_FAULT = 0x3,
DEV_NOT_READY = 0x4,
INVALID_CMD = 0x20,
INVALID_LBA = 0x21,
INVALID_CDB = 0x24,
INVALID_LUN = 0x25,
WRITE_PROTECT = 0x27
};
/** Standard SCSI bus timing values measured in ns. */
@@ -149,46 +68,15 @@ enum ScsiError : int {
#define SCSI_MAX_DEVS 8
class ScsiBus;
typedef std::function<void()> action_callback;
class ScsiDevice : public HWComponent {
public:
ScsiDevice(int my_id) {
this->scsi_id = my_id;
this->cur_phase = ScsiPhase::BUS_FREE;
};
ScsiDevice() = default;
~ScsiDevice() = default;
virtual void notify(ScsiBus* bus_obj, ScsiMsg msg_type, int param);
virtual void next_step(ScsiBus* bus_obj);
virtual void prepare_xfer(ScsiBus* bus_obj, int& bytes_in, int& bytes_out);
virtual void switch_phase(const int new_phase);
virtual void notify(ScsiMsg msg_type, int param) = 0;
virtual bool has_data() { return this->data_size != 0; };
virtual int send_data(uint8_t* dst_ptr, int count);
virtual int rcv_data(const uint8_t* src_ptr, const int count);
virtual bool prepare_data() = 0;
virtual void process_command() = 0;
protected:
uint8_t cmd_buf[16] = {};
uint8_t msg_buf[16] = {}; // TODO: clarify how big this one should be
int scsi_id;
int initiator_id;
int cur_phase;
uint8_t* data_ptr = nullptr;
int data_size;
int incoming_size;
uint8_t status;
int sense;
ScsiBus* bus_obj;
action_callback pre_xfer_action = nullptr;
action_callback post_xfer_action = nullptr;
private:
int scsi_id;
};
/** This class provides a higher level abstraction for the SCSI bus. */
@@ -197,43 +85,32 @@ public:
ScsiBus();
~ScsiBus() = default;
// low-level state management
void register_device(int id, ScsiDevice* dev_obj);
int current_phase() { return this->cur_phase; };
int get_initiator_id() { return this->initiator_id; };
int get_target_id() { return this->target_id; };
// reading/writing control lines
void assert_ctrl_line(int id, uint16_t mask);
void release_ctrl_line(int id, uint16_t mask);
void release_ctrl_lines(int id);
uint16_t test_ctrl_lines(uint16_t mask);
// reading/writing data lines
uint8_t get_data_lines() { return this->data_lines; };
// low-level control/status
void register_device(int id, ScsiDevice* dev_obj);
void assert_ctrl_line(int id, uint16_t mask);
void release_ctrl_line(int id, uint16_t mask);
void release_ctrl_lines(int id);
int current_phase() { return this->cur_phase; };
// high-level control/status
int switch_phase(int id, int new_phase);
bool begin_arbitration(int id);
bool end_arbitration(int id);
bool begin_selection(int initiator_id, int target_id, bool atn);
void confirm_selection(int target_id);
bool end_selection(int initiator_id, int target_id);
void disconnect(int dev_id);
bool pull_data(const int id, uint8_t* dst_ptr, const int size);
bool push_data(const int id, const uint8_t* src_ptr, const int size);
void target_next_step();
bool negotiate_xfer(int& bytes_in, int& bytes_out);
protected:
void change_bus_phase(int initiator_id);
private:
std::string name;
// SCSI devices registered with this bus
std::array<ScsiDevice*, SCSI_MAX_DEVS> devices;
// per-device state of the control lines
uint16_t dev_ctrl_lines[SCSI_MAX_DEVS] = {};
uint16_t dev_ctrl_lines[SCSI_MAX_DEVS];
uint16_t ctrl_lines;
int cur_phase;
+10 -104
View File
@@ -36,11 +36,11 @@ ScsiBus::ScsiBus()
this->dev_ctrl_lines[i] = 0;
}
this->ctrl_lines = 0; // all control lines released
this->data_lines = 0; // data lines released
this->ctrl_lines = 0; // all control lines released
this->data_lines = 0; // data lines released
this->arb_winner_id = -1;
this->initiator_id = -1;
this->target_id = -1;
this->initiator_id = -1;
this->target_id = -1;
}
void ScsiBus::register_device(int id, ScsiDevice* dev_obj)
@@ -58,7 +58,7 @@ void ScsiBus::change_bus_phase(int initiator_id)
if (i == initiator_id)
continue; // don't notify the initiator
if (this->devices[i] != nullptr) {
this->devices[i]->notify(this, ScsiMsg::BUS_PHASE_CHANGE, this->cur_phase);
this->devices[i]->notify(ScsiMsg::BUS_PHASE_CHANGE, this->cur_phase);
}
}
}
@@ -67,14 +67,15 @@ void ScsiBus::assert_ctrl_line(int initiator_id, uint16_t mask)
{
uint16_t new_state = 0xFFFFU & mask;
this->dev_ctrl_lines[initiator_id] |= new_state;
this->dev_ctrl_lines[initiator_id] = new_state;
if (new_state == this->ctrl_lines) {
return;
}
this->ctrl_lines = new_state;
if (new_state & SCSI_CTRL_RST) {
this->ctrl_lines |= SCSI_CTRL_RST;
this->cur_phase = ScsiPhase::RESET;
change_bus_phase(initiator_id);
}
@@ -97,8 +98,6 @@ void ScsiBus::release_ctrl_line(int id, uint16_t mask)
this->cur_phase = ScsiPhase::BUS_FREE;
change_bus_phase(id);
}
} else {
this->ctrl_lines = new_state;
}
}
@@ -107,61 +106,6 @@ void ScsiBus::release_ctrl_lines(int id)
this->release_ctrl_line(id, 0xFFFFUL);
}
uint16_t ScsiBus::test_ctrl_lines(uint16_t mask)
{
uint16_t new_state = 0;
// OR control lines of all devices together
for (int i = 0; i < SCSI_MAX_DEVS; i++) {
new_state |= this->dev_ctrl_lines[i];
}
return new_state & mask;
}
int ScsiBus::switch_phase(int id, int new_phase)
{
int old_phase = this->cur_phase;
// leave the current phase (low-level)
switch (old_phase) {
case ScsiPhase::COMMAND:
this->release_ctrl_line(id, SCSI_CTRL_CD);
break;
case ScsiPhase::DATA_IN:
this->release_ctrl_line(id, SCSI_CTRL_IO);
break;
case ScsiPhase::STATUS:
this->release_ctrl_line(id, SCSI_CTRL_CD | SCSI_CTRL_IO);
break;
case ScsiPhase::MESSAGE_OUT:
this->release_ctrl_line(id, SCSI_CTRL_CD | SCSI_CTRL_MSG);
break;
}
// enter new phase (low-level)
switch (new_phase) {
case ScsiPhase::COMMAND:
this->assert_ctrl_line(id, SCSI_CTRL_CD);
break;
case ScsiPhase::DATA_IN:
this->assert_ctrl_line(id, SCSI_CTRL_IO);
break;
case ScsiPhase::STATUS:
this->assert_ctrl_line(id, SCSI_CTRL_CD | SCSI_CTRL_IO);
break;
case ScsiPhase::MESSAGE_OUT:
this->assert_ctrl_line(id, SCSI_CTRL_CD | SCSI_CTRL_MSG);
break;
}
// switch the bus to the new phase (high-level)
this->cur_phase = new_phase;
change_bus_phase(id);
return old_phase;
}
bool ScsiBus::begin_arbitration(int initiator_id)
{
if (this->cur_phase == ScsiPhase::BUS_FREE) {
@@ -199,9 +143,7 @@ bool ScsiBus::begin_selection(int initiator_id, int target_id, bool atn)
if (this->cur_phase != ScsiPhase::ARBITRATION || this->arb_winner_id != initiator_id)
return false;
this->assert_ctrl_line(initiator_id, SCSI_CTRL_SEL);
this->data_lines = (1 << initiator_id) | (1 << target_id);
this->data_lines |= (1 << initiator_id) | (1 << target_id);
if (atn) {
assert_ctrl_line(initiator_id, SCSI_CTRL_ATN);
@@ -219,7 +161,7 @@ void ScsiBus::confirm_selection(int target_id)
// notify initiator about selection confirmation from target
if (this->initiator_id >= 0) {
this->devices[this->initiator_id]->notify(this, ScsiMsg::CONFIRM_SEL, target_id);
this->devices[this->initiator_id]->notify(ScsiMsg::CONFIRM_SEL, target_id);
}
}
@@ -229,42 +171,6 @@ bool ScsiBus::end_selection(int initiator_id, int target_id)
return this->target_id == target_id;
}
bool ScsiBus::pull_data(const int id, uint8_t* dst_ptr, const int size)
{
if (dst_ptr == nullptr || !size) {
return false;
}
if (!this->devices[id]->send_data(dst_ptr, size)) {
LOG_F(ERROR, "ScsiBus: error while transferring T->I data!");
return false;
}
return true;
}
bool ScsiBus::push_data(const int id, const uint8_t* src_ptr, const int size)
{
if (!this->devices[id]->rcv_data(src_ptr, size)) {
LOG_F(ERROR, "ScsiBus: error while transferring I->T data!");
return false;
}
return true;
}
void ScsiBus::target_next_step()
{
this->devices[this->target_id]->next_step(this);
}
bool ScsiBus::negotiate_xfer(int& bytes_in, int& bytes_out)
{
this->devices[this->target_id]->prepare_xfer(this, bytes_in, bytes_out);
return true;
}
void ScsiBus::disconnect(int dev_id)
{
this->release_ctrl_lines(dev_id);
-364
View File
@@ -1,364 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file SCSI CD-ROM emulation. */
#include <devices/common/scsi/scsi.h>
#include <devices/common/scsi/scsicdrom.h>
#include <devices/deviceregistry.h>
#include <loguru.hpp>
#include <machines/machineproperties.h>
#include <memaccess.h>
#include <cinttypes>
#include <cstring>
#include <stdio.h>
#include <sys/stat.h>
using namespace std;
static char cdrom_vendor_sony_id[] = "SONY ";
static char cdu8003a_product_id[] = "CD-ROM CDU-8003A";
static char cdu8003a_revision_id[] = "1.9a";
ScsiCdrom::ScsiCdrom(int my_id) : ScsiDevice(my_id)
{
supports_types(HWCompType::SCSI_DEV);
this->sector_size = 2048;
this->pre_xfer_action = nullptr;
this->post_xfer_action = nullptr;
}
void ScsiCdrom::insert_image(std::string filename)
{
this->cdr_img.open(filename, ios::out | ios::in | ios::binary);
struct stat stat_buf;
int rc = stat(filename.c_str(), &stat_buf);
if (!rc) {
this->img_size = stat_buf.st_size;
this->total_frames = (this->img_size + this->sector_size - 1) / this->sector_size;
// create single track descriptor
this->tracks[0] = {.trk_num = 1, .adr_ctrl = 0x14, .start_lba = 0};
this->num_tracks = 1;
// create Lead-out descriptor containing all data
this->tracks[1] = {.trk_num = LEAD_OUT_TRK_NUM, .adr_ctrl = 0x14,
.start_lba = static_cast<uint32_t>(this->total_frames)};
} else {
ABORT_F("SCSI-CDROM: could not determine file size using stat()");
}
this->cdr_img.seekg(0, std::ios_base::beg);
}
void ScsiCdrom::process_command()
{
uint32_t lba, xfer_len;
this->pre_xfer_action = nullptr;
this->post_xfer_action = nullptr;
// assume successful command execution
this->status = ScsiStatus::GOOD;
switch (cmd_buf[0]) {
case ScsiCommand::TEST_UNIT_READY:
this->switch_phase(ScsiPhase::STATUS);
break;
case ScsiCommand::READ_6:
lba = ((cmd_buf[1] & 0x1F) << 16) + (cmd_buf[2] << 8) + cmd_buf[3];
this->read(lba, cmd_buf[4], 6);
break;
case ScsiCommand::INQUIRY:
this->inquiry();
break;
case ScsiCommand::MODE_SELECT_6:
this->incoming_size = this->cmd_buf[4];
this->switch_phase(ScsiPhase::DATA_OUT);
break;
case ScsiCommand::MODE_SENSE_6:
this->mode_sense();
break;
case ScsiCommand::PREVENT_ALLOW_MEDIUM_REMOVAL:
this->eject_allowed = (this->cmd_buf[4] & 1) == 0;
this->switch_phase(ScsiPhase::STATUS);
break;
case ScsiCommand::READ_CAPACITY_10:
this->read_capacity();
break;
case ScsiCommand::READ_10:
lba = READ_DWORD_BE_U(&this->cmd_buf[2]);
xfer_len = READ_WORD_BE_U(&this->cmd_buf[7]);
if (this->cmd_buf[1] & 1) {
ABORT_F("SCSI-CDROM: RelAdr bit set in READ_10");
}
read(lba, xfer_len, 10);
break;
case ScsiCommand::READ_TOC:
this->read_toc();
break;
default:
ABORT_F("SCSI_CDROM: unsupported command %d", this->cmd_buf[0]);
}
}
bool ScsiCdrom::prepare_data()
{
switch (this->cur_phase) {
case ScsiPhase::DATA_IN:
this->data_ptr = (uint8_t*)this->data_buf;
this->data_size = this->bytes_out;
break;
case ScsiPhase::DATA_OUT:
this->data_ptr = (uint8_t*)this->data_buf;
this->data_size = 0;
break;
case ScsiPhase::STATUS:
break;
default:
LOG_F(WARNING, "SCSI_CDROM: unexpected phase in prepare_data");
return false;
}
return true;
}
void ScsiCdrom::read(const uint32_t lba, const uint16_t transfer_len, const uint8_t cmd_len)
{
uint32_t transfer_size = transfer_len;
std::memset(this->data_buf, 0, sizeof(this->data_buf));
if (cmd_len == 6 && transfer_len == 0) {
transfer_size = 256;
}
transfer_size *= this->sector_size;
uint64_t device_offset = lba * this->sector_size;
this->cdr_img.seekg(device_offset, this->cdr_img.beg);
this->cdr_img.read(this->data_buf, transfer_size);
this->bytes_out = transfer_size;
this->msg_buf[0] = ScsiMessage::COMMAND_COMPLETE;
this->switch_phase(ScsiPhase::DATA_IN);
}
void ScsiCdrom::inquiry()
{
int page_num = cmd_buf[2];
int alloc_len = cmd_buf[4];
if (page_num) {
ABORT_F("SCSI_CDROM: invalid page number in INQUIRY");
}
if (alloc_len > 36) {
LOG_F(WARNING, "SCSI_CDROM: more than 36 bytes requested in INQUIRY");
}
this->data_buf[0] = 5; // device type: CD-ROM
this->data_buf[1] = 0x80; // removable media
this->data_buf[2] = 2; // ANSI version: SCSI-2
this->data_buf[3] = 1; // response data format
this->data_buf[4] = 0x1F; // additional length
this->data_buf[5] = 0;
this->data_buf[6] = 0;
this->data_buf[7] = 0x18; // supports synchronous xfers and linked commands
std::memcpy(&this->data_buf[8], cdrom_vendor_sony_id, 8);
std::memcpy(&this->data_buf[16], cdu8003a_product_id, 16);
std::memcpy(&this->data_buf[32], cdu8003a_revision_id, 4);
this->bytes_out = 36;
this->msg_buf[0] = ScsiMessage::COMMAND_COMPLETE;
this->switch_phase(ScsiPhase::DATA_IN);
}
static char Apple_Copyright_Page_Data[] = "APPLE COMPUTER, INC ";
void ScsiCdrom::mode_sense()
{
uint8_t page_code = this->cmd_buf[2] & 0x3F;
uint8_t alloc_len = this->cmd_buf[4];
int num_blocks = (this->img_size + this->sector_size) / this->sector_size;
this->data_buf[ 0] = 13; // initial data size
this->data_buf[ 1] = 0; // medium type
this->data_buf[ 2] = 0x80; // medium is write protected
this->data_buf[ 3] = 8; // block description length
this->data_buf[ 4] = 0; // density code
this->data_buf[ 5] = (num_blocks >> 16) & 0xFFU;
this->data_buf[ 6] = (num_blocks >> 8) & 0xFFU;
this->data_buf[ 7] = (num_blocks ) & 0xFFU;
this->data_buf[ 8] = 0;
this->data_buf[ 9] = 0;
this->data_buf[10] = (this->sector_size >> 8) & 0xFFU;
this->data_buf[11] = (this->sector_size ) & 0xFFU;
this->data_buf[12] = page_code;
switch (page_code) {
case 0x01:
this->data_buf[13] = 6; // data size
std::memset(&this->data_buf[14], 0, 6);
this->data_buf[0] += 7;
break;
case 0x30:
this->data_buf[13] = 22; // data size
std::memcpy(&this->data_buf[14], Apple_Copyright_Page_Data, 22);
this->data_buf[0] += 23;
break;
default:
ABORT_F("SCSI-HD: unsupported page %d in MODE_SENSE_6", page_code);
}
this->bytes_out = this->data_buf[0];
this->msg_buf[0] = ScsiMessage::COMMAND_COMPLETE;
this->switch_phase(ScsiPhase::DATA_IN);
}
void ScsiCdrom::read_toc()
{
int tot_tracks;
uint8_t start_track = this->cmd_buf[6];
uint16_t alloc_len = (this->cmd_buf[7] << 8) + this->cmd_buf[8];
bool is_msf = !!(this->cmd_buf[1] & 2);
if (this->cmd_buf[2] & 0xF) {
ABORT_F("SCSI-CDROM: unsupported format in READ_TOC");
}
if (!alloc_len) {
LOG_F(WARNING, "SCSI-CDROM: zero allocation length passed to READ_TOC");
return;
}
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, "SCSI-CDROM: invalid starting track %d in READ_TOC", start_track);
this->status = ScsiStatus::CHECK_CONDITION;
this->sense = ScsiSense::ILLEGAL_REQ;
this->switch_phase(ScsiPhase::STATUS);
return;
}
char* buf_ptr = this->data_buf;
int data_len = (tot_tracks * 8) + 2;
// write TOC data header
*buf_ptr++ = (data_len >> 8) & 0xFFU;
*buf_ptr++ = (data_len >> 0) & 0xFFU;
*buf_ptr++ = 1; // 1st track number
*buf_ptr++ = this->num_tracks; // last track number
for (int tx = 0; tx < tot_tracks; tx++) {
if ((buf_ptr - this->data_buf + 8) > alloc_len)
break; // exit the loop if the output buffer length is exhausted
TrackDescriptor& td = this->tracks[start_track + tx - 1];
*buf_ptr++ = 0; // reserved
*buf_ptr++ = td.adr_ctrl;
*buf_ptr++ = td.trk_num;
*buf_ptr++ = 0; // reserved
if (is_msf) {
AddrMsf msf = lba_to_msf(td.start_lba + 150);
*buf_ptr++ = 0; // reserved
*buf_ptr++ = msf.min;
*buf_ptr++ = msf.sec;
*buf_ptr++ = msf.frm;
} else {
*buf_ptr++ = (td.start_lba >> 24) & 0xFFU;
*buf_ptr++ = (td.start_lba >> 16) & 0xFFU;
*buf_ptr++ = (td.start_lba >> 8) & 0xFFU;
*buf_ptr++ = (td.start_lba >> 0) & 0xFFU;
}
}
this->bytes_out = alloc_len;
this->msg_buf[0] = ScsiMessage::COMMAND_COMPLETE;
this->switch_phase(ScsiPhase::DATA_IN);
}
void ScsiCdrom::read_capacity()
{
uint32_t lba = READ_DWORD_BE_U(&this->cmd_buf[2]);
if (this->cmd_buf[1] & 1) {
ABORT_F("SCSI-CDROM: RelAdr bit set in READ_CAPACITY_10");
}
if (!(this->cmd_buf[8] & 1) && lba) {
LOG_F(ERROR, "SCSI-CDROM: non-zero LBA for PMI=0");
this->status = ScsiStatus::CHECK_CONDITION;
this->sense = ScsiSense::ILLEGAL_REQ;
this->switch_phase(ScsiPhase::STATUS);
return;
}
int last_lba = this->total_frames - 1;
this->data_buf[0] = (last_lba >> 24) & 0xFFU;
this->data_buf[1] = (last_lba >> 16) & 0xFFU;
this->data_buf[2] = (last_lba >> 8) & 0xFFU;
this->data_buf[3] = (last_lba >> 0) & 0xFFU;
this->data_buf[4] = 0;
this->data_buf[5] = 0;
this->data_buf[6] = (this->sector_size >> 8) & 0xFFU;
this->data_buf[7] = this->sector_size & 0xFFU;
this->bytes_out = 8;
this->msg_buf[0] = ScsiMessage::COMMAND_COMPLETE;
this->switch_phase(ScsiPhase::DATA_IN);
}
AddrMsf ScsiCdrom::lba_to_msf(const int lba)
{
return {.min = lba / 4500, .sec = (lba / 75) % 60, .frm = lba % 75};
}
static const PropMap ScsiCdromProperties = {
{"cdr_img", new StrProperty("")},
};
static const DeviceDescription ScsiCdromDescriptor =
{ScsiCdrom::create, {}, ScsiCdromProperties};
REGISTER_DEVICE(ScsiCdrom, ScsiCdromDescriptor);
-89
View File
@@ -1,89 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file SCSI CD-ROM definitions. */
#ifndef SCSI_CDROM_H
#define SCSI_CDROM_H
#include <devices/common/scsi/scsi.h>
#include <cinttypes>
#include <fstream>
#include <memory>
#include <string>
/* Original CD-ROM addressing mode expressed
in minutes, seconds and frames */
typedef struct {
int min;
int sec;
int frm;
} AddrMsf;
/* Descriptor for CD-ROM tracks in TOC */
typedef struct {
uint8_t trk_num;
uint8_t adr_ctrl;
uint32_t start_lba;
} TrackDescriptor;
#define CDROM_MAX_TRACKS 100
#define LEAD_OUT_TRK_NUM 0xAA
class ScsiCdrom : public ScsiDevice {
public:
ScsiCdrom(int my_id);
~ScsiCdrom() = default;
static std::unique_ptr<HWComponent> create() {
return std::unique_ptr<ScsiCdrom>(new ScsiCdrom(3));
}
void insert_image(std::string filename);
virtual void process_command();
virtual bool prepare_data();
protected:
void read(uint32_t lba, uint16_t transfer_len, uint8_t cmd_len);
void inquiry();
void mode_sense();
void read_toc();
void read_capacity();
private:
AddrMsf lba_to_msf(const int lba);
private:
std::fstream cdr_img;
uint64_t img_size;
int total_frames;
int num_tracks;
int sector_size;
bool eject_allowed = true;
int bytes_out = 0;
TrackDescriptor tracks[CDROM_MAX_TRACKS];
char data_buf[1 << 18]; // TODO: proper buffer management
};
#endif // SCSI_CDROM_H
-165
View File
@@ -1,165 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <core/timermanager.h>
#include <devices/common/scsi/scsi.h>
#include <loguru.hpp>
#include <cinttypes>
#include <cstring>
void ScsiDevice::notify(ScsiBus* bus_obj, ScsiMsg msg_type, int param)
{
if (msg_type == ScsiMsg::BUS_PHASE_CHANGE) {
switch (param) {
case ScsiPhase::RESET:
LOG_F(9, "ScsiDevice %d: bus reset aknowledged", this->scsi_id);
break;
case ScsiPhase::SELECTION:
// check if something tries to select us
if (bus_obj->get_data_lines() & (1 << scsi_id)) {
LOG_F(9, "ScsiDevice %d selected", this->scsi_id);
TimerManager::get_instance()->add_oneshot_timer(
BUS_SETTLE_DELAY,
[this, bus_obj]() {
// don't confirm selection if BSY or I/O are asserted
if (bus_obj->test_ctrl_lines(SCSI_CTRL_BSY | SCSI_CTRL_IO))
return;
bus_obj->assert_ctrl_line(this->scsi_id, SCSI_CTRL_BSY);
bus_obj->confirm_selection(this->scsi_id);
this->initiator_id = bus_obj->get_initiator_id();
this->bus_obj = bus_obj;
if (bus_obj->test_ctrl_lines(SCSI_CTRL_ATN)) {
this->switch_phase(ScsiPhase::MESSAGE_OUT);
if (this->msg_buf[0] != 0x80) {
LOG_F(INFO, "ScsiDevice: received message 0x%X", this->msg_buf[0]);
}
}
this->switch_phase(ScsiPhase::COMMAND);
this->process_command();
if (this->prepare_data()) {
bus_obj->assert_ctrl_line(this->scsi_id, SCSI_CTRL_REQ);
} else {
ABORT_F("ScsiDevice: prepare_data() failed");
}
});
}
break;
}
}
}
void ScsiDevice::switch_phase(const int new_phase)
{
this->cur_phase = new_phase;
this->bus_obj->switch_phase(this->scsi_id, this->cur_phase);
}
void ScsiDevice::next_step(ScsiBus* bus_obj)
{
switch (this->cur_phase) {
case ScsiPhase::COMMAND:
this->process_command();
this->switch_phase(ScsiPhase::DATA_IN);
break;
case ScsiPhase::DATA_OUT:
if (this->data_size >= this->incoming_size) {
if (this->post_xfer_action != nullptr) {
this->post_xfer_action();
}
this->switch_phase(ScsiPhase::STATUS);
}
break;
case ScsiPhase::DATA_IN:
if (!this->has_data()) {
this->switch_phase(ScsiPhase::STATUS);
}
break;
case ScsiPhase::STATUS:
this->switch_phase(ScsiPhase::MESSAGE_IN);
break;
case ScsiPhase::MESSAGE_IN:
case ScsiPhase::BUS_FREE:
bus_obj->release_ctrl_lines(this->scsi_id);
this->switch_phase(ScsiPhase::BUS_FREE);
break;
default:
LOG_F(WARNING, "ScsiDevice: nothing to do for phase %d", this->cur_phase);
}
}
void ScsiDevice::prepare_xfer(ScsiBus* bus_obj, int& bytes_in, int& bytes_out)
{
this->cur_phase = bus_obj->current_phase();
switch (this->cur_phase) {
case ScsiPhase::COMMAND:
this->data_ptr = this->cmd_buf;
this->data_size = bytes_in;
break;
case ScsiPhase::STATUS:
this->data_ptr = &this->status;
this->data_size = 1;
bytes_out = 1;
break;
case ScsiPhase::DATA_IN:
bytes_out = this->data_size;
break;
case ScsiPhase::DATA_OUT:
break;
case ScsiPhase::MESSAGE_OUT:
this->data_ptr = this->msg_buf;
this->data_size = bytes_in;
break;
case ScsiPhase::MESSAGE_IN:
this->data_ptr = this->msg_buf;
this->data_size = 1;
bytes_out = 1;
break;
default:
ABORT_F("ScsiDevice: unhandled phase %d in prepare_xfer()", this->cur_phase);
}
}
int ScsiDevice::send_data(uint8_t* dst_ptr, const int count)
{
if (dst_ptr == nullptr || !count) {
return 0;
}
int actual_count = std::min(this->data_size, count);
std::memcpy(dst_ptr, this->data_ptr, actual_count);
this->data_ptr += actual_count;
this->data_size -= actual_count;
return actual_count;
}
int ScsiDevice::rcv_data(const uint8_t* src_ptr, const int count)
{
// accumulating incoming data in the pre-configured buffer
std::memcpy(this->data_ptr, src_ptr, count);
this->data_ptr += count;
this->data_size += count;
return count;
}
-307
View File
@@ -1,307 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file Generic SCSI Hard Disk emulation. */
#include <devices/common/scsi/scsi.h>
#include <devices/common/scsi/scsihd.h>
#include <devices/deviceregistry.h>
#include <loguru.hpp>
#include <machines/machinebase.h>
#include <machines/machineproperties.h>
#include <memaccess.h>
#include <fstream>
#include <cstring>
#include <stdio.h>
#include <sys/stat.h>
#define HDD_SECTOR_SIZE 512
using namespace std;
ScsiHardDisk::ScsiHardDisk(int my_id) : ScsiDevice(my_id) {
supports_types(HWCompType::SCSI_DEV);
}
void ScsiHardDisk::insert_image(std::string filename) {
//We don't want to store everything in memory, but
//we want to keep the hard disk available.
this->hdd_img.open(filename, ios::out | ios::in | ios::binary);
struct stat stat_buf;
int rc = stat(filename.c_str(), &stat_buf);
if (!rc) {
this->img_size = stat_buf.st_size;
this->total_blocks = (this->img_size + HDD_SECTOR_SIZE - 1) / HDD_SECTOR_SIZE;
} else {
ABORT_F("ScsiHardDisk: could not determine file size using stat()");
}
this->hdd_img.seekg(0, std::ios_base::beg);
}
void ScsiHardDisk::process_command() {
uint32_t lba = 0;
uint16_t transfer_len = 0;
uint16_t alloc_len = 0;
uint8_t param_len = 0;
uint8_t page_code = 0;
uint8_t subpage_code = 0;
this->pre_xfer_action = nullptr;
this->post_xfer_action = nullptr;
// assume successful command execution
this->status = ScsiStatus::GOOD;
uint8_t* cmd = this->cmd_buf;
if (cmd[0] != 0 && cmd[0] != 8 && cmd[0] != 0xA && cmd[0] != 0x28
&& cmd[0] != 0x2A && cmd[0] != 0x25) {
ABORT_F("SCSI-HD: untested command 0x%X", cmd[0]);
}
switch (cmd[0]) {
case ScsiCommand::TEST_UNIT_READY:
test_unit_ready();
break;
case ScsiCommand::REWIND:
rewind();
break;
case ScsiCommand::REQ_SENSE:
alloc_len = cmd[4];
req_sense(alloc_len);
break;
case ScsiCommand::INQUIRY:
alloc_len = (cmd[3] << 8) + cmd[4];
inquiry(alloc_len);
break;
case ScsiCommand::READ_6:
lba = ((cmd[1] & 0x1F) << 16) + (cmd[2] << 8) + cmd[3];
transfer_len = cmd[4];
read(lba, transfer_len, 6);
break;
case ScsiCommand::READ_10:
lba = (cmd[2] << 24) + (cmd[3] << 16) + (cmd[4] << 8) + cmd[5];
transfer_len = (cmd[7] << 8) + cmd[8];
read(lba, transfer_len, 10);
break;
case ScsiCommand::WRITE_6:
lba = ((cmd[1] & 0x1F) << 16) + (cmd[2] << 8) + cmd[3];
transfer_len = cmd[4];
write(lba, transfer_len, 6);
break;
case ScsiCommand::WRITE_10:
lba = (cmd[2] << 24) + (cmd[3] << 16) + (cmd[4] << 8) + cmd[5];
transfer_len = (cmd[7] << 8) + cmd[8];
write(lba, transfer_len, 10);
this->switch_phase(ScsiPhase::DATA_OUT);
break;
case ScsiCommand::SEEK_6:
lba = ((cmd[1] & 0x1F) << 16) + (cmd[2] << 8) + cmd[3];
seek(lba);
break;
case ScsiCommand::MODE_SELECT_6:
param_len = cmd[4];
mode_select_6(param_len);
break;
case ScsiCommand::MODE_SENSE_6:
page_code = cmd[2] & 0x1F;
subpage_code = cmd[3];
alloc_len = cmd[4];
mode_sense_6(page_code, subpage_code, alloc_len);
break;
case ScsiCommand::READ_CAPACITY_10:
read_capacity_10();
break;
default:
LOG_F(WARNING, "SCSI_HD: unrecognized command: %x", cmd[0]);
}
}
bool ScsiHardDisk::prepare_data() {
switch (this->cur_phase) {
case ScsiPhase::DATA_IN:
this->data_ptr = (uint8_t*)this->img_buffer;
this->data_size = this->cur_buf_cnt;
break;
case ScsiPhase::DATA_OUT:
this->data_ptr = (uint8_t*)this->img_buffer;
this->data_size = 0;
break;
case ScsiPhase::STATUS:
if (!error) {
this->img_buffer[0] = ScsiStatus::GOOD;
} else {
this->img_buffer[0] = ScsiStatus::CHECK_CONDITION;
}
this->cur_buf_cnt = 1;
break;
case ScsiPhase::MESSAGE_IN:
this->img_buffer[0] = this->msg_code;
this->cur_buf_cnt = 1;
break;
default:
LOG_F(WARNING, "SCSI_HD: unexpected phase in prepare_data");
return false;
}
return true;
}
int ScsiHardDisk::test_unit_ready() {
this->switch_phase(ScsiPhase::STATUS);
return ScsiError::NO_ERROR;
}
int ScsiHardDisk::req_sense(uint16_t alloc_len) {
if (alloc_len != 252) {
LOG_F(WARNING, "Inappropriate Allocation Length: %d", alloc_len);
}
return ScsiError::NO_ERROR; // placeholder - no sense
}
void ScsiHardDisk::inquiry(uint16_t alloc_len) {
if (alloc_len >= 48) {
uint8_t empty_filler[1 << 17] = {0x0};
std::memcpy(img_buffer, empty_filler, (1 << 17));
img_buffer[2] = 0x1;
img_buffer[3] = 0x2;
img_buffer[4] = 0x31;
img_buffer[7] = 0x1C;
std::memcpy(img_buffer + 8, vendor_info, 8);
std::memcpy(img_buffer + 16, prod_info, 16);
std::memcpy(img_buffer + 32, rev_info, 8);
std::memcpy(img_buffer + 40, serial_info, 8);
}
else {
LOG_F(WARNING, "Inappropriate Allocation Length: %d", alloc_len);
}
}
int ScsiHardDisk::send_diagnostic() {
return 0x0;
}
int ScsiHardDisk::mode_select_6(uint8_t param_len) {
if (param_len == 0) {
return 0x0;
}
else {
LOG_F(WARNING, "Mode Select calling for param length of: %d", param_len);
return param_len;
}
}
void ScsiHardDisk::mode_sense_6(uint8_t page_code, uint8_t subpage_code, uint8_t alloc_len) {
LOG_F(WARNING, "Page Code %d; Subpage Code: %d", page_code, subpage_code);
}
void ScsiHardDisk::read_capacity_10() {
uint32_t lba = READ_DWORD_BE_U(&this->cmd_buf[2]);
if (this->cmd_buf[1] & 1) {
ABORT_F("SCSI-HD: RelAdr bit set in READ_CAPACITY_10");
}
if (!(this->cmd_buf[8] & 1) && lba) {
LOG_F(ERROR, "SCSI-HD: non-zero LBA for PMI=0");
this->status = ScsiStatus::CHECK_CONDITION;
this->sense = ScsiSense::ILLEGAL_REQ;
this->switch_phase(ScsiPhase::STATUS);
return;
}
uint32_t last_lba = this->total_blocks - 1;
uint32_t blk_len = HDD_SECTOR_SIZE;
WRITE_DWORD_BE_A(&img_buffer[0], last_lba);
WRITE_DWORD_BE_A(&img_buffer[4], blk_len);
this->cur_buf_cnt = 8;
this->msg_buf[0] = ScsiMessage::COMMAND_COMPLETE;
this->switch_phase(ScsiPhase::DATA_IN);
}
void ScsiHardDisk::format() {
}
void ScsiHardDisk::read(uint32_t lba, uint16_t transfer_len, uint8_t cmd_len) {
uint32_t transfer_size = transfer_len;
std::memset(img_buffer, 0, sizeof(img_buffer));
if (cmd_len == 6 && transfer_len == 0) {
transfer_size = 256;
}
transfer_size *= HDD_SECTOR_SIZE;
uint64_t device_offset = lba * HDD_SECTOR_SIZE;
this->hdd_img.seekg(device_offset, this->hdd_img.beg);
this->hdd_img.read(img_buffer, transfer_size);
this->cur_buf_cnt = transfer_size;
this->msg_buf[0] = ScsiMessage::COMMAND_COMPLETE;
this->switch_phase(ScsiPhase::DATA_IN);
}
void ScsiHardDisk::write(uint32_t lba, uint16_t transfer_len, uint8_t cmd_len) {
uint32_t transfer_size = transfer_len;
if (cmd_len == 6 && transfer_len == 0) {
transfer_size = 256;
}
transfer_size *= HDD_SECTOR_SIZE;
uint64_t device_offset = lba * HDD_SECTOR_SIZE;
this->incoming_size = transfer_size;
this->hdd_img.seekg(device_offset, this->hdd_img.beg);
this->post_xfer_action = [this]() {
this->hdd_img.write(this->img_buffer, this->incoming_size);
};
}
void ScsiHardDisk::seek(uint32_t lba) {
uint64_t device_offset = lba * HDD_SECTOR_SIZE;
this->hdd_img.seekg(device_offset, this->hdd_img.beg);
}
void ScsiHardDisk::rewind() {
this->hdd_img.seekg(0, this->hdd_img.beg);
}
static const PropMap SCSI_HD_Properties = {
{"hdd_img", new StrProperty("")},
{"hdd_wr_prot", new BinProperty(0)},
};
static const DeviceDescription SCSI_HD_Descriptor =
{ScsiHardDisk::create, {}, SCSI_HD_Properties};
REGISTER_DEVICE(ScsiHD, SCSI_HD_Descriptor);
-82
View File
@@ -1,82 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** @file SCSI hard drive definitions. */
#ifndef SCSI_HD_H
#define SCSI_HD_H
#include <devices/common/scsi/scsi.h>
#include <cinttypes>
#include <fstream>
#include <memory>
#include <stdio.h>
#include <string>
class ScsiHardDisk : public ScsiDevice {
public:
ScsiHardDisk(int my_id);
~ScsiHardDisk() = default;
static std::unique_ptr<HWComponent> create() {
return std::unique_ptr<ScsiHardDisk>(new ScsiHardDisk(0));
}
void insert_image(std::string filename);
void process_command();
bool prepare_data();
protected:
int test_unit_ready();
int req_sense(uint16_t alloc_len);
int send_diagnostic();
int mode_select_6(uint8_t param_len);
void mode_sense_6(uint8_t page_code, uint8_t subpage_code, uint8_t alloc_len);
void format();
void inquiry(uint16_t alloc_len);
void read_capacity_10();
void read(uint32_t lba, uint16_t transfer_len, uint8_t cmd_len);
void write(uint32_t lba, uint16_t transfer_len, uint8_t cmd_len);
void seek(uint32_t lba);
void rewind();
private:
std::fstream hdd_img;
uint64_t img_size;
int total_blocks;
uint64_t file_offset = 0;
char img_buffer[1 << 21]; // TODO: add proper buffer management!
uint32_t cur_buf_cnt = 0;
uint8_t error = ScsiError::NO_ERROR;
uint8_t msg_code = 0;
//inquiry info
char vendor_info[8] = {'D', 'i', 'n', 'g', 'u', 's', 'D', '\0'};
char prod_info[16] = {'E', 'm', 'u', 'l', 'a', 't', 'e', 'd', ' ', 'D', 'i', 's', 'k', '\0'};
char rev_info[8] = {'d', 'i', '0', '0', '0', '0', '0', '1'};
char serial_info[8] = {'0', '0', '0', '0', '0', '0', '0', '0'};
};
#endif // SCSI_HD_H
+16 -8
View File
@@ -93,8 +93,8 @@ int ViaCuda::device_postinit()
}
void ViaCuda::cuda_init() {
this->old_tip = 1;
this->old_byteack = 1;
this->old_tip = 0;
this->old_byteack = 0;
this->treq = 1;
this->in_count = 0;
this->out_count = 0;
@@ -260,6 +260,10 @@ void ViaCuda::update_irq()
}
}
inline bool ViaCuda::ready() {
return ((this->via_regs[VIA_DIRB] & 0x38) == 0x30);
}
void ViaCuda::assert_sr_int() {
this->sr_timer_on = false;
this->_via_ifr |= VIA_IF_SR;
@@ -318,6 +322,11 @@ void ViaCuda::schedule_sr_int(uint64_t timeout_ns) {
}
void ViaCuda::write(uint8_t new_state) {
if (!ready()) {
LOG_F(WARNING, "Cuda not ready!");
return;
}
int new_tip = !!(new_state & CUDA_TIP);
int new_byteack = !!(new_state & CUDA_BYTEACK);
@@ -339,12 +348,8 @@ void ViaCuda::write(uint8_t new_state) {
process_packet();
/* start response transaction */
TimerManager::get_instance()->add_oneshot_timer(
USECS_TO_NSECS(13), // delay TREQ assertion for New World
[this]() {
this->via_regs[VIA_B] &= ~CUDA_TREQ; // assert TREQ
this->treq = 0;
});
this->via_regs[VIA_B] &= ~CUDA_TREQ; /* assert TREQ */
this->treq = 0;
}
this->in_count = 0;
@@ -357,6 +362,7 @@ void ViaCuda::write(uint8_t new_state) {
}
// send dummy byte as idle acknowledge or attention
//assert_sr_int();
schedule_sr_int(USECS_TO_NSECS(61));
} else {
if (this->via_regs[VIA_ACR] & 0x10) { /* data transfer: Host --> Cuda */
@@ -364,11 +370,13 @@ void ViaCuda::write(uint8_t new_state) {
this->in_buf[this->in_count++] = this->via_regs[VIA_SR];
// tell the system we've read the byte after 71 usecs
schedule_sr_int(USECS_TO_NSECS(71));
//assert_sr_int();
} else {
LOG_F(WARNING, "Cuda input buffer too small. Truncating data!");
}
} else { /* data transfer: Cuda --> Host */
(this->*out_handler)();
//assert_sr_int();
// tell the system we've written next byte after 88 usecs
schedule_sr_int(USECS_TO_NSECS(88));
}
+1
View File
@@ -237,6 +237,7 @@ private:
// CUDA methods
void cuda_init();
bool ready();
void write(uint8_t new_state);
void response_header(uint32_t pkt_type, uint32_t pkt_flag);
void error_response(uint32_t error);
+48 -126
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
Copyright (C) 2018-21 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -21,8 +21,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file Support for reading and writing of various floppy images. */
#include <devices/floppy/floppyimg.h>
#include <machines/machineproperties.h>
#include "floppyimg.h"
#include <loguru.hpp>
#include <memaccess.h>
@@ -68,14 +67,27 @@ static FlopImgType identify_image(std::ifstream& img_file)
return FlopImgType::UNKNOWN;
}
static int64_t get_hfs_vol_size(const uint8_t *mdb_data)
{
uint16_t drNmAlBlks = READ_WORD_BE_A(&mdb_data[18]);
uint32_t drAlBlkSiz = READ_DWORD_BE_A(&mdb_data[20]);
// calculate size of the volume bitmap
uint32_t vol_bmp_size = (((drNmAlBlks + 8) >> 3) + 512) & 0xFFFFFE00UL;
return (drNmAlBlks * drAlBlkSiz + vol_bmp_size + 3*BLOCK_SIZE);
}
//======================= RAW IMAGE CONVERTER ============================
RawFloppyImg::RawFloppyImg(std::string& file_path) : FloppyImgConverter()
{
this->img_path = file_path;
}
/**
For raw images, we'll attempt to guess disk format based on image size.
/** For raw images, we're going to ensure that the data fits into
one of the supported floppy disk sizes as well as image size
matches the size of the embedded HFS/MFS volume.
Then we'll attempt to guess disk format based on image size.
*/
int RawFloppyImg::calc_phys_params()
{
@@ -90,46 +102,50 @@ int RawFloppyImg::calc_phys_params()
// determine image size
img_file.seekg(0, img_file.end);
size_t img_size = img_file.tellg();
if (img_size > 2*1024*1024) {
LOG_F(ERROR, "RawFloppyImg: image size is too large to determine disk format from image size!");
return -1;
}
this->img_size = (int)img_size;
this->img_size = img_file.tellg();
img_file.seekg(0, img_file.beg);
img_file.close();
// verify image size
if (this->img_size < 5*BLOCK_SIZE) {
img_file.close();
LOG_F(ERROR, "RawFloppyImg: image too short!");
return -1;
}
if (this->img_size > MFM_HD_SIZE) {
img_file.close();
LOG_F(ERROR, "RawFloppyImg: image too big!");
return -1;
}
// raw images don't include anything other than raw disk data
this->data_size = this->img_size;
// read Master Directory Block from logical block 2
uint8_t buf[512] = { 0 };
// see if user has specified disk format manually
std::string fmt = GET_STR_PROP("fdd_fmt");
if (!fmt.empty()) {
if (fmt == "GCR_400K") {
this->img_size = 409600;
} else if (fmt == "GCR_800K") {
this->img_size = 819200;
} else if (fmt == "MFM_720K") {
this->img_size = 737280;
} else if (fmt == "MFM_1440K") {
this->img_size = 1474560;
} else {
LOG_F(WARNING, "Invalid floppy disk format %s", fmt.c_str());
}
img_file.seekg(2*BLOCK_SIZE, img_file.beg);
img_file.read((char *)buf, sizeof(buf));
img_file.close();
uint64_t vol_size = 0;
if (buf[0] == 0x42 && buf[1] == 0x44) {
// check HFS volume size
vol_size = get_hfs_vol_size(buf);
} else if (buf[0] == 0xD2 && buf[1] == 0xD7) {
// check MFS volume size
} else {
LOG_F(ERROR, "RawFloppyImg: unknown volume type!");
return -1;
}
if (vol_size > this->img_size) {
LOG_F(INFO, "RawFloppyImg: volume size > image size!");
LOG_F(INFO, "Volume size: %llu, Image size: %d", vol_size, this->img_size);
return -1;
}
// raw images don't include anything than raw disk data
this->data_size = this->img_size;
// guess disk format from image file size
static struct {
int capacity;
@@ -199,102 +215,9 @@ int RawFloppyImg::export_data()
return 0;
}
// ====================== DISK COPY 4.2 IMAGE CONVERTER ======================
DiskCopy42Img::DiskCopy42Img(std::string& file_path) : FloppyImgConverter()
{
this->img_path = file_path;
}
int DiskCopy42Img::calc_phys_params() {
std::ifstream img_file;
img_file.open(img_path, std::ios::in | std::ios::binary);
if (img_file.fail()) {
img_file.close();
LOG_F(ERROR, "DiskCopy42Img: could not open specified floppy image!");
return -1;
}
// determine image size
img_file.seekg(0, img_file.end);
size_t img_size = img_file.tellg();
img_file.seekg(0, img_file.beg);
// get data size from image
uint8_t buf[4];
img_file.seekg(0x40, img_file.beg);
img_file.read((char *)&buf, 4);
this->data_size = READ_DWORD_BE_U(buf);
if (this->data_size > img_size) {
img_file.close();
LOG_F(ERROR, "DiskCopy42Img: invalid data size %d", this->data_size);
return -1;
}
this->img_size = (int)img_size;
uint8_t disk_format = 0xFFU;
img_file.seekg(0x50, img_file.beg);
img_file.read((char *)&disk_format, 1);
img_file.read((char *)&this->format_byte, 1);
img_file.close();
this->density = 0; // assume double density by default
this->num_tracks = 80;
this->num_sides = ((this->format_byte >> 5) & 1) + 1;
switch (disk_format) {
case 0:
case 1:
this->rec_method = 0; // GCR
this->num_sectors = 800;
break;
case 2:
this->rec_method = 1; // MFM
this->num_sectors = 1440;
this->format_byte = 2;
break;
case 3:
this->rec_method = 1; // MFM
this->density = 1; // report high density
this->num_sectors = 2880;
this->format_byte = 2;
break;
default:
LOG_F(ERROR, "DiskCopy42Img: invalid disk format %X", disk_format);
return -1;
}
return 0;
}
int DiskCopy42Img::get_raw_disk_data(char* buf) {
std::ifstream img_file;
img_file.open(img_path, std::ios::in | std::ios::binary);
if (img_file.fail()) {
img_file.close();
LOG_F(ERROR, "DiskCopy42Img: could not open specified floppy image!");
return -1;
}
img_file.seekg(0x54, img_file.beg);
img_file.read(buf, this->data_size);
img_file.close();
return 0;
}
int DiskCopy42Img::export_data(void) {
return 0;
}
FloppyImgConverter* open_floppy_image(std::string& img_path)
{
FloppyImgConverter *fconv = nullptr;
FloppyImgConverter *fconv;
std::ifstream img_file;
@@ -316,15 +239,14 @@ FloppyImgConverter* open_floppy_image(std::string& img_path)
break;
case FlopImgType::DC42:
LOG_F(INFO, "Disk Copy 4.2 image");
fconv = new DiskCopy42Img(img_path);
break;
case FlopImgType::WOZ1:
case FlopImgType::WOZ2:
LOG_F(INFO, "WOZ v%s image", (itype == FlopImgType::WOZ2) ? "2" : "1");
break;
default:
LOG_F(WARNING, "Unknown image format - assume RAW");
fconv = new RawFloppyImg(img_path);
LOG_F(ERROR, "Unknown/unsupported image format!");
return nullptr;
}
if (fconv->calc_phys_params()) {
+1 -12
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
Copyright (C) 2018-21 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -82,17 +82,6 @@ public:
int export_data(void);
};
/** Converter for Disk Copy 4.2 images. */
class DiskCopy42Img : public FloppyImgConverter {
public:
DiskCopy42Img(std::string& file_path);
~DiskCopy42Img() = default;
int calc_phys_params(void);
int get_raw_disk_data(char* buf);
int export_data(void);
};
extern FloppyImgConverter* open_floppy_image(std::string& img_path);
#endif // FLOPPY_IMG_H
+22 -141
View File
@@ -21,7 +21,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file Macintosh Superdrive emulation. */
#include <core/timermanager.h>
#include <devices/floppy/floppyimg.h>
#include <devices/floppy/superdrive.h>
#include <loguru.hpp>
@@ -36,22 +35,13 @@ MacSuperDrive::MacSuperDrive()
this->name = "Superdrive";
this->supported_types = HWCompType::FLOPPY_DRV;
this->media_kind = MediaKind::high_density;
this->has_disk = 0; // drive is empty
this->eject_latch = 0; // eject latch is off
this->reset_params();
}
void MacSuperDrive::reset_params()
{
this->media_kind = MediaKind::high_density;
this->has_disk = 0; // drive is empty
this->motor_stat = 0; // spindle motor is off
this->motor_on_time = 0;
this->cur_track = 0; // current head position
this->is_ready = 0; // drive not ready
// come up in the MFM mode by default
this->switch_drive_mode(RecMethod::MFM);
this->drive_mode = RecMethod::MFM; // assume MFM mode by default
this->motor_stat = 0; // spindle motor is off
this->cur_track = 0; // current head position
this->is_ready = 0; // drive not ready
}
void MacSuperDrive::command(uint8_t addr, uint8_t value)
@@ -77,25 +67,13 @@ void MacSuperDrive::command(uint8_t addr, uint8_t value)
if (this->motor_stat != new_motor_stat) {
this->motor_stat = new_motor_stat;
if (new_motor_stat) {
this->motor_on_time = TimerManager::get_instance()->current_time_ns();
this->track_start_time = 0;
this->sector_start_time = 0;
this->init_track_search(-1);
this->is_ready = 1;
LOG_F(INFO, "Superdrive: turn spindle motor on");
} else {
this->motor_on_time = 0;
this->is_ready = 0;
LOG_F(INFO, "Superdrive: turn spindle motor off");
}
}
break;
case CommandAddr::Eject_Disk:
if (value) {
LOG_F(INFO, "Superdrive: disk ejected");
this->eject_latch = 1;
this->reset_params();
}
case CommandAddr::Reset_Eject_Latch:
if (value) {
this->eject_latch = 0;
@@ -124,7 +102,8 @@ uint8_t MacSuperDrive::status(uint8_t addr)
case StatusAddr::Eject_Latch:
return this->eject_latch;
case StatusAddr::Select_Head_0:
return this->cur_head = 0;
this->cur_head = 0;
return 1; // not sure what should be returned here
case StatusAddr::MFM_Support:
return 1; // Superdrive does support MFM encoding scheme
case StatusAddr::Double_Sided:
@@ -138,7 +117,8 @@ uint8_t MacSuperDrive::status(uint8_t addr)
case StatusAddr::Track_Zero:
return this->track_zero ^ 1; // reverse logic
case StatusAddr::Select_Head_1:
return this->cur_head = 1;
this->cur_head = 1;
return 1; // not sure what should be returned here
case StatusAddr::Drive_Mode:
return this->drive_mode;
case StatusAddr::Drive_Ready:
@@ -224,138 +204,39 @@ void MacSuperDrive::switch_drive_mode(int mode)
this->track2lblk[trk] = trk * sectors_per_track * 2;
}
// set up disk timing parameters
this->index_delay = MFM_INDX_MARK_DELAY;
this->addr_mark_delay = MFM_ADR_MARK_DELAY;
if (this->media_kind) {
this->sector_delay = MFM_HD_SECTOR_DELAY;
this->eot_delay = MFM_HD_EOT_DELAY;
} else {
this->sector_delay = MFM_DD_SECTOR_DELAY;
this->eot_delay = MFM_DD_EOT_DELAY;
}
this->drive_mode = RecMethod::MFM;
}
}
double MacSuperDrive::get_current_track_delay()
{
return 60.0f / this->rpm_per_track[this->cur_track];
return (1.0f / (this->rpm_per_track[this->cur_track] / 60));
}
double MacSuperDrive::get_sector_delay()
{
return this->get_current_track_delay() / this->sectors_per_track[this->cur_track];
}
void MacSuperDrive::init_track_search(int pos)
{
if (pos == -1) {
// pick random sector number
uint64_t seed = TimerManager::get_instance()->current_time_ns() >> 8;
this->cur_sector = seed % this->sectors_per_track[this->cur_track];
LOG_F(9, "Superdrive: current sector number set to %d", this->cur_sector);
this->cur_sector = this->sectors_per_track[this->cur_track] / 2;
} else {
this->cur_sector = pos;
}
}
uint64_t MacSuperDrive::sync_to_disk()
SectorHdr MacSuperDrive::next_sector_header()
{
uint64_t cur_time_ns, track_time_ns;
uint64_t track_delay = this->get_current_track_delay() * NS_PER_SEC;
// look how much ns have been elapsed since the last motor enabling
cur_time_ns = TimerManager::get_instance()->current_time_ns() - this->motor_on_time;
if (!this->track_start_time ||
(cur_time_ns - this->track_start_time) >= track_delay) {
// subtract full disk revolutions
track_time_ns = cur_time_ns % track_delay;
this->track_start_time = cur_time_ns - track_time_ns;
// return delay until the first address mark if we're currently
// looking at the end of track
if (track_time_ns >= this->eot_delay) {
this->next_sector = 0;
// CHEAT: don't account for the remaining time of the current track
return this->index_delay + this->addr_mark_delay;
}
// return delay until the first address mark
// if the first address mark was not reached yet
if (track_time_ns < this->index_delay) {
this->next_sector = 0;
return this->index_delay + this->addr_mark_delay - track_time_ns;
}
} else {
track_time_ns = cur_time_ns - this->track_start_time;
this->cur_sector++;
if (this->cur_sector >= this->sectors_per_track[this->cur_track]) {
this->cur_sector = 0;
}
// subtract index field delay
track_time_ns -= this->index_delay;
// calculate current sector number from timestamp
int cur_sect_num = this->cur_sector = (int)(track_time_ns / this->sector_delay);
this->sector_start_time = this->track_start_time + cur_sect_num * this->sector_delay +
this->index_delay;
if (this->cur_sector + 1 >= this->sectors_per_track[this->cur_track]) {
uint64_t diff = track_delay - (cur_time_ns - this->track_start_time);
this->next_sector = 0;
this->track_start_time = 0;
this->sector_start_time = 0;
return diff + this->index_delay + this->addr_mark_delay;
} else {
this->next_sector = this->cur_sector + 1;
uint64_t diff = cur_time_ns - this->sector_start_time;
this->sector_start_time += this->sector_delay;
return this->sector_delay - diff + this->addr_mark_delay;
}
}
uint64_t MacSuperDrive::next_addr_mark_delay(uint8_t *next_sect_num)
{
uint64_t delay;
if (this->cur_sector + 1 >= this->sectors_per_track[this->cur_track]) {
this->next_sector = 0;
delay = this->index_delay + this->addr_mark_delay;
} else {
this->next_sector = this->cur_sector + 1;
delay = this->addr_mark_delay;
}
if (next_sect_num) {
*next_sect_num = this->next_sector + ((this->rec_method == RecMethod::MFM) ? 1 : 0);
}
return delay;
}
uint64_t MacSuperDrive::next_sector_delay()
{
if (this->cur_sector + 1 >= this->sectors_per_track[this->cur_track]) {
this->next_sector = 0;
return this->sector_delay + this->index_delay + this->addr_mark_delay;
}
this->next_sector = this->cur_sector + 1;
return this->sector_delay - this->addr_mark_delay;
}
uint64_t MacSuperDrive::sector_data_delay()
{
return MFM_SECT_DATA_DELAY;
}
SectorHdr MacSuperDrive::current_sector_header()
{
this->cur_sector = this->next_sector;
// MFM sector numbering is 1-based so we need to bump sector number
uint8_t sector_num = this->cur_sector + ((this->rec_method == RecMethod::MFM) ? 1 : 0);
int sector_num = this->cur_sector + ((this->rec_method == RecMethod::MFM) ? 1 : 0);
return SectorHdr {
this->cur_track,
+27 -59
View File
@@ -24,7 +24,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef MAC_SUPERDRIVE_H
#define MAC_SUPERDRIVE_H
#include <core/timermanager.h>
#include <devices/common/hwcomponent.h>
#include <devices/floppy/floppyimg.h>
@@ -32,19 +31,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <memory>
#include <string>
// convert number of bytes to disk time = nbytes * bits_per_byte * 2 us
#define MFM_BYTES_TO_DISK_TIME(bytes) USECS_TO_NSECS((bytes) * 8 * 2)
// timing constans for MFM disks
constexpr uint32_t MFM_INDX_MARK_DELAY = MFM_BYTES_TO_DISK_TIME(146);
constexpr uint32_t MFM_ADR_MARK_DELAY = MFM_BYTES_TO_DISK_TIME(22);
constexpr uint32_t MFM_SECT_DATA_DELAY = MFM_BYTES_TO_DISK_TIME(514);
constexpr uint32_t MFM_DD_SECTOR_DELAY = MFM_BYTES_TO_DISK_TIME(658);
constexpr uint32_t MFM_HD_SECTOR_DELAY = MFM_BYTES_TO_DISK_TIME(675);
constexpr uint32_t MFM_DD_EOT_DELAY = MFM_BYTES_TO_DISK_TIME( 6250 - 182);
constexpr uint32_t MFM_HD_EOT_DELAY = MFM_BYTES_TO_DISK_TIME(12500 - 204);
namespace MacSuperdrive {
/** Apple Drive status request addresses. */
@@ -70,7 +56,6 @@ enum CommandAddr : uint8_t {
Step_Direction = 0,
Do_Step = 1,
Motor_On_Off = 2,
Eject_Disk = 3,
Reset_Eject_Latch = 4,
Switch_Drive_Mode = 5,
};
@@ -88,10 +73,10 @@ enum RecMethod : int {
};
typedef struct SectorHdr {
int track;
int side;
int sector;
int format;
int track;
int side;
int sector;
int format;
} SectorHdr;
class MacSuperDrive : public HWComponent {
@@ -102,55 +87,38 @@ public:
void command(uint8_t addr, uint8_t value);
uint8_t status(uint8_t addr);
int insert_disk(std::string& img_path, int write_flag);
void init_track_search(int pos);
uint64_t sync_to_disk();
uint64_t next_addr_mark_delay(uint8_t *next_sect_num);
uint64_t next_sector_delay();
SectorHdr current_sector_header();
char* get_sector_data_ptr(int sector_num);
uint64_t sector_data_delay();
double get_current_track_delay();
double get_address_mark_delay();
double get_sector_delay();
void init_track_search(int pos);
SectorHdr next_sector_header();
char* get_sector_data_ptr(int sector_num);
protected:
void reset_params();
void set_disk_phys_params();
void switch_drive_mode(int mode);
private:
uint8_t has_disk;
uint8_t eject_latch;
uint8_t motor_stat; // spindle motor status: 1 - on, 0 - off
uint8_t drive_mode; // drive mode: 0 - GCR, 1 - MFM
uint8_t is_ready;
uint8_t track_zero; // 1 - if head is at track zero
int step_dir; // step direction -1/+1
int cur_track; // track number the head is currently at
int cur_head; // current head number: 1 - upper, 0 - lower
int cur_sector; // current sector number
int next_sector; // next sector number
uint64_t motor_on_time = 0; // time in ns the spindle motor was switched on
uint64_t track_start_time = 0;
uint64_t sector_start_time = 0;
uint8_t has_disk;
uint8_t eject_latch;
uint8_t motor_stat; // spindle motor status: 1 - on, 0 - off
uint8_t drive_mode; // drive mode: 0 - GCR, 1 - MFM
uint8_t is_ready;
uint8_t track_zero; // 1 - if head is at track zero
int step_dir; // step direction -1/+1
int cur_track; // track number the head is currently at
int cur_head; // current head number: 1 - upper, 0 - lower
int cur_sector; // current sector number
// physical parameters of the currently inserted disk
uint8_t media_kind;
uint8_t wr_protect;
uint8_t format_byte;
int rec_method;
int num_tracks;
int num_sides;
int sectors_per_track[80];
int rpm_per_track[80];
int track2lblk[80]; // convert track number to first logical block number
// timing parameters for MFM disks
uint32_t index_delay; // number of ns needed to read the index mark
uint32_t addr_mark_delay; // number of ns needed to read an address index mark
uint32_t sector_delay; // number of ns needed to read a sector
uint32_t eot_delay; // number of ns until end of track gap
uint8_t media_kind;
uint8_t wr_protect;
uint8_t format_byte;
int rec_method;
int num_tracks;
int num_sides;
int sectors_per_track[80];
int rpm_per_track[80];
int track2lblk[80]; // convert track number to first logical block number
std::unique_ptr<FloppyImgConverter> img_conv;
+61 -134
View File
@@ -33,7 +33,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cinttypes>
#include <memory>
#include <string>
#include <vector>
using namespace Swim3;
@@ -42,17 +41,14 @@ Swim3Ctrl::Swim3Ctrl()
this->name = "SWIM3";
this->supported_types = HWCompType::FLOPPY_CTRL;
this->setup_reg = 0;
this->mode_reg = 0;
this->int_reg = 0;
this->int_flags = 0;
this->int_mask = 0;
this->error = 0;
this->step_count = 0;
this->xfer_cnt = 0;
this->first_sec = 0xFF;
this->cur_state = SWIM3_IDLE;
this->setup_reg = 0;
this->mode_reg = 0;
this->int_reg = 0;
this->int_flags = 0;
this->int_mask = 0;
this->error = 0;
this->xfer_cnt = 0;
this->first_sec = 0xFF;
// Attach virtual Superdrive to the internal drive connector
// TODO: make SWIM3/drive wiring user selectable
@@ -78,11 +74,9 @@ int Swim3Ctrl::device_postinit()
uint8_t Swim3Ctrl::read(uint8_t reg_offset)
{
uint8_t status_addr, rddata_val, old_int_flags, old_error;
uint8_t status_addr, status_val, old_int_flags, old_error;
switch(reg_offset) {
case Swim3Reg::Timer:
return this->calc_timer_val();
case Swim3Reg::Error:
old_error = this->error;
this->error = 0;
@@ -94,20 +88,18 @@ uint8_t Swim3Ctrl::read(uint8_t reg_offset)
case Swim3Reg::Handshake_Mode1:
if (this->mode_reg & 2) { // internal drive?
status_addr = ((this->mode_reg & 0x20) >> 2) | (this->phase_lines & 7);
rddata_val = this->int_drive->status(status_addr) & 1;
status_val = this->int_drive->status(status_addr) & 1;
// transfer rddata_val to both bit 2 (RDDATA) and bit 3 (SENSE)
// transfer status_val to both bit 2 (RDDATA) and bit 3 (SENSE)
// because those signals seem to be historically wired together
return (rddata_val << 2) | (rddata_val << 3);
return ((status_val << 2) | (status_val << 3));
}
return 0xC; // report both RdData & Sense high
return 4;
case Swim3Reg::Interrupt_Flags:
old_int_flags = this->int_flags;
this->int_flags = 0; // read from this register clears all flags
update_irq();
return old_int_flags;
case Swim3Reg::Step:
return this->step_count;
case Swim3Reg::Current_Track:
return this->cur_track;
case Swim3Reg::Current_Sector:
@@ -128,27 +120,21 @@ uint8_t Swim3Ctrl::read(uint8_t reg_offset)
void Swim3Ctrl::write(uint8_t reg_offset, uint8_t value)
{
uint8_t status_addr;
uint8_t old_mode_reg;
switch(reg_offset) {
case Swim3Reg::Timer:
this->init_timer(value);
break;
case Swim3Reg::Param_Data:
this->pram = value;
break;
case Swim3Reg::Phase:
this->phase_lines = value & 0xF;
if (this->phase_lines & 8) { // CA3 aka LSTRB high -> sending a command to the drive
if (this->mode_reg & 2) { // if internal drive is selected
if (value & 8) {
if (this->mode_reg & 2) { // internal drive?
this->int_drive->command(
((this->mode_reg & 0x20) >> 3) | (this->phase_lines & 3),
(value >> 2) & 1
);
}
} else if (this->phase_lines == 4 && (this->mode_reg & 2)) {
status_addr = ((this->mode_reg & 0x20) >> 2) | (this->phase_lines & 7);
this->rd_line = this->int_drive->status(status_addr) & 1;
}
break;
case Swim3Reg::Setup:
@@ -291,66 +277,53 @@ void Swim3Ctrl::start_disk_access()
this->mode_reg |= SWIM3_GO;
LOG_F(9, "SWIM3: disk access started!");
this->target_sect = this->first_sec;
this->access_timer_id = TimerManager::get_instance()->add_oneshot_timer(
this->int_drive->sync_to_disk(),
[this]() {
this->cur_state = SWIM3_ADDR_MARK_SEARCH;
this->disk_access();
}
);
}
void Swim3Ctrl::disk_access()
{
MacSuperdrive::SectorHdr hdr;
uint64_t delay;
switch(this->cur_state) {
case SWIM3_ADDR_MARK_SEARCH:
hdr = this->int_drive->current_sector_header();
// update the corresponding SWIM3 registers
this->cur_track = ((hdr.side & 1) << 7) | (hdr.track & 0x7F);
this->cur_sector = 0x80 /* CRC/checksum valid */ | (hdr.sector & 0x7F);
this->format = hdr.format;
// generate ID_read interrupt
this->int_flags |= INT_ID_READ;
update_irq();
if ((this->cur_sector & 0x7F) == this->target_sect) {
// sector matches -> transfer its data
this->cur_state = SWIM3_DATA_XFER;
delay = this->int_drive->sector_data_delay();
} else {
// move to next address mark
this->cur_state = SWIM3_ADDR_MARK_SEARCH;
delay = this->int_drive->next_sector_delay();
}
break;
case SWIM3_DATA_XFER:
// transfer sector data over DMA
this->dma_ch->push_data(this->int_drive->get_sector_data_ptr(this->cur_sector & 0x7F), 512);
if (--this->xfer_cnt == 0) {
this->stop_disk_access();
// generate sector_done interrupt
this->int_flags |= INT_SECT_DONE;
update_irq();
return;
}
this->cur_state = SWIM3_ADDR_MARK_SEARCH;
delay = this->int_drive->next_addr_mark_delay(&this->target_sect);
break;
default:
LOG_F(ERROR, "SWIM3: unknown disk access phase 0x%X", this->cur_state);
return;
if (this->first_sec == 0xFF) {
// $FF means no sector to match ->
// generate ID_read interrups as long as the GO bit is set
this->int_drive->init_track_search(-1); // start at random sector
} else {
this->cur_sector = this->first_sec;
}
this->access_timer_id = TimerManager::get_instance()->add_oneshot_timer(
delay,
[this]() {
this->disk_access();
}
);
// HACK: figure out from bits in int_mask register which kind of disk access is requested
if (this->int_mask & INT_ID_READ) { // read address header
this->access_timer_id = TimerManager::get_instance()->add_cyclic_timer(
static_cast<uint64_t>(this->int_drive->get_sector_delay() * NS_PER_SEC + 0.5f),
[this]() {
// get next sector's address field
MacSuperdrive::SectorHdr addr = this->int_drive->next_sector_header();
// set up the corresponding SWIM3 registers
this->cur_track = ((addr.side & 1) << 7) | (addr.track & 0x7F);
this->cur_sector = 0x80 /* CRC/checksum valid */ | (addr.sector & 0x7F);
this->format = addr.format;
// generate ID_read interrupt
this->int_flags |= INT_ID_READ;
update_irq();
}
);
} else { // otherwise, read sector data
this->access_timer_id = TimerManager::get_instance()->add_cyclic_timer(
static_cast<uint64_t>(this->int_drive->get_sector_delay() * NS_PER_SEC + 0.5f),
[this]() {
// transfer sector data over DMA
this->dma_ch->push_data(this->int_drive->get_sector_data_ptr(this->cur_sector), 512);
// get next address field
MacSuperdrive::SectorHdr addr = this->int_drive->next_sector_header();
// set up the corresponding SWIM3 registers
this->cur_track = ((addr.side & 1) << 7) | (addr.track & 0x7F);
this->cur_sector = 0x80 /* CRC/checksum valid */ | (addr.sector & 0x7F);
this->format = addr.format;
if (--this->xfer_cnt == 0) {
this->stop_disk_access();
// generate sector_done interrupt
this->int_flags |= INT_SECT_DONE;
update_irq();
}
}
);
}
}
void Swim3Ctrl::stop_disk_access()
@@ -362,57 +335,11 @@ void Swim3Ctrl::stop_disk_access()
this->access_timer_id = 0;
}
void Swim3Ctrl::init_timer(const uint8_t start_val)
{
if (this->timer_val) {
LOG_F(WARNING, "SWIM3: attempt to re-arm the timer");
}
this->timer_val = start_val;
if (!this->timer_val) {
this->one_us_timer_start = 0;
return;
}
this->one_us_timer_start = TimerManager::get_instance()->current_time_ns();
this->one_us_timer_id = TimerManager::get_instance()->add_oneshot_timer(
this->timer_val * NS_PER_USEC,
[this]() {
this->timer_val = 0;
this->int_flags |= INT_TIMER_DONE;
update_irq();
}
);
}
uint8_t Swim3Ctrl::calc_timer_val()
{
if (!this->timer_val) {
return 0;
}
uint64_t time_now = TimerManager::get_instance()->current_time_ns();
uint64_t us_elapsed = (time_now - this->one_us_timer_start) / NS_PER_USEC;
if (us_elapsed > this->timer_val) {
return 0;
} else {
return (this->timer_val - us_elapsed) & 0xFFU;
}
}
// floppy disk formats properties for the cases
// where disk format needs to be specified manually
static const std::vector<std::string> FloppyFormats = {
"", "GCR_400K", "GCR_800K", "MFM_720K", "MFM_1440K"
};
static const PropMap Swim3_Properties = {
{"fdd_img",
new StrProperty("")},
{"fdd_wr_prot",
new BinProperty(0)},
{"fdd_fmt",
new StrProperty("", FloppyFormats)},
};
static const DeviceDescription Swim3_Descriptor = {
+9 -27
View File
@@ -64,17 +64,9 @@ enum {
/** Interrupt flags. */
enum {
INT_TIMER_DONE = 0x01,
INT_STEP_DONE = 0x02,
INT_ID_READ = 0x04,
INT_SECT_DONE = 0x08,
};
// SWIM3 internal states.
enum {
SWIM3_IDLE,
SWIM3_ADDR_MARK_SEARCH,
SWIM3_DATA_XFER,
INT_STEP_DONE = 0x02,
INT_ID_READ = 0x04,
INT_SECT_DONE = 0x08,
};
class Swim3Ctrl : public HWComponent {
@@ -97,22 +89,18 @@ public:
};
protected:
void update_irq();
void start_stepping();
void do_step();
void stop_stepping();
void start_disk_access();
void disk_access();
void stop_disk_access();
void init_timer(const uint8_t start_val);
uint8_t calc_timer_val();
void update_irq();
void start_stepping();
void do_step();
void stop_stepping();
void start_disk_access();
void stop_disk_access();
private:
std::unique_ptr<MacSuperdrive::MacSuperDrive> int_drive;
DmaBidirChannel* dma_ch;
uint8_t timer_val = 0; // internal timer that decrements at a 1 us rate
uint8_t setup_reg;
uint8_t mode_reg;
uint8_t error;
@@ -124,20 +112,14 @@ private:
uint8_t step_count;
uint8_t cur_track;
uint8_t cur_sector;
uint8_t target_sect;
uint8_t format; // format byte from the last GCR/MFM address field
uint8_t first_sec;
uint8_t xfer_cnt;
uint8_t gap_size;
uint8_t rd_line;
int cur_state;
int one_us_timer_id = 0;
int step_timer_id = 0;
int access_timer_id = 0;
uint64_t one_us_timer_start = 0;
// Interrupt related stuff
InterruptCtrl* int_ctrl = nullptr;
uint32_t irq_id = 0;
+7 -87
View File
@@ -53,8 +53,6 @@ AMIC::AMIC() : MMIODevice()
// connect internal SCSI controller
this->scsi = dynamic_cast<Sc53C94*>(gMachineObj->get_comp_by_name("Sc53C94"));
this->scsi_dma = std::unique_ptr<AmicScsiDma> (new AmicScsiDma());
this->scsi->set_dma_channel(this->scsi_dma.get());
// connect serial HW
this->escc = dynamic_cast<EsccController*>(gMachineObj->get_comp_by_name("Escc"));
@@ -117,11 +115,7 @@ uint32_t AMIC::read(uint32_t rgn_start, uint32_t offset, int size)
case 0xA: // MACE registers
return this->mace->read((offset >> 4) & 0x1F);
case 0x10: // SCSI registers
if (offset & 0x100) {
return this->scsi->pseudo_dma_read();
} else {
return this->scsi->read((offset >> 4) & 0xF);
}
return this->scsi->read((offset >> 4) & 0xF);
case 0x14: // Sound registers
switch (offset) {
case AMICReg::Snd_Stat_0:
@@ -172,7 +166,7 @@ uint32_t AMIC::read(uint32_t rgn_start, uint32_t offset, int size)
case AMICReg::DMA_Base_Addr_3:
return (this->dma_base >> (3 - (offset & 3)) * 8) & 0xFF;
case AMICReg::SCSI_DMA_Ctrl:
return this->scsi_dma->read_stat();
return this->scsi_dma_cs;
case AMICReg::Floppy_Addr_Ptr_0:
case AMICReg::Floppy_Addr_Ptr_1:
case AMICReg::Floppy_Addr_Ptr_2:
@@ -235,7 +229,7 @@ void AMIC::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size)
this->snd_buf_size);
this->snd_out_dma->enable();
this->awacs->set_sample_rate((this->snd_out_ctrl >> 1) & 3);
this->awacs->dma_out_start();
this->awacs->start_output_dma();
} else {
LOG_F(9, "AMIC Sound Out DMA disabled!");
this->snd_out_dma->disable();
@@ -257,12 +251,6 @@ void AMIC::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size)
}
switch(offset) {
case AMICReg::VIA2_IFR:
// for each "1" in value clear the corresponding IRQ bit
// TODO: is bit 7 read only?
// TODO: update interrupts?
this->via2_ifr &= ~(value & 0x7F);
break;
case AMICReg::VIA2_Slot_IER:
LOG_F(INFO, "AMIC VIA2 Slot Interrupt Enable Register updated, val=%x", value);
break;
@@ -326,24 +314,9 @@ void AMIC::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size)
case AMICReg::Enet_DMA_Xmt_Ctrl:
LOG_F(INFO, "AMIC Ethernet Transmit DMA Ctrl updated, val=%x", value);
break;
case AMICReg::SCSI_DMA_Base_0:
case AMICReg::SCSI_DMA_Base_1:
case AMICReg::SCSI_DMA_Base_2:
case AMICReg::SCSI_DMA_Base_3:
SET_ADDR_BYTE(this->scsi_dma_base, offset, value);
this->scsi_dma_base &= 0xFFFFFFF8UL;
LOG_F(9, "AMIC: SCSI DMA base address set to 0x%X", this->scsi_dma_base);
break;
case AMICReg::SCSI_DMA_Ctrl:
if (value & 1) { // RST bit set?
this->scsi_addr_ptr = this->scsi_dma_base;
this->scsi_dma->reset(this->scsi_addr_ptr);
}
if (value & 2) { // RUN bit set?
this->scsi_dma->reinit(this->scsi_dma_base);
this->scsi->real_dma_xfer((value >> 6) & 1);
}
this->scsi_dma->write_ctrl(value);
LOG_F(INFO, "AMIC SCSI DMA Ctrl updated, val=%x", value);
this->scsi_dma_cs = value;
break;
case AMICReg::Enet_DMA_Rcv_Ctrl:
LOG_F(INFO, "AMIC Ethernet Receive DMA Ctrl updated, val=%x", value);
@@ -518,7 +491,7 @@ DmaPullResult AmicSndOutDma::pull_data(uint32_t req_len, uint32_t *avail_len,
*p_data = mmu_get_dma_mem(
(this->snd_buf_num ? this->out_buf1 : this->out_buf0) + this->cur_buf_pos,
len, nullptr);
len);
this->cur_buf_pos += len;
*avail_len = len;
return DmaPullResult::MoreData;
@@ -551,14 +524,9 @@ void AmicFloppyDma::write_ctrl(uint8_t value)
int AmicFloppyDma::push_data(const char* src_ptr, int len)
{
bool is_writable;
len = std::min((int)this->byte_count, len);
uint8_t *p_data = mmu_get_dma_mem(this->addr_ptr, len, &is_writable);
if (!is_writable) {
ABORT_F("AMIC: attempting DMA write to read-only memory");
}
uint8_t *p_data = mmu_get_dma_mem(this->addr_ptr, len);
std::memcpy(p_data, src_ptr, len);
this->addr_ptr += len;
@@ -576,54 +544,6 @@ DmaPullResult AmicFloppyDma::pull_data(uint32_t req_len, uint32_t *avail_len,
return DmaPullResult::NoMoreData;
}
// ============================ SCSI DMA stuff ================================
void AmicScsiDma::reset(const uint32_t addr_ptr)
{
this->stat &= 0x48; // clear interrupt flag, RUN and RST bits
this->addr_ptr = addr_ptr;
this->byte_count = 0;
}
void AmicScsiDma::reinit(const uint32_t addr_ptr)
{
this->addr_ptr = addr_ptr;
this->byte_count = 0;
}
void AmicScsiDma::write_ctrl(uint8_t value)
{
// copy over DIR, IE and RUN bits
this->stat = (this->stat & 0x81) | (value & 0x4A);
// clear interrupt flag if requested
if (value & 0x80) {
this->stat &= 0x7F;
}
}
int AmicScsiDma::push_data(const char* src_ptr, int len)
{
bool is_writable;
uint8_t *p_data = mmu_get_dma_mem(this->addr_ptr, len, &is_writable);
std::memcpy(p_data, src_ptr, len);
this->addr_ptr += len;
return 0;
}
DmaPullResult AmicScsiDma::pull_data(uint32_t req_len, uint32_t *avail_len,
uint8_t **p_data)
{
bool is_writable;
*p_data = mmu_get_dma_mem(this->addr_ptr, req_len, &is_writable);
this->addr_ptr += req_len;
*avail_len = req_len;
return DmaPullResult::MoreData;
}
static vector<string> Amic_Subdevices = {
"Sc53C94", "Escc", "Mace", "ViaCuda", "Swim3"
};
+5 -41
View File
@@ -102,27 +102,6 @@ private:
uint8_t stat;
};
/** AMIC-specific SCSI DMA implementation. */
class AmicScsiDma : public DmaBidirChannel {
public:
AmicScsiDma() = default;
~AmicScsiDma() = default;
void reinit(const uint32_t addr_ptr);
void reset(const uint32_t addr_ptr);
void write_ctrl(const uint8_t value);
uint8_t read_stat() { return this->stat; };
int push_data(const char* src_ptr, int len);
DmaPullResult pull_data(uint32_t req_len, uint32_t *avail_len,
uint8_t **p_data);
private:
uint32_t addr_ptr;
uint16_t byte_count;
uint8_t stat;
};
// macro for byte wise updating of AMIC DMA address registers
#define SET_ADDR_BYTE(reg, offset, value) \
mask = 0xFF000000UL >> (8 * ((offset) & 3)); \
@@ -171,10 +150,6 @@ enum AMICReg : uint32_t {
// Interrupt registers
Int_Ctrl = 0x2A000,
DMA_Int_0 = 0x2A008,
Bus_Err_Int_0 = 0x2A009,
DMA_Int_1 = 0x2A00A,
Bus_Err_Int_1 = 0x2A00B,
// Undocumented diagnostics register
Diag_Reg = 0x2C000,
@@ -185,14 +160,8 @@ enum AMICReg : uint32_t {
DMA_Base_Addr_2 = 0x31002,
DMA_Base_Addr_3 = 0x31003,
Enet_DMA_Xmt_Ctrl = 0x31C20,
Enet_DMA_Rcv_Ctrl = 0x32028,
// SCSI DMA registers
SCSI_DMA_Base_0 = 0x32000,
SCSI_DMA_Base_1 = 0x32001,
SCSI_DMA_Base_2 = 0x32002,
SCSI_DMA_Base_3 = 0x32003,
SCSI_DMA_Ctrl = 0x32008,
Enet_DMA_Rcv_Ctrl = 0x32028,
// Floppy (SWIM3) DMA registers
Floppy_Addr_Ptr_0 = 0x32060,
@@ -241,19 +210,15 @@ private:
uint8_t emmo_pin; // EMMO aka factory tester pin status, active low
uint32_t dma_base = 0; // DMA physical base address
uint32_t scsi_dma_base = 0; // physical base address for SCSI DMA
uint16_t snd_buf_size = 0; // sound buffer size in bytes
uint8_t snd_out_ctrl = 0;
uint32_t dma_base = 0; // DMA physical base address
uint16_t snd_buf_size = 0; // sound buffer size in bytes
uint8_t snd_out_ctrl = 0;
// floppy DMA state
uint32_t floppy_addr_ptr;
uint16_t floppy_byte_cnt;
// SCSI DMA state
uint32_t scsi_addr_ptr;
//uint8_t scsi_dma_cs = 0; // SCSI DMA control/status register value
uint8_t scsi_dma_cs = 0; // SCSI DMA control/status register value
// interrupt state
uint8_t int_ctrl = 0;
@@ -276,7 +241,6 @@ private:
std::unique_ptr<AwacDevicePdm> awacs;
std::unique_ptr<AmicSndOutDma> snd_out_dma;
std::unique_ptr<AmicFloppyDma> floppy_dma;
std::unique_ptr<AmicScsiDma> scsi_dma;
// on-board video
std::unique_ptr<DisplayID> disp_id;
+6 -14
View File
@@ -35,15 +35,14 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
GrandCentral::GrandCentral() : PCIDevice("mac-io/grandcentral"), InterruptCtrl()
{
supports_types(HWCompType::MMIO_DEV | HWCompType::PCI_DEV | HWCompType::INT_CTRL);
supports_types(HWCompType::MMIO_DEV | HWCompType::INT_CTRL);
// populate my PCI config header
this->vendor_id = PCI_VENDOR_APPLE;
this->device_id = 0x0002;
this->class_rev = 0xFF000002;
this->cache_ln_sz = 8;
this->setup_bars({{0, 0xFFFE0000UL}}); // declare 128Kb of memory-mapped I/O space
this->bars_cfg[0] = 0xFFFE0000UL; // declare 128Kb of memory-mapped I/O space
this->pci_notify_bar_change = [this](int bar_num) {
this->notify_bar_change(bar_num);
@@ -60,8 +59,8 @@ GrandCentral::GrandCentral() : PCIDevice("mac-io/grandcentral"), InterruptCtrl()
this->snd_out_dma = std::unique_ptr<DMAChannel> (new DMAChannel());
this->awacs->set_dma_out(this->snd_out_dma.get());
this->snd_out_dma->set_callbacks(
std::bind(&AwacsScreamer::dma_out_start, this->awacs.get()),
std::bind(&AwacsScreamer::dma_out_stop, this->awacs.get())
std::bind(&AwacsScreamer::dma_start, this->awacs.get()),
std::bind(&AwacsScreamer::dma_end, this->awacs.get())
);
// connect serial HW
@@ -75,8 +74,6 @@ GrandCentral::GrandCentral() : PCIDevice("mac-io/grandcentral"), InterruptCtrl()
// connect floppy disk HW
this->swim3 = dynamic_cast<Swim3::Swim3Ctrl*>(gMachineObj->get_comp_by_name("Swim3"));
this->floppy_dma = std::unique_ptr<DMAChannel> (new DMAChannel());
this->swim3->set_dma_channel(this->floppy_dma.get());
// set EMMO pin status (active low)
this->emmo_pin = GET_BIN_PROP("emmo") ^ 1;
@@ -139,11 +136,9 @@ uint32_t GrandCentral::read(uint32_t rgn_start, uint32_t offset, int size)
(this->nvram_addr_hi << 5) + ((offset >> 4) & 0x1F));
}
} else if (offset & 0x8000) { // DMA register space
unsigned subdev_num = (offset >> 8) & 0xF;
unsigned subdev_num = (offset >> 12) & 0xF;
switch (subdev_num) {
case 1:
return this->floppy_dma->reg_read(offset & 0xFF, size);
case 8:
return this->snd_out_dma->reg_read(offset & 0xFF, size);
default:
@@ -228,12 +223,9 @@ void GrandCentral::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
this->base_addr + offset);
}
} else if (offset & 0x8000) { // DMA register space
unsigned subdev_num = (offset >> 8) & 0xF;
unsigned subdev_num = (offset >> 12) & 0xF;
switch (subdev_num) {
case 1:
this->floppy_dma->reg_write(offset & 0xFF, value, size);
break;
case 8:
this->snd_out_dma->reg_write(offset & 0xFF, value, size);
break;
+38 -80
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -21,7 +21,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cpu/ppc/ppcemu.h>
#include <devices/deviceregistry.h>
#include <devices/common/ata/idechannel.h>
#include <devices/common/dbdma.h>
#include <devices/common/hwcomponent.h>
#include <devices/common/viacuda.h>
@@ -35,6 +34,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cinttypes>
#include <functional>
#include <iostream>
#include <memory>
/** Heathrow Mac I/O device emulation.
@@ -46,7 +46,7 @@ using namespace std;
HeathrowIC::HeathrowIC() : PCIDevice("mac-io/heathrow"), InterruptCtrl()
{
supports_types(HWCompType::MMIO_DEV | HWCompType::PCI_DEV | HWCompType::INT_CTRL);
supports_types(HWCompType::MMIO_DEV | HWCompType::INT_CTRL);
// populate my PCI config header
this->vendor_id = PCI_VENDOR_APPLE;
@@ -54,8 +54,7 @@ HeathrowIC::HeathrowIC() : PCIDevice("mac-io/heathrow"), InterruptCtrl()
this->class_rev = 0xFF000001;
this->cache_ln_sz = 8;
this->lat_timer = 0x40;
this->setup_bars({{0, 0xFFF80000UL}}); // declare 512Kb of memory-mapped I/O space
this->bars_cfg[0] = 0xFFF80000UL; // declare 512Kb of memory-mapped I/O space
this->pci_notify_bar_change = [this](int bar_num) {
this->notify_bar_change(bar_num);
@@ -67,31 +66,23 @@ HeathrowIC::HeathrowIC() : PCIDevice("mac-io/heathrow"), InterruptCtrl()
// connect Cuda
this->viacuda = dynamic_cast<ViaCuda*>(gMachineObj->get_comp_by_name("ViaCuda"));
// find appropriate sound chip, create a DMA output channel for sound,
// then wire everything together
this->snd_codec = dynamic_cast<MacioSndCodec*>(gMachineObj->get_comp_by_type(HWCompType::SND_CODEC));
// initialize sound chip and its DMA output channel, then wire them together
this->screamer = std::unique_ptr<AwacsScreamer> (new AwacsScreamer());
this->snd_out_dma = std::unique_ptr<DMAChannel> (new DMAChannel());
this->snd_codec->set_dma_out(this->snd_out_dma.get());
this->screamer->set_dma_out(this->snd_out_dma.get());
this->snd_out_dma->set_callbacks(
std::bind(&AwacsScreamer::dma_out_start, this->snd_codec),
std::bind(&AwacsScreamer::dma_out_stop, this->snd_codec)
std::bind(&AwacsScreamer::dma_start, this->screamer.get()),
std::bind(&AwacsScreamer::dma_end, this->screamer.get())
);
// connect SCSI HW
this->mesh = dynamic_cast<MeshController*>(gMachineObj->get_comp_by_name("Mesh"));
// connect IDE HW
this->ide_0 = dynamic_cast<IdeChannel*>(gMachineObj->get_comp_by_name("Ide0"));
this->ide_1 = dynamic_cast<IdeChannel*>(gMachineObj->get_comp_by_name("Ide1"));
this->mesh = dynamic_cast<MESHController*>(gMachineObj->get_comp_by_name("Mesh"));
// connect serial HW
this->escc = dynamic_cast<EsccController*>(gMachineObj->get_comp_by_name("Escc"));
// connect floppy disk HW and initialize its DMA channel
// connect floppy disk HW
this->swim3 = dynamic_cast<Swim3::Swim3Ctrl*>(gMachineObj->get_comp_by_name("Swim3"));
this->floppy_dma = std::unique_ptr<DMAChannel> (new DMAChannel());
this->swim3->set_dma_channel(this->floppy_dma.get());
this->floppy_dma->register_dma_int(this, 2);
// set EMMO pin status (active low)
this->emmo_pin = GET_BIN_PROP("emmo") ^ 1;
@@ -104,7 +95,7 @@ void HeathrowIC::notify_bar_change(int bar_num)
if (this->base_addr != (this->bars[bar_num] & 0xFFFFFFF0UL)) {
if (this->base_addr) {
this->host_instance->pci_unregister_mmio_region(this->base_addr, 0x80000, this);
LOG_F(WARNING, "Heathrow: deallocating I/O memory not implemented");
}
this->base_addr = this->bars[0] & 0xFFFFFFF0UL;
this->host_instance->pci_register_mmio_region(this->base_addr, 0x80000, this);
@@ -113,23 +104,21 @@ void HeathrowIC::notify_bar_change(int bar_num)
}
uint32_t HeathrowIC::dma_read(uint32_t offset, int size) {
uint32_t res = 0;
switch (offset >> 8) {
case 1:
return this->floppy_dma->reg_read(offset & 0xFF, size);
case 8:
return this->snd_out_dma->reg_read(offset & 0xFF, size);
res = this->snd_out_dma->reg_read(offset & 0xFF, size);
break;
default:
LOG_F(WARNING, "Unsupported DMA channel read, offset=0x%X", offset);
}
return 0;
return res;
}
void HeathrowIC::dma_write(uint32_t offset, uint32_t value, int size) {
switch (offset >> 8) {
case 1:
this->floppy_dma->reg_write(offset & 0xFF, value, size);
break;
case 8:
this->snd_out_dma->reg_write(offset & 0xFF, value, size);
break;
@@ -164,20 +153,14 @@ uint32_t HeathrowIC::read(uint32_t rgn_start, uint32_t offset, int size) {
case 0x13: // ESCC MacRISC addressing
return this->escc->read((offset >> 4) & 0xF);
case 0x14:
res = this->snd_codec->snd_ctrl_read(offset - 0x14000, size);
res = this->screamer->snd_ctrl_read(offset - 0x14000, size);
break;
case 0x15: // SWIM3
return this->swim3->read((offset >> 4 )& 0xF);
case 0x16: // VIA-CUDA
case 0x16:
case 0x17:
res = this->viacuda->read((offset - 0x16000) >> 9);
break;
case 0x20: // IDE 0
res = this->ide_0->read((offset >> 4) & 0x1F, size);
break;
case 0x21: // IDE 1
res = this->ide_1->read((offset >> 4) & 0x1F, size);
break;
default:
if (sub_addr >= 0x60) {
res = this->nvram->read_byte((offset - 0x60000) >> 4);
@@ -214,21 +197,15 @@ void HeathrowIC::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int
this->escc->write((offset >> 4) & 0xF, value);
break;
case 0x14:
this->snd_codec->snd_ctrl_write(offset - 0x14000, value, size);
this->screamer->snd_ctrl_write(offset - 0x14000, value, size);
break;
case 0x15: // SWIM3
this->swim3->write((offset >> 4) & 0xF, value);
break;
case 0x16: // VIA-CUDA
case 0x16:
case 0x17:
this->viacuda->write((offset - 0x16000) >> 9, value);
break;
case 0x20: // IDE O
this->ide_0->write((offset >> 4) & 0x1F, value, size);
break;
case 0x21: // IDE 1
this->ide_1->write((offset >> 4) & 0x1F, value, size);
break;
default:
if (sub_addr >= 0x60) {
this->nvram->write_byte((offset - 0x60000) >> 4, value);
@@ -260,17 +237,12 @@ uint32_t HeathrowIC::mio_ctrl_read(uint32_t offset, int size) {
case MIO_INT_LEVELS1:
res = this->int_levels1;
break;
case MIO_INT_CLEAR1:
case MIO_INT_CLEAR2:
// some Mac OS drivers reads from those write-only registers
// so we return zero here as real HW does
break;
case MIO_OHARE_ID:
case MIO_HEAT_ID:
LOG_F(9, "read from MIO:ID register at Address %x", ppc_state.pc);
res = (this->fp_id << 24) | (this->mon_id << 16) | (this->mb_id << 8) |
(this->cpu_id | (this->emmo_pin << 4));
break;
case MIO_OHARE_FEAT_CTRL:
case MIO_HEAT_FEAT_CTRL:
LOG_F(9, "read from MIO:Feat_Ctrl register");
res = this->feat_ctrl;
break;
@@ -308,10 +280,10 @@ void HeathrowIC::mio_ctrl_write(uint32_t offset, uint32_t value, int size) {
this->int_events1 &= BYTESWAP_32(value);
}
break;
case MIO_OHARE_ID:
case MIO_HEAT_ID:
LOG_F(WARNING, "Attempted to write %x to MIO:ID at %x; Address : %x", value, offset, ppc_state.pc);
break;
case MIO_OHARE_FEAT_CTRL:
case MIO_HEAT_FEAT_CTRL:
this->feature_control(BYTESWAP_32(value));
break;
case 0x3C:
@@ -381,38 +353,23 @@ void HeathrowIC::ack_int(uint32_t irq_id, uint8_t irq_line_state)
this->int_levels1 &= ~irq_id;
}
}
this->signal_cpu_int();
// signal CPU interrupt
if (this->int_events1 || this->int_events2) {
if (!this->cpu_int_latch) {
this->cpu_int_latch = true;
ppc_assert_int();
LOG_F(5, "Heathrow: CPU INT asserted, source: %d", irq_id);
} else {
LOG_F(5, "Heathrow: CPU INT already latched");
}
}
} else {
ABORT_F("%s: native interrupt mode not implemented", this->name.c_str());
ABORT_F("Heathrow: native interrupt mode not implemented");
}
}
void HeathrowIC::ack_dma_int(uint32_t irq_id, uint8_t irq_line_state)
{
if (this->int_mask1 & MACIO_INT_MODE) { // 68k interrupt emulation mode?
this->int_events1 |= irq_id; // signal IRQ line change
this->int_events1 &= this->int_mask1;
// update IRQ line state
if (irq_line_state) {
this->int_levels1 |= irq_id;
} else {
this->int_levels1 &= ~irq_id;
}
this->signal_cpu_int();
} else {
ABORT_F("%s: native interrupt mode not implemented", this->name.c_str());
}
}
void HeathrowIC::signal_cpu_int() {
if (this->int_events1 || this->int_events2) {
if (!this->cpu_int_latch) {
this->cpu_int_latch = true;
ppc_assert_int();
} else {
LOG_F(5, "%s: CPU INT already latched", this->name.c_str());
}
}
}
void HeathrowIC::clear_cpu_int()
@@ -425,7 +382,8 @@ void HeathrowIC::clear_cpu_int()
}
static const vector<string> Heathrow_Subdevices = {
"NVRAM", "ViaCuda", "Mesh", "Escc", "Swim3", "Ide0", "Ide1"};
"NVRAM", "ViaCuda", "Mesh", "Escc", "Swim3"
};
static const DeviceDescription Heathrow_Descriptor = {
HeathrowIC::create, Heathrow_Subdevices, {}
+5 -55
View File
@@ -51,7 +51,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef MACIO_H
#define MACIO_H
#include <devices/common/ata/idechannel.h>
#include <devices/common/dbdma.h>
#include <devices/common/mmiodevice.h>
#include <devices/common/nvram.h>
@@ -142,50 +141,6 @@ private:
Swim3::Swim3Ctrl* swim3; // floppy disk controller
std::unique_ptr<DMAChannel> snd_out_dma;
std::unique_ptr<DMAChannel> floppy_dma;
};
class OHare : public PCIDevice, public InterruptCtrl {
public:
OHare();
~OHare() = default;
static std::unique_ptr<HWComponent> create() {
return std::unique_ptr<OHare>(new OHare());
}
// MMIO device methods
uint32_t read(uint32_t rgn_start, uint32_t offset, int size);
void write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size);
// InterruptCtrl methods
uint32_t register_dev_int(IntSrc src_id);
uint32_t register_dma_int(IntSrc src_id);
void ack_int(uint32_t irq_id, uint8_t irq_line_state);
void ack_dma_int(uint32_t irq_id, uint8_t irq_line_state);
protected:
void notify_bar_change(int bar_num);
uint32_t read_ctrl(uint32_t offset, int size);
void write_ctrl(uint32_t offset, uint32_t value, int size);
uint32_t dma_read(uint32_t offset, int size);
void dma_write(uint32_t offset, uint32_t value, int size);
private:
uint32_t base_addr = 0;
// interrupt state
uint32_t int_mask = 0;
uint32_t int_levels = 0;
uint32_t int_events = 0;
bool cpu_int_latch = false;
std::unique_ptr<AwacsScreamer> awacs; // AWACS audio codec instance
std::unique_ptr<DMAChannel> snd_out_dma;
NVram* nvram; // NVRAM module
ViaCuda* viacuda; // VIA cell with Cuda MCU attached to it
EsccController* escc; // ESCC serial controller
};
/**
@@ -212,10 +167,10 @@ private:
VIA-CUDA register space: 0x00016000, size: 0x00002000
*/
/** O'Hare/Heathrow specific registers. */
/** Heathrow specific registers. */
enum {
MIO_OHARE_ID = 0x34, // IDs register
MIO_OHARE_FEAT_CTRL = 0x38, // feature control register
MIO_HEAT_ID = 0x34, // IDs register
MIO_HEAT_FEAT_CTRL = 0x38, // feature control register
};
class HeathrowIC : public PCIDevice, public InterruptCtrl {
@@ -247,7 +202,6 @@ protected:
void notify_bar_change(int bar_num);
void feature_control(const uint32_t value);
void signal_cpu_int();
void clear_cpu_int();
private:
@@ -269,19 +223,15 @@ private:
uint8_t emmo_pin; // factory tester status, active low
// subdevice objects
MacioSndCodec* snd_codec; // audio codec instance
std::unique_ptr<AwacsScreamer> screamer; // Screamer audio codec instance
NVram* nvram; // NVRAM
ViaCuda* viacuda; // VIA cell with Cuda MCU attached to it
MeshController* mesh; // MESH SCSI cell instance
MESHController* mesh; // MESH SCSI cell instance
EsccController* escc; // ESCC serial controller
IdeChannel* ide_0; // Internal ATA
IdeChannel* ide_1; // Media Bay ATA
Swim3::Swim3Ctrl* swim3; // floppy disk controller
// DMA channels
std::unique_ptr<DMAChannel> snd_out_dma;
std::unique_ptr<DMAChannel> floppy_dma;
};
#endif /* MACIO_H */
-236
View File
@@ -1,236 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <cpu/ppc/ppcemu.h>
#include <devices/ioctrl/macio.h>
#include <endianswap.h>
#include <loguru.hpp>
#include <machines/machinebase.h>
#include <cinttypes>
OHare::OHare() : PCIDevice("mac-io/ohare"), InterruptCtrl()
{
supports_types(HWCompType::MMIO_DEV | HWCompType::PCI_DEV | HWCompType::INT_CTRL);
// populate my PCI config header
this->vendor_id = PCI_VENDOR_APPLE;
this->device_id = 0x0007;
this->class_rev = 0xFF000001;
this->cache_ln_sz = 8;
this->setup_bars({{0, 0xFFF80000UL}}); // declare 512Kb of memory-mapped I/O space
this->pci_notify_bar_change = [this](int bar_num) {
this->notify_bar_change(bar_num);
};
// NVRAM connection
this->nvram = dynamic_cast<NVram*>(gMachineObj->get_comp_by_name("NVRAM"));
// connect Cuda
this->viacuda = dynamic_cast<ViaCuda*>(gMachineObj->get_comp_by_name("ViaCuda"));
// initialize sound chip and its DMA output channel, then wire them together
this->awacs = std::unique_ptr<AwacsScreamer> (new AwacsScreamer());
this->snd_out_dma = std::unique_ptr<DMAChannel> (new DMAChannel());
this->awacs->set_dma_out(this->snd_out_dma.get());
this->snd_out_dma->set_callbacks(
std::bind(&AwacsScreamer::dma_out_start, this->awacs.get()),
std::bind(&AwacsScreamer::dma_out_stop, this->awacs.get())
);
// connect serial HW
this->escc = dynamic_cast<EsccController*>(gMachineObj->get_comp_by_name("Escc"));
}
void OHare::notify_bar_change(int bar_num)
{
if (bar_num) // only BAR0 is supported
return;
if (this->base_addr != (this->bars[bar_num] & 0xFFFFFFF0UL)) {
if (this->base_addr) {
LOG_F(WARNING, "%s: deallocating I/O memory not implemented",
this->pci_name.c_str());
}
this->base_addr = this->bars[0] & 0xFFFFFFF0UL;
this->host_instance->pci_register_mmio_region(this->base_addr, 0x80000, this);
LOG_F(INFO, "%s: base address set to 0x%X", this->pci_name.c_str(), this->base_addr);
}
}
uint32_t OHare::read(uint32_t rgn_start, uint32_t offset, int size)
{
unsigned sub_addr = (offset >> 12) & 0x7F;
switch (sub_addr) {
case 0:
return read_ctrl(offset, size);
case 8:
return dma_read(offset & 0x7FFF, size);
case 0x13: // ESCC MacRISC addressing
return this->escc->read((offset >> 4) & 0xF);
case 0x14: // AWACS
return this->awacs->snd_ctrl_read(offset & 0xFF, size);
case 0x16:
case 0x17:
return this->viacuda->read((offset >> 9) & 0xF);
case 0x20:
return 0xFF7FU;
default:
if (sub_addr >= 0x60) {
return this->nvram->read_byte((offset - 0x60000) >> 4);
} else {
LOG_F(WARNING, "OHare: read from unimplemented register 0x%X",
this->base_addr + offset);
}
}
return 0xFFFFFFFFUL;
}
void OHare::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size)
{
unsigned sub_addr = (offset >> 12) & 0x7F;
switch (sub_addr) {
case 0:
this->write_ctrl(offset, value, size);
break;
case 8:
this->dma_write(offset & 0x7FFF, value, size);
break;
case 0x13: // ESCC MacRISC addressing
this->escc->write((offset >> 4) & 0xF, value);
break;
case 0x14: // AWACS
this->awacs->snd_ctrl_write(offset & 0xFF, value, size);
break;
case 0x16:
case 0x17: // VIA-CUDA
this->viacuda->write((offset >> 9) & 0xF, value);
break;
case 0x20:
LOG_F(INFO, "OHare: write to IDE0 register at 0x%X", offset);
break;
default:
if (sub_addr >= 0x60) {
this->nvram->write_byte((offset - 0x60000) >> 4, value);
} else {
LOG_F(WARNING, "OHare: writing to unimplemented device register 0x%X",
this->base_addr + offset);
}
}
}
uint32_t OHare::read_ctrl(uint32_t offset, int size)
{
uint32_t res = 0;
switch (offset & 0xFC) {
case MIO_INT_EVENTS1:
res = this->int_events;
break;
case MIO_OHARE_ID: // HACK: no clue what this register is supposed to contain
res = 0xFFFFBFFFUL;
default:
LOG_F(WARNING, "OHare: read from unknown control register at %x", offset);
break;
}
return BYTESWAP_32(res);
}
void OHare::write_ctrl(uint32_t offset, uint32_t value, int size)
{
switch (offset) {
case MIO_INT_MASK1:
this->int_mask = BYTESWAP_32(value);
break;
case MIO_INT_CLEAR1:
if (value & MACIO_INT_CLR) {
this->int_events = 0;
this->cpu_int_latch = false;
ppc_release_int();
LOG_F(5, "OHare: CPU INT latch cleared");
} else {
this->int_events &= BYTESWAP_32(value);
}
break;
default:
LOG_F(WARNING, "OHare: writing to unimplemented control register 0x%X",
this->base_addr + offset);
}
}
uint32_t OHare::dma_read(uint32_t offset, int size)
{
switch (offset >> 8) {
case 8:
return this->snd_out_dma->reg_read(offset & 0xFF, size);
default:
LOG_F(WARNING, "OHare: unsupported DMA channel read, offset=0x%X", offset);
}
return 0xFFFFFFUL;
}
void OHare::dma_write(uint32_t offset, uint32_t value, int size)
{
switch (offset >> 8) {
case 8:
this->snd_out_dma->reg_write(offset & 0xFF, value, size);
break;
default:
LOG_F(WARNING, "OHare: unsupported DMA channel write, offset=0x%X, val=0x%X", offset, value);
}
}
uint32_t OHare::register_dev_int(IntSrc src_id)
{
return 0;
}
uint32_t OHare::register_dma_int(IntSrc src_id)
{
return 0;
}
void OHare::ack_int(uint32_t irq_id, uint8_t irq_line_state)
{
}
void OHare::ack_dma_int(uint32_t irq_id, uint8_t irq_line_state)
{
}
static const vector<string> OHare_Subdevices = {
"NVRAM", "ViaCuda", "Mesh", "Escc", "Swim3"
};
static const DeviceDescription OHare_Descriptor = {
OHare::create, OHare_Subdevices, {}
};
REGISTER_DEVICE(OHare, OHare_Descriptor);
+12 -181
View File
@@ -25,15 +25,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cstring>
#include <string>
#include <vector>
#include <loguru.hpp>
static inline bool match_mem_entry(const AddressMapEntry* entry,
const uint32_t start, const uint32_t end,
MMIODevice* dev_instance)
{
return start == entry->start && end == entry->end &&
(!dev_instance || dev_instance == entry->devobj);
}
MemCtrlBase::~MemCtrlBase() {
for (auto& entry : address_map) {
@@ -60,96 +52,12 @@ AddressMapEntry* MemCtrlBase::find_range(uint32_t addr) {
}
AddressMapEntry* MemCtrlBase::find_range_exact(uint32_t addr, uint32_t size,
MMIODevice* dev_instance)
{
if (size) {
const uint32_t end = addr + size - 1;
for (auto& entry : address_map) {
if (match_mem_entry(entry, addr, end, dev_instance))
return entry;
}
}
return nullptr;
}
AddressMapEntry* MemCtrlBase::find_range_contains(uint32_t addr, uint32_t size) {
if (size) {
uint32_t end = addr + size - 1;
for (auto& entry : address_map) {
if (addr >= entry->start && end <= entry->end)
return entry;
}
}
return nullptr;
}
AddressMapEntry* MemCtrlBase::find_range_overlaps(uint32_t addr, uint32_t size) {
if (size) {
uint32_t end = addr + size - 1;
for (auto& entry : address_map) {
if (end >= entry->start && addr <= entry->end)
return entry;
}
}
return nullptr;
}
bool MemCtrlBase::is_range_free(uint32_t addr, uint32_t size) {
bool result = true;
if (size) {
uint32_t end = addr + size - 1;
for (auto& entry : address_map) {
if (addr == entry->start && end == entry->end) {
LOG_F(WARNING, "memory region 0x%X..0x%X%s%s%s already exists",
addr, end,
entry->devobj ? " (" : "",
entry->devobj ? entry->devobj->get_name().c_str() : "",
entry->devobj ? ")"
: ""
);
result = false;
}
else if (addr >= entry->start && end <= entry->end) {
LOG_F(WARNING, "0x%X..0x%X already exists in memory region 0x%X..0x%X%s%s%s",
addr, end, entry->start, entry->end,
entry->devobj ? " (" : "",
entry->devobj ? entry->devobj->get_name().c_str() : "",
entry->devobj ? ")"
: ""
);
result = false;
}
else if (end >= entry->start && addr <= entry->end) {
LOG_F(ERROR, "0x%X..0x%X overlaps existing memory region 0x%X..0x%X%s%s%s",
addr, end, entry->start, entry->end,
entry->devobj ? " (" : "",
entry->devobj ? entry->devobj->get_name().c_str() : "",
entry->devobj ? ")"
: ""
);
result = false;
}
}
}
return result;
}
bool MemCtrlBase::add_mem_region(uint32_t start_addr, uint32_t size,
uint32_t dest_addr, uint32_t type,
uint8_t init_val = 0)
{
bool MemCtrlBase::add_mem_region(
uint32_t start_addr, uint32_t size, uint32_t dest_addr, uint32_t type, uint8_t init_val = 0) {
AddressMapEntry *entry;
/* error if a memory region for the given range already exists */
if (!is_range_free(start_addr, size))
if (find_range(start_addr) || find_range(start_addr + size))
return false;
uint8_t* reg_content = new uint8_t[size];
@@ -158,9 +66,8 @@ bool MemCtrlBase::add_mem_region(uint32_t start_addr, uint32_t size,
entry = new AddressMapEntry;
uint32_t end = start_addr + size - 1;
entry->start = start_addr;
entry->end = end;
entry->end = start_addr + size - 1;
entry->mirror = dest_addr;
entry->type = type;
entry->devobj = 0;
@@ -168,14 +75,6 @@ bool MemCtrlBase::add_mem_region(uint32_t start_addr, uint32_t size,
this->address_map.push_back(entry);
LOG_F(INFO, "Added mem region 0x%X..0x%X (%s%s%s%s) -> 0x%X", start_addr, end,
entry->type & RT_ROM ? "ROM," : "",
entry->type & RT_RAM ? "RAM," : "",
entry->type & RT_MMIO ? "MMIO," : "",
entry->type & RT_MIRROR ? "MIRROR," : "",
dest_addr
);
return true;
}
@@ -199,9 +98,8 @@ bool MemCtrlBase::add_mem_mirror(uint32_t start_addr, uint32_t dest_addr) {
entry = new AddressMapEntry;
uint32_t end = start_addr + (ref_entry->end - ref_entry->start);
entry->start = start_addr;
entry->end = end;
entry->end = start_addr + (ref_entry->end - ref_entry->start);
entry->mirror = dest_addr;
entry->type = ref_entry->type | RT_MIRROR;
entry->devobj = 0;
@@ -209,54 +107,36 @@ bool MemCtrlBase::add_mem_mirror(uint32_t start_addr, uint32_t dest_addr) {
this->address_map.push_back(entry);
LOG_F(INFO, "Added mem region mirror 0x%X..0x%X (%s%s%s%s) -> 0x%X : 0x%X..0x%X%s%s%s",
start_addr, end,
entry->type & RT_ROM ? "ROM," : "",
entry->type & RT_RAM ? "RAM," : "",
entry->type & RT_MMIO ? "MMIO," : "",
entry->type & RT_MIRROR ? "MIRROR," : "",
dest_addr,
ref_entry->start, ref_entry->end,
ref_entry->devobj ? " (" : "",
ref_entry->devobj ? ref_entry->devobj->get_name().c_str() : "",
ref_entry->devobj ? ")"
: ""
);
return true;
}
bool MemCtrlBase::set_data(uint32_t load_addr, const uint8_t* data, uint32_t size) {
bool MemCtrlBase::set_data(uint32_t reg_addr, const uint8_t* data, uint32_t size) {
AddressMapEntry* ref_entry;
uint32_t cpy_size;
ref_entry = find_range(load_addr);
ref_entry = find_range(reg_addr);
if (!ref_entry)
return false;
uint32_t load_offset = load_addr - ref_entry->start;
cpy_size = std::min(ref_entry->end - ref_entry->start + 1, size);
memcpy(ref_entry->mem_ptr + load_offset, data, cpy_size);
memcpy(ref_entry->mem_ptr, data, cpy_size);
return true;
}
bool MemCtrlBase::add_mmio_region(uint32_t start_addr, uint32_t size, MMIODevice* dev_instance)
{
bool MemCtrlBase::add_mmio_region(uint32_t start_addr, uint32_t size, MMIODevice* dev_instance) {
AddressMapEntry *entry;
/* error if a memory region for the given range already exists */
if (!is_range_free(start_addr, size))
/* error if another region for the given range already exists */
if (find_range(start_addr) || find_range(start_addr + size - 1))
return false;
entry = new AddressMapEntry;
uint32_t end = start_addr + size - 1;
entry->start = start_addr;
entry->end = end;
entry->end = start_addr + size - 1;
entry->mirror = 0;
entry->type = RT_MMIO;
entry->devobj = dev_instance;
@@ -264,58 +144,9 @@ bool MemCtrlBase::add_mmio_region(uint32_t start_addr, uint32_t size, MMIODevice
this->address_map.push_back(entry);
LOG_F(INFO, "Added mmio region 0x%X..0x%X%s%s%s",
start_addr, end,
dev_instance ? " (" : "",
dev_instance ? dev_instance->get_name().c_str() : "",
dev_instance ? ")"
: ""
);
return true;
}
bool MemCtrlBase::remove_mmio_region(uint32_t start_addr, uint32_t size, MMIODevice* dev_instance)
{
int found = 0;
uint32_t end = start_addr + size - 1;
address_map.erase(std::remove_if(address_map.begin(), address_map.end(),
[start_addr, end, dev_instance, &found](const AddressMapEntry *entry) {
bool result = match_mem_entry(entry, start_addr, end, dev_instance);
found += result;
return result;
}
), address_map.end());
if (found == 0)
LOG_F(ERROR, "Cannot find mmio region 0x%X..0x%X%s%s%s to remove",
start_addr, end,
dev_instance ? " (" : "",
dev_instance ? dev_instance->get_name().c_str() : "",
dev_instance ? ")"
: ""
);
else if (found > 1)
LOG_F(ERROR, "Removed %d occurrences of mmio region 0x%X..0x%X%s%s%s",
found, start_addr, end,
dev_instance ? " (" : "",
dev_instance ? dev_instance->get_name().c_str() : "",
dev_instance ? ")"
: ""
);
else
LOG_F(INFO, "Removed mmio region 0x%X..0x%X%s%s%s",
start_addr, end,
dev_instance ? " (" : "",
dev_instance ? dev_instance->get_name().c_str() : "",
dev_instance ? ")"
: ""
);
return (found > 0);
}
AddressMapEntry* MemCtrlBase::find_rom_region()
{
for (auto& entry : address_map) {
-6
View File
@@ -68,16 +68,10 @@ public:
virtual bool add_mem_mirror(uint32_t start_addr, uint32_t dest_addr);
virtual bool add_mmio_region(uint32_t start_addr, uint32_t size, MMIODevice* dev_instance);
virtual bool remove_mmio_region(uint32_t start_addr, uint32_t size, MMIODevice* dev_instance);
virtual bool set_data(uint32_t reg_addr, const uint8_t* data, uint32_t size);
AddressMapEntry* find_range(uint32_t addr);
AddressMapEntry* find_range_exact(uint32_t addr, uint32_t size, MMIODevice* dev_instance);
AddressMapEntry* find_range_contains(uint32_t addr, uint32_t size);
AddressMapEntry* find_range_overlaps(uint32_t addr, uint32_t size);
bool is_range_free(uint32_t addr, uint32_t size);
AddressMapEntry* find_rom_region();
protected:
+133 -172
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -26,16 +26,19 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <devices/deviceregistry.h>
#include <devices/memctrl/memctrlbase.h>
#include <devices/memctrl/mpc106.h>
#include <loguru.hpp>
#include <memaccess.h>
#include <cinttypes>
#include <cstring>
#include <iostream>
#include <loguru.hpp>
#include <string>
#include <vector>
MPC106::MPC106() : MemCtrlBase(), PCIDevice("Grackle"), PCIHost()
{
this->name = "Grackle";
supports_types(HWCompType::MEM_CTRL | HWCompType::MMIO_DEV |
HWCompType::PCI_HOST | HWCompType::PCI_DEV);
@@ -47,9 +50,6 @@ MPC106::MPC106() : MemCtrlBase(), PCIDevice("Grackle"), PCIHost()
this->command = 6;
this->status = 0x80;
// assign PCI device number zero to myself
this->pci_register_device(DEV_FUN(0,0), this);
// add PCI/ISA I/O space, 64K for now
add_mmio_region(0xFE000000, 0x10000, this);
@@ -62,7 +62,7 @@ int MPC106::device_postinit()
std::string pci_dev_name;
static const std::map<std::string, int> pci_slots = {
{"pci_A1", DEV_FUN(0xD,0)}, {"pci_B1", DEV_FUN(0xE,0)}, {"pci_C1", DEV_FUN(0xF,0)}
{"pci_A1", 0xD}, {"pci_B1", 0xE}, {"pci_C1", 0xF}
};
for (auto& slot : pci_slots) {
@@ -75,193 +75,153 @@ int MPC106::device_postinit()
}
uint32_t MPC106::read(uint32_t rgn_start, uint32_t offset, int size) {
uint32_t result;
if (rgn_start == 0xFE000000) {
return pci_io_read_broadcast(offset, size);
}
if (offset < 0x200000) {
return this->config_addr;
// broadcast I/O request to devices that support I/O space
// until a device returns true that means "request accepted"
for (auto& dev : this->io_space_devs) {
if (dev->pci_io_read(offset, size, &result)) {
return result;
}
}
LOG_F(ERROR, "Attempt to read from unmapped PCI I/O space, offset=0x%X", offset);
} else {
if (offset >= 0x200000) {
if (this->config_addr & 0x80) // process only if bit E (enable) is set
return pci_read(size);
}
if (this->config_addr & 0x80) { // process only if bit E (enable) is set
return pci_read(offset, size);
}
// FIXME: reading from CONFIG_ADDR is ignored for now
return 0;
}
void MPC106::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size) {
if (rgn_start == 0xFE000000) {
pci_io_write_broadcast(offset, size, value);
// broadcast I/O request to devices that support I/O space
// until a device returns true that means "request accepted"
for (auto& dev : this->io_space_devs) {
if (dev->pci_io_write(offset, value, size)) {
return;
}
}
LOG_F(ERROR, "Attempt to write to unmapped PCI I/O space, offset=0x%X", offset);
} else {
if (offset < 0x200000) {
this->config_addr = value;
return;
}
if (this->config_addr & 0x80) { // process only if bit E (enable) is set
return pci_write(offset, value, size);
} else {
if (this->config_addr & 0x80) // process only if bit E (enable) is set
return pci_write(value, size);
}
}
uint32_t MPC106::pci_read(uint32_t offset, uint32_t size) {
int bus_num, dev_num, fun_num;
uint8_t reg_offs;
AccessDetails details;
PCIDevice *device;
cfg_setup(offset, size, bus_num, dev_num, fun_num, reg_offs, details, device);
details.flags |= PCI_CONFIG_READ;
if (device) {
return pci_conv_rd_data(device->pci_cfg_read(reg_offs, details), details);
}
LOG_READ_NON_EXISTENT_PCI_DEVICE();
return 0xFFFFFFFFUL; // PCI spec §6.1
}
void MPC106::pci_write(uint32_t offset, uint32_t value, uint32_t size) {
int bus_num, dev_num, fun_num;
uint8_t reg_offs;
AccessDetails details;
PCIDevice *device;
cfg_setup(offset, size, bus_num, dev_num, fun_num, reg_offs, details, device);
details.flags |= PCI_CONFIG_WRITE;
if (device) {
if (size == 4 && !details.offset) { // aligned DWORD writes -> fast path
device->pci_cfg_write(reg_offs, BYTESWAP_32(value), details);
return;
}
// otherwise perform necessary data transformations -> slow path
uint32_t old_val = details.size == 4 ? 0 : device->pci_cfg_read(reg_offs, details);
uint32_t new_val = pci_conv_wr_data(old_val, value, details);
device->pci_cfg_write(reg_offs, new_val, details);
return;
}
LOG_WRITE_NON_EXISTENT_PCI_DEVICE();
}
uint32_t MPC106::pci_read(uint32_t size) {
int bus_num, dev_num, fun_num, reg_offs;
inline void MPC106::cfg_setup(uint32_t offset, int size, int &bus_num, int &dev_num,
int &fun_num, uint8_t &reg_offs, AccessDetails &details,
PCIDevice *&device)
{
device = NULL;
details.size = size;
details.offset = offset & 3;
bus_num = (this->config_addr >> 8) & 0xFF;
bus_num = (this->config_addr >> 8) & 0xFF;
dev_num = (this->config_addr >> 19) & 0x1F;
fun_num = (this->config_addr >> 16) & 0x07;
reg_offs = (this->config_addr >> 24) & 0xFC;
if (bus_num) {
details.flags = PCI_CONFIG_TYPE_1;
device = pci_find_device(bus_num, dev_num, fun_num);
LOG_F(
ERROR,
"%s err: read attempt from non-local PCI bus, config_addr = %x %02x:%02x.%x @%02x.%c",
this->name.c_str(), this->config_addr, bus_num, dev_num, fun_num, reg_offs,
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size
);
return 0xFFFFFFFFUL; // PCI spec §6.1
}
else {
details.flags = PCI_CONFIG_TYPE_0;
if (this->dev_map.count(DEV_FUN(dev_num, fun_num))) {
device = this->dev_map[DEV_FUN(dev_num, fun_num)];
if (dev_num == 0 && fun_num == 0) { // dev_num 0 is assigned to myself
return this->pci_cfg_read(reg_offs, size);
} else {
if (this->dev_map.count(dev_num)) {
return this->dev_map[dev_num]->pci_cfg_read(reg_offs, size);
} else {
LOG_F(
ERROR,
"%s err: read attempt from non-existing PCI device %02x:%02x.%x @%02x.%c",
this->name.c_str(), bus_num, dev_num, fun_num, reg_offs,
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size
);
return 0xFFFFFFFFUL; // PCI spec §6.1
}
}
return 0;
}
uint32_t MPC106::pci_cfg_read(uint32_t reg_offs, AccessDetails &details) {
if (reg_offs < 64) {
return PCIDevice::pci_cfg_read(reg_offs, details);
}
void MPC106::pci_write(uint32_t value, uint32_t size) {
int bus_num, dev_num, fun_num, reg_offs;
switch (reg_offs) {
case GrackleReg::CFG10:
return 0;
case GrackleReg::PMCR1:
return (this->odcr << 24) | (this->pmcr2 << 16) | this->pmcr1;
case GrackleReg::MSAR1:
case GrackleReg::MSAR2:
return this->mem_start[(reg_offs >> 2) & 1];
case GrackleReg::EMSAR1:
case GrackleReg::EMSAR2:
return this->ext_mem_start[(reg_offs >> 2) & 1];
case GrackleReg::MEAR1:
case GrackleReg::MEAR2:
return this->mem_end[(reg_offs >> 2) & 1];
case GrackleReg::EMEAR1:
case GrackleReg::EMEAR2:
return this->ext_mem_end[(reg_offs >> 2) & 1];
case GrackleReg::MBER:
return this->mem_bank_en;
case GrackleReg::PICR1:
return this->picr1;
case GrackleReg::PICR2:
return this->picr2;
case GrackleReg::MCCR1:
return this->mccr1;
case GrackleReg::MCCR2:
return this->mccr2;
case GrackleReg::MCCR3:
return this->mccr3;
case GrackleReg::MCCR4:
return this->mccr4;
default:
LOG_READ_UNIMPLEMENTED_CONFIG_REGISTER();
}
bus_num = (this->config_addr >> 8) & 0xFF;
dev_num = (this->config_addr >> 19) & 0x1F;
fun_num = (this->config_addr >> 16) & 0x07;
reg_offs = (this->config_addr >> 24) & 0xFC;
return 0; // PCI Spec §6.1
}
void MPC106::pci_cfg_write(uint32_t reg_offs, uint32_t value, AccessDetails &details) {
if (reg_offs < 64) {
PCIDevice::pci_cfg_write(reg_offs, value, details);
if (bus_num) {
LOG_F(
ERROR,
"%s err: write attempt to non-local PCI bus, config_addr = %x %02x:%02x.%x @%02x.%c = %0*x",
this->name.c_str(), this->config_addr, bus_num, dev_num, fun_num, reg_offs,
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size,
size * 2, value
);
return;
}
switch (reg_offs) {
case GrackleReg::CFG10:
// Open Firmware writes 0 to subordinate bus # - we don't care
break;
case GrackleReg::PMCR1:
this->pmcr1 = value & 0xFFFFU;
this->pmcr2 = (value >> 16) & 0xFF;
this->odcr = value >> 24;
break;
case GrackleReg::MSAR1:
case GrackleReg::MSAR2:
this->mem_start[(reg_offs >> 2) & 1] = value;
break;
case GrackleReg::EMSAR1:
case GrackleReg::EMSAR2:
this->ext_mem_start[(reg_offs >> 2) & 1] = value;
break;
case GrackleReg::MEAR1:
case GrackleReg::MEAR2:
this->mem_end[(reg_offs >> 2) & 1] = value;
break;
case GrackleReg::EMEAR1:
case GrackleReg::EMEAR2:
this->ext_mem_end[(reg_offs >> 2) & 1] = value;
break;
case GrackleReg::MBER:
this->mem_bank_en = value & 0xFFU;
break;
case GrackleReg::PICR1:
this->picr1 = value;
break;
case GrackleReg::PICR2:
this->picr2 = value;
break;
case GrackleReg::MCCR1:
if ((value ^ this->mccr1) & MEMGO) {
if (value & MEMGO)
setup_ram();
if (dev_num == 0 && fun_num == 0) { // dev_num 0 is assigned to myself
this->pci_cfg_write(reg_offs, value, size);
} else {
if (this->dev_map.count(dev_num)) {
this->dev_map[dev_num]->pci_cfg_write(reg_offs, value, size);
} else {
LOG_F(
ERROR,
"%s err: write attempt to non-existing PCI device %02x:%02x.%x @%02x.%c = %0*x",
this->name.c_str(), bus_num, dev_num, fun_num, reg_offs,
size == 4 ? 'l' : size == 2 ? 'w' : size == 1 ? 'b' : '0' + size,
size * 2, value
);
}
this->mccr1 = value;
break;
case GrackleReg::MCCR2:
this->mccr2 = value;
break;
case GrackleReg::MCCR3:
this->mccr3 = value;
break;
case GrackleReg::MCCR4:
this->mccr4 = value;
break;
default:
LOG_WRITE_UNIMPLEMENTED_CONFIG_REGISTER();
}
}
uint32_t MPC106::pci_cfg_read(uint32_t reg_offs, uint32_t size) {
#ifdef MPC106_DEBUG
LOG_F(9, "read from Grackle register %08X", reg_offs);
#endif
if (reg_offs < 64) {
return PCIDevice::pci_cfg_read(reg_offs, size);
}
return read_mem(&this->my_pci_cfg_hdr[reg_offs], size);
}
void MPC106::pci_cfg_write(uint32_t reg_offs, uint32_t value, uint32_t size) {
#ifdef MPC106_DEBUG
LOG_F(9, "write %08X to Grackle register %08X", value, reg_offs);
#endif
if (reg_offs < 64) {
PCIDevice::pci_cfg_write(reg_offs, value, size);
return;
}
// FIXME: implement write-protection for read-only registers
write_mem(&this->my_pci_cfg_hdr[reg_offs], value, size);
if (this->my_pci_cfg_hdr[0xF2] & 8) {
#ifdef MPC106_DEBUG
LOG_F(9, "MPC106: MCCR1[MEMGO] was set!");
#endif
setup_ram();
}
}
@@ -269,32 +229,33 @@ void MPC106::setup_ram() {
uint32_t mem_start, mem_end, ext_mem_start, ext_mem_end, bank_start, bank_end;
uint32_t ram_size = 0;
uint8_t bank_en = this->my_pci_cfg_hdr[0xA0];
for (int bank = 0; bank < 8; bank++) {
if (this->mem_bank_en & (1 << bank)) {
if (bank_en & (1 << bank)) {
if (bank < 4) {
mem_start = this->mem_start[0];
ext_mem_start = this->ext_mem_start[0];
mem_end = this->mem_end[0];
ext_mem_end = this->ext_mem_end[0];
mem_start = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x80]);
ext_mem_start = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x88]);
mem_end = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x90]);
ext_mem_end = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x98]);
} else {
mem_start = this->mem_start[1];
ext_mem_start = this->ext_mem_start[1];
mem_end = this->mem_end[1];
ext_mem_end = this->ext_mem_end[1];
mem_start = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x84]);
ext_mem_start = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x8C]);
mem_end = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x94]);
ext_mem_end = READ_DWORD_LE_A(&this->my_pci_cfg_hdr[0x9C]);
}
bank_start = (((ext_mem_start >> bank * 8) & 3) << 30) |
(((mem_start >> bank * 8) & 0xFF) << 20);
bank_end = (((ext_mem_end >> bank * 8) & 3) << 30) |
(((mem_end >> bank * 8) & 0xFF) << 20) | 0xFFFFFUL;
if (bank && bank_start != ram_size)
LOG_F(WARNING, "Grackle: RAM not contiguous!");
LOG_F(WARNING, "MPC106: RAM not contiguous!");
ram_size += bank_end - bank_start + 1;
}
}
if (!this->add_ram_region(0, ram_size)) {
LOG_F(WARNING, "Grackle: RAM allocation 0x%X..0x%X failed (maybe already exists?)",
0, ram_size - 1);
LOG_F(ERROR, "MPC106 RAM allocation failed!");
}
}
+97 -54
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -19,7 +19,7 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** MPC106 (Grackle) definitions.
/** MPC106 (Grackle) emulation
Grackle IC is a combined memory and PCI controller manufactured by Motorola.
It's the central device in the Gossamer architecture.
@@ -31,8 +31,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
- our virtual device reports revision 4.0 as expected by machine firmware
*/
#ifndef MPC106_H
#define MPC106_H
#ifndef MPC106_H_
#define MPC106_H_
#include <devices/common/mmiodevice.h>
#include <devices/common/pci/pcidevice.h>
@@ -43,32 +43,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <memory>
#include <unordered_map>
/** Grackle configuration space registers. */
enum GrackleReg : uint32_t {
CFG10 = 0x40, // bus # + subordinate bus # + disconnect counter
PMCR1 = 0x70, // power management config 1
MSAR1 = 0x80, // memory starting address 1
MSAR2 = 0x84, // memory starting address 2
EMSAR1 = 0x88, // extended memory starting address 1
EMSAR2 = 0x8C, // extended memory starting address 2
MEAR1 = 0x90, // memory ending address 1
MEAR2 = 0x94, // memory ending address 2
EMEAR1 = 0x98, // extended memory ending address 1
EMEAR2 = 0x9C, // extended memory ending address 2
MBER = 0xA0, // memory bank enable
PICR1 = 0xA8, // processor interface configuration 1
PICR2 = 0xAC, // processor interface configuration 2
MCCR1 = 0xF0, // memory control configuration 1
MCCR2 = 0xF4, // memory control configuration 2
MCCR3 = 0xF8, // memory control configuration 3
MCCR4 = 0xFC // memory control configuration 4
};
/* MCCR1 bit definitions. */
enum {
MEMGO = 1 << 19,
};
class MPC106 : public MemCtrlBase, public PCIDevice, public PCIHost {
public:
MPC106();
@@ -85,37 +59,106 @@ public:
protected:
/* PCI access */
uint32_t pci_read(uint32_t offset, uint32_t size);
void pci_write(uint32_t offset, uint32_t value, uint32_t size);
uint32_t pci_read(uint32_t size);
void pci_write(uint32_t value, uint32_t size);
/* my own PCI configuration registers access */
uint32_t pci_cfg_read(uint32_t reg_offs, AccessDetails &details);
void pci_cfg_write(uint32_t reg_offs, uint32_t value, AccessDetails &details);
uint32_t pci_cfg_read(uint32_t reg_offs, uint32_t size);
void pci_cfg_write(uint32_t reg_offs, uint32_t value, uint32_t size);
bool supports_io_space(void) {
return true;
};
void setup_ram(void);
private:
inline void cfg_setup(uint32_t offset, int size, int &bus_num, int &dev_num,
int &fun_num, uint8_t &reg_offs, AccessDetails &details,
PCIDevice *&device);
uint8_t my_pci_cfg_hdr[256] = {
0x57, 0x10, // vendor ID: Motorola
0x02, 0x00, // device ID: MPC106
0x06, 0x00, // PCI command
0x80, 0x00, // PCI status
0x40, // revision ID: 4.0
0x00, // standard programming
0x00, // subclass code: host bridge
0x06, // class code: bridge device
0x08, // cache line size
0x00, // latency timer
0x00, // header type
0x00, // BIST Control
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, // Interrupt line
0x00, // Interrupt pin
0x00, // MIN GNT
0x00, // MAX LAT
0x00, // Bus number
0x00, // Subordinate bus number
0x00, // Discount counter
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, // Performance monitor command
0x00, 0x00, // Performance monitor mode control
0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00, // Performance monitor counter 0
0x00, 0x00, 0x00, 0x00, // Performance monitor counter 1
0x00, 0x00, 0x00, 0x00, // Performance monitor counter 2
0x00, 0x00, 0x00, 0x00, // Performance monitor counter 3
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF,
0x00, 0x00, // Power mgt config 1
0x00, // Power mgt config 2
0xCD, // default value for ODCR
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, // Memory Starting Address
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Extended Memory Starting Address
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Memory Ending Address
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Extended Memory Ending Address
0x00, // Memory bank enable
0xFF, 0xFF,
0x00, // Memory page mode
0xFF, 0xFF, 0xFF, 0xFF,
0x10, 0x00, 0x00, 0xFF, // PICR1
0x0C, 0x06, 0x0C, 0x00, // PICR2
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, // ECC single-bit error counter
0x00, // ECC single-bit error trigger
0x04, // Alternate OS visible paramaters 1
0x01, // Alternate OS visible paramaters 2
0xFF, 0xFF, 0xFF, 0xFF,
0x01, // Error enabling 1
0x00, // Error detection 1
0xFF,
0x00, // 60x bus error status
0x00, // Error enabling 2
0x00, // Error detection 2
0xFF,
0x00, // PCI bus error status
0x00, 0x00, 0x00, 0x00, // 60x/PCI ERROR address
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF,
0x42, 0x00, 0xFF, 0x0F, // Emulation support config 1
0x00, 0x00, 0x00, 0x00, // Modified memory status (no clear)
0x20, 0x00, 0x00, 0x00, // Emulation support config 2
0x00, 0x00, 0x00, 0x00, // Modified memory status (clear)
0x00, 0x00, 0x02, 0xFF, // Memory ctrl config 1
0x03, 0x00, 0x00, 0x00, // Memory ctrl config 2
0x00, 0x00, 0x00, 0x00, // Memory ctrl config 3
0x00, 0x00, 0x10, 0x00 // Memory ctrl config 4
};
uint32_t config_addr;
uint16_t pmcr1 = 0; // power management config 1
uint8_t pmcr2 = 0; // power management config 2
uint8_t odcr = 0xCD; // output driver control
uint32_t picr1 = 0xFF100010; // ROM on CPU bus, address map B, CPU type = MPC601
uint32_t picr2 = 0x000C060C;
uint32_t mccr1 = 0xFF820000; // 64bit ROM bus
uint32_t mccr2 = 3;
uint32_t mccr3 = 0;
uint32_t mccr4 = 0x00100000;
uint32_t mem_start[2] = {};
uint32_t ext_mem_start[2] = {};
uint32_t mem_end[2] = {};
uint32_t ext_mem_end[2] = {};
uint8_t mem_bank_en = 0;
};
#endif // MPC106_H
#endif
-128
View File
@@ -1,128 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** PSX Memory Controller emulation. */
#include <devices/deviceregistry.h>
#include <devices/memctrl/psx.h>
#include <loguru.hpp>
#include <cinttypes>
#include <string>
PsxCtrl::PsxCtrl(int bridge_num, std::string name)
{
supports_types(HWCompType::MEM_CTRL | HWCompType::MMIO_DEV);
// add MMIO region for the PSX control registers
add_mmio_region(0xF8000000, 0x70, this);
this->sys_id = 0x10000000;
this->chip_rev = 0; // old PSX, what's about PSX+?
this->sys_config = PSX_BUS_SPEED_50;
}
uint32_t PsxCtrl::read(uint32_t rgn_start, uint32_t offset, int size)
{
switch (offset >> 3) {
case PsxReg::Sys_Id:
return this->sys_id;
case PsxReg::Revision:
return this->chip_rev;
case PsxReg::Sys_Config:
return this->sys_config;
default:
LOG_F(WARNING, "PSX: read from unsupported control register at 0x%X", offset);
return 0;
}
}
void PsxCtrl::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size)
{
switch (offset >> 3) {
case PsxReg::Sys_Config:
this->sys_config = value;
break;
case PsxReg::ROM_Config:
this->rom_cfg = value;
break;
case PsxReg::DRAM_Config:
this->dram_cfg = value;
break;
case PsxReg::DRAM_Refresh:
this->dram_refresh = value;
break;
case PsxReg::Flash_Config:
this->flash_cfg = value;
break;
case PsxReg::Page1_Mapping:
case PsxReg::Page2_Mapping:
case PsxReg::Page3_Mapping:
case PsxReg::Page4_Mapping:
case PsxReg::Page5_Mapping:
this->pages_cfg[(offset >> 3) - PsxReg::Page1_Mapping] = value;
break;
default:
LOG_F(WARNING, "PSX: write to unsupported/read-only control register at 0x%X", offset);
};
}
void PsxCtrl::insert_ram_dimm(int slot_num, uint32_t capacity)
{
if (slot_num < 0 || slot_num >= 5) {
ABORT_F("PSX: invalid DIMM slot %d", slot_num);
}
switch (capacity) {
case DRAM_CAP_2MB:
case DRAM_CAP_4MB:
case DRAM_CAP_8MB:
case DRAM_CAP_16MB:
case DRAM_CAP_32MB:
this->bank_sizes[slot_num] = capacity;
break;
default:
ABORT_F("PSX: unsupported DRAM capacity %d", capacity);
}
}
void PsxCtrl::map_phys_ram()
{
uint32_t total_ram = 0;
for (int i = 0; i < 5; i++) {
total_ram += this->bank_sizes[i];
}
if (total_ram > DRAM_CAP_32MB) {
ABORT_F("PSX: RAM bigger than 32MB not supported yet");
}
if (!add_ram_region(0x00000000, total_ram)) {
ABORT_F("PSX: could not allocate RAM storage");
}
}
static const DeviceDescription Psx_Descriptor = {
PsxCtrl::create, {}, {}
};
REGISTER_DEVICE(Psx, Psx_Descriptor);
-88
View File
@@ -1,88 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** PSX Memory Controller definitions. */
#ifndef PSX_MEMCTRL_H
#define PSX_MEMCTRL_H
#include <devices/common/mmiodevice.h>
#include <devices/memctrl/memctrlbase.h>
#include <cinttypes>
#include <memory>
#include <string>
namespace PsxReg {
enum {
Sys_Id = 0,
Revision = 1,
Sys_Config = 2,
ROM_Config = 3,
DRAM_Config = 4,
DRAM_Refresh = 5,
Flash_Config = 6,
Page1_Mapping = 8,
Page2_Mapping = 9,
Page3_Mapping = 10,
Page4_Mapping = 11,
Page5_Mapping = 12,
Bus_Timeout = 13
};
}; // namespace PsxReg
/** Bus (aka CPU) speed constants. */
enum {
PSX_BUS_SPEED_38 = 0, // bus frequency 38 MHz
PSX_BUS_SPEED_33 = 1, // bus frequency 33 MHz
PSX_BUS_SPEED_40 = 2, // bus frequency 40 MHz
PSX_BUS_SPEED_50 = 3, // bus frequency 50 MHz
};
class PsxCtrl : public MemCtrlBase, public MMIODevice {
public:
PsxCtrl(int bridge_num, std::string name);
~PsxCtrl() = default;
static std::unique_ptr<HWComponent> create() {
return std::unique_ptr<PsxCtrl>(new PsxCtrl(1, "PSX-PCI1"));
};
// MMIODevice methods
uint32_t read(uint32_t rgn_start, uint32_t offset, int size);
void write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size);
void insert_ram_dimm(int slot_num, uint32_t capacity);
void map_phys_ram();
private:
uint32_t sys_id;
uint32_t chip_rev;
uint32_t sys_config;
uint32_t rom_cfg;
uint32_t dram_cfg;
uint32_t dram_refresh;
uint32_t flash_cfg;
uint32_t pages_cfg[5];
uint32_t bank_sizes[5] = {};
};
#endif // PSX_MEMCTRL_H
+4 -3
View File
@@ -336,6 +336,7 @@ void CharIoSocket::rcv_disable()
bool CharIoSocket::rcv_char_available()
{
static int consecutivechars = 0;
static int count = 0;
if (consecutivechars >= 15) {
consecutivechars++;
@@ -376,7 +377,7 @@ bool CharIoSocket::rcv_char_available()
if (sockfd != -1) {
if (FD_ISSET(sockfd, &readfds)) {
uint8_t c;
int received = (int)recv(sockfd, &c, 1, 0);
int received = recv(sockfd, &c, 1, 0);
if (received == -1) {
if (acceptfd == -1) {
//LOG_F(INFO, "socket sock read (not accepted yet) err: %s", strerror(errno)); // this happens once before accept
@@ -442,7 +443,7 @@ int CharIoSocket::xmit_char(uint8_t c)
CharIoSocket::rcv_char_available();
if (acceptfd != -1) {
int sent = (int)send(acceptfd, &c, 1, 0);
int sent = send(acceptfd, &c, 1, 0);
if (sent == -1) {
LOG_F(INFO, "socket accept write err: %s", strerror(errno));
}
@@ -462,7 +463,7 @@ int CharIoSocket::rcv_char(uint8_t *c)
CharIoSocket::rcv_char_available();
if (acceptfd != -1) {
int received = (int)recv(acceptfd, c, 1, 0);
int received = recv(acceptfd, c, 1, 0);
if (received == -1) {
LOG_F(INFO, "socket accept read err: %s", strerror(errno));
}
+1
View File
@@ -92,6 +92,7 @@ uint8_t EsccController::read(uint8_t reg_offset)
} else {
return this->ch_a->read_reg(this->reg_ptr);
}
this->reg_ptr = 0;
break;
case EsccReg::Port_B_Data:
return this->ch_b->receive_byte();
+70 -54
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-21 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -24,9 +24,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
Currently supported audio codecs:
- PDM AWACs in Nubus Power Macintosh models
- Screamer AWACs in Beige G3
Author: Max Poliakovski 2019-21
*/
#include <devices/deviceregistry.h>
#include <devices/common/dbdma.h>
#include <devices/sound/awacs.h>
#include <devices/sound/soundserver.h>
#include <endianswap.h>
@@ -36,12 +38,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <loguru.hpp>
#include <memory>
AwacsBase::AwacsBase(std::string name)
AwacsBase::AwacsBase()
{
supports_types(HWCompType::SND_CODEC);
this->name = name;
// connect to SoundServer
this->snd_server = dynamic_cast<SoundServer *>
(gMachineObj->get_comp_by_name("SoundServer"));
@@ -51,43 +49,31 @@ AwacsBase::AwacsBase(std::string name)
void AwacsBase::set_sample_rate(int sr_id)
{
if (sr_id > this->max_sr_id) {
LOG_F(ERROR, "%s: invalid sample rate ID %d!", this->name.c_str(), sr_id);
LOG_F(ERROR, "AWACs: invalid sample rate ID %d!", sr_id);
} else {
this->cur_sample_rate = this->sr_table[sr_id];
}
};
void AwacsBase::dma_out_start()
void AwacsBase::start_output_dma()
{
int err;
bool reopen = false;
int err;
if (this->out_stream_ready && this->out_sample_rate != this->cur_sample_rate)
reopen = true;
if (reopen) {
snd_server->close_out_stream();
if ((err = this->snd_server->open_out_stream(this->cur_sample_rate,
(void *)this->dma_out_ch))) {
LOG_F(ERROR, "AWACs: unable to open sound output stream: %d", err);
this->out_stream_ready = false;
return;
}
if (!this->out_stream_ready || reopen) {
if ((err = this->snd_server->open_out_stream(this->cur_sample_rate,
(void *)this->dma_out_ch))) {
LOG_F(ERROR, "%s: unable to open sound output stream: %d",
this->name.c_str(), err);
return;
}
this->out_stream_ready = true;
if ((err = snd_server->start_out_stream())) {
LOG_F(ERROR, "%s: could not start sound output stream", this->name.c_str());
}
this->out_sample_rate = this->cur_sample_rate;
this->out_stream_ready = true;
if ((err = snd_server->start_out_stream())) {
LOG_F(ERROR, "AWACs: could not start sound output stream");
}
}
void AwacsBase::dma_out_stop()
void AwacsBase::stop_output_dma()
{
if (this->out_stream_ready) {
snd_server->close_out_stream();
@@ -96,7 +82,7 @@ void AwacsBase::dma_out_stop()
}
//=========================== PDM-style AWACs =================================
AwacDevicePdm::AwacDevicePdm() : AwacsBase("AWAC-PDM")
AwacDevicePdm::AwacDevicePdm() : AwacsBase()
{
static int pdm_awac_freqs[3] = {22050, 29400, 44100};
@@ -107,40 +93,37 @@ AwacDevicePdm::AwacDevicePdm() : AwacsBase("AWAC-PDM")
uint32_t AwacDevicePdm::read_stat()
{
LOG_F(INFO, "%s: status requested!", this->name.c_str());
LOG_F(INFO, "AWACs-PDM: status requested!");
// TODO: return valid status including manufacturer & device IDs
return 0;
}
void AwacDevicePdm::write_ctrl(uint32_t addr, uint16_t value)
{
LOG_F(9, "AWACs-PDM: control updated, addr=0x%X, val=0x%X", addr, value);
if (addr <= 4) {
this->ctrl_regs[addr] = value;
} else {
LOG_F(ERROR, "%s: invalid control register address %d!", this->name.c_str(),
addr);
LOG_F(ERROR, "AWACs-PDM: invalid control register address %d!", addr);
}
}
//============================= Screamer AWACs ================================
AwacsScreamer::AwacsScreamer(std::string name) : MacioSndCodec(name)
AwacsScreamer::AwacsScreamer() : AwacsBase()
{
static int screamer_freqs[8] = {
44100, 29400, 22050, 17640, 14700, 11025, 8820, 7350
};
this->sr_table = screamer_freqs;
this->max_sr_id = 7;
}
int AwacsScreamer::device_postinit() {
this->audio_proc = std::unique_ptr<AudioProcessor> (new AudioProcessor());
/* register audio processor chip with the I2C bus */
I2CBus* i2c_bus = dynamic_cast<I2CBus*>(gMachineObj->get_comp_by_type(HWCompType::I2C_HOST));
i2c_bus->register_device(0x45, this->audio_proc.get());
return 0;
static int screamer_freqs[8] = {
44100, 29400, 22050, 17640, 14700, 11025, 8820, 7350
};
this->sr_table = screamer_freqs;
this->max_sr_id = 7;
}
uint32_t AwacsScreamer::snd_ctrl_read(uint32_t offset, int size)
@@ -153,7 +136,7 @@ uint32_t AwacsScreamer::snd_ctrl_read(uint32_t offset, int size)
case AWAC_CODEC_STATUS_REG:
return (AWAC_AVAILABLE << 8) | (AWAC_MAKER_CRYSTAL << 16) | (AWAC_REV_SCREAMER << 20);
default:
LOG_F(ERROR, "%s: unsupported register at offset 0x%X", this->name.c_str(), offset);
LOG_F(ERROR, "Screamer: unsupported register at offset 0x%X", offset);
}
return 0;
@@ -167,25 +150,58 @@ void AwacsScreamer::snd_ctrl_write(uint32_t offset, uint32_t value, int size)
switch (offset) {
case AWAC_SOUND_CTRL_REG:
this->snd_ctrl_reg = BYTESWAP_32(value);
this->set_sample_rate((this->snd_ctrl_reg >> 8) & 7);
LOG_F(9, "Screamer: new sound control value = 0x%X", this->snd_ctrl_reg);
break;
case AWAC_CODEC_CTRL_REG:
subframe = (value >> 14) & 3;
reg_num = (value >> 20) & 7;
data = ((value >> 8) & 0xF00) | ((value >> 24) & 0xFF);
LOG_F(9, "%s subframe = %d, reg = %d, data = %08X", this->name.c_str(),
LOG_F(9, "Screamer subframe = %d, reg = %d, data = %08X",
subframe, reg_num, data);
if (!subframe)
this->control_regs[reg_num] = data;
break;
default:
LOG_F(ERROR, "%s: unsupported register at offset 0x%X", this->name.c_str(),
offset);
LOG_F(ERROR, "Screamer: unsupported register at offset 0x%X", offset);
}
}
static const DeviceDescription Screamer_Descriptor = {
AwacsScreamer::create, {}, {}
};
void AwacsScreamer::open_stream(int sample_rate)
{
int err;
REGISTER_DEVICE(ScreamerSnd, Screamer_Descriptor);
if ((err = this->snd_server->open_out_stream(sample_rate, (void *)this->dma_out_ch))) {
LOG_F(ERROR, "Screamer: unable to open sound output stream: %d", err);
this->out_stream_ready = false;
} else {
this->out_sample_rate = sample_rate;
this->out_stream_ready = true;
}
}
void AwacsScreamer::dma_start()
{
int err;
if (!this->out_stream_ready) {
this->open_stream(this->sr_table[(this->snd_ctrl_reg >> 8) & 7]);
} else if (this->out_sample_rate != this->sr_table[(this->snd_ctrl_reg >> 8) & 7]) {
snd_server->close_out_stream();
this->open_stream(this->sr_table[(this->snd_ctrl_reg >> 8) & 7]);
} else {
LOG_F(ERROR, "Screamer: unpausing attempted!");
return;
}
if (!this->out_stream_ready) {
return;
}
if ((err = snd_server->start_out_stream())) {
LOG_F(ERROR, "Screamer: could not start sound output stream");
}
}
void AwacsScreamer::dma_end()
{
}
+32 -37
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-21 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -28,19 +28,18 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef AWAC_H
#define AWAC_H
#include <devices/common/dbdma.h>
#include <devices/common/dmacore.h>
#include <devices/common/hwcomponent.h>
#include <devices/common/i2c/i2c.h>
#include <devices/sound/soundserver.h>
#include <cinttypes>
#include <memory>
#include <string>
/** Base class for the AWACs codecs. */
class AwacsBase : public HWComponent {
class AwacsBase {
public:
AwacsBase(std::string name);
AwacsBase();
~AwacsBase() = default;
void set_dma_out(DmaOutChannel *dma_out_ch) {
@@ -48,8 +47,8 @@ public:
};
void set_sample_rate(int sr_id);
void dma_out_start();
void dma_out_stop();
void start_output_dma();
void stop_output_dma();
protected:
SoundServer *snd_server; // SoundServer instance pointer
@@ -58,9 +57,8 @@ protected:
int *sr_table; // pointer to the table of supported sample rates
int max_sr_id; // maximum value for sample rate ID
bool out_stream_ready = false;
int cur_sample_rate = -1;
int out_sample_rate = -1;
bool out_stream_ready;
int cur_sample_rate;
};
/** AWACs PDM-style sound codec. */
@@ -72,17 +70,24 @@ public:
uint32_t read_stat(void);
void write_ctrl(uint32_t addr, uint16_t value);
void dma_out_start(uint8_t sample_rate_id);
void dma_out_stop();
private:
uint16_t ctrl_regs[5] = {}; // 12-bit wide control registers
uint16_t ctrl_regs[5]; // 12-bit wide control registers
};
/** Offsets to MacIO sound codec registers. */
/** AWACs Screamer registers offsets. */
enum {
AWAC_SOUND_CTRL_REG = 0x00,
AWAC_CODEC_CTRL_REG = 0x10,
AWAC_CODEC_STATUS_REG = 0x20,
};
/** AWACs Screamer manufacturer and revision. */
#define AWAC_MAKER_CRYSTAL 1
#define AWAC_REV_SCREAMER 3
/** Apple source calls this kValidData but doesn't explain
what it actually means. It seems like it's used to check
if the sound codec is available.
@@ -102,7 +107,7 @@ public:
bool send_subaddress(uint8_t sub_addr) {
if ((sub_addr & 0xF) > 6)
return false; // invalid subaddress -> no acknowledge
return false; /* invalid subaddress -> no acknowledge */
this->sub_addr = sub_addr & 0xF;
this->auto_inc = !!(sub_addr & 0x10);
@@ -123,7 +128,7 @@ public:
}
return true;
} else {
return false; // invalid sub_addr -> no acknowledge
return false; /* invalid sub_addr -> no acknowledge */
}
};
@@ -134,43 +139,33 @@ public:
};
private:
uint8_t regs[7] = {}; // control registers, see TDA7433 datasheet
uint8_t regs[7]; /* control registers, see TDA7433 datasheet */
uint8_t sub_addr;
int pos;
int auto_inc;
};
/** Sound codec interface with the typical MacIO access. */
class MacioSndCodec : public AwacsBase {
/** AWACs Screamer sound codec. */
class AwacsScreamer : public AwacsBase {
public:
MacioSndCodec(std::string name) : AwacsBase(name) {};
virtual uint32_t snd_ctrl_read(uint32_t offset, int size) = 0;
virtual void snd_ctrl_write(uint32_t offset, uint32_t value, int size) = 0;
};
/** AWACs Screamer manufacturer and revision. */
#define AWAC_MAKER_CRYSTAL 1
#define AWAC_REV_SCREAMER 3
/** Screamer sound codec. */
class AwacsScreamer : public MacioSndCodec {
public:
AwacsScreamer(std::string name = "Screamer");
AwacsScreamer();
~AwacsScreamer() = default;
uint32_t snd_ctrl_read(uint32_t offset, int size);
void snd_ctrl_write(uint32_t offset, uint32_t value, int size);
int device_postinit();
void dma_start();
void dma_end();
static std::unique_ptr<HWComponent> create() {
return std::unique_ptr<AwacsScreamer>(new AwacsScreamer("Screamer"));
}
protected:
void open_stream(int sample_rate);
private:
uint32_t snd_ctrl_reg = 0;
uint16_t control_regs[8] = {}; // control registers, each 12-bits wide
uint8_t is_busy = 0;
uint32_t snd_ctrl_reg = { 0 };
uint16_t control_regs[8] = { 0 }; /* control registers, each 12-bits wide */
uint8_t is_busy = 0;
int out_sample_rate;
std::unique_ptr<AudioProcessor> audio_proc;
};
-104
View File
@@ -1,104 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** Burgundy sound codec emulation. */
#include <core/timermanager.h>
#include <devices/common/hwcomponent.h>
#include <devices/deviceregistry.h>
#include <devices/sound/burgundy.h>
#include <endianswap.h>
#include <loguru.hpp>
#include <memaccess.h>
BurgundyCodec::BurgundyCodec(std::string name) : MacioSndCodec(name)
{
supports_types(HWCompType::SND_CODEC);
static int burgundy_sample_rates[1] = { 44100 };
// Burgundy seems to supports only one sample rate
this->sr_table = burgundy_sample_rates;
this->max_sr_id = 1;
this->set_sample_rate(0); // set default sample rate
}
uint32_t BurgundyCodec::snd_ctrl_read(uint32_t offset, int size) {
uint32_t result = 0;
switch (offset) {
case AWAC_CODEC_CTRL_REG:
result = this->last_ctrl_data;
break;
case AWAC_CODEC_STATUS_REG:
result = (this->first_valid << 23) | BURGUNDY_READY |
(this->byte_counter << 14) | (this->read_pos << 12) |
(this->data_byte << 4);
break;
default:
LOG_F(ERROR, "%s: read from unsupported register 0x%X", this->name.c_str(),
offset);
}
return BYTESWAP_32(result);
}
void BurgundyCodec::snd_ctrl_write(uint32_t offset, uint32_t value, int size) {
uint8_t reg_addr, cur_byte, last_byte;
value = BYTESWAP_32(value);
switch (offset) {
case AWAC_CODEC_CTRL_REG:
this->last_ctrl_data = value;
reg_addr = (value >> 12) & 0xFF;
cur_byte = (value >> 8) & 3;
last_byte = (value >> 10) & 3;
if (value & BURGUNDY_REG_WR) {
uint32_t mask = 0xFFU << (cur_byte * 8);
this->reg_array[reg_addr] = (this->reg_array[reg_addr] & ~mask) |
((value & 0xFFU) << (cur_byte * 8));
} else {
this->reg_addr = reg_addr;
this->read_pos = cur_byte;
this->data_byte = (this->reg_array[reg_addr] >> (cur_byte * 8)) & 0xFFU;
this->first_valid = 1;
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;
default:
LOG_F(ERROR, "%s: write to unsupported register 0x%X", this->name.c_str(),
offset);
}
}
static const DeviceDescription Burgundy_Descriptor = {
BurgundyCodec::create, {}, {}
};
REGISTER_DEVICE(BurgundySnd, Burgundy_Descriptor);
-64
View File
@@ -1,64 +0,0 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** Burgundy sound codec definitions. */
#ifndef BURGUNDY_H
#define BURGUNDY_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. */
#define BURGUNDY_NUM_REGS 123
class BurgundyCodec : public MacioSndCodec {
public:
BurgundyCodec(std::string name);
~BurgundyCodec() = default;
uint32_t snd_ctrl_read(uint32_t offset, int size);
void snd_ctrl_write(uint32_t offset, uint32_t value, int size);
static std::unique_ptr<HWComponent> create() {
return std::unique_ptr<BurgundyCodec>(new BurgundyCodec("Burgundy"));
}
private:
uint32_t last_ctrl_data = 0;
uint8_t byte_counter = 0;
uint8_t reg_addr = 0;
uint8_t first_valid = 0;
uint8_t read_pos = 0;
uint8_t data_byte = 0;
uint32_t reg_array[BURGUNDY_NUM_REGS] = {};
};
#endif // BURGUNDY_H
+6 -6
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -147,12 +147,12 @@ long sound_out_callback(cubeb_stream *stream, void *user_data,
out_frames = 0;
while (req_frames > 0) {
if (!dma_ch->pull_data((uint32_t)req_frames << 2, &got_len, &p_in)) {
if (!dma_ch->pull_data(req_frames << 2, &got_len, &p_in)) {
frames = got_len >> 2;
in_buf = (int16_t*)p_in;
for (int i = (int)frames; i > 0; i--) {
for (int i = frames; i > 0; i--) {
out_buf[0] = BYTESWAP_16(in_buf[0]);
out_buf[1] = BYTESWAP_16(in_buf[1]);
in_buf += 2;
@@ -192,7 +192,7 @@ int SoundServer::open_out_stream(uint32_t sample_rate, void *user_data)
LOG_F(ERROR, "Could not get minimum latency, error: %d", res);
return -1;
} else {
LOG_F(9, "Minimum sound latency: %d frames", latency_frames);
LOG_F(INFO, "Minimum sound latency: %d frames", latency_frames);
}
res = cubeb_stream_init(this->cubeb_ctx, &this->out_stream, "SndOut stream",
@@ -203,7 +203,7 @@ int SoundServer::open_out_stream(uint32_t sample_rate, void *user_data)
return -1;
}
LOG_F(9, "Sound output stream opened.");
LOG_F(INFO, "Sound output stream opened.");
this->status = SND_STREAM_OPENED;
@@ -219,5 +219,5 @@ void SoundServer::close_out_stream()
{
cubeb_stream_stop(this->out_stream);
cubeb_stream_destroy(this->out_stream);
LOG_F(9, "Sound output stream closed.");
LOG_F(INFO, "Sound output stream closed.");
}
+138 -142
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -31,154 +31,150 @@ enum {
/** Mach64 register offsets. */
enum {
ATI_CRTC_H_TOTAL_DISP = 0x000, // 0x0000
ATI_CRTC_H_SYNC_STRT_WID = 0x001, // 0x0004
ATI_CRTC_V_TOTAL_DISP = 0x002, // 0x0008
ATI_CRTC_V_SYNC_STRT_WID = 0x003, // 0x000C
ATI_CRTC_VLINE_CRNT_VLINE = 0x004, // 0x0010
ATI_CRTC_OFF_PITCH = 0x005, // 0x0014
ATI_CRTC_INT_CNTL = 0x006, // 0x0018
ATI_CRTC_GEN_CNTL = 0x007, // 0x001C
ATI_DSP_CONFIG = 0x008, // 0x0020
ATI_DSP_ON_OFF = 0x009, // 0x0024
ATI_TIMER_CFG = 0x00A, // 0x0028
ATI_MEM_BUF_CNTL = 0x00B, // 0x002C
ATI_MEM_ADDR_CFG = 0x00D, // 0x0034
ATI_CRT_TRAP = 0x00E, // 0x0038
ATI_I2C_CNTL_0 = 0x00F, // 0x003C
ATI_OVR_CLR = 0x010, // 0x0040
ATI_OVR_WID_LEFT_RIGHT = 0x011, // 0x0044
ATI_OVR_WID_TOP_BOTTOM = 0x012, // 0x0048
ATI_VGA_DSP_CFG = 0x013, // 0x004C
ATI_VGA_DSP_ON_OFF = 0x014, // 0x0050
ATI_DSP2_CONFIG = 0x015, // 0x0054 <-- LT specific
ATI_DSP2_ON_OFF = 0x016, // 0x0058 <-- LT specific
ATI_CRTC2_OFF_PITCH = 0x017, // 0x005C <-- LT specific
ATI_CUR_CLR0 = 0x018, // 0x0060
ATI_CUR_CLR1 = 0x019, // 0x0064
ATI_CUR_OFFSET = 0x01A, // 0x0068
ATI_CUR_HORZ_VERT_POSN = 0x01B, // 0x006C
ATI_CUR_HORZ_VERT_OFF = 0x01C, // 0x0070
ATI_GP_IO = 0x01E, // 0x0078
ATI_HW_DEBUG = 0x01F, // 0x007C
ATI_SCRATCH_REG0 = 0x020, // 0x0080
ATI_SCRATCH_REG1 = 0x021, // 0x0084
ATI_SCRATCH_REG2 = 0x022, // 0x0088
ATI_SCRATCH_REG3 = 0x023, // 0x008C
ATI_CLOCK_CNTL = 0x024, // 0x0090
ATI_CONFIG_STAT1 = 0x025, // 0x0094
ATI_CONFIG_STAT2 = 0x026, // 0x0098
ATI_BUS_CNTL = 0x028, // 0x00A0
ATI_EXT_MEM_CNTL = 0x02B, // 0x00AC
ATI_MEM_CNTL = 0x02C, // 0x00B0
ATI_MEM_VGA_WP_SEL = 0x02D, // 0x00B4
ATI_MEM_VGA_RP_SEL = 0x02E, // 0x00B8
ATI_I2C_CNTL_1 = 0x02F, // 0x00BC
ATI_DAC_REGS = 0x030, // 0x00C0
// byte offsets for the built-in DAC registers
ATI_CRTC_H_TOTAL_DISP = 0x0000,
ATI_CRTC_H_SYNC_STRT_WID = 0x0004,
ATI_CRTC_V_TOTAL_DISP = 0x0008,
ATI_CRTC_V_SYNC_STRT_WID = 0x000C,
ATI_CRTC_VLINE_CRNT_VLINE = 0x0010,
ATI_CRTC_OFF_PITCH = 0x0014,
ATI_CRTC_INT_CNTL = 0x0018,
ATI_CRTC_GEN_CNTL = 0x001C,
ATI_DSP_CONFIG = 0x0020,
ATI_DSP_ON_OFF = 0x0024,
ATI_TIMER_CFG = 0x0028,
ATI_MEM_BUF_CNTL = 0x002C,
ATI_MEM_ADDR_CFG = 0x0034,
ATI_CRT_TRAP = 0x0038,
ATI_I2C_CNTL_0 = 0x003C,
ATI_OVR_CLR = 0x0040,
ATI_OVR_WID_LEFT_RIGHT = 0x0044,
ATI_OVR_WID_TOP_BOTTOM = 0x0048,
ATI_VGA_DSP_CFG = 0x004C,
ATI_VGA_DSP_TGL = 0x0050,
ATI_DSP2_CONFIG = 0x0054,
ATI_DSP2_TOGGLE = 0x0058,
ATI_CRTC2_OFF_PITCH = 0x005C,
ATI_CUR_CLR0 = 0x0060,
ATI_CUR_CLR1 = 0x0064,
ATI_CUR_OFFSET = 0x0068,
ATI_CUR_HORZ_VERT_POSN = 0x006C,
ATI_CUR_HORZ_VERT_OFF = 0x0070,
ATI_GP_IO = 0x0078,
ATI_HW_DEBUG = 0x007C,
ATI_SCRATCH_REG0 = 0x0080,
ATI_SCRATCH_REG1 = 0x0084,
ATI_SCRATCH_REG2 = 0x0088,
ATI_SCRATCH_REG3 = 0x008C,
ATI_CLOCK_CNTL = 0x0090,
ATI_CONFIG_STAT1 = 0x0094,
ATI_CONFIG_STAT2 = 0x0098,
ATI_BUS_CNTL = 0x00A0,
ATI_EXT_MEM_CNTL = 0x00AC,
ATI_MEM_CNTL = 0x00B0,
ATI_MEM_VGA_WP_SEL = 0x00B4,
ATI_MEM_VGA_RP_SEL = 0x00B8,
ATI_I2C_CNTL_1 = 0x00BC,
ATI_DAC_REGS = 0x00C0,
ATI_DAC_W_INDEX = 0x00C0,
ATI_DAC_DATA = 0x00C1,
ATI_DAC_MASK = 0x00C2,
ATI_DAC_R_INDEX = 0x00C3,
ATI_DAC_CNTL = 0x031, // 0x00C4
ATI_GEN_TEST_CNTL = 0x034, // 0x00D0
ATI_CUSTOM_MACRO_CNTL = 0x035, // 0x00D4
ATI_CONFIG_CNTL = 0x037, // 0x00DC
ATI_CONFIG_CHIP_ID = 0x038, // 0x00E0
ATI_CONFIG_STAT0 = 0x039, // 0x00E4
ATI_GX_CONFIG_STAT1 = 0x03A, // 0x00E8 <-- GX/CT specific
ATI_CRC_SIG = 0x03A, // 0x00E8
ATI_DST_OFF_PITCH = 0x040, // 0x0100
ATI_DST_X = 0x041, // 0x0104
ATI_DST_Y = 0x042, // 0x0108
ATI_DST_Y_X = 0x043, // 0x010C
ATI_DST_WIDTH = 0x044, // 0x0110
ATI_DST_HEIGHT = 0x045, // 0x0114
ATI_DST_HEIGHT_WIDTH = 0x046, // 0x0118
ATI_DST_X_WIDTH = 0x047, // 0x011C
ATI_DST_BRES_LNTH = 0x048, // 0x0120
ATI_DST_BRES_ERR = 0x049, // 0x0124
ATI_DST_BRES_INC = 0x04A, // 0x0128
ATI_DST_BRES_DEC = 0x04B, // 0x012C
ATI_DST_CNTL = 0x04C, // 0x0130
ATI_DST_Y_X_ALIAS1 = 0x04D, // 0x0134
ATI_TRAIL_BRES_ERR = 0x04E, // 0x0138
ATI_TRAIL_BRES_INC = 0x04F, // 0x013C
ATI_TRAIL_BRES_DEC = 0x050, // 0x0140
ATI_DST_BRES_LNTH_ALIAS1 = 0x051, // 0x0144
ATI_Z_OFF_PITCH = 0x052, // 0x0148
ATI_Z_CNTL = 0x053, // 0x014C
ATI_ALPHA_TST_CNTL = 0x054, // 0x0150
ATI_SRC_OFF_PITCH = 0x060, // 0x0180
ATI_SRC_X = 0x061, // 0x0184
ATI_SRC_Y = 0x062, // 0x0188
ATI_SRC_Y_X = 0x063, // 0x018C
ATI_SRC_WIDTH1 = 0x064, // 0x0190
ATI_SRC_HEIGHT1 = 0x065, // 0x0194
ATI_SRC_HEIGHT1_WIDTH1 = 0x066, // 0x0198
ATI_SRC_X_START = 0x067, // 0x019C
ATI_SRC_Y_START = 0x068, // 0x01A0
ATI_SRC_Y_X_START = 0x069, // 0x01A4
ATI_SRC_WIDTH2 = 0x06A, // 0x01A8
ATI_SRC_HEIGHT2 = 0x06B, // 0x01AC
ATI_SRC_HEIGHT2_WIDTH2 = 0x06C, // 0x01B0
ATI_SRC_CNTL = 0x06D, // 0x01B4
ATI_SCALE_OFF = 0x070, // 0x01C0
ATI_SCALE_WIDTH = 0x077, // 0x01DC
ATI_SCALE_HEIGHT = 0x078, // 0x01E0
ATI_SCALE_PITCH = 0x07B, // 0x01EC
ATI_SCALE_X_INC = 0x07C, // 0x01F0
ATI_SCALE_Y_INC = 0x07D, // 0x01F4
ATI_SCALE_VACC = 0x07E, // 0x01F8
ATI_SCALE_3D_CNTL = 0x07F, // 0x01FC
ATI_HOST_CNTL = 0x090, // 0x0240
ATI_PAT_REG0 = 0x0A0, // 0x0280
ATI_PAT_REG1 = 0x0A1, // 0x0284
ATI_PAT_CNTL = 0x0A2, // 0x0288
ATI_SC_LEFT = 0x0A8, // 0x02A0
ATI_SC_RIGHT = 0x0A9, // 0x02A4
ATI_SC_LEFT_RIGHT = 0x0AA, // 0x02A8
ATI_SC_TOP = 0x0AB, // 0x02AC
ATI_SC_BOTTOM = 0x0AC, // 0x02B0
ATI_SC_TOP_BOTTOM = 0x0AD, // 0x02B4
ATI_DP_BKGD_CLR = 0x0B0, // 0x02C0
ATI_DP_FRGD_CLR = 0x0B1, // 0x02C4
ATI_DP_FOG_CLR = 0x0B1, // 0x02C4
ATI_DP_WRITE_MSK = 0x0B2, // 0x02C8
ATI_DP_PIX_WIDTH = 0x0B4, // 0x02D0
ATI_DP_MIX = 0x0B5, // 0x02D4
ATI_DP_SRC = 0x0B6, // 0x02D8
ATI_DP_FRGD_CLR_MIX = 0x0B7, // 0x02DC
ATI_DP_FRGD_BKGD_CLR = 0x0B8, // 0x02E0
ATI_DST_X_Y = 0x0BA, // 0x02E8
ATI_DST_WIDTH_HEIGHT = 0x0BB, // 0x02EC
ATI_USR_DST_PITCH = 0x0BC, // 0x02F0
ATI_DP_SET_GUI_ENGINE2 = 0x0BE, // 0x02F8
ATI_DP_SET_GUI_ENGINE = 0x0BF, // 0x02FC
ATI_CLR_CMP_CLR = 0x0C0, // 0x0300
ATI_CLR_CMP_MSK = 0x0C1, // 0x0304
ATI_CLR_CMP_CNTL = 0x0C2, // 0x0308
ATI_FIFO_STAT = 0x0C4, // 0x0310
ATI_CONTEXT_MASK = 0x0C8, // 0x0320 <-- 264VT specific
ATI_GUI_TRAJ_CNTL = 0x0CC, // 0x0330
ATI_GUI_STAT = 0x0CE, // 0x0338
ATI_MPP_CONFIG = 0x130, // 0x04C0
ATI_MPP_STROBE_SEQ = 0x131, // 0x04C4
ATI_MPP_ADDR = 0x132, // 0x04C8
ATI_MPP_DATA = 0x133, // 0x04CC
ATI_TVO_CNTL = 0x140, // 0x0500
ATI_SETUP_CNTL = 0x1C1, // 0x0704
ATI_DAC_CNTL = 0x00C4,
ATI_GEN_TEST_CNTL = 0x00D0,
ATI_CUSTOM_MACRO_CNTL = 0x00D4,
ATI_CONFIG_CNTL = 0x00DC,
ATI_CONFIG_CHIP_ID = 0x00E0,
ATI_CONFIG_STAT0 = 0x00E4,
ATI_GX_CONFIG_STAT1 = 0x00E8, // GX only
ATI_CRC_SIG = 0x00E8,
ATI_DST_Y_X_ALIAS1 = 0x00F4,
ATI_DST_OFF_PITCH = 0x0100,
ATI_DST_X = 0x0104,
ATI_DST_Y = 0x0108,
ATI_DST_Y_X = 0x010C,
ATI_DST_WIDTH = 0x0110,
ATI_DST_HEIGHT = 0x0114,
ATI_DST_HEIGHT_WIDTH = 0x0118,
ATI_DST_X_WIDTH = 0x011C,
ATI_DST_BRES_LNTH = 0x0120,
ATI_DST_BRES_ERR = 0x0124,
ATI_DST_BRES_INC = 0x0128,
ATI_DST_BRES_DEC = 0x012C,
ATI_DST_CNTL = 0x0130,
ATI_DST_Y_X_ALIAS2 = 0x0134,
ATI_TRAIL_BRES_ERR = 0x0138,
ATI_TRAIL_BRES_INC = 0x013C,
ATI_TRAIL_BRES_DEC = 0x0140,
ATI_DST_BRES_LNTH_ALIAS1 = 0x0144,
ATI_Z_OFF_PITCH = 0x0148,
ATI_Z_CNTL = 0x014C,
ATI_ALPHA_TST_CNTL = 0x0150,
ATI_SRC_OFF_PITCH = 0x0180,
ATI_SRC_X = 0x0184,
ATI_SRC_Y = 0x0188,
ATI_SRC_Y_X = 0x018C,
ATI_SRC_WIDTH1 = 0x0190,
ATI_SRC_HEIGHT1 = 0x0194,
ATI_SRC_HEIGHT1_WIDTH1 = 0x0198,
ATI_SRC_X_START = 0x019C,
ATI_SRC_Y_START = 0x01A0,
ATI_SRC_Y_X_START = 0x01A4,
ATI_SRC_WIDTH2 = 0x01A8,
ATI_SRC_HEIGHT2 = 0x01AC,
ATI_SRC_HEIGHT2_WIDTH2 = 0x01B0,
ATI_SRC_CNTL = 0x01B4,
ATI_SCALE_OFF = 0x01C0,
ATI_SCALE_WIDTH = 0x01DC,
ATI_SCALE_HEIGHT = 0x01E0,
ATI_SCALE_PITCH = 0x01EC,
ATI_SCALE_X_INC = 0x01F0,
ATI_SCALE_Y_INC = 0x01F4,
ATI_SCALE_VACC = 0x01F8,
ATI_SCALE_3D_CNTL = 0x01FC,
ATI_HOST_CNTL = 0x0240,
ATI_PAT_REG0 = 0x0280,
ATI_PAT_REG1 = 0x0284,
ATI_PAT_CNTL = 0x0288,
ATI_SC_LEFT = 0x02A0,
ATI_SC_RIGHT = 0x02A4,
ATI_SC_LEFT_RIGHT = 0x02A8,
ATI_SC_TOP = 0x02AC,
ATI_SC_BOTTOM = 0x02B0,
ATI_SC_TOP_BOTTOM = 0x02B4,
ATI_DP_BKGD_CLR = 0x02C0,
ATI_DP_FOG_CLR = 0x02C0,
ATI_DP_WRITE_MSK = 0x02C8,
ATI_DP_PIX_WIDTH = 0x02D0,
ATI_DP_MIX = 0x02D4,
ATI_DP_SRC = 0x02D8,
ATI_FRGD_CLR_MIX = 0x02DC,
ATI_FRGD_BKGD_CLR = 0x02E0,
ATI_DST_X_Y = 0x02E8,
ATI_DST_WIDTH_HEIGHT = 0x02EC,
ATI_USR_DST_PITCH = 0x02F0,
ATI_DP_SET_GUI_ENGINE2 = 0x02F4,
ATI_DP_SET_GUI_ENGINE = 0x02F8,
ATI_CLR_CMP_CLR = 0x0300,
ATI_CLR_CMP_MSK = 0x0304,
ATI_CLR_CMP_CNTL = 0x0308,
ATI_FIFO_STAT = 0x0310,
ATI_CONTEXT_MASK = 0x0320,
ATI_GUI_TRAJ_CNTL = 0x0330,
ATI_GUI_STAT = 0x0338,
ATI_MPP_CONFIG = 0x04C0,
ATI_MPP_STROBE_SEQ = 0x04C4,
ATI_MPP_ADDR = 0x04C8,
ATI_MPP_DATA = 0x04CC,
ATI_TVO_CNTL = 0x0500,
ATI_SETUP_CNTL = 0x0704,
ATI_INVALID = 0xFFFF
};
constexpr auto APERTURE_SIZE = 0x01000000UL; // Mach64 aperture size
constexpr auto MM_REGS_0_OFF = 0x007FFC00UL; // offset to memory mapped registers, block 0
constexpr auto MM_REGS_1_OFF = 0x007FF800UL; // offset to memory mapped registers, block 1
constexpr auto MM_REGS_2_OFF = 0x003FFC00UL; // offset to memory mapped registers, 4MB aperture
constexpr auto BE_FB_OFFSET = 0x00800000UL; // Offset to the big-endian frame buffer
constexpr auto APERTURE_SIZE = 0x01000000UL; /* Mach64 aperture size */
constexpr auto MM_REGS_0_OFF = 0x007FFC00UL; /* offset to memory mapped registers, block 0 */
constexpr auto MM_REGS_1_OFF = 0x007FF800UL; /* offset to memory mapped registers, block 1 */
constexpr auto MM_REGS_2_OFF = 0x003FFC00UL; /* offset to memory mapped registers, 4MB aperture */
constexpr auto BE_FB_OFFSET = 0x00800000UL; /* Offset to the big-endian frame buffer */
constexpr auto ATI_XTAL = 14318180.0f; // external crystal oscillator frequency
+62 -99
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -21,10 +21,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** ATI Mach64 GX emulation.
It emulates an ATI88800GX controller with an IBM RGB514 style RAMDAC.
Emulation is limited to a basic frame buffer for now.
Emulation is limited to a basic framebuffer for now.
*/
#include <core/bitops.h>
#include <core/timermanager.h>
#include <devices/deviceregistry.h>
#include <devices/video/atimach64defs.h>
@@ -41,12 +40,11 @@ AtiMach64Gx::AtiMach64Gx()
{
supports_types(HWCompType::MMIO_DEV | HWCompType::PCI_DEV);
// set up PCI configuration space header
/* set up PCI configuration space header */
this->vendor_id = PCI_VENDOR_ATI;
this->device_id = ATI_MACH64_GX_DEV_ID;
this->class_rev = (0x030000 << 8) | 3;
this->setup_bars({{0, 0xFF000000UL}}); // declare main aperture (16MB)
this->bars_cfg[0] = 0xFF000000UL; // declare main aperture (16MB)
this->pci_notify_bar_change = [this](int bar_num) {
this->notify_bar_change(bar_num);
@@ -54,8 +52,7 @@ AtiMach64Gx::AtiMach64Gx()
// declare expansion ROM containing FCode and Mac OS drivers
if (this->attach_exp_rom_image(std::string("113-32900-004_Apple_MACH64.bin"))) {
ABORT_F("%s: could not load ROM - this device won't work properly!",
this->name.c_str());
LOG_F(WARNING, "AtiMach64Gx: could not load ROM - this device won't work properly!");
}
// initialize display identification
@@ -64,9 +61,6 @@ AtiMach64Gx::AtiMach64Gx()
// allocate video RAM
this->vram_size = 2 << 20;
this->vram_ptr = std::unique_ptr<uint8_t[]> (new uint8_t[this->vram_size]);
// set up RAMDAC identification
this->regs[ATI_CONFIG_STAT0] = 1 << 9;
}
void AtiMach64Gx::notify_bar_change(int bar_num)
@@ -108,7 +102,7 @@ static const uint32_t io_idx_to_reg_offset[32] = {
ATI_DAC_CNTL, ATI_GEN_TEST_CNTL,
ATI_CONFIG_CNTL, ATI_CONFIG_CHIP_ID,
ATI_CONFIG_STAT0, ATI_GX_CONFIG_STAT1,
ATI_INVALID, ATI_CRTC_H_TOTAL_DISP
ATI_INVALID, ATI_INVALID
};
bool AtiMach64Gx::pci_io_read(uint32_t offset, uint32_t size, uint32_t* res)
@@ -121,13 +115,13 @@ bool AtiMach64Gx::pci_io_read(uint32_t offset, uint32_t size, uint32_t* res)
}
// convert ISA-style I/O address to MMIO register offset
offset = io_idx_to_reg_offset[(offset >> 10) & 0x1F] * 4 + (offset & 3);
offset = io_idx_to_reg_offset[(offset >> 10) & 0x1F] + (offset & 3);
// CONFIG_CNTL is accessible from I/O space only
if ((offset >> 2) == ATI_CONFIG_CNTL) {
if ((offset & ~3) == ATI_CONFIG_CNTL) {
*res = read_mem(((uint8_t *)&this->config_cntl) + (offset & 3), size);
} else {
*res = BYTESWAP_SIZED(this->read_reg(offset, size), size);
*res = this->read_reg(offset, size);
}
return true;
@@ -141,109 +135,75 @@ bool AtiMach64Gx::pci_io_write(uint32_t offset, uint32_t value, uint32_t size)
}
// convert ISA-style I/O address to MMIO register offset
offset = io_idx_to_reg_offset[(offset >> 10) & 0x1F] * 4 + (offset & 3);
offset = io_idx_to_reg_offset[(offset >> 10) & 0x1F] + (offset & 3);
// CONFIG_CNTL is accessible from I/O space only
if ((offset >> 2) == ATI_CONFIG_CNTL) {
if ((offset & ~3) == ATI_CONFIG_CNTL) {
write_mem(((uint8_t *)&this->config_cntl) + (offset & 3), value, size);
switch (this->config_cntl & 3) {
case 0:
LOG_F(WARNING, "%s: linear aperture disabled!", this->name.c_str());
LOG_F(WARNING, "AtiMach64Gx: linear aperture disabled!");
break;
case 1:
LOG_F(INFO, "%s: aperture size set to 4MB", this->name.c_str());
LOG_F(INFO, "AtiMach64Gx: aperture size set to 4MB");
this->mm_regs_offset = MM_REGS_2_OFF;
break;
case 2:
LOG_F(INFO, "%s: aperture size set to 8MB", this->name.c_str());
LOG_F(INFO, "AtiMach64Gx: aperture size set to 8MB");
this->mm_regs_offset = MM_REGS_0_OFF;
break;
default:
LOG_F(ERROR, "%s: invalid aperture size in CONFIG_CNTL", this->name.c_str());
LOG_F(ERROR, "AtiMach64Gx: invalid aperture size in CONFIG_CNTL");
}
} else {
this->write_reg(offset, BYTESWAP_SIZED(value, size), size);
this->write_reg(offset, value, size);
}
return true;
}
uint32_t AtiMach64Gx::read_reg(uint32_t reg_offset, uint32_t size)
uint32_t AtiMach64Gx::read_reg(uint32_t offset, uint32_t size)
{
uint32_t offset = reg_offset & 3;
LOG_F(INFO, "AtiMach64Gx: read from I/O mapped reg at 0x%X", offset);
uint64_t result = this->regs[reg_offset >> 2];
if (!offset && size == 4) { // fast path
return result;
} else { // slow path
if ((offset + size) > 4) {
result |= (uint64_t)(this->regs[(reg_offset >> 2) + 1]) << 32;
}
return extract_bits<uint64_t>(result, offset * 8, size * 8);
}
return read_mem(&this->mm_regs[offset], size);
}
void AtiMach64Gx::write_reg(uint32_t reg_offset, uint32_t value, uint32_t size)
void AtiMach64Gx::write_reg(uint32_t offset, uint32_t value, uint32_t size)
{
uint8_t gpio_dirs, gpio_levels;
int crtc_en;
uint32_t offset = reg_offset & 3;
reg_offset >>= 2;
// write value to internal registers with endian conversion
write_mem(&this->mm_regs[offset], value, size);
if (offset || size != 4) { // slow path
if ((offset + size) > 4) {
ABORT_F("%s: unaligned DWORD writes not implemented", this->name.c_str());
}
uint64_t old_val = this->regs[reg_offset];
insert_bits<uint64_t>(old_val, value, offset * 8, size * 8);
value = old_val;
}
switch (reg_offset) {
case ATI_CRTC_OFF_PITCH:
this->fb_pitch = extract_bits<uint32_t>(value, 22, 10) * 8;
this->fb_ptr = &this->vram_ptr[extract_bits<uint32_t>(value, 0, 20) * 8];
break;
switch (offset & ~3) {
case ATI_CRTC_GEN_CNTL:
if (bit_changed(this->regs[reg_offset], value, 6)) {
if (value & 0x40) {
this->blank_on = true;
this->blank_display();
} else {
this->blank_on = false;
}
}
if (bit_changed(this->regs[reg_offset], value, 25)) {
if (!bit_set(value, 25)) {
crtc_en = (this->mm_regs[ATI_CRTC_GEN_CNTL+3] >> 1) & 1;
if (crtc_en != this->crtc_enable) {
if (!crtc_en) {
this->disable_crtc_internal();
} else {
this->blank_on = false;
}
}
break;
case ATI_DAC_REGS:
if (size == 1) { // only byte accesses are allowed for DAC registers
int dac_reg_addr = ((this->regs[ATI_DAC_CNTL] & 1) << 2) | offset;
rgb514_write_reg(dac_reg_addr, extract_bits<uint32_t>(value, offset * 8, 8));
int dac_reg_addr = ((this->mm_regs[ATI_DAC_CNTL] & 1) << 2) | (offset & 3);
rgb514_write_reg(dac_reg_addr, value);
}
break;
case ATI_DAC_CNTL:
// monitor ID is usually accessed using 8bit writes
if (offset == 3) {
gpio_dirs = extract_bits<uint32_t>(value, 27, 3);
gpio_levels = extract_bits<uint32_t>(value, 24, 3);
if ((offset & 3) == 3) {
gpio_dirs = (value >> 3) & 7;
gpio_levels = value & 7;
gpio_levels = this->disp_id->read_monitor_sense(gpio_levels, gpio_dirs);
insert_bits<uint32_t>(value, gpio_levels, 24, 3);
this->mm_regs[ATI_DAC_CNTL+3] = (this->mm_regs[ATI_DAC_CNTL+3] & 0xF8U) | gpio_levels;
}
break;
case ATI_CONFIG_STAT0:
return; // prevent writes to this read-only register
default:
LOG_F(INFO, "AtiMach64Gx: write 0x%X to I/O mapped reg at 0x%X", value, offset);
}
this->regs[reg_offset] = value;
}
uint32_t AtiMach64Gx::read(uint32_t rgn_start, uint32_t offset, int size)
@@ -252,7 +212,7 @@ uint32_t AtiMach64Gx::read(uint32_t rgn_start, uint32_t offset, int size)
if (offset < this->vram_size) {
return read_mem(&this->vram_ptr[offset], size);
} else if (offset >= this->mm_regs_offset) {
return BYTESWAP_SIZED(read_reg(offset - this->mm_regs_offset, size), size);
return read_reg(offset - this->mm_regs_offset, size);
}
}
@@ -270,31 +230,33 @@ void AtiMach64Gx::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int
if (offset < this->vram_size) {
write_mem(&this->vram_ptr[offset], value, size);
} else if (offset >= this->mm_regs_offset) {
write_reg(offset - this->mm_regs_offset, BYTESWAP_SIZED(value, size), size);
write_reg(offset - this->mm_regs_offset, value, size);
}
}
}
void AtiMach64Gx::enable_crtc_internal()
{
uint32_t new_width, new_height;
int new_width = (this->mm_regs[ATI_CRTC_H_TOTAL_DISP+2] + 1) * 8;
// check for unsupported modes and fail early
if (!bit_set(this->regs[ATI_CRTC_GEN_CNTL], 24))
ABORT_F("%s: VGA not supported", this->name.c_str());
new_width = (extract_bits<uint32_t>(this->regs[ATI_CRTC_H_TOTAL_DISP], 16, 8) + 1) * 8;
new_height = extract_bits<uint32_t>(this->regs[ATI_CRTC_V_TOTAL_DISP], 16, 11) + 1;
int new_height = (READ_WORD_LE_A(&this->mm_regs[ATI_CRTC_V_TOTAL_DISP+2]) & 0x7FFUL) + 1;
if (new_width != this->active_width || new_height != this->active_height) {
this->create_display_window(new_width, new_height);
LOG_F(WARNING, "AtiMach64Gx: display window resizing not implemented yet!");
}
// calculate display refresh rate
this->hori_total = (extract_bits<uint32_t>(this->regs[ATI_CRTC_H_TOTAL_DISP], 0, 9) + 1) * 8;
this->vert_total = extract_bits<uint32_t>(this->regs[ATI_CRTC_V_TOTAL_DISP], 0, 11) + 1;
/* calculate display refresh rate */
int hori_total = (this->mm_regs[ATI_CRTC_H_TOTAL_DISP] + 1) * 8;
this->refresh_rate = this->pixel_clock / this->hori_total / this->vert_total;
int vert_total = (READ_WORD_LE_A(&this->mm_regs[ATI_CRTC_V_TOTAL_DISP]) & 0x7FFUL) + 1;
this->refresh_rate = this->pixel_clock / hori_total / vert_total;
int32_t src_offset = (READ_DWORD_LE_A(&this->mm_regs[ATI_CRTC_OFF_PITCH]) & 0xFFFFFU) * 8;
this->fb_pitch = ((READ_DWORD_LE_A(&this->mm_regs[ATI_CRTC_OFF_PITCH])) >> 19) & 0x1FF8U;
this->fb_ptr = &this->vram_ptr[src_offset];
// specify framebuffer converter
switch (this->pixel_depth) {
@@ -304,21 +266,19 @@ void AtiMach64Gx::enable_crtc_internal()
};
break;
default:
ABORT_F("%s: unsupported pixel depth %d", this->name.c_str(), this->pixel_depth);
}
if (this->refresh_task_id) {
TimerManager::get_instance()->cancel_timer(this->refresh_task_id);
ABORT_F("AtiMach64Gx: unsupported pixel depth %d", this->pixel_depth);
}
uint64_t refresh_interval = static_cast<uint64_t>(1.0f / this->refresh_rate * NS_PER_SEC + 0.5);
this->refresh_task_id = TimerManager::get_instance()->add_cyclic_timer(
TimerManager::get_instance()->add_cyclic_timer(
refresh_interval,
[this]() {
this->update_screen();
}
);
this->update_screen();
this->crtc_on = true;
this->crtc_enable = 1;
@@ -326,8 +286,6 @@ void AtiMach64Gx::enable_crtc_internal()
void AtiMach64Gx::disable_crtc_internal()
{
this->blank_on = true;
this->blank_display();
this->crtc_enable = 0;
}
@@ -341,8 +299,11 @@ void AtiMach64Gx::rgb514_write_reg(uint8_t reg_addr, uint8_t value)
case Rgb514::CLUT_DATA:
this->clut_color[this->comp_index++] = value;
if (this->comp_index >= 3) {
this->set_palette_color(this->clut_index, clut_color[0],
clut_color[1], clut_color[2], 0xFF);
// TODO: combine separate components into a single ARGB value
this->palette[this->clut_index][0] = this->clut_color[0];
this->palette[this->clut_index][1] = this->clut_color[1];
this->palette[this->clut_index][2] = this->clut_color[2];
this->palette[this->clut_index][3] = 255;
this->clut_index++;
this->comp_index = 0;
}
@@ -362,12 +323,14 @@ void AtiMach64Gx::rgb514_write_reg(uint8_t reg_addr, uint8_t value)
this->rgb514_write_ind_reg((this->dac_idx_hi << 8) + this->dac_idx_lo, value);
break;
default:
ABORT_F("RGB514: access to unimplemented register at 0x%X", reg_addr);
LOG_F(WARNING, "RGB514: access to unimplemented register at 0x%X", reg_addr);
}
}
void AtiMach64Gx::rgb514_write_ind_reg(uint8_t reg_addr, uint8_t value)
{
LOG_F(INFO, "RGB514: write 0x%X to register 0x%X", value, reg_addr);
this->dac_regs[reg_addr] = value;
switch (reg_addr) {
+8 -8
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -41,23 +41,23 @@ public:
return std::unique_ptr<AtiMach64Gx>(new AtiMach64Gx());
}
// PCI device methods
/* PCI device methods */
bool supports_io_space(void) {
return true;
};
// I/O space access methods
/* I/O space access methods */
bool pci_io_read(uint32_t offset, uint32_t size, uint32_t* res);
bool pci_io_write(uint32_t offset, uint32_t value, uint32_t size);
// MMIODevice methods
/* MMIODevice methods */
uint32_t read(uint32_t rgn_start, uint32_t offset, int size);
void write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size);
protected:
void notify_bar_change(int bar_num);
uint32_t read_reg(uint32_t reg_offset, uint32_t size);
void write_reg(uint32_t reg_offset, uint32_t value, uint32_t size);
uint32_t read_reg(uint32_t offset, uint32_t size);
void write_reg(uint32_t offset, uint32_t value, uint32_t size);
void enable_crtc_internal();
void disable_crtc_internal();
@@ -65,7 +65,7 @@ protected:
void rgb514_write_ind_reg(uint8_t reg_addr, uint8_t value);
private:
uint32_t regs[256] = {}; // internal registers
uint8_t mm_regs[2048] = { 0 }; // internal registers
int vram_size;
uint32_t aperture_base;
@@ -85,4 +85,4 @@ private:
std::unique_ptr<uint8_t[]> vram_ptr;
};
#endif // ATI_MACH64_GX_H
#endif /* ATI_MACH64_GX_H */
+237 -270
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -19,7 +19,6 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <core/bitops.h>
#include <core/timermanager.h>
#include <devices/common/hwcomponent.h>
#include <devices/common/pci/pcidevice.h>
@@ -90,8 +89,9 @@ static const std::map<uint16_t, std::string> mach64_reg_names = {
{0x0704, "SETUP_CNTL"},
};
ATIRage::ATIRage(uint16_t dev_id)
: PCIDevice("ati-rage"), VideoCtrlBase(640, 480)
: PCIDevice("ati-rage"), VideoCtrlBase(1024, 768)
{
uint8_t asic_id;
@@ -99,11 +99,11 @@ ATIRage::ATIRage(uint16_t dev_id)
this->vram_size = GET_INT_PROP("gfxmem_size") << 20; // convert MBs to bytes
// allocate video RAM
/* allocate video RAM */
this->vram_ptr = std::unique_ptr<uint8_t[]> (new uint8_t[this->vram_size]);
// ATI Rage driver needs to know ASIC ID (manufacturer's internal chip code)
// to operate properly
/* ATI Rage driver needs to know ASIC ID (manufacturer's internal chip code)
to operate properly */
switch (dev_id) {
case ATI_RAGE_GT_DEV_ID:
asic_id = 0x9A; // GT-B2U3 fabricated by UMC
@@ -116,7 +116,7 @@ ATIRage::ATIRage(uint16_t dev_id)
LOG_F(WARNING, "ATI Rage: bogus ASIC ID assigned!");
}
// set up PCI configuration space header
/* set up PCI configuration space header */
this->vendor_id = PCI_VENDOR_ATI;
this->device_id = dev_id;
this->subsys_vndr = PCI_VENDOR_ATI;
@@ -124,26 +124,20 @@ ATIRage::ATIRage(uint16_t dev_id)
this->class_rev = (0x030000 << 8) | asic_id;
this->min_gnt = 8;
this->irq_pin = 1;
this->setup_bars({
{0, 0xFF000000UL}, // declare main aperture (16MB)
{1, 0xFFFFFF01UL}, // declare I/O region (256 bytes)
{2, 0xFFFFF000UL} // declare register aperture (4KB)
});
this->bars_cfg[0] = 0xFF000000UL; // declare main aperture (16MB)
this->bars_cfg[1] = 0xFFFFFF01UL; // declare I/O region (256 bytes)
this->bars_cfg[2] = 0xFFFFF000UL; // declare register aperture (4KB)
this->pci_notify_bar_change = [this](int bar_num) {
this->notify_bar_change(bar_num);
};
// stuff default values into chip registers
this->regs[ATI_CONFIG_CHIP_ID] = (asic_id << 24) | dev_id;
/* stuff default values into chip registers */
WRITE_DWORD_LE_A(&this->mm_regs[ATI_CONFIG_CHIP_ID],
(asic_id << 24) | dev_id);
// initialize display identification
/* initialize display identification */
this->disp_id = std::unique_ptr<DisplayID> (new DisplayID());
uint8_t mon_code = this->disp_id->read_monitor_sense(0, 0);
this->regs[ATI_GP_IO] = ((mon_code & 6) << 11) | ((mon_code & 1) << 8);
}
void ATIRage::notify_bar_change(int bar_num)
@@ -167,35 +161,34 @@ void ATIRage::notify_bar_change(int bar_num)
}
}
uint32_t ATIRage::pci_cfg_read(uint32_t reg_offs, AccessDetails &details)
uint32_t ATIRage::pci_cfg_read(uint32_t reg_offs, uint32_t size)
{
if (reg_offs < 64) {
return PCIDevice::pci_cfg_read(reg_offs, details);
return PCIDevice::pci_cfg_read(reg_offs, size);
}
switch (reg_offs) {
case 0x40:
return this->user_cfg;
default:
LOG_READ_UNIMPLEMENTED_CONFIG_REGISTER();
LOG_F(WARNING, "ATIRage: reading from unimplemented config register at 0x%X", reg_offs);
}
return 0;
}
void ATIRage::pci_cfg_write(uint32_t reg_offs, uint32_t value, AccessDetails &details)
void ATIRage::pci_cfg_write(uint32_t reg_offs, uint32_t value, uint32_t size)
{
if (reg_offs < 64) {
PCIDevice::pci_cfg_write(reg_offs, value, details);
return;
}
switch (reg_offs) {
case 0x40:
this->user_cfg = value;
break;
default:
LOG_WRITE_UNIMPLEMENTED_CONFIG_REGISTER();
PCIDevice::pci_cfg_write(reg_offs, value, size);
} else {
switch (reg_offs) {
case 0x40:
this->user_cfg = value;
break;
default:
LOG_F(WARNING, "ATIRage: writing to unimplemented config register at 0x%X", reg_offs);
}
}
}
@@ -208,183 +201,160 @@ const char* ATIRage::get_reg_name(uint32_t reg_offset) {
}
}
uint32_t ATIRage::read_reg(uint32_t reg_offset, uint32_t size) {
uint64_t result;
uint32_t offset = reg_offset & 3;
uint32_t ATIRage::read_reg(uint32_t offset, uint32_t size) {
uint32_t res;
switch (reg_offset >> 2) {
// perform register-specific pre-read action
switch (offset & ~3) {
case ATI_GP_IO:
break;
case ATI_CLOCK_CNTL:
result = this->regs[ATI_CLOCK_CNTL];
if ((offset + size - 1) >= 2) {
uint8_t pll_addr = (this->regs[ATI_CLOCK_CNTL] >> 10) & 0x3F;
insert_bits<uint64_t>(result, this->plls[pll_addr], 16, 8);
/* reading from internal PLL registers */
if (offset == ATI_CLOCK_CNTL+2 && size == 1 &&
!(this->mm_regs[ATI_CLOCK_CNTL+1] & 0x2)) {
return this->plls[this->mm_regs[ATI_CLOCK_CNTL+1] >> 2];
}
break;
case ATI_DAC_REGS:
result = this->regs[ATI_DAC_REGS];
switch (reg_offset) {
case ATI_DAC_W_INDEX:
insert_bits<uint64_t>(result, this->dac_wr_index, 0, 8);
break;
case ATI_DAC_MASK:
insert_bits<uint64_t>(result, this->dac_mask, 16, 8);
break;
case ATI_DAC_R_INDEX:
insert_bits<uint64_t>(result, this->dac_rd_index, 24, 8);
break;
case ATI_DAC_DATA:
if (!this->comp_index) {
uint8_t alpha; // temp variable for unused alpha
get_palette_colors(this->dac_rd_index, color_buf[0],
color_buf[1], color_buf[2], alpha);
}
insert_bits<uint64_t>(result, color_buf[this->comp_index], 8, 8);
if (++this->comp_index >= 3) {
this->dac_rd_index++; // auto-increment reading index
this->comp_index = 0; // reset color component index
if (offset == ATI_DAC_DATA) {
this->mm_regs[ATI_DAC_DATA] =
this->palette[this->mm_regs[ATI_DAC_R_INDEX]][this->comp_index];
this->comp_index++; /* move to next color component */
if (this->comp_index >= 3) {
/* autoincrement reading index - move to next palette entry */
(this->mm_regs[ATI_DAC_R_INDEX])++;
this->comp_index = 0;
}
}
break;
default:
result = this->regs[reg_offset >> 2];
LOG_F(
INFO,
"ATI Rage: read I/O reg %s at 0x%X, size=%d, val=0x%X",
get_reg_name(offset),
offset,
size,
read_mem(&this->mm_regs[offset], size));
}
if (!offset && size == 4) { // fast path
return result;
} else { // slow path
if ((offset + size) > 4) {
result |= (uint64_t)(this->regs[(reg_offset >> 2) + 1]) << 32;
}
return extract_bits<uint64_t>(result, offset * 8, size * 8);
}
// reading internal registers with necessary endian conversion
res = read_mem(&this->mm_regs[offset], size);
return res;
}
void ATIRage::write_reg(uint32_t reg_offset, uint32_t value, uint32_t size) {
uint32_t offset = reg_offset & 3;
reg_offset >>= 2;
void ATIRage::write_reg(uint32_t offset, uint32_t value, uint32_t size)
{
uint8_t gpio_levels, gpio_dirs;
if (offset || size != 4) { // slow path
if ((offset + size) > 4) {
ABORT_F("%s: unaligned DWORD writes not implemented", this->name.c_str());
}
uint64_t old_val = this->regs[reg_offset];
insert_bits<uint64_t>(old_val, value, offset * 8, size * 8);
value = old_val;
}
// writing internal registers with necessary endian conversion
write_mem(&this->mm_regs[offset], value, size);
switch (reg_offset) {
case ATI_CRTC_H_TOTAL_DISP:
LOG_F(9, "%s: ATI_CRTC_H_TOTAL_DISP set to 0x%08X", this->name.c_str(), value);
break;
// perform register-specific post-write action
switch (offset & ~3) {
case ATI_CRTC_OFF_PITCH:
this->regs[reg_offset] = value;
this->fb_pitch = extract_bits<uint32_t>(value, 22, 10) * 8;
this->fb_ptr = &this->vram_ptr[extract_bits<uint32_t>(value, 0, 20) * 8];
if (bit_set(this->regs[ATI_CRTC_GEN_CNTL], 25) &&
!bit_set(this->regs[ATI_CRTC_GEN_CNTL], 6)) {
this->crtc_update();
}
LOG_F(INFO, "ATI Rage: CRTC_OFF_PITCH=0x%08X", READ_DWORD_LE_A(&this->mm_regs[ATI_CRTC_OFF_PITCH]));
break;
case ATI_CRTC_GEN_CNTL:
if (bit_changed(this->regs[reg_offset], value, 6)) {
if (value & 0x40) {
this->regs[reg_offset] |= (1 << 6);
this->blank_on = true;
this->blank_display();
} else {
this->regs[reg_offset] &= ~(1 << 6);
this->blank_on = false;
}
}
if (bit_changed(this->regs[reg_offset], value, 25)) {
this->regs[reg_offset] = value;
if (bit_set(this->regs[reg_offset], 25) &&
!bit_set(this->regs[reg_offset], 6)) {
this->crtc_update();
}
return;
if (this->mm_regs[ATI_CRTC_GEN_CNTL+3] & 2) {
this->crtc_enable();
} else {
this->crtc_on = false;
}
LOG_F(INFO, "ATI Rage: CRTC_GEN_CNTL:CRTC_ENABLE=%d", !!(this->mm_regs[ATI_CRTC_GEN_CNTL+3] & 2));
LOG_F(INFO, "ATI Rage: CRTC_GEN_CNTL:CRTC_DISPLAY_DIS=%d", !!(this->mm_regs[ATI_CRTC_GEN_CNTL] & 0x40));
break;
case ATI_CUR_OFFSET:
LOG_F(INFO, "ATI Rage: CUR_OFFSET=0x%08X", READ_DWORD_LE_A(&this->mm_regs[ATI_CUR_OFFSET]));
break;
case ATI_CUR_HORZ_VERT_POSN:
LOG_F(INFO, "ATI Rage: CUR_HORZ_VERT_POSN=0x%08X", READ_DWORD_LE_A(&this->mm_regs[ATI_CUR_HORZ_VERT_POSN]));
break;
case ATI_CUR_HORZ_VERT_OFF:
LOG_F(INFO, "ATI Rage: CUR_HORZ_VERT_OFF=0x%08X", READ_DWORD_LE_A(&this->mm_regs[ATI_CUR_HORZ_VERT_OFF]));
break;
case ATI_GP_IO:
this->regs[reg_offset] = value;
if (offset < 2 && (offset + size - 1) >= 1) {
uint8_t gpio_levels = (this->regs[ATI_GP_IO] >> 8) & 0xFFU;
if (offset < (ATI_GP_IO + 2)) {
gpio_levels = this->mm_regs[ATI_GP_IO+1];
gpio_levels = ((gpio_levels & 0x30) >> 3) | (gpio_levels & 1);
uint8_t gpio_dirs = (this->regs[ATI_GP_IO] >> 24) & 0xFFU;
gpio_dirs = ((gpio_dirs & 0x30) >> 3) | (gpio_dirs & 1);
gpio_dirs = this->mm_regs[ATI_GP_IO+3];
gpio_dirs = ((gpio_dirs & 0x30) >> 3) | (gpio_dirs & 1);
gpio_levels = this->disp_id->read_monitor_sense(gpio_levels, gpio_dirs);
insert_bits<uint32_t>(this->regs[ATI_GP_IO],
((gpio_levels & 6) << 3) | (gpio_levels & 1), 8, 8);
this->mm_regs[ATI_GP_IO+1] = ((gpio_levels & 6) << 3) | (gpio_levels & 1);
}
return;
break;
case ATI_CLOCK_CNTL:
this->regs[reg_offset] = value;
if ((offset + size - 1) >= 2 && bit_set(this->regs[ATI_CLOCK_CNTL], 9)) {
uint8_t pll_addr = (this->regs[ATI_CLOCK_CNTL] >> 10) & 0x3F;
uint8_t pll_data = (value >> 16) & 0xFF;
/* writing to internal PLL registers */
if (offset == ATI_CLOCK_CNTL+2 && size == 1 &&
(this->mm_regs[ATI_CLOCK_CNTL+1] & 0x2)) {
int pll_addr = this->mm_regs[ATI_CLOCK_CNTL+1] >> 2;
uint8_t pll_data = this->mm_regs[ATI_CLOCK_CNTL+2];
this->plls[pll_addr] = pll_data;
LOG_F(9, "%s: PLL #%d set to 0x%02X", this->name.c_str(), pll_addr, pll_data);
LOG_F(INFO, "ATI Rage: PLL #%d set to 0x%02X", pll_addr, pll_data);
} else if (offset == ATI_CLOCK_CNTL && size == 1) {
LOG_F(INFO, "ATI Rage: CLOCK_SEL = 0x%02X",
this->mm_regs[ATI_CLOCK_CNTL] & 3);
}
return;
break;
case ATI_DAC_REGS:
switch (reg_offset * 4 + offset) {
switch (offset) {
/* writing to read/write index registers resets color component index */
case ATI_DAC_W_INDEX:
this->dac_wr_index = value & 0xFFU;
this->comp_index = 0;
break;
case ATI_DAC_MASK:
this->dac_mask = (value >> 16) & 0xFFU;
break;
case ATI_DAC_R_INDEX:
this->dac_rd_index = (value >> 24) & 0xFFU;
this->comp_index = 0;
break;
case ATI_DAC_DATA:
this->color_buf[this->comp_index] = (value >> 8) & this->dac_mask;
if (++this->comp_index >= 3) {
this->set_palette_color(this->dac_wr_index, color_buf[0],
color_buf[1], color_buf[2], 0xFF);
this->dac_wr_index++; // auto-increment color index
this->comp_index = 0; // reset color component index
this->palette[this->mm_regs[ATI_DAC_W_INDEX]][this->comp_index] = value & 0xFF;
this->comp_index++; /* move to next color component */
if (this->comp_index >= 3) {
LOG_F(
INFO,
"ATI DAC palette entry #%d set to R=%X, G=%X, B=%X",
this->mm_regs[ATI_DAC_W_INDEX],
this->palette[this->mm_regs[ATI_DAC_W_INDEX]][0],
this->palette[this->mm_regs[ATI_DAC_W_INDEX]][1],
this->palette[this->mm_regs[ATI_DAC_W_INDEX]][2]);
/* autoincrement writing index - move to next palette entry */
(this->mm_regs[ATI_DAC_W_INDEX])++;
this->comp_index = 0;
}
}
return;
case ATI_GEN_TEST_CNTL:
if (bit_changed(this->regs[reg_offset], value, 7)) {
if (bit_set(value, 7))
this->setup_hw_cursor();
else
this->cursor_on = false;
}
if (bit_changed(this->regs[reg_offset], value, 8)) {
if (!bit_set(value, 8))
LOG_F(9, "%s: reset GUI engine", this->name.c_str());
}
if (bit_changed(this->regs[reg_offset], value, 9)) {
if (bit_set(value, 9))
LOG_F(9, "%s: reset memory controller", this->name.c_str());
}
if (value & 0xFFFFFC00) {
LOG_F(WARNING, "%s: unhandled GEN_TEST_CNTL state=0x%X",
this->name.c_str(), value);
}
break;
case ATI_CONFIG_CHIP_ID:
return; // prevent writes to this read-only register
case ATI_GEN_TEST_CNTL:
LOG_F(INFO, "HW cursor: %s", this->mm_regs[ATI_GEN_TEST_CNTL] & 0x80 ? "on" : "off");
break;
default:
LOG_F(
INFO,
"ATI Rage: %s register at 0x%X set to 0x%X",
get_reg_name(offset),
offset & ~3,
READ_DWORD_LE_A(&this->mm_regs[offset & ~3]));
}
this->regs[reg_offset] = value;
//if ((this->mm_regs[ATI_CRTC_GEN_CNTL+3] & 2) &&
// !(this->mm_regs[ATI_CRTC_GEN_CNTL] & 0x40)) {
// int32_t src_offset = (READ_DWORD_LE_A(&this->mm_regs[ATI_CRTC_OFF_PITCH]) & 0xFFFF) * 8;
// this->fb_pitch = ((READ_DWORD_LE_A(&this->mm_regs[ATI_CRTC_OFF_PITCH])) >> 19) & 0x1FF8;
// this->fb_ptr = &this->vram_ptr[src_offset];
// this->update_screen();
//}
}
bool ATIRage::io_access_allowed(uint32_t offset) {
if (offset >= this->io_base && offset < (this->io_base + 0x100)) {
if (this->command & 1) {
return true;
}
if (!(this->command & 1)) {
LOG_F(WARNING, "ATI I/O space disabled in the command reg");
return false;
}
return false;
if (offset < this->io_base || offset > (this->io_base + 0x100)) {
LOG_F(WARNING, "Rage: I/O out of range, base=0x%X, offset=0x%X", io_base, offset);
return false;
}
return true;
}
@@ -393,7 +363,7 @@ bool ATIRage::pci_io_read(uint32_t offset, uint32_t size, uint32_t* res) {
return false;
}
*res = BYTESWAP_SIZED(this->read_reg(offset - this->io_base, size), size);
*res = this->read_reg(offset - this->io_base, size);
return true;
}
@@ -403,24 +373,35 @@ bool ATIRage::pci_io_write(uint32_t offset, uint32_t value, uint32_t size) {
return false;
}
this->write_reg(offset - this->io_base, BYTESWAP_SIZED(value, size), size);
this->write_reg(offset - this->io_base, value, size);
return true;
}
uint32_t ATIRage::read(uint32_t rgn_start, uint32_t offset, int size)
{
if (offset < this->vram_size) { // little-endian VRAM region
LOG_F(8, "Reading ATI Rage PCI memory: region=%X, offset=%X, size %d", rgn_start, offset, size);
if (rgn_start < this->aperture_base || offset > APERTURE_SIZE) {
LOG_F(WARNING, "ATI Rage: attempt to read outside the aperture!");
return 0;
}
if (offset < this->vram_size) {
/* read from little-endian VRAM region */
return read_mem(&this->vram_ptr[offset], size);
}
else if (offset >= BE_FB_OFFSET) { // big-endian VRAM region
return read_mem(&this->vram_ptr[offset - BE_FB_OFFSET], size);
else if (offset >= BE_FB_OFFSET) {
/* read from big-endian VRAM region */
return read_mem_rev(&this->vram_ptr[offset - BE_FB_OFFSET], size);
}
else if (offset >= MM_REGS_0_OFF) { // memory-mapped registers, block 0
return BYTESWAP_SIZED(this->read_reg(offset & 0x3FF, size), size);
else if (offset >= MM_REGS_0_OFF) {
/* read from memory-mapped registers, block 0 */
return this->read_reg(offset - MM_REGS_0_OFF, size);
}
else if (offset >= MM_REGS_1_OFF) { // memory-mapped registers, block 1
return BYTESWAP_SIZED(this->read_reg((offset & 0x3FF) + 0x400, size), size);
else if (offset >= MM_REGS_1_OFF) {
/* read from memory-mapped registers, block 1 */
return this->read_reg(offset - MM_REGS_1_OFF + 0x400, size);
}
else {
LOG_F(WARNING, "ATI Rage: read attempt from unmapped aperture region at 0x%08X", offset);
@@ -431,17 +412,28 @@ uint32_t ATIRage::read(uint32_t rgn_start, uint32_t offset, int size)
void ATIRage::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size)
{
if (offset < this->vram_size) { // little-endian VRAM region
LOG_F(8, "Writing reg=%X, offset=%X, value=%X, size %d", rgn_start, offset, value, size);
if (rgn_start < this->aperture_base || offset > APERTURE_SIZE) {
LOG_F(WARNING, "ATI Rage: attempt to write outside the aperture!");
return;
}
if (offset < this->vram_size) {
/* write to little-endian VRAM region */
write_mem(&this->vram_ptr[offset], value, size);
}
else if (offset >= BE_FB_OFFSET) { // big-endian VRAM region
write_mem(&this->vram_ptr[offset & (BE_FB_OFFSET - 1)], value, size);
else if (offset >= BE_FB_OFFSET) {
/* write to big-endian VRAM region */
write_mem_rev(&this->vram_ptr[offset - BE_FB_OFFSET], value, size);
}
else if (offset >= MM_REGS_0_OFF) { // memory-mapped registers, block 0
this->write_reg(offset & 0x3FF, BYTESWAP_SIZED(value, size), size);
else if (offset >= MM_REGS_0_OFF) {
/* write to memory-mapped registers, block 0 */
this->write_reg(offset - MM_REGS_0_OFF, value, size);
}
else if (offset >= MM_REGS_1_OFF) { // memory-mapped registers, block 1
this->write_reg((offset & 0x3FF) + 0x400, BYTESWAP_SIZED(value, size), size);
else if (offset >= MM_REGS_1_OFF) {
/* write to memory-mapped registers, block 1 */
this->write_reg(offset - MM_REGS_1_OFF + 0x400, value, size);
}
else {
LOG_F(WARNING, "ATI Rage: write attempt to unmapped aperture region at 0x%08X", offset);
@@ -458,17 +450,15 @@ void ATIRage::verbose_pixel_format(int crtc_index) {
return;
}
uint32_t fmt = extract_bits<uint32_t>(this->regs[ATI_CRTC_GEN_CNTL], 8, 3);
const char* what = "Pixel format:";
switch (fmt) {
switch (this->mm_regs[ATI_CRTC_GEN_CNTL+1] & 7) {
case 1:
LOG_F(INFO, "%s 4 bpp with DAC palette", what);
break;
case 2:
// check the undocumented DAC_DIRECT bit
if (bit_set(this->regs[ATI_DAC_CNTL], 10)) {
if (this->mm_regs[ATI_DAC_CNTL+1] & 4) {
LOG_F(INFO, "%s 8 bpp direct color (RGB322)", what);
} else {
LOG_F(INFO, "%s 8 bpp with DAC palette", what);
@@ -487,112 +477,95 @@ void ATIRage::verbose_pixel_format(int crtc_index) {
LOG_F(INFO, "%s 32 bpp direct color (ARGB8888)", what);
break;
default:
LOG_F(ERROR, "%s: CRTC pixel format %d not supported", this->name.c_str(), fmt);
LOG_F(ERROR, "ATI Rage: CRTC pixel format %d not supported",
this->mm_regs[ATI_CRTC_GEN_CNTL+2] & 7);
}
}
void ATIRage::crtc_update() {
uint32_t new_width, new_height, new_htotal, new_vtotal;
void ATIRage::crtc_enable() {
/* active (visible) width is specified in characters (8 px) - 1 */
this->active_width = (this->mm_regs[ATI_CRTC_H_TOTAL_DISP+2] + 1) * 8;
// check for unsupported modes and fail early
if (!bit_set(this->regs[ATI_CRTC_GEN_CNTL], 24))
ABORT_F("%s: VGA not supported", this->name.c_str());
/* active (visible) height is specified in lines - 1 */
this->active_height =
(READ_WORD_LE_A(&this->mm_regs[ATI_CRTC_V_TOTAL_DISP+2]) & 0x7FFUL) + 1;
if ((this->plls[PLL_VCLK_CNTL] & 3) != 3)
ABORT_F("%s: VLCK source != VPLL", this->name.c_str());
if ((this->plls[PLL_VCLK_CNTL] & 3) == 3) {
/* look up which VPLL ouput is requested */
int clock_sel = this->mm_regs[ATI_CLOCK_CNTL] & 3;
bool need_recalc = false;
/* calculate VPLL output frequency */
float vpll_freq = calc_pll_freq(2, this->plls[VCLK0_FB_DIV + clock_sel]);
new_width = (extract_bits<uint32_t>(this->regs[ATI_CRTC_H_TOTAL_DISP], 16, 8) + 1) * 8;
new_height = extract_bits<uint32_t>(this->regs[ATI_CRTC_V_TOTAL_DISP], 16, 11) + 1;
/* calculate post divider's index */
/* NOTE: post divider's index has been extended by an additional
bit in Rage Pro. This bit is resided in PLL_EXT_CNTL register.
*/
int post_div_idx = ((this->plls[PLL_EXT_CNTL] >> (clock_sel + 2)) & 4) |
((this->plls[VCLK_POST_DIV] >> (clock_sel * 2)) & 3);
if (new_width != this->active_width || new_height != this->active_height) {
this->create_display_window(new_width, new_height);
need_recalc = true;
}
/* pixel clock = source_freq / post_div */
this->pixel_clock = vpll_freq / mach64_post_div[post_div_idx];
new_htotal = (extract_bits<uint32_t>(this->regs[ATI_CRTC_H_TOTAL_DISP], 0, 9) + 1) * 8;
new_vtotal = extract_bits<uint32_t>(this->regs[ATI_CRTC_V_TOTAL_DISP], 0, 11) + 1;
/* calculate display refresh rate */
int hori_total =
((READ_WORD_LE_A(&this->mm_regs[ATI_CRTC_H_TOTAL_DISP])
& 0x1FFUL) + 1) * 8;
if (new_htotal != this->hori_total || new_vtotal != this->vert_total) {
this->hori_total = new_htotal;
this->vert_total = new_vtotal;
need_recalc = true;
}
int vert_total =
(READ_WORD_LE_A(&this->mm_regs[ATI_CRTC_V_TOTAL_DISP]) & 0x7FFUL) + 1;
if (!need_recalc)
return;
this->refresh_rate = pixel_clock / hori_total / vert_total;
// look up which VPLL ouput is requested
int clock_sel = this->regs[ATI_CLOCK_CNTL] & 3;
int32_t src_offset = (READ_DWORD_LE_A(&this->mm_regs[ATI_CRTC_OFF_PITCH]) & 0xFFFF) * 8;
// calculate VPLL output frequency
float vpll_freq = calc_pll_freq(2, this->plls[VCLK0_FB_DIV + clock_sel]);
this->fb_pitch = ((READ_DWORD_LE_A(&this->mm_regs[ATI_CRTC_OFF_PITCH])) >> 19) & 0x1FF8;
// calculate post divider's index
// NOTE: post divider's index has been extended by an additional
// bit in Rage Pro. This bit is resided in PLL_EXT_CNTL register.
int post_div_idx = ((this->plls[PLL_EXT_CNTL] >> (clock_sel + 2)) & 4) |
((this->plls[VCLK_POST_DIV] >> (clock_sel * 2)) & 3);
this->fb_ptr = &this->vram_ptr[src_offset];
// pixel clock = source_freq / post_div
this->pixel_clock = vpll_freq / mach64_post_div[post_div_idx];
// calculate display refresh rate
this->refresh_rate = pixel_clock / this->hori_total / this->vert_total;
// set up frame buffer converter
int pix_fmt = extract_bits<uint32_t>(this->regs[ATI_CRTC_GEN_CNTL], 8, 3);
switch (pix_fmt) {
case 2:
if (bit_set(this->regs[ATI_DAC_CNTL], 10)) {
ABORT_F("%s: DAC_DIRECT set!", this->name.c_str());
}
// specify framebuffer converter (hardcoded for now)
this->convert_fb_cb = [this](uint8_t *dst_buf, int dst_pitch) {
this->convert_frame_8bpp(dst_buf, dst_pitch);
};
break;
default:
ABORT_F("%s: unsupported pixel format %d", this->name.c_str(), pix_fmt);
LOG_F(INFO, "ATI Rage: primary CRT controller enabled:");
LOG_F(INFO, "Video mode: %s",
(this->mm_regs[ATI_CRTC_GEN_CNTL+3] & 1) ? "extended" : "VGA");
LOG_F(INFO, "Video width: %d px", this->active_width);
LOG_F(INFO, "Video height: %d px", this->active_height);
verbose_pixel_format(0);
LOG_F(INFO, "VPLL frequency: %f MHz", vpll_freq * 1e-6);
LOG_F(INFO, "Pixel (dot) clock: %f MHz", this->pixel_clock * 1e-6);
LOG_F(INFO, "Refresh rate: %f Hz", this->refresh_rate);
uint64_t refresh_interval = static_cast<uint64_t>(1.0f / this->refresh_rate * NS_PER_SEC + 0.5);
TimerManager::get_instance()->add_cyclic_timer(
refresh_interval,
[this]() {
this->update_screen();
}
);
this->update_screen();
} else {
LOG_F(WARNING, "ATI Rage: VLCK source != VPLL!");
}
LOG_F(INFO, "%s: primary CRT controller enabled:", this->name.c_str());
LOG_F(INFO, "Video mode: %s",
bit_set(this->regs[ATI_CRTC_GEN_CNTL], 24) ? "extended" : "VGA");
LOG_F(INFO, "Video width: %d px", this->active_width);
LOG_F(INFO, "Video height: %d px", this->active_height);
verbose_pixel_format(0);
LOG_F(INFO, "VPLL frequency: %f MHz", vpll_freq * 1e-6);
LOG_F(INFO, "Pixel (dot) clock: %f MHz", this->pixel_clock * 1e-6);
LOG_F(INFO, "Refresh rate: %f Hz", this->refresh_rate);
if (this->refresh_task_id) {
TimerManager::get_instance()->cancel_timer(this->refresh_task_id);
}
uint64_t refresh_interval = static_cast<uint64_t>(1.0f / this->refresh_rate * NS_PER_SEC + 0.5);
this->refresh_task_id = TimerManager::get_instance()->add_cyclic_timer(
refresh_interval,
[this]() {
this->update_screen();
}
);
this->crtc_on = true;
}
void ATIRage::draw_hw_cursor(uint8_t *dst_buf, int dst_pitch) {
uint8_t *src_buf, *src_row, *dst_row, px4;
int vert_offset = extract_bits<uint32_t>(this->regs[ATI_CUR_HORZ_VERT_OFF], 16, 5);
int horz_offset = READ_DWORD_LE_A(&this->mm_regs[ATI_CUR_HORZ_VERT_OFF]) & 0x3F;
int vert_offset = (READ_DWORD_LE_A(&this->mm_regs[ATI_CUR_HORZ_VERT_OFF]) >> 16) & 0x3F;
src_buf = &this->vram_ptr[this->regs[ATI_CUR_OFFSET] * 8];
src_buf = &this->vram_ptr[(READ_DWORD_LE_A(&this->mm_regs[ATI_CUR_OFFSET]) * 8)];
int cur_height = 64 - vert_offset;
uint32_t color0 = this->regs[ATI_CUR_CLR0] | 0x000000FFUL;
uint32_t color1 = this->regs[ATI_CUR_CLR1] | 0x000000FFUL;
uint32_t color0 = READ_DWORD_LE_A(&this->mm_regs[ATI_CUR_CLR0]) | 0x000000FFUL;
uint32_t color1 = READ_DWORD_LE_A(&this->mm_regs[ATI_CUR_CLR1]) | 0x000000FFUL;
for (int h = 0; h < cur_height; h++) {
dst_row = &dst_buf[h * dst_pitch];
@@ -610,7 +583,6 @@ void ATIRage::draw_hw_cursor(uint8_t *dst_buf, int dst_pitch) {
WRITE_DWORD_BE_A(dst_row, color1);
break;
case 2: // transparent
WRITE_DWORD_BE_A(dst_row, 0);
break;
case 3: // 1's complement of display pixel
break;
@@ -620,11 +592,6 @@ void ATIRage::draw_hw_cursor(uint8_t *dst_buf, int dst_pitch) {
}
}
void ATIRage::get_cursor_position(int& x, int& y) {
x = this->regs[ATI_CUR_HORZ_VERT_POSN] & 0xFFFFU;
y = (this->regs[ATI_CUR_HORZ_VERT_POSN] >> 16) & 0xFFFFU;
}
static const PropMap AtiRage_Properties = {
{"gfxmem_size",
new IntProperty( 2, vector<uint32_t>({2, 4, 6}))},
+18 -20
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-22 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -55,15 +55,19 @@ public:
return std::unique_ptr<ATIRage>(new ATIRage(ATI_RAGE_PRO_DEV_ID));
}
// MMIODevice methods
/* MMIODevice methods */
uint32_t read(uint32_t rgn_start, uint32_t offset, int size);
void write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size);
// PCI device methods
uint32_t pci_cfg_read(uint32_t reg_offs, AccessDetails &details);
void pci_cfg_write(uint32_t reg_offs, uint32_t value, AccessDetails &details);
/* PCI device methods */
bool supports_io_space(void) {
return true;
};
// I/O space access methods
uint32_t pci_cfg_read(uint32_t reg_offs, uint32_t size);
void pci_cfg_write(uint32_t reg_offs, uint32_t value, uint32_t size);
/* I/O space access methods */
bool pci_io_read(uint32_t offset, uint32_t size, uint32_t* res);
bool pci_io_write(uint32_t offset, uint32_t value, uint32_t size);
@@ -71,20 +75,19 @@ protected:
void notify_bar_change(int bar_num);
const char* get_reg_name(uint32_t reg_offset);
bool io_access_allowed(uint32_t offset);
uint32_t read_reg(uint32_t reg_offset, uint32_t size);
void write_reg(uint32_t reg_addr, uint32_t value, uint32_t size);
uint32_t read_reg(uint32_t offset, uint32_t size);
void write_reg(uint32_t offset, uint32_t value, uint32_t size);
float calc_pll_freq(int scale, int fb_div);
void verbose_pixel_format(int crtc_index);
void crtc_update();
void crtc_enable();
void draw_hw_cursor(uint8_t *dst_buf, int dst_pitch);
void get_cursor_position(int& x, int& y);
private:
uint32_t regs[512] = {}; // internal registers
uint8_t plls[64] = {}; // internal PLL registers
uint8_t mm_regs[2048] = {0}; // internal registers
// Video RAM variables
uint8_t plls[64] = {0}; // internal PLL registers
/* Video RAM variables */
std::unique_ptr<uint8_t[]> vram_ptr;
uint32_t vram_size;
@@ -94,12 +97,7 @@ private:
std::unique_ptr<DisplayID> disp_id;
// DAC interface state
uint8_t dac_wr_index = 0; // current DAC color index for writing
uint8_t dac_rd_index = 0; // current DAC color index for reading
uint8_t dac_mask = 0; // current DAC mask
int comp_index = 0; // current color component index
uint8_t color_buf[3] = {}; // buffer for storing DAC color components
int comp_index; /* color component index for DAC palette access */
};
#endif // ATI_RAGE_H
#endif /* ATI_RAGE_H */
+82 -97
View File
@@ -59,12 +59,8 @@ ControlVideo::ControlVideo()
this->vendor_id = PCI_VENDOR_APPLE;
this->device_id = 3;
this->class_rev = 0;
this->setup_bars({
{0, 0xFFFFFFFFUL}, // I/O region (4 bytes but it's weird because bit 1 is set)
{1, 0xFFFFF000UL}, // base address for the HW registers (4KB)
{2, 0xFC000000UL} // base address for the VRAM (64MB)
});
this->bars_cfg[1] = 0xFFFFF000UL; // base address for the HW registers (4KB)
this->bars_cfg[2] = 0xFC000000UL; // base address for the VRAM (64MB)
this->pci_notify_bar_change = [this](int bar_num) {
this->notify_bar_change(bar_num);
@@ -88,10 +84,6 @@ ControlVideo::ControlVideo()
void ControlVideo::notify_bar_change(int bar_num)
{
switch (bar_num) {
case 0:
this->io_base = this->bars[bar_num] & ~3;
LOG_F(INFO, "Control: I/O space address set to 0x%08X", this->io_base);
break;
case 1:
if (this->regs_base != (this->bars[bar_num] & 0xFFFFFFF0UL)) {
this->regs_base = this->bars[bar_num] & 0xFFFFFFF0UL;
@@ -124,22 +116,18 @@ uint32_t ControlVideo::read(uint32_t rgn_start, uint32_t offset, int size)
}
}
if (rgn_start == this->regs_base) {
switch (offset >> 4) {
case ControlRegs::TEST:
result = this->test;
break;
case ControlRegs::MON_SENSE:
result = this->cur_mon_id << 6;
break;
default:
LOG_F(INFO, "read from 0x%08X:0x%08X", rgn_start, offset);
}
return BYTESWAP_32(result);
switch (offset >> 4) {
case ControlRegs::TEST:
result = this->test;
break;
case ControlRegs::MON_SENSE:
result = this->cur_mon_id << 6;
break;
default:
LOG_F(INFO, "read from 0x%08X:0x%08X", rgn_start, offset);
}
return 0;
return BYTESWAP_32(result);
}
void ControlVideo::write(uint32_t rgn_start, uint32_t offset, uint32_t value, int size)
@@ -153,77 +141,75 @@ void ControlVideo::write(uint32_t rgn_start, uint32_t offset, uint32_t value, in
return;
}
if (rgn_start == this->regs_base) {
value = BYTESWAP_32(value);
value = BYTESWAP_32(value);
switch (offset >> 4) {
case ControlRegs::VFPEQ:
case ControlRegs::VFP:
case ControlRegs::VAL:
case ControlRegs::VBP:
case ControlRegs::VBPEQ:
case ControlRegs::VSYNC:
case ControlRegs::VHLINE:
case ControlRegs::PIPED:
case ControlRegs::HPIX:
case ControlRegs::HFP:
case ControlRegs::HAL:
case ControlRegs::HBWAY:
case ControlRegs::HSP:
case ControlRegs::HEQ:
case ControlRegs::HLFLN:
case ControlRegs::HSERR:
this->swatch_params[(offset >> 4) - 1] = value;
break;
case ControlRegs::TEST:
if (this->test != value) {
if ((this->test & ~TEST_STROBE) != (value & ~TEST_STROBE)) {
this->test = value;
this->test_shift = 0;
LOG_F(9, "New TEST value: 0x%08X", this->test);
} else {
LOG_F(9, "TEST strobe bit flipped, new value: 0x%08X", value);
this->test = value;
if (++this->test_shift >= 3) {
LOG_F(9, "Received TEST reg value: 0x%08X", this->test & ~TEST_STROBE);
if ((this->test ^ this->prev_test) & 0x400) {
if (this->test & 0x400) {
this->disable_display();
} else {
this->enable_display();
}
this->prev_test = this->test;
switch (offset >> 4) {
case ControlRegs::VFPEQ:
case ControlRegs::VFP:
case ControlRegs::VAL:
case ControlRegs::VBP:
case ControlRegs::VBPEQ:
case ControlRegs::VSYNC:
case ControlRegs::VHLINE:
case ControlRegs::PIPED:
case ControlRegs::HPIX:
case ControlRegs::HFP:
case ControlRegs::HAL:
case ControlRegs::HBWAY:
case ControlRegs::HSP:
case ControlRegs::HEQ:
case ControlRegs::HLFLN:
case ControlRegs::HSERR:
this->swatch_params[(offset >> 4) - 1] = value;
break;
case ControlRegs::TEST:
if (this->test != value) {
if ((this->test & ~TEST_STROBE) != (value & ~TEST_STROBE)) {
this->test = value;
this->test_shift = 0;
LOG_F(9, "New TEST value: 0x%08X", this->test);
} else {
LOG_F(9, "TEST strobe bit flipped, new value: 0x%08X", value);
this->test = value;
if (++this->test_shift >= 3) {
LOG_F(9, "Received TEST reg value: 0x%08X", this->test & ~TEST_STROBE);
if ((this->test ^ this->prev_test) & 0x400) {
if (this->test & 0x400) {
this->disable_display();
} else {
this->enable_display();
}
this->prev_test = this->test;
}
}
}
break;
case ControlRegs::GBASE:
this->fb_base = value;
break;
case ControlRegs::ROW_WORDS:
this->row_words = value;
break;
case ControlRegs::MON_SENSE:
LOG_F(9, "Control: monitor sense written with 0x%X", value);
value = (value >> 3) & 7;
this->cur_mon_id = this->display_id->read_monitor_sense(value & 7, value ^ 7);
break;
case ControlRegs::ENABLE:
this->flags = value;
break;
case ControlRegs::GSC_DIVIDE:
this->clock_divider = value;
break;
case ControlRegs::REFRESH_COUNT:
LOG_F(INFO, "Control: refresh count set to 0x%08X", value);
break;
case ControlRegs::INT_ENABLE:
this->int_enable = value;
break;
default:
LOG_F(INFO, "write 0x%08X to 0x%08X:0x%08X", value, rgn_start, offset);
}
break;
case ControlRegs::GBASE:
this->fb_base = value;
break;
case ControlRegs::ROW_WORDS:
this->row_words = value;
break;
case ControlRegs::MON_SENSE:
LOG_F(9, "Control: monitor sense written with 0x%X", value);
value = (value >> 3) & 7;
this->cur_mon_id = this->display_id->read_monitor_sense(value & 7, value ^ 7);
break;
case ControlRegs::ENABLE:
this->flags = value;
break;
case ControlRegs::GSC_DIVIDE:
this->clock_divider = value;
break;
case ControlRegs::REFRESH_COUNT:
LOG_F(INFO, "Control: refresh count set to 0x%08X", value);
break;
case ControlRegs::INT_ENABLE:
this->int_enable = value;
break;
default:
LOG_F(INFO, "write 0x%08X to 0x%08X:0x%08X", value, rgn_start, offset);
}
}
@@ -293,20 +279,16 @@ void ControlVideo::enable_display()
/ (new_height + vert_blank);
LOG_F(INFO, "Control: refresh rate set to %f Hz", this->refresh_rate);
if (this->refresh_task_id) {
TimerManager::get_instance()->cancel_timer(this->refresh_task_id);
}
// set up periodic timer for display updates
uint64_t refresh_interval = static_cast<uint64_t>(1.0f / refresh_rate * NS_PER_SEC + 0.5);
this->refresh_task_id = TimerManager::get_instance()->add_cyclic_timer(
TimerManager::get_instance()->add_cyclic_timer(
refresh_interval,
[this]() {
this->update_screen();
}
);
this->blank_on = false;
this->update_screen();
LOG_F(INFO, "Control: display enabled");
this->crtc_on = true;
@@ -356,8 +338,11 @@ void ControlVideo::iodev_write(uint32_t address, uint16_t value)
case RadacalRegs::CLUT_DATA:
this->clut_color[this->comp_index++] = value;
if (this->comp_index >= 3) {
this->set_palette_color(this->rad_addr, clut_color[0],
clut_color[1], clut_color[2], 0xFF);
// TODO: combine separate components into a single ARGB value
this->palette[this->rad_addr][0] = this->clut_color[0];
this->palette[this->rad_addr][1] = this->clut_color[1];
this->palette[this->rad_addr][2] = this->clut_color[2];
this->palette[this->rad_addr][3] = 255;
this->rad_addr++; // auto-increment CLUT address
this->comp_index = 0;
}
-1
View File
@@ -117,7 +117,6 @@ private:
std::unique_ptr<uint8_t[]> vram_ptr;
uint32_t vram_size;
uint32_t io_base = 0;
uint32_t vram_base = 0;
uint32_t regs_base = 0;
uint32_t prev_test = 0x433;
+1
View File
@@ -88,6 +88,7 @@ DisplayID::DisplayID(uint8_t std_code, uint8_t ext_code)
uint8_t DisplayID::read_monitor_sense(uint8_t levels, uint8_t dirs)
{
uint8_t scl, sda;
uint16_t result;
switch(this->id_kind) {
case Disp_Id_Kind::DDC2B:
+27 -30
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-21 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -46,15 +46,6 @@ PdmOnboardVideo::PdmOnboardVideo()
void PdmOnboardVideo::set_video_mode(uint8_t new_mode)
{
if (this->blanking != (new_mode & 0x80)) {
if (new_mode & 0x80) {
this->disable_video_internal();
} else {
this->blank_on = false;
this->blanking = 0;
}
}
switch(new_mode & 0x7F) {
case PdmVideoMode::Portrait:
case PdmVideoMode::Rgb12in:
@@ -65,14 +56,20 @@ void PdmOnboardVideo::set_video_mode(uint8_t new_mode)
this->video_mode = new_mode & 0x1F;
LOG_F(INFO, "PDM-Video: video mode set to 0x%X", this->video_mode);
}
if (!this->blanking) {
this->enable_video_internal();
if (this->blanking != (new_mode & 0x80)) {
this->blanking = new_mode & 0x80;
if (this->blanking) {
this->disable_video_internal();
} else {
this->enable_video_internal();
}
}
break;
default:
LOG_F(9, "PDM-Video: video disabled, new mode = 0x%X", new_mode & 0x1F);
this->video_mode = new_mode & 0x1F;
this->disable_video_internal();
this->blanking = 0x80;
this->crtc_on = false;
}
}
@@ -110,10 +107,13 @@ void PdmOnboardVideo::set_clut_color(uint8_t color)
{
this->clut_color[this->comp_index++] = color;
if (this->comp_index >= 3) {
this->set_palette_color(this->clut_index, clut_color[0],
clut_color[1], clut_color[2], 0xFF);
this->clut_index++;
this->comp_index = 0;
// TODO: combine separate components into a single ARGB value
this->palette[this->clut_index][0] = this->clut_color[0];
this->palette[this->clut_index][1] = this->clut_color[1];
this->palette[this->clut_index][2] = this->clut_color[2];
this->palette[this->clut_index][3] = 255;
this->clut_index++; // assume the HW works like that
this->comp_index = 0; // assume the HW works like that
}
}
@@ -204,38 +204,33 @@ void PdmOnboardVideo::enable_video_internal()
LOG_F(INFO, "PDM-Video: framebuffer phys base addr = 0x%X", fb_base_phys);
// set framebuffer address and pitch
this->fb_ptr = mmu_get_dma_mem(fb_base_phys, PDM_FB_SIZE_MAX, nullptr);
this->fb_ptr = mmu_get_dma_mem(fb_base_phys, PDM_FB_SIZE_MAX);
this->active_width = new_width;
this->active_height = new_height;
this->set_depth_internal(new_width);
if (this->refresh_task_id) {
TimerManager::get_instance()->cancel_timer(this->refresh_task_id);
}
// set up video refresh timer
double refresh_rate_hz = (double)(this->pixel_clock) / (new_width + hori_blank) / (new_height + vert_blank);
LOG_F(INFO, "PDM-Video: refresh rate set to %f Hz", refresh_rate_hz);
uint64_t refresh_interval = static_cast<uint64_t>(1.0f / refresh_rate_hz * NS_PER_SEC + 0.5);
this->refresh_task_id = TimerManager::get_instance()->add_cyclic_timer(
TimerManager::get_instance()->add_cyclic_timer(
refresh_interval,
[this]() {
this->update_screen();
}
);
LOG_F(9, "PDM-Video: video enabled");
this->update_screen();
LOG_F(INFO, "PDM-Video: video enabled");
this->crtc_on = true;
}
void PdmOnboardVideo::disable_video_internal()
{
this->blank_on = true;
this->blank_display();
this->blanking = 0x80;
this->crtc_on = false;
LOG_F(9, "PDM-Video: video disabled");
LOG_F(INFO, "PDM-Video: video disabled");
}
/** Ariel II has a weird 1bpp mode where a white pixel is mapped to
@@ -250,8 +245,10 @@ void PdmOnboardVideo::convert_frame_1bpp(uint8_t *dst_buf, int dst_pitch)
uint32_t pixels[2];
// prepare cached ARGB values for white & black pixels
pixels[0] = this->palette[127];
pixels[1] = this->palette[255];
pixels[0] = (0xFF << 24) | (this->palette[127][0] << 16) |
(this->palette[127][1] << 8) | this->palette[127][2];
pixels[1] = (0xFF << 24) | (this->palette[255][0] << 16) |
(this->palette[255][1] << 8) | this->palette[255][2];
src_buf = this->fb_ptr;
src_pitch = this->fb_pitch;
+61 -133
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-21 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -21,10 +21,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
/** @file Video Conroller base class implementation. */
#include <core/hostevents.h>
#include <devices/video/videoctrl.h>
#include "videoctrl.h"
#include <loguru.hpp>
#include <memaccess.h>
#include <SDL.h>
#include <chrono>
@@ -32,23 +30,55 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
VideoCtrlBase::VideoCtrlBase(int width, int height)
{
EventManager::get_instance()->register_handler(EventType::EVENT_WINDOW,
[this](const BaseEvent& event) {
const WindowEvent& wnd_event = static_cast<const WindowEvent&>(event);
if (wnd_event.sub_type == SDL_WINDOWEVENT_SIZE_CHANGED &&
wnd_event.window_id == this->disp_wnd_id)
this->resizing = false;
});
LOG_F(INFO, "Create display window...");
this->create_display_window(width, height);
this->active_width = width;
this->active_height = height;
// Create display window
this->display_wnd = SDL_CreateWindow(
"DingusPPC Display",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
this->active_width,
this->active_height,
SDL_WINDOW_OPENGL
);
if (this->display_wnd == NULL) {
LOG_F(ERROR, "Display: SDL_CreateWindow failed with %s", SDL_GetError());
}
this->renderer = SDL_CreateRenderer(this->display_wnd, -1, SDL_RENDERER_ACCELERATED);
if (this->renderer == NULL) {
LOG_F(ERROR, "Display: SDL_CreateRenderer failed with %s", SDL_GetError());
}
SDL_SetRenderDrawColor(this->renderer, 0, 0, 0, 255);
SDL_RenderClear(this->renderer);
SDL_RenderPresent(this->renderer);
// Stupidly poll for 10 events.
// Otherwise no window will be shown on mac OS!
SDL_Event e;
for (int i = 0; i < 10; i++) {
SDL_PollEvent(&e);
}
this->disp_texture = SDL_CreateTexture(
this->renderer,
SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING,
width, height
);
if (this->disp_texture == NULL) {
LOG_F(ERROR, "Display: SDL_CreateTexture failed with %s", SDL_GetError());
}
}
VideoCtrlBase::~VideoCtrlBase()
{
if (this->cursor_texture) {
SDL_DestroyTexture(this->cursor_texture);
}
if (this->disp_texture) {
SDL_DestroyTexture(this->disp_texture);
}
@@ -62,61 +92,6 @@ VideoCtrlBase::~VideoCtrlBase()
}
}
void VideoCtrlBase::create_display_window(int width, int height)
{
if (!this->display_wnd) { // create display window
this->display_wnd = SDL_CreateWindow(
"DingusPPC Display",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
width, height,
SDL_WINDOW_OPENGL
);
this->disp_wnd_id = SDL_GetWindowID(this->display_wnd);
if (this->display_wnd == NULL) {
ABORT_F("Display: SDL_CreateWindow failed with %s", SDL_GetError());
}
this->renderer = SDL_CreateRenderer(this->display_wnd, -1, SDL_RENDERER_ACCELERATED);
if (this->renderer == NULL) {
ABORT_F("Display: SDL_CreateRenderer failed with %s", SDL_GetError());
}
this->blank_on = true; // TODO: should be true!
this->blank_display();
} else { // resize display window
SDL_SetWindowSize(this->display_wnd, width, height);
this->resizing = true;
}
this->active_width = width;
this->active_height = height;
if (this->disp_texture) {
SDL_DestroyTexture(this->disp_texture);
}
this->disp_texture = SDL_CreateTexture(
this->renderer,
SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING,
width, height
);
if (this->disp_texture == NULL) {
ABORT_F("Display: SDL_CreateTexture failed with %s", SDL_GetError());
}
}
void VideoCtrlBase::blank_display() {
SDL_SetRenderDrawColor(this->renderer, 0, 0, 0, 255);
SDL_RenderClear(this->renderer);
SDL_RenderPresent(this->renderer);
}
void VideoCtrlBase::update_screen()
{
uint8_t* dst_buf;
@@ -124,14 +99,6 @@ void VideoCtrlBase::update_screen()
//auto start_time = std::chrono::steady_clock::now();
if (this->resizing)
return;
if (this->blank_on) {
this->blank_display();
return;
}
SDL_LockTexture(this->disp_texture, NULL, (void **)&dst_buf, &dst_pitch);
// texture update callback to get ARGB data from guest framebuffer
@@ -140,61 +107,18 @@ void VideoCtrlBase::update_screen()
SDL_UnlockTexture(this->disp_texture);
SDL_RenderClear(this->renderer);
SDL_RenderCopy(this->renderer, this->disp_texture, NULL, NULL);
// draw HW cursor if enabled
if (this->cursor_on) {
this->get_cursor_position(cursor_rect.x, cursor_rect.y);
SDL_RenderCopy(this->renderer, this->cursor_texture, NULL, &cursor_rect);
}
SDL_RenderPresent(this->renderer);
}
void VideoCtrlBase::get_palette_colors(uint8_t index, uint8_t& r, uint8_t& g,
uint8_t& b, uint8_t& a)
{
b = this->palette[index] & 0xFFU;
g = (this->palette[index] >> 8) & 0xFFU;
r = (this->palette[index] >> 16) & 0xFFU;
a = (this->palette[index] >> 24) & 0xFFU;
}
// HW cursor data is stored at the beginning of the video memory
// HACK: use src_offset to recognize cursor data being ready
// Normally, we should check GEN_CUR_ENABLE bit in the GEN_TEST_CNTL register
//if (src_offset > 0x400 && READ_DWORD_LE_A(&this->block_io_regs[ATI_CUR_OFFSET])) {
// this->draw_hw_cursor(dst_buf + dst_pitch * 20 + 120, dst_pitch);
//}
void VideoCtrlBase::set_palette_color(uint8_t index, uint8_t r, uint8_t g, uint8_t b, uint8_t a)
{
this->palette[index] = (a << 24) | (r << 16) | (g << 8) | b;
}
void VideoCtrlBase::setup_hw_cursor(int cursor_width, int cursor_height)
{
uint8_t* dst_buf;
int dst_pitch;
if (this->cursor_texture) {
SDL_DestroyTexture(this->cursor_texture);
}
this->cursor_texture = SDL_CreateTexture(
this->renderer,
SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING,
cursor_width, cursor_height
);
if (this->cursor_texture == NULL) {
ABORT_F("SDL_CreateTexture for HW cursor failed with %s", SDL_GetError());
}
SDL_LockTexture(this->cursor_texture, NULL, (void **)&dst_buf, &dst_pitch);
SDL_SetTextureBlendMode(this->cursor_texture, SDL_BLENDMODE_BLEND);
this->draw_hw_cursor(dst_buf, dst_pitch);
SDL_UnlockTexture(this->cursor_texture);
this->cursor_rect.x = 0;
this->cursor_rect.y = 0;
this->cursor_rect.w = cursor_width;
this->cursor_rect.h = cursor_height;
this->cursor_on = true;
//auto end_time = std::chrono::steady_clock::now();
//auto time_elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time);
//LOG_F(INFO, "Display uodate took: %lld ns", time_elapsed.count());
}
void VideoCtrlBase::convert_frame_1bpp(uint8_t *dst_buf, int dst_pitch)
@@ -204,7 +128,7 @@ void VideoCtrlBase::convert_frame_1bpp(uint8_t *dst_buf, int dst_pitch)
void VideoCtrlBase::convert_frame_8bpp(uint8_t *dst_buf, int dst_pitch)
{
uint8_t *src_buf, *src_row, *dst_row;
uint8_t *src_buf, *src_row, *dst_row, pix;
int src_pitch;
src_buf = this->fb_ptr;
@@ -215,7 +139,11 @@ void VideoCtrlBase::convert_frame_8bpp(uint8_t *dst_buf, int dst_pitch)
dst_row = &dst_buf[h * dst_pitch];
for (int x = 0; x < this->active_width; x++) {
WRITE_DWORD_LE_A(dst_row, this->palette[src_row[x]]);
pix = src_row[x];
dst_row[0] = this->palette[pix][2]; // B
dst_row[1] = this->palette[pix][1]; // G
dst_row[2] = this->palette[pix][0]; // R
dst_row[3] = 255; // Alpha
dst_row += 4;
}
}
+6 -26
View File
@@ -1,6 +1,6 @@
/*
DingusPPC - The Experimental PowerPC Macintosh emulator
Copyright (C) 2018-23 divingkatae and maximum
Copyright (C) 2018-21 divingkatae and maximum
(theweirdo) spatium
(Contact divingkatae#1017 or powermax#2286 on Discord for more info)
@@ -34,53 +34,33 @@ public:
VideoCtrlBase(int width = 640, int height = 480);
~VideoCtrlBase();
void create_display_window(int width, int height);
void blank_display();
void update_screen(void);
void get_palette_colors(uint8_t index, uint8_t& r, uint8_t& g, uint8_t& b,
uint8_t& a);
void set_palette_color(uint8_t index, uint8_t r, uint8_t g, uint8_t b, uint8_t a);
// HW cursor support
void setup_hw_cursor(int cursor_width=64, int cur_height=64);
virtual void draw_hw_cursor(uint8_t *dst_buf, int dst_pitch) {};
virtual void get_cursor_position(int& x, int& y) { x = 0; y = 0; };
// converters for various framebuffer pixel depths
virtual void convert_frame_1bpp(uint8_t *dst_buf, int dst_pitch);
virtual void convert_frame_8bpp(uint8_t *dst_buf, int dst_pitch);
protected:
// CRT controller parameters
/* CRT controller parameters */
bool crtc_on = false;
bool blank_on = true;
bool resizing = false;
bool cursor_on = false;
int active_width; // width of the visible display area
int active_height; // height of the visible display area
int hori_total = 0;
int vert_total = 0;
int pixel_depth;
float pixel_clock;
float refresh_rate;
uint32_t palette[256]; // internal DAC palette in RGBA format
uint8_t palette[256][4]; /* internal DAC palette in RGBA format */
// Framebuffer parameters
uint8_t* fb_ptr;
int fb_pitch;
uint32_t refresh_task_id = 0;
std::function<void(uint8_t *dst_buf, int dst_pitch)> convert_fb_cb;
private:
uint32_t disp_wnd_id = 0;
SDL_Window* display_wnd = 0;
SDL_Renderer* renderer = 0;
SDL_Texture* disp_texture = 0;
SDL_Texture* cursor_texture = 0;
SDL_Rect cursor_rect; // destination rectangle for cursor drawing
SDL_Window *display_wnd;
SDL_Renderer *renderer;
SDL_Texture *disp_texture;
};
#endif // VIDEO_CTRL_H
-3
View File
@@ -69,7 +69,4 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#endif
#define BYTESWAP_SIZED(val, size) \
(size) == 2 ? BYTESWAP_16((val)) : ((size) == 4 ? BYTESWAP_32((val)) : (val))
#endif /* ENDIAN_SWAP_H */
Loaded 100 of 235 files, more files were not shown because too many files have changed in this diff. Show more