diff options
73 files changed, 1402 insertions, 1287 deletions
diff --git a/.travis-deps.sh b/.travis-deps.sh index 2a0f6b284..bd09da0d0 100644 --- a/.travis-deps.sh +++ b/.travis-deps.sh @@ -24,8 +24,6 @@ if [ "$TRAVIS_OS_NAME" = linux -o -z "$TRAVIS_OS_NAME" ]; then curl http://www.cmake.org/files/v2.8/cmake-2.8.11-Linux-i386.tar.gz \ | sudo tar -xz -C /usr/local --strip-components=1 elif [ "$TRAVIS_OS_NAME" = osx ]; then - export HOMEBREW_CACHE="$PWD/.homebrew-cache" - mkdir -p "$HOMEBREW_CACHE" brew tap homebrew/versions brew install qt5 glfw3 pkgconfig fi diff --git a/.travis.yml b/.travis.yml index 8c5aceb7c..1cb369d5b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,11 +4,6 @@ os: language: cpp -cache: - apt: true - directories: - - .homebrew-cache - before_install: - sh .travis-deps.sh diff --git a/CMakeLists.txt b/CMakeLists.txt index 884520cef..20a5a011a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,8 +5,8 @@ cmake_minimum_required(VERSION 2.8.11) project(citra) if (NOT MSVC) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wno-attributes") - add_definitions(-pthread) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wno-attributes -pthread") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pthread") else() # Silence deprecation warnings add_definitions(/D_CRT_SECURE_NO_WARNINGS) @@ -17,14 +17,14 @@ else() # As far as I can tell, there's no way to override the CMake defaults while leaving user # changes intact, so we'll just clobber everything and say sorry. message(STATUS "Cache compiler flags ignored, please edit CMakeFiles.txt to change the flags.") + # /MP - Multi-threaded compilation # /MD - Multi-threaded runtime # /Ox - Full optimization - # /Oi - Use intrinsic functions # /Oy- - Don't omit frame pointer # /GR- - Disable RTTI # /GS- - No stack buffer overflow checks # /EHsc - C++-only exception handling semantics - set(optimization_flags "/MD /Ox /Oi /Oy- /DNDEBUG /GR- /GS- /EHsc") + set(optimization_flags "/MP /MD /Ox /Oy- /GR- /GS- /EHsc") # /Zi - Output debugging information # /Zo - enahnced debug info for optimized builds set(CMAKE_C_FLAGS_RELEASE "${optimization_flags} /Zi" CACHE STRING "" FORCE) @@ -32,7 +32,11 @@ else() set(CMAKE_C_FLAGS_RELWITHDEBINFO "${optimization_flags} /Zi /Zo" CACHE STRING "" FORCE) set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${optimization_flags} /Zi /Zo" CACHE STRING "" FORCE) endif() + add_definitions(-DSINGLETHREADED) +# CMake seems to only define _DEBUG on Windows +set_property(DIRECTORY APPEND PROPERTY + COMPILE_DEFINITIONS $<$<CONFIG:Debug>:_DEBUG> $<$<NOT:$<CONFIG:Debug>>:NDEBUG>) find_package(PNG QUIET) if (PNG_FOUND) @@ -106,10 +110,17 @@ if (ENABLE_GLFW) endif() IF (APPLE) - # CoreFoundation is required only on OSX - FIND_LIBRARY(COREFOUNDATION_LIBRARY CoreFoundation) + FIND_LIBRARY(COCOA_LIBRARY Cocoa) # Umbrella framework for everything GUI-related + FIND_LIBRARY(IOKIT_LIBRARY IOKit) # GLFW dependency + FIND_LIBRARY(COREVIDEO_LIBRARY CoreVideo) # GLFW dependency + set(PLATFORM_LIBRARIES iconv ${COCOA_LIBRARY} ${IOKIT_LIBRARY} ${COREVIDEO_LIBRARY}) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -stdlib=libc++") +ELSEIF(WIN32) + set(PLATFORM_LIBRARIES winmm ws2_32) +ELSE() + set(PLATFORM_LIBRARIES rt) ENDIF (APPLE) option(ENABLE_QT "Enable the Qt frontend" ON) diff --git a/appveyor.yml b/appveyor.yml new file mode 100644 index 000000000..83d3b900e --- /dev/null +++ b/appveyor.yml @@ -0,0 +1,17 @@ +# it seems that Qt is only installed by default on unstable os at the moment +os: unstable + +# shallow clone +clone_depth: 1 + +environment: + QTDIR: C:\Qt\5.4\msvc2013_opengl + +install: + - git submodule update --init --recursive + +before_build: + - mkdir build + - cd build + - cmake .. + - cd .. diff --git a/externals/boost b/externals/boost -Subproject 97052c28acb141dbf3c5e14114af99045344b69 +Subproject a1afc91d3aaa3da06bdbc13c78613e146665340 diff --git a/src/citra/CMakeLists.txt b/src/citra/CMakeLists.txt index bbb3374f2..713f49193 100644 --- a/src/citra/CMakeLists.txt +++ b/src/citra/CMakeLists.txt @@ -16,20 +16,6 @@ create_directory_groups(${SRCS} ${HEADERS}) add_executable(citra ${SRCS} ${HEADERS}) target_link_libraries(citra core common video_core) target_link_libraries(citra ${GLFW_LIBRARIES} ${OPENGL_gl_LIBRARY} inih) - -if (UNIX) - target_link_libraries(citra -pthread) -endif() - -if (APPLE) - target_link_libraries(citra iconv ${COREFOUNDATION_LIBRARY}) -elseif (WIN32) - target_link_libraries(citra winmm wsock32 ws2_32) - if (MINGW) # GCC does not support codecvt, so use iconv instead - target_link_libraries(citra iconv) - endif() -else() # Unix - target_link_libraries(citra rt) -endif() +target_link_libraries(citra ${PLATFORM_LIBRARIES}) #install(TARGETS citra RUNTIME DESTINATION ${bindir}) diff --git a/src/citra_qt/CMakeLists.txt b/src/citra_qt/CMakeLists.txt index a0ba252b3..bbc521f8a 100644 --- a/src/citra_qt/CMakeLists.txt +++ b/src/citra_qt/CMakeLists.txt @@ -60,17 +60,6 @@ endif() add_executable(citra-qt ${SRCS} ${HEADERS} ${UI_HDRS}) target_link_libraries(citra-qt core common video_core qhexedit) target_link_libraries(citra-qt ${OPENGL_gl_LIBRARY} ${CITRA_QT_LIBS}) - -if (UNIX) - target_link_libraries(citra-qt -pthread) -endif() - -if (APPLE) - target_link_libraries(citra-qt iconv ${COREFOUNDATION_LIBRARY}) -elseif (WIN32) - target_link_libraries(citra-qt winmm wsock32 ws2_32) -else() # Unix - target_link_libraries(citra-qt rt) -endif() +target_link_libraries(citra-qt ${PLATFORM_LIBRARIES}) #install(TARGETS citra-qt RUNTIME DESTINATION ${bindir}) diff --git a/src/citra_qt/debugger/callstack.cpp b/src/citra_qt/debugger/callstack.cpp index ab317a723..025a5896b 100644 --- a/src/citra_qt/debugger/callstack.cpp +++ b/src/citra_qt/debugger/callstack.cpp @@ -38,6 +38,9 @@ void CallstackWidget::OnDebugModeEntered() { ret_addr = Memory::Read32(addr); call_addr = ret_addr - 4; //get call address??? + + if (Memory::GetPointer(call_addr) == nullptr) + break; /* TODO (mattvail) clean me, move to debugger interface */ u32 insn = Memory::Read32(call_addr); diff --git a/src/citra_qt/debugger/disassembler.cpp b/src/citra_qt/debugger/disassembler.cpp index 3a1940015..c61ace925 100644 --- a/src/citra_qt/debugger/disassembler.cpp +++ b/src/citra_qt/debugger/disassembler.cpp @@ -13,6 +13,7 @@ #include "core/core.h" #include "common/break_points.h" #include "common/symbols.h" +#include "core/arm/arm_interface.h" #include "core/arm/skyeye_common/armdefs.h" #include "core/arm/disassembler/arm_disasm.h" diff --git a/src/citra_qt/debugger/graphics_framebuffer.cpp b/src/citra_qt/debugger/graphics_framebuffer.cpp index caa6896f9..a9423d6c7 100644 --- a/src/citra_qt/debugger/graphics_framebuffer.cpp +++ b/src/citra_qt/debugger/graphics_framebuffer.cpp @@ -158,17 +158,17 @@ void GraphicsFramebufferWidget::OnFramebufferAddressChanged(qint64 new_value) } } -void GraphicsFramebufferWidget::OnFramebufferWidthChanged(unsigned int new_value) +void GraphicsFramebufferWidget::OnFramebufferWidthChanged(int new_value) { - if (framebuffer_width != new_value) { - framebuffer_width = new_value; + if (framebuffer_width != static_cast<unsigned>(new_value)) { + framebuffer_width = static_cast<unsigned>(new_value); framebuffer_source_list->setCurrentIndex(static_cast<int>(Source::Custom)); emit Update(); } } -void GraphicsFramebufferWidget::OnFramebufferHeightChanged(unsigned int new_value) +void GraphicsFramebufferWidget::OnFramebufferHeightChanged(int new_value) { if (framebuffer_height != new_value) { framebuffer_height = new_value; diff --git a/src/citra_qt/debugger/graphics_framebuffer.h b/src/citra_qt/debugger/graphics_framebuffer.h index 02813525c..56215761e 100644 --- a/src/citra_qt/debugger/graphics_framebuffer.h +++ b/src/citra_qt/debugger/graphics_framebuffer.h @@ -62,8 +62,8 @@ public: public slots: void OnFramebufferSourceChanged(int new_value); void OnFramebufferAddressChanged(qint64 new_value); - void OnFramebufferWidthChanged(unsigned int new_value); - void OnFramebufferHeightChanged(unsigned int new_value); + void OnFramebufferWidthChanged(int new_value); + void OnFramebufferHeightChanged(int new_value); void OnFramebufferFormatChanged(int new_value); void OnUpdate(); diff --git a/src/common/common.h b/src/common/common.h index ba33373ae..3246c7797 100644 --- a/src/common/common.h +++ b/src/common/common.h @@ -11,13 +11,6 @@ #include <cstdio> #include <cstring> -// Force enable logging in the right modes. For some reason, something had changed -// so that debugfast no longer logged. -#if defined(_DEBUG) || defined(DEBUGFAST) -#undef LOGGING -#define LOGGING 1 -#endif - #define STACKALIGN // An inheritable class to disallow the copy constructor and operator= functions @@ -154,16 +147,10 @@ enum EMUSTATE_CHANGE #ifdef _MSC_VER -#ifndef _XBOX inline unsigned long long bswap64(unsigned long long x) { return _byteswap_uint64(x); } inline unsigned int bswap32(unsigned int x) { return _byteswap_ulong(x); } inline unsigned short bswap16(unsigned short x) { return _byteswap_ushort(x); } #else -inline unsigned long long bswap64(unsigned long long x) { return __loaddoublewordbytereverse(0, &x); } -inline unsigned int bswap32(unsigned int x) { return __loadwordbytereverse(0, &x); } -inline unsigned short bswap16(unsigned short x) { return __loadshortbytereverse(0, &x); } -#endif -#else // TODO: speedup inline unsigned short bswap16(unsigned short x) { return (x << 8) | (x >> 8); } inline unsigned int bswap32(unsigned int x) { return (x >> 24) | ((x & 0xFF0000) >> 8) | ((x & 0xFF00) << 8) | (x << 24);} diff --git a/src/common/common_paths.h b/src/common/common_paths.h index e692e5492..0ecf2d9de 100644 --- a/src/common/common_paths.h +++ b/src/common/common_paths.h @@ -35,26 +35,23 @@ #define JAP_DIR "JAP" // Subdirs in the User dir returned by GetUserPath(D_USER_IDX) -#define CONFIG_DIR "config" -#define GAMECONFIG_DIR "game_config" -#define MAPS_DIR "maps" -#define CACHE_DIR "cache" -#define SDMC_DIR "sdmc" -#define EXTSAVEDATA_DIR "extsavedata" -#define SAVEDATA_DIR "savedata" -#define SAVEDATACHECK_DIR "savedatacheck" -#define SYSDATA_DIR "sysdata" -#define SYSSAVEDATA_DIR "syssavedata" -#define SHADERCACHE_DIR "shader_cache" -#define STATESAVES_DIR "state_saves" -#define SCREENSHOTS_DIR "screenShots" -#define DUMP_DIR "dump" -#define DUMP_TEXTURES_DIR "textures" -#define DUMP_FRAMES_DIR "frames" -#define DUMP_AUDIO_DIR "audio" -#define LOGS_DIR "logs" -#define SHADERS_DIR "shaders" -#define SYSCONF_DIR "sysconf" +#define CONFIG_DIR "config" +#define GAMECONFIG_DIR "game_config" +#define MAPS_DIR "maps" +#define CACHE_DIR "cache" +#define SDMC_DIR "sdmc" +#define NAND_DIR "nand" +#define SYSDATA_DIR "sysdata" +#define SHADERCACHE_DIR "shader_cache" +#define STATESAVES_DIR "state_saves" +#define SCREENSHOTS_DIR "screenShots" +#define DUMP_DIR "dump" +#define DUMP_TEXTURES_DIR "textures" +#define DUMP_FRAMES_DIR "frames" +#define DUMP_AUDIO_DIR "audio" +#define LOGS_DIR "logs" +#define SHADERS_DIR "shaders" +#define SYSCONF_DIR "sysconf" // Filenames // Files in the directory returned by GetUserPath(D_CONFIG_IDX) diff --git a/src/common/file_util.cpp b/src/common/file_util.cpp index 0a6cd80c8..706e7c842 100644 --- a/src/common/file_util.cpp +++ b/src/common/file_util.cpp @@ -676,11 +676,8 @@ const std::string& GetUserPath(const unsigned int DirIDX, const std::string &new paths[D_MAPS_IDX] = paths[D_USER_IDX] + MAPS_DIR DIR_SEP; paths[D_CACHE_IDX] = paths[D_USER_IDX] + CACHE_DIR DIR_SEP; paths[D_SDMC_IDX] = paths[D_USER_IDX] + SDMC_DIR DIR_SEP; - paths[D_EXTSAVEDATA] = paths[D_USER_IDX] + EXTSAVEDATA_DIR DIR_SEP; - paths[D_SAVEDATA_IDX] = paths[D_USER_IDX] + SAVEDATA_DIR DIR_SEP; - paths[D_SAVEDATACHECK_IDX] = paths[D_USER_IDX] + SAVEDATACHECK_DIR DIR_SEP; + paths[D_NAND_IDX] = paths[D_USER_IDX] + NAND_DIR DIR_SEP; paths[D_SYSDATA_IDX] = paths[D_USER_IDX] + SYSDATA_DIR DIR_SEP; - paths[D_SYSSAVEDATA_IDX] = paths[D_USER_IDX] + SYSSAVEDATA_DIR DIR_SEP; paths[D_SHADERCACHE_IDX] = paths[D_USER_IDX] + SHADERCACHE_DIR DIR_SEP; paths[D_SHADERS_IDX] = paths[D_USER_IDX] + SHADERS_DIR DIR_SEP; paths[D_STATESAVES_IDX] = paths[D_USER_IDX] + STATESAVES_DIR DIR_SEP; @@ -722,10 +719,7 @@ const std::string& GetUserPath(const unsigned int DirIDX, const std::string &new paths[D_MAPS_IDX] = paths[D_USER_IDX] + MAPS_DIR DIR_SEP; paths[D_CACHE_IDX] = paths[D_USER_IDX] + CACHE_DIR DIR_SEP; paths[D_SDMC_IDX] = paths[D_USER_IDX] + SDMC_DIR DIR_SEP; - paths[D_EXTSAVEDATA] = paths[D_USER_IDX] + EXTSAVEDATA_DIR DIR_SEP; - paths[D_SAVEDATA_IDX] = paths[D_USER_IDX] + SAVEDATA_DIR DIR_SEP; - paths[D_SAVEDATACHECK_IDX] = paths[D_USER_IDX] + SAVEDATACHECK_DIR DIR_SEP; - paths[D_SYSSAVEDATA_IDX] = paths[D_USER_IDX] + SYSSAVEDATA_DIR DIR_SEP; + paths[D_NAND_IDX] = paths[D_USER_IDX] + NAND_DIR DIR_SEP; paths[D_SHADERCACHE_IDX] = paths[D_USER_IDX] + SHADERCACHE_DIR DIR_SEP; paths[D_SHADERS_IDX] = paths[D_USER_IDX] + SHADERS_DIR DIR_SEP; paths[D_STATESAVES_IDX] = paths[D_USER_IDX] + STATESAVES_DIR DIR_SEP; diff --git a/src/common/file_util.h b/src/common/file_util.h index c83ecd87d..86aab2e3d 100644 --- a/src/common/file_util.h +++ b/src/common/file_util.h @@ -27,11 +27,8 @@ enum { D_STATESAVES_IDX, D_SCREENSHOTS_IDX, D_SDMC_IDX, - D_EXTSAVEDATA, - D_SAVEDATA_IDX, - D_SAVEDATACHECK_IDX, + D_NAND_IDX, D_SYSDATA_IDX, - D_SYSSAVEDATA_IDX, D_HIRESTEXTURES_IDX, D_DUMP_IDX, D_DUMPFRAMES_IDX, diff --git a/src/common/log.h b/src/common/log.h index 667f2fbb9..b397cf14d 100644 --- a/src/common/log.h +++ b/src/common/log.h @@ -14,7 +14,7 @@ #endif #endif -#if _DEBUG +#ifdef _DEBUG #define _dbg_assert_(_t_, _a_) \ if (!(_a_)) {\ LOG_CRITICAL(_t_, "Error...\n\n Line: %d\n File: %s\n Time: %s\n\nIgnore and continue?", \ diff --git a/src/common/logging/backend.cpp b/src/common/logging/backend.cpp index 7ac30ad50..83ebb42d9 100644 --- a/src/common/logging/backend.cpp +++ b/src/common/logging/backend.cpp @@ -22,6 +22,7 @@ static std::shared_ptr<Logger> global_logger; SUB(Common, Memory) \ CLS(Core) \ SUB(Core, ARM11) \ + SUB(Core, Timing) \ CLS(Config) \ CLS(Debug) \ SUB(Debug, Emulated) \ diff --git a/src/common/logging/log.h b/src/common/logging/log.h index 06b99b07a..3d94bf0d9 100644 --- a/src/common/logging/log.h +++ b/src/common/logging/log.h @@ -41,6 +41,7 @@ enum class Class : ClassType { Common_Memory, ///< Memory mapping and management functions Core, ///< LLE emulation core Core_ARM11, ///< ARM11 CPU core + Core_Timing, ///< CoreTiming functions Config, ///< Emulator configuration (including commandline) Debug, ///< Debugging tools Debug_Emulated, ///< Debug messages from the emulated programs @@ -73,17 +74,6 @@ enum class Class : ClassType { }; /** - * Level below which messages are simply discarded without buffering regardless of the display - * settings. - */ -const Level MINIMUM_LEVEL = -#ifdef _DEBUG - Level::Trace; -#else - Level::Debug; -#endif - -/** * Logs a message to the global logger. This proxy exists to avoid exposing the details of the * Logger class, including the ConcurrentRingBuffer template, to all files that desire to log * messages, reducing unecessary recompilations. @@ -102,13 +92,15 @@ void LogMessage(Class log_class, Level log_level, } // namespace Log #define LOG_GENERIC(log_class, log_level, ...) \ - do { \ - if (::Log::Level::log_level >= ::Log::MINIMUM_LEVEL) \ - ::Log::LogMessage(::Log::Class::log_class, ::Log::Level::log_level, \ - __FILE__, __LINE__, __func__, __VA_ARGS__); \ - } while (0) + ::Log::LogMessage(::Log::Class::log_class, ::Log::Level::log_level, \ + __FILE__, __LINE__, __func__, __VA_ARGS__) +#ifdef _DEBUG #define LOG_TRACE( log_class, ...) LOG_GENERIC(log_class, Trace, __VA_ARGS__) +#else +#define LOG_TRACE( log_class, ...) (void(0)) +#endif + #define LOG_DEBUG( log_class, ...) LOG_GENERIC(log_class, Debug, __VA_ARGS__) #define LOG_INFO( log_class, ...) LOG_GENERIC(log_class, Info, __VA_ARGS__) #define LOG_WARNING( log_class, ...) LOG_GENERIC(log_class, Warning, __VA_ARGS__) diff --git a/src/common/mem_arena.cpp b/src/common/mem_arena.cpp index 9904d2472..a20361d6f 100644 --- a/src/common/mem_arena.cpp +++ b/src/common/mem_arena.cpp @@ -29,10 +29,6 @@ #endif #endif -#ifdef IOS -void* globalbase = nullptr; -#endif - #ifdef ANDROID // Hopefully this ABI will never change... @@ -95,7 +91,7 @@ int ashmem_unpin_region(int fd, size_t offset, size_t len) #endif // Android -#if defined(_WIN32) && !defined(_XBOX) +#if defined(_WIN32) SYSTEM_INFO sysInfo; #endif @@ -103,11 +99,7 @@ SYSTEM_INFO sysInfo; // Windows mappings need to be on 64K boundaries, due to Alpha legacy. #ifdef _WIN32 size_t roundup(size_t x) { -#ifndef _XBOX int gran = sysInfo.dwAllocationGranularity ? sysInfo.dwAllocationGranularity : 0x10000; -#else - int gran = 0x10000; // 64k in 360 -#endif return (x + gran - 1) & ~(gran - 1); } #else @@ -120,10 +112,8 @@ size_t roundup(size_t x) { void MemArena::GrabLowMemSpace(size_t size) { #ifdef _WIN32 -#ifndef _XBOX hMemoryMapping = CreateFileMapping(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, (DWORD)(size), nullptr); GetSystemInfo(&sysInfo); -#endif #elif defined(ANDROID) // Use ashmem so we don't have to allocate a file on disk! fd = ashmem_create_region("PPSSPP_RAM", size); @@ -163,9 +153,6 @@ void MemArena::ReleaseSpace() #ifdef _WIN32 CloseHandle(hMemoryMapping); hMemoryMapping = 0; -#elif defined(__SYMBIAN32__) - memmap->Close(); - delete memmap; #else close(fd); #endif @@ -175,22 +162,13 @@ void MemArena::ReleaseSpace() void *MemArena::CreateView(s64 offset, size_t size, void *base) { #ifdef _WIN32 -#ifdef _XBOX - size = roundup(size); - // use 64kb pages - void * ptr = VirtualAlloc(nullptr, size, MEM_COMMIT | MEM_LARGE_PAGES, PAGE_READWRITE); - return ptr; -#else size = roundup(size); void *ptr = MapViewOfFileEx(hMemoryMapping, FILE_MAP_ALL_ACCESS, 0, (DWORD)((u64)offset), size, base); return ptr; -#endif #else void *retval = mmap(base, size, PROT_READ | PROT_WRITE, MAP_SHARED | // Do not sync memory to underlying file. Linux has this by default. -#ifdef BLACKBERRY - MAP_NOSYNCFILE | -#elif defined(__FreeBSD__) +#ifdef __FreeBSD__ MAP_NOSYNC | #endif ((base == nullptr) ? 0 : MAP_FIXED), fd, offset); @@ -208,17 +186,12 @@ void *MemArena::CreateView(s64 offset, size_t size, void *base) void MemArena::ReleaseView(void* view, size_t size) { #ifdef _WIN32 -#ifndef _XBOX UnmapViewOfFile(view); -#endif -#elif defined(__SYMBIAN32__) - memmap->Decommit(((int)view - (int)memmap->Base()) & 0x3FFFFFFF, size); #else munmap(view, size); #endif } -#ifndef __SYMBIAN32__ u8* MemArena::Find4GBBase() { #ifdef _M_X64 @@ -242,20 +215,6 @@ u8* MemArena::Find4GBBase() } return base; #else -#ifdef IOS - void* base = nullptr; - if (globalbase == nullptr){ - base = mmap(0, 0x08000000, PROT_READ | PROT_WRITE, - MAP_ANON | MAP_SHARED, -1, 0); - if (base == MAP_FAILED) { - PanicAlert("Failed to map 128 MB of memory space: %s", strerror(errno)); - return 0; - } - munmap(base, 0x08000000); - globalbase = base; - } - else{ base = globalbase; } -#else void* base = mmap(0, 0x10000000, PROT_READ | PROT_WRITE, MAP_ANON | MAP_SHARED, -1, 0); if (base == MAP_FAILED) { @@ -263,12 +222,10 @@ u8* MemArena::Find4GBBase() return 0; } munmap(base, 0x10000000); -#endif return static_cast<u8*>(base); #endif #endif } -#endif // yeah, this could also be done in like two bitwise ops... @@ -284,10 +241,6 @@ static bool Memory_TryBase(u8 *base, const MemoryView *views, int num_views, u32 size_t position = 0; size_t last_position = 0; -#if defined(_XBOX) - void *ptr; -#endif - // Zero all the pointers to be sure. for (int i = 0; i < num_views; i++) { @@ -308,18 +261,6 @@ static bool Memory_TryBase(u8 *base, const MemoryView *views, int num_views, u32 position = last_position; } else { -#ifdef __SYMBIAN32__ - *(view.out_ptr_low) = (u8*)((int)arena->memmap->Base() + view.virtual_address); - arena->memmap->Commit(view.virtual_address & 0x3FFFFFFF, view.size); - } - *(view.out_ptr) = (u8*)((int)arena->memmap->Base() + view.virtual_address & 0x3FFFFFFF); -#elif defined(_XBOX) - *(view.out_ptr_low) = (u8*)(base + view.virtual_address); - //arena->memmap->Commit(view.virtual_address & 0x3FFFFFFF, view.size); - ptr = VirtualAlloc(base + (view.virtual_address & 0x3FFFFFFF), view.size, MEM_COMMIT, PAGE_READWRITE); - } - *(view.out_ptr) = (u8*)base + (view.virtual_address & 0x3FFFFFFF); -#else *(view.out_ptr_low) = (u8*)arena->CreateView(position, view.size); if (!*view.out_ptr_low) goto bail; @@ -340,7 +281,6 @@ static bool Memory_TryBase(u8 *base, const MemoryView *views, int num_views, u32 } #endif -#endif last_position = position; position += roundup(view.size); } @@ -389,9 +329,7 @@ u8 *MemoryMap_Setup(const MemoryView *views, int num_views, u32 flags, MemArena total_mem += roundup(views[i].size); } // Grab some pagefile backed memory out of the void ... -#ifndef __SYMBIAN32__ arena->GrabLowMemSpace(total_mem); -#endif // Now, create views in high memory where there's plenty of space. #ifdef _M_X64 @@ -403,15 +341,6 @@ u8 *MemoryMap_Setup(const MemoryView *views, int num_views, u32 flags, MemArena PanicAlert("MemoryMap_Setup: Failed finding a memory base."); return 0; } -#elif defined(_XBOX) - // Reserve 256MB - u8 *base = (u8*)VirtualAlloc(0, 0x10000000, MEM_RESERVE | MEM_LARGE_PAGES, PAGE_READWRITE); - if (!Memory_TryBase(base, views, num_views, flags, arena)) - { - PanicAlert("MemoryMap_Setup: Failed finding a memory base."); - exit(0); - return 0; - } #elif defined(_WIN32) // Try a whole range of possible bases. Return once we got a valid one. u32 max_base_addr = 0x7FFF0000 - 0x10000000; @@ -428,15 +357,6 @@ u8 *MemoryMap_Setup(const MemoryView *views, int num_views, u32 flags, MemArena break; } } -#elif defined(__SYMBIAN32__) - arena->memmap = new RChunk(); - arena->memmap->CreateDisconnectedLocal(0, 0, 0x10000000); - if (!Memory_TryBase(arena->memmap->Base(), views, num_views, flags, arena)) - { - PanicAlert("MemoryMap_Setup: Failed finding a memory base."); - return 0; - } - u8* base = arena->memmap->Base(); #else // Linux32 is fine with the x64 method, although limited to 32-bit with no automirrors. u8 *base = MemArena::Find4GBBase(); diff --git a/src/common/mem_arena.h b/src/common/mem_arena.h index b5f0aa890..3379d2529 100644 --- a/src/common/mem_arena.h +++ b/src/common/mem_arena.h @@ -21,10 +21,6 @@ #include <windows.h> #endif -#ifdef __SYMBIAN32__ -#include <e32std.h> -#endif - #include "common/common.h" // This class lets you create a block of anonymous RAM, and then arbitrarily map views into it. @@ -39,12 +35,8 @@ public: void *CreateView(s64 offset, size_t size, void *base = 0); void ReleaseView(void *view, size_t size); -#ifdef __SYMBIAN32__ - RChunk* memmap; -#else // This only finds 1 GB in 32-bit static u8 *Find4GBBase(); -#endif private: #ifdef _WIN32 diff --git a/src/common/platform.h b/src/common/platform.h index ce9cfd4a2..ba1109c9f 100644 --- a/src/common/platform.h +++ b/src/common/platform.h @@ -35,7 +35,6 @@ #define PLATFORM_MACOSX 2 #define PLATFORM_LINUX 3 #define PLATFORM_ANDROID 4 -#define PLATFORM_IOS 5 //////////////////////////////////////////////////////////////////////////////////////////////////// // Platform detection diff --git a/src/common/swap.h b/src/common/swap.h index 4f8f39efb..e2d918362 100644 --- a/src/common/swap.h +++ b/src/common/swap.h @@ -48,11 +48,7 @@ // MSVC #elif defined(_MSC_VER) && !defined(COMMON_BIG_ENDIAN) && !defined(COMMON_LITTLE_ENDIAN) -#ifdef _XBOX -#define COMMON_BIG_ENDIAN 1 -#else #define COMMON_LITTLE_ENDIAN 1 -#endif #endif diff --git a/src/common/thread_queue_list.h b/src/common/thread_queue_list.h index 4e1c0a215..444abf115 100644 --- a/src/common/thread_queue_list.h +++ b/src/common/thread_queue_list.h @@ -4,213 +4,143 @@ #pragma once +#include <array> +#include <deque> + +#include <boost/range/algorithm_ext/erase.hpp> + #include "common/common.h" namespace Common { -template<class IdType> +template<class T, unsigned int N> struct ThreadQueueList { - // Number of queues (number of priority levels starting at 0.) - static const int NUM_QUEUES = 128; + // TODO(yuriks): If performance proves to be a problem, the std::deques can be replaced with + // (dynamically resizable) circular buffers to remove their overhead when + // inserting and popping. - // Initial number of threads a single queue can handle. - static const int INITIAL_CAPACITY = 32; + typedef unsigned int Priority; - struct Queue { - // Next ever-been-used queue (worse priority.) - Queue *next; - // First valid item in data. - int first; - // One after last valid item in data. - int end; - // A too-large array with room on the front and end. - IdType *data; - // Size of data array. - int capacity; - }; + // Number of priority levels. (Valid levels are [0..NUM_QUEUES).) + static const Priority NUM_QUEUES = N; ThreadQueueList() { - memset(queues, 0, sizeof(queues)); - first = invalid(); - } - - ~ThreadQueueList() { - for (int i = 0; i < NUM_QUEUES; ++i) - { - if (queues[i].data != nullptr) - free(queues[i].data); - } + first = nullptr; } // Only for debugging, returns priority level. - int contains(const IdType uid) { - for (int i = 0; i < NUM_QUEUES; ++i) - { - if (queues[i].data == nullptr) - continue; - - Queue *cur = &queues[i]; - for (int j = cur->first; j < cur->end; ++j) - { - if (cur->data[j] == uid) - return i; + Priority contains(const T& uid) { + for (Priority i = 0; i < NUM_QUEUES; ++i) { + Queue& cur = queues[i]; + if (std::find(cur.data.cbegin(), cur.data.cend(), uid) != cur.data.cend()) { + return i; } } return -1; } - inline IdType pop_first() { + T pop_first() { Queue *cur = first; - while (cur != invalid()) - { - if (cur->end - cur->first > 0) - return cur->data[cur->first++]; - cur = cur->next; + while (cur != nullptr) { + if (!cur->data.empty()) { + auto tmp = std::move(cur->data.front()); + cur->data.pop_front(); + return tmp; + } + cur = cur->next_nonempty; } - //_dbg_assert_msg_(SCEKERNEL, false, "ThreadQueueList should not be empty."); - return 0; + return T(); } - inline IdType pop_first_better(u32 priority) { + T pop_first_better(Priority priority) { Queue *cur = first; Queue *stop = &queues[priority]; - while (cur < stop) - { - if (cur->end - cur->first > 0) - return cur->data[cur->first++]; - cur = cur->next; + while (cur < stop) { + if (!cur->data.empty()) { + auto tmp = std::move(cur->data.front()); + cur->data.pop_front(); + return tmp; + } + cur = cur->next_nonempty; } - return 0; + return T(); } - inline void push_front(u32 priority, const IdType threadID) { + void push_front(Priority priority, const T& thread_id) { Queue *cur = &queues[priority]; - cur->data[--cur->first] = threadID; - if (cur->first == 0) - rebalance(priority); + cur->data.push_front(thread_id); } - inline void push_back(u32 priority, const IdType threadID) { + void push_back(Priority priority, const T& thread_id) { Queue *cur = &queues[priority]; - cur->data[cur->end++] = threadID; - if (cur->end == cur->capacity) - rebalance(priority); + cur->data.push_back(thread_id); } - inline void remove(u32 priority, const IdType threadID) { + void remove(Priority priority, const T& thread_id) { Queue *cur = &queues[priority]; - //_dbg_assert_msg_(SCEKERNEL, cur->next != NULL, "ThreadQueueList::Queue should already be linked up."); - - for (int i = cur->first; i < cur->end; ++i) - { - if (cur->data[i] == threadID) - { - int remaining = --cur->end - i; - if (remaining > 0) - memmove(&cur->data[i], &cur->data[i + 1], remaining * sizeof(IdType)); - return; - } - } - - // Wasn't there. + boost::remove_erase(cur->data, thread_id); } - inline void rotate(u32 priority) { + void rotate(Priority priority) { Queue *cur = &queues[priority]; - //_dbg_assert_msg_(SCEKERNEL, cur->next != NULL, "ThreadQueueList::Queue should already be linked up."); - if (cur->end - cur->first > 1) - { - cur->data[cur->end++] = cur->data[cur->first++]; - if (cur->end == cur->capacity) - rebalance(priority); + if (cur->data.size() > 1) { + cur->data.push_back(std::move(cur->data.front())); + cur->data.pop_front(); } } - inline void clear() { - for (int i = 0; i < NUM_QUEUES; ++i) - { - if (queues[i].data != nullptr) - free(queues[i].data); - } - memset(queues, 0, sizeof(queues)); - first = invalid(); + void clear() { + queues.fill(Queue()); + first = nullptr; } - inline bool empty(u32 priority) const { + bool empty(Priority priority) const { const Queue *cur = &queues[priority]; - return cur->first == cur->end; + return cur->data.empty(); } - inline void prepare(u32 priority) { - Queue *cur = &queues[priority]; - if (cur->next == nullptr) - link(priority, INITIAL_CAPACITY); + void prepare(Priority priority) { + Queue* cur = &queues[priority]; + if (cur->next_nonempty == UnlinkedTag()) + link(priority); } private: - Queue *invalid() const { - return (Queue *) -1; + struct Queue { + // Points to the next active priority, skipping over ones that have never been used. + Queue* next_nonempty = UnlinkedTag(); + // Double-ended queue of threads in this priority level + std::deque<T> data; + }; + + /// Special tag used to mark priority levels that have never been used. + static Queue* UnlinkedTag() { + return reinterpret_cast<Queue*>(1); } - void link(u32 priority, int size) { - //_dbg_assert_msg_(SCEKERNEL, queues[priority].data == NULL, "ThreadQueueList::Queue should only be initialized once."); - - if (size <= INITIAL_CAPACITY) - size = INITIAL_CAPACITY; - else - { - int goal = size; - size = INITIAL_CAPACITY; - while (size < goal) - size *= 2; - } + void link(Priority priority) { Queue *cur = &queues[priority]; - cur->data = (IdType *) malloc(sizeof(IdType) * size); - cur->capacity = size; - cur->first = size / 2; - cur->end = size / 2; - - for (int i = (int) priority - 1; i >= 0; --i) - { - if (queues[i].next != nullptr) - { - cur->next = queues[i].next; - queues[i].next = cur; + + for (int i = priority - 1; i >= 0; --i) { + if (queues[i].next_nonempty != UnlinkedTag()) { + cur->next_nonempty = queues[i].next_nonempty; + queues[i].next_nonempty = cur; return; } } - cur->next = first; + cur->next_nonempty = first; first = cur; } - void rebalance(u32 priority) { - Queue *cur = &queues[priority]; - int size = cur->end - cur->first; - if (size >= cur->capacity - 2) { - IdType *new_data = (IdType *)realloc(cur->data, cur->capacity * 2 * sizeof(IdType)); - if (new_data != nullptr) { - cur->capacity *= 2; - cur->data = new_data; - } - } - - int newFirst = (cur->capacity - size) / 2; - if (newFirst != cur->first) { - memmove(&cur->data[newFirst], &cur->data[cur->first], size * sizeof(IdType)); - cur->first = newFirst; - cur->end = newFirst + size; - } - } - // The first queue that's ever been used. - Queue *first; + Queue* first; // The priority level queues of thread ids. - Queue queues[NUM_QUEUES]; + std::array<Queue, NUM_QUEUES> queues; }; } // namespace diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index b67226d8d..8723a471f 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -31,6 +31,7 @@ set(SRCS hle/kernel/mutex.cpp hle/kernel/semaphore.cpp hle/kernel/shared_memory.cpp + hle/kernel/timer.cpp hle/kernel/thread.cpp hle/service/ac_u.cpp hle/service/act_u.cpp @@ -123,6 +124,7 @@ set(HEADERS hle/kernel/semaphore.h hle/kernel/session.h hle/kernel/shared_memory.h + hle/kernel/timer.h hle/kernel/thread.h hle/service/ac_u.h hle/service/act_u.h diff --git a/src/core/arm/arm_interface.h b/src/core/arm/arm_interface.h index 3b7209418..e612f7439 100644 --- a/src/core/arm/arm_interface.h +++ b/src/core/arm/arm_interface.h @@ -7,7 +7,9 @@ #include "common/common.h" #include "common/common_types.h" -#include "core/hle/svc.h" +namespace Core { + struct ThreadContext; +} /// Generic ARM11 CPU interface class ARM_Interface : NonCopyable { @@ -87,13 +89,13 @@ public: * Saves the current CPU context * @param ctx Thread context to save */ - virtual void SaveContext(ThreadContext& ctx) = 0; + virtual void SaveContext(Core::ThreadContext& ctx) = 0; /** * Loads a CPU context * @param ctx Thread context to load */ - virtual void LoadContext(const ThreadContext& ctx) = 0; + virtual void LoadContext(const Core::ThreadContext& ctx) = 0; /// Prepare core for thread reschedule (if needed to correctly handle state) virtual void PrepareReschedule() = 0; @@ -103,6 +105,8 @@ public: return num_instructions; } + s64 down_count; ///< A decreasing counter of remaining cycles before the next event, decreased by the cpu run loop + protected: /** diff --git a/src/core/arm/dyncom/arm_dyncom.cpp b/src/core/arm/dyncom/arm_dyncom.cpp index a838fd25a..9c4cc90f2 100644 --- a/src/core/arm/dyncom/arm_dyncom.cpp +++ b/src/core/arm/dyncom/arm_dyncom.cpp @@ -9,11 +9,14 @@ #include "core/arm/dyncom/arm_dyncom.h" #include "core/arm/dyncom/arm_dyncom_interpreter.h" +#include "core/core.h" +#include "core/core_timing.h" + const static cpu_config_t s_arm11_cpu_info = { "armv6", "arm11", 0x0007b000, 0x0007f000, NONCACHE }; -ARM_DynCom::ARM_DynCom() : ticks(0) { +ARM_DynCom::ARM_DynCom() { state = std::unique_ptr<ARMul_State>(new ARMul_State); ARMul_EmulateInit(); @@ -72,11 +75,14 @@ void ARM_DynCom::SetCPSR(u32 cpsr) { } u64 ARM_DynCom::GetTicks() const { - return ticks; + // TODO(Subv): Remove ARM_DynCom::GetTicks() and use CoreTiming::GetTicks() directly once ARMemu is gone + return CoreTiming::GetTicks(); } void ARM_DynCom::AddTicks(u64 ticks) { - this->ticks += ticks; + down_count -= ticks; + if (down_count < 0) + CoreTiming::Advance(); } void ARM_DynCom::ExecuteInstructions(int num_instructions) { @@ -85,10 +91,11 @@ void ARM_DynCom::ExecuteInstructions(int num_instructions) { // Dyncom only breaks on instruction dispatch. This only happens on every instruction when // executing one instruction at a time. Otherwise, if a block is being executed, more // instructions may actually be executed than specified. - ticks += InterpreterMainLoop(state.get()); + unsigned ticks_executed = InterpreterMainLoop(state.get()); + AddTicks(ticks_executed); } -void ARM_DynCom::SaveContext(ThreadContext& ctx) { +void ARM_DynCom::SaveContext(Core::ThreadContext& ctx) { memcpy(ctx.cpu_registers, state->Reg, sizeof(ctx.cpu_registers)); memcpy(ctx.fpu_registers, state->ExtReg, sizeof(ctx.fpu_registers)); @@ -104,7 +111,7 @@ void ARM_DynCom::SaveContext(ThreadContext& ctx) { ctx.mode = state->NextInstr; } -void ARM_DynCom::LoadContext(const ThreadContext& ctx) { +void ARM_DynCom::LoadContext(const Core::ThreadContext& ctx) { memcpy(state->Reg, ctx.cpu_registers, sizeof(ctx.cpu_registers)); memcpy(state->ExtReg, ctx.fpu_registers, sizeof(ctx.fpu_registers)); diff --git a/src/core/arm/dyncom/arm_dyncom.h b/src/core/arm/dyncom/arm_dyncom.h index 7284dcd07..f16fb070c 100644 --- a/src/core/arm/dyncom/arm_dyncom.h +++ b/src/core/arm/dyncom/arm_dyncom.h @@ -71,13 +71,13 @@ public: * Saves the current CPU context * @param ctx Thread context to save */ - void SaveContext(ThreadContext& ctx) override; + void SaveContext(Core::ThreadContext& ctx) override; /** * Loads a CPU context * @param ctx Thread context to load */ - void LoadContext(const ThreadContext& ctx) override; + void LoadContext(const Core::ThreadContext& ctx) override; /// Prepare core for thread reschedule (if needed to correctly handle state) void PrepareReschedule() override; @@ -89,8 +89,5 @@ public: void ExecuteInstructions(int num_instructions) override; private: - std::unique_ptr<ARMul_State> state; - u64 ticks; - }; diff --git a/src/core/arm/dyncom/arm_dyncom_interpreter.cpp b/src/core/arm/dyncom/arm_dyncom_interpreter.cpp index 9b291862c..e3ca02e98 100644 --- a/src/core/arm/dyncom/arm_dyncom_interpreter.cpp +++ b/src/core/arm/dyncom/arm_dyncom_interpreter.cpp @@ -947,6 +947,15 @@ typedef struct _smla_inst { unsigned int Rn; } smla_inst; +typedef struct smlalxy_inst { + unsigned int x; + unsigned int y; + unsigned int RdLo; + unsigned int RdHi; + unsigned int Rm; + unsigned int Rn; +} smlalxy_inst; + typedef struct ssat_inst { unsigned int Rn; unsigned int Rd; @@ -2403,7 +2412,25 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(smlal)(unsigned int inst, int index) return inst_base; } -ARM_INST_PTR INTERPRETER_TRANSLATE(smlalxy)(unsigned int inst, int index) { UNIMPLEMENTED_INSTRUCTION("SMLALXY"); } +ARM_INST_PTR INTERPRETER_TRANSLATE(smlalxy)(unsigned int inst, int index) +{ + arm_inst* const inst_base = (arm_inst*)AllocBuffer(sizeof(arm_inst) + sizeof(smlalxy_inst)); + smlalxy_inst* const inst_cream = (smlalxy_inst*)inst_base->component; + + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; + inst_base->load_r15 = 0; + + inst_cream->x = BIT(inst, 5); + inst_cream->y = BIT(inst, 6); + inst_cream->RdLo = BITS(inst, 12, 15); + inst_cream->RdHi = BITS(inst, 16, 19); + inst_cream->Rn = BITS(inst, 0, 4); + inst_cream->Rm = BITS(inst, 8, 11); + + return inst_base; +} ARM_INST_PTR INTERPRETER_TRANSLATE(smlaw)(unsigned int inst, int index) { @@ -5686,6 +5713,34 @@ unsigned InterpreterMainLoop(ARMul_State* state) { } SMLALXY_INST: + { + if (inst_base->cond == 0xE || CondPassed(cpu, inst_base->cond)) { + smlalxy_inst* const inst_cream = (smlalxy_inst*)inst_base->component; + + u64 operand1 = RN; + u64 operand2 = RM; + + if (inst_cream->x != 0) + operand1 >>= 16; + if (inst_cream->y != 0) + operand2 >>= 16; + operand1 &= 0xFFFF; + if (operand1 & 0x8000) + operand1 -= 65536; + operand2 &= 0xFFFF; + if (operand2 & 0x8000) + operand2 -= 65536; + + u64 dest = ((u64)RDHI << 32 | RDLO) + (operand1 * operand2); + RDLO = (dest & 0xFFFFFFFF); + RDHI = ((dest >> 32) & 0xFFFFFFFF); + } + + cpu->Reg[15] += GET_INST_SIZE(cpu); + INC_PC(sizeof(smlalxy_inst)); + FETCH_INST; + GOTO_NEXT_INST; + } SMLAW_INST: { @@ -5836,16 +5891,13 @@ unsigned InterpreterMainLoop(ARMul_State* state) { SMULW_INST: { - if ((inst_base->cond == 0xe) || CondPassed(cpu, inst_base->cond)) { - smlad_inst *inst_cream = (smlad_inst *)inst_base->component; - int64_t rm = RM; - int64_t rn = RN; - if (inst_cream->m) - rm = BITS(rm, 16, 31); - else - rm = BITS(rm, 0, 15); - int64_t rst = rm * rn; - RD = BITS(rst, 16, 47); + if (inst_base->cond == 0xE || CondPassed(cpu, inst_base->cond)) { + smlad_inst* const inst_cream = (smlad_inst*)inst_base->component; + + s16 rm = (inst_cream->m == 1) ? ((RM >> 16) & 0xFFFF) : (RM & 0xFFFF); + + s64 result = (s64)rm * (s64)(s32)RN; + RD = BITS(result, 16, 47); } cpu->Reg[15] += GET_INST_SIZE(cpu); INC_PC(sizeof(smlad_inst)); @@ -6267,6 +6319,7 @@ unsigned InterpreterMainLoop(ARMul_State* state) { addr = RN; unsigned int value = Memory::Read8(addr); Memory::Write8(addr, (RM & 0xFF)); + RD = value; } cpu->Reg[15] += GET_INST_SIZE(cpu); INC_PC(sizeof(swp_inst)); @@ -6643,10 +6696,10 @@ unsigned InterpreterMainLoop(ARMul_State* state) { { if (inst_base->cond == 0xE || CondPassed(cpu, inst_base->cond)) { umaal_inst* const inst_cream = (umaal_inst*)inst_base->component; - const u32 rm = RM; - const u32 rn = RN; - const u32 rd_lo = RDLO; - const u32 rd_hi = RDHI; + const u64 rm = RM; + const u64 rn = RN; + const u64 rd_lo = RDLO; + const u64 rd_hi = RDHI; const u64 result = (rm * rn) + rd_lo + rd_hi; RDLO = (result & 0xFFFFFFFF); diff --git a/src/core/arm/interpreter/arm_interpreter.cpp b/src/core/arm/interpreter/arm_interpreter.cpp index 80ebc359e..c76d371a2 100644 --- a/src/core/arm/interpreter/arm_interpreter.cpp +++ b/src/core/arm/interpreter/arm_interpreter.cpp @@ -4,6 +4,8 @@ #include "core/arm/interpreter/arm_interpreter.h" +#include "core/core.h" + const static cpu_config_t arm11_cpu_info = { "armv6", "arm11", 0x0007b000, 0x0007f000, NONCACHE }; @@ -75,7 +77,7 @@ void ARM_Interpreter::ExecuteInstructions(int num_instructions) { ARMul_Emulate32(state); } -void ARM_Interpreter::SaveContext(ThreadContext& ctx) { +void ARM_Interpreter::SaveContext(Core::ThreadContext& ctx) { memcpy(ctx.cpu_registers, state->Reg, sizeof(ctx.cpu_registers)); memcpy(ctx.fpu_registers, state->ExtReg, sizeof(ctx.fpu_registers)); @@ -91,7 +93,7 @@ void ARM_Interpreter::SaveContext(ThreadContext& ctx) { ctx.mode = state->NextInstr; } -void ARM_Interpreter::LoadContext(const ThreadContext& ctx) { +void ARM_Interpreter::LoadContext(const Core::ThreadContext& ctx) { memcpy(state->Reg, ctx.cpu_registers, sizeof(ctx.cpu_registers)); memcpy(state->ExtReg, ctx.fpu_registers, sizeof(ctx.fpu_registers)); diff --git a/src/core/arm/interpreter/arm_interpreter.h b/src/core/arm/interpreter/arm_interpreter.h index 019dad5df..e5ecc69c2 100644 --- a/src/core/arm/interpreter/arm_interpreter.h +++ b/src/core/arm/interpreter/arm_interpreter.h @@ -70,13 +70,13 @@ public: * Saves the current CPU context * @param ctx Thread context to save */ - void SaveContext(ThreadContext& ctx) override; + void SaveContext(Core::ThreadContext& ctx) override; /** * Loads a CPU context * @param ctx Thread context to load */ - void LoadContext(const ThreadContext& ctx) override; + void LoadContext(const Core::ThreadContext& ctx) override; /// Prepare core for thread reschedule (if needed to correctly handle state) void PrepareReschedule() override; diff --git a/src/core/core.cpp b/src/core/core.cpp index 8ac4481cc..e9e5c35cc 100644 --- a/src/core/core.cpp +++ b/src/core/core.cpp @@ -5,8 +5,10 @@ #include "common/common_types.h" #include "core/core.h" +#include "core/core_timing.h" #include "core/settings.h" +#include "core/arm/arm_interface.h" #include "core/arm/disassembler/arm_disasm.h" #include "core/arm/interpreter/arm_interpreter.h" #include "core/arm/dyncom/arm_dyncom.h" @@ -16,14 +18,22 @@ namespace Core { -static u64 last_ticks = 0; ///< Last CPU ticks -static ARM_Disasm* disasm = nullptr; ///< ARM disassembler ARM_Interface* g_app_core = nullptr; ///< ARM11 application core ARM_Interface* g_sys_core = nullptr; ///< ARM11 system (OS) core /// Run the core CPU loop void RunLoop(int tight_loop) { - g_app_core->Run(tight_loop); + // If the current thread is an idle thread, then don't execute instructions, + // instead advance to the next event and try to yield to the next thread + if (Kernel::GetCurrentThread()->IsIdle()) { + LOG_TRACE(Core_ARM11, "Idling"); + CoreTiming::Idle(); + CoreTiming::Advance(); + HLE::Reschedule(__func__); + } else { + g_app_core->Run(tight_loop); + } + HW::Update(); if (HLE::g_reschedule) { Kernel::Reschedule(); @@ -49,7 +59,6 @@ void Stop() { int Init() { LOG_DEBUG(Core, "initialized OK"); - disasm = new ARM_Disasm(); g_sys_core = new ARM_Interpreter(); switch (Settings::values.cpu_core) { @@ -62,13 +71,10 @@ int Init() { break; } - last_ticks = Core::g_app_core->GetTicks(); - return 0; } void Shutdown() { - delete disasm; delete g_app_core; delete g_sys_core; diff --git a/src/core/core.h b/src/core/core.h index ecd58a73a..2f5e8bc6b 100644 --- a/src/core/core.h +++ b/src/core/core.h @@ -4,8 +4,9 @@ #pragma once -#include "core/arm/arm_interface.h" -#include "core/arm/skyeye_common/armdefs.h" +#include "common/common_types.h" + +class ARM_Interface; //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -16,6 +17,21 @@ enum CPUCore { CPU_OldInterpreter, }; +struct ThreadContext { + u32 cpu_registers[13]; + u32 sp; + u32 lr; + u32 pc; + u32 cpsr; + u32 fpu_registers[32]; + u32 fpscr; + u32 fpexc; + + // These are not part of native ThreadContext, but needed by emu + u32 reg_15; + u32 mode; +}; + extern ARM_Interface* g_app_core; ///< ARM11 application core extern ARM_Interface* g_sys_core; ///< ARM11 system (OS) core diff --git a/src/core/core_timing.cpp b/src/core/core_timing.cpp index 321648b37..ec9d52a08 100644 --- a/src/core/core_timing.cpp +++ b/src/core/core_timing.cpp @@ -1,16 +1,16 @@ -// Copyright 2013 Dolphin Emulator Project / 2014 Citra Emulator Project +// Copyright (c) 2012- PPSSPP Project / Dolphin Project. // Licensed under GPLv2 or any later version // Refer to the license.txt file included. -#include <vector> -#include <cstdio> #include <atomic> +#include <cstdio> #include <mutex> +#include <vector> #include "common/chunk_file.h" -#include "common/msg_handler.h" -#include "common/string_util.h" +#include "common/log.h" +#include "core/arm/arm_interface.h" #include "core/core.h" #include "core/core_timing.h" @@ -22,16 +22,15 @@ int g_clock_rate_arm11 = 268123480; namespace CoreTiming { - struct EventType { EventType() {} - EventType(TimedCallback cb, const char *n) + EventType(TimedCallback cb, const char* n) : callback(cb), name(n) {} TimedCallback callback; - const char *name; + const char* name; }; std::vector<EventType> event_types; @@ -41,262 +40,247 @@ struct BaseEvent s64 time; u64 userdata; int type; - // Event *next; }; typedef LinkedListItem<BaseEvent> Event; -Event *first; -Event *tsFirst; -Event *tsLast; +Event* first; +Event* ts_first; +Event* ts_last; // event pools -Event *eventPool = 0; -Event *eventTsPool = 0; -int allocatedTsEvents = 0; +Event* event_pool = 0; +Event* event_ts_pool = 0; +int allocated_ts_events = 0; // Optimization to skip MoveEvents when possible. -std::atomic<u32> hasTsEvents; +std::atomic<bool> has_ts_events(false); -// Downcount has been moved to currentMIPS, to save a couple of clocks in every ARM JIT block -// as we can already reach that structure through a register. -int slicelength; +int g_slice_length; -MEMORY_ALIGNED16(s64) globalTimer; -s64 idledCycles; +s64 global_timer; +s64 idled_cycles; +s64 last_global_time_ticks; +s64 last_global_time_us; -static std::recursive_mutex externalEventSection; +static std::recursive_mutex external_event_section; // Warning: not included in save state. -void(*advanceCallback)(int cyclesExecuted) = nullptr; +using AdvanceCallback = void(int cycles_executed); +AdvanceCallback* advance_callback = nullptr; +std::vector<MHzChangeCallback> mhz_change_callbacks; -void SetClockFrequencyMHz(int cpuMhz) -{ - g_clock_rate_arm11 = cpuMhz * 1000000; +void FireMhzChange() { + for (auto callback : mhz_change_callbacks) + callback(); +} + +void SetClockFrequencyMHz(int cpu_mhz) { + // When the mhz changes, we keep track of what "time" it was before hand. + // This way, time always moves forward, even if mhz is changed. + last_global_time_us = GetGlobalTimeUs(); + last_global_time_ticks = GetTicks(); + + g_clock_rate_arm11 = cpu_mhz * 1000000; // TODO: Rescale times of scheduled events? + + FireMhzChange(); } -int GetClockFrequencyMHz() -{ +int GetClockFrequencyMHz() { return g_clock_rate_arm11 / 1000000; } +u64 GetGlobalTimeUs() { + s64 ticks_since_last = GetTicks() - last_global_time_ticks; + int freq = GetClockFrequencyMHz(); + s64 us_since_last = ticks_since_last / freq; + return last_global_time_us + us_since_last; +} -Event* GetNewEvent() -{ - if (!eventPool) +Event* GetNewEvent() { + if (!event_pool) return new Event; - Event* ev = eventPool; - eventPool = ev->next; - return ev; + Event* event = event_pool; + event_pool = event->next; + return event; } -Event* GetNewTsEvent() -{ - allocatedTsEvents++; +Event* GetNewTsEvent() { + allocated_ts_events++; - if (!eventTsPool) + if (!event_ts_pool) return new Event; - Event* ev = eventTsPool; - eventTsPool = ev->next; - return ev; + Event* event = event_ts_pool; + event_ts_pool = event->next; + return event; } -void FreeEvent(Event* ev) -{ - ev->next = eventPool; - eventPool = ev; +void FreeEvent(Event* event) { + event->next = event_pool; + event_pool = event; } -void FreeTsEvent(Event* ev) -{ - ev->next = eventTsPool; - eventTsPool = ev; - allocatedTsEvents--; +void FreeTsEvent(Event* event) { + event->next = event_ts_pool; + event_ts_pool = event; + allocated_ts_events--; } -int RegisterEvent(const char *name, TimedCallback callback) -{ +int RegisterEvent(const char* name, TimedCallback callback) { event_types.push_back(EventType(callback, name)); return (int)event_types.size() - 1; } -void AntiCrashCallback(u64 userdata, int cyclesLate) -{ - LOG_CRITICAL(Core, "Savestate broken: an unregistered event was called."); +void AntiCrashCallback(u64 userdata, int cycles_late) { + LOG_CRITICAL(Core_Timing, "Savestate broken: an unregistered event was called."); Core::Halt("invalid timing events"); } -void RestoreRegisterEvent(int event_type, const char *name, TimedCallback callback) -{ +void RestoreRegisterEvent(int event_type, const char* name, TimedCallback callback) { if (event_type >= (int)event_types.size()) event_types.resize(event_type + 1, EventType(AntiCrashCallback, "INVALID EVENT")); event_types[event_type] = EventType(callback, name); } -void UnregisterAllEvents() -{ +void UnregisterAllEvents() { if (first) PanicAlert("Cannot unregister events with events pending"); event_types.clear(); } -void Init() -{ - //currentMIPS->downcount = INITIAL_SLICE_LENGTH; - //slicelength = INITIAL_SLICE_LENGTH; - globalTimer = 0; - idledCycles = 0; - hasTsEvents = 0; +void Init() { + Core::g_app_core->down_count = INITIAL_SLICE_LENGTH; + g_slice_length = INITIAL_SLICE_LENGTH; + global_timer = 0; + idled_cycles = 0; + last_global_time_ticks = 0; + last_global_time_us = 0; + has_ts_events = 0; + mhz_change_callbacks.clear(); } -void Shutdown() -{ +void Shutdown() { MoveEvents(); ClearPendingEvents(); UnregisterAllEvents(); - while (eventPool) - { - Event *ev = eventPool; - eventPool = ev->next; - delete ev; + while (event_pool) { + Event* event = event_pool; + event_pool = event->next; + delete event; } - std::lock_guard<std::recursive_mutex> lk(externalEventSection); - while (eventTsPool) - { - Event *ev = eventTsPool; - eventTsPool = ev->next; - delete ev; + std::lock_guard<std::recursive_mutex> lock(external_event_section); + while (event_ts_pool) { + Event* event = event_ts_pool; + event_ts_pool = event->next; + delete event; } } -u64 GetTicks() -{ - LOG_ERROR(Core, "Unimplemented function!"); - return 0; - //return (u64)globalTimer + slicelength - currentMIPS->downcount; +u64 GetTicks() { + return (u64)global_timer + g_slice_length - Core::g_app_core->down_count; } -u64 GetIdleTicks() -{ - return (u64)idledCycles; +u64 GetIdleTicks() { + return (u64)idled_cycles; } // This is to be called when outside threads, such as the graphics thread, wants to // schedule things to be executed on the main thread. -void ScheduleEvent_Threadsafe(s64 cyclesIntoFuture, int event_type, u64 userdata) -{ - std::lock_guard<std::recursive_mutex> lk(externalEventSection); - Event *ne = GetNewTsEvent(); - ne->time = GetTicks() + cyclesIntoFuture; - ne->type = event_type; - ne->next = 0; - ne->userdata = userdata; - if (!tsFirst) - tsFirst = ne; - if (tsLast) - tsLast->next = ne; - tsLast = ne; - - hasTsEvents.store(1, std::memory_order_release); +void ScheduleEvent_Threadsafe(s64 cycles_into_future, int event_type, u64 userdata) { + std::lock_guard<std::recursive_mutex> lock(external_event_section); + Event* new_event = GetNewTsEvent(); + new_event->time = GetTicks() + cycles_into_future; + new_event->type = event_type; + new_event->next = 0; + new_event->userdata = userdata; + if (!ts_first) + ts_first = new_event; + if (ts_last) + ts_last->next = new_event; + ts_last = new_event; + + has_ts_events = true; } // Same as ScheduleEvent_Threadsafe(0, ...) EXCEPT if we are already on the CPU thread // in which case the event will get handled immediately, before returning. -void ScheduleEvent_Threadsafe_Immediate(int event_type, u64 userdata) -{ +void ScheduleEvent_Threadsafe_Immediate(int event_type, u64 userdata) { if (false) //Core::IsCPUThread()) { - std::lock_guard<std::recursive_mutex> lk(externalEventSection); + std::lock_guard<std::recursive_mutex> lock(external_event_section); event_types[event_type].callback(userdata, 0); } else ScheduleEvent_Threadsafe(0, event_type, userdata); } -void ClearPendingEvents() -{ - while (first) - { - Event *e = first->next; +void ClearPendingEvents() { + while (first) { + Event* event = first->next; FreeEvent(first); - first = e; + first = event; } } -void AddEventToQueue(Event* ne) -{ - Event* prev = nullptr; - Event** pNext = &first; - for (;;) - { - Event*& next = *pNext; - if (!next || ne->time < next->time) - { - ne->next = next; - next = ne; +void AddEventToQueue(Event* new_event) { + Event* prev_event = nullptr; + Event** next_event = &first; + for (;;) { + Event*& next = *next_event; + if (!next || new_event->time < next->time) { + new_event->next = next; + next = new_event; break; } - prev = next; - pNext = &prev->next; + prev_event = next; + next_event = &prev_event->next; } } -// This must be run ONLY from within the cpu thread -// cyclesIntoFuture may be VERY inaccurate if called from anything else -// than Advance -void ScheduleEvent(s64 cyclesIntoFuture, int event_type, u64 userdata) -{ - Event *ne = GetNewEvent(); - ne->userdata = userdata; - ne->type = event_type; - ne->time = GetTicks() + cyclesIntoFuture; - AddEventToQueue(ne); +void ScheduleEvent(s64 cycles_into_future, int event_type, u64 userdata) { + Event* new_event = GetNewEvent(); + new_event->userdata = userdata; + new_event->type = event_type; + new_event->time = GetTicks() + cycles_into_future; + AddEventToQueue(new_event); } -// Returns cycles left in timer. -s64 UnscheduleEvent(int event_type, u64 userdata) -{ +s64 UnscheduleEvent(int event_type, u64 userdata) { s64 result = 0; if (!first) return result; - while (first) - { - if (first->type == event_type && first->userdata == userdata) - { - result = first->time - globalTimer; + while (first) { + if (first->type == event_type && first->userdata == userdata) { + result = first->time - GetTicks(); - Event *next = first->next; + Event* next = first->next; FreeEvent(first); first = next; - } - else - { + } else { break; } } if (!first) return result; - Event *prev = first; - Event *ptr = prev->next; - while (ptr) - { - if (ptr->type == event_type && ptr->userdata == userdata) - { - result = ptr->time - globalTimer; - prev->next = ptr->next; + Event* prev_event = first; + Event* ptr = prev_event->next; + + while (ptr) { + if (ptr->type == event_type && ptr->userdata == userdata) { + result = ptr->time - GetTicks(); + + prev_event->next = ptr->next; FreeEvent(ptr); - ptr = prev->next; - } - else - { - prev = ptr; + ptr = prev_event->next; + } else { + prev_event = ptr; ptr = ptr->next; } } @@ -304,51 +288,44 @@ s64 UnscheduleEvent(int event_type, u64 userdata) return result; } -s64 UnscheduleThreadsafeEvent(int event_type, u64 userdata) -{ +s64 UnscheduleThreadsafeEvent(int event_type, u64 userdata) { s64 result = 0; - std::lock_guard<std::recursive_mutex> lk(externalEventSection); - if (!tsFirst) + std::lock_guard<std::recursive_mutex> lock(external_event_section); + if (!ts_first) return result; - while (tsFirst) - { - if (tsFirst->type == event_type && tsFirst->userdata == userdata) - { - result = tsFirst->time - globalTimer; - Event *next = tsFirst->next; - FreeTsEvent(tsFirst); - tsFirst = next; - } - else - { + while (ts_first) { + if (ts_first->type == event_type && ts_first->userdata == userdata) { + result = ts_first->time - GetTicks(); + + Event* next = ts_first->next; + FreeTsEvent(ts_first); + ts_first = next; + } else { break; } } - if (!tsFirst) + + if (!ts_first) { - tsLast = nullptr; + ts_last = nullptr; return result; } - Event *prev = tsFirst; - Event *ptr = prev->next; - while (ptr) - { - if (ptr->type == event_type && ptr->userdata == userdata) - { - result = ptr->time - globalTimer; - - prev->next = ptr->next; - if (ptr == tsLast) - tsLast = prev; - FreeTsEvent(ptr); - ptr = prev->next; - } - else - { - prev = ptr; - ptr = ptr->next; + Event* prev_event = ts_first; + Event* next = prev_event->next; + while (next) { + if (next->type == event_type && next->userdata == userdata) { + result = next->time - GetTicks(); + + prev_event->next = next->next; + if (next == ts_last) + ts_last = prev_event; + FreeTsEvent(next); + next = prev_event->next; + } else { + prev_event = next; + next = next->next; } } @@ -356,271 +333,217 @@ s64 UnscheduleThreadsafeEvent(int event_type, u64 userdata) } // Warning: not included in save state. -void RegisterAdvanceCallback(void(*callback)(int cyclesExecuted)) -{ - advanceCallback = callback; +void RegisterAdvanceCallback(AdvanceCallback* callback) { + advance_callback = callback; } -bool IsScheduled(int event_type) -{ +void RegisterMHzChangeCallback(MHzChangeCallback callback) { + mhz_change_callbacks.push_back(callback); +} + +bool IsScheduled(int event_type) { if (!first) return false; - Event *e = first; - while (e) { - if (e->type == event_type) + Event* event = first; + while (event) { + if (event->type == event_type) return true; - e = e->next; + event = event->next; } return false; } -void RemoveEvent(int event_type) -{ +void RemoveEvent(int event_type) { if (!first) return; - while (first) - { - if (first->type == event_type) - { + while (first) { + if (first->type == event_type) { Event *next = first->next; FreeEvent(first); first = next; - } - else - { + } else { break; } } if (!first) return; - Event *prev = first; - Event *ptr = prev->next; - while (ptr) - { - if (ptr->type == event_type) - { - prev->next = ptr->next; - FreeEvent(ptr); - ptr = prev->next; - } - else - { - prev = ptr; - ptr = ptr->next; + Event* prev = first; + Event* next = prev->next; + while (next) { + if (next->type == event_type) { + prev->next = next->next; + FreeEvent(next); + next = prev->next; + } else { + prev = next; + next = next->next; } } } -void RemoveThreadsafeEvent(int event_type) -{ - std::lock_guard<std::recursive_mutex> lk(externalEventSection); - if (!tsFirst) - { +void RemoveThreadsafeEvent(int event_type) { + std::lock_guard<std::recursive_mutex> lock(external_event_section); + if (!ts_first) return; - } - while (tsFirst) - { - if (tsFirst->type == event_type) - { - Event *next = tsFirst->next; - FreeTsEvent(tsFirst); - tsFirst = next; - } - else - { + + while (ts_first) { + if (ts_first->type == event_type) { + Event* next = ts_first->next; + FreeTsEvent(ts_first); + ts_first = next; + } else { break; } } - if (!tsFirst) - { - tsLast = nullptr; + + if (!ts_first) { + ts_last = nullptr; return; } - Event *prev = tsFirst; - Event *ptr = prev->next; - while (ptr) - { - if (ptr->type == event_type) - { - prev->next = ptr->next; - if (ptr == tsLast) - tsLast = prev; - FreeTsEvent(ptr); - ptr = prev->next; - } - else - { - prev = ptr; - ptr = ptr->next; + + Event* prev = ts_first; + Event* next = prev->next; + while (next) { + if (next->type == event_type) { + prev->next = next->next; + if (next == ts_last) + ts_last = prev; + FreeTsEvent(next); + next = prev->next; + } else { + prev = next; + next = next->next; } } } -void RemoveAllEvents(int event_type) -{ +void RemoveAllEvents(int event_type) { RemoveThreadsafeEvent(event_type); RemoveEvent(event_type); } -//This raise only the events required while the fifo is processing data -void ProcessFifoWaitEvents() -{ - while (first) - { - if (first->time <= globalTimer) - { - //LOG(TIMER, "[Scheduler] %s (%lld, %lld) ", - // first->name ? first->name : "?", (u64)globalTimer, (u64)first->time); +// This raise only the events required while the fifo is processing data +void ProcessFifoWaitEvents() { + while (first) { + if (first->time <= (s64)GetTicks()) { Event* evt = first; first = first->next; - event_types[evt->type].callback(evt->userdata, (int)(globalTimer - evt->time)); + event_types[evt->type].callback(evt->userdata, (int)(GetTicks() - evt->time)); FreeEvent(evt); - } - else - { + } else { break; } } } -void MoveEvents() -{ - hasTsEvents.store(0, std::memory_order_release); +void MoveEvents() { + has_ts_events = false; - std::lock_guard<std::recursive_mutex> lk(externalEventSection); + std::lock_guard<std::recursive_mutex> lock(external_event_section); // Move events from async queue into main queue - while (tsFirst) - { - Event *next = tsFirst->next; - AddEventToQueue(tsFirst); - tsFirst = next; + while (ts_first) { + Event* next = ts_first->next; + AddEventToQueue(ts_first); + ts_first = next; } - tsLast = nullptr; + ts_last = nullptr; // Move free events to threadsafe pool - while (allocatedTsEvents > 0 && eventPool) - { - Event *ev = eventPool; - eventPool = ev->next; - ev->next = eventTsPool; - eventTsPool = ev; - allocatedTsEvents--; + while (allocated_ts_events > 0 && event_pool) { + Event* event = event_pool; + event_pool = event->next; + event->next = event_ts_pool; + event_ts_pool = event; + allocated_ts_events--; } } -void Advance() -{ - LOG_ERROR(Core, "Unimplemented function!"); - //int cyclesExecuted = slicelength - currentMIPS->downcount; - //globalTimer += cyclesExecuted; - //currentMIPS->downcount = slicelength; - - //if (Common::AtomicLoadAcquire(hasTsEvents)) - // MoveEvents(); - //ProcessFifoWaitEvents(); - - //if (!first) - //{ - // // WARN_LOG(TIMER, "WARNING - no events in queue. Setting currentMIPS->downcount to 10000"); - // currentMIPS->downcount += 10000; - //} - //else - //{ - // slicelength = (int)(first->time - globalTimer); - // if (slicelength > MAX_SLICE_LENGTH) - // slicelength = MAX_SLICE_LENGTH; - // currentMIPS->downcount = slicelength; - //} - //if (advanceCallback) - // advanceCallback(cyclesExecuted); -} - -void LogPendingEvents() -{ - Event *ptr = first; - while (ptr) - { - //INFO_LOG(TIMER, "PENDING: Now: %lld Pending: %lld Type: %d", globalTimer, ptr->time, ptr->type); - ptr = ptr->next; - } +void ForceCheck() { + int cycles_executed = g_slice_length - Core::g_app_core->down_count; + global_timer += cycles_executed; + // This will cause us to check for new events immediately. + Core::g_app_core->down_count = 0; + // But let's not eat a bunch more time in Advance() because of this. + g_slice_length = 0; } -void Idle(int maxIdle) -{ - LOG_ERROR(Core, "Unimplemented function!"); - //int cyclesDown = currentMIPS->downcount; - //if (maxIdle != 0 && cyclesDown > maxIdle) - // cyclesDown = maxIdle; - - //if (first && cyclesDown > 0) - //{ - // int cyclesExecuted = slicelength - currentMIPS->downcount; - // int cyclesNextEvent = (int) (first->time - globalTimer); - - // if (cyclesNextEvent < cyclesExecuted + cyclesDown) - // { - // cyclesDown = cyclesNextEvent - cyclesExecuted; - // // Now, now... no time machines, please. - // if (cyclesDown < 0) - // cyclesDown = 0; - // } - //} - - //INFO_LOG(TIME, "Idle for %i cycles! (%f ms)", cyclesDown, cyclesDown / (float)(g_clock_rate_arm11 * 0.001f)); - - //idledCycles += cyclesDown; - //currentMIPS->downcount -= cyclesDown; - //if (currentMIPS->downcount == 0) - // currentMIPS->downcount = -1; -} - -std::string GetScheduledEventsSummary() -{ - Event *ptr = first; - std::string text = "Scheduled events\n"; - text.reserve(1000); - while (ptr) - { - unsigned int t = ptr->type; - if (t >= event_types.size()) - PanicAlert("Invalid event type"); // %i", t); - const char *name = event_types[ptr->type].name; - if (!name) - name = "[unknown]"; +void Advance() { + int cycles_executed = g_slice_length - Core::g_app_core->down_count; + global_timer += cycles_executed; + Core::g_app_core->down_count = g_slice_length; - text += Common::StringFromFormat("%s : %i %08x%08x\n", name, (int)ptr->time, - (u32)(ptr->userdata >> 32), (u32)(ptr->userdata)); + if (has_ts_events) + MoveEvents(); + ProcessFifoWaitEvents(); - ptr = ptr->next; + if (!first) { + if (g_slice_length < 10000) { + g_slice_length += 10000; + Core::g_app_core->down_count += g_slice_length; + } + } else { + // Note that events can eat cycles as well. + int target = (int)(first->time - global_timer); + if (target > MAX_SLICE_LENGTH) + target = MAX_SLICE_LENGTH; + + const int diff = target - g_slice_length; + g_slice_length += diff; + Core::g_app_core->down_count += diff; } - return text; + if (advance_callback) + advance_callback(cycles_executed); } -void Event_DoState(PointerWrap &p, BaseEvent *ev) -{ - p.Do(*ev); +void LogPendingEvents() { + Event* event = first; + while (event) { + //LOG_TRACE(Core_Timing, "PENDING: Now: %lld Pending: %lld Type: %d", globalTimer, next->time, next->type); + event = event->next; + } } -void DoState(PointerWrap &p) -{ - std::lock_guard<std::recursive_mutex> lk(externalEventSection); +void Idle(int max_idle) { + int cycles_down = Core::g_app_core->down_count; + if (max_idle != 0 && cycles_down > max_idle) + cycles_down = max_idle; - auto s = p.Section("CoreTiming", 1); - if (!s) - return; + if (first && cycles_down > 0) { + int cycles_executed = g_slice_length - Core::g_app_core->down_count; + int cycles_next_event = (int)(first->time - global_timer); - int n = (int)event_types.size(); - p.Do(n); - // These (should) be filled in later by the modules. - event_types.resize(n, EventType(AntiCrashCallback, "INVALID EVENT")); + if (cycles_next_event < cycles_executed + cycles_down) { + cycles_down = cycles_next_event - cycles_executed; + // Now, now... no time machines, please. + if (cycles_down < 0) + cycles_down = 0; + } + } - p.DoLinkedList<BaseEvent, GetNewEvent, FreeEvent, Event_DoState>(first, (Event **)nullptr); - p.DoLinkedList<BaseEvent, GetNewTsEvent, FreeTsEvent, Event_DoState>(tsFirst, &tsLast); + LOG_TRACE(Core_Timing, "Idle for %i cycles! (%f ms)", cycles_down, cycles_down / (float)(g_clock_rate_arm11 * 0.001f)); - p.Do(g_clock_rate_arm11); - p.Do(slicelength); - p.Do(globalTimer); - p.Do(idledCycles); + idled_cycles += cycles_down; + Core::g_app_core->down_count -= cycles_down; + if (Core::g_app_core->down_count == 0) + Core::g_app_core->down_count = -1; +} + +std::string GetScheduledEventsSummary() { + Event* event = first; + std::string text = "Scheduled events\n"; + text.reserve(1000); + while (event) { + unsigned int t = event->type; + if (t >= event_types.size()) + PanicAlert("Invalid event type"); // %i", t); + const char* name = event_types[event->type].name; + if (!name) + name = "[unknown]"; + text += Common::StringFromFormat("%s : %i %08x%08x\n", name, (int)event->time, + (u32)(event->userdata >> 32), (u32)(event->userdata)); + event = event->next; + } + return text; } } // namespace diff --git a/src/core/core_timing.h b/src/core/core_timing.h index 496234538..d62ff3604 100644 --- a/src/core/core_timing.h +++ b/src/core/core_timing.h @@ -1,9 +1,11 @@ -// Copyright 2013 Dolphin Emulator Project / 2014 Citra Emulator Project +// Copyright (c) 2012- PPSSPP Project / Dolphin Project. // Licensed under GPLv2 or any later version // Refer to the license.txt file included. #pragma once +#include <string> + // This is a system to schedule events into the emulated machine's future. Time is measured // in main CPU clock cycles. @@ -12,14 +14,14 @@ // See HW/SystemTimers.cpp for the main part of Dolphin's usage of this scheduler. -// The int cyclesLate that the callbacks get is how many cycles late it was. +// The int cycles_late that the callbacks get is how many cycles late it was. // So to schedule a new event on a regular basis: // inside callback: -// ScheduleEvent(periodInCycles - cyclesLate, callback, "whatever") +// ScheduleEvent(periodInCycles - cycles_late, callback, "whatever") -#include "common/common.h" +#include <functional> -class PointerWrap; +#include "common/common.h" extern int g_clock_rate_arm11; @@ -55,55 +57,84 @@ inline s64 cyclesToUs(s64 cycles) { return cycles / (g_clock_rate_arm11 / 1000000); } -namespace CoreTiming { +inline u64 cyclesToMs(s64 cycles) { + return cycles / (g_clock_rate_arm11 / 1000); +} +namespace CoreTiming +{ void Init(); void Shutdown(); -typedef void(*TimedCallback)(u64 userdata, int cyclesLate); +typedef void(*MHzChangeCallback)(); +typedef std::function<void(u64 userdata, int cycles_late)> TimedCallback; u64 GetTicks(); u64 GetIdleTicks(); - -// Returns the event_type identifier. -int RegisterEvent(const char *name, TimedCallback callback); -// For save states. +u64 GetGlobalTimeUs(); + +/** + * Registers an event type with the specified name and callback + * @param name Name of the event type + * @param callback Function that will execute when this event fires + * @returns An identifier for the event type that was registered + */ +int RegisterEvent(const char* name, TimedCallback callback); +/// For save states. void RestoreRegisterEvent(int event_type, const char *name, TimedCallback callback); void UnregisterAllEvents(); -// userdata MAY NOT CONTAIN POINTERS. userdata might get written and reloaded from disk, -// when we implement state saves. -void ScheduleEvent(s64 cyclesIntoFuture, int event_type, u64 userdata = 0); -void ScheduleEvent_Threadsafe(s64 cyclesIntoFuture, int event_type, u64 userdata = 0); +/// userdata MAY NOT CONTAIN POINTERS. userdata might get written and reloaded from disk, +/// when we implement state saves. +/** + * Schedules an event to run after the specified number of cycles, + * with an optional parameter to be passed to the callback handler. + * This must be run ONLY from within the cpu thread. + * @param cycles_into_future The number of cycles after which this event will be fired + * @param event_type The event type to fire, as returned from RegisterEvent + * @param userdata Optional parameter to pass to the callback when fired + */ +void ScheduleEvent(s64 cycles_into_future, int event_type, u64 userdata = 0); + +void ScheduleEvent_Threadsafe(s64 cycles_into_future, int event_type, u64 userdata = 0); void ScheduleEvent_Threadsafe_Immediate(int event_type, u64 userdata = 0); + +/** + * Unschedules an event with the specified type and userdata + * @param event_type The type of event to unschedule, as returned from RegisterEvent + * @param userdata The userdata that identifies this event, as passed to ScheduleEvent + * @returns The remaining ticks until the next invocation of the event callback + */ s64 UnscheduleEvent(int event_type, u64 userdata); + s64 UnscheduleThreadsafeEvent(int event_type, u64 userdata); void RemoveEvent(int event_type); void RemoveThreadsafeEvent(int event_type); void RemoveAllEvents(int event_type); bool IsScheduled(int event_type); +/// Runs any pending events and updates downcount for the next slice of cycles void Advance(); void MoveEvents(); void ProcessFifoWaitEvents(); +void ForceCheck(); -// Pretend that the main CPU has executed enough cycles to reach the next event. +/// Pretend that the main CPU has executed enough cycles to reach the next event. void Idle(int maxIdle = 0); -// Clear all pending events. This should ONLY be done on exit or state load. +/// Clear all pending events. This should ONLY be done on exit or state load. void ClearPendingEvents(); void LogPendingEvents(); -// Warning: not included in save states. -void RegisterAdvanceCallback(void(*callback)(int cyclesExecuted)); +/// Warning: not included in save states. +void RegisterAdvanceCallback(void(*callback)(int cycles_executed)); +void RegisterMHzChangeCallback(MHzChangeCallback callback); std::string GetScheduledEventsSummary(); -void DoState(PointerWrap &p); - -void SetClockFrequencyMHz(int cpuMhz); +void SetClockFrequencyMHz(int cpu_mhz); int GetClockFrequencyMHz(); -extern int slicelength; +extern int g_slice_length; } // namespace diff --git a/src/core/file_sys/archive_extsavedata.cpp b/src/core/file_sys/archive_extsavedata.cpp index 4759ef3ae..0805f42ae 100644 --- a/src/core/file_sys/archive_extsavedata.cpp +++ b/src/core/file_sys/archive_extsavedata.cpp @@ -9,6 +9,7 @@ #include "core/file_sys/archive_extsavedata.h" #include "core/file_sys/disk_archive.h" +#include "core/hle/service/fs/archive.h" #include "core/settings.h" //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -19,15 +20,22 @@ namespace FileSys { static std::string GetExtSaveDataPath(const std::string& mount_point, const Path& path) { std::vector<u8> vec_data = path.AsBinary(); const u32* data = reinterpret_cast<const u32*>(vec_data.data()); - u32 media_type = data[0]; u32 save_low = data[1]; u32 save_high = data[2]; - return Common::StringFromFormat("%s%s/%08X/%08X/", mount_point.c_str(), media_type == 0 ? "nand" : "sdmc", save_high, save_low); + return Common::StringFromFormat("%s%08X/%08X/", mount_point.c_str(), save_high, save_low); } -Archive_ExtSaveData::Archive_ExtSaveData(const std::string& mount_point) - : DiskArchive(mount_point), concrete_mount_point(mount_point) { - LOG_INFO(Service_FS, "Directory %s set as base for ExtSaveData.", this->mount_point.c_str()); +static std::string GetExtDataContainerPath(const std::string& mount_point, bool shared) { + if (shared) + return Common::StringFromFormat("%sdata/%s/extdata/", mount_point.c_str(), SYSTEM_ID.c_str()); + + return Common::StringFromFormat("%sNintendo 3DS/%s/%s/extdata/", mount_point.c_str(), + SYSTEM_ID.c_str(), SDCARD_ID.c_str()); +} + +Archive_ExtSaveData::Archive_ExtSaveData(const std::string& mount_location, bool shared) + : DiskArchive(GetExtDataContainerPath(mount_location, shared)) { + LOG_INFO(Service_FS, "Directory %s set as base for ExtSaveData.", mount_point.c_str()); } bool Archive_ExtSaveData::Initialize() { diff --git a/src/core/file_sys/archive_extsavedata.h b/src/core/file_sys/archive_extsavedata.h index a3a144799..fb7f209d2 100644 --- a/src/core/file_sys/archive_extsavedata.h +++ b/src/core/file_sys/archive_extsavedata.h @@ -17,7 +17,7 @@ namespace FileSys { /// File system interface to the ExtSaveData archive class Archive_ExtSaveData final : public DiskArchive { public: - Archive_ExtSaveData(const std::string& mount_point); + Archive_ExtSaveData(const std::string& mount_point, bool shared); /** * Initialize the archive. diff --git a/src/core/file_sys/archive_savedata.cpp b/src/core/file_sys/archive_savedata.cpp index 280d4ff5d..3baee5294 100644 --- a/src/core/file_sys/archive_savedata.cpp +++ b/src/core/file_sys/archive_savedata.cpp @@ -9,6 +9,7 @@ #include "core/file_sys/archive_savedata.h" #include "core/file_sys/disk_archive.h" +#include "core/hle/service/fs/archive.h" #include "core/settings.h" //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -16,14 +17,25 @@ namespace FileSys { -Archive_SaveData::Archive_SaveData(const std::string& mount_point) - : DiskArchive(mount_point) { +static std::string GetSaveDataContainerPath(const std::string& sdmc_directory) { + return Common::StringFromFormat("%sNintendo 3DS/%s/%s/title/", sdmc_directory.c_str(), + SYSTEM_ID.c_str(), SDCARD_ID.c_str()); +} + +static std::string GetSaveDataPath(const std::string& mount_location, u64 program_id) { + u32 high = program_id >> 32; + u32 low = program_id & 0xFFFFFFFF; + return Common::StringFromFormat("%s%08x/%08x/data/00000001/", mount_location.c_str(), high, low); +} + +Archive_SaveData::Archive_SaveData(const std::string& sdmc_directory) + : DiskArchive(GetSaveDataContainerPath(sdmc_directory)) { LOG_INFO(Service_FS, "Directory %s set as SaveData.", this->mount_point.c_str()); } ResultCode Archive_SaveData::Open(const Path& path) { if (concrete_mount_point.empty()) - concrete_mount_point = Common::StringFromFormat("%s%016X", mount_point.c_str(), Kernel::g_program_id) + DIR_SEP; + concrete_mount_point = GetSaveDataPath(mount_point, Kernel::g_program_id); if (!FileUtil::Exists(concrete_mount_point)) { // When a SaveData archive is created for the first time, it is not yet formatted // and the save file/directory structure expected by the game has not yet been initialized. diff --git a/src/core/file_sys/archive_savedatacheck.cpp b/src/core/file_sys/archive_savedatacheck.cpp index 233158a0c..a7a507536 100644 --- a/src/core/file_sys/archive_savedatacheck.cpp +++ b/src/core/file_sys/archive_savedatacheck.cpp @@ -5,13 +5,24 @@ #include "common/file_util.h" #include "core/file_sys/archive_savedatacheck.h" +#include "core/hle/service/fs/archive.h" //////////////////////////////////////////////////////////////////////////////////////////////////// // FileSys namespace namespace FileSys { -Archive_SaveDataCheck::Archive_SaveDataCheck(const std::string& mount_loc) : mount_point(mount_loc) { +static std::string GetSaveDataCheckContainerPath(const std::string& nand_directory) { + return Common::StringFromFormat("%s%s/title/", nand_directory.c_str(), SYSTEM_ID.c_str()); +} + +static std::string GetSaveDataCheckPath(const std::string& mount_point, u32 high, u32 low) { + return Common::StringFromFormat("%s%08x/%08x/content/00000000.app.romfs", + mount_point.c_str(), high, low); +} + +Archive_SaveDataCheck::Archive_SaveDataCheck(const std::string& nand_directory) : + mount_point(GetSaveDataCheckContainerPath(nand_directory)) { } ResultCode Archive_SaveDataCheck::Open(const Path& path) { @@ -23,7 +34,7 @@ ResultCode Archive_SaveDataCheck::Open(const Path& path) { // this archive again with a different path, will corrupt the previously open file. auto vec = path.AsBinary(); const u32* data = reinterpret_cast<u32*>(vec.data()); - std::string file_path = Common::StringFromFormat("%s%08x%08x.bin", mount_point.c_str(), data[1], data[0]); + std::string file_path = GetSaveDataCheckPath(mount_point, data[1], data[0]); FileUtil::IOFile file(file_path, "rb"); std::fill(raw_data.begin(), raw_data.end(), 0); diff --git a/src/core/file_sys/archive_sdmc.cpp b/src/core/file_sys/archive_sdmc.cpp index 1c1c170b6..26b03e82f 100644 --- a/src/core/file_sys/archive_sdmc.cpp +++ b/src/core/file_sys/archive_sdmc.cpp @@ -16,8 +16,8 @@ namespace FileSys { -Archive_SDMC::Archive_SDMC(const std::string& mount_point) : DiskArchive(mount_point) { - LOG_INFO(Service_FS, "Directory %s set as SDMC.", mount_point.c_str()); +Archive_SDMC::Archive_SDMC(const std::string& sdmc_directory) : DiskArchive(sdmc_directory) { + LOG_INFO(Service_FS, "Directory %s set as SDMC.", sdmc_directory.c_str()); } bool Archive_SDMC::Initialize() { diff --git a/src/core/file_sys/archive_systemsavedata.cpp b/src/core/file_sys/archive_systemsavedata.cpp index 0da32d510..c2a5d641a 100644 --- a/src/core/file_sys/archive_systemsavedata.cpp +++ b/src/core/file_sys/archive_systemsavedata.cpp @@ -9,6 +9,7 @@ #include "core/file_sys/archive_systemsavedata.h" #include "core/file_sys/disk_archive.h" +#include "core/hle/service/fs/archive.h" #include "core/settings.h" //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -22,8 +23,12 @@ static std::string GetSystemSaveDataPath(const std::string& mount_point, u64 sav return Common::StringFromFormat("%s%08X/%08X/", mount_point.c_str(), save_low, save_high); } +static std::string GetSystemSaveDataContainerPath(const std::string& mount_point) { + return Common::StringFromFormat("%sdata/%s/sysdata/", mount_point.c_str(), SYSTEM_ID.c_str()); +} + Archive_SystemSaveData::Archive_SystemSaveData(const std::string& mount_point, u64 save_id) - : DiskArchive(GetSystemSaveDataPath(mount_point, save_id)) { + : DiskArchive(GetSystemSaveDataPath(GetSystemSaveDataContainerPath(mount_point), save_id)) { LOG_INFO(Service_FS, "Directory %s set as SystemSaveData.", this->mount_point.c_str()); } diff --git a/src/core/file_sys/archive_systemsavedata.h b/src/core/file_sys/archive_systemsavedata.h index 55d85193c..c8f5845ca 100644 --- a/src/core/file_sys/archive_systemsavedata.h +++ b/src/core/file_sys/archive_systemsavedata.h @@ -15,8 +15,6 @@ namespace FileSys { /// File system interface to the SystemSaveData archive -/// TODO(Subv): This archive should point to a location in the NAND, -/// specifically nand:/data/<ID0>/sysdata/<SaveID-Low>/<SaveID-High> class Archive_SystemSaveData final : public DiskArchive { public: Archive_SystemSaveData(const std::string& mount_point, u64 save_id); diff --git a/src/core/hle/function_wrappers.h b/src/core/hle/function_wrappers.h index 0f822f84b..a2f51b41b 100644 --- a/src/core/hle/function_wrappers.h +++ b/src/core/hle/function_wrappers.h @@ -5,6 +5,8 @@ #pragma once #include "common/common_types.h" + +#include "core/arm/arm_interface.h" #include "core/mem_map.h" #include "core/hle/hle.h" @@ -135,6 +137,12 @@ template<s32 func(u32*, u32, u32, u32, u32)> void Wrap() { FuncReturn(retval); } +template<s32 func(u32, s64, s64)> void Wrap() { + s64 param1 = ((u64)PARAM(3) << 32) | PARAM(2); + s64 param2 = ((u64)PARAM(4) << 32) | PARAM(1); + FuncReturn(func(PARAM(0), param1, param2)); +} + //////////////////////////////////////////////////////////////////////////////////////////////////// // Function wrappers that return type u32 diff --git a/src/core/hle/hle.cpp b/src/core/hle/hle.cpp index 33ac12507..5d77a1458 100644 --- a/src/core/hle/hle.cpp +++ b/src/core/hle/hle.cpp @@ -4,6 +4,7 @@ #include <vector> +#include "core/arm/arm_interface.h" #include "core/mem_map.h" #include "core/hle/hle.h" #include "core/hle/kernel/thread.h" diff --git a/src/core/hle/hle.h b/src/core/hle/hle.h index 59b770f02..3f6f9a4b5 100644 --- a/src/core/hle/hle.h +++ b/src/core/hle/hle.h @@ -4,6 +4,8 @@ #pragma once +#include <string> + #include "common/common_types.h" #include "core/core.h" diff --git a/src/core/hle/kernel/address_arbiter.cpp b/src/core/hle/kernel/address_arbiter.cpp index 736bbc36a..62e3460e1 100644 --- a/src/core/hle/kernel/address_arbiter.cpp +++ b/src/core/hle/kernel/address_arbiter.cpp @@ -30,24 +30,28 @@ public: /// Arbitrate an address ResultCode ArbitrateAddress(Handle handle, ArbitrationType type, u32 address, s32 value) { + Object* object = Kernel::g_handle_table.GetGeneric(handle).get(); + if (object == nullptr) + return InvalidHandle(ErrorModule::Kernel); + switch (type) { // Signal thread(s) waiting for arbitrate address... case ArbitrationType::Signal: // Negative value means resume all threads if (value < 0) { - ArbitrateAllThreads(handle, address); + ArbitrateAllThreads(object, address); } else { // Resume first N threads for(int i = 0; i < value; i++) - ArbitrateHighestPriorityThread(handle, address); + ArbitrateHighestPriorityThread(object, address); } break; // Wait current thread (acquire the arbiter)... case ArbitrationType::WaitIfLessThan: if ((s32)Memory::Read32(address) <= value) { - Kernel::WaitCurrentThread(WAITTYPE_ARB, handle, address); + Kernel::WaitCurrentThread(WAITTYPE_ARB, object, address); HLE::Reschedule(__func__); } break; @@ -57,7 +61,7 @@ ResultCode ArbitrateAddress(Handle handle, ArbitrationType type, u32 address, s3 s32 memory_value = Memory::Read32(address) - 1; Memory::Write32(address, memory_value); if (memory_value <= value) { - Kernel::WaitCurrentThread(WAITTYPE_ARB, handle, address); + Kernel::WaitCurrentThread(WAITTYPE_ARB, object, address); HLE::Reschedule(__func__); } break; diff --git a/src/core/hle/kernel/event.cpp b/src/core/hle/kernel/event.cpp index e43c3ee4e..271190dbe 100644 --- a/src/core/hle/kernel/event.cpp +++ b/src/core/hle/kernel/event.cpp @@ -33,11 +33,11 @@ public: ResultVal<bool> WaitSynchronization() override { bool wait = locked; if (locked) { - Handle thread = GetCurrentThreadHandle(); + Handle thread = GetCurrentThread()->GetHandle(); if (std::find(waiting_threads.begin(), waiting_threads.end(), thread) == waiting_threads.end()) { waiting_threads.push_back(thread); } - Kernel::WaitCurrentThread(WAITTYPE_EVENT, GetHandle()); + Kernel::WaitCurrentThread(WAITTYPE_EVENT, this); } if (reset_type != RESETTYPE_STICKY && !permanent_locked) { locked = true; @@ -53,7 +53,7 @@ public: * @return Result of operation, 0 on success, otherwise error code */ ResultCode SetPermanentLock(Handle handle, const bool permanent_locked) { - Event* evt = g_handle_table.Get<Event>(handle); + Event* evt = g_handle_table.Get<Event>(handle).get(); if (evt == nullptr) return InvalidHandle(ErrorModule::Kernel); evt->permanent_locked = permanent_locked; @@ -67,7 +67,7 @@ ResultCode SetPermanentLock(Handle handle, const bool permanent_locked) { * @return Result of operation, 0 on success, otherwise error code */ ResultCode SetEventLocked(const Handle handle, const bool locked) { - Event* evt = g_handle_table.Get<Event>(handle); + Event* evt = g_handle_table.Get<Event>(handle).get(); if (evt == nullptr) return InvalidHandle(ErrorModule::Kernel); if (!evt->permanent_locked) { @@ -82,13 +82,15 @@ ResultCode SetEventLocked(const Handle handle, const bool locked) { * @return Result of operation, 0 on success, otherwise error code */ ResultCode SignalEvent(const Handle handle) { - Event* evt = g_handle_table.Get<Event>(handle); + Event* evt = g_handle_table.Get<Event>(handle).get(); if (evt == nullptr) return InvalidHandle(ErrorModule::Kernel); // Resume threads waiting for event to signal bool event_caught = false; for (size_t i = 0; i < evt->waiting_threads.size(); ++i) { - ResumeThreadFromWait( evt->waiting_threads[i]); + Thread* thread = Kernel::g_handle_table.Get<Thread>(evt->waiting_threads[i]).get(); + if (thread != nullptr) + thread->ResumeFromWait(); // If any thread is signalled awake by this event, assume the event was "caught" and reset // the event. This will result in the next thread waiting on the event to block. Otherwise, @@ -110,7 +112,7 @@ ResultCode SignalEvent(const Handle handle) { * @return Result of operation, 0 on success, otherwise error code */ ResultCode ClearEvent(Handle handle) { - Event* evt = g_handle_table.Get<Event>(handle); + Event* evt = g_handle_table.Get<Event>(handle).get(); if (evt == nullptr) return InvalidHandle(ErrorModule::Kernel); if (!evt->permanent_locked) { diff --git a/src/core/hle/kernel/kernel.cpp b/src/core/hle/kernel/kernel.cpp index e59ed1b57..d3684896f 100644 --- a/src/core/hle/kernel/kernel.cpp +++ b/src/core/hle/kernel/kernel.cpp @@ -6,13 +6,15 @@ #include "common/common.h" +#include "core/arm/arm_interface.h" #include "core/core.h" #include "core/hle/kernel/kernel.h" #include "core/hle/kernel/thread.h" +#include "core/hle/kernel/timer.h" namespace Kernel { -Handle g_main_thread = 0; +SharedPtr<Thread> g_main_thread = nullptr; HandleTable g_handle_table; u64 g_program_id = 0; @@ -21,7 +23,7 @@ HandleTable::HandleTable() { Clear(); } -ResultVal<Handle> HandleTable::Create(Object* obj) { +ResultVal<Handle> HandleTable::Create(SharedPtr<Object> obj) { _dbg_assert_(Kernel, obj != nullptr); u16 slot = next_free_slot; @@ -37,22 +39,23 @@ ResultVal<Handle> HandleTable::Create(Object* obj) { // CTR-OS doesn't use generation 0, so skip straight to 1. if (next_generation >= (1 << 15)) next_generation = 1; + Handle handle = generation | (slot << 15); + if (obj->handle == INVALID_HANDLE) + obj->handle = handle; + generations[slot] = generation; - intrusive_ptr_add_ref(obj); - objects[slot] = obj; + objects[slot] = std::move(obj); - Handle handle = generation | (slot << 15); - obj->handle = handle; return MakeResult<Handle>(handle); } ResultVal<Handle> HandleTable::Duplicate(Handle handle) { - Object* object = GetGeneric(handle); + SharedPtr<Object> object = GetGeneric(handle); if (object == nullptr) { LOG_ERROR(Kernel, "Tried to duplicate invalid handle: %08X", handle); return ERR_INVALID_HANDLE; } - return Create(object); + return Create(std::move(object)); } ResultCode HandleTable::Close(Handle handle) { @@ -62,7 +65,6 @@ ResultCode HandleTable::Close(Handle handle) { size_t slot = GetSlot(handle); u16 generation = GetGeneration(handle); - intrusive_ptr_release(objects[slot]); objects[slot] = nullptr; generations[generation] = next_free_slot; @@ -77,10 +79,9 @@ bool HandleTable::IsValid(Handle handle) const { return slot < MAX_COUNT && objects[slot] != nullptr && generations[slot] == generation; } -Object* HandleTable::GetGeneric(Handle handle) const { +SharedPtr<Object> HandleTable::GetGeneric(Handle handle) const { if (handle == CurrentThread) { - // TODO(yuriks) Directly return the pointer once this is possible. - handle = GetCurrentThreadHandle(); + return GetCurrentThread(); } else if (handle == CurrentProcess) { LOG_ERROR(Kernel, "Current process (%08X) pseudo-handle not supported", CurrentProcess); return nullptr; @@ -95,8 +96,6 @@ Object* HandleTable::GetGeneric(Handle handle) const { void HandleTable::Clear() { for (size_t i = 0; i < MAX_COUNT; ++i) { generations[i] = i + 1; - if (objects[i] != nullptr) - intrusive_ptr_release(objects[i]); objects[i] = nullptr; } next_free_slot = 0; @@ -105,12 +104,13 @@ void HandleTable::Clear() { /// Initialize the kernel void Init() { Kernel::ThreadingInit(); + Kernel::TimersInit(); } /// Shutdown the kernel void Shutdown() { Kernel::ThreadingShutdown(); - + Kernel::TimersShutdown(); g_handle_table.Clear(); // Free all kernel objects } @@ -123,7 +123,9 @@ bool LoadExec(u32 entry_point) { Core::g_app_core->SetPC(entry_point); // 0x30 is the typical main thread priority I've seen used so far - g_main_thread = Kernel::SetupMainThread(0x30); + g_main_thread = Kernel::SetupMainThread(0x30, Kernel::DEFAULT_STACK_SIZE); + // Setup the idle thread + Kernel::SetupIdleThread(); return true; } diff --git a/src/core/hle/kernel/kernel.h b/src/core/hle/kernel/kernel.h index 7f86fd07d..5e5217b78 100644 --- a/src/core/hle/kernel/kernel.h +++ b/src/core/hle/kernel/kernel.h @@ -4,6 +4,8 @@ #pragma once +#include <boost/intrusive_ptr.hpp> + #include <array> #include <string> #include "common/common.h" @@ -16,6 +18,8 @@ const Handle INVALID_HANDLE = 0; namespace Kernel { +class Thread; + // TODO: Verify code const ResultCode ERR_OUT_OF_HANDLES(ErrorDescription::OutOfMemory, ErrorModule::Kernel, ErrorSummary::OutOfResource, ErrorLevel::Temporary); @@ -39,6 +43,7 @@ enum class HandleType : u32 { Process = 8, AddressArbiter = 9, Semaphore = 10, + Timer = 11 }; enum { @@ -49,7 +54,7 @@ class HandleTable; class Object : NonCopyable { friend class HandleTable; - u32 handle; + u32 handle = INVALID_HANDLE; public: virtual ~Object() {} Handle GetHandle() const { return handle; } @@ -73,7 +78,7 @@ private: unsigned int ref_count = 0; }; -// Special functions that will later be used by boost::instrusive_ptr to do automatic ref-counting +// Special functions used by boost::instrusive_ptr to do automatic ref-counting inline void intrusive_ptr_add_ref(Object* object) { ++object->ref_count; } @@ -84,6 +89,9 @@ inline void intrusive_ptr_release(Object* object) { } } +template <typename T> +using SharedPtr = boost::intrusive_ptr<T>; + /** * This class allows the creation of Handles, which are references to objects that can be tested * for validity and looked up. Here they are used to pass references to kernel objects to/from the @@ -116,7 +124,7 @@ public: * @return The created Handle or one of the following errors: * - `ERR_OUT_OF_HANDLES`: the maximum number of handles has been exceeded. */ - ResultVal<Handle> Create(Object* obj); + ResultVal<Handle> Create(SharedPtr<Object> obj); /** * Returns a new handle that points to the same object as the passed in handle. @@ -140,7 +148,7 @@ public: * Looks up a handle. * @returns Pointer to the looked-up object, or `nullptr` if the handle is not valid. */ - Object* GetGeneric(Handle handle) const; + SharedPtr<Object> GetGeneric(Handle handle) const; /** * Looks up a handle while verifying its type. @@ -148,10 +156,10 @@ public: * type differs from the handle type `T::HANDLE_TYPE`. */ template <class T> - T* Get(Handle handle) const { - Object* object = GetGeneric(handle); + SharedPtr<T> Get(Handle handle) const { + SharedPtr<Object> object = GetGeneric(handle); if (object != nullptr && object->GetHandleType() == T::HANDLE_TYPE) { - return static_cast<T*>(object); + return boost::static_pointer_cast<T>(std::move(object)); } return nullptr; } @@ -170,7 +178,7 @@ private: static u16 GetGeneration(Handle handle) { return handle & 0x7FFF; } /// Stores the Object referenced by the handle or null if the slot is empty. - std::array<Object*, MAX_COUNT> objects; + std::array<SharedPtr<Object>, MAX_COUNT> objects; /** * The value of `next_generation` when the handle was created, used to check for validity. For @@ -189,7 +197,7 @@ private: }; extern HandleTable g_handle_table; -extern Handle g_main_thread; +extern SharedPtr<Thread> g_main_thread; /// The ID code of the currently running game /// TODO(Subv): This variable should not be here, diff --git a/src/core/hle/kernel/mutex.cpp b/src/core/hle/kernel/mutex.cpp index 3dfeffc9b..853a5dd74 100644 --- a/src/core/hle/kernel/mutex.cpp +++ b/src/core/hle/kernel/mutex.cpp @@ -40,14 +40,21 @@ static MutexMap g_mutex_held_locks; * @param mutex Mutex that is to be acquired * @param thread Thread that will acquired */ -void MutexAcquireLock(Mutex* mutex, Handle thread = GetCurrentThreadHandle()) { +void MutexAcquireLock(Mutex* mutex, Handle thread = GetCurrentThread()->GetHandle()) { g_mutex_held_locks.insert(std::make_pair(thread, mutex->GetHandle())); mutex->lock_thread = thread; } -bool ReleaseMutexForThread(Mutex* mutex, Handle thread) { - MutexAcquireLock(mutex, thread); - Kernel::ResumeThreadFromWait(thread); +bool ReleaseMutexForThread(Mutex* mutex, Handle thread_handle) { + MutexAcquireLock(mutex, thread_handle); + + Thread* thread = Kernel::g_handle_table.Get<Thread>(thread_handle).get(); + if (thread == nullptr) { + LOG_ERROR(Kernel, "Called with invalid handle: %08X", thread_handle); + return false; + } + + thread->ResumeFromWait(); return true; } @@ -87,7 +94,7 @@ void ReleaseThreadMutexes(Handle thread) { // Release every mutex that the thread holds, and resume execution on the waiting threads for (MutexMap::iterator iter = locked.first; iter != locked.second; ++iter) { - Mutex* mutex = g_handle_table.Get<Mutex>(iter->second); + Mutex* mutex = g_handle_table.Get<Mutex>(iter->second).get(); ResumeWaitingThread(mutex); } @@ -115,7 +122,7 @@ bool ReleaseMutex(Mutex* mutex) { * @param handle Handle to mutex to release */ ResultCode ReleaseMutex(Handle handle) { - Mutex* mutex = Kernel::g_handle_table.Get<Mutex>(handle); + Mutex* mutex = Kernel::g_handle_table.Get<Mutex>(handle).get(); if (mutex == nullptr) return InvalidHandle(ErrorModule::Kernel); if (!ReleaseMutex(mutex)) { @@ -168,8 +175,8 @@ Handle CreateMutex(bool initial_locked, const std::string& name) { ResultVal<bool> Mutex::WaitSynchronization() { bool wait = locked; if (locked) { - waiting_threads.push_back(GetCurrentThreadHandle()); - Kernel::WaitCurrentThread(WAITTYPE_MUTEX, GetHandle()); + waiting_threads.push_back(GetCurrentThread()->GetHandle()); + Kernel::WaitCurrentThread(WAITTYPE_MUTEX, this); } else { // Lock the mutex when the first thread accesses it locked = true; diff --git a/src/core/hle/kernel/semaphore.cpp b/src/core/hle/kernel/semaphore.cpp index 6bc8066a6..88ec9a104 100644 --- a/src/core/hle/kernel/semaphore.cpp +++ b/src/core/hle/kernel/semaphore.cpp @@ -37,8 +37,8 @@ public: bool wait = !IsAvailable(); if (wait) { - Kernel::WaitCurrentThread(WAITTYPE_SEMA, GetHandle()); - waiting_threads.push(GetCurrentThreadHandle()); + Kernel::WaitCurrentThread(WAITTYPE_SEMA, this); + waiting_threads.push(GetCurrentThread()->GetHandle()); } else { --available_count; } @@ -70,7 +70,7 @@ ResultCode CreateSemaphore(Handle* handle, s32 initial_count, } ResultCode ReleaseSemaphore(s32* count, Handle handle, s32 release_count) { - Semaphore* semaphore = g_handle_table.Get<Semaphore>(handle); + Semaphore* semaphore = g_handle_table.Get<Semaphore>(handle).get(); if (semaphore == nullptr) return InvalidHandle(ErrorModule::Kernel); @@ -84,7 +84,9 @@ ResultCode ReleaseSemaphore(s32* count, Handle handle, s32 release_count) { // Notify some of the threads that the semaphore has been released // stop once the semaphore is full again or there are no more waiting threads while (!semaphore->waiting_threads.empty() && semaphore->IsAvailable()) { - Kernel::ResumeThreadFromWait(semaphore->waiting_threads.front()); + Thread* thread = Kernel::g_handle_table.Get<Thread>(semaphore->waiting_threads.front()).get(); + if (thread != nullptr) + thread->ResumeFromWait(); semaphore->waiting_threads.pop(); --semaphore->available_count; } diff --git a/src/core/hle/kernel/shared_memory.cpp b/src/core/hle/kernel/shared_memory.cpp index cea1f6fa1..5368e4728 100644 --- a/src/core/hle/kernel/shared_memory.cpp +++ b/src/core/hle/kernel/shared_memory.cpp @@ -61,7 +61,7 @@ ResultCode MapSharedMemory(u32 handle, u32 address, MemoryPermission permissions return ResultCode(ErrorDescription::InvalidAddress, ErrorModule::Kernel, ErrorSummary::InvalidArgument, ErrorLevel::Permanent); } - SharedMemory* shared_memory = Kernel::g_handle_table.Get<SharedMemory>(handle); + SharedMemory* shared_memory = Kernel::g_handle_table.Get<SharedMemory>(handle).get(); if (shared_memory == nullptr) return InvalidHandle(ErrorModule::Kernel); shared_memory->base_address = address; @@ -72,7 +72,7 @@ ResultCode MapSharedMemory(u32 handle, u32 address, MemoryPermission permissions } ResultVal<u8*> GetSharedMemoryPointer(Handle handle, u32 offset) { - SharedMemory* shared_memory = Kernel::g_handle_table.Get<SharedMemory>(handle); + SharedMemory* shared_memory = Kernel::g_handle_table.Get<SharedMemory>(handle).get(); if (shared_memory == nullptr) return InvalidHandle(ErrorModule::Kernel); if (0 != shared_memory->base_address) diff --git a/src/core/hle/kernel/thread.cpp b/src/core/hle/kernel/thread.cpp index 872df2d14..bc86a7c59 100644 --- a/src/core/hle/kernel/thread.cpp +++ b/src/core/hle/kernel/thread.cpp @@ -10,7 +10,9 @@ #include "common/common.h" #include "common/thread_queue_list.h" +#include "core/arm/arm_interface.h" #include "core/core.h" +#include "core/core_timing.h" #include "core/hle/hle.h" #include "core/hle/kernel/kernel.h" #include "core/hle/kernel/thread.h" @@ -20,64 +22,25 @@ namespace Kernel { -class Thread : public Kernel::Object { -public: - - std::string GetName() const override { return name; } - std::string GetTypeName() const override { return "Thread"; } - - static const HandleType HANDLE_TYPE = HandleType::Thread; - HandleType GetHandleType() const override { return HANDLE_TYPE; } - - inline bool IsRunning() const { return (status & THREADSTATUS_RUNNING) != 0; } - inline bool IsStopped() const { return (status & THREADSTATUS_DORMANT) != 0; } - inline bool IsReady() const { return (status & THREADSTATUS_READY) != 0; } - inline bool IsWaiting() const { return (status & THREADSTATUS_WAIT) != 0; } - inline bool IsSuspended() const { return (status & THREADSTATUS_SUSPEND) != 0; } - - ResultVal<bool> WaitSynchronization() override { - const bool wait = status != THREADSTATUS_DORMANT; - if (wait) { - Handle thread = GetCurrentThreadHandle(); - if (std::find(waiting_threads.begin(), waiting_threads.end(), thread) == waiting_threads.end()) { - waiting_threads.push_back(thread); - } - WaitCurrentThread(WAITTYPE_THREADEND, this->GetHandle()); +ResultVal<bool> Thread::WaitSynchronization() { + const bool wait = status != THREADSTATUS_DORMANT; + if (wait) { + Thread* thread = GetCurrentThread(); + if (std::find(waiting_threads.begin(), waiting_threads.end(), thread) == waiting_threads.end()) { + waiting_threads.push_back(thread); } - - return MakeResult<bool>(wait); + WaitCurrentThread(WAITTYPE_THREADEND, this); } - ThreadContext context; - - u32 thread_id; - - u32 status; - u32 entry_point; - u32 stack_top; - u32 stack_size; - - s32 initial_priority; - s32 current_priority; - - s32 processor_id; - - WaitType wait_type; - Handle wait_handle; - VAddr wait_address; - - std::vector<Handle> waiting_threads; - - std::string name; -}; + return MakeResult<bool>(wait); +} // Lists all thread ids that aren't deleted/etc. -static std::vector<Handle> thread_queue; +static std::vector<SharedPtr<Thread>> thread_list; // Lists only ready thread ids. -static Common::ThreadQueueList<Handle> thread_ready_queue; +static Common::ThreadQueueList<Thread*, THREADPRIO_LOWEST+1> thread_ready_queue; -static Handle current_thread_handle; static Thread* current_thread; static const u32 INITIAL_THREAD_ID = 1; ///< The first available thread id at startup @@ -87,30 +50,9 @@ Thread* GetCurrentThread() { return current_thread; } -/// Gets the current thread handle -Handle GetCurrentThreadHandle() { - return GetCurrentThread()->GetHandle(); -} - -/// Sets the current thread -inline void SetCurrentThread(Thread* t) { - current_thread = t; - current_thread_handle = t->GetHandle(); -} - -/// Saves the current CPU context -void SaveContext(ThreadContext& ctx) { - Core::g_app_core->SaveContext(ctx); -} - -/// Loads a CPU context -void LoadContext(ThreadContext& ctx) { - Core::g_app_core->LoadContext(ctx); -} - /// Resets a thread -void ResetThread(Thread* t, u32 arg, s32 lowest_priority) { - memset(&t->context, 0, sizeof(ThreadContext)); +static void ResetThread(Thread* t, u32 arg, s32 lowest_priority) { + memset(&t->context, 0, sizeof(Core::ThreadContext)); t->context.cpu_registers[0] = arg; t->context.pc = t->context.reg_15 = t->entry_point; @@ -126,22 +68,21 @@ void ResetThread(Thread* t, u32 arg, s32 lowest_priority) { t->current_priority = t->initial_priority; } t->wait_type = WAITTYPE_NONE; - t->wait_handle = 0; + t->wait_object = nullptr; t->wait_address = 0; } /// Change a thread to "ready" state -void ChangeReadyState(Thread* t, bool ready) { - Handle handle = t->GetHandle(); +static void ChangeReadyState(Thread* t, bool ready) { if (t->IsReady()) { if (!ready) { - thread_ready_queue.remove(t->current_priority, handle); + thread_ready_queue.remove(t->current_priority, t); } } else if (ready) { if (t->IsRunning()) { - thread_ready_queue.push_front(t->current_priority, handle); + thread_ready_queue.push_front(t->current_priority, t); } else { - thread_ready_queue.push_back(t->current_priority, handle); + thread_ready_queue.push_back(t->current_priority, t); } t->status = THREADSTATUS_READY; } @@ -153,43 +94,36 @@ static bool CheckWaitType(const Thread* thread, WaitType type) { } /// Check if a thread is blocking on a specified wait type with a specified handle -static bool CheckWaitType(const Thread* thread, WaitType type, Handle wait_handle) { - return CheckWaitType(thread, type) && (wait_handle == thread->wait_handle); +static bool CheckWaitType(const Thread* thread, WaitType type, Object* wait_object) { + return CheckWaitType(thread, type) && wait_object == thread->wait_object; } /// Check if a thread is blocking on a specified wait type with a specified handle and address -static bool CheckWaitType(const Thread* thread, WaitType type, Handle wait_handle, VAddr wait_address) { - return CheckWaitType(thread, type, wait_handle) && (wait_address == thread->wait_address); +static bool CheckWaitType(const Thread* thread, WaitType type, Object* wait_object, VAddr wait_address) { + return CheckWaitType(thread, type, wait_object) && (wait_address == thread->wait_address); } /// Stops the current thread -ResultCode StopThread(Handle handle, const char* reason) { - Thread* thread = g_handle_table.Get<Thread>(handle); - if (thread == nullptr) return InvalidHandle(ErrorModule::Kernel); - +void Thread::Stop(const char* reason) { // Release all the mutexes that this thread holds - ReleaseThreadMutexes(handle); + ReleaseThreadMutexes(GetHandle()); - ChangeReadyState(thread, false); - thread->status = THREADSTATUS_DORMANT; - for (Handle waiting_handle : thread->waiting_threads) { - Thread* waiting_thread = g_handle_table.Get<Thread>(waiting_handle); - - if (CheckWaitType(waiting_thread, WAITTYPE_THREADEND, handle)) - ResumeThreadFromWait(waiting_handle); + ChangeReadyState(this, false); + status = THREADSTATUS_DORMANT; + for (auto& waiting_thread : waiting_threads) { + if (CheckWaitType(waiting_thread.get(), WAITTYPE_THREADEND, this)) + waiting_thread->ResumeFromWait(); } - thread->waiting_threads.clear(); + waiting_threads.clear(); // Stopped threads are never waiting. - thread->wait_type = WAITTYPE_NONE; - thread->wait_handle = 0; - thread->wait_address = 0; - - return RESULT_SUCCESS; + wait_type = WAITTYPE_NONE; + wait_object = nullptr; + wait_address = 0; } /// Changes a threads state -void ChangeThreadState(Thread* t, ThreadStatus new_status) { +static void ChangeThreadState(Thread* t, ThreadStatus new_status) { if (!t || t->status == new_status) { return; } @@ -204,46 +138,44 @@ void ChangeThreadState(Thread* t, ThreadStatus new_status) { } /// Arbitrate the highest priority thread that is waiting -Handle ArbitrateHighestPriorityThread(u32 arbiter, u32 address) { - Handle highest_priority_thread = 0; +Thread* ArbitrateHighestPriorityThread(Object* arbiter, u32 address) { + Thread* highest_priority_thread = nullptr; s32 priority = THREADPRIO_LOWEST; // Iterate through threads, find highest priority thread that is waiting to be arbitrated... - for (Handle handle : thread_queue) { - Thread* thread = g_handle_table.Get<Thread>(handle); - - if (!CheckWaitType(thread, WAITTYPE_ARB, arbiter, address)) + for (auto& thread : thread_list) { + if (!CheckWaitType(thread.get(), WAITTYPE_ARB, arbiter, address)) continue; if (thread == nullptr) continue; // TODO(yuriks): Thread handle will hang around forever. Should clean up. if(thread->current_priority <= priority) { - highest_priority_thread = handle; + highest_priority_thread = thread.get(); priority = thread->current_priority; } } + // If a thread was arbitrated, resume it - if (0 != highest_priority_thread) - ResumeThreadFromWait(highest_priority_thread); + if (nullptr != highest_priority_thread) { + highest_priority_thread->ResumeFromWait(); + } return highest_priority_thread; } /// Arbitrate all threads currently waiting -void ArbitrateAllThreads(u32 arbiter, u32 address) { +void ArbitrateAllThreads(Object* arbiter, u32 address) { // Iterate through threads, find highest priority thread that is waiting to be arbitrated... - for (Handle handle : thread_queue) { - Thread* thread = g_handle_table.Get<Thread>(handle); - - if (CheckWaitType(thread, WAITTYPE_ARB, arbiter, address)) - ResumeThreadFromWait(handle); + for (auto& thread : thread_list) { + if (CheckWaitType(thread.get(), WAITTYPE_ARB, arbiter, address)) + thread->ResumeFromWait(); } } /// Calls a thread by marking it as "ready" (note: will not actually execute until current thread yields) -void CallThread(Thread* t) { +static void CallThread(Thread* t) { // Stop waiting if (t->wait_type != WAITTYPE_NONE) { t->wait_type = WAITTYPE_NONE; @@ -252,12 +184,12 @@ void CallThread(Thread* t) { } /// Switches CPU context to that of the specified thread -void SwitchContext(Thread* t) { +static void SwitchContext(Thread* t) { Thread* cur = GetCurrentThread(); // Save context for current thread if (cur) { - SaveContext(cur->context); + Core::g_app_core->SaveContext(cur->context); if (cur->IsRunning()) { ChangeReadyState(cur, true); @@ -265,19 +197,19 @@ void SwitchContext(Thread* t) { } // Load context of new thread if (t) { - SetCurrentThread(t); + current_thread = t; ChangeReadyState(t, false); t->status = (t->status | THREADSTATUS_RUNNING) & ~THREADSTATUS_READY; t->wait_type = WAITTYPE_NONE; - LoadContext(t->context); + Core::g_app_core->LoadContext(t->context); } else { - SetCurrentThread(nullptr); + current_thread = nullptr; } } /// Gets the next thread that is ready to be run by priority -Thread* NextThread() { - Handle next; +static Thread* NextThread() { + Thread* next; Thread* cur = GetCurrentThread(); if (cur && cur->IsRunning()) { @@ -288,63 +220,111 @@ Thread* NextThread() { if (next == 0) { return nullptr; } - return Kernel::g_handle_table.Get<Thread>(next); + return next; } -void WaitCurrentThread(WaitType wait_type, Handle wait_handle) { +void WaitCurrentThread(WaitType wait_type, Object* wait_object) { Thread* thread = GetCurrentThread(); thread->wait_type = wait_type; - thread->wait_handle = wait_handle; + thread->wait_object = wait_object; ChangeThreadState(thread, ThreadStatus(THREADSTATUS_WAIT | (thread->status & THREADSTATUS_SUSPEND))); } -void WaitCurrentThread(WaitType wait_type, Handle wait_handle, VAddr wait_address) { - WaitCurrentThread(wait_type, wait_handle); +void WaitCurrentThread(WaitType wait_type, Object* wait_object, VAddr wait_address) { + WaitCurrentThread(wait_type, wait_object); GetCurrentThread()->wait_address = wait_address; } +/// Event type for the thread wake up event +static int ThreadWakeupEventType = -1; + +/// Callback that will wake up the thread it was scheduled for +static void ThreadWakeupCallback(u64 parameter, int cycles_late) { + Handle handle = static_cast<Handle>(parameter); + SharedPtr<Thread> thread = Kernel::g_handle_table.Get<Thread>(handle); + if (thread == nullptr) { + LOG_ERROR(Kernel, "Thread doesn't exist %u", handle); + return; + } + + thread->ResumeFromWait(); +} + + +void WakeThreadAfterDelay(Thread* thread, s64 nanoseconds) { + // Don't schedule a wakeup if the thread wants to wait forever + if (nanoseconds == -1) + return; + _dbg_assert_(Kernel, thread != nullptr); + + u64 microseconds = nanoseconds / 1000; + CoreTiming::ScheduleEvent(usToCycles(microseconds), ThreadWakeupEventType, thread->GetHandle()); +} + /// Resumes a thread from waiting by marking it as "ready" -void ResumeThreadFromWait(Handle handle) { - Thread* thread = Kernel::g_handle_table.Get<Thread>(handle); - if (thread) { - thread->status &= ~THREADSTATUS_WAIT; - thread->wait_handle = 0; - thread->wait_type = WAITTYPE_NONE; - if (!(thread->status & (THREADSTATUS_WAITSUSPEND | THREADSTATUS_DORMANT | THREADSTATUS_DEAD))) { - ChangeReadyState(thread, true); - } +void Thread::ResumeFromWait() { + // Cancel any outstanding wakeup events + CoreTiming::UnscheduleEvent(ThreadWakeupEventType, GetHandle()); + + status &= ~THREADSTATUS_WAIT; + wait_object = nullptr; + wait_type = WAITTYPE_NONE; + if (!(status & (THREADSTATUS_WAITSUSPEND | THREADSTATUS_DORMANT | THREADSTATUS_DEAD))) { + ChangeReadyState(this, true); } } /// Prints the thread queue for debugging purposes -void DebugThreadQueue() { +static void DebugThreadQueue() { Thread* thread = GetCurrentThread(); if (!thread) { return; } - LOG_DEBUG(Kernel, "0x%02X 0x%08X (current)", thread->current_priority, GetCurrentThreadHandle()); - for (u32 i = 0; i < thread_queue.size(); i++) { - Handle handle = thread_queue[i]; - s32 priority = thread_ready_queue.contains(handle); + LOG_DEBUG(Kernel, "0x%02X 0x%08X (current)", thread->current_priority, GetCurrentThread()->GetHandle()); + for (auto& t : thread_list) { + s32 priority = thread_ready_queue.contains(t.get()); if (priority != -1) { - LOG_DEBUG(Kernel, "0x%02X 0x%08X", priority, handle); + LOG_DEBUG(Kernel, "0x%02X 0x%08X", priority, t->GetHandle()); } } } -/// Creates a new thread -Thread* CreateThread(Handle& handle, const char* name, u32 entry_point, s32 priority, - s32 processor_id, u32 stack_top, int stack_size) { +ResultVal<SharedPtr<Thread>> Thread::Create(std::string name, VAddr entry_point, s32 priority, + u32 arg, s32 processor_id, VAddr stack_top, u32 stack_size) { + if (stack_size < 0x200) { + LOG_ERROR(Kernel, "(name=%s): invalid stack_size=0x%08X", name.c_str(), stack_size); + // TODO: Verify error + return ResultCode(ErrorDescription::InvalidSize, ErrorModule::Kernel, + ErrorSummary::InvalidArgument, ErrorLevel::Permanent); + } + + if (priority < THREADPRIO_HIGHEST || priority > THREADPRIO_LOWEST) { + s32 new_priority = CLAMP(priority, THREADPRIO_HIGHEST, THREADPRIO_LOWEST); + LOG_WARNING(Kernel_SVC, "(name=%s): invalid priority=%d, clamping to %d", + name.c_str(), priority, new_priority); + // TODO(bunnei): Clamping to a valid priority is not necessarily correct behavior... Confirm + // validity of this + priority = new_priority; + } - _assert_msg_(KERNEL, (priority >= THREADPRIO_HIGHEST && priority <= THREADPRIO_LOWEST), - "priority=%d, outside of allowable range!", priority) + if (!Memory::GetPointer(entry_point)) { + LOG_ERROR(Kernel_SVC, "(name=%s): invalid entry %08x", name.c_str(), entry_point); + // TODO: Verify error + return ResultCode(ErrorDescription::InvalidAddress, ErrorModule::Kernel, + ErrorSummary::InvalidArgument, ErrorLevel::Permanent); + } - Thread* thread = new Thread; + SharedPtr<Thread> thread(new Thread); - // TOOD(yuriks): Fix error reporting - handle = Kernel::g_handle_table.Create(thread).ValueOr(INVALID_HANDLE); + // TODO(yuriks): Thread requires a handle to be inserted into the various scheduling queues for + // the time being. Create a handle here, it will be copied to the handle field in + // the object and use by the rest of the code. This should be removed when other + // code doesn't rely on the handle anymore. + ResultVal<Handle> handle = Kernel::g_handle_table.Create(thread); + if (handle.Failed()) + return handle.Code(); - thread_queue.push_back(handle); + thread_list.push_back(thread); thread_ready_queue.prepare(priority); thread->thread_id = next_thread_id++; @@ -355,69 +335,18 @@ Thread* CreateThread(Handle& handle, const char* name, u32 entry_point, s32 prio thread->initial_priority = thread->current_priority = priority; thread->processor_id = processor_id; thread->wait_type = WAITTYPE_NONE; - thread->wait_handle = 0; + thread->wait_object = nullptr; thread->wait_address = 0; - thread->name = name; - - return thread; -} - -/// Creates a new thread - wrapper for external user -Handle CreateThread(const char* name, u32 entry_point, s32 priority, u32 arg, s32 processor_id, - u32 stack_top, int stack_size) { - - if (name == nullptr) { - LOG_ERROR(Kernel_SVC, "nullptr name"); - return -1; - } - if ((u32)stack_size < 0x200) { - LOG_ERROR(Kernel_SVC, "(name=%s): invalid stack_size=0x%08X", name, - stack_size); - return -1; - } - if (priority < THREADPRIO_HIGHEST || priority > THREADPRIO_LOWEST) { - s32 new_priority = CLAMP(priority, THREADPRIO_HIGHEST, THREADPRIO_LOWEST); - LOG_WARNING(Kernel_SVC, "(name=%s): invalid priority=%d, clamping to %d", - name, priority, new_priority); - // TODO(bunnei): Clamping to a valid priority is not necessarily correct behavior... Confirm - // validity of this - priority = new_priority; - } - if (!Memory::GetPointer(entry_point)) { - LOG_ERROR(Kernel_SVC, "(name=%s): invalid entry %08x", name, entry_point); - return -1; - } - Handle handle; - Thread* thread = CreateThread(handle, name, entry_point, priority, processor_id, stack_top, - stack_size); - - ResetThread(thread, arg, 0); - CallThread(thread); - - return handle; -} + thread->name = std::move(name); -/// Get the priority of the thread specified by handle -ResultVal<u32> GetThreadPriority(const Handle handle) { - Thread* thread = g_handle_table.Get<Thread>(handle); - if (thread == nullptr) return InvalidHandle(ErrorModule::Kernel); + ResetThread(thread.get(), arg, 0); + CallThread(thread.get()); - return MakeResult<u32>(thread->current_priority); + return MakeResult<SharedPtr<Thread>>(std::move(thread)); } /// Set the priority of the thread specified by handle -ResultCode SetThreadPriority(Handle handle, s32 priority) { - Thread* thread = nullptr; - if (!handle) { - thread = GetCurrentThread(); // TODO(bunnei): Is this correct behavior? - } else { - thread = g_handle_table.Get<Thread>(handle); - if (thread == nullptr) { - return InvalidHandle(ErrorModule::Kernel); - } - } - _assert_msg_(KERNEL, (thread != nullptr), "called, but thread is nullptr!"); - +void Thread::SetPriority(s32 priority) { // If priority is invalid, clamp to valid range if (priority < THREADPRIO_HIGHEST || priority > THREADPRIO_LOWEST) { s32 new_priority = CLAMP(priority, THREADPRIO_HIGHEST, THREADPRIO_LOWEST); @@ -428,31 +357,39 @@ ResultCode SetThreadPriority(Handle handle, s32 priority) { } // Change thread priority - s32 old = thread->current_priority; - thread_ready_queue.remove(old, handle); - thread->current_priority = priority; - thread_ready_queue.prepare(thread->current_priority); + s32 old = current_priority; + thread_ready_queue.remove(old, this); + current_priority = priority; + thread_ready_queue.prepare(current_priority); // Change thread status to "ready" and push to ready queue - if (thread->IsRunning()) { - thread->status = (thread->status & ~THREADSTATUS_RUNNING) | THREADSTATUS_READY; + if (IsRunning()) { + status = (status & ~THREADSTATUS_RUNNING) | THREADSTATUS_READY; } - if (thread->IsReady()) { - thread_ready_queue.push_back(thread->current_priority, handle); + if (IsReady()) { + thread_ready_queue.push_back(current_priority, this); } - - return RESULT_SUCCESS; } -/// Sets up the primary application thread -Handle SetupMainThread(s32 priority, int stack_size) { - Handle handle; +Handle SetupIdleThread() { + // We need to pass a few valid values to get around parameter checking in Thread::Create. + auto thread_res = Thread::Create("idle", Memory::KERNEL_MEMORY_VADDR, THREADPRIO_LOWEST, 0, + THREADPROCESSORID_0, 0, Kernel::DEFAULT_STACK_SIZE); + _dbg_assert_(Kernel, thread_res.Succeeded()); + SharedPtr<Thread> thread = std::move(*thread_res); - // Initialize new "main" thread - Thread* thread = CreateThread(handle, "main", Core::g_app_core->GetPC(), priority, - THREADPROCESSORID_0, Memory::SCRATCHPAD_VADDR_END, stack_size); + thread->idle = true; + CallThread(thread.get()); + return thread->GetHandle(); +} - ResetThread(thread, 0, 0); +SharedPtr<Thread> SetupMainThread(s32 priority, u32 stack_size) { + // Initialize new "main" thread + auto thread_res = Thread::Create("main", Core::g_app_core->GetPC(), priority, 0, + THREADPROCESSORID_0, Memory::SCRATCHPAD_VADDR_END, stack_size); + // TODO(yuriks): Propagate error + _dbg_assert_(Kernel, thread_res.Succeeded()); + SharedPtr<Thread> thread = std::move(*thread_res); // If running another thread already, set it to "ready" state Thread* cur = GetCurrentThread(); @@ -461,11 +398,11 @@ Handle SetupMainThread(s32 priority, int stack_size) { } // Run new "main" thread - SetCurrentThread(thread); + current_thread = thread.get(); thread->status = THREADSTATUS_RUNNING; - LoadContext(thread->context); + Core::g_app_core->LoadContext(thread->context); - return handle; + return thread; } @@ -481,37 +418,19 @@ void Reschedule() { } else { LOG_TRACE(Kernel, "cannot context switch from 0x%08X, no higher priority thread!", prev->GetHandle()); - for (Handle handle : thread_queue) { - Thread* thread = g_handle_table.Get<Thread>(handle); + for (auto& thread : thread_list) { LOG_TRACE(Kernel, "\thandle=0x%08X prio=0x%02X, status=0x%08X wait_type=0x%08X wait_handle=0x%08X", - thread->GetHandle(), thread->current_priority, thread->status, thread->wait_type, thread->wait_handle); + thread->GetHandle(), thread->current_priority, thread->status, thread->wait_type, + (thread->wait_object ? thread->wait_object->GetHandle() : INVALID_HANDLE)); } } - - // TODO(bunnei): Hack - There is no timing mechanism yet to wake up a thread if it has been put - // to sleep. So, we'll just immediately set it to "ready" again after an attempted context - // switch has occurred. This results in the current thread yielding on a sleep once, and then it - // will immediately be placed back in the queue for execution. - - if (CheckWaitType(prev, WAITTYPE_SLEEP)) - ResumeThreadFromWait(prev->GetHandle()); -} - -ResultCode GetThreadId(u32* thread_id, Handle handle) { - Thread* thread = g_handle_table.Get<Thread>(handle); - if (thread == nullptr) - return ResultCode(ErrorDescription::InvalidHandle, ErrorModule::OS, - ErrorSummary::WrongArgument, ErrorLevel::Permanent); - - *thread_id = thread->thread_id; - - return RESULT_SUCCESS; } //////////////////////////////////////////////////////////////////////////////////////////////////// void ThreadingInit() { next_thread_id = INITIAL_THREAD_ID; + ThreadWakeupEventType = CoreTiming::RegisterEvent("ThreadWakeupCallback", ThreadWakeupCallback); } void ThreadingShutdown() { diff --git a/src/core/hle/kernel/thread.h b/src/core/hle/kernel/thread.h index 0e1397cd9..284dec400 100644 --- a/src/core/hle/kernel/thread.h +++ b/src/core/hle/kernel/thread.h @@ -4,8 +4,12 @@ #pragma once +#include <string> +#include <vector> + #include "common/common_types.h" +#include "core/core.h" #include "core/mem_map.h" #include "core/hle/kernel/kernel.h" @@ -43,67 +47,115 @@ enum WaitType { WAITTYPE_MUTEX, WAITTYPE_SYNCH, WAITTYPE_ARB, + WAITTYPE_TIMER, }; namespace Kernel { -/// Creates a new thread - wrapper for external user -Handle CreateThread(const char* name, u32 entry_point, s32 priority, u32 arg, s32 processor_id, - u32 stack_top, int stack_size=Kernel::DEFAULT_STACK_SIZE); +class Thread : public Kernel::Object { +public: + static ResultVal<SharedPtr<Thread>> Create(std::string name, VAddr entry_point, s32 priority, + u32 arg, s32 processor_id, VAddr stack_top, u32 stack_size); -/// Sets up the primary application thread -Handle SetupMainThread(s32 priority, int stack_size=Kernel::DEFAULT_STACK_SIZE); + std::string GetName() const override { return name; } + std::string GetTypeName() const override { return "Thread"; } -/// Reschedules to the next available thread (call after current thread is suspended) -void Reschedule(); + static const HandleType HANDLE_TYPE = HandleType::Thread; + HandleType GetHandleType() const override { return HANDLE_TYPE; } -/// Stops the current thread -ResultCode StopThread(Handle thread, const char* reason); + inline bool IsRunning() const { return (status & THREADSTATUS_RUNNING) != 0; } + inline bool IsStopped() const { return (status & THREADSTATUS_DORMANT) != 0; } + inline bool IsReady() const { return (status & THREADSTATUS_READY) != 0; } + inline bool IsWaiting() const { return (status & THREADSTATUS_WAIT) != 0; } + inline bool IsSuspended() const { return (status & THREADSTATUS_SUSPEND) != 0; } + inline bool IsIdle() const { return idle; } -/** - * Retrieves the ID of the specified thread handle - * @param thread_id Will contain the output thread id - * @param handle Handle to the thread we want - * @return Whether the function was successful or not - */ -ResultCode GetThreadId(u32* thread_id, Handle handle); + ResultVal<bool> WaitSynchronization() override; + + s32 GetPriority() const { return current_priority; } + void SetPriority(s32 priority); + + u32 GetThreadId() const { return thread_id; } + + void Stop(const char* reason); + /// Resumes a thread from waiting by marking it as "ready". + void ResumeFromWait(); + + Core::ThreadContext context; + + u32 thread_id; + + u32 status; + u32 entry_point; + u32 stack_top; + u32 stack_size; + + s32 initial_priority; + s32 current_priority; + + s32 processor_id; + + WaitType wait_type; + Object* wait_object; + VAddr wait_address; -/// Resumes a thread from waiting by marking it as "ready" -void ResumeThreadFromWait(Handle handle); + std::vector<SharedPtr<Thread>> waiting_threads; + + std::string name; + + /// Whether this thread is intended to never actually be executed, i.e. always idle + bool idle = false; + +private: + Thread() = default; +}; + +/// Sets up the primary application thread +SharedPtr<Thread> SetupMainThread(s32 priority, u32 stack_size); + +/// Reschedules to the next available thread (call after current thread is suspended) +void Reschedule(); /// Arbitrate the highest priority thread that is waiting -Handle ArbitrateHighestPriorityThread(u32 arbiter, u32 address); +Thread* ArbitrateHighestPriorityThread(Object* arbiter, u32 address); /// Arbitrate all threads currently waiting... -void ArbitrateAllThreads(u32 arbiter, u32 address); +void ArbitrateAllThreads(Object* arbiter, u32 address); -/// Gets the current thread handle -Handle GetCurrentThreadHandle(); +/// Gets the current thread +Thread* GetCurrentThread(); /** * Puts the current thread in the wait state for the given type * @param wait_type Type of wait - * @param wait_handle Handle of Kernel object that we are waiting on, defaults to current thread + * @param wait_object Kernel object that we are waiting on, defaults to current thread + */ +void WaitCurrentThread(WaitType wait_type, Object* wait_object = GetCurrentThread()); + +/** + * Schedules an event to wake up the specified thread after the specified delay. + * @param handle The thread handle. + * @param nanoseconds The time this thread will be allowed to sleep for. */ -void WaitCurrentThread(WaitType wait_type, Handle wait_handle=GetCurrentThreadHandle()); +void WakeThreadAfterDelay(Thread* thread, s64 nanoseconds); /** * Puts the current thread in the wait state for the given type * @param wait_type Type of wait - * @param wait_handle Handle of Kernel object that we are waiting on, defaults to current thread + * @param wait_object Kernel object that we are waiting on * @param wait_address Arbitration address used to resume from wait */ -void WaitCurrentThread(WaitType wait_type, Handle wait_handle, VAddr wait_address); +void WaitCurrentThread(WaitType wait_type, Object* wait_object, VAddr wait_address); -/// Put current thread in a wait state - on WaitSynchronization -void WaitThread_Synchronization(); -/// Get the priority of the thread specified by handle -ResultVal<u32> GetThreadPriority(const Handle handle); - -/// Set the priority of the thread specified by handle -ResultCode SetThreadPriority(Handle handle, s32 priority); +/** + * Sets up the idle thread, this is a thread that is intended to never execute instructions, + * only to advance the timing. It is scheduled when there are no other ready threads in the thread queue + * and will try to yield on every call. + * @returns The handle of the idle thread + */ +Handle SetupIdleThread(); /// Initialize threading void ThreadingInit(); diff --git a/src/core/hle/kernel/timer.cpp b/src/core/hle/kernel/timer.cpp new file mode 100644 index 000000000..3b0452d4d --- /dev/null +++ b/src/core/hle/kernel/timer.cpp @@ -0,0 +1,144 @@ +// Copyright 2015 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include <set> + +#include "common/common.h" + +#include "core/core_timing.h" +#include "core/hle/kernel/kernel.h" +#include "core/hle/kernel/timer.h" +#include "core/hle/kernel/thread.h" + +namespace Kernel { + +class Timer : public Object { +public: + std::string GetTypeName() const override { return "Timer"; } + std::string GetName() const override { return name; } + + static const HandleType HANDLE_TYPE = HandleType::Timer; + HandleType GetHandleType() const override { return HANDLE_TYPE; } + + ResetType reset_type; ///< The ResetType of this timer + + bool signaled; ///< Whether the timer has been signaled or not + std::set<Handle> waiting_threads; ///< Threads that are waiting for the timer + std::string name; ///< Name of timer (optional) + + u64 initial_delay; ///< The delay until the timer fires for the first time + u64 interval_delay; ///< The delay until the timer fires after the first time + + ResultVal<bool> WaitSynchronization() override { + bool wait = !signaled; + if (wait) { + waiting_threads.insert(GetCurrentThread()->GetHandle()); + Kernel::WaitCurrentThread(WAITTYPE_TIMER, this); + } + return MakeResult<bool>(wait); + } +}; + +/** + * Creates a timer. + * @param handle Reference to handle for the newly created timer + * @param reset_type ResetType describing how to create timer + * @param name Optional name of timer + * @return Newly created Timer object + */ +Timer* CreateTimer(Handle& handle, const ResetType reset_type, const std::string& name) { + Timer* timer = new Timer; + + handle = Kernel::g_handle_table.Create(timer).ValueOr(INVALID_HANDLE); + + timer->reset_type = reset_type; + timer->signaled = false; + timer->name = name; + timer->initial_delay = 0; + timer->interval_delay = 0; + return timer; +} + +ResultCode CreateTimer(Handle* handle, const ResetType reset_type, const std::string& name) { + CreateTimer(*handle, reset_type, name); + return RESULT_SUCCESS; +} + +ResultCode ClearTimer(Handle handle) { + SharedPtr<Timer> timer = Kernel::g_handle_table.Get<Timer>(handle); + + if (timer == nullptr) + return InvalidHandle(ErrorModule::Kernel); + + timer->signaled = false; + return RESULT_SUCCESS; +} + +/// The event type of the generic timer callback event +static int TimerCallbackEventType = -1; + +/// The timer callback event, called when a timer is fired +static void TimerCallback(u64 timer_handle, int cycles_late) { + SharedPtr<Timer> timer = Kernel::g_handle_table.Get<Timer>(timer_handle); + + if (timer == nullptr) { + LOG_CRITICAL(Kernel, "Callback fired for invalid timer %u", timer_handle); + return; + } + + LOG_TRACE(Kernel, "Timer %u fired", timer_handle); + + timer->signaled = true; + + // Resume all waiting threads + for (Handle thread_handle : timer->waiting_threads) { + if (SharedPtr<Thread> thread = Kernel::g_handle_table.Get<Thread>(thread_handle)) + thread->ResumeFromWait(); + } + + timer->waiting_threads.clear(); + + if (timer->reset_type == RESETTYPE_ONESHOT) + timer->signaled = false; + + if (timer->interval_delay != 0) { + // Reschedule the timer with the interval delay + u64 interval_microseconds = timer->interval_delay / 1000; + CoreTiming::ScheduleEvent(usToCycles(interval_microseconds) - cycles_late, + TimerCallbackEventType, timer_handle); + } +} + +ResultCode SetTimer(Handle handle, s64 initial, s64 interval) { + SharedPtr<Timer> timer = Kernel::g_handle_table.Get<Timer>(handle); + + if (timer == nullptr) + return InvalidHandle(ErrorModule::Kernel); + + timer->initial_delay = initial; + timer->interval_delay = interval; + + u64 initial_microseconds = initial / 1000; + CoreTiming::ScheduleEvent(usToCycles(initial_microseconds), TimerCallbackEventType, handle); + return RESULT_SUCCESS; +} + +ResultCode CancelTimer(Handle handle) { + SharedPtr<Timer> timer = Kernel::g_handle_table.Get<Timer>(handle); + + if (timer == nullptr) + return InvalidHandle(ErrorModule::Kernel); + + CoreTiming::UnscheduleEvent(TimerCallbackEventType, handle); + return RESULT_SUCCESS; +} + +void TimersInit() { + TimerCallbackEventType = CoreTiming::RegisterEvent("TimerCallback", TimerCallback); +} + +void TimersShutdown() { +} + +} // namespace diff --git a/src/core/hle/kernel/timer.h b/src/core/hle/kernel/timer.h new file mode 100644 index 000000000..f8aa66b60 --- /dev/null +++ b/src/core/hle/kernel/timer.h @@ -0,0 +1,47 @@ +// Copyright 2015 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include "common/common_types.h" + +#include "core/hle/kernel/kernel.h" +#include "core/hle/svc.h" + +namespace Kernel { + +/** + * Cancels a timer + * @param handle Handle of the timer to cancel + */ +ResultCode CancelTimer(Handle handle); + +/** + * Starts a timer with the specified initial delay and interval + * @param handle Handle of the timer to start + * @param initial Delay until the timer is first fired + * @param interval Delay until the timer is fired after the first time + */ +ResultCode SetTimer(Handle handle, s64 initial, s64 interval); + +/** + * Clears a timer + * @param handle Handle of the timer to clear + */ +ResultCode ClearTimer(Handle handle); + +/** + * Creates a timer + * @param Handle to newly created Timer object + * @param reset_type ResetType describing how to create the timer + * @param name Optional name of timer + * @return ResultCode of the error + */ +ResultCode CreateTimer(Handle* handle, const ResetType reset_type, const std::string& name="Unknown"); + +/// Initializes the required variables for timers +void TimersInit(); +/// Tears down the timer variables +void TimersShutdown(); +} // namespace diff --git a/src/core/hle/result.h b/src/core/hle/result.h index 0e9c213e0..82dcf5bba 100644 --- a/src/core/hle/result.h +++ b/src/core/hle/result.h @@ -369,14 +369,14 @@ private: StorageType storage; ResultCode result_code; -#if _DEBUG +#ifdef _DEBUG // The purpose of this pointer is to aid inspecting the type with a debugger, eliminating the // need to cast `storage` to a pointer or pay attention to `result_code`. const T* debug_ptr; #endif void UpdateDebugPtr() { -#if _DEBUG +#ifdef _DEBUG debug_ptr = empty() ? nullptr : static_cast<const T*>(static_cast<const void*>(&storage)); #endif } diff --git a/src/core/hle/service/apt_u.cpp b/src/core/hle/service/apt_u.cpp index d8b261ba7..d0ff4e585 100644 --- a/src/core/hle/service/apt_u.cpp +++ b/src/core/hle/service/apt_u.cpp @@ -52,8 +52,6 @@ void Initialize(Service::Interface* self) { Kernel::ReleaseMutex(lock_handle); cmd_buff[1] = 0; // No error - - LOG_DEBUG(Service_APT, "called"); } void GetLockHandle(Service::Interface* self) { @@ -194,8 +192,6 @@ void AppletUtility(Service::Interface* self) { * 4 : Handle to shared font memory */ void GetSharedFont(Service::Interface* self) { - LOG_TRACE(Kernel_SVC, "called"); - u32* cmd_buff = Kernel::GetCommandBuffer(); if (!shared_font.empty()) { diff --git a/src/core/hle/service/cfg/cfg.cpp b/src/core/hle/service/cfg/cfg.cpp index 161aa8531..8812c49ef 100644 --- a/src/core/hle/service/cfg/cfg.cpp +++ b/src/core/hle/service/cfg/cfg.cpp @@ -161,9 +161,9 @@ ResultCode FormatConfig() { void CFGInit() { // TODO(Subv): In the future we should use the FS service to query this archive, // currently it is not possible because you can only have one open archive of the same type at any time - std::string syssavedata_directory = FileUtil::GetUserPath(D_SYSSAVEDATA_IDX); + std::string nand_directory = FileUtil::GetUserPath(D_NAND_IDX); cfg_system_save_data = Common::make_unique<FileSys::Archive_SystemSaveData>( - syssavedata_directory, CFG_SAVE_ID); + nand_directory, CFG_SAVE_ID); if (!cfg_system_save_data->Initialize()) { LOG_CRITICAL(Service_CFG, "Could not initialize SystemSaveData archive for the CFG:U service"); return; diff --git a/src/core/hle/service/fs/archive.cpp b/src/core/hle/service/fs/archive.cpp index f761c6ab9..958dd9344 100644 --- a/src/core/hle/service/fs/archive.cpp +++ b/src/core/hle/service/fs/archive.cpp @@ -36,6 +36,10 @@ namespace std { }; } +/// TODO(Subv): Confirm length of these strings +const std::string SYSTEM_ID = "00000000000000000000000000000000"; +const std::string SDCARD_ID = "00000000000000000000000000000000"; + namespace Service { namespace FS { @@ -432,11 +436,11 @@ ResultCode FormatSaveData() { void ArchiveInit() { next_handle = 1; - // TODO(Link Mauve): Add the other archive types (see here for the known types: - // http://3dbrew.org/wiki/FS:OpenArchive#Archive_idcodes). Currently the only half-finished - // archive type is SDMC, so it is the only one getting exposed. + // TODO(Subv): Add the other archive types (see here for the known types: + // http://3dbrew.org/wiki/FS:OpenArchive#Archive_idcodes). std::string sdmc_directory = FileUtil::GetUserPath(D_SDMC_IDX); + std::string nand_directory = FileUtil::GetUserPath(D_NAND_IDX); auto sdmc_archive = Common::make_unique<FileSys::Archive_SDMC>(sdmc_directory); if (sdmc_archive->Initialize()) CreateArchive(std::move(sdmc_archive), ArchiveIdCode::SDMC); @@ -444,28 +448,24 @@ void ArchiveInit() { LOG_ERROR(Service_FS, "Can't instantiate SDMC archive with path %s", sdmc_directory.c_str()); // Create the SaveData archive - std::string savedata_directory = FileUtil::GetUserPath(D_SAVEDATA_IDX); - auto savedata_archive = Common::make_unique<FileSys::Archive_SaveData>(savedata_directory); + auto savedata_archive = Common::make_unique<FileSys::Archive_SaveData>(sdmc_directory); CreateArchive(std::move(savedata_archive), ArchiveIdCode::SaveData); - std::string extsavedata_directory = FileUtil::GetUserPath(D_EXTSAVEDATA); - auto extsavedata_archive = Common::make_unique<FileSys::Archive_ExtSaveData>(extsavedata_directory); + auto extsavedata_archive = Common::make_unique<FileSys::Archive_ExtSaveData>(sdmc_directory, false); if (extsavedata_archive->Initialize()) CreateArchive(std::move(extsavedata_archive), ArchiveIdCode::ExtSaveData); else - LOG_ERROR(Service_FS, "Can't instantiate ExtSaveData archive with path %s", extsavedata_directory.c_str()); + LOG_ERROR(Service_FS, "Can't instantiate ExtSaveData archive with path %s", extsavedata_archive->GetMountPoint().c_str()); - std::string sharedextsavedata_directory = FileUtil::GetUserPath(D_EXTSAVEDATA); - auto sharedextsavedata_archive = Common::make_unique<FileSys::Archive_ExtSaveData>(sharedextsavedata_directory); + auto sharedextsavedata_archive = Common::make_unique<FileSys::Archive_ExtSaveData>(nand_directory, true); if (sharedextsavedata_archive->Initialize()) CreateArchive(std::move(sharedextsavedata_archive), ArchiveIdCode::SharedExtSaveData); else LOG_ERROR(Service_FS, "Can't instantiate SharedExtSaveData archive with path %s", - sharedextsavedata_directory.c_str()); + sharedextsavedata_archive->GetMountPoint().c_str()); // Create the SaveDataCheck archive, basically a small variation of the RomFS archive - std::string savedatacheck_directory = FileUtil::GetUserPath(D_SAVEDATACHECK_IDX); - auto savedatacheck_archive = Common::make_unique<FileSys::Archive_SaveDataCheck>(savedatacheck_directory); + auto savedatacheck_archive = Common::make_unique<FileSys::Archive_SaveDataCheck>(nand_directory); CreateArchive(std::move(savedatacheck_archive), ArchiveIdCode::SaveDataCheck); } diff --git a/src/core/hle/service/fs/archive.h b/src/core/hle/service/fs/archive.h index 9e9efa019..b3f2134f2 100644 --- a/src/core/hle/service/fs/archive.h +++ b/src/core/hle/service/fs/archive.h @@ -10,6 +10,11 @@ #include "core/hle/kernel/kernel.h" #include "core/hle/result.h" +/// The unique system identifier hash, also known as ID0 +extern const std::string SYSTEM_ID; +/// The scrambled SD card CID, also known as ID1 +extern const std::string SDCARD_ID; + namespace Service { namespace FS { diff --git a/src/core/hle/service/fs/fs_user.cpp b/src/core/hle/service/fs/fs_user.cpp index 7eb32146d..56f3117f4 100644 --- a/src/core/hle/service/fs/fs_user.cpp +++ b/src/core/hle/service/fs/fs_user.cpp @@ -27,8 +27,6 @@ static void Initialize(Service::Interface* self) { // TODO(Link Mauve): check the behavior when cmd_buff[1] isn't 32, as per // http://3dbrew.org/wiki/FS:Initialize#Request cmd_buff[1] = RESULT_SUCCESS.raw; - - LOG_DEBUG(Service_FS, "called"); } /** @@ -104,8 +102,8 @@ static void OpenFileDirectly(Service::Interface* self) { FileSys::Path archive_path(archivename_type, archivename_size, archivename_ptr); FileSys::Path file_path(filename_type, filename_size, filename_ptr); - LOG_DEBUG(Service_FS, "archive_path=%s file_path=%s, mode=%u attributes=%d", - archive_path.DebugStr().c_str(), file_path.DebugStr().c_str(), mode.hex, attributes); + LOG_DEBUG(Service_FS, "archive_id=0x%08X archive_path=%s file_path=%s, mode=%u attributes=%d", + archive_id, archive_path.DebugStr().c_str(), file_path.DebugStr().c_str(), mode.hex, attributes); ResultVal<ArchiveHandle> archive_handle = OpenArchive(archive_id, archive_path); if (archive_handle.Failed()) { @@ -367,7 +365,7 @@ static void OpenArchive(Service::Interface* self) { u32 archivename_ptr = cmd_buff[5]; FileSys::Path archive_path(archivename_type, archivename_size, archivename_ptr); - LOG_DEBUG(Service_FS, "archive_path=%s", archive_path.DebugStr().c_str()); + LOG_DEBUG(Service_FS, "archive_id=0x%08X archive_path=%s", archive_id, archive_path.DebugStr().c_str()); ResultVal<ArchiveHandle> handle = OpenArchive(archive_id, archive_path); cmd_buff[1] = handle.Code().raw; @@ -408,8 +406,6 @@ static void IsSdmcDetected(Service::Interface* self) { cmd_buff[1] = 0; cmd_buff[2] = Settings::values.use_virtual_sd ? 1 : 0; - - LOG_DEBUG(Service_FS, "called"); } /** diff --git a/src/core/hle/service/gsp_gpu.cpp b/src/core/hle/service/gsp_gpu.cpp index 0127d4ee5..2b115240f 100644 --- a/src/core/hle/service/gsp_gpu.cpp +++ b/src/core/hle/service/gsp_gpu.cpp @@ -291,8 +291,11 @@ static void ExecuteCommand(const Command& command, u32 thread_id) { // Update framebuffer information if requested for (int screen_id = 0; screen_id < 2; ++screen_id) { FrameBufferUpdate* info = GetFrameBufferInfo(thread_id, screen_id); - if (info->is_dirty) + + if (info->is_dirty) { SetBufferSwap(screen_id, info->framebuffer_info[info->index]); + info->framebuffer_info->active_fb = info->framebuffer_info->active_fb ^ 1; + } info->is_dirty = false; } @@ -328,9 +331,6 @@ static void ExecuteCommand(const Command& command, u32 thread_id) { /// This triggers handling of the GX command written to the command buffer in shared memory. static void TriggerCmdReqQueue(Service::Interface* self) { - - LOG_TRACE(Service_GSP, "called"); - // Iterate through each thread's command queue... for (unsigned thread_id = 0; thread_id < 0x4; ++thread_id) { CommandBuffer* command_buffer = (CommandBuffer*)GetCommandBuffer(thread_id); diff --git a/src/core/hle/service/hid_user.cpp b/src/core/hle/service/hid_user.cpp index 99b0ea5a0..1403b1de9 100644 --- a/src/core/hle/service/hid_user.cpp +++ b/src/core/hle/service/hid_user.cpp @@ -4,6 +4,7 @@ #include "common/log.h" +#include "core/arm/arm_interface.h" #include "core/hle/hle.h" #include "core/hle/kernel/event.h" #include "core/hle/kernel/shared_memory.h" @@ -162,8 +163,6 @@ static void GetIPCHandles(Service::Interface* self) { cmd_buff[6] = event_accelerometer; cmd_buff[7] = event_gyroscope; cmd_buff[8] = event_debug_pad; - - LOG_TRACE(Service_HID, "called"); } const Interface::FunctionInfo FunctionTable[] = { diff --git a/src/core/hle/service/ptm_u.cpp b/src/core/hle/service/ptm_u.cpp index 9cc700c46..753180add 100644 --- a/src/core/hle/service/ptm_u.cpp +++ b/src/core/hle/service/ptm_u.cpp @@ -76,8 +76,6 @@ static void GetShellState(Service::Interface* self) { cmd_buff[1] = 0; cmd_buff[2] = shell_open ? 1 : 0; - - LOG_TRACE(Service_PTM, "PTM_U::GetShellState called"); } /** @@ -142,10 +140,10 @@ Interface::Interface() { Register(FunctionTable, ARRAY_SIZE(FunctionTable)); // Create the SharedExtSaveData archive 0xF000000B and the gamecoin.dat file // TODO(Subv): In the future we should use the FS service to query this archive - std::string extsavedata_directory = FileUtil::GetUserPath(D_EXTSAVEDATA); - ptm_shared_extsavedata = Common::make_unique<FileSys::Archive_ExtSaveData>(extsavedata_directory); + std::string nand_directory = FileUtil::GetUserPath(D_NAND_IDX); + ptm_shared_extsavedata = Common::make_unique<FileSys::Archive_ExtSaveData>(nand_directory, true); if (!ptm_shared_extsavedata->Initialize()) { - LOG_CRITICAL(Service_PTM, "Could not initialize ExtSaveData archive for the PTM:U service"); + LOG_CRITICAL(Service_PTM, "Could not initialize SharedExtSaveData archive for the PTM:U service"); return; } FileSys::Path archive_path(ptm_shared_extdata_id); diff --git a/src/core/hle/service/service.cpp b/src/core/hle/service/service.cpp index c5233e687..33c29a4a0 100644 --- a/src/core/hle/service/service.cpp +++ b/src/core/hle/service/service.cpp @@ -46,36 +46,23 @@ Manager* g_manager = nullptr; ///< Service manager //////////////////////////////////////////////////////////////////////////////////////////////////// // Service Manager class -Manager::Manager() { -} - -Manager::~Manager() { - for(Interface* service : m_services) { - DeleteService(service->GetPortName()); - } -} - -/// Add a service to the manager (does not create it though) void Manager::AddService(Interface* service) { // TOOD(yuriks): Fix error reporting m_port_map[service->GetPortName()] = Kernel::g_handle_table.Create(service).ValueOr(INVALID_HANDLE); m_services.push_back(service); } -/// Removes a service from the manager, also frees memory void Manager::DeleteService(const std::string& port_name) { Interface* service = FetchFromPortName(port_name); m_services.erase(std::remove(m_services.begin(), m_services.end(), service), m_services.end()); m_port_map.erase(port_name); - delete service; } -/// Get a Service Interface from its Handle Interface* Manager::FetchFromHandle(Handle handle) { - return Kernel::g_handle_table.Get<Interface>(handle); + // TODO(yuriks): This function is very suspicious and should probably be exterminated. + return Kernel::g_handle_table.Get<Interface>(handle).get(); } -/// Get a Service Interface from its port Interface* Manager::FetchFromPortName(const std::string& port_name) { auto itr = m_port_map.find(port_name); if (itr == m_port_map.end()) { diff --git a/src/core/hle/service/service.h b/src/core/hle/service/service.h index 28b4ccd17..e75d5008b 100644 --- a/src/core/hle/service/service.h +++ b/src/core/hle/service/service.h @@ -33,6 +33,22 @@ class Interface : public Kernel::Session { // processes. friend class Manager; + + /** + * Creates a function string for logging, complete with the name (or header code, depending + * on what's passed in) the port name, and all the cmd_buff arguments. + */ + std::string MakeFunctionString(const std::string& name, const std::string& port_name, const u32* cmd_buff) { + // Number of params == bits 0-5 + bits 6-11 + int num_params = (cmd_buff[0] & 0x3F) + ((cmd_buff[0] >> 6) & 0x3F); + + std::string function_string = Common::StringFromFormat("function '%s': port=%s", name.c_str(), port_name.c_str()); + for (int i = 1; i <= num_params; ++i) { + function_string += Common::StringFromFormat(", cmd_buff[%i]=%u", i, cmd_buff[i]); + } + return function_string; + } + public: std::string GetName() const override { return GetPortName(); } @@ -72,21 +88,14 @@ public: auto itr = m_functions.find(cmd_buff[0]); if (itr == m_functions.end() || itr->second.func == nullptr) { - // Number of params == bits 0-5 + bits 6-11 - int num_params = (cmd_buff[0] & 0x3F) + ((cmd_buff[0] >> 6) & 0x3F); - - std::string error = "unknown/unimplemented function '%s': port=%s"; - for (int i = 1; i <= num_params; ++i) { - error += Common::StringFromFormat(", cmd_buff[%i]=%u", i, cmd_buff[i]); - } - - std::string name = (itr == m_functions.end()) ? Common::StringFromFormat("0x%08X", cmd_buff[0]) : itr->second.name; - - LOG_ERROR(Service, error.c_str(), name.c_str(), GetPortName().c_str()); + std::string function_name = (itr == m_functions.end()) ? Common::StringFromFormat("0x%08X", cmd_buff[0]) : itr->second.name; + LOG_ERROR(Service, "%s %s", "unknown/unimplemented", MakeFunctionString(function_name, GetPortName(), cmd_buff).c_str()); // TODO(bunnei): Hack - ignore error cmd_buff[1] = 0; return MakeResult<bool>(false); + } else { + LOG_TRACE(Service, "%s", MakeFunctionString(itr->second.name, GetPortName(), cmd_buff).c_str()); } itr->second.func(this); @@ -114,29 +123,22 @@ private: /// Simple class to manage accessing services from ports and UID handles class Manager { - public: - Manager(); - - ~Manager(); - - /// Add a service to the manager (does not create it though) + /// Add a service to the manager void AddService(Interface* service); - /// Removes a service from the manager (does not delete it though) + /// Removes a service from the manager void DeleteService(const std::string& port_name); - /// Get a Service Interface from its UID - Interface* FetchFromHandle(u32 uid); + /// Get a Service Interface from its Handle + Interface* FetchFromHandle(Handle handle); /// Get a Service Interface from its port Interface* FetchFromPortName(const std::string& port_name); private: - std::vector<Interface*> m_services; std::map<std::string, u32> m_port_map; - }; /// Initialize ServiceManager diff --git a/src/core/hle/service/srv.cpp b/src/core/hle/service/srv.cpp index 912b52adf..ac5f30a28 100644 --- a/src/core/hle/service/srv.cpp +++ b/src/core/hle/service/srv.cpp @@ -14,16 +14,12 @@ namespace SRV { static Handle g_event_handle = 0; static void Initialize(Service::Interface* self) { - LOG_DEBUG(Service_SRV, "called"); - u32* cmd_buff = Kernel::GetCommandBuffer(); cmd_buff[1] = 0; // No error } static void GetProcSemaphore(Service::Interface* self) { - LOG_TRACE(Service_SRV, "called"); - u32* cmd_buff = Kernel::GetCommandBuffer(); // TODO(bunnei): Change to a semaphore once these have been implemented diff --git a/src/core/hle/service/y2r_u.cpp b/src/core/hle/service/y2r_u.cpp index f9e3619dd..b3d873ef0 100644 --- a/src/core/hle/service/y2r_u.cpp +++ b/src/core/hle/service/y2r_u.cpp @@ -12,6 +12,21 @@ namespace Y2R_U { +/** + * Y2R_U::IsBusyConversion service function + * Outputs: + * 1 : Result of function, 0 on success, otherwise error code + * 2 : Whether the current conversion is of type busy conversion (?) + */ +static void IsBusyConversion(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[1] = RESULT_SUCCESS.raw;; + cmd_buff[2] = 0; + + LOG_WARNING(Service, "(STUBBED) called"); +} + const Interface::FunctionInfo FunctionTable[] = { {0x00010040, nullptr, "SetInputFormat"}, {0x00030040, nullptr, "SetOutputFormat"}, @@ -29,7 +44,7 @@ const Interface::FunctionInfo FunctionTable[] = { {0x00220040, nullptr, "SetAlpha"}, {0x00260000, nullptr, "StartConversion"}, {0x00270000, nullptr, "StopConversion"}, - {0x00280000, nullptr, "IsBusyConversion"}, + {0x00280000, IsBusyConversion, "IsBusyConversion"}, {0x002A0000, nullptr, "PingProcess"}, {0x002B0000, nullptr, "DriverInitialize"}, {0x002C0000, nullptr, "DriverFinalize"} diff --git a/src/core/hle/svc.cpp b/src/core/hle/svc.cpp index c25409a9f..d3b4483ca 100644 --- a/src/core/hle/svc.cpp +++ b/src/core/hle/svc.cpp @@ -7,6 +7,7 @@ #include "common/string_util.h" #include "common/symbols.h" +#include "core/arm/arm_interface.h" #include "core/mem_map.h" #include "core/hle/kernel/address_arbiter.h" @@ -15,6 +16,7 @@ #include "core/hle/kernel/semaphore.h" #include "core/hle/kernel/shared_memory.h" #include "core/hle/kernel/thread.h" +#include "core/hle/kernel/timer.h" #include "core/hle/function_wrappers.h" #include "core/hle/result.h" @@ -23,6 +25,8 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// // Namespace SVC +using Kernel::SharedPtr; + namespace SVC { enum ControlMemoryOperation { @@ -92,7 +96,7 @@ static Result ConnectToPort(Handle* out, const char* port_name) { /// Synchronize to an OS service static Result SendSyncRequest(Handle handle) { - Kernel::Session* session = Kernel::g_handle_table.Get<Kernel::Session>(handle); + SharedPtr<Kernel::Session> session = Kernel::g_handle_table.Get<Kernel::Session>(handle); if (session == nullptr) { return InvalidHandle(ErrorModule::Kernel).raw; } @@ -119,12 +123,12 @@ static Result WaitSynchronization1(Handle handle, s64 nano_seconds) { // TODO(bunnei): Do something with nano_seconds, currently ignoring this bool wait_infinite = (nano_seconds == -1); // Used to wait until a thread has terminated - Kernel::Object* object = Kernel::g_handle_table.GetGeneric(handle); + SharedPtr<Kernel::Object> object = Kernel::g_handle_table.GetGeneric(handle); if (object == nullptr) return InvalidHandle(ErrorModule::Kernel).raw; - LOG_TRACE(Kernel_SVC, "called handle=0x%08X(%s:%s), nanoseconds=%lld", handle, object->GetTypeName().c_str(), - object->GetName().c_str(), nano_seconds); + LOG_TRACE(Kernel_SVC, "called handle=0x%08X(%s:%s), nanoseconds=%lld", handle, + object->GetTypeName().c_str(), object->GetName().c_str(), nano_seconds); ResultVal<bool> wait = object->WaitSynchronization(); @@ -139,6 +143,7 @@ static Result WaitSynchronization1(Handle handle, s64 nano_seconds) { /// Wait for the given handles to synchronize, timeout after the specified nanoseconds static Result WaitSynchronizationN(s32* out, Handle* handles, s32 handle_count, bool wait_all, s64 nano_seconds) { + // TODO(bunnei): Do something with nano_seconds, currently ignoring this bool unlock_all = true; bool wait_infinite = (nano_seconds == -1); // Used to wait until a thread has terminated @@ -148,12 +153,12 @@ static Result WaitSynchronizationN(s32* out, Handle* handles, s32 handle_count, // Iterate through each handle, synchronize kernel object for (s32 i = 0; i < handle_count; i++) { - Kernel::Object* object = Kernel::g_handle_table.GetGeneric(handles[i]); + SharedPtr<Kernel::Object> object = Kernel::g_handle_table.GetGeneric(handles[i]); if (object == nullptr) return InvalidHandle(ErrorModule::Kernel).raw; - LOG_TRACE(Kernel_SVC, "\thandle[%d] = 0x%08X(%s:%s)", i, handles[i], object->GetTypeName().c_str(), - object->GetName().c_str()); + LOG_TRACE(Kernel_SVC, "\thandle[%d] = 0x%08X(%s:%s)", i, handles[i], + object->GetTypeName().c_str(), object->GetName().c_str()); // TODO(yuriks): Verify how the real function behaves when an error happens here ResultVal<bool> wait_result = object->WaitSynchronization(); @@ -180,7 +185,6 @@ static Result WaitSynchronizationN(s32* out, Handle* handles, s32 handle_count, /// Create an address arbiter (to allocate access to shared resources) static Result CreateAddressArbiter(u32* arbiter) { - LOG_TRACE(Kernel_SVC, "called"); Handle handle = Kernel::CreateAddressArbiter(); *arbiter = handle; return 0; @@ -220,6 +224,8 @@ static Result GetResourceLimitCurrentValues(s64* values, Handle resource_limit, /// Creates a new thread static Result CreateThread(u32 priority, u32 entry_point, u32 arg, u32 stack_top, u32 processor_id) { + using Kernel::Thread; + std::string name; if (Symbols::HasSymbol(entry_point)) { TSymbol symbol = Symbols::GetSymbol(entry_point); @@ -228,41 +234,53 @@ static Result CreateThread(u32 priority, u32 entry_point, u32 arg, u32 stack_top name = Common::StringFromFormat("unknown-%08x", entry_point); } - Handle thread = Kernel::CreateThread(name.c_str(), entry_point, priority, arg, processor_id, - stack_top); + ResultVal<SharedPtr<Thread>> thread_res = Kernel::Thread::Create( + name, entry_point, priority, arg, processor_id, stack_top, Kernel::DEFAULT_STACK_SIZE); + if (thread_res.Failed()) + return thread_res.Code().raw; + SharedPtr<Thread> thread = std::move(*thread_res); - Core::g_app_core->SetReg(1, thread); + // TODO(yuriks): Create new handle instead of using built-in + Core::g_app_core->SetReg(1, thread->GetHandle()); LOG_TRACE(Kernel_SVC, "called entrypoint=0x%08X (%s), arg=0x%08X, stacktop=0x%08X, " "threadpriority=0x%08X, processorid=0x%08X : created handle=0x%08X", entry_point, - name.c_str(), arg, stack_top, priority, processor_id, thread); + name.c_str(), arg, stack_top, priority, processor_id, thread->GetHandle()); + + if (THREADPROCESSORID_1 == processor_id) { + LOG_WARNING(Kernel_SVC, + "thread designated for system CPU core (UNIMPLEMENTED) will be run with app core scheduling"); + } return 0; } /// Called when a thread exits -static u32 ExitThread() { - Handle thread = Kernel::GetCurrentThreadHandle(); - - LOG_TRACE(Kernel_SVC, "called, pc=0x%08X", Core::g_app_core->GetPC()); // PC = 0x0010545C +static void ExitThread() { + LOG_TRACE(Kernel_SVC, "called, pc=0x%08X", Core::g_app_core->GetPC()); - Kernel::StopThread(thread, __func__); + Kernel::GetCurrentThread()->Stop(__func__); HLE::Reschedule(__func__); - return 0; } /// Gets the priority for the specified thread static Result GetThreadPriority(s32* priority, Handle handle) { - ResultVal<u32> priority_result = Kernel::GetThreadPriority(handle); - if (priority_result.Succeeded()) { - *priority = *priority_result; - } - return priority_result.Code().raw; + const SharedPtr<Kernel::Thread> thread = Kernel::g_handle_table.Get<Kernel::Thread>(handle); + if (thread == nullptr) + return InvalidHandle(ErrorModule::Kernel).raw; + + *priority = thread->GetPriority(); + return RESULT_SUCCESS.raw; } /// Sets the priority for the specified thread static Result SetThreadPriority(Handle handle, s32 priority) { - return Kernel::SetThreadPriority(handle, priority).raw; + SharedPtr<Kernel::Thread> thread = Kernel::g_handle_table.Get<Kernel::Thread>(handle); + if (thread == nullptr) + return InvalidHandle(ErrorModule::Kernel).raw; + + thread->SetPriority(priority); + return RESULT_SUCCESS.raw; } /// Create a mutex @@ -283,8 +301,13 @@ static Result ReleaseMutex(Handle handle) { /// Get the ID for the specified thread. static Result GetThreadId(u32* thread_id, Handle handle) { LOG_TRACE(Kernel_SVC, "called thread=0x%08X", handle); - ResultCode result = Kernel::GetThreadId(thread_id, handle); - return result.raw; + + const SharedPtr<Kernel::Thread> thread = Kernel::g_handle_table.Get<Kernel::Thread>(handle); + if (thread == nullptr) + return InvalidHandle(ErrorModule::Kernel).raw; + + *thread_id = thread->GetThreadId(); + return RESULT_SUCCESS.raw; } /// Creates a semaphore @@ -338,12 +361,42 @@ static Result ClearEvent(Handle evt) { return Kernel::ClearEvent(evt).raw; } +/// Creates a timer +static Result CreateTimer(Handle* handle, u32 reset_type) { + ResultCode res = Kernel::CreateTimer(handle, static_cast<ResetType>(reset_type)); + LOG_TRACE(Kernel_SVC, "called reset_type=0x%08X : created handle=0x%08X", + reset_type, *handle); + return res.raw; +} + +/// Clears a timer +static Result ClearTimer(Handle handle) { + LOG_TRACE(Kernel_SVC, "called timer=0x%08X", handle); + return Kernel::ClearTimer(handle).raw; +} + +/// Starts a timer +static Result SetTimer(Handle handle, s64 initial, s64 interval) { + LOG_TRACE(Kernel_SVC, "called timer=0x%08X", handle); + return Kernel::SetTimer(handle, initial, interval).raw; +} + +/// Cancels a timer +static Result CancelTimer(Handle handle) { + LOG_TRACE(Kernel_SVC, "called timer=0x%08X", handle); + return Kernel::CancelTimer(handle).raw; +} + /// Sleep the current thread static void SleepThread(s64 nanoseconds) { LOG_TRACE(Kernel_SVC, "called nanoseconds=%lld", nanoseconds); // Sleep current thread and check for next thread to schedule Kernel::WaitCurrentThread(WAITTYPE_SLEEP); + + // Create an event to wake the thread up after the specified nanosecond delay has passed + Kernel::WakeThreadAfterDelay(Kernel::GetCurrentThread(), nanoseconds); + HLE::Reschedule(__func__); } @@ -374,7 +427,7 @@ const HLE::FunctionDef SVC_Table[] = { {0x06, nullptr, "GetProcessIdealProcessor"}, {0x07, nullptr, "SetProcessIdealProcessor"}, {0x08, HLE::Wrap<CreateThread>, "CreateThread"}, - {0x09, HLE::Wrap<ExitThread>, "ExitThread"}, + {0x09, ExitThread, "ExitThread"}, {0x0A, HLE::Wrap<SleepThread>, "SleepThread"}, {0x0B, HLE::Wrap<GetThreadPriority>, "GetThreadPriority"}, {0x0C, HLE::Wrap<SetThreadPriority>, "SetThreadPriority"}, @@ -391,10 +444,10 @@ const HLE::FunctionDef SVC_Table[] = { {0x17, HLE::Wrap<CreateEvent>, "CreateEvent"}, {0x18, HLE::Wrap<SignalEvent>, "SignalEvent"}, {0x19, HLE::Wrap<ClearEvent>, "ClearEvent"}, - {0x1A, nullptr, "CreateTimer"}, - {0x1B, nullptr, "SetTimer"}, - {0x1C, nullptr, "CancelTimer"}, - {0x1D, nullptr, "ClearTimer"}, + {0x1A, HLE::Wrap<CreateTimer>, "CreateTimer"}, + {0x1B, HLE::Wrap<SetTimer>, "SetTimer"}, + {0x1C, HLE::Wrap<CancelTimer>, "CancelTimer"}, + {0x1D, HLE::Wrap<ClearTimer>, "ClearTimer"}, {0x1E, HLE::Wrap<CreateMemoryBlock>, "CreateMemoryBlock"}, {0x1F, HLE::Wrap<MapMemoryBlock>, "MapMemoryBlock"}, {0x20, nullptr, "UnmapMemoryBlock"}, diff --git a/src/core/hle/svc.h b/src/core/hle/svc.h index ad780818e..5d020a5ba 100644 --- a/src/core/hle/svc.h +++ b/src/core/hle/svc.h @@ -20,21 +20,6 @@ struct PageInfo { u32 flags; }; -struct ThreadContext { - u32 cpu_registers[13]; - u32 sp; - u32 lr; - u32 pc; - u32 cpsr; - u32 fpu_registers[32]; - u32 fpscr; - u32 fpexc; - - // These are not part of native ThreadContext, but needed by emu - u32 reg_15; - u32 mode; -}; - enum ResetType { RESETTYPE_ONESHOT, RESETTYPE_STICKY, diff --git a/src/core/hw/gpu.cpp b/src/core/hw/gpu.cpp index e346e0ad6..3b730a0de 100644 --- a/src/core/hw/gpu.cpp +++ b/src/core/hw/gpu.cpp @@ -4,6 +4,8 @@ #include "common/common_types.h" +#include "core/arm/arm_interface.h" + #include "core/settings.h" #include "core/core.h" #include "core/mem_map.h" diff --git a/src/core/system.cpp b/src/core/system.cpp index d6188f055..f4c2df1cd 100644 --- a/src/core/system.cpp +++ b/src/core/system.cpp @@ -21,11 +21,11 @@ void UpdateState(State state) { void Init(EmuWindow* emu_window) { Core::Init(); + CoreTiming::Init(); Memory::Init(); HW::Init(); Kernel::Init(); HLE::Init(); - CoreTiming::Init(); VideoCore::Init(emu_window); } @@ -38,11 +38,11 @@ void RunLoopUntil(u64 global_cycles) { void Shutdown() { VideoCore::Shutdown(); - CoreTiming::Shutdown(); HLE::Shutdown(); Kernel::Shutdown(); HW::Shutdown(); Memory::Shutdown(); + CoreTiming::Shutdown(); Core::Shutdown(); } diff --git a/src/video_core/renderer_opengl/renderer_opengl.cpp b/src/video_core/renderer_opengl/renderer_opengl.cpp index 4df3a5e25..29d220e8d 100644 --- a/src/video_core/renderer_opengl/renderer_opengl.cpp +++ b/src/video_core/renderer_opengl/renderer_opengl.cpp @@ -87,8 +87,11 @@ void RendererOpenGL::SwapBuffers() { */ void RendererOpenGL::LoadFBToActiveGLTexture(const GPU::Regs::FramebufferConfig& framebuffer, const TextureInfo& texture) { + + // TODO: Why are active_fb and the valid framebuffer flipped compared to 3dbrew documentation + // and GSP definitions? const VAddr framebuffer_vaddr = Memory::PhysicalToVirtualAddress( - framebuffer.active_fb == 1 ? framebuffer.address_left2 : framebuffer.address_left1); + framebuffer.active_fb == 0 ? framebuffer.address_left2 : framebuffer.address_left1); LOG_TRACE(Render_OpenGL, "0x%08x bytes from 0x%08x(%dx%d), fmt %x", framebuffer.stride * framebuffer.height, |