Kernel: Style and Corrections

This commit is contained in:
Fernando Sahmkow 2019-06-19 09:11:18 -04:00 committed by FernandoS27
parent fcc6b34fff
commit 82218c925a
12 changed files with 137 additions and 96 deletions

View file

@ -404,9 +404,10 @@ void System::PrepareReschedule() {
CurrentCpuCore().PrepareReschedule(); CurrentCpuCore().PrepareReschedule();
} }
void System::PrepareReschedule(s32 core_index) { void System::PrepareReschedule(const u32 core_index) {
if (core_index >= 0) if (core_index < GlobalScheduler().CpuCoresCount()) {
CpuCore(core_index).PrepareReschedule(); CpuCore(core_index).PrepareReschedule();
}
} }
PerfStatsResults System::GetAndResetPerfStats() { PerfStatsResults System::GetAndResetPerfStats() {

View file

@ -24,10 +24,10 @@ class VfsFilesystem;
} // namespace FileSys } // namespace FileSys
namespace Kernel { namespace Kernel {
class GlobalScheduler;
class KernelCore; class KernelCore;
class Process; class Process;
class Scheduler; class Scheduler;
class GlobalScheduler;
} // namespace Kernel } // namespace Kernel
namespace Loader { namespace Loader {
@ -186,7 +186,7 @@ public:
void PrepareReschedule(); void PrepareReschedule();
/// Prepare the core emulation for a reschedule /// Prepare the core emulation for a reschedule
void PrepareReschedule(s32 core_index); void PrepareReschedule(u32 core_index);
/// Gets and resets core performance statistics /// Gets and resets core performance statistics
PerfStatsResults GetAndResetPerfStats(); PerfStatsResults GetAndResetPerfStats();

View file

@ -111,7 +111,7 @@ void Cpu::PrepareReschedule() {
void Cpu::Reschedule() { void Cpu::Reschedule() {
// Lock the global kernel mutex when we manipulate the HLE state // Lock the global kernel mutex when we manipulate the HLE state
std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock); std::lock_guard lock(HLE::g_hle_lock);
global_scheduler.SelectThread(core_index); global_scheduler.SelectThread(core_index);
scheduler->TryDoContextSwitch(); scheduler->TryDoContextSwitch();

View file

@ -12,8 +12,8 @@
#include "common/common_types.h" #include "common/common_types.h"
namespace Kernel { namespace Kernel {
class Scheduler;
class GlobalScheduler; class GlobalScheduler;
class Scheduler;
} // namespace Kernel } // namespace Kernel
namespace Core { namespace Core {

View file

@ -22,7 +22,6 @@ namespace Kernel {
namespace { namespace {
// Wake up num_to_wake (or all) threads in a vector. // Wake up num_to_wake (or all) threads in a vector.
void WakeThreads(const std::vector<SharedPtr<Thread>>& waiting_threads, s32 num_to_wake) { void WakeThreads(const std::vector<SharedPtr<Thread>>& waiting_threads, s32 num_to_wake) {
auto& system = Core::System::GetInstance(); auto& system = Core::System::GetInstance();
// Only process up to 'target' threads, unless 'target' is <= 0, in which case process // Only process up to 'target' threads, unless 'target' is <= 0, in which case process
// them all. // them all.

View file

@ -89,7 +89,7 @@ static void ThreadWakeupCallback(u64 thread_handle, [[maybe_unused]] s64 cycles_
} }
struct KernelCore::Impl { struct KernelCore::Impl {
explicit Impl(Core::System& system) : system{system} {} explicit Impl(Core::System& system) : system{system}, global_scheduler{system} {}
void Initialize(KernelCore& kernel) { void Initialize(KernelCore& kernel) {
Shutdown(); Shutdown();

View file

@ -140,7 +140,7 @@ ResultCode Mutex::Release(VAddr address) {
thread->SetMutexWaitAddress(0); thread->SetMutexWaitAddress(0);
thread->SetWaitHandle(0); thread->SetWaitHandle(0);
Core::System::GetInstance().PrepareReschedule(); system.PrepareReschedule();
return RESULT_SUCCESS; return RESULT_SUCCESS;
} }

View file

@ -1,6 +1,9 @@
// Copyright 2018 yuzu emulator team // Copyright 2018 yuzu emulator team
// Licensed under GPLv2 or any later version // Licensed under GPLv2 or any later version
// Refer to the license.txt file included. // 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 <algorithm>
#include <set> #include <set>
@ -19,16 +22,15 @@
namespace Kernel { namespace Kernel {
/* GlobalScheduler::GlobalScheduler(Core::System& system) : system{system} {
* SelectThreads, Yield functions originally by TuxSH. reselection_pending = false;
* licensed under GPLv2 or later under exception provided by the author. }
*/
void GlobalScheduler::AddThread(SharedPtr<Thread> thread) { void GlobalScheduler::AddThread(SharedPtr<Thread> thread) {
thread_list.push_back(std::move(thread)); thread_list.push_back(std::move(thread));
} }
void GlobalScheduler::RemoveThread(Thread* thread) { void GlobalScheduler::RemoveThread(const Thread* thread) {
thread_list.erase(std::remove(thread_list.begin(), thread_list.end(), thread), thread_list.erase(std::remove(thread_list.begin(), thread_list.end(), thread),
thread_list.end()); thread_list.end());
} }
@ -37,7 +39,7 @@ void GlobalScheduler::RemoveThread(Thread* thread) {
* UnloadThread selects a core and forces it to unload its current thread's context * UnloadThread selects a core and forces it to unload its current thread's context
*/ */
void GlobalScheduler::UnloadThread(s32 core) { void GlobalScheduler::UnloadThread(s32 core) {
Scheduler& sched = Core::System::GetInstance().Scheduler(core); Scheduler& sched = system.Scheduler(core);
sched.UnloadThread(); sched.UnloadThread();
} }
@ -52,7 +54,7 @@ void GlobalScheduler::UnloadThread(s32 core) {
* thread in another core and swap it with its current thread. * thread in another core and swap it with its current thread.
*/ */
void GlobalScheduler::SelectThread(u32 core) { void GlobalScheduler::SelectThread(u32 core) {
auto update_thread = [](Thread* thread, Scheduler& sched) { const auto update_thread = [](Thread* thread, Scheduler& sched) {
if (thread != sched.selected_thread) { if (thread != sched.selected_thread) {
if (thread == nullptr) { if (thread == nullptr) {
++sched.idle_selection_count; ++sched.idle_selection_count;
@ -62,7 +64,7 @@ void GlobalScheduler::SelectThread(u32 core) {
sched.context_switch_pending = sched.selected_thread != sched.current_thread; sched.context_switch_pending = sched.selected_thread != sched.current_thread;
std::atomic_thread_fence(std::memory_order_seq_cst); std::atomic_thread_fence(std::memory_order_seq_cst);
}; };
Scheduler& sched = Core::System::GetInstance().Scheduler(core); Scheduler& sched = system.Scheduler(core);
Thread* current_thread = nullptr; Thread* current_thread = nullptr;
// Step 1: Get top thread in schedule queue. // Step 1: Get top thread in schedule queue.
current_thread = scheduled_queue[core].empty() ? nullptr : scheduled_queue[core].front(); current_thread = scheduled_queue[core].empty() ? nullptr : scheduled_queue[core].front();
@ -118,8 +120,8 @@ void GlobalScheduler::SelectThread(u32 core) {
*/ */
void GlobalScheduler::YieldThread(Thread* yielding_thread) { void GlobalScheduler::YieldThread(Thread* yielding_thread) {
// Note: caller should use critical section, etc. // Note: caller should use critical section, etc.
u32 core_id = static_cast<u32>(yielding_thread->GetProcessorID()); const u32 core_id = static_cast<u32>(yielding_thread->GetProcessorID());
u32 priority = yielding_thread->GetPriority(); const u32 priority = yielding_thread->GetPriority();
// Yield the thread // Yield the thread
ASSERT_MSG(yielding_thread == scheduled_queue[core_id].front(priority), ASSERT_MSG(yielding_thread == scheduled_queue[core_id].front(priority),
@ -139,8 +141,8 @@ void GlobalScheduler::YieldThread(Thread* yielding_thread) {
void GlobalScheduler::YieldThreadAndBalanceLoad(Thread* yielding_thread) { void GlobalScheduler::YieldThreadAndBalanceLoad(Thread* yielding_thread) {
// Note: caller should check if !thread.IsSchedulerOperationRedundant and use critical section, // Note: caller should check if !thread.IsSchedulerOperationRedundant and use critical section,
// etc. // etc.
u32 core_id = static_cast<u32>(yielding_thread->GetProcessorID()); const u32 core_id = static_cast<u32>(yielding_thread->GetProcessorID());
u32 priority = yielding_thread->GetPriority(); const u32 priority = yielding_thread->GetPriority();
// Yield the thread // Yield the thread
ASSERT_MSG(yielding_thread == scheduled_queue[core_id].front(priority), ASSERT_MSG(yielding_thread == scheduled_queue[core_id].front(priority),
@ -155,13 +157,14 @@ void GlobalScheduler::YieldThreadAndBalanceLoad(Thread* yielding_thread) {
Thread* next_thread = scheduled_queue[core_id].front(priority); Thread* next_thread = scheduled_queue[core_id].front(priority);
Thread* winner = nullptr; Thread* winner = nullptr;
for (auto& thread : suggested_queue[core_id]) { for (auto& thread : suggested_queue[core_id]) {
s32 source_core = thread->GetProcessorID(); const s32 source_core = thread->GetProcessorID();
if (source_core >= 0) { if (source_core >= 0) {
if (current_threads[source_core] != nullptr) { if (current_threads[source_core] != nullptr) {
if (thread == current_threads[source_core] || if (thread == current_threads[source_core] ||
current_threads[source_core]->GetPriority() < min_regular_priority) current_threads[source_core]->GetPriority() < min_regular_priority) {
continue; continue;
} }
}
if (next_thread->GetLastRunningTicks() >= thread->GetLastRunningTicks() || if (next_thread->GetLastRunningTicks() >= thread->GetLastRunningTicks() ||
next_thread->GetPriority() < thread->GetPriority()) { next_thread->GetPriority() < thread->GetPriority()) {
if (thread->GetPriority() <= priority) { if (thread->GetPriority() <= priority) {
@ -174,8 +177,9 @@ void GlobalScheduler::YieldThreadAndBalanceLoad(Thread* yielding_thread) {
if (winner != nullptr) { if (winner != nullptr) {
if (winner != yielding_thread) { if (winner != yielding_thread) {
if (winner->IsRunning()) if (winner->IsRunning()) {
UnloadThread(winner->GetProcessorID()); UnloadThread(winner->GetProcessorID());
}
TransferToCore(winner->GetPriority(), core_id, winner); TransferToCore(winner->GetPriority(), core_id, winner);
} }
} else { } else {
@ -195,7 +199,7 @@ void GlobalScheduler::YieldThreadAndWaitForLoadBalancing(Thread* yielding_thread
// Note: caller should check if !thread.IsSchedulerOperationRedundant and use critical section, // Note: caller should check if !thread.IsSchedulerOperationRedundant and use critical section,
// etc. // etc.
Thread* winner = nullptr; Thread* winner = nullptr;
u32 core_id = static_cast<u32>(yielding_thread->GetProcessorID()); 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 // Remove the thread from its scheduled mlq, put it on the corresponding "suggested" one instead
TransferToCore(yielding_thread->GetPriority(), -1, yielding_thread); TransferToCore(yielding_thread->GetPriority(), -1, yielding_thread);
@ -209,9 +213,10 @@ void GlobalScheduler::YieldThreadAndWaitForLoadBalancing(Thread* yielding_thread
current_threads[i] = scheduled_queue[i].empty() ? nullptr : scheduled_queue[i].front(); current_threads[i] = scheduled_queue[i].empty() ? nullptr : scheduled_queue[i].front();
} }
for (auto& thread : suggested_queue[core_id]) { for (auto& thread : suggested_queue[core_id]) {
s32 source_core = thread->GetProcessorID(); const s32 source_core = thread->GetProcessorID();
if (source_core < 0 || thread == current_threads[source_core]) if (source_core < 0 || thread == current_threads[source_core]) {
continue; continue;
}
if (current_threads[source_core] == nullptr || if (current_threads[source_core] == nullptr ||
current_threads[source_core]->GetPriority() >= min_regular_priority) { current_threads[source_core]->GetPriority() >= min_regular_priority) {
winner = thread; winner = thread;
@ -220,8 +225,9 @@ void GlobalScheduler::YieldThreadAndWaitForLoadBalancing(Thread* yielding_thread
} }
if (winner != nullptr) { if (winner != nullptr) {
if (winner != yielding_thread) { if (winner != yielding_thread) {
if (winner->IsRunning()) if (winner->IsRunning()) {
UnloadThread(winner->GetProcessorID()); UnloadThread(winner->GetProcessorID());
}
TransferToCore(winner->GetPriority(), core_id, winner); TransferToCore(winner->GetPriority(), core_id, winner);
} }
} else { } else {
@ -232,6 +238,16 @@ void GlobalScheduler::YieldThreadAndWaitForLoadBalancing(Thread* yielding_thread
AskForReselectionOrMarkRedundant(yielding_thread, winner); AskForReselectionOrMarkRedundant(yielding_thread, winner);
} }
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::AskForReselectionOrMarkRedundant(Thread* current_thread, Thread* winner) { void GlobalScheduler::AskForReselectionOrMarkRedundant(Thread* current_thread, Thread* winner) {
if (current_thread == winner) { if (current_thread == winner) {
// TODO(blinkhawk): manage redundant operations, this is not implemented. // TODO(blinkhawk): manage redundant operations, this is not implemented.
@ -244,13 +260,13 @@ void GlobalScheduler::AskForReselectionOrMarkRedundant(Thread* current_thread, T
GlobalScheduler::~GlobalScheduler() = default; GlobalScheduler::~GlobalScheduler() = default;
Scheduler::Scheduler(Core::System& system, Core::ARM_Interface& cpu_core, u32 id) Scheduler::Scheduler(Core::System& system, Core::ARM_Interface& cpu_core, u32 core_id)
: system(system), cpu_core(cpu_core), id(id) {} : system(system), cpu_core(cpu_core), core_id(core_id) {}
Scheduler::~Scheduler() {} Scheduler::~Scheduler() = default;
bool Scheduler::HaveReadyThreads() const { bool Scheduler::HaveReadyThreads() const {
return system.GlobalScheduler().HaveReadyThreads(id); return system.GlobalScheduler().HaveReadyThreads(core_id);
} }
Thread* Scheduler::GetCurrentThread() const { Thread* Scheduler::GetCurrentThread() const {
@ -262,7 +278,7 @@ Thread* Scheduler::GetSelectedThread() const {
} }
void Scheduler::SelectThreads() { void Scheduler::SelectThreads() {
system.GlobalScheduler().SelectThread(id); system.GlobalScheduler().SelectThread(core_id);
} }
u64 Scheduler::GetLastContextSwitchTicks() const { u64 Scheduler::GetLastContextSwitchTicks() const {
@ -270,13 +286,14 @@ u64 Scheduler::GetLastContextSwitchTicks() const {
} }
void Scheduler::TryDoContextSwitch() { void Scheduler::TryDoContextSwitch() {
if (context_switch_pending) if (context_switch_pending) {
SwitchContext(); SwitchContext();
}
} }
void Scheduler::UnloadThread() { void Scheduler::UnloadThread() {
Thread* const previous_thread = GetCurrentThread(); Thread* const previous_thread = GetCurrentThread();
Process* const previous_process = Core::CurrentProcess(); Process* const previous_process = system.Kernel().CurrentProcess();
UpdateLastContextSwitchTime(previous_thread, previous_process); UpdateLastContextSwitchTime(previous_thread, previous_process);
@ -301,10 +318,11 @@ void Scheduler::SwitchContext() {
Thread* const new_thread = GetSelectedThread(); Thread* const new_thread = GetSelectedThread();
context_switch_pending = false; context_switch_pending = false;
if (new_thread == previous_thread) if (new_thread == previous_thread) {
return; return;
}
Process* const previous_process = Core::CurrentProcess(); Process* const previous_process = system.Kernel().CurrentProcess();
UpdateLastContextSwitchTime(previous_thread, previous_process); UpdateLastContextSwitchTime(previous_thread, previous_process);
@ -324,7 +342,7 @@ void Scheduler::SwitchContext() {
// Load context of new thread // Load context of new thread
if (new_thread) { if (new_thread) {
ASSERT_MSG(new_thread->GetProcessorID() == this->id, ASSERT_MSG(new_thread->GetProcessorID() == this->core_id,
"Thread must be assigned to this core."); "Thread must be assigned to this core.");
ASSERT_MSG(new_thread->GetStatus() == ThreadStatus::Ready, ASSERT_MSG(new_thread->GetStatus() == ThreadStatus::Ready,
"Thread must be ready to become running."); "Thread must be ready to become running.");
@ -353,7 +371,7 @@ void Scheduler::SwitchContext() {
void Scheduler::UpdateLastContextSwitchTime(Thread* thread, Process* process) { void Scheduler::UpdateLastContextSwitchTime(Thread* thread, Process* process) {
const u64 prev_switch_ticks = last_context_switch_time; const u64 prev_switch_ticks = last_context_switch_time;
const u64 most_recent_switch_ticks = Core::System::GetInstance().CoreTiming().GetTicks(); const u64 most_recent_switch_ticks = system.CoreTiming().GetTicks();
const u64 update_ticks = most_recent_switch_ticks - prev_switch_ticks; const u64 update_ticks = most_recent_switch_ticks - prev_switch_ticks;
if (thread != nullptr) { if (thread != nullptr) {

View file

@ -24,63 +24,71 @@ class GlobalScheduler final {
public: public:
static constexpr u32 NUM_CPU_CORES = 4; static constexpr u32 NUM_CPU_CORES = 4;
GlobalScheduler() { explicit GlobalScheduler(Core::System& system);
reselection_pending = false;
}
~GlobalScheduler(); ~GlobalScheduler();
/// Adds a new thread to the scheduler /// Adds a new thread to the scheduler
void AddThread(SharedPtr<Thread> thread); void AddThread(SharedPtr<Thread> thread);
/// Removes a thread from the scheduler /// Removes a thread from the scheduler
void RemoveThread(Thread* thread); void RemoveThread(const Thread* thread);
/// Returns a list of all threads managed by the scheduler /// Returns a list of all threads managed by the scheduler
const std::vector<SharedPtr<Thread>>& GetThreadList() const { const std::vector<SharedPtr<Thread>>& GetThreadList() const {
return thread_list; return thread_list;
} }
// 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) { void Suggest(u32 priority, u32 core, Thread* thread) {
suggested_queue[core].add(thread, priority); suggested_queue[core].add(thread, priority);
} }
// 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) { void Unsuggest(u32 priority, u32 core, Thread* thread) {
suggested_queue[core].remove(thread, priority); suggested_queue[core].remove(thread, priority);
} }
void Schedule(u32 priority, u32 core, Thread* thread) { // Add a thread to the scheduling queue of a cpu core. The thread is added at the
ASSERT_MSG(thread->GetProcessorID() == core, "Thread must be assigned to this core."); // back the queue in its priority level
scheduled_queue[core].add(thread, priority); void Schedule(u32 priority, u32 core, Thread* thread);
}
void SchedulePrepend(u32 priority, u32 core, Thread* thread) { // Add a thread to the scheduling queue of a cpu core. The thread is added at the
ASSERT_MSG(thread->GetProcessorID() == core, "Thread must be assigned to this core."); // front the queue in its priority level
scheduled_queue[core].add(thread, priority, false); void SchedulePrepend(u32 priority, u32 core, Thread* thread);
}
// Reschedule an already scheduled thread based on a new priority
void Reschedule(u32 priority, u32 core, Thread* thread) { void Reschedule(u32 priority, u32 core, Thread* thread) {
scheduled_queue[core].remove(thread, priority); scheduled_queue[core].remove(thread, priority);
scheduled_queue[core].add(thread, priority); scheduled_queue[core].add(thread, priority);
} }
// Unschedule a thread.
void Unschedule(u32 priority, u32 core, Thread* thread) { void Unschedule(u32 priority, u32 core, Thread* thread) {
scheduled_queue[core].remove(thread, priority); scheduled_queue[core].remove(thread, priority);
} }
// 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) { void TransferToCore(u32 priority, s32 destination_core, Thread* thread) {
bool schedulable = thread->GetPriority() < THREADPRIO_COUNT; const bool schedulable = thread->GetPriority() < THREADPRIO_COUNT;
s32 source_core = thread->GetProcessorID(); const s32 source_core = thread->GetProcessorID();
if (source_core == destination_core || !schedulable) if (source_core == destination_core || !schedulable) {
return; return;
}
thread->SetProcessorID(destination_core); thread->SetProcessorID(destination_core);
if (source_core >= 0) if (source_core >= 0) {
Unschedule(priority, source_core, thread); Unschedule(priority, source_core, thread);
}
if (destination_core >= 0) { if (destination_core >= 0) {
Unsuggest(priority, destination_core, thread); Unsuggest(priority, destination_core, thread);
Schedule(priority, destination_core, thread); Schedule(priority, destination_core, thread);
} }
if (source_core >= 0) if (source_core >= 0) {
Suggest(priority, source_core, thread); Suggest(priority, source_core, thread);
} }
}
/* /*
* UnloadThread selects a core and forces it to unload its current thread's context * UnloadThread selects a core and forces it to unload its current thread's context
@ -99,7 +107,7 @@ public:
*/ */
void SelectThread(u32 core); void SelectThread(u32 core);
bool HaveReadyThreads(u32 core_id) { bool HaveReadyThreads(u32 core_id) const {
return !scheduled_queue[core_id].empty(); return !scheduled_queue[core_id].empty();
} }
@ -133,8 +141,8 @@ public:
reselection_pending.store(true, std::memory_order_release); reselection_pending.store(true, std::memory_order_release);
} }
bool IsReselectionPending() { bool IsReselectionPending() const {
return reselection_pending.load(std::memory_order_acquire); return reselection_pending.load();
} }
private: private:
@ -147,11 +155,12 @@ private:
/// Lists all thread ids that aren't deleted/etc. /// Lists all thread ids that aren't deleted/etc.
std::vector<SharedPtr<Thread>> thread_list; std::vector<SharedPtr<Thread>> thread_list;
Core::System& system;
}; };
class Scheduler final { class Scheduler final {
public: public:
explicit Scheduler(Core::System& system, Core::ARM_Interface& cpu_core, const u32 id); explicit Scheduler(Core::System& system, Core::ARM_Interface& cpu_core, const u32 core_id);
~Scheduler(); ~Scheduler();
/// Returns whether there are any threads that are ready to run. /// Returns whether there are any threads that are ready to run.
@ -204,7 +213,7 @@ private:
Core::ARM_Interface& cpu_core; Core::ARM_Interface& cpu_core;
u64 last_context_switch_time = 0; u64 last_context_switch_time = 0;
u64 idle_selection_count = 0; u64 idle_selection_count = 0;
const u32 id; const u32 core_id;
bool context_switch_pending = false; bool context_switch_pending = false;
}; };

View file

@ -1560,13 +1560,13 @@ static void SleepThread(Core::System& system, s64 nanoseconds) {
if (nanoseconds <= 0) { if (nanoseconds <= 0) {
switch (static_cast<SleepType>(nanoseconds)) { switch (static_cast<SleepType>(nanoseconds)) {
case SleepType::YieldWithoutLoadBalancing: case SleepType::YieldWithoutLoadBalancing:
current_thread->YieldType0(); current_thread->YieldSimple();
break; break;
case SleepType::YieldWithLoadBalancing: case SleepType::YieldWithLoadBalancing:
current_thread->YieldType1(); current_thread->YieldAndBalanceLoad();
break; break;
case SleepType::YieldAndWaitForLoadBalancing: case SleepType::YieldAndWaitForLoadBalancing:
current_thread->YieldType2(); current_thread->YieldAndWaitForLoadBalancing();
break; break;
default: default:
UNREACHABLE_MSG("Unimplemented sleep yield type '{:016X}'!", nanoseconds); UNREACHABLE_MSG("Unimplemented sleep yield type '{:016X}'!", nanoseconds);
@ -1638,9 +1638,10 @@ static ResultCode SignalProcessWideKey(Core::System& system, VAddr condition_var
const auto& thread_list = scheduler.GetThreadList(); const auto& thread_list = scheduler.GetThreadList();
for (const auto& thread : thread_list) { for (const auto& thread : thread_list) {
if (thread->GetCondVarWaitAddress() == condition_variable_addr) if (thread->GetCondVarWaitAddress() == condition_variable_addr) {
waiting_threads.push_back(thread); waiting_threads.push_back(thread);
} }
}
// Sort them by priority, such that the highest priority ones come first. // Sort them by priority, such that the highest priority ones come first.
std::sort(waiting_threads.begin(), waiting_threads.end(), std::sort(waiting_threads.begin(), waiting_threads.end(),
@ -1747,9 +1748,11 @@ static ResultCode WaitForAddress(Core::System& system, VAddr address, u32 type,
const auto arbitration_type = static_cast<AddressArbiter::ArbitrationType>(type); const auto arbitration_type = static_cast<AddressArbiter::ArbitrationType>(type);
auto& address_arbiter = system.Kernel().CurrentProcess()->GetAddressArbiter(); auto& address_arbiter = system.Kernel().CurrentProcess()->GetAddressArbiter();
ResultCode result = address_arbiter.WaitForAddress(address, arbitration_type, value, timeout); const ResultCode result =
if (result == RESULT_SUCCESS) address_arbiter.WaitForAddress(address, arbitration_type, value, timeout);
if (result == RESULT_SUCCESS) {
system.PrepareReschedule(); system.PrepareReschedule();
}
return result; return result;
} }

View file

@ -373,43 +373,44 @@ void Thread::Sleep(s64 nanoseconds) {
WakeAfterDelay(nanoseconds); WakeAfterDelay(nanoseconds);
} }
void Thread::YieldType0() { void Thread::YieldSimple() {
auto& scheduler = kernel.GlobalScheduler(); auto& scheduler = kernel.GlobalScheduler();
scheduler.YieldThread(this); scheduler.YieldThread(this);
} }
void Thread::YieldType1() { void Thread::YieldAndBalanceLoad() {
auto& scheduler = kernel.GlobalScheduler(); auto& scheduler = kernel.GlobalScheduler();
scheduler.YieldThreadAndBalanceLoad(this); scheduler.YieldThreadAndBalanceLoad(this);
} }
void Thread::YieldType2() { void Thread::YieldAndWaitForLoadBalancing() {
auto& scheduler = kernel.GlobalScheduler(); auto& scheduler = kernel.GlobalScheduler();
scheduler.YieldThreadAndWaitForLoadBalancing(this); scheduler.YieldThreadAndWaitForLoadBalancing(this);
} }
void Thread::SetSchedulingStatus(ThreadSchedStatus new_status) { void Thread::SetSchedulingStatus(ThreadSchedStatus new_status) {
u32 old_flags = scheduling_state; const u32 old_flags = scheduling_state;
scheduling_state = scheduling_state =
(scheduling_state & ThreadSchedMasks::HighMask) | static_cast<u32>(new_status); (scheduling_state & ThreadSchedMasks::HighMask) | static_cast<u32>(new_status);
AdjustSchedulingOnStatus(old_flags); AdjustSchedulingOnStatus(old_flags);
} }
void Thread::SetCurrentPriority(u32 new_priority) { void Thread::SetCurrentPriority(u32 new_priority) {
u32 old_priority = current_priority; u32 old_priority = std::exchange(current_priority, new_priority);
current_priority = new_priority;
AdjustSchedulingOnPriority(old_priority); AdjustSchedulingOnPriority(old_priority);
} }
ResultCode Thread::SetCoreAndAffinityMask(s32 new_core, u64 new_affinity_mask) { ResultCode Thread::SetCoreAndAffinityMask(s32 new_core, u64 new_affinity_mask) {
auto HighestSetCore = [](u64 mask, u32 max_cores) { const auto HighestSetCore = [](u64 mask, u32 max_cores) {
for (s32 core = max_cores - 1; core >= 0; core--) { for (s32 core = max_cores - 1; core >= 0; core--) {
if (((mask >> core) & 1) != 0) if (((mask >> core) & 1) != 0) {
return core; return core;
} }
}
return -1; return -1;
}; };
bool use_override = affinity_override_count != 0;
const bool use_override = affinity_override_count != 0;
// The value -3 is "do not change the ideal core". // The value -3 is "do not change the ideal core".
if (new_core == -3) { if (new_core == -3) {
new_core = use_override ? ideal_core_override : ideal_core; new_core = use_override ? ideal_core_override : ideal_core;
@ -421,11 +422,10 @@ ResultCode Thread::SetCoreAndAffinityMask(s32 new_core, u64 new_affinity_mask) {
ideal_core_override = new_core; ideal_core_override = new_core;
affinity_mask_override = new_affinity_mask; affinity_mask_override = new_affinity_mask;
} else { } else {
u64 old_affinity_mask = affinity_mask; const u64 old_affinity_mask = std::exchange(affinity_mask, new_affinity_mask);
ideal_core = new_core; ideal_core = new_core;
affinity_mask = new_affinity_mask;
if (old_affinity_mask != new_affinity_mask) { if (old_affinity_mask != new_affinity_mask) {
s32 old_core = processor_id; const s32 old_core = processor_id;
if (processor_id >= 0 && ((affinity_mask >> processor_id) & 1) == 0) { if (processor_id >= 0 && ((affinity_mask >> processor_id) & 1) == 0) {
if (ideal_core < 0) { if (ideal_core < 0) {
processor_id = HighestSetCore(affinity_mask, GlobalScheduler::NUM_CPU_CORES); processor_id = HighestSetCore(affinity_mask, GlobalScheduler::NUM_CPU_CORES);
@ -440,30 +440,35 @@ ResultCode Thread::SetCoreAndAffinityMask(s32 new_core, u64 new_affinity_mask) {
} }
void Thread::AdjustSchedulingOnStatus(u32 old_flags) { void Thread::AdjustSchedulingOnStatus(u32 old_flags) {
if (old_flags == scheduling_state) if (old_flags == scheduling_state) {
return; return;
}
auto& scheduler = kernel.GlobalScheduler(); auto& scheduler = kernel.GlobalScheduler();
if (static_cast<ThreadSchedStatus>(old_flags & ThreadSchedMasks::LowMask) == if (static_cast<ThreadSchedStatus>(old_flags & ThreadSchedMasks::LowMask) ==
ThreadSchedStatus::Runnable) { ThreadSchedStatus::Runnable) {
// In this case the thread was running, now it's pausing/exitting // In this case the thread was running, now it's pausing/exitting
if (processor_id >= 0) if (processor_id >= 0) {
scheduler.Unschedule(current_priority, processor_id, this); scheduler.Unschedule(current_priority, processor_id, this);
}
for (s32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) { for (u32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) {
if (core != processor_id && ((affinity_mask >> core) & 1) != 0) if (core != processor_id && ((affinity_mask >> core) & 1) != 0) {
scheduler.Unsuggest(current_priority, core, this); scheduler.Unsuggest(current_priority, core, this);
} }
}
} else if (GetSchedulingStatus() == ThreadSchedStatus::Runnable) { } else if (GetSchedulingStatus() == ThreadSchedStatus::Runnable) {
// The thread is now set to running from being stopped // The thread is now set to running from being stopped
if (processor_id >= 0) if (processor_id >= 0) {
scheduler.Schedule(current_priority, processor_id, this); scheduler.Schedule(current_priority, processor_id, this);
}
for (s32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) { for (u32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) {
if (core != processor_id && ((affinity_mask >> core) & 1) != 0) if (core != processor_id && ((affinity_mask >> core) & 1) != 0) {
scheduler.Suggest(current_priority, core, this); scheduler.Suggest(current_priority, core, this);
} }
} }
}
scheduler.SetReselectionPending(); scheduler.SetReselectionPending();
} }
@ -477,7 +482,7 @@ void Thread::AdjustSchedulingOnPriority(u32 old_priority) {
scheduler.Unschedule(old_priority, processor_id, this); scheduler.Unschedule(old_priority, processor_id, this);
} }
for (s32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) { for (u32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) {
if (core != processor_id && ((affinity_mask >> core) & 1) != 0) { if (core != processor_id && ((affinity_mask >> core) & 1) != 0) {
scheduler.Unsuggest(old_priority, core, this); scheduler.Unsuggest(old_priority, core, this);
} }
@ -494,7 +499,7 @@ void Thread::AdjustSchedulingOnPriority(u32 old_priority) {
} }
} }
for (s32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) { for (u32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) {
if (core != processor_id && ((affinity_mask >> core) & 1) != 0) { if (core != processor_id && ((affinity_mask >> core) & 1) != 0) {
scheduler.Suggest(current_priority, core, this); scheduler.Suggest(current_priority, core, this);
} }
@ -506,10 +511,11 @@ void Thread::AdjustSchedulingOnPriority(u32 old_priority) {
void Thread::AdjustSchedulingOnAffinity(u64 old_affinity_mask, s32 old_core) { void Thread::AdjustSchedulingOnAffinity(u64 old_affinity_mask, s32 old_core) {
auto& scheduler = Core::System::GetInstance().GlobalScheduler(); auto& scheduler = Core::System::GetInstance().GlobalScheduler();
if (GetSchedulingStatus() != ThreadSchedStatus::Runnable || if (GetSchedulingStatus() != ThreadSchedStatus::Runnable ||
current_priority >= THREADPRIO_COUNT) current_priority >= THREADPRIO_COUNT) {
return; return;
}
for (s32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) { for (u32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) {
if (((old_affinity_mask >> core) & 1) != 0) { if (((old_affinity_mask >> core) & 1) != 0) {
if (core == old_core) { if (core == old_core) {
scheduler.Unschedule(current_priority, core, this); scheduler.Unschedule(current_priority, core, this);
@ -519,7 +525,7 @@ void Thread::AdjustSchedulingOnAffinity(u64 old_affinity_mask, s32 old_core) {
} }
} }
for (s32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) { for (u32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) {
if (((affinity_mask >> core) & 1) != 0) { if (((affinity_mask >> core) & 1) != 0) {
if (core == processor_id) { if (core == processor_id) {
scheduler.Schedule(current_priority, core, this); scheduler.Schedule(current_priority, core, this);

View file

@ -75,7 +75,12 @@ enum class ThreadActivity : u32 {
Paused = 1, Paused = 1,
}; };
enum class ThreadSchedStatus : u32 { None = 0, Paused = 1, Runnable = 2, Exited = 3 }; enum class ThreadSchedStatus : u32 {
None = 0,
Paused = 1,
Runnable = 2,
Exited = 3,
};
enum ThreadSchedFlags : u32 { enum ThreadSchedFlags : u32 {
ProcessPauseFlag = 1 << 4, ProcessPauseFlag = 1 << 4,
@ -403,15 +408,15 @@ public:
void Sleep(s64 nanoseconds); void Sleep(s64 nanoseconds);
/// Yields this thread without rebalancing loads. /// Yields this thread without rebalancing loads.
void YieldType0(); void YieldSimple();
/// Yields this thread and does a load rebalancing. /// Yields this thread and does a load rebalancing.
void YieldType1(); void YieldAndBalanceLoad();
/// Yields this thread and if the core is left idle, loads are rebalanced /// Yields this thread and if the core is left idle, loads are rebalanced
void YieldType2(); void YieldAndWaitForLoadBalancing();
ThreadSchedStatus GetSchedulingStatus() { ThreadSchedStatus GetSchedulingStatus() const {
return static_cast<ThreadSchedStatus>(scheduling_state & ThreadSchedMasks::LowMask); return static_cast<ThreadSchedStatus>(scheduling_state & ThreadSchedMasks::LowMask);
} }