diff options
35 files changed, 1363 insertions, 556 deletions
diff --git a/.gitmodules b/.gitmodules index 35e0d1240..ee0dc6c19 100644 --- a/.gitmodules +++ b/.gitmodules @@ -26,11 +26,11 @@ path = externals/mbedtls url = https://github.com/DarkLordZach/mbedtls [submodule "opus"] - path = externals/opus - url = https://github.com/ogniK5377/opus.git + path = externals/opus/opus + url = https://github.com/xiph/opus.git [submodule "soundtouch"] - path = externals/soundtouch - url = https://github.com/citra-emu/ext-soundtouch.git + path = externals/soundtouch + url = https://github.com/citra-emu/ext-soundtouch.git [submodule "libressl"] path = externals/libressl url = https://github.com/citra-emu/ext-libressl-portable.git diff --git a/externals/opus b/externals/opus deleted file mode 160000 -Subproject 562f8ba555c4181e1b57e82e496e4a959b9c019 diff --git a/externals/opus/CMakeLists.txt b/externals/opus/CMakeLists.txt new file mode 100644 index 000000000..cbb393272 --- /dev/null +++ b/externals/opus/CMakeLists.txt @@ -0,0 +1,250 @@ +cmake_minimum_required(VERSION 3.8) + +project(opus) + +option(OPUS_STACK_PROTECTOR "Use stack protection" OFF) +option(OPUS_USE_ALLOCA "Use alloca for stack arrays (on non-C99 compilers)" OFF) +option(OPUS_CUSTOM_MODES "Enable non-Opus modes, e.g. 44.1 kHz & 2^n frames" OFF) +option(OPUS_FIXED_POINT "Compile as fixed-point (for machines without a fast enough FPU)" OFF) +option(OPUS_ENABLE_FLOAT_API "Compile with the floating point API (for machines with float library" ON) + +include(opus/opus_functions.cmake) + +if(OPUS_STACK_PROTECTOR) + if(NOT MSVC) # GC on by default on MSVC + check_and_set_flag(STACK_PROTECTION_STRONG -fstack-protector-strong) + endif() +else() + if(MSVC) + check_and_set_flag(BUFFER_SECURITY_CHECK /GS-) + endif() +endif() + +add_library(opus STATIC + # CELT sources + opus/celt/bands.c + opus/celt/celt.c + opus/celt/celt_decoder.c + opus/celt/celt_encoder.c + opus/celt/celt_lpc.c + opus/celt/cwrs.c + opus/celt/entcode.c + opus/celt/entdec.c + opus/celt/entenc.c + opus/celt/kiss_fft.c + opus/celt/laplace.c + opus/celt/mathops.c + opus/celt/mdct.c + opus/celt/modes.c + opus/celt/pitch.c + opus/celt/quant_bands.c + opus/celt/rate.c + opus/celt/vq.c + + # SILK sources + opus/silk/A2NLSF.c + opus/silk/CNG.c + opus/silk/HP_variable_cutoff.c + opus/silk/LPC_analysis_filter.c + opus/silk/LPC_fit.c + opus/silk/LPC_inv_pred_gain.c + opus/silk/LP_variable_cutoff.c + opus/silk/NLSF2A.c + opus/silk/NLSF_VQ.c + opus/silk/NLSF_VQ_weights_laroia.c + opus/silk/NLSF_decode.c + opus/silk/NLSF_del_dec_quant.c + opus/silk/NLSF_encode.c + opus/silk/NLSF_stabilize.c + opus/silk/NLSF_unpack.c + opus/silk/NSQ.c + opus/silk/NSQ_del_dec.c + opus/silk/PLC.c + opus/silk/VAD.c + opus/silk/VQ_WMat_EC.c + opus/silk/ana_filt_bank_1.c + opus/silk/biquad_alt.c + opus/silk/bwexpander.c + opus/silk/bwexpander_32.c + opus/silk/check_control_input.c + opus/silk/code_signs.c + opus/silk/control_SNR.c + opus/silk/control_audio_bandwidth.c + opus/silk/control_codec.c + opus/silk/dec_API.c + opus/silk/decode_core.c + opus/silk/decode_frame.c + opus/silk/decode_indices.c + opus/silk/decode_parameters.c + opus/silk/decode_pitch.c + opus/silk/decode_pulses.c + opus/silk/decoder_set_fs.c + opus/silk/enc_API.c + opus/silk/encode_indices.c + opus/silk/encode_pulses.c + opus/silk/gain_quant.c + opus/silk/init_decoder.c + opus/silk/init_encoder.c + opus/silk/inner_prod_aligned.c + opus/silk/interpolate.c + opus/silk/lin2log.c + opus/silk/log2lin.c + opus/silk/pitch_est_tables.c + opus/silk/process_NLSFs.c + opus/silk/quant_LTP_gains.c + opus/silk/resampler.c + opus/silk/resampler_down2.c + opus/silk/resampler_down2_3.c + opus/silk/resampler_private_AR2.c + opus/silk/resampler_private_IIR_FIR.c + opus/silk/resampler_private_down_FIR.c + opus/silk/resampler_private_up2_HQ.c + opus/silk/resampler_rom.c + opus/silk/shell_coder.c + opus/silk/sigm_Q15.c + opus/silk/sort.c + opus/silk/stereo_LR_to_MS.c + opus/silk/stereo_MS_to_LR.c + opus/silk/stereo_decode_pred.c + opus/silk/stereo_encode_pred.c + opus/silk/stereo_find_predictor.c + opus/silk/stereo_quant_pred.c + opus/silk/sum_sqr_shift.c + opus/silk/table_LSF_cos.c + opus/silk/tables_LTP.c + opus/silk/tables_NLSF_CB_NB_MB.c + opus/silk/tables_NLSF_CB_WB.c + opus/silk/tables_gain.c + opus/silk/tables_other.c + opus/silk/tables_pitch_lag.c + opus/silk/tables_pulses_per_block.c + + # Opus sources + opus/src/analysis.c + opus/src/mapping_matrix.c + opus/src/mlp.c + opus/src/mlp_data.c + opus/src/opus.c + opus/src/opus_decoder.c + opus/src/opus_encoder.c + opus/src/opus_multistream.c + opus/src/opus_multistream_decoder.c + opus/src/opus_multistream_encoder.c + opus/src/opus_projection_decoder.c + opus/src/opus_projection_encoder.c + opus/src/repacketizer.c +) + +if (DEBUG) + target_sources(opus PRIVATE opus/silk/debug.c) +endif() + +if (OPUS_FIXED_POINT) + target_sources(opus PRIVATE + opus/silk/fixed/LTP_analysis_filter_FIX.c + opus/silk/fixed/LTP_scale_ctrl_FIX.c + opus/silk/fixed/apply_sine_window_FIX.c + opus/silk/fixed/autocorr_FIX.c + opus/silk/fixed/burg_modified_FIX.c + opus/silk/fixed/corrMatrix_FIX.c + opus/silk/fixed/encode_frame_FIX.c + opus/silk/fixed/find_LPC_FIX.c + opus/silk/fixed/find_LTP_FIX.c + opus/silk/fixed/find_pitch_lags_FIX.c + opus/silk/fixed/find_pred_coefs_FIX.c + opus/silk/fixed/k2a_FIX.c + opus/silk/fixed/k2a_Q16_FIX.c + opus/silk/fixed/noise_shape_analysis_FIX.c + opus/silk/fixed/pitch_analysis_core_FIX.c + opus/silk/fixed/prefilter_FIX.c + opus/silk/fixed/process_gains_FIX.c + opus/silk/fixed/regularize_correlations_FIX.c + opus/silk/fixed/residual_energy16_FIX.c + opus/silk/fixed/residual_energy_FIX.c + opus/silk/fixed/schur64_FIX.c + opus/silk/fixed/schur_FIX.c + opus/silk/fixed/solve_LS_FIX.c + opus/silk/fixed/vector_ops_FIX.c + opus/silk/fixed/warped_autocorrelation_FIX.c + ) +else() + target_sources(opus PRIVATE + opus/silk/float/LPC_analysis_filter_FLP.c + opus/silk/float/LPC_inv_pred_gain_FLP.c + opus/silk/float/LTP_analysis_filter_FLP.c + opus/silk/float/LTP_scale_ctrl_FLP.c + opus/silk/float/apply_sine_window_FLP.c + opus/silk/float/autocorrelation_FLP.c + opus/silk/float/burg_modified_FLP.c + opus/silk/float/bwexpander_FLP.c + opus/silk/float/corrMatrix_FLP.c + opus/silk/float/encode_frame_FLP.c + opus/silk/float/energy_FLP.c + opus/silk/float/find_LPC_FLP.c + opus/silk/float/find_LTP_FLP.c + opus/silk/float/find_pitch_lags_FLP.c + opus/silk/float/find_pred_coefs_FLP.c + opus/silk/float/inner_product_FLP.c + opus/silk/float/k2a_FLP.c + opus/silk/float/noise_shape_analysis_FLP.c + opus/silk/float/pitch_analysis_core_FLP.c + opus/silk/float/process_gains_FLP.c + opus/silk/float/regularize_correlations_FLP.c + opus/silk/float/residual_energy_FLP.c + opus/silk/float/scale_copy_vector_FLP.c + opus/silk/float/scale_vector_FLP.c + opus/silk/float/schur_FLP.c + opus/silk/float/sort_FLP.c + opus/silk/float/warped_autocorrelation_FLP.c + opus/silk/float/wrappers_FLP.c + ) +endif() + +target_compile_definitions(opus PRIVATE OPUS_BUILD ENABLE_HARDENING) + +if(NOT MSVC) + target_compile_definitions(opus PRIVATE _FORTIFY_SOURCE=2) +endif() + +# It is strongly recommended to uncomment one of these VAR_ARRAYS: Use C99 +# variable-length arrays for stack allocation USE_ALLOCA: Use alloca() for stack +# allocation If none is defined, then the fallback is a non-threadsafe global +# array +if(OPUS_USE_ALLOCA OR MSVC) + target_compile_definitions(opus PRIVATE USE_ALLOCA) +else() + target_compile_definitions(opus PRIVATE VAR_ARRAYS) +endif() + +if(OPUS_CUSTOM_MODES) + target_compile_definitions(opus PRIVATE CUSTOM_MODES) +endif() + +if(NOT OPUS_ENABLE_FLOAT_API) + target_compile_definitions(opus PRIVATE DISABLE_FLOAT_API) +endif() + +target_compile_definitions(opus +PUBLIC + -DOPUS_VERSION="\\"1.3.1\\"" + +PRIVATE + # Use C99 intrinsics to speed up float-to-int conversion + HAVE_LRINTF +) + +if (FIXED_POINT) + target_compile_definitions(opus PRIVATE -DFIXED_POINT=1 -DDISABLE_FLOAT_API) +endif() + +target_include_directories(opus +PUBLIC + opus/include + +PRIVATE + opus/celt + opus/silk + opus/silk/fixed + opus/silk/float + opus/src +) diff --git a/externals/opus/opus b/externals/opus/opus new file mode 160000 +Subproject ad8fe90db79b7d2a135e3dfd2ed6631b0c5662a diff --git a/src/common/multi_level_queue.h b/src/common/multi_level_queue.h index 9cb448f56..50acfdbf2 100644 --- a/src/common/multi_level_queue.h +++ b/src/common/multi_level_queue.h @@ -304,6 +304,13 @@ public: return levels[priority == Depth ? 63 : priority].back(); } + void clear() { + used_priorities = 0; + for (std::size_t i = 0; i < Depth; i++) { + levels[i].clear(); + } + } + private: using const_list_iterator = typename std::list<T>::const_iterator; diff --git a/src/core/core.cpp b/src/core/core.cpp index b7b9259ec..eba17218a 100644 --- a/src/core/core.cpp +++ b/src/core/core.cpp @@ -409,6 +409,12 @@ void System::PrepareReschedule() { CurrentCpuCore().PrepareReschedule(); } +void System::PrepareReschedule(const u32 core_index) { + if (core_index < GlobalScheduler().CpuCoresCount()) { + CpuCore(core_index).PrepareReschedule(); + } +} + PerfStatsResults System::GetAndResetPerfStats() { return impl->GetAndResetPerfStats(); } @@ -449,6 +455,16 @@ const Kernel::Scheduler& System::Scheduler(std::size_t core_index) const { return CpuCore(core_index).Scheduler(); } +/// Gets the global scheduler +Kernel::GlobalScheduler& System::GlobalScheduler() { + return impl->kernel.GlobalScheduler(); +} + +/// Gets the global scheduler +const Kernel::GlobalScheduler& System::GlobalScheduler() const { + return impl->kernel.GlobalScheduler(); +} + Kernel::Process* System::CurrentProcess() { return impl->kernel.CurrentProcess(); } diff --git a/src/core/core.h b/src/core/core.h index 90e7ac607..984074ce3 100644 --- a/src/core/core.h +++ b/src/core/core.h @@ -24,6 +24,7 @@ class VfsFilesystem; } // namespace FileSys namespace Kernel { +class GlobalScheduler; class KernelCore; class Process; class Scheduler; @@ -184,6 +185,9 @@ public: /// Prepare the core emulation for a reschedule void PrepareReschedule(); + /// Prepare the core emulation for a reschedule + void PrepareReschedule(u32 core_index); + /// Gets and resets core performance statistics PerfStatsResults GetAndResetPerfStats(); @@ -238,6 +242,12 @@ public: /// Gets the scheduler for the CPU core with the specified index const Kernel::Scheduler& Scheduler(std::size_t core_index) const; + /// Gets the global scheduler + Kernel::GlobalScheduler& GlobalScheduler(); + + /// Gets the global scheduler + const Kernel::GlobalScheduler& GlobalScheduler() const; + /// Provides a pointer to the current process Kernel::Process* CurrentProcess(); diff --git a/src/core/core_cpu.cpp b/src/core/core_cpu.cpp index 6bd9639c6..233ea572c 100644 --- a/src/core/core_cpu.cpp +++ b/src/core/core_cpu.cpp @@ -52,7 +52,8 @@ bool CpuBarrier::Rendezvous() { Cpu::Cpu(System& system, ExclusiveMonitor& exclusive_monitor, CpuBarrier& cpu_barrier, std::size_t core_index) - : cpu_barrier{cpu_barrier}, core_timing{system.CoreTiming()}, core_index{core_index} { + : cpu_barrier{cpu_barrier}, global_scheduler{system.GlobalScheduler()}, + core_timing{system.CoreTiming()}, core_index{core_index} { #ifdef ARCHITECTURE_x86_64 arm_interface = std::make_unique<ARM_Dynarmic>(system, exclusive_monitor, core_index); #else @@ -60,7 +61,7 @@ Cpu::Cpu(System& system, ExclusiveMonitor& exclusive_monitor, CpuBarrier& cpu_ba LOG_WARNING(Core, "CPU JIT requested, but Dynarmic not available"); #endif - scheduler = std::make_unique<Kernel::Scheduler>(system, *arm_interface); + scheduler = std::make_unique<Kernel::Scheduler>(system, *arm_interface, core_index); } Cpu::~Cpu() = default; @@ -81,21 +82,21 @@ void Cpu::RunLoop(bool tight_loop) { return; } + Reschedule(); + // If we don't have a currently active thread then don't execute instructions, // instead advance to the next event and try to yield to the next thread if (Kernel::GetCurrentThread() == nullptr) { LOG_TRACE(Core, "Core-{} idling", core_index); core_timing.Idle(); - core_timing.Advance(); - PrepareReschedule(); } else { if (tight_loop) { arm_interface->Run(); } else { arm_interface->Step(); } - core_timing.Advance(); } + core_timing.Advance(); Reschedule(); } @@ -106,18 +107,18 @@ void Cpu::SingleStep() { void Cpu::PrepareReschedule() { arm_interface->PrepareReschedule(); - reschedule_pending = true; } void Cpu::Reschedule() { - if (!reschedule_pending) { - return; - } - - reschedule_pending = false; // Lock the global kernel mutex when we manipulate the HLE state - std::lock_guard lock{HLE::g_hle_lock}; - scheduler->Reschedule(); + std::lock_guard lock(HLE::g_hle_lock); + + global_scheduler.SelectThread(core_index); + scheduler->TryDoContextSwitch(); +} + +void Cpu::Shutdown() { + scheduler->Shutdown(); } } // namespace Core diff --git a/src/core/core_cpu.h b/src/core/core_cpu.h index 7589beb8c..cafca8df7 100644 --- a/src/core/core_cpu.h +++ b/src/core/core_cpu.h @@ -12,8 +12,9 @@ #include "common/common_types.h" namespace Kernel { +class GlobalScheduler; class Scheduler; -} +} // namespace Kernel namespace Core { class System; @@ -83,6 +84,8 @@ public: return core_index; } + void Shutdown(); + static std::unique_ptr<ExclusiveMonitor> MakeExclusiveMonitor(std::size_t num_cores); private: @@ -90,6 +93,7 @@ private: std::unique_ptr<ARM_Interface> arm_interface; CpuBarrier& cpu_barrier; + Kernel::GlobalScheduler& global_scheduler; std::unique_ptr<Kernel::Scheduler> scheduler; Timing::CoreTiming& core_timing; diff --git a/src/core/cpu_core_manager.cpp b/src/core/cpu_core_manager.cpp index 16b384076..8efd410bb 100644 --- a/src/core/cpu_core_manager.cpp +++ b/src/core/cpu_core_manager.cpp @@ -58,6 +58,7 @@ void CpuCoreManager::Shutdown() { thread_to_cpu.clear(); for (auto& cpu_core : cores) { + cpu_core->Shutdown(); cpu_core.reset(); } diff --git a/src/core/file_sys/savedata_factory.cpp b/src/core/file_sys/savedata_factory.cpp index fc8755c78..e2a7eaf7b 100644 --- a/src/core/file_sys/savedata_factory.cpp +++ b/src/core/file_sys/savedata_factory.cpp @@ -16,6 +16,7 @@ namespace FileSys { constexpr char SAVE_DATA_SIZE_FILENAME[] = ".yuzu_save_size"; namespace { + void PrintSaveDataDescriptorWarnings(SaveDataDescriptor meta) { if (meta.type == SaveDataType::SystemSaveData || meta.type == SaveDataType::SaveData) { if (meta.zero_1 != 0) { @@ -52,6 +53,13 @@ void PrintSaveDataDescriptorWarnings(SaveDataDescriptor meta) { meta.user_id[1], meta.user_id[0]); } } + +bool ShouldSaveDataBeAutomaticallyCreated(SaveDataSpaceId space, const SaveDataDescriptor& desc) { + return desc.type == SaveDataType::CacheStorage || desc.type == SaveDataType::TemporaryStorage || + (space == SaveDataSpaceId::NandUser && ///< Normal Save Data -- Current Title & User + desc.type == SaveDataType::SaveData && desc.title_id == 0 && desc.save_id == 0); +} + } // Anonymous namespace std::string SaveDataDescriptor::DebugInfo() const { @@ -96,6 +104,10 @@ ResultVal<VirtualDir> SaveDataFactory::Open(SaveDataSpaceId space, auto out = dir->GetDirectoryRelative(save_directory); + if (out == nullptr && ShouldSaveDataBeAutomaticallyCreated(space, meta)) { + return Create(space, meta); + } + // Return an error if the save data doesn't actually exist. if (out == nullptr) { // TODO(Subv): Find out correct error code. diff --git a/src/core/gdbstub/gdbstub.cpp b/src/core/gdbstub/gdbstub.cpp index db51d722f..20bb50868 100644 --- a/src/core/gdbstub/gdbstub.cpp +++ b/src/core/gdbstub/gdbstub.cpp @@ -202,13 +202,11 @@ void RegisterModule(std::string name, VAddr beg, VAddr end, bool add_elf_ext) { } static Kernel::Thread* FindThreadById(s64 id) { - for (u32 core = 0; core < Core::NUM_CPU_CORES; core++) { - const auto& threads = Core::System::GetInstance().Scheduler(core).GetThreadList(); - for (auto& thread : threads) { - if (thread->GetThreadID() == static_cast<u64>(id)) { - current_core = core; - return thread.get(); - } + const auto& threads = Core::System::GetInstance().GlobalScheduler().GetThreadList(); + for (auto& thread : threads) { + if (thread->GetThreadID() == static_cast<u64>(id)) { + current_core = thread->GetProcessorID(); + return thread.get(); } } return nullptr; @@ -647,11 +645,9 @@ static void HandleQuery() { SendReply(buffer.c_str()); } else if (strncmp(query, "fThreadInfo", strlen("fThreadInfo")) == 0) { std::string val = "m"; - for (u32 core = 0; core < Core::NUM_CPU_CORES; core++) { - const auto& threads = Core::System::GetInstance().Scheduler(core).GetThreadList(); - for (const auto& thread : threads) { - val += fmt::format("{:x},", thread->GetThreadID()); - } + const auto& threads = Core::System::GetInstance().GlobalScheduler().GetThreadList(); + for (const auto& thread : threads) { + val += fmt::format("{:x},", thread->GetThreadID()); } val.pop_back(); SendReply(val.c_str()); @@ -661,13 +657,11 @@ static void HandleQuery() { std::string buffer; buffer += "l<?xml version=\"1.0\"?>"; buffer += "<threads>"; - for (u32 core = 0; core < Core::NUM_CPU_CORES; core++) { - const auto& threads = Core::System::GetInstance().Scheduler(core).GetThreadList(); - for (const auto& thread : threads) { - buffer += - fmt::format(R"*(<thread id="{:x}" core="{:d}" name="Thread {:x}"></thread>)*", - thread->GetThreadID(), core, thread->GetThreadID()); - } + const auto& threads = Core::System::GetInstance().GlobalScheduler().GetThreadList(); + for (const auto& thread : threads) { + buffer += + fmt::format(R"*(<thread id="{:x}" core="{:d}" name="Thread {:x}"></thread>)*", + thread->GetThreadID(), thread->GetProcessorID(), thread->GetThreadID()); } buffer += "</threads>"; SendReply(buffer.c_str()); diff --git a/src/core/hle/kernel/address_arbiter.cpp b/src/core/hle/kernel/address_arbiter.cpp index c8842410b..de0a9064e 100644 --- a/src/core/hle/kernel/address_arbiter.cpp +++ b/src/core/hle/kernel/address_arbiter.cpp @@ -22,6 +22,7 @@ namespace Kernel { namespace { // Wake up num_to_wake (or all) threads in a vector. void WakeThreads(const std::vector<SharedPtr<Thread>>& waiting_threads, s32 num_to_wake) { + auto& system = Core::System::GetInstance(); // Only process up to 'target' threads, unless 'target' is <= 0, in which case process // them all. std::size_t last = waiting_threads.size(); @@ -35,6 +36,7 @@ void WakeThreads(const std::vector<SharedPtr<Thread>>& waiting_threads, s32 num_ waiting_threads[i]->SetWaitSynchronizationResult(RESULT_SUCCESS); waiting_threads[i]->SetArbiterWaitAddress(0); waiting_threads[i]->ResumeFromWait(); + system.PrepareReschedule(waiting_threads[i]->GetProcessorID()); } } } // Anonymous namespace @@ -89,12 +91,20 @@ ResultCode AddressArbiter::ModifyByWaitingCountAndSignalToAddressIfEqual(VAddr a // Determine the modified value depending on the waiting count. s32 updated_value; - if (waiting_threads.empty()) { - updated_value = value + 1; - } else if (num_to_wake <= 0 || waiting_threads.size() <= static_cast<u32>(num_to_wake)) { - updated_value = value - 1; + if (num_to_wake <= 0) { + if (waiting_threads.empty()) { + updated_value = value + 1; + } else { + updated_value = value - 1; + } } else { - updated_value = value; + if (waiting_threads.empty()) { + updated_value = value + 1; + } else if (waiting_threads.size() <= static_cast<u32>(num_to_wake)) { + updated_value = value - 1; + } else { + updated_value = value; + } } if (static_cast<s32>(Memory::Read32(address)) != value) { @@ -169,30 +179,22 @@ ResultCode AddressArbiter::WaitForAddressImpl(VAddr address, s64 timeout) { current_thread->WakeAfterDelay(timeout); - system.CpuCore(current_thread->GetProcessorID()).PrepareReschedule(); + system.PrepareReschedule(current_thread->GetProcessorID()); return RESULT_TIMEOUT; } std::vector<SharedPtr<Thread>> AddressArbiter::GetThreadsWaitingOnAddress(VAddr address) const { - const auto RetrieveWaitingThreads = [this](std::size_t core_index, - std::vector<SharedPtr<Thread>>& waiting_threads, - VAddr arb_addr) { - const auto& scheduler = system.Scheduler(core_index); - const auto& thread_list = scheduler.GetThreadList(); - - for (const auto& thread : thread_list) { - if (thread->GetArbiterWaitAddress() == arb_addr) { - waiting_threads.push_back(thread); - } - } - }; // Retrieve all threads that are waiting for this address. std::vector<SharedPtr<Thread>> threads; - RetrieveWaitingThreads(0, threads, address); - RetrieveWaitingThreads(1, threads, address); - RetrieveWaitingThreads(2, threads, address); - RetrieveWaitingThreads(3, threads, address); + const auto& scheduler = system.GlobalScheduler(); + const auto& thread_list = scheduler.GetThreadList(); + + for (const auto& thread : thread_list) { + if (thread->GetArbiterWaitAddress() == address) { + threads.push_back(thread); + } + } // Sort them by priority, such that the highest priority ones come first. std::sort(threads.begin(), threads.end(), diff --git a/src/core/hle/kernel/kernel.cpp b/src/core/hle/kernel/kernel.cpp index 799e5e0d8..f94ac150d 100644 --- a/src/core/hle/kernel/kernel.cpp +++ b/src/core/hle/kernel/kernel.cpp @@ -12,12 +12,15 @@ #include "core/core.h" #include "core/core_timing.h" +#include "core/core_timing_util.h" #include "core/hle/kernel/address_arbiter.h" #include "core/hle/kernel/client_port.h" +#include "core/hle/kernel/errors.h" #include "core/hle/kernel/handle_table.h" #include "core/hle/kernel/kernel.h" #include "core/hle/kernel/process.h" #include "core/hle/kernel/resource_limit.h" +#include "core/hle/kernel/scheduler.h" #include "core/hle/kernel/thread.h" #include "core/hle/lock.h" #include "core/hle/result.h" @@ -58,12 +61,8 @@ static void ThreadWakeupCallback(u64 thread_handle, [[maybe_unused]] s64 cycles_ if (thread->HasWakeupCallback()) { resume = thread->InvokeWakeupCallback(ThreadWakeupReason::Timeout, thread, nullptr, 0); } - } - - if (thread->GetMutexWaitAddress() != 0 || thread->GetCondVarWaitAddress() != 0 || - thread->GetWaitHandle() != 0) { - ASSERT(thread->GetStatus() == ThreadStatus::WaitMutex || - thread->GetStatus() == ThreadStatus::WaitCondVar); + } else if (thread->GetStatus() == ThreadStatus::WaitMutex || + thread->GetStatus() == ThreadStatus::WaitCondVar) { thread->SetMutexWaitAddress(0); thread->SetCondVarWaitAddress(0); thread->SetWaitHandle(0); @@ -83,18 +82,23 @@ static void ThreadWakeupCallback(u64 thread_handle, [[maybe_unused]] s64 cycles_ } if (resume) { + if (thread->GetStatus() == ThreadStatus::WaitCondVar || + thread->GetStatus() == ThreadStatus::WaitArb) { + thread->SetWaitSynchronizationResult(RESULT_TIMEOUT); + } thread->ResumeFromWait(); } } struct KernelCore::Impl { - explicit Impl(Core::System& system) : system{system} {} + explicit Impl(Core::System& system) : system{system}, global_scheduler{system} {} void Initialize(KernelCore& kernel) { Shutdown(); InitializeSystemResourceLimit(kernel); InitializeThreads(); + InitializePreemption(); } void Shutdown() { @@ -110,6 +114,9 @@ struct KernelCore::Impl { thread_wakeup_callback_handle_table.Clear(); thread_wakeup_event_type = nullptr; + preemption_event = nullptr; + + global_scheduler.Shutdown(); named_ports.clear(); } @@ -132,6 +139,18 @@ struct KernelCore::Impl { system.CoreTiming().RegisterEvent("ThreadWakeupCallback", ThreadWakeupCallback); } + void InitializePreemption() { + preemption_event = system.CoreTiming().RegisterEvent( + "PreemptionCallback", [this](u64 userdata, s64 cycles_late) { + global_scheduler.PreemptThreads(); + s64 time_interval = Core::Timing::msToCycles(std::chrono::milliseconds(10)); + system.CoreTiming().ScheduleEvent(time_interval, preemption_event); + }); + + s64 time_interval = Core::Timing::msToCycles(std::chrono::milliseconds(10)); + system.CoreTiming().ScheduleEvent(time_interval, preemption_event); + } + std::atomic<u32> next_object_id{0}; std::atomic<u64> next_kernel_process_id{Process::InitialKIPIDMin}; std::atomic<u64> next_user_process_id{Process::ProcessIDMin}; @@ -140,10 +159,12 @@ struct KernelCore::Impl { // Lists all processes that exist in the current session. std::vector<SharedPtr<Process>> process_list; Process* current_process = nullptr; + Kernel::GlobalScheduler global_scheduler; SharedPtr<ResourceLimit> system_resource_limit; Core::Timing::EventType* thread_wakeup_event_type = nullptr; + Core::Timing::EventType* preemption_event = nullptr; // TODO(yuriks): This can be removed if Thread objects are explicitly pooled in the future, // allowing us to simply use a pool index or similar. Kernel::HandleTable thread_wakeup_callback_handle_table; @@ -203,6 +224,14 @@ const std::vector<SharedPtr<Process>>& KernelCore::GetProcessList() const { return impl->process_list; } +Kernel::GlobalScheduler& KernelCore::GlobalScheduler() { + return impl->global_scheduler; +} + +const Kernel::GlobalScheduler& KernelCore::GlobalScheduler() const { + return impl->global_scheduler; +} + void KernelCore::AddNamedPort(std::string name, SharedPtr<ClientPort> port) { impl->named_ports.emplace(std::move(name), std::move(port)); } diff --git a/src/core/hle/kernel/kernel.h b/src/core/hle/kernel/kernel.h index 0cc44ee76..c4397fc77 100644 --- a/src/core/hle/kernel/kernel.h +++ b/src/core/hle/kernel/kernel.h @@ -21,6 +21,7 @@ namespace Kernel { class AddressArbiter; class ClientPort; +class GlobalScheduler; class HandleTable; class Process; class ResourceLimit; @@ -75,6 +76,12 @@ public: /// Retrieves the list of processes. const std::vector<SharedPtr<Process>>& GetProcessList() const; + /// Gets the sole instance of the global scheduler + Kernel::GlobalScheduler& GlobalScheduler(); + + /// Gets the sole instance of the global scheduler + const Kernel::GlobalScheduler& GlobalScheduler() const; + /// Adds a port to the named port table void AddNamedPort(std::string name, SharedPtr<ClientPort> port); diff --git a/src/core/hle/kernel/mutex.cpp b/src/core/hle/kernel/mutex.cpp index 98e87313b..663d0f4b6 100644 --- a/src/core/hle/kernel/mutex.cpp +++ b/src/core/hle/kernel/mutex.cpp @@ -139,6 +139,9 @@ ResultCode Mutex::Release(VAddr address) { thread->SetCondVarWaitAddress(0); thread->SetMutexWaitAddress(0); thread->SetWaitHandle(0); + thread->SetWaitSynchronizationResult(RESULT_SUCCESS); + + system.PrepareReschedule(); return RESULT_SUCCESS; } diff --git a/src/core/hle/kernel/process.cpp b/src/core/hle/kernel/process.cpp index e80a12ac3..12a900bcc 100644 --- a/src/core/hle/kernel/process.cpp +++ b/src/core/hle/kernel/process.cpp @@ -213,10 +213,7 @@ void Process::PrepareForTermination() { } }; - stop_threads(system.Scheduler(0).GetThreadList()); - stop_threads(system.Scheduler(1).GetThreadList()); - stop_threads(system.Scheduler(2).GetThreadList()); - stop_threads(system.Scheduler(3).GetThreadList()); + stop_threads(system.GlobalScheduler().GetThreadList()); FreeTLSRegion(tls_region_address); tls_region_address = 0; diff --git a/src/core/hle/kernel/scheduler.cpp b/src/core/hle/kernel/scheduler.cpp index e8447b69a..e6dcb9639 100644 --- a/src/core/hle/kernel/scheduler.cpp +++ b/src/core/hle/kernel/scheduler.cpp @@ -1,8 +1,13 @@ // Copyright 2018 yuzu emulator team // Licensed under GPLv2 or any later version // Refer to the license.txt file included. +// +// SelectThreads, Yield functions originally by TuxSH. +// licensed under GPLv2 or later under exception provided by the author. #include <algorithm> +#include <set> +#include <unordered_set> #include <utility> #include "common/assert.h" @@ -17,56 +22,434 @@ namespace Kernel { -std::mutex Scheduler::scheduler_mutex; +GlobalScheduler::GlobalScheduler(Core::System& system) : system{system} { + is_reselection_pending = false; +} + +void GlobalScheduler::AddThread(SharedPtr<Thread> thread) { + thread_list.push_back(std::move(thread)); +} + +void GlobalScheduler::RemoveThread(const Thread* thread) { + thread_list.erase(std::remove(thread_list.begin(), thread_list.end(), thread), + thread_list.end()); +} + +/* + * UnloadThread selects a core and forces it to unload its current thread's context + */ +void GlobalScheduler::UnloadThread(s32 core) { + Scheduler& sched = system.Scheduler(core); + sched.UnloadThread(); +} + +/* + * SelectThread takes care of selecting the new scheduled thread. + * It does it in 3 steps: + * - First a thread is selected from the top of the priority queue. If no thread + * is obtained then we move to step two, else we are done. + * - Second we try to get a suggested thread that's not assigned to any core or + * that is not the top thread in that core. + * - Third is no suggested thread is found, we do a second pass and pick a running + * thread in another core and swap it with its current thread. + */ +void GlobalScheduler::SelectThread(u32 core) { + const auto update_thread = [](Thread* thread, Scheduler& sched) { + if (thread != sched.selected_thread) { + if (thread == nullptr) { + ++sched.idle_selection_count; + } + sched.selected_thread = thread; + } + sched.is_context_switch_pending = sched.selected_thread != sched.current_thread; + std::atomic_thread_fence(std::memory_order_seq_cst); + }; + Scheduler& sched = system.Scheduler(core); + Thread* current_thread = nullptr; + // Step 1: Get top thread in schedule queue. + current_thread = scheduled_queue[core].empty() ? nullptr : scheduled_queue[core].front(); + if (current_thread) { + update_thread(current_thread, sched); + return; + } + // Step 2: Try selecting a suggested thread. + Thread* winner = nullptr; + std::set<s32> sug_cores; + for (auto thread : suggested_queue[core]) { + s32 this_core = thread->GetProcessorID(); + Thread* thread_on_core = nullptr; + if (this_core >= 0) { + thread_on_core = scheduled_queue[this_core].front(); + } + if (this_core < 0 || thread != thread_on_core) { + winner = thread; + break; + } + sug_cores.insert(this_core); + } + // if we got a suggested thread, select it, else do a second pass. + if (winner && winner->GetPriority() > 2) { + if (winner->IsRunning()) { + UnloadThread(winner->GetProcessorID()); + } + TransferToCore(winner->GetPriority(), core, winner); + update_thread(winner, sched); + return; + } + // Step 3: Select a suggested thread from another core + for (auto& src_core : sug_cores) { + auto it = scheduled_queue[src_core].begin(); + it++; + if (it != scheduled_queue[src_core].end()) { + Thread* thread_on_core = scheduled_queue[src_core].front(); + Thread* to_change = *it; + if (thread_on_core->IsRunning() || to_change->IsRunning()) { + UnloadThread(src_core); + } + TransferToCore(thread_on_core->GetPriority(), core, thread_on_core); + current_thread = thread_on_core; + break; + } + } + update_thread(current_thread, sched); +} + +/* + * YieldThread takes a thread and moves it to the back of the it's priority list + * This operation can be redundant and no scheduling is changed if marked as so. + */ +bool GlobalScheduler::YieldThread(Thread* yielding_thread) { + // Note: caller should use critical section, etc. + const u32 core_id = static_cast<u32>(yielding_thread->GetProcessorID()); + const u32 priority = yielding_thread->GetPriority(); + + // Yield the thread + ASSERT_MSG(yielding_thread == scheduled_queue[core_id].front(priority), + "Thread yielding without being in front"); + scheduled_queue[core_id].yield(priority); + + Thread* winner = scheduled_queue[core_id].front(priority); + return AskForReselectionOrMarkRedundant(yielding_thread, winner); +} + +/* + * YieldThreadAndBalanceLoad takes a thread and moves it to the back of the it's priority list. + * Afterwards, tries to pick a suggested thread from the suggested queue that has worse time or + * a better priority than the next thread in the core. + * This operation can be redundant and no scheduling is changed if marked as so. + */ +bool GlobalScheduler::YieldThreadAndBalanceLoad(Thread* yielding_thread) { + // Note: caller should check if !thread.IsSchedulerOperationRedundant and use critical section, + // etc. + const u32 core_id = static_cast<u32>(yielding_thread->GetProcessorID()); + const u32 priority = yielding_thread->GetPriority(); + + // Yield the thread + ASSERT_MSG(yielding_thread == scheduled_queue[core_id].front(priority), + "Thread yielding without being in front"); + scheduled_queue[core_id].yield(priority); + + std::array<Thread*, NUM_CPU_CORES> current_threads; + for (u32 i = 0; i < NUM_CPU_CORES; i++) { + current_threads[i] = scheduled_queue[i].empty() ? nullptr : scheduled_queue[i].front(); + } + + Thread* next_thread = scheduled_queue[core_id].front(priority); + Thread* winner = nullptr; + for (auto& thread : suggested_queue[core_id]) { + const s32 source_core = thread->GetProcessorID(); + if (source_core >= 0) { + if (current_threads[source_core] != nullptr) { + if (thread == current_threads[source_core] || + current_threads[source_core]->GetPriority() < min_regular_priority) { + continue; + } + } + } + if (next_thread->GetLastRunningTicks() >= thread->GetLastRunningTicks() || + next_thread->GetPriority() < thread->GetPriority()) { + if (thread->GetPriority() <= priority) { + winner = thread; + break; + } + } + } + + if (winner != nullptr) { + if (winner != yielding_thread) { + if (winner->IsRunning()) { + UnloadThread(winner->GetProcessorID()); + } + TransferToCore(winner->GetPriority(), core_id, winner); + } + } else { + winner = next_thread; + } + + return AskForReselectionOrMarkRedundant(yielding_thread, winner); +} + +/* + * YieldThreadAndWaitForLoadBalancing takes a thread and moves it out of the scheduling queue + * and into the suggested queue. If no thread can be squeduled afterwards in that core, + * a suggested thread is obtained instead. + * This operation can be redundant and no scheduling is changed if marked as so. + */ +bool GlobalScheduler::YieldThreadAndWaitForLoadBalancing(Thread* yielding_thread) { + // Note: caller should check if !thread.IsSchedulerOperationRedundant and use critical section, + // etc. + Thread* winner = nullptr; + const u32 core_id = static_cast<u32>(yielding_thread->GetProcessorID()); + + // Remove the thread from its scheduled mlq, put it on the corresponding "suggested" one instead + TransferToCore(yielding_thread->GetPriority(), -1, yielding_thread); + + // If the core is idle, perform load balancing, excluding the threads that have just used this + // function... + if (scheduled_queue[core_id].empty()) { + // Here, "current_threads" is calculated after the ""yield"", unlike yield -1 + std::array<Thread*, NUM_CPU_CORES> current_threads; + for (u32 i = 0; i < NUM_CPU_CORES; i++) { + current_threads[i] = scheduled_queue[i].empty() ? nullptr : scheduled_queue[i].front(); + } + for (auto& thread : suggested_queue[core_id]) { + const s32 source_core = thread->GetProcessorID(); + if (source_core < 0 || thread == current_threads[source_core]) { + continue; + } + if (current_threads[source_core] == nullptr || + current_threads[source_core]->GetPriority() >= min_regular_priority) { + winner = thread; + } + break; + } + if (winner != nullptr) { + if (winner != yielding_thread) { + if (winner->IsRunning()) { + UnloadThread(winner->GetProcessorID()); + } + TransferToCore(winner->GetPriority(), core_id, winner); + } + } else { + winner = yielding_thread; + } + } + + return AskForReselectionOrMarkRedundant(yielding_thread, winner); +} + +void GlobalScheduler::PreemptThreads() { + for (std::size_t core_id = 0; core_id < NUM_CPU_CORES; core_id++) { + const u32 priority = preemption_priorities[core_id]; + + if (scheduled_queue[core_id].size(priority) > 0) { + scheduled_queue[core_id].front(priority)->IncrementYieldCount(); + scheduled_queue[core_id].yield(priority); + if (scheduled_queue[core_id].size(priority) > 1) { + scheduled_queue[core_id].front(priority)->IncrementYieldCount(); + } + } + + Thread* current_thread = + scheduled_queue[core_id].empty() ? nullptr : scheduled_queue[core_id].front(); + Thread* winner = nullptr; + for (auto& thread : suggested_queue[core_id]) { + const s32 source_core = thread->GetProcessorID(); + if (thread->GetPriority() != priority) { + continue; + } + if (source_core >= 0) { + Thread* next_thread = scheduled_queue[source_core].empty() + ? nullptr + : scheduled_queue[source_core].front(); + if (next_thread != nullptr && next_thread->GetPriority() < 2) { + break; + } + if (next_thread == thread) { + continue; + } + } + if (current_thread != nullptr && + current_thread->GetLastRunningTicks() >= thread->GetLastRunningTicks()) { + winner = thread; + break; + } + } + + if (winner != nullptr) { + if (winner->IsRunning()) { + UnloadThread(winner->GetProcessorID()); + } + TransferToCore(winner->GetPriority(), core_id, winner); + current_thread = + winner->GetPriority() <= current_thread->GetPriority() ? winner : current_thread; + } + + if (current_thread != nullptr && current_thread->GetPriority() > priority) { + for (auto& thread : suggested_queue[core_id]) { + const s32 source_core = thread->GetProcessorID(); + if (thread->GetPriority() < priority) { + continue; + } + if (source_core >= 0) { + Thread* next_thread = scheduled_queue[source_core].empty() + ? nullptr + : scheduled_queue[source_core].front(); + if (next_thread != nullptr && next_thread->GetPriority() < 2) { + break; + } + if (next_thread == thread) { + continue; + } + } + if (current_thread != nullptr && + current_thread->GetLastRunningTicks() >= thread->GetLastRunningTicks()) { + winner = thread; + break; + } + } + + if (winner != nullptr) { + if (winner->IsRunning()) { + UnloadThread(winner->GetProcessorID()); + } + TransferToCore(winner->GetPriority(), core_id, winner); + current_thread = winner; + } + } + + is_reselection_pending.store(true, std::memory_order_release); + } +} + +void GlobalScheduler::Suggest(u32 priority, u32 core, Thread* thread) { + suggested_queue[core].add(thread, priority); +} + +void GlobalScheduler::Unsuggest(u32 priority, u32 core, Thread* thread) { + suggested_queue[core].remove(thread, priority); +} + +void GlobalScheduler::Schedule(u32 priority, u32 core, Thread* thread) { + ASSERT_MSG(thread->GetProcessorID() == core, "Thread must be assigned to this core."); + scheduled_queue[core].add(thread, priority); +} + +void GlobalScheduler::SchedulePrepend(u32 priority, u32 core, Thread* thread) { + ASSERT_MSG(thread->GetProcessorID() == core, "Thread must be assigned to this core."); + scheduled_queue[core].add(thread, priority, false); +} + +void GlobalScheduler::Reschedule(u32 priority, u32 core, Thread* thread) { + scheduled_queue[core].remove(thread, priority); + scheduled_queue[core].add(thread, priority); +} + +void GlobalScheduler::Unschedule(u32 priority, u32 core, Thread* thread) { + scheduled_queue[core].remove(thread, priority); +} + +void GlobalScheduler::TransferToCore(u32 priority, s32 destination_core, Thread* thread) { + const bool schedulable = thread->GetPriority() < THREADPRIO_COUNT; + const s32 source_core = thread->GetProcessorID(); + if (source_core == destination_core || !schedulable) { + return; + } + thread->SetProcessorID(destination_core); + if (source_core >= 0) { + Unschedule(priority, source_core, thread); + } + if (destination_core >= 0) { + Unsuggest(priority, destination_core, thread); + Schedule(priority, destination_core, thread); + } + if (source_core >= 0) { + Suggest(priority, source_core, thread); + } +} -Scheduler::Scheduler(Core::System& system, Core::ARM_Interface& cpu_core) - : cpu_core{cpu_core}, system{system} {} +bool GlobalScheduler::AskForReselectionOrMarkRedundant(Thread* current_thread, Thread* winner) { + if (current_thread == winner) { + current_thread->IncrementYieldCount(); + return true; + } else { + is_reselection_pending.store(true, std::memory_order_release); + return false; + } +} -Scheduler::~Scheduler() { - for (auto& thread : thread_list) { - thread->Stop(); +void GlobalScheduler::Shutdown() { + for (std::size_t core = 0; core < NUM_CPU_CORES; core++) { + scheduled_queue[core].clear(); + suggested_queue[core].clear(); } + thread_list.clear(); } +GlobalScheduler::~GlobalScheduler() = default; + +Scheduler::Scheduler(Core::System& system, Core::ARM_Interface& cpu_core, u32 core_id) + : system(system), cpu_core(cpu_core), core_id(core_id) {} + +Scheduler::~Scheduler() = default; + bool Scheduler::HaveReadyThreads() const { - std::lock_guard lock{scheduler_mutex}; - return !ready_queue.empty(); + return system.GlobalScheduler().HaveReadyThreads(core_id); } Thread* Scheduler::GetCurrentThread() const { return current_thread.get(); } +Thread* Scheduler::GetSelectedThread() const { + return selected_thread.get(); +} + +void Scheduler::SelectThreads() { + system.GlobalScheduler().SelectThread(core_id); +} + u64 Scheduler::GetLastContextSwitchTicks() const { return last_context_switch_time; } -Thread* Scheduler::PopNextReadyThread() { - Thread* next = nullptr; - Thread* thread = GetCurrentThread(); +void Scheduler::TryDoContextSwitch() { + if (is_context_switch_pending) { + SwitchContext(); + } +} - if (thread && thread->GetStatus() == ThreadStatus::Running) { - if (ready_queue.empty()) { - return thread; - } - // We have to do better than the current thread. - // This call returns null when that's not possible. - next = ready_queue.front(); - if (next == nullptr || next->GetPriority() >= thread->GetPriority()) { - next = thread; - } - } else { - if (ready_queue.empty()) { - return nullptr; +void Scheduler::UnloadThread() { + Thread* const previous_thread = GetCurrentThread(); + Process* const previous_process = system.Kernel().CurrentProcess(); + + UpdateLastContextSwitchTime(previous_thread, previous_process); + + // Save context for previous thread + if (previous_thread) { + cpu_core.SaveContext(previous_thread->GetContext()); + // Save the TPIDR_EL0 system register in case it was modified. + previous_thread->SetTPIDR_EL0(cpu_core.GetTPIDR_EL0()); + + if (previous_thread->GetStatus() == ThreadStatus::Running) { + // This is only the case when a reschedule is triggered without the current thread + // yielding execution (i.e. an event triggered, system core time-sliced, etc) + previous_thread->SetStatus(ThreadStatus::Ready); } - next = ready_queue.front(); + previous_thread->SetIsRunning(false); } - - return next; + current_thread = nullptr; } -void Scheduler::SwitchContext(Thread* new_thread) { - Thread* previous_thread = GetCurrentThread(); +void Scheduler::SwitchContext() { + Thread* const previous_thread = GetCurrentThread(); + Thread* const new_thread = GetSelectedThread(); + + is_context_switch_pending = false; + if (new_thread == previous_thread) { + return; + } + Process* const previous_process = system.Kernel().CurrentProcess(); UpdateLastContextSwitchTime(previous_thread, previous_process); @@ -80,23 +463,23 @@ void Scheduler::SwitchContext(Thread* new_thread) { if (previous_thread->GetStatus() == ThreadStatus::Running) { // This is only the case when a reschedule is triggered without the current thread // yielding execution (i.e. an event triggered, system core time-sliced, etc) - ready_queue.add(previous_thread, previous_thread->GetPriority(), false); previous_thread->SetStatus(ThreadStatus::Ready); } + previous_thread->SetIsRunning(false); } // Load context of new thread if (new_thread) { + ASSERT_MSG(new_thread->GetProcessorID() == this->core_id, + "Thread must be assigned to this core."); ASSERT_MSG(new_thread->GetStatus() == ThreadStatus::Ready, "Thread must be ready to become running."); // Cancel any outstanding wakeup events for this thread new_thread->CancelWakeupTimer(); - current_thread = new_thread; - - ready_queue.remove(new_thread, new_thread->GetPriority()); new_thread->SetStatus(ThreadStatus::Running); + new_thread->SetIsRunning(true); auto* const thread_owner_process = current_thread->GetOwnerProcess(); if (previous_process != thread_owner_process) { @@ -130,124 +513,9 @@ void Scheduler::UpdateLastContextSwitchTime(Thread* thread, Process* process) { last_context_switch_time = most_recent_switch_ticks; } -void Scheduler::Reschedule() { - std::lock_guard lock{scheduler_mutex}; - - Thread* cur = GetCurrentThread(); - Thread* next = PopNextReadyThread(); - - if (cur && next) { - LOG_TRACE(Kernel, "context switch {} -> {}", cur->GetObjectId(), next->GetObjectId()); - } else if (cur) { - LOG_TRACE(Kernel, "context switch {} -> idle", cur->GetObjectId()); - } else if (next) { - LOG_TRACE(Kernel, "context switch idle -> {}", next->GetObjectId()); - } - - SwitchContext(next); -} - -void Scheduler::AddThread(SharedPtr<Thread> thread) { - std::lock_guard lock{scheduler_mutex}; - - thread_list.push_back(std::move(thread)); -} - -void Scheduler::RemoveThread(Thread* thread) { - std::lock_guard lock{scheduler_mutex}; - - thread_list.erase(std::remove(thread_list.begin(), thread_list.end(), thread), - thread_list.end()); -} - -void Scheduler::ScheduleThread(Thread* thread, u32 priority) { - std::lock_guard lock{scheduler_mutex}; - - ASSERT(thread->GetStatus() == ThreadStatus::Ready); - ready_queue.add(thread, priority); -} - -void Scheduler::UnscheduleThread(Thread* thread, u32 priority) { - std::lock_guard lock{scheduler_mutex}; - - ASSERT(thread->GetStatus() == ThreadStatus::Ready); - ready_queue.remove(thread, priority); -} - -void Scheduler::SetThreadPriority(Thread* thread, u32 priority) { - std::lock_guard lock{scheduler_mutex}; - if (thread->GetPriority() == priority) { - return; - } - - // If thread was ready, adjust queues - if (thread->GetStatus() == ThreadStatus::Ready) - ready_queue.adjust(thread, thread->GetPriority(), priority); -} - -Thread* Scheduler::GetNextSuggestedThread(u32 core, u32 maximum_priority) const { - std::lock_guard lock{scheduler_mutex}; - - const u32 mask = 1U << core; - for (auto* thread : ready_queue) { - if ((thread->GetAffinityMask() & mask) != 0 && thread->GetPriority() < maximum_priority) { - return thread; - } - } - return nullptr; -} - -void Scheduler::YieldWithoutLoadBalancing(Thread* thread) { - ASSERT(thread != nullptr); - // Avoid yielding if the thread isn't even running. - ASSERT(thread->GetStatus() == ThreadStatus::Running); - - // Sanity check that the priority is valid - ASSERT(thread->GetPriority() < THREADPRIO_COUNT); - - // Yield this thread -- sleep for zero time and force reschedule to different thread - GetCurrentThread()->Sleep(0); -} - -void Scheduler::YieldWithLoadBalancing(Thread* thread) { - ASSERT(thread != nullptr); - const auto priority = thread->GetPriority(); - const auto core = static_cast<u32>(thread->GetProcessorID()); - - // Avoid yielding if the thread isn't even running. - ASSERT(thread->GetStatus() == ThreadStatus::Running); - - // Sanity check that the priority is valid - ASSERT(priority < THREADPRIO_COUNT); - - // Sleep for zero time to be able to force reschedule to different thread - GetCurrentThread()->Sleep(0); - - Thread* suggested_thread = nullptr; - - // Search through all of the cpu cores (except this one) for a suggested thread. - // Take the first non-nullptr one - for (unsigned cur_core = 0; cur_core < Core::NUM_CPU_CORES; ++cur_core) { - const auto res = - system.CpuCore(cur_core).Scheduler().GetNextSuggestedThread(core, priority); - - // If scheduler provides a suggested thread - if (res != nullptr) { - // And its better than the current suggested thread (or is the first valid one) - if (suggested_thread == nullptr || - suggested_thread->GetPriority() > res->GetPriority()) { - suggested_thread = res; - } - } - } - - // If a suggested thread was found, queue that for this core - if (suggested_thread != nullptr) - suggested_thread->ChangeCore(core, suggested_thread->GetAffinityMask()); -} - -void Scheduler::YieldAndWaitForLoadBalancing(Thread* thread) { - UNIMPLEMENTED_MSG("Wait for load balancing thread yield type is not implemented!"); +void Scheduler::Shutdown() { + current_thread = nullptr; + selected_thread = nullptr; } } // namespace Kernel diff --git a/src/core/hle/kernel/scheduler.h b/src/core/hle/kernel/scheduler.h index b29bf7be8..fcae28e0a 100644 --- a/src/core/hle/kernel/scheduler.h +++ b/src/core/hle/kernel/scheduler.h @@ -20,124 +20,172 @@ namespace Kernel { class Process; -class Scheduler final { +class GlobalScheduler final { public: - explicit Scheduler(Core::System& system, Core::ARM_Interface& cpu_core); - ~Scheduler(); + static constexpr u32 NUM_CPU_CORES = 4; - /// Returns whether there are any threads that are ready to run. - bool HaveReadyThreads() const; + explicit GlobalScheduler(Core::System& system); + ~GlobalScheduler(); + /// Adds a new thread to the scheduler + void AddThread(SharedPtr<Thread> thread); - /// Reschedules to the next available thread (call after current thread is suspended) - void Reschedule(); + /// Removes a thread from the scheduler + void RemoveThread(const Thread* thread); - /// Gets the current running thread - Thread* GetCurrentThread() const; + /// Returns a list of all threads managed by the scheduler + const std::vector<SharedPtr<Thread>>& GetThreadList() const { + return thread_list; + } - /// Gets the timestamp for the last context switch in ticks. - u64 GetLastContextSwitchTicks() const; + // Add a thread to the suggested queue of a cpu core. Suggested threads may be + // picked if no thread is scheduled to run on the core. + void Suggest(u32 priority, u32 core, Thread* thread); - /// Adds a new thread to the scheduler - void AddThread(SharedPtr<Thread> thread); + // Remove a thread to the suggested queue of a cpu core. Suggested threads may be + // picked if no thread is scheduled to run on the core. + void Unsuggest(u32 priority, u32 core, Thread* thread); - /// Removes a thread from the scheduler - void RemoveThread(Thread* thread); + // Add a thread to the scheduling queue of a cpu core. The thread is added at the + // back the queue in its priority level + void Schedule(u32 priority, u32 core, Thread* thread); - /// Schedules a thread that has become "ready" - void ScheduleThread(Thread* thread, u32 priority); + // Add a thread to the scheduling queue of a cpu core. The thread is added at the + // front the queue in its priority level + void SchedulePrepend(u32 priority, u32 core, Thread* thread); - /// Unschedules a thread that was already scheduled - void UnscheduleThread(Thread* thread, u32 priority); + // Reschedule an already scheduled thread based on a new priority + void Reschedule(u32 priority, u32 core, Thread* thread); - /// Sets the priority of a thread in the scheduler - void SetThreadPriority(Thread* thread, u32 priority); + // Unschedule a thread. + void Unschedule(u32 priority, u32 core, Thread* thread); - /// Gets the next suggested thread for load balancing - Thread* GetNextSuggestedThread(u32 core, u32 minimum_priority) const; + // Transfers a thread into an specific core. If the destination_core is -1 + // it will be unscheduled from its source code and added into its suggested + // queue. + void TransferToCore(u32 priority, s32 destination_core, Thread* thread); - /** - * YieldWithoutLoadBalancing -- analogous to normal yield on a system - * Moves the thread to the end of the ready queue for its priority, and then reschedules the - * system to the new head of the queue. - * - * Example (Single Core -- but can be extrapolated to multi): - * ready_queue[prio=0]: ThreadA, ThreadB, ThreadC (->exec order->) - * Currently Running: ThreadR - * - * ThreadR calls YieldWithoutLoadBalancing - * - * ThreadR is moved to the end of ready_queue[prio=0]: - * ready_queue[prio=0]: ThreadA, ThreadB, ThreadC, ThreadR (->exec order->) - * Currently Running: Nothing - * - * System is rescheduled (ThreadA is popped off of queue): - * ready_queue[prio=0]: ThreadB, ThreadC, ThreadR (->exec order->) - * Currently Running: ThreadA - * - * If the queue is empty at time of call, no yielding occurs. This does not cross between cores - * or priorities at all. + /* + * UnloadThread selects a core and forces it to unload its current thread's context */ - void YieldWithoutLoadBalancing(Thread* thread); + void UnloadThread(s32 core); + + /* + * SelectThread takes care of selecting the new scheduled thread. + * It does it in 3 steps: + * - First a thread is selected from the top of the priority queue. If no thread + * is obtained then we move to step two, else we are done. + * - Second we try to get a suggested thread that's not assigned to any core or + * that is not the top thread in that core. + * - Third is no suggested thread is found, we do a second pass and pick a running + * thread in another core and swap it with its current thread. + */ + void SelectThread(u32 core); - /** - * YieldWithLoadBalancing -- yield but with better selection of the new running thread - * Moves the current thread to the end of the ready queue for its priority, then selects a - * 'suggested thread' (a thread on a different core that could run on this core) from the - * scheduler, changes its core, and reschedules the current core to that thread. - * - * Example (Dual Core -- can be extrapolated to Quad Core, this is just normal yield if it were - * single core): - * ready_queue[core=0][prio=0]: ThreadA, ThreadB (affinities not pictured as irrelevant - * ready_queue[core=1][prio=0]: ThreadC[affinity=both], ThreadD[affinity=core1only] - * Currently Running: ThreadQ on Core 0 || ThreadP on Core 1 - * - * ThreadQ calls YieldWithLoadBalancing - * - * ThreadQ is moved to the end of ready_queue[core=0][prio=0]: - * ready_queue[core=0][prio=0]: ThreadA, ThreadB - * ready_queue[core=1][prio=0]: ThreadC[affinity=both], ThreadD[affinity=core1only] - * Currently Running: ThreadQ on Core 0 || ThreadP on Core 1 - * - * A list of suggested threads for each core is compiled - * Suggested Threads: {ThreadC on Core 1} - * If this were quad core (as the switch is), there could be between 0 and 3 threads in this - * list. If there are more than one, the thread is selected by highest prio. - * - * ThreadC is core changed to Core 0: - * ready_queue[core=0][prio=0]: ThreadC, ThreadA, ThreadB, ThreadQ - * ready_queue[core=1][prio=0]: ThreadD - * Currently Running: None on Core 0 || ThreadP on Core 1 - * - * System is rescheduled (ThreadC is popped off of queue): - * ready_queue[core=0][prio=0]: ThreadA, ThreadB, ThreadQ - * ready_queue[core=1][prio=0]: ThreadD - * Currently Running: ThreadC on Core 0 || ThreadP on Core 1 - * - * If no suggested threads can be found this will behave just as normal yield. If there are - * multiple candidates for the suggested thread on a core, the highest prio is taken. + bool HaveReadyThreads(u32 core_id) const { + return !scheduled_queue[core_id].empty(); + } + + /* + * YieldThread takes a thread and moves it to the back of the it's priority list + * This operation can be redundant and no scheduling is changed if marked as so. */ - void YieldWithLoadBalancing(Thread* thread); + bool YieldThread(Thread* thread); - /// Currently unknown -- asserts as unimplemented on call - void YieldAndWaitForLoadBalancing(Thread* thread); + /* + * YieldThreadAndBalanceLoad takes a thread and moves it to the back of the it's priority list. + * Afterwards, tries to pick a suggested thread from the suggested queue that has worse time or + * a better priority than the next thread in the core. + * This operation can be redundant and no scheduling is changed if marked as so. + */ + bool YieldThreadAndBalanceLoad(Thread* thread); - /// Returns a list of all threads managed by the scheduler - const std::vector<SharedPtr<Thread>>& GetThreadList() const { - return thread_list; + /* + * YieldThreadAndWaitForLoadBalancing takes a thread and moves it out of the scheduling queue + * and into the suggested queue. If no thread can be squeduled afterwards in that core, + * a suggested thread is obtained instead. + * This operation can be redundant and no scheduling is changed if marked as so. + */ + bool YieldThreadAndWaitForLoadBalancing(Thread* thread); + + /* + * PreemptThreads this operation rotates the scheduling queues of threads at + * a preemption priority and then does some core rebalancing. Preemption priorities + * can be found in the array 'preemption_priorities'. This operation happens + * every 10ms. + */ + void PreemptThreads(); + + u32 CpuCoresCount() const { + return NUM_CPU_CORES; + } + + void SetReselectionPending() { + is_reselection_pending.store(true, std::memory_order_release); } + bool IsReselectionPending() const { + return is_reselection_pending.load(std::memory_order_acquire); + } + + void Shutdown(); + private: - /** - * Pops and returns the next thread from the thread queue - * @return A pointer to the next ready thread - */ - Thread* PopNextReadyThread(); + bool AskForReselectionOrMarkRedundant(Thread* current_thread, Thread* winner); + + static constexpr u32 min_regular_priority = 2; + std::array<Common::MultiLevelQueue<Thread*, THREADPRIO_COUNT>, NUM_CPU_CORES> scheduled_queue; + std::array<Common::MultiLevelQueue<Thread*, THREADPRIO_COUNT>, NUM_CPU_CORES> suggested_queue; + std::atomic<bool> is_reselection_pending; + + // `preemption_priorities` are the priority levels at which the global scheduler + // preempts threads every 10 ms. They are ordered from Core 0 to Core 3 + std::array<u32, NUM_CPU_CORES> preemption_priorities = {59, 59, 59, 62}; + + /// Lists all thread ids that aren't deleted/etc. + std::vector<SharedPtr<Thread>> thread_list; + Core::System& system; +}; + +class Scheduler final { +public: + explicit Scheduler(Core::System& system, Core::ARM_Interface& cpu_core, u32 core_id); + ~Scheduler(); + + /// Returns whether there are any threads that are ready to run. + bool HaveReadyThreads() const; + /// Reschedules to the next available thread (call after current thread is suspended) + void TryDoContextSwitch(); + + /// Unloads currently running thread + void UnloadThread(); + + /// Select the threads in top of the scheduling multilist. + void SelectThreads(); + + /// Gets the current running thread + Thread* GetCurrentThread() const; + + /// Gets the currently selected thread from the top of the multilevel queue + Thread* GetSelectedThread() const; + + /// Gets the timestamp for the last context switch in ticks. + u64 GetLastContextSwitchTicks() const; + + bool ContextSwitchPending() const { + return is_context_switch_pending; + } + + /// Shutdowns the scheduler. + void Shutdown(); + +private: + friend class GlobalScheduler; /** * Switches the CPU's active thread context to that of the specified thread * @param new_thread The thread to switch to */ - void SwitchContext(Thread* new_thread); + void SwitchContext(); /** * Called on every context switch to update the internal timestamp @@ -152,19 +200,16 @@ private: */ void UpdateLastContextSwitchTime(Thread* thread, Process* process); - /// Lists all thread ids that aren't deleted/etc. - std::vector<SharedPtr<Thread>> thread_list; - - /// Lists only ready thread ids. - Common::MultiLevelQueue<Thread*, THREADPRIO_LOWEST + 1> ready_queue; - SharedPtr<Thread> current_thread = nullptr; + SharedPtr<Thread> selected_thread = nullptr; + Core::System& system; Core::ARM_Interface& cpu_core; u64 last_context_switch_time = 0; + u64 idle_selection_count = 0; + const u32 core_id; - Core::System& system; - static std::mutex scheduler_mutex; + bool is_context_switch_pending = false; }; } // namespace Kernel diff --git a/src/core/hle/kernel/svc.cpp b/src/core/hle/kernel/svc.cpp index 1fd1a732a..f64236be1 100644 --- a/src/core/hle/kernel/svc.cpp +++ b/src/core/hle/kernel/svc.cpp @@ -516,7 +516,7 @@ static ResultCode WaitSynchronization(Core::System& system, Handle* index, VAddr thread->WakeAfterDelay(nano_seconds); thread->SetWakeupCallback(DefaultThreadWakeupCallback); - system.CpuCore(thread->GetProcessorID()).PrepareReschedule(); + system.PrepareReschedule(thread->GetProcessorID()); return RESULT_TIMEOUT; } @@ -534,6 +534,7 @@ static ResultCode CancelSynchronization(Core::System& system, Handle thread_hand } thread->CancelWait(); + system.PrepareReschedule(thread->GetProcessorID()); return RESULT_SUCCESS; } @@ -1066,6 +1067,8 @@ static ResultCode SetThreadActivity(Core::System& system, Handle handle, u32 act } thread->SetActivity(static_cast<ThreadActivity>(activity)); + + system.PrepareReschedule(thread->GetProcessorID()); return RESULT_SUCCESS; } @@ -1147,7 +1150,7 @@ static ResultCode SetThreadPriority(Core::System& system, Handle handle, u32 pri thread->SetPriority(priority); - system.CpuCore(thread->GetProcessorID()).PrepareReschedule(); + system.PrepareReschedule(thread->GetProcessorID()); return RESULT_SUCCESS; } @@ -1503,7 +1506,7 @@ static ResultCode CreateThread(Core::System& system, Handle* out_handle, VAddr e thread->SetName( fmt::format("thread[entry_point={:X}, handle={:X}]", entry_point, *new_thread_handle)); - system.CpuCore(thread->GetProcessorID()).PrepareReschedule(); + system.PrepareReschedule(thread->GetProcessorID()); return RESULT_SUCCESS; } @@ -1525,7 +1528,7 @@ static ResultCode StartThread(Core::System& system, Handle thread_handle) { thread->ResumeFromWait(); if (thread->GetStatus() == ThreadStatus::Ready) { - system.CpuCore(thread->GetProcessorID()).PrepareReschedule(); + system.PrepareReschedule(thread->GetProcessorID()); } return RESULT_SUCCESS; @@ -1537,7 +1540,7 @@ static void ExitThread(Core::System& system) { auto* const current_thread = system.CurrentScheduler().GetCurrentThread(); current_thread->Stop(); - system.CurrentScheduler().RemoveThread(current_thread); + system.GlobalScheduler().RemoveThread(current_thread); system.PrepareReschedule(); } @@ -1553,17 +1556,18 @@ static void SleepThread(Core::System& system, s64 nanoseconds) { auto& scheduler = system.CurrentScheduler(); auto* const current_thread = scheduler.GetCurrentThread(); + bool is_redundant = false; if (nanoseconds <= 0) { switch (static_cast<SleepType>(nanoseconds)) { case SleepType::YieldWithoutLoadBalancing: - scheduler.YieldWithoutLoadBalancing(current_thread); + is_redundant = current_thread->YieldSimple(); break; case SleepType::YieldWithLoadBalancing: - scheduler.YieldWithLoadBalancing(current_thread); + is_redundant = current_thread->YieldAndBalanceLoad(); break; case SleepType::YieldAndWaitForLoadBalancing: - scheduler.YieldAndWaitForLoadBalancing(current_thread); + is_redundant = current_thread->YieldAndWaitForLoadBalancing(); break; default: UNREACHABLE_MSG("Unimplemented sleep yield type '{:016X}'!", nanoseconds); @@ -1572,10 +1576,13 @@ static void SleepThread(Core::System& system, s64 nanoseconds) { current_thread->Sleep(nanoseconds); } - // Reschedule all CPU cores - for (std::size_t i = 0; i < Core::NUM_CPU_CORES; ++i) { - system.CpuCore(i).PrepareReschedule(); + if (is_redundant) { + // If it's redundant, the core is pretty much idle. Some games keep idling + // a core while it's doing nothing, we advance timing to avoid costly continuous + // calls. + system.CoreTiming().AddTicks(2000); } + system.PrepareReschedule(current_thread->GetProcessorID()); } /// Wait process wide key atomic @@ -1601,6 +1608,8 @@ static ResultCode WaitProcessWideKeyAtomic(Core::System& system, VAddr mutex_add return ERR_INVALID_ADDRESS; } + ASSERT(condition_variable_addr == Common::AlignDown(condition_variable_addr, 4)); + auto* const current_process = system.Kernel().CurrentProcess(); const auto& handle_table = current_process->GetHandleTable(); SharedPtr<Thread> thread = handle_table.Get<Thread>(thread_handle); @@ -1622,7 +1631,7 @@ static ResultCode WaitProcessWideKeyAtomic(Core::System& system, VAddr mutex_add // Note: Deliberately don't attempt to inherit the lock owner's priority. - system.CpuCore(current_thread->GetProcessorID()).PrepareReschedule(); + system.PrepareReschedule(current_thread->GetProcessorID()); return RESULT_SUCCESS; } @@ -1632,24 +1641,19 @@ static ResultCode SignalProcessWideKey(Core::System& system, VAddr condition_var LOG_TRACE(Kernel_SVC, "called, condition_variable_addr=0x{:X}, target=0x{:08X}", condition_variable_addr, target); - const auto RetrieveWaitingThreads = [&system](std::size_t core_index, - std::vector<SharedPtr<Thread>>& waiting_threads, - VAddr condvar_addr) { - const auto& scheduler = system.Scheduler(core_index); - const auto& thread_list = scheduler.GetThreadList(); - - for (const auto& thread : thread_list) { - if (thread->GetCondVarWaitAddress() == condvar_addr) - waiting_threads.push_back(thread); - } - }; + ASSERT(condition_variable_addr == Common::AlignDown(condition_variable_addr, 4)); // Retrieve a list of all threads that are waiting for this condition variable. std::vector<SharedPtr<Thread>> waiting_threads; - RetrieveWaitingThreads(0, waiting_threads, condition_variable_addr); - RetrieveWaitingThreads(1, waiting_threads, condition_variable_addr); - RetrieveWaitingThreads(2, waiting_threads, condition_variable_addr); - RetrieveWaitingThreads(3, waiting_threads, condition_variable_addr); + const auto& scheduler = system.GlobalScheduler(); + const auto& thread_list = scheduler.GetThreadList(); + + for (const auto& thread : thread_list) { + if (thread->GetCondVarWaitAddress() == condition_variable_addr) { + waiting_threads.push_back(thread); + } + } + // Sort them by priority, such that the highest priority ones come first. std::sort(waiting_threads.begin(), waiting_threads.end(), [](const SharedPtr<Thread>& lhs, const SharedPtr<Thread>& rhs) { @@ -1679,18 +1683,20 @@ static ResultCode SignalProcessWideKey(Core::System& system, VAddr condition_var // Atomically read the value of the mutex. u32 mutex_val = 0; + u32 update_val = 0; + const VAddr mutex_address = thread->GetMutexWaitAddress(); do { - monitor.SetExclusive(current_core, thread->GetMutexWaitAddress()); + monitor.SetExclusive(current_core, mutex_address); // If the mutex is not yet acquired, acquire it. - mutex_val = Memory::Read32(thread->GetMutexWaitAddress()); + mutex_val = Memory::Read32(mutex_address); if (mutex_val != 0) { - monitor.ClearExclusive(); - break; + update_val = mutex_val | Mutex::MutexHasWaitersFlag; + } else { + update_val = thread->GetWaitHandle(); } - } while (!monitor.ExclusiveWrite32(current_core, thread->GetMutexWaitAddress(), - thread->GetWaitHandle())); + } while (!monitor.ExclusiveWrite32(current_core, mutex_address, update_val)); if (mutex_val == 0) { // We were able to acquire the mutex, resume this thread. ASSERT(thread->GetStatus() == ThreadStatus::WaitCondVar); @@ -1704,20 +1710,9 @@ static ResultCode SignalProcessWideKey(Core::System& system, VAddr condition_var thread->SetLockOwner(nullptr); thread->SetMutexWaitAddress(0); thread->SetWaitHandle(0); - system.CpuCore(thread->GetProcessorID()).PrepareReschedule(); + thread->SetWaitSynchronizationResult(RESULT_SUCCESS); + system.PrepareReschedule(thread->GetProcessorID()); } else { - // Atomically signal that the mutex now has a waiting thread. - do { - monitor.SetExclusive(current_core, thread->GetMutexWaitAddress()); - - // Ensure that the mutex value is still what we expect. - u32 value = Memory::Read32(thread->GetMutexWaitAddress()); - // TODO(Subv): When this happens, the kernel just clears the exclusive state and - // retries the initial read for this thread. - ASSERT_MSG(mutex_val == value, "Unhandled synchronization primitive case"); - } while (!monitor.ExclusiveWrite32(current_core, thread->GetMutexWaitAddress(), - mutex_val | Mutex::MutexHasWaitersFlag)); - // The mutex is already owned by some other thread, make this thread wait on it. const Handle owner_handle = static_cast<Handle>(mutex_val & Mutex::MutexOwnerMask); const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable(); @@ -1728,6 +1723,7 @@ static ResultCode SignalProcessWideKey(Core::System& system, VAddr condition_var thread->SetStatus(ThreadStatus::WaitMutex); owner->AddMutexWaiter(thread); + system.PrepareReschedule(thread->GetProcessorID()); } } @@ -1754,7 +1750,12 @@ static ResultCode WaitForAddress(Core::System& system, VAddr address, u32 type, const auto arbitration_type = static_cast<AddressArbiter::ArbitrationType>(type); auto& address_arbiter = system.Kernel().CurrentProcess()->GetAddressArbiter(); - return address_arbiter.WaitForAddress(address, arbitration_type, value, timeout); + const ResultCode result = + address_arbiter.WaitForAddress(address, arbitration_type, value, timeout); + if (result == RESULT_SUCCESS) { + system.PrepareReschedule(); + } + return result; } // Signals to an address (via Address Arbiter) @@ -2040,7 +2041,10 @@ static ResultCode SetThreadCoreMask(Core::System& system, Handle thread_handle, return ERR_INVALID_HANDLE; } + system.PrepareReschedule(thread->GetProcessorID()); thread->ChangeCore(core, affinity_mask); + system.PrepareReschedule(thread->GetProcessorID()); + return RESULT_SUCCESS; } @@ -2151,6 +2155,7 @@ static ResultCode SignalEvent(Core::System& system, Handle handle) { } writable_event->Signal(); + system.PrepareReschedule(); return RESULT_SUCCESS; } diff --git a/src/core/hle/kernel/thread.cpp b/src/core/hle/kernel/thread.cpp index ec529e7f2..962530d2d 100644 --- a/src/core/hle/kernel/thread.cpp +++ b/src/core/hle/kernel/thread.cpp @@ -45,15 +45,7 @@ void Thread::Stop() { callback_handle); kernel.ThreadWakeupCallbackHandleTable().Close(callback_handle); callback_handle = 0; - - // Clean up thread from ready queue - // This is only needed when the thread is terminated forcefully (SVC TerminateProcess) - if (status == ThreadStatus::Ready || status == ThreadStatus::Paused) { - scheduler->UnscheduleThread(this, current_priority); - } - - status = ThreadStatus::Dead; - + SetStatus(ThreadStatus::Dead); WakeupAllWaitingThreads(); // Clean up any dangling references in objects that this thread was waiting for @@ -132,17 +124,16 @@ void Thread::ResumeFromWait() { wakeup_callback = nullptr; if (activity == ThreadActivity::Paused) { - status = ThreadStatus::Paused; + SetStatus(ThreadStatus::Paused); return; } - status = ThreadStatus::Ready; - - ChangeScheduler(); + SetStatus(ThreadStatus::Ready); } void Thread::CancelWait() { ASSERT(GetStatus() == ThreadStatus::WaitSynch); + ClearWaitObjects(); SetWaitSynchronizationResult(ERR_SYNCHRONIZATION_CANCELED); ResumeFromWait(); } @@ -205,9 +196,9 @@ ResultVal<SharedPtr<Thread>> Thread::Create(KernelCore& kernel, std::string name thread->name = std::move(name); thread->callback_handle = kernel.ThreadWakeupCallbackHandleTable().Create(thread).Unwrap(); thread->owner_process = &owner_process; + auto& scheduler = kernel.GlobalScheduler(); + scheduler.AddThread(thread); thread->tls_address = thread->owner_process->CreateTLSRegion(); - thread->scheduler = &system.Scheduler(processor_id); - thread->scheduler->AddThread(thread); thread->owner_process->RegisterThread(thread.get()); @@ -250,6 +241,22 @@ void Thread::SetStatus(ThreadStatus new_status) { return; } + switch (new_status) { + case ThreadStatus::Ready: + case ThreadStatus::Running: + SetSchedulingStatus(ThreadSchedStatus::Runnable); + break; + case ThreadStatus::Dormant: + SetSchedulingStatus(ThreadSchedStatus::None); + break; + case ThreadStatus::Dead: + SetSchedulingStatus(ThreadSchedStatus::Exited); + break; + default: + SetSchedulingStatus(ThreadSchedStatus::Paused); + break; + } + if (status == ThreadStatus::Running) { last_running_ticks = Core::System::GetInstance().CoreTiming().GetTicks(); } @@ -311,8 +318,7 @@ void Thread::UpdatePriority() { return; } - scheduler->SetThreadPriority(this, new_priority); - current_priority = new_priority; + SetCurrentPriority(new_priority); if (!lock_owner) { return; @@ -328,47 +334,7 @@ void Thread::UpdatePriority() { } void Thread::ChangeCore(u32 core, u64 mask) { - ideal_core = core; - affinity_mask = mask; - ChangeScheduler(); -} - -void Thread::ChangeScheduler() { - if (status != ThreadStatus::Ready) { - return; - } - - auto& system = Core::System::GetInstance(); - std::optional<s32> new_processor_id{GetNextProcessorId(affinity_mask)}; - - if (!new_processor_id) { - new_processor_id = processor_id; - } - if (ideal_core != -1 && system.Scheduler(ideal_core).GetCurrentThread() == nullptr) { - new_processor_id = ideal_core; - } - - ASSERT(*new_processor_id < 4); - - // Add thread to new core's scheduler - auto& next_scheduler = system.Scheduler(*new_processor_id); - - if (*new_processor_id != processor_id) { - // Remove thread from previous core's scheduler - scheduler->RemoveThread(this); - next_scheduler.AddThread(this); - } - - processor_id = *new_processor_id; - - // If the thread was ready, unschedule from the previous core and schedule on the new core - scheduler->UnscheduleThread(this, current_priority); - next_scheduler.ScheduleThread(this, current_priority); - - // Change thread's scheduler - scheduler = &next_scheduler; - - system.CpuCore(processor_id).PrepareReschedule(); + SetCoreAndAffinityMask(core, mask); } bool Thread::AllWaitObjectsReady() const { @@ -388,10 +354,8 @@ void Thread::SetActivity(ThreadActivity value) { if (value == ThreadActivity::Paused) { // Set status if not waiting - if (status == ThreadStatus::Ready) { - status = ThreadStatus::Paused; - } else if (status == ThreadStatus::Running) { - status = ThreadStatus::Paused; + if (status == ThreadStatus::Ready || status == ThreadStatus::Running) { + SetStatus(ThreadStatus::Paused); Core::System::GetInstance().CpuCore(processor_id).PrepareReschedule(); } } else if (status == ThreadStatus::Paused) { @@ -408,6 +372,170 @@ void Thread::Sleep(s64 nanoseconds) { WakeAfterDelay(nanoseconds); } +bool Thread::YieldSimple() { + auto& scheduler = kernel.GlobalScheduler(); + return scheduler.YieldThread(this); +} + +bool Thread::YieldAndBalanceLoad() { + auto& scheduler = kernel.GlobalScheduler(); + return scheduler.YieldThreadAndBalanceLoad(this); +} + +bool Thread::YieldAndWaitForLoadBalancing() { + auto& scheduler = kernel.GlobalScheduler(); + return scheduler.YieldThreadAndWaitForLoadBalancing(this); +} + +void Thread::SetSchedulingStatus(ThreadSchedStatus new_status) { + const u32 old_flags = scheduling_state; + scheduling_state = (scheduling_state & static_cast<u32>(ThreadSchedMasks::HighMask)) | + static_cast<u32>(new_status); + AdjustSchedulingOnStatus(old_flags); +} + +void Thread::SetCurrentPriority(u32 new_priority) { + const u32 old_priority = std::exchange(current_priority, new_priority); + AdjustSchedulingOnPriority(old_priority); +} + +ResultCode Thread::SetCoreAndAffinityMask(s32 new_core, u64 new_affinity_mask) { + const auto HighestSetCore = [](u64 mask, u32 max_cores) { + for (s32 core = max_cores - 1; core >= 0; core--) { + if (((mask >> core) & 1) != 0) { + return core; + } + } + return -1; + }; + + const bool use_override = affinity_override_count != 0; + if (new_core == THREADPROCESSORID_DONT_UPDATE) { + new_core = use_override ? ideal_core_override : ideal_core; + if ((new_affinity_mask & (1ULL << new_core)) == 0) { + return ERR_INVALID_COMBINATION; + } + } + if (use_override) { + ideal_core_override = new_core; + affinity_mask_override = new_affinity_mask; + } else { + const u64 old_affinity_mask = std::exchange(affinity_mask, new_affinity_mask); + ideal_core = new_core; + if (old_affinity_mask != new_affinity_mask) { + const s32 old_core = processor_id; + if (processor_id >= 0 && ((affinity_mask >> processor_id) & 1) == 0) { + if (ideal_core < 0) { + processor_id = HighestSetCore(affinity_mask, GlobalScheduler::NUM_CPU_CORES); + } else { + processor_id = ideal_core; + } + } + AdjustSchedulingOnAffinity(old_affinity_mask, old_core); + } + } + return RESULT_SUCCESS; +} + +void Thread::AdjustSchedulingOnStatus(u32 old_flags) { + if (old_flags == scheduling_state) { + return; + } + + auto& scheduler = kernel.GlobalScheduler(); + if (static_cast<ThreadSchedStatus>(old_flags & static_cast<u32>(ThreadSchedMasks::LowMask)) == + ThreadSchedStatus::Runnable) { + // In this case the thread was running, now it's pausing/exitting + if (processor_id >= 0) { + scheduler.Unschedule(current_priority, processor_id, this); + } + + for (s32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) { + if (core != processor_id && ((affinity_mask >> core) & 1) != 0) { + scheduler.Unsuggest(current_priority, static_cast<u32>(core), this); + } + } + } else if (GetSchedulingStatus() == ThreadSchedStatus::Runnable) { + // The thread is now set to running from being stopped + if (processor_id >= 0) { + scheduler.Schedule(current_priority, processor_id, this); + } + + for (s32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) { + if (core != processor_id && ((affinity_mask >> core) & 1) != 0) { + scheduler.Suggest(current_priority, static_cast<u32>(core), this); + } + } + } + + scheduler.SetReselectionPending(); +} + +void Thread::AdjustSchedulingOnPriority(u32 old_priority) { + if (GetSchedulingStatus() != ThreadSchedStatus::Runnable) { + return; + } + auto& scheduler = Core::System::GetInstance().GlobalScheduler(); + if (processor_id >= 0) { + scheduler.Unschedule(old_priority, processor_id, this); + } + + for (u32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) { + if (core != processor_id && ((affinity_mask >> core) & 1) != 0) { + scheduler.Unsuggest(old_priority, core, this); + } + } + + // Add thread to the new priority queues. + Thread* current_thread = GetCurrentThread(); + + if (processor_id >= 0) { + if (current_thread == this) { + scheduler.SchedulePrepend(current_priority, processor_id, this); + } else { + scheduler.Schedule(current_priority, processor_id, this); + } + } + + for (u32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) { + if (core != processor_id && ((affinity_mask >> core) & 1) != 0) { + scheduler.Suggest(current_priority, core, this); + } + } + + scheduler.SetReselectionPending(); +} + +void Thread::AdjustSchedulingOnAffinity(u64 old_affinity_mask, s32 old_core) { + auto& scheduler = Core::System::GetInstance().GlobalScheduler(); + if (GetSchedulingStatus() != ThreadSchedStatus::Runnable || + current_priority >= THREADPRIO_COUNT) { + return; + } + + for (u32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) { + if (((old_affinity_mask >> core) & 1) != 0) { + if (core == old_core) { + scheduler.Unschedule(current_priority, core, this); + } else { + scheduler.Unsuggest(current_priority, core, this); + } + } + } + + for (u32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) { + if (((affinity_mask >> core) & 1) != 0) { + if (core == processor_id) { + scheduler.Schedule(current_priority, core, this); + } else { + scheduler.Suggest(current_priority, core, this); + } + } + } + + scheduler.SetReselectionPending(); +} + //////////////////////////////////////////////////////////////////////////////////////////////////// /** diff --git a/src/core/hle/kernel/thread.h b/src/core/hle/kernel/thread.h index 07e989637..c9870873d 100644 --- a/src/core/hle/kernel/thread.h +++ b/src/core/hle/kernel/thread.h @@ -75,6 +75,26 @@ enum class ThreadActivity : u32 { Paused = 1, }; +enum class ThreadSchedStatus : u32 { + None = 0, + Paused = 1, + Runnable = 2, + Exited = 3, +}; + +enum class ThreadSchedFlags : u32 { + ProcessPauseFlag = 1 << 4, + ThreadPauseFlag = 1 << 5, + ProcessDebugPauseFlag = 1 << 6, + KernelInitPauseFlag = 1 << 8, +}; + +enum class ThreadSchedMasks : u32 { + LowMask = 0x000f, + HighMask = 0xfff0, + ForcePauseMask = 0x0070, +}; + class Thread final : public WaitObject { public: using MutexWaitingThreads = std::vector<SharedPtr<Thread>>; @@ -278,6 +298,10 @@ public: return processor_id; } + void SetProcessorID(s32 new_core) { + processor_id = new_core; + } + Process* GetOwnerProcess() { return owner_process; } @@ -295,6 +319,9 @@ public: } void ClearWaitObjects() { + for (const auto& waiting_object : wait_objects) { + waiting_object->RemoveWaitingThread(this); + } wait_objects.clear(); } @@ -383,11 +410,47 @@ public: /// Sleeps this thread for the given amount of nanoseconds. void Sleep(s64 nanoseconds); + /// Yields this thread without rebalancing loads. + bool YieldSimple(); + + /// Yields this thread and does a load rebalancing. + bool YieldAndBalanceLoad(); + + /// Yields this thread and if the core is left idle, loads are rebalanced + bool YieldAndWaitForLoadBalancing(); + + void IncrementYieldCount() { + yield_count++; + } + + u64 GetYieldCount() const { + return yield_count; + } + + ThreadSchedStatus GetSchedulingStatus() const { + return static_cast<ThreadSchedStatus>(scheduling_state & + static_cast<u32>(ThreadSchedMasks::LowMask)); + } + + bool IsRunning() const { + return is_running; + } + + void SetIsRunning(bool value) { + is_running = value; + } + private: explicit Thread(KernelCore& kernel); ~Thread() override; - void ChangeScheduler(); + void SetSchedulingStatus(ThreadSchedStatus new_status); + void SetCurrentPriority(u32 new_priority); + ResultCode SetCoreAndAffinityMask(s32 new_core, u64 new_affinity_mask); + + void AdjustSchedulingOnStatus(u32 old_flags); + void AdjustSchedulingOnPriority(u32 old_priority); + void AdjustSchedulingOnAffinity(u64 old_affinity_mask, s32 old_core); Core::ARM_Interface::ThreadContext context{}; @@ -409,6 +472,8 @@ private: u64 total_cpu_time_ticks = 0; ///< Total CPU running ticks. u64 last_running_ticks = 0; ///< CPU tick when thread was last running + u64 yield_count = 0; ///< Number of redundant yields carried by this thread. + ///< a redundant yield is one where no scheduling is changed s32 processor_id = 0; @@ -453,6 +518,13 @@ private: ThreadActivity activity = ThreadActivity::Normal; + s32 ideal_core_override = -1; + u64 affinity_mask_override = 0x1; + u32 affinity_override_count = 0; + + u32 scheduling_state = 0; + bool is_running = false; + std::string name; }; diff --git a/src/core/hle/kernel/wait_object.cpp b/src/core/hle/kernel/wait_object.cpp index 0e96ba872..c00cef062 100644 --- a/src/core/hle/kernel/wait_object.cpp +++ b/src/core/hle/kernel/wait_object.cpp @@ -6,6 +6,9 @@ #include "common/assert.h" #include "common/common_types.h" #include "common/logging/log.h" +#include "core/core.h" +#include "core/core_cpu.h" +#include "core/hle/kernel/kernel.h" #include "core/hle/kernel/object.h" #include "core/hle/kernel/process.h" #include "core/hle/kernel/thread.h" @@ -82,9 +85,6 @@ void WaitObject::WakeupWaitingThread(SharedPtr<Thread> thread) { const std::size_t index = thread->GetWaitObjectIndex(this); - for (const auto& object : thread->GetWaitObjects()) { - object->RemoveWaitingThread(thread.get()); - } thread->ClearWaitObjects(); thread->CancelWakeupTimer(); @@ -95,6 +95,7 @@ void WaitObject::WakeupWaitingThread(SharedPtr<Thread> thread) { } if (resume) { thread->ResumeFromWait(); + Core::System::GetInstance().PrepareReschedule(thread->GetProcessorID()); } } diff --git a/src/video_core/engines/kepler_compute.cpp b/src/video_core/engines/kepler_compute.cpp index 91adef360..3a39aeabe 100644 --- a/src/video_core/engines/kepler_compute.cpp +++ b/src/video_core/engines/kepler_compute.cpp @@ -50,7 +50,7 @@ void KeplerCompute::CallMethod(const GPU::MethodCall& method_call) { } } -Tegra::Texture::FullTextureInfo KeplerCompute::GetTexture(std::size_t offset) const { +Texture::FullTextureInfo KeplerCompute::GetTexture(std::size_t offset) const { const std::bitset<8> cbuf_mask = launch_description.const_buffer_enable_mask.Value(); ASSERT(cbuf_mask[regs.tex_cb_index]); @@ -61,13 +61,11 @@ Tegra::Texture::FullTextureInfo KeplerCompute::GetTexture(std::size_t offset) co ASSERT(address < texinfo.Address() + texinfo.size); const Texture::TextureHandle tex_handle{memory_manager.Read<u32>(address)}; - return GetTextureInfo(tex_handle, offset); + return GetTextureInfo(tex_handle); } -Texture::FullTextureInfo KeplerCompute::GetTextureInfo(const Texture::TextureHandle tex_handle, - std::size_t offset) const { - return Texture::FullTextureInfo{static_cast<u32>(offset), GetTICEntry(tex_handle.tic_id), - GetTSCEntry(tex_handle.tsc_id)}; +Texture::FullTextureInfo KeplerCompute::GetTextureInfo(Texture::TextureHandle tex_handle) const { + return Texture::FullTextureInfo{GetTICEntry(tex_handle.tic_id), GetTSCEntry(tex_handle.tsc_id)}; } u32 KeplerCompute::AccessConstBuffer32(ShaderType stage, u64 const_buffer, u64 offset) const { @@ -89,7 +87,7 @@ SamplerDescriptor KeplerCompute::AccessBindlessSampler(ShaderType stage, u64 con const GPUVAddr tex_info_address = tex_info_buffer.Address() + offset; const Texture::TextureHandle tex_handle{memory_manager.Read<u32>(tex_info_address)}; - const Texture::FullTextureInfo tex_info = GetTextureInfo(tex_handle, offset); + const Texture::FullTextureInfo tex_info = GetTextureInfo(tex_handle); SamplerDescriptor result = SamplerDescriptor::FromTicTexture(tex_info.tic.texture_type.Value()); result.is_shadow.Assign(tex_info.tsc.depth_compare_enabled.Value()); return result; diff --git a/src/video_core/engines/kepler_compute.h b/src/video_core/engines/kepler_compute.h index 8e7182727..b185c98c7 100644 --- a/src/video_core/engines/kepler_compute.h +++ b/src/video_core/engines/kepler_compute.h @@ -196,11 +196,10 @@ public: /// Write the value to the register identified by method. void CallMethod(const GPU::MethodCall& method_call); - Tegra::Texture::FullTextureInfo GetTexture(std::size_t offset) const; + Texture::FullTextureInfo GetTexture(std::size_t offset) const; - /// Given a Texture Handle, returns the TSC and TIC entries. - Texture::FullTextureInfo GetTextureInfo(const Texture::TextureHandle tex_handle, - std::size_t offset) const; + /// Given a texture handle, returns the TSC and TIC entries. + Texture::FullTextureInfo GetTextureInfo(Texture::TextureHandle tex_handle) const; u32 AccessConstBuffer32(ShaderType stage, u64 const_buffer, u64 offset) const override; diff --git a/src/video_core/engines/maxwell_3d.cpp b/src/video_core/engines/maxwell_3d.cpp index 558955451..2bed6cb38 100644 --- a/src/video_core/engines/maxwell_3d.cpp +++ b/src/video_core/engines/maxwell_3d.cpp @@ -98,11 +98,10 @@ void Maxwell3D::InitializeRegisterDefaults() { mme_inline[MAXWELL3D_REG_INDEX(index_array.count)] = true; } -#define DIRTY_REGS_POS(field_name) (offsetof(Maxwell3D::DirtyRegs, field_name)) +#define DIRTY_REGS_POS(field_name) static_cast<u8>(offsetof(Maxwell3D::DirtyRegs, field_name)) void Maxwell3D::InitDirtySettings() { - const auto set_block = [this](const std::size_t start, const std::size_t range, - const u8 position) { + const auto set_block = [this](std::size_t start, std::size_t range, u8 position) { const auto start_itr = dirty_pointers.begin() + start; const auto end_itr = start_itr + range; std::fill(start_itr, end_itr, position); @@ -113,10 +112,10 @@ void Maxwell3D::InitDirtySettings() { constexpr u32 registers_per_rt = sizeof(regs.rt[0]) / sizeof(u32); constexpr u32 rt_start_reg = MAXWELL3D_REG_INDEX(rt); constexpr u32 rt_end_reg = rt_start_reg + registers_per_rt * 8; - u32 rt_dirty_reg = DIRTY_REGS_POS(render_target); + u8 rt_dirty_reg = DIRTY_REGS_POS(render_target); for (u32 rt_reg = rt_start_reg; rt_reg < rt_end_reg; rt_reg += registers_per_rt) { set_block(rt_reg, registers_per_rt, rt_dirty_reg); - rt_dirty_reg++; + ++rt_dirty_reg; } constexpr u32 depth_buffer_flag = DIRTY_REGS_POS(depth_buffer); dirty_pointers[MAXWELL3D_REG_INDEX(zeta_enable)] = depth_buffer_flag; @@ -130,35 +129,35 @@ void Maxwell3D::InitDirtySettings() { constexpr u32 vertex_array_start = MAXWELL3D_REG_INDEX(vertex_array); constexpr u32 vertex_array_size = sizeof(regs.vertex_array[0]) / sizeof(u32); constexpr u32 vertex_array_end = vertex_array_start + vertex_array_size * Regs::NumVertexArrays; - u32 va_reg = DIRTY_REGS_POS(vertex_array); - u32 vi_reg = DIRTY_REGS_POS(vertex_instance); + u8 va_dirty_reg = DIRTY_REGS_POS(vertex_array); + u8 vi_dirty_reg = DIRTY_REGS_POS(vertex_instance); for (u32 vertex_reg = vertex_array_start; vertex_reg < vertex_array_end; vertex_reg += vertex_array_size) { - set_block(vertex_reg, 3, va_reg); + set_block(vertex_reg, 3, va_dirty_reg); // The divisor concerns vertex array instances - dirty_pointers[vertex_reg + 3] = vi_reg; - va_reg++; - vi_reg++; + dirty_pointers[static_cast<std::size_t>(vertex_reg) + 3] = vi_dirty_reg; + ++va_dirty_reg; + ++vi_dirty_reg; } constexpr u32 vertex_limit_start = MAXWELL3D_REG_INDEX(vertex_array_limit); constexpr u32 vertex_limit_size = sizeof(regs.vertex_array_limit[0]) / sizeof(u32); constexpr u32 vertex_limit_end = vertex_limit_start + vertex_limit_size * Regs::NumVertexArrays; - va_reg = DIRTY_REGS_POS(vertex_array); + va_dirty_reg = DIRTY_REGS_POS(vertex_array); for (u32 vertex_reg = vertex_limit_start; vertex_reg < vertex_limit_end; vertex_reg += vertex_limit_size) { - set_block(vertex_reg, vertex_limit_size, va_reg); - va_reg++; + set_block(vertex_reg, vertex_limit_size, va_dirty_reg); + va_dirty_reg++; } constexpr u32 vertex_instance_start = MAXWELL3D_REG_INDEX(instanced_arrays); constexpr u32 vertex_instance_size = sizeof(regs.instanced_arrays.is_instanced[0]) / sizeof(u32); constexpr u32 vertex_instance_end = vertex_instance_start + vertex_instance_size * Regs::NumVertexArrays; - vi_reg = DIRTY_REGS_POS(vertex_instance); + vi_dirty_reg = DIRTY_REGS_POS(vertex_instance); for (u32 vertex_reg = vertex_instance_start; vertex_reg < vertex_instance_end; vertex_reg += vertex_instance_size) { - set_block(vertex_reg, vertex_instance_size, vi_reg); - vi_reg++; + set_block(vertex_reg, vertex_instance_size, vi_dirty_reg); + vi_dirty_reg++; } set_block(MAXWELL3D_REG_INDEX(vertex_attrib_format), regs.vertex_attrib_format.size(), DIRTY_REGS_POS(vertex_attrib_format)); @@ -172,7 +171,7 @@ void Maxwell3D::InitDirtySettings() { // State // Viewport - constexpr u32 viewport_dirty_reg = DIRTY_REGS_POS(viewport); + constexpr u8 viewport_dirty_reg = DIRTY_REGS_POS(viewport); constexpr u32 viewport_start = MAXWELL3D_REG_INDEX(viewports); constexpr u32 viewport_size = sizeof(regs.viewports) / sizeof(u32); set_block(viewport_start, viewport_size, viewport_dirty_reg); @@ -199,7 +198,7 @@ void Maxwell3D::InitDirtySettings() { set_block(primitive_restart_start, primitive_restart_size, DIRTY_REGS_POS(primitive_restart)); // Depth Test - constexpr u32 depth_test_dirty_reg = DIRTY_REGS_POS(depth_test); + constexpr u8 depth_test_dirty_reg = DIRTY_REGS_POS(depth_test); dirty_pointers[MAXWELL3D_REG_INDEX(depth_test_enable)] = depth_test_dirty_reg; dirty_pointers[MAXWELL3D_REG_INDEX(depth_write_enabled)] = depth_test_dirty_reg; dirty_pointers[MAXWELL3D_REG_INDEX(depth_test_func)] = depth_test_dirty_reg; @@ -224,12 +223,12 @@ void Maxwell3D::InitDirtySettings() { dirty_pointers[MAXWELL3D_REG_INDEX(stencil_back_mask)] = stencil_test_dirty_reg; // Color Mask - constexpr u32 color_mask_dirty_reg = DIRTY_REGS_POS(color_mask); + constexpr u8 color_mask_dirty_reg = DIRTY_REGS_POS(color_mask); dirty_pointers[MAXWELL3D_REG_INDEX(color_mask_common)] = color_mask_dirty_reg; set_block(MAXWELL3D_REG_INDEX(color_mask), sizeof(regs.color_mask) / sizeof(u32), color_mask_dirty_reg); // Blend State - constexpr u32 blend_state_dirty_reg = DIRTY_REGS_POS(blend_state); + constexpr u8 blend_state_dirty_reg = DIRTY_REGS_POS(blend_state); set_block(MAXWELL3D_REG_INDEX(blend_color), sizeof(regs.blend_color) / sizeof(u32), blend_state_dirty_reg); dirty_pointers[MAXWELL3D_REG_INDEX(independent_blend_enable)] = blend_state_dirty_reg; @@ -238,12 +237,12 @@ void Maxwell3D::InitDirtySettings() { blend_state_dirty_reg); // Scissor State - constexpr u32 scissor_test_dirty_reg = DIRTY_REGS_POS(scissor_test); + constexpr u8 scissor_test_dirty_reg = DIRTY_REGS_POS(scissor_test); set_block(MAXWELL3D_REG_INDEX(scissor_test), sizeof(regs.scissor_test) / sizeof(u32), scissor_test_dirty_reg); // Polygon Offset - constexpr u32 polygon_offset_dirty_reg = DIRTY_REGS_POS(polygon_offset); + constexpr u8 polygon_offset_dirty_reg = DIRTY_REGS_POS(polygon_offset); dirty_pointers[MAXWELL3D_REG_INDEX(polygon_offset_fill_enable)] = polygon_offset_dirty_reg; dirty_pointers[MAXWELL3D_REG_INDEX(polygon_offset_line_enable)] = polygon_offset_dirty_reg; dirty_pointers[MAXWELL3D_REG_INDEX(polygon_offset_point_enable)] = polygon_offset_dirty_reg; @@ -252,7 +251,7 @@ void Maxwell3D::InitDirtySettings() { dirty_pointers[MAXWELL3D_REG_INDEX(polygon_offset_clamp)] = polygon_offset_dirty_reg; // Depth bounds - constexpr u32 depth_bounds_values_dirty_reg = DIRTY_REGS_POS(depth_bounds_values); + constexpr u8 depth_bounds_values_dirty_reg = DIRTY_REGS_POS(depth_bounds_values); dirty_pointers[MAXWELL3D_REG_INDEX(depth_bounds[0])] = depth_bounds_values_dirty_reg; dirty_pointers[MAXWELL3D_REG_INDEX(depth_bounds[1])] = depth_bounds_values_dirty_reg; } @@ -761,61 +760,8 @@ Texture::TSCEntry Maxwell3D::GetTSCEntry(u32 tsc_index) const { return tsc_entry; } -std::vector<Texture::FullTextureInfo> Maxwell3D::GetStageTextures(Regs::ShaderStage stage) const { - std::vector<Texture::FullTextureInfo> textures; - - auto& fragment_shader = state.shader_stages[static_cast<std::size_t>(stage)]; - auto& tex_info_buffer = fragment_shader.const_buffers[regs.tex_cb_index]; - ASSERT(tex_info_buffer.enabled && tex_info_buffer.address != 0); - - GPUVAddr tex_info_buffer_end = tex_info_buffer.address + tex_info_buffer.size; - - // Offset into the texture constbuffer where the texture info begins. - static constexpr std::size_t TextureInfoOffset = 0x20; - - for (GPUVAddr current_texture = tex_info_buffer.address + TextureInfoOffset; - current_texture < tex_info_buffer_end; current_texture += sizeof(Texture::TextureHandle)) { - - const Texture::TextureHandle tex_handle{memory_manager.Read<u32>(current_texture)}; - - Texture::FullTextureInfo tex_info{}; - // TODO(Subv): Use the shader to determine which textures are actually accessed. - tex_info.index = - static_cast<u32>(current_texture - tex_info_buffer.address - TextureInfoOffset) / - sizeof(Texture::TextureHandle); - - // Load the TIC data. - auto tic_entry = GetTICEntry(tex_handle.tic_id); - // TODO(Subv): Workaround for BitField's move constructor being deleted. - std::memcpy(&tex_info.tic, &tic_entry, sizeof(tic_entry)); - - // Load the TSC data - auto tsc_entry = GetTSCEntry(tex_handle.tsc_id); - // TODO(Subv): Workaround for BitField's move constructor being deleted. - std::memcpy(&tex_info.tsc, &tsc_entry, sizeof(tsc_entry)); - - textures.push_back(tex_info); - } - - return textures; -} - -Texture::FullTextureInfo Maxwell3D::GetTextureInfo(const Texture::TextureHandle tex_handle, - std::size_t offset) const { - Texture::FullTextureInfo tex_info{}; - tex_info.index = static_cast<u32>(offset); - - // Load the TIC data. - auto tic_entry = GetTICEntry(tex_handle.tic_id); - // TODO(Subv): Workaround for BitField's move constructor being deleted. - std::memcpy(&tex_info.tic, &tic_entry, sizeof(tic_entry)); - - // Load the TSC data - auto tsc_entry = GetTSCEntry(tex_handle.tsc_id); - // TODO(Subv): Workaround for BitField's move constructor being deleted. - std::memcpy(&tex_info.tsc, &tsc_entry, sizeof(tsc_entry)); - - return tex_info; +Texture::FullTextureInfo Maxwell3D::GetTextureInfo(Texture::TextureHandle tex_handle) const { + return Texture::FullTextureInfo{GetTICEntry(tex_handle.tic_id), GetTSCEntry(tex_handle.tsc_id)}; } Texture::FullTextureInfo Maxwell3D::GetStageTexture(Regs::ShaderStage stage, @@ -831,7 +777,7 @@ Texture::FullTextureInfo Maxwell3D::GetStageTexture(Regs::ShaderStage stage, const Texture::TextureHandle tex_handle{memory_manager.Read<u32>(tex_info_address)}; - return GetTextureInfo(tex_handle, offset); + return GetTextureInfo(tex_handle); } u32 Maxwell3D::GetRegisterValue(u32 method) const { @@ -868,7 +814,7 @@ SamplerDescriptor Maxwell3D::AccessBindlessSampler(ShaderType stage, u64 const_b const GPUVAddr tex_info_address = tex_info_buffer.address + offset; const Texture::TextureHandle tex_handle{memory_manager.Read<u32>(tex_info_address)}; - const Texture::FullTextureInfo tex_info = GetTextureInfo(tex_handle, offset); + const Texture::FullTextureInfo tex_info = GetTextureInfo(tex_handle); SamplerDescriptor result = SamplerDescriptor::FromTicTexture(tex_info.tic.texture_type.Value()); result.is_shadow.Assign(tex_info.tsc.depth_compare_enabled.Value()); return result; diff --git a/src/video_core/engines/maxwell_3d.h b/src/video_core/engines/maxwell_3d.h index fa846a621..8cc842684 100644 --- a/src/video_core/engines/maxwell_3d.h +++ b/src/video_core/engines/maxwell_3d.h @@ -1166,6 +1166,8 @@ public: struct DirtyRegs { static constexpr std::size_t NUM_REGS = 256; + static_assert(NUM_REGS - 1 <= std::numeric_limits<u8>::max()); + union { struct { bool null_dirty; @@ -1248,12 +1250,8 @@ public: void FlushMMEInlineDraw(); - /// Given a Texture Handle, returns the TSC and TIC entries. - Texture::FullTextureInfo GetTextureInfo(const Texture::TextureHandle tex_handle, - std::size_t offset) const; - - /// Returns a list of enabled textures for the specified shader stage. - std::vector<Texture::FullTextureInfo> GetStageTextures(Regs::ShaderStage stage) const; + /// Given a texture handle, returns the TSC and TIC entries. + Texture::FullTextureInfo GetTextureInfo(Texture::TextureHandle tex_handle) const; /// Returns the texture information for a specific texture in a specific shader stage. Texture::FullTextureInfo GetStageTexture(Regs::ShaderStage stage, std::size_t offset) const; diff --git a/src/video_core/morton.cpp b/src/video_core/morton.cpp index fe5f08ace..2f2fe6859 100644 --- a/src/video_core/morton.cpp +++ b/src/video_core/morton.cpp @@ -112,6 +112,7 @@ static constexpr ConversionArray morton_to_linear_fns = { MortonCopy<true, PixelFormat::ASTC_2D_8X6_SRGB>, MortonCopy<true, PixelFormat::ASTC_2D_6X5>, MortonCopy<true, PixelFormat::ASTC_2D_6X5_SRGB>, + MortonCopy<true, PixelFormat::E5B9G9R9F>, MortonCopy<true, PixelFormat::Z32F>, MortonCopy<true, PixelFormat::Z16>, MortonCopy<true, PixelFormat::Z24S8>, @@ -192,6 +193,7 @@ static constexpr ConversionArray linear_to_morton_fns = { nullptr, nullptr, nullptr, + MortonCopy<false, PixelFormat::E5B9G9R9F>, MortonCopy<false, PixelFormat::Z32F>, MortonCopy<false, PixelFormat::Z16>, MortonCopy<false, PixelFormat::Z24S8>, diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp index ce0d757f9..63cf4216b 100644 --- a/src/video_core/renderer_opengl/gl_rasterizer.cpp +++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp @@ -933,7 +933,7 @@ TextureBufferUsage RasterizerOpenGL::SetupDrawTextures(Maxwell::ShaderStage stag for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) { const auto& entry = entries[bindpoint]; - const auto texture = [&]() { + const auto texture = [&] { if (!entry.IsBindless()) { return maxwell3d.GetStageTexture(stage, entry.GetOffset()); } @@ -941,7 +941,7 @@ TextureBufferUsage RasterizerOpenGL::SetupDrawTextures(Maxwell::ShaderStage stag Tegra::Texture::TextureHandle tex_handle; Tegra::Engines::ShaderType shader_type = static_cast<Tegra::Engines::ShaderType>(stage); tex_handle.raw = maxwell3d.AccessConstBuffer32(shader_type, cbuf.first, cbuf.second); - return maxwell3d.GetTextureInfo(tex_handle, entry.GetOffset()); + return maxwell3d.GetTextureInfo(tex_handle); }(); if (SetupTexture(base_bindings.sampler + bindpoint, texture, entry)) { @@ -964,7 +964,7 @@ TextureBufferUsage RasterizerOpenGL::SetupComputeTextures(const Shader& kernel) for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) { const auto& entry = entries[bindpoint]; - const auto texture = [&]() { + const auto texture = [&] { if (!entry.IsBindless()) { return compute.GetTexture(entry.GetOffset()); } @@ -972,7 +972,7 @@ TextureBufferUsage RasterizerOpenGL::SetupComputeTextures(const Shader& kernel) Tegra::Texture::TextureHandle tex_handle; tex_handle.raw = compute.AccessConstBuffer32(Tegra::Engines::ShaderType::Compute, cbuf.first, cbuf.second); - return compute.GetTextureInfo(tex_handle, entry.GetOffset()); + return compute.GetTextureInfo(tex_handle); }(); if (SetupTexture(bindpoint, texture, entry)) { @@ -1010,7 +1010,7 @@ void RasterizerOpenGL::SetupComputeImages(const Shader& shader) { const auto& entries = shader->GetShaderEntries().images; for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) { const auto& entry = entries[bindpoint]; - const auto tic = [&]() { + const auto tic = [&] { if (!entry.IsBindless()) { return compute.GetTexture(entry.GetOffset()).tic; } @@ -1018,7 +1018,7 @@ void RasterizerOpenGL::SetupComputeImages(const Shader& shader) { Tegra::Texture::TextureHandle tex_handle; tex_handle.raw = compute.AccessConstBuffer32(Tegra::Engines::ShaderType::Compute, cbuf.first, cbuf.second); - return compute.GetTextureInfo(tex_handle, entry.GetOffset()).tic; + return compute.GetTextureInfo(tex_handle).tic; }(); SetupImage(bindpoint, tic, entry); } diff --git a/src/video_core/renderer_opengl/gl_texture_cache.cpp b/src/video_core/renderer_opengl/gl_texture_cache.cpp index 2f9bfd7e4..55b3e58b2 100644 --- a/src/video_core/renderer_opengl/gl_texture_cache.cpp +++ b/src/video_core/renderer_opengl/gl_texture_cache.cpp @@ -131,6 +131,7 @@ constexpr std::array<FormatTuple, VideoCore::Surface::MaxPixelFormat> tex_format {GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_8X6_SRGB {GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_6X5 {GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_6X5_SRGB + {GL_RGB9_E5, GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV, ComponentType::Float, false}, // E5B9G9R9F // Depth formats {GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT, ComponentType::Float, false}, // Z32F diff --git a/src/video_core/surface.cpp b/src/video_core/surface.cpp index 9a3c05288..621136b6e 100644 --- a/src/video_core/surface.cpp +++ b/src/video_core/surface.cpp @@ -315,6 +315,14 @@ PixelFormat PixelFormatFromTextureFormat(Tegra::Texture::TextureFormat format, break; } break; + case Tegra::Texture::TextureFormat::E5B9G9R9_SHAREDEXP: + switch (component_type) { + case Tegra::Texture::ComponentType::FLOAT: + return PixelFormat::E5B9G9R9F; + default: + break; + } + break; case Tegra::Texture::TextureFormat::ZF32: return PixelFormat::Z32F; case Tegra::Texture::TextureFormat::Z16: diff --git a/src/video_core/surface.h b/src/video_core/surface.h index 97668f802..d3bcd38c5 100644 --- a/src/video_core/surface.h +++ b/src/video_core/surface.h @@ -86,19 +86,20 @@ enum class PixelFormat { ASTC_2D_8X6_SRGB = 68, ASTC_2D_6X5 = 69, ASTC_2D_6X5_SRGB = 70, + E5B9G9R9F = 71, MaxColorFormat, // Depth formats - Z32F = 71, - Z16 = 72, + Z32F = 72, + Z16 = 73, MaxDepthFormat, // DepthStencil formats - Z24S8 = 73, - S8Z24 = 74, - Z32FS8 = 75, + Z24S8 = 74, + S8Z24 = 75, + Z32FS8 = 76, MaxDepthStencilFormat, @@ -207,6 +208,7 @@ constexpr std::array<u32, MaxPixelFormat> compression_factor_shift_table = {{ 2, // ASTC_2D_8X6_SRGB 2, // ASTC_2D_6X5 2, // ASTC_2D_6X5_SRGB + 0, // E5B9G9R9F 0, // Z32F 0, // Z16 0, // Z24S8 @@ -302,6 +304,7 @@ constexpr std::array<u32, MaxPixelFormat> block_width_table = {{ 8, // ASTC_2D_8X6_SRGB 6, // ASTC_2D_6X5 6, // ASTC_2D_6X5_SRGB + 1, // E5B9G9R9F 1, // Z32F 1, // Z16 1, // Z24S8 @@ -389,6 +392,7 @@ constexpr std::array<u32, MaxPixelFormat> block_height_table = {{ 6, // ASTC_2D_8X6_SRGB 5, // ASTC_2D_6X5 5, // ASTC_2D_6X5_SRGB + 1, // E5B9G9R9F 1, // Z32F 1, // Z16 1, // Z24S8 @@ -476,6 +480,7 @@ constexpr std::array<u32, MaxPixelFormat> bpp_table = {{ 128, // ASTC_2D_8X6_SRGB 128, // ASTC_2D_6X5 128, // ASTC_2D_6X5_SRGB + 32, // E5B9G9R9F 32, // Z32F 16, // Z16 32, // Z24S8 @@ -578,6 +583,7 @@ constexpr std::array<SurfaceCompression, MaxPixelFormat> compression_type_table SurfaceCompression::Converted, // ASTC_2D_8X6_SRGB SurfaceCompression::Converted, // ASTC_2D_6X5 SurfaceCompression::Converted, // ASTC_2D_6X5_SRGB + SurfaceCompression::None, // E5B9G9R9F SurfaceCompression::None, // Z32F SurfaceCompression::None, // Z16 SurfaceCompression::None, // Z24S8 diff --git a/src/video_core/textures/astc.cpp b/src/video_core/textures/astc.cpp index a9b8f69af..58b608a36 100644 --- a/src/video_core/textures/astc.cpp +++ b/src/video_core/textures/astc.cpp @@ -422,7 +422,7 @@ static TexelWeightParams DecodeBlockInfo(InputBitStream& strm) { TexelWeightParams params; // Read the entire block mode all at once - uint16_t modeBits = strm.ReadBits(11); + uint16_t modeBits = static_cast<uint16_t>(strm.ReadBits(11)); // Does this match the void extent block mode? if ((modeBits & 0x01FF) == 0x1FC) { @@ -625,10 +625,10 @@ static void FillVoidExtentLDR(InputBitStream& strm, uint32_t* const outBuf, uint } // Decode the RGBA components and renormalize them to the range [0, 255] - uint16_t r = strm.ReadBits(16); - uint16_t g = strm.ReadBits(16); - uint16_t b = strm.ReadBits(16); - uint16_t a = strm.ReadBits(16); + uint16_t r = static_cast<uint16_t>(strm.ReadBits(16)); + uint16_t g = static_cast<uint16_t>(strm.ReadBits(16)); + uint16_t b = static_cast<uint16_t>(strm.ReadBits(16)); + uint16_t a = static_cast<uint16_t>(strm.ReadBits(16)); uint32_t rgba = (r >> 8) | (g & 0xFF00) | (static_cast<uint32_t>(b) & 0xFF00) << 8 | (static_cast<uint32_t>(a) & 0xFF00) << 16; @@ -681,9 +681,10 @@ protected: public: Pixel() = default; - Pixel(ChannelType a, ChannelType r, ChannelType g, ChannelType b, unsigned bitDepth = 8) + Pixel(uint32_t a, uint32_t r, uint32_t g, uint32_t b, unsigned bitDepth = 8) : m_BitDepth{uint8_t(bitDepth), uint8_t(bitDepth), uint8_t(bitDepth), uint8_t(bitDepth)}, - color{a, r, g, b} {} + color{static_cast<ChannelType>(a), static_cast<ChannelType>(r), + static_cast<ChannelType>(g), static_cast<ChannelType>(b)} {} // Changes the depth of each pixel. This scales the values to // the appropriate bit depth by either truncating the least diff --git a/src/video_core/textures/texture.h b/src/video_core/textures/texture.h index e36bc2c04..0429af9c1 100644 --- a/src/video_core/textures/texture.h +++ b/src/video_core/textures/texture.h @@ -354,7 +354,6 @@ struct TSCEntry { static_assert(sizeof(TSCEntry) == 0x20, "TSCEntry has wrong size"); struct FullTextureInfo { - u32 index; TICEntry tic; TSCEntry tsc; }; diff --git a/src/yuzu/debugger/wait_tree.cpp b/src/yuzu/debugger/wait_tree.cpp index cd8180f8b..c5b9aa08f 100644 --- a/src/yuzu/debugger/wait_tree.cpp +++ b/src/yuzu/debugger/wait_tree.cpp @@ -66,10 +66,7 @@ std::vector<std::unique_ptr<WaitTreeThread>> WaitTreeItem::MakeThreadItemList() }; const auto& system = Core::System::GetInstance(); - add_threads(system.Scheduler(0).GetThreadList()); - add_threads(system.Scheduler(1).GetThreadList()); - add_threads(system.Scheduler(2).GetThreadList()); - add_threads(system.Scheduler(3).GetThreadList()); + add_threads(system.GlobalScheduler().GetThreadList()); return item_list; } |