summaryrefslogtreecommitdiffstats
path: root/src/core/hle
diff options
context:
space:
mode:
Diffstat (limited to 'src/core/hle')
-rw-r--r--src/core/hle/ipc.h6
-rw-r--r--src/core/hle/kernel/address_arbiter.cpp46
-rw-r--r--src/core/hle/kernel/kernel.cpp43
-rw-r--r--src/core/hle/kernel/kernel.h7
-rw-r--r--src/core/hle/kernel/mutex.cpp3
-rw-r--r--src/core/hle/kernel/process.cpp5
-rw-r--r--src/core/hle/kernel/scheduler.cpp539
-rw-r--r--src/core/hle/kernel/scheduler.h250
-rw-r--r--src/core/hle/kernel/svc.cpp99
-rw-r--r--src/core/hle/kernel/thread.cpp252
-rw-r--r--src/core/hle/kernel/thread.h74
-rw-r--r--src/core/hle/kernel/wait_object.cpp7
-rw-r--r--src/core/hle/service/am/am.cpp36
-rw-r--r--src/core/hle/service/am/am.h3
-rw-r--r--src/core/hle/service/am/applets/error.cpp11
-rw-r--r--src/core/hle/service/apm/controller.cpp50
-rw-r--r--src/core/hle/service/apm/controller.h2
-rw-r--r--src/core/hle/service/bcat/backend/backend.cpp4
-rw-r--r--src/core/hle/service/bcat/backend/backend.h12
-rw-r--r--src/core/hle/service/bcat/backend/boxcat.cpp29
-rw-r--r--src/core/hle/service/bcat/backend/boxcat.h10
-rw-r--r--src/core/hle/service/bcat/module.cpp24
-rw-r--r--src/core/hle/service/es/es.cpp12
-rw-r--r--src/core/hle/service/hid/controllers/npad.cpp64
-rw-r--r--src/core/hle/service/hid/controllers/npad.h10
-rw-r--r--src/core/hle/service/hid/hid.cpp13
-rw-r--r--src/core/hle/service/hid/hid.h1
-rw-r--r--src/core/hle/service/lm/lm.cpp187
-rw-r--r--src/core/hle/service/lm/lm.h6
-rw-r--r--src/core/hle/service/lm/manager.cpp133
-rw-r--r--src/core/hle/service/lm/manager.h106
-rw-r--r--src/core/hle/service/ns/pl_u.cpp169
-rw-r--r--src/core/hle/service/ns/pl_u.h3
-rw-r--r--src/core/hle/service/nvdrv/devices/nvdisp_disp0.cpp4
-rw-r--r--src/core/hle/service/nvdrv/devices/nvhost_ctrl.cpp33
-rw-r--r--src/core/hle/service/nvdrv/interface.cpp4
-rw-r--r--src/core/hle/service/nvdrv/nvdrv.cpp4
-rw-r--r--src/core/hle/service/nvflinger/buffer_queue.cpp4
-rw-r--r--src/core/hle/service/nvflinger/buffer_queue.h6
-rw-r--r--src/core/hle/service/nvflinger/nvflinger.cpp12
-rw-r--r--src/core/hle/service/service.cpp2
-rw-r--r--src/core/hle/service/vi/vi.cpp2
42 files changed, 1475 insertions, 812 deletions
diff --git a/src/core/hle/ipc.h b/src/core/hle/ipc.h
index fae54bcc7..7ce313190 100644
--- a/src/core/hle/ipc.h
+++ b/src/core/hle/ipc.h
@@ -160,7 +160,7 @@ struct DomainMessageHeader {
// Used when responding to an IPC request, Server -> Client.
struct {
u32_le num_objects;
- INSERT_PADDING_WORDS(3);
+ INSERT_UNION_PADDING_WORDS(3);
};
// Used when performing an IPC request, Client -> Server.
@@ -171,8 +171,10 @@ struct DomainMessageHeader {
BitField<16, 16, u32> size;
};
u32_le object_id;
- INSERT_PADDING_WORDS(2);
+ INSERT_UNION_PADDING_WORDS(2);
};
+
+ std::array<u32, 4> raw{};
};
};
static_assert(sizeof(DomainMessageHeader) == 16, "DomainMessageHeader size is incorrect");
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..0e2dbf13e 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,403 @@
namespace Kernel {
-std::mutex Scheduler::scheduler_mutex;
+GlobalScheduler::GlobalScheduler(Core::System& system) : system{system} {}
-Scheduler::Scheduler(Core::System& system, Core::ARM_Interface& cpu_core)
- : cpu_core{cpu_core}, system{system} {}
+GlobalScheduler::~GlobalScheduler() = default;
-Scheduler::~Scheduler() {
- for (auto& thread : thread_list) {
- thread->Stop();
+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());
+}
+
+void GlobalScheduler::UnloadThread(s32 core) {
+ Scheduler& sched = system.Scheduler(core);
+ sched.UnloadThread();
+}
+
+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);
}
+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
+ const Thread* const winner = scheduled_queue[core_id].front(priority);
+ ASSERT_MSG(yielding_thread == winner, "Thread yielding without being in front");
+ scheduled_queue[core_id].yield(priority);
+
+ return AskForReselectionOrMarkRedundant(yielding_thread, winner);
+}
+
+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);
+}
+
+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(), s32(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(), s32(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() == s32(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() == s32(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);
+ }
+}
+
+bool GlobalScheduler::AskForReselectionOrMarkRedundant(Thread* current_thread,
+ const Thread* winner) {
+ if (current_thread == winner) {
+ current_thread->IncrementYieldCount();
+ return true;
+ } else {
+ is_reselection_pending.store(true, std::memory_order_release);
+ return false;
+ }
+}
+
+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();
+}
+
+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 +432,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() == s32(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 +482,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..f2d6311b8 100644
--- a/src/core/hle/kernel/scheduler.h
+++ b/src/core/hle/kernel/scheduler.h
@@ -20,124 +20,185 @@ namespace Kernel {
class Process;
-class Scheduler final {
+class GlobalScheduler final {
public:
- explicit Scheduler(Core::System& system, Core::ARM_Interface& cpu_core);
- ~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 Reschedule();
-
- /// Gets the current running thread
- Thread* GetCurrentThread() const;
+ static constexpr u32 NUM_CPU_CORES = 4;
- /// Gets the timestamp for the last context switch in ticks.
- u64 GetLastContextSwitchTicks() const;
+ explicit GlobalScheduler(Core::System& system);
+ ~GlobalScheduler();
/// Adds a new thread to the scheduler
void AddThread(SharedPtr<Thread> thread);
/// Removes a thread from the scheduler
- void RemoveThread(Thread* thread);
+ void RemoveThread(const Thread* thread);
- /// Schedules a thread that has become "ready"
- void ScheduleThread(Thread* thread, u32 priority);
+ /// Returns a list of all threads managed by the scheduler
+ const std::vector<SharedPtr<Thread>>& GetThreadList() const {
+ return thread_list;
+ }
- /// Unschedules a thread that was already scheduled
- void UnscheduleThread(Thread* thread, u32 priority);
+ /**
+ * 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);
- /// Sets the priority of a thread in the scheduler
- void SetThreadPriority(Thread* thread, u32 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);
- /// Gets the next suggested thread for load balancing
- Thread* GetNextSuggestedThread(u32 core, u32 minimum_priority) const;
+ /**
+ * 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);
/**
- * 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.
+ * 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);
+
+ /// Reschedule an already scheduled thread based on a new priority
+ void Reschedule(u32 priority, u32 core, Thread* thread);
+
+ /// Unschedules a thread.
+ void Unschedule(u32 priority, u32 core, Thread* thread);
+
+ /**
+ * 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 YieldWithoutLoadBalancing(Thread* thread);
+ void TransferToCore(u32 priority, s32 destination_core, Thread* thread);
+
+ /// Selects a core and forces it to unload its current thread's context
+ void UnloadThread(s32 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.
+ * Takes care of selecting the new scheduled thread in three steps:
*
- * 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
+ * 1. 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.
*
- * ThreadQ calls YieldWithLoadBalancing
+ * 2. 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.
*
- * 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
+ * 3. 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);
+
+ bool HaveReadyThreads(u32 core_id) const {
+ return !scheduled_queue[core_id].empty();
+ }
+
+ /**
+ * Takes a thread and moves it to the back of the it's priority list.
*
- * 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.
+ * @note This operation can be redundant and no scheduling is changed if marked as so.
+ */
+ bool YieldThread(Thread* thread);
+
+ /**
+ * 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.
*
- * 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
+ * @note This operation can be redundant and no scheduling is changed if marked as so.
+ */
+ bool YieldThreadAndBalanceLoad(Thread* thread);
+
+ /**
+ * Takes a thread and moves it out of the scheduling queue.
+ * and into the suggested queue. If no thread can be scheduled afterwards in that core,
+ * a suggested thread is obtained instead.
*
- * 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
+ * @note This operation can be redundant and no scheduling is changed if marked as so.
+ */
+ bool YieldThreadAndWaitForLoadBalancing(Thread* thread);
+
+ /**
+ * 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'.
*
- * 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.
+ * @note This operation happens every 10ms.
*/
- void YieldWithLoadBalancing(Thread* thread);
+ void PreemptThreads();
- /// Currently unknown -- asserts as unimplemented on call
- void YieldAndWaitForLoadBalancing(Thread* thread);
+ u32 CpuCoresCount() const {
+ return NUM_CPU_CORES;
+ }
- /// Returns a list of all threads managed by the scheduler
- const std::vector<SharedPtr<Thread>>& GetThreadList() const {
- return thread_list;
+ 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, const Thread* winner);
- /**
- * 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);
+ 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{false};
+
+ // 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
+ void SwitchContext();
/**
* Called on every context switch to update the internal timestamp
@@ -152,19 +213,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/core/hle/service/am/am.cpp b/src/core/hle/service/am/am.cpp
index 941ebc93a..3d8a91d22 100644
--- a/src/core/hle/service/am/am.cpp
+++ b/src/core/hle/service/am/am.cpp
@@ -1073,9 +1073,9 @@ IApplicationFunctions::IApplicationFunctions(Core::System& system_)
{71, nullptr, "RequestToReboot"},
{80, nullptr, "ExitAndRequestToShowThanksMessage"},
{90, &IApplicationFunctions::EnableApplicationCrashReport, "EnableApplicationCrashReport"},
- {100, nullptr, "InitializeApplicationCopyrightFrameBuffer"},
- {101, nullptr, "SetApplicationCopyrightImage"},
- {102, nullptr, "SetApplicationCopyrightVisibility"},
+ {100, &IApplicationFunctions::InitializeApplicationCopyrightFrameBuffer, "InitializeApplicationCopyrightFrameBuffer"},
+ {101, &IApplicationFunctions::SetApplicationCopyrightImage, "SetApplicationCopyrightImage"},
+ {102, &IApplicationFunctions::SetApplicationCopyrightVisibility, "SetApplicationCopyrightVisibility"},
{110, nullptr, "QueryApplicationPlayStatistics"},
{120, nullptr, "ExecuteProgram"},
{121, nullptr, "ClearUserChannel"},
@@ -1103,6 +1103,31 @@ void IApplicationFunctions::EnableApplicationCrashReport(Kernel::HLERequestConte
rb.Push(RESULT_SUCCESS);
}
+void IApplicationFunctions::InitializeApplicationCopyrightFrameBuffer(
+ Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
+
+void IApplicationFunctions::SetApplicationCopyrightImage(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
+
+void IApplicationFunctions::SetApplicationCopyrightVisibility(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto is_visible = rp.Pop<bool>();
+
+ LOG_WARNING(Service_AM, "(STUBBED) called, is_visible={}", is_visible);
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
+
void IApplicationFunctions::BeginBlockingHomeButtonShortAndLongPressed(
Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_AM, "(STUBBED) called");
@@ -1140,8 +1165,9 @@ void IApplicationFunctions::PopLaunchParameter(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_AM, "called, kind={:08X}", static_cast<u8>(kind));
if (kind == LaunchParameterKind::ApplicationSpecific && !launch_popped_application_specific) {
- const auto backend = BCAT::CreateBackendFromSettings(
- [this](u64 tid) { return system.GetFileSystemController().GetBCATDirectory(tid); });
+ const auto backend = BCAT::CreateBackendFromSettings(system, [this](u64 tid) {
+ return system.GetFileSystemController().GetBCATDirectory(tid);
+ });
const auto build_id_full = system.GetCurrentProcessBuildID();
u64 build_id{};
std::memcpy(&build_id, build_id_full.data(), sizeof(u64));
diff --git a/src/core/hle/service/am/am.h b/src/core/hle/service/am/am.h
index ccd053c13..2ae9402a8 100644
--- a/src/core/hle/service/am/am.h
+++ b/src/core/hle/service/am/am.h
@@ -252,6 +252,9 @@ private:
void BeginBlockingHomeButton(Kernel::HLERequestContext& ctx);
void EndBlockingHomeButton(Kernel::HLERequestContext& ctx);
void EnableApplicationCrashReport(Kernel::HLERequestContext& ctx);
+ void InitializeApplicationCopyrightFrameBuffer(Kernel::HLERequestContext& ctx);
+ void SetApplicationCopyrightImage(Kernel::HLERequestContext& ctx);
+ void SetApplicationCopyrightVisibility(Kernel::HLERequestContext& ctx);
void GetGpuErrorDetectedSystemEvent(Kernel::HLERequestContext& ctx);
bool launch_popped_application_specific = false;
diff --git a/src/core/hle/service/am/applets/error.cpp b/src/core/hle/service/am/applets/error.cpp
index a7db26725..eab0d42c9 100644
--- a/src/core/hle/service/am/applets/error.cpp
+++ b/src/core/hle/service/am/applets/error.cpp
@@ -20,9 +20,9 @@ namespace Service::AM::Applets {
struct ShowError {
u8 mode;
bool jump;
- INSERT_PADDING_BYTES(4);
+ INSERT_UNION_PADDING_BYTES(4);
bool use_64bit_error_code;
- INSERT_PADDING_BYTES(1);
+ INSERT_UNION_PADDING_BYTES(1);
u64 error_code_64;
u32 error_code_32;
};
@@ -32,7 +32,7 @@ static_assert(sizeof(ShowError) == 0x14, "ShowError has incorrect size.");
struct ShowErrorRecord {
u8 mode;
bool jump;
- INSERT_PADDING_BYTES(6);
+ INSERT_UNION_PADDING_BYTES(6);
u64 error_code_64;
u64 posix_time;
};
@@ -41,7 +41,7 @@ static_assert(sizeof(ShowErrorRecord) == 0x18, "ShowErrorRecord has incorrect si
struct SystemErrorArg {
u8 mode;
bool jump;
- INSERT_PADDING_BYTES(6);
+ INSERT_UNION_PADDING_BYTES(6);
u64 error_code_64;
std::array<char, 8> language_code;
std::array<char, 0x800> main_text;
@@ -52,7 +52,7 @@ static_assert(sizeof(SystemErrorArg) == 0x1018, "SystemErrorArg has incorrect si
struct ApplicationErrorArg {
u8 mode;
bool jump;
- INSERT_PADDING_BYTES(6);
+ INSERT_UNION_PADDING_BYTES(6);
u32 error_code;
std::array<char, 8> language_code;
std::array<char, 0x800> main_text;
@@ -65,6 +65,7 @@ union Error::ErrorArguments {
ShowErrorRecord error_record;
SystemErrorArg system_error;
ApplicationErrorArg application_error;
+ std::array<u8, 0x1018> raw{};
};
namespace {
diff --git a/src/core/hle/service/apm/controller.cpp b/src/core/hle/service/apm/controller.cpp
index 073d0f6fa..25a886238 100644
--- a/src/core/hle/service/apm/controller.cpp
+++ b/src/core/hle/service/apm/controller.cpp
@@ -2,6 +2,10 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
+#include <algorithm>
+#include <array>
+#include <utility>
+
#include "common/logging/log.h"
#include "core/core_timing.h"
#include "core/hle/service/apm/controller.h"
@@ -9,8 +13,7 @@
namespace Service::APM {
-constexpr PerformanceConfiguration DEFAULT_PERFORMANCE_CONFIGURATION =
- PerformanceConfiguration::Config7;
+constexpr auto DEFAULT_PERFORMANCE_CONFIGURATION = PerformanceConfiguration::Config7;
Controller::Controller(Core::Timing::CoreTiming& core_timing)
: core_timing{core_timing}, configs{
@@ -22,18 +25,35 @@ Controller::~Controller() = default;
void Controller::SetPerformanceConfiguration(PerformanceMode mode,
PerformanceConfiguration config) {
- static const std::map<PerformanceConfiguration, u32> PCONFIG_TO_SPEED_MAP{
- {PerformanceConfiguration::Config1, 1020}, {PerformanceConfiguration::Config2, 1020},
- {PerformanceConfiguration::Config3, 1224}, {PerformanceConfiguration::Config4, 1020},
- {PerformanceConfiguration::Config5, 1020}, {PerformanceConfiguration::Config6, 1224},
- {PerformanceConfiguration::Config7, 1020}, {PerformanceConfiguration::Config8, 1020},
- {PerformanceConfiguration::Config9, 1020}, {PerformanceConfiguration::Config10, 1020},
- {PerformanceConfiguration::Config11, 1020}, {PerformanceConfiguration::Config12, 1020},
- {PerformanceConfiguration::Config13, 1785}, {PerformanceConfiguration::Config14, 1785},
- {PerformanceConfiguration::Config15, 1020}, {PerformanceConfiguration::Config16, 1020},
- };
-
- SetClockSpeed(PCONFIG_TO_SPEED_MAP.find(config)->second);
+ static constexpr std::array<std::pair<PerformanceConfiguration, u32>, 16> config_to_speed{{
+ {PerformanceConfiguration::Config1, 1020},
+ {PerformanceConfiguration::Config2, 1020},
+ {PerformanceConfiguration::Config3, 1224},
+ {PerformanceConfiguration::Config4, 1020},
+ {PerformanceConfiguration::Config5, 1020},
+ {PerformanceConfiguration::Config6, 1224},
+ {PerformanceConfiguration::Config7, 1020},
+ {PerformanceConfiguration::Config8, 1020},
+ {PerformanceConfiguration::Config9, 1020},
+ {PerformanceConfiguration::Config10, 1020},
+ {PerformanceConfiguration::Config11, 1020},
+ {PerformanceConfiguration::Config12, 1020},
+ {PerformanceConfiguration::Config13, 1785},
+ {PerformanceConfiguration::Config14, 1785},
+ {PerformanceConfiguration::Config15, 1020},
+ {PerformanceConfiguration::Config16, 1020},
+ }};
+
+ const auto iter = std::find_if(config_to_speed.cbegin(), config_to_speed.cend(),
+ [config](const auto& entry) { return entry.first == config; });
+
+ if (iter == config_to_speed.cend()) {
+ LOG_ERROR(Service_APM, "Invalid performance configuration value provided: {}",
+ static_cast<u32>(config));
+ return;
+ }
+
+ SetClockSpeed(iter->second);
configs.insert_or_assign(mode, config);
}
@@ -48,7 +68,7 @@ void Controller::SetFromCpuBoostMode(CpuBoostMode mode) {
BOOST_MODE_TO_CONFIG_MAP.at(static_cast<u32>(mode)));
}
-PerformanceMode Controller::GetCurrentPerformanceMode() {
+PerformanceMode Controller::GetCurrentPerformanceMode() const {
return Settings::values.use_docked_mode ? PerformanceMode::Docked : PerformanceMode::Handheld;
}
diff --git a/src/core/hle/service/apm/controller.h b/src/core/hle/service/apm/controller.h
index 454caa6eb..af0c4cd34 100644
--- a/src/core/hle/service/apm/controller.h
+++ b/src/core/hle/service/apm/controller.h
@@ -56,7 +56,7 @@ public:
void SetPerformanceConfiguration(PerformanceMode mode, PerformanceConfiguration config);
void SetFromCpuBoostMode(CpuBoostMode mode);
- PerformanceMode GetCurrentPerformanceMode();
+ PerformanceMode GetCurrentPerformanceMode() const;
PerformanceConfiguration GetCurrentPerformanceConfiguration(PerformanceMode mode);
private:
diff --git a/src/core/hle/service/bcat/backend/backend.cpp b/src/core/hle/service/bcat/backend/backend.cpp
index 9d6946bc5..b86fda29a 100644
--- a/src/core/hle/service/bcat/backend/backend.cpp
+++ b/src/core/hle/service/bcat/backend/backend.cpp
@@ -10,8 +10,8 @@
namespace Service::BCAT {
-ProgressServiceBackend::ProgressServiceBackend(std::string_view event_name) {
- auto& kernel{Core::System::GetInstance().Kernel()};
+ProgressServiceBackend::ProgressServiceBackend(Kernel::KernelCore& kernel,
+ std::string_view event_name) {
event = Kernel::WritableEvent::CreateEventPair(
kernel, Kernel::ResetType::Automatic,
std::string("ProgressServiceBackend:UpdateEvent:").append(event_name));
diff --git a/src/core/hle/service/bcat/backend/backend.h b/src/core/hle/service/bcat/backend/backend.h
index 51dbd3316..ea4b16ad0 100644
--- a/src/core/hle/service/bcat/backend/backend.h
+++ b/src/core/hle/service/bcat/backend/backend.h
@@ -15,6 +15,14 @@
#include "core/hle/kernel/writable_event.h"
#include "core/hle/result.h"
+namespace Core {
+class System;
+}
+
+namespace Kernel {
+class KernelCore;
+}
+
namespace Service::BCAT {
struct DeliveryCacheProgressImpl;
@@ -88,7 +96,7 @@ public:
void FinishDownload(ResultCode result);
private:
- explicit ProgressServiceBackend(std::string_view event_name);
+ explicit ProgressServiceBackend(Kernel::KernelCore& kernel, std::string_view event_name);
Kernel::SharedPtr<Kernel::ReadableEvent> GetEvent() const;
DeliveryCacheProgressImpl& GetImpl();
@@ -145,6 +153,6 @@ public:
std::optional<std::vector<u8>> GetLaunchParameter(TitleIDVersion title) override;
};
-std::unique_ptr<Backend> CreateBackendFromSettings(DirectoryGetter getter);
+std::unique_ptr<Backend> CreateBackendFromSettings(Core::System& system, DirectoryGetter getter);
} // namespace Service::BCAT
diff --git a/src/core/hle/service/bcat/backend/boxcat.cpp b/src/core/hle/service/bcat/backend/boxcat.cpp
index 64022982b..918159e11 100644
--- a/src/core/hle/service/bcat/backend/boxcat.cpp
+++ b/src/core/hle/service/bcat/backend/boxcat.cpp
@@ -104,14 +104,15 @@ std::string GetZIPFilePath(u64 title_id) {
// If the error is something the user should know about (build ID mismatch, bad client version),
// display an error.
-void HandleDownloadDisplayResult(DownloadResult res) {
+void HandleDownloadDisplayResult(const AM::Applets::AppletManager& applet_manager,
+ DownloadResult res) {
if (res == DownloadResult::Success || res == DownloadResult::NoResponse ||
res == DownloadResult::GeneralWebError || res == DownloadResult::GeneralFSError ||
res == DownloadResult::NoMatchTitleId || res == DownloadResult::InvalidContentType) {
return;
}
- const auto& frontend{Core::System::GetInstance().GetAppletManager().GetAppletFrontendSet()};
+ const auto& frontend{applet_manager.GetAppletFrontendSet()};
frontend.error->ShowCustomErrorText(
ResultCode(-1), "There was an error while attempting to use Boxcat.",
DOWNLOAD_RESULT_LOG_MESSAGES[static_cast<std::size_t>(res)], [] {});
@@ -264,12 +265,13 @@ private:
u64 build_id;
};
-Boxcat::Boxcat(DirectoryGetter getter) : Backend(std::move(getter)) {}
+Boxcat::Boxcat(AM::Applets::AppletManager& applet_manager_, DirectoryGetter getter)
+ : Backend(std::move(getter)), applet_manager{applet_manager_} {}
Boxcat::~Boxcat() = default;
-void SynchronizeInternal(DirectoryGetter dir_getter, TitleIDVersion title,
- ProgressServiceBackend& progress,
+void SynchronizeInternal(AM::Applets::AppletManager& applet_manager, DirectoryGetter dir_getter,
+ TitleIDVersion title, ProgressServiceBackend& progress,
std::optional<std::string> dir_name = {}) {
progress.SetNeedHLELock(true);
@@ -295,7 +297,7 @@ void SynchronizeInternal(DirectoryGetter dir_getter, TitleIDVersion title,
FileUtil::Delete(zip_path);
}
- HandleDownloadDisplayResult(res);
+ HandleDownloadDisplayResult(applet_manager, res);
progress.FinishDownload(ERROR_GENERAL_BCAT_FAILURE);
return;
}
@@ -364,17 +366,24 @@ void SynchronizeInternal(DirectoryGetter dir_getter, TitleIDVersion title,
bool Boxcat::Synchronize(TitleIDVersion title, ProgressServiceBackend& progress) {
is_syncing.exchange(true);
- std::thread([this, title, &progress] { SynchronizeInternal(dir_getter, title, progress); })
+
+ std::thread([this, title, &progress] {
+ SynchronizeInternal(applet_manager, dir_getter, title, progress);
+ })
.detach();
+
return true;
}
bool Boxcat::SynchronizeDirectory(TitleIDVersion title, std::string name,
ProgressServiceBackend& progress) {
is_syncing.exchange(true);
- std::thread(
- [this, title, name, &progress] { SynchronizeInternal(dir_getter, title, progress, name); })
+
+ std::thread([this, title, name, &progress] {
+ SynchronizeInternal(applet_manager, dir_getter, title, progress, name);
+ })
.detach();
+
return true;
}
@@ -420,7 +429,7 @@ std::optional<std::vector<u8>> Boxcat::GetLaunchParameter(TitleIDVersion title)
FileUtil::Delete(path);
}
- HandleDownloadDisplayResult(res);
+ HandleDownloadDisplayResult(applet_manager, res);
return std::nullopt;
}
}
diff --git a/src/core/hle/service/bcat/backend/boxcat.h b/src/core/hle/service/bcat/backend/boxcat.h
index 601151189..d65b42e58 100644
--- a/src/core/hle/service/bcat/backend/boxcat.h
+++ b/src/core/hle/service/bcat/backend/boxcat.h
@@ -9,6 +9,10 @@
#include <optional>
#include "core/hle/service/bcat/backend/backend.h"
+namespace Service::AM::Applets {
+class AppletManager;
+}
+
namespace Service::BCAT {
struct EventStatus {
@@ -20,12 +24,13 @@ struct EventStatus {
/// Boxcat is yuzu's custom backend implementation of Nintendo's BCAT service. It is free to use and
/// doesn't require a switch or nintendo account. The content is controlled by the yuzu team.
class Boxcat final : public Backend {
- friend void SynchronizeInternal(DirectoryGetter dir_getter, TitleIDVersion title,
+ friend void SynchronizeInternal(AM::Applets::AppletManager& applet_manager,
+ DirectoryGetter dir_getter, TitleIDVersion title,
ProgressServiceBackend& progress,
std::optional<std::string> dir_name);
public:
- explicit Boxcat(DirectoryGetter getter);
+ explicit Boxcat(AM::Applets::AppletManager& applet_manager_, DirectoryGetter getter);
~Boxcat() override;
bool Synchronize(TitleIDVersion title, ProgressServiceBackend& progress) override;
@@ -53,6 +58,7 @@ private:
class Client;
std::unique_ptr<Client> client;
+ AM::Applets::AppletManager& applet_manager;
};
} // namespace Service::BCAT
diff --git a/src/core/hle/service/bcat/module.cpp b/src/core/hle/service/bcat/module.cpp
index 4e4aa758b..6d9d1527d 100644
--- a/src/core/hle/service/bcat/module.cpp
+++ b/src/core/hle/service/bcat/module.cpp
@@ -125,7 +125,11 @@ private:
class IBcatService final : public ServiceFramework<IBcatService> {
public:
explicit IBcatService(Core::System& system_, Backend& backend_)
- : ServiceFramework("IBcatService"), system{system_}, backend{backend_} {
+ : ServiceFramework("IBcatService"), system{system_}, backend{backend_},
+ progress{{
+ ProgressServiceBackend{system_.Kernel(), "Normal"},
+ ProgressServiceBackend{system_.Kernel(), "Directory"},
+ }} {
// clang-format off
static const FunctionInfo functions[] = {
{10100, &IBcatService::RequestSyncDeliveryCache, "RequestSyncDeliveryCache"},
@@ -249,10 +253,7 @@ private:
Core::System& system;
Backend& backend;
- std::array<ProgressServiceBackend, static_cast<std::size_t>(SyncType::Count)> progress{
- ProgressServiceBackend{"Normal"},
- ProgressServiceBackend{"Directory"},
- };
+ std::array<ProgressServiceBackend, static_cast<std::size_t>(SyncType::Count)> progress;
};
void Module::Interface::CreateBcatService(Kernel::HLERequestContext& ctx) {
@@ -557,12 +558,12 @@ void Module::Interface::CreateDeliveryCacheStorageServiceWithApplicationId(
rb.PushIpcInterface<IDeliveryCacheStorageService>(fsc.GetBCATDirectory(title_id));
}
-std::unique_ptr<Backend> CreateBackendFromSettings(DirectoryGetter getter) {
- const auto backend = Settings::values.bcat_backend;
-
+std::unique_ptr<Backend> CreateBackendFromSettings([[maybe_unused]] Core::System& system,
+ DirectoryGetter getter) {
#ifdef YUZU_ENABLE_BOXCAT
- if (backend == "boxcat")
- return std::make_unique<Boxcat>(std::move(getter));
+ if (Settings::values.bcat_backend == "boxcat") {
+ return std::make_unique<Boxcat>(system.GetAppletManager(), std::move(getter));
+ }
#endif
return std::make_unique<NullBackend>(std::move(getter));
@@ -571,7 +572,8 @@ std::unique_ptr<Backend> CreateBackendFromSettings(DirectoryGetter getter) {
Module::Interface::Interface(Core::System& system_, std::shared_ptr<Module> module_,
FileSystem::FileSystemController& fsc_, const char* name)
: ServiceFramework(name), fsc{fsc_}, module{std::move(module_)},
- backend{CreateBackendFromSettings([&fsc_](u64 tid) { return fsc_.GetBCATDirectory(tid); })},
+ backend{CreateBackendFromSettings(system_,
+ [&fsc_](u64 tid) { return fsc_.GetBCATDirectory(tid); })},
system{system_} {}
Module::Interface::~Interface() = default;
diff --git a/src/core/hle/service/es/es.cpp b/src/core/hle/service/es/es.cpp
index af70d174d..f77ddd739 100644
--- a/src/core/hle/service/es/es.cpp
+++ b/src/core/hle/service/es/es.cpp
@@ -128,7 +128,7 @@ private:
void CountCommonTicket(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_ETicket, "called");
- const auto count = keys.GetCommonTickets().size();
+ const u32 count = static_cast<u32>(keys.GetCommonTickets().size());
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
@@ -138,7 +138,7 @@ private:
void CountPersonalizedTicket(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_ETicket, "called");
- const auto count = keys.GetPersonalizedTickets().size();
+ const u32 count = static_cast<u32>(keys.GetPersonalizedTickets().size());
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
@@ -150,7 +150,7 @@ private:
if (keys.GetCommonTickets().empty())
out_entries = 0;
else
- out_entries = ctx.GetWriteBufferSize() / sizeof(u128);
+ out_entries = static_cast<u32>(ctx.GetWriteBufferSize() / sizeof(u128));
LOG_DEBUG(Service_ETicket, "called, entries={:016X}", out_entries);
@@ -160,7 +160,7 @@ private:
std::transform(tickets.begin(), tickets.end(), std::back_inserter(ids),
[](const auto& pair) { return pair.first; });
- out_entries = std::min<u32>(ids.size(), out_entries);
+ out_entries = static_cast<u32>(std::min<std::size_t>(ids.size(), out_entries));
ctx.WriteBuffer(ids.data(), out_entries * sizeof(u128));
IPC::ResponseBuilder rb{ctx, 3};
@@ -173,7 +173,7 @@ private:
if (keys.GetPersonalizedTickets().empty())
out_entries = 0;
else
- out_entries = ctx.GetWriteBufferSize() / sizeof(u128);
+ out_entries = static_cast<u32>(ctx.GetWriteBufferSize() / sizeof(u128));
LOG_DEBUG(Service_ETicket, "called, entries={:016X}", out_entries);
@@ -183,7 +183,7 @@ private:
std::transform(tickets.begin(), tickets.end(), std::back_inserter(ids),
[](const auto& pair) { return pair.first; });
- out_entries = std::min<u32>(ids.size(), out_entries);
+ out_entries = static_cast<u32>(std::min<std::size_t>(ids.size(), out_entries));
ctx.WriteBuffer(ids.data(), out_entries * sizeof(u128));
IPC::ResponseBuilder rb{ctx, 3};
diff --git a/src/core/hle/service/hid/controllers/npad.cpp b/src/core/hle/service/hid/controllers/npad.cpp
index a2b25a796..81bd2f3cb 100644
--- a/src/core/hle/service/hid/controllers/npad.cpp
+++ b/src/core/hle/service/hid/controllers/npad.cpp
@@ -583,36 +583,6 @@ bool Controller_NPad::SwapNpadAssignment(u32 npad_id_1, u32 npad_id_2) {
return true;
}
-bool Controller_NPad::IsControllerSupported(NPadControllerType controller) {
- if (controller == NPadControllerType::Handheld) {
- // Handheld is not even a supported type, lets stop here
- if (std::find(supported_npad_id_types.begin(), supported_npad_id_types.end(),
- NPAD_HANDHELD) == supported_npad_id_types.end()) {
- return false;
- }
- // Handheld should not be supported in docked mode
- if (Settings::values.use_docked_mode) {
- return false;
- }
- }
- switch (controller) {
- case NPadControllerType::ProController:
- return style.pro_controller;
- case NPadControllerType::Handheld:
- return style.handheld;
- case NPadControllerType::JoyDual:
- return style.joycon_dual;
- case NPadControllerType::JoyLeft:
- return style.joycon_left;
- case NPadControllerType::JoyRight:
- return style.joycon_right;
- case NPadControllerType::Pokeball:
- return style.pokeball;
- default:
- return false;
- }
-}
-
Controller_NPad::LedPattern Controller_NPad::GetLedPattern(u32 npad_id) {
if (npad_id == npad_id_list.back() || npad_id == npad_id_list[npad_id_list.size() - 2]) {
// These are controllers without led patterns
@@ -659,25 +629,24 @@ void Controller_NPad::ClearAllConnectedControllers() {
}
void Controller_NPad::DisconnectAllConnectedControllers() {
- std::for_each(connected_controllers.begin(), connected_controllers.end(),
- [](ControllerHolder& controller) { controller.is_connected = false; });
+ for (ControllerHolder& controller : connected_controllers) {
+ controller.is_connected = false;
+ }
}
void Controller_NPad::ConnectAllDisconnectedControllers() {
- std::for_each(connected_controllers.begin(), connected_controllers.end(),
- [](ControllerHolder& controller) {
- if (controller.type != NPadControllerType::None && !controller.is_connected) {
- controller.is_connected = false;
- }
- });
+ for (ControllerHolder& controller : connected_controllers) {
+ if (controller.type != NPadControllerType::None && !controller.is_connected) {
+ controller.is_connected = true;
+ }
+ }
}
void Controller_NPad::ClearAllControllers() {
- std::for_each(connected_controllers.begin(), connected_controllers.end(),
- [](ControllerHolder& controller) {
- controller.type = NPadControllerType::None;
- controller.is_connected = false;
- });
+ for (ControllerHolder& controller : connected_controllers) {
+ controller.type = NPadControllerType::None;
+ controller.is_connected = false;
+ }
}
u32 Controller_NPad::GetAndResetPressState() {
@@ -685,10 +654,10 @@ u32 Controller_NPad::GetAndResetPressState() {
}
bool Controller_NPad::IsControllerSupported(NPadControllerType controller) const {
- const bool support_handheld =
- std::find(supported_npad_id_types.begin(), supported_npad_id_types.end(), NPAD_HANDHELD) !=
- supported_npad_id_types.end();
if (controller == NPadControllerType::Handheld) {
+ const bool support_handheld =
+ std::find(supported_npad_id_types.begin(), supported_npad_id_types.end(),
+ NPAD_HANDHELD) != supported_npad_id_types.end();
// Handheld is not even a supported type, lets stop here
if (!support_handheld) {
return false;
@@ -700,6 +669,7 @@ bool Controller_NPad::IsControllerSupported(NPadControllerType controller) const
return true;
}
+
if (std::any_of(supported_npad_id_types.begin(), supported_npad_id_types.end(),
[](u32 npad_id) { return npad_id <= MAX_NPAD_ID; })) {
switch (controller) {
@@ -717,6 +687,7 @@ bool Controller_NPad::IsControllerSupported(NPadControllerType controller) const
return false;
}
}
+
return false;
}
@@ -795,6 +766,7 @@ Controller_NPad::NPadControllerType Controller_NPad::DecideBestController(
priority_list.push_back(NPadControllerType::JoyLeft);
priority_list.push_back(NPadControllerType::JoyRight);
priority_list.push_back(NPadControllerType::JoyDual);
+ break;
}
const auto iter = std::find_if(priority_list.begin(), priority_list.end(),
diff --git a/src/core/hle/service/hid/controllers/npad.h b/src/core/hle/service/hid/controllers/npad.h
index 1bc3d55d6..16c4caa1f 100644
--- a/src/core/hle/service/hid/controllers/npad.h
+++ b/src/core/hle/service/hid/controllers/npad.h
@@ -301,6 +301,11 @@ private:
bool is_connected;
};
+ void InitNewlyAddedControler(std::size_t controller_idx);
+ bool IsControllerSupported(NPadControllerType controller) const;
+ NPadControllerType DecideBestController(NPadControllerType priority) const;
+ void RequestPadStateUpdate(u32 npad_id);
+
u32 press_state{};
NPadType style{};
@@ -321,12 +326,7 @@ private:
std::array<ControllerHolder, 10> connected_controllers{};
bool can_controllers_vibrate{true};
- void InitNewlyAddedControler(std::size_t controller_idx);
- bool IsControllerSupported(NPadControllerType controller) const;
- NPadControllerType DecideBestController(NPadControllerType priority) const;
- void RequestPadStateUpdate(u32 npad_id);
std::array<ControllerPad, 10> npad_pad_states{};
- bool IsControllerSupported(NPadControllerType controller);
bool is_in_lr_assignment_mode{false};
Core::System& system;
};
diff --git a/src/core/hle/service/hid/hid.cpp b/src/core/hle/service/hid/hid.cpp
index 9ab8b930e..ecc130f6c 100644
--- a/src/core/hle/service/hid/hid.cpp
+++ b/src/core/hle/service/hid/hid.cpp
@@ -195,7 +195,7 @@ Hid::Hid(Core::System& system) : ServiceFramework("hid"), system(system) {
{101, &Hid::GetSupportedNpadStyleSet, "GetSupportedNpadStyleSet"},
{102, &Hid::SetSupportedNpadIdType, "SetSupportedNpadIdType"},
{103, &Hid::ActivateNpad, "ActivateNpad"},
- {104, nullptr, "DeactivateNpad"},
+ {104, &Hid::DeactivateNpad, "DeactivateNpad"},
{106, &Hid::AcquireNpadStyleSetUpdateEventHandle, "AcquireNpadStyleSetUpdateEventHandle"},
{107, &Hid::DisconnectNpad, "DisconnectNpad"},
{108, &Hid::GetPlayerLedPattern, "GetPlayerLedPattern"},
@@ -470,6 +470,17 @@ void Hid::ActivateNpad(Kernel::HLERequestContext& ctx) {
applet_resource->ActivateController(HidController::NPad);
}
+void Hid::DeactivateNpad(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
+
+ LOG_DEBUG(Service_HID, "called, applet_resource_user_id={}", applet_resource_user_id);
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+ applet_resource->DeactivateController(HidController::NPad);
+}
+
void Hid::AcquireNpadStyleSetUpdateEventHandle(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const auto npad_id{rp.Pop<u32>()};
diff --git a/src/core/hle/service/hid/hid.h b/src/core/hle/service/hid/hid.h
index 10abd10ed..f08e036a3 100644
--- a/src/core/hle/service/hid/hid.h
+++ b/src/core/hle/service/hid/hid.h
@@ -99,6 +99,7 @@ private:
void GetSupportedNpadStyleSet(Kernel::HLERequestContext& ctx);
void SetSupportedNpadIdType(Kernel::HLERequestContext& ctx);
void ActivateNpad(Kernel::HLERequestContext& ctx);
+ void DeactivateNpad(Kernel::HLERequestContext& ctx);
void AcquireNpadStyleSetUpdateEventHandle(Kernel::HLERequestContext& ctx);
void DisconnectNpad(Kernel::HLERequestContext& ctx);
void GetPlayerLedPattern(Kernel::HLERequestContext& ctx);
diff --git a/src/core/hle/service/lm/lm.cpp b/src/core/hle/service/lm/lm.cpp
index 2a61593e2..435f2d286 100644
--- a/src/core/hle/service/lm/lm.cpp
+++ b/src/core/hle/service/lm/lm.cpp
@@ -6,8 +6,10 @@
#include <string>
#include "common/logging/log.h"
+#include "common/scope_exit.h"
#include "core/hle/ipc_helpers.h"
#include "core/hle/service/lm/lm.h"
+#include "core/hle/service/lm/manager.h"
#include "core/hle/service/service.h"
#include "core/memory.h"
@@ -15,65 +17,16 @@ namespace Service::LM {
class ILogger final : public ServiceFramework<ILogger> {
public:
- ILogger() : ServiceFramework("ILogger") {
+ ILogger(Manager& manager) : ServiceFramework("ILogger"), manager(manager) {
static const FunctionInfo functions[] = {
- {0x00000000, &ILogger::Initialize, "Initialize"},
- {0x00000001, &ILogger::SetDestination, "SetDestination"},
+ {0, &ILogger::Log, "Log"},
+ {1, &ILogger::SetDestination, "SetDestination"},
};
RegisterHandlers(functions);
}
private:
- struct MessageHeader {
- enum Flags : u32_le {
- IsHead = 1,
- IsTail = 2,
- };
- enum Severity : u32_le {
- Trace,
- Info,
- Warning,
- Error,
- Critical,
- };
-
- u64_le pid;
- u64_le threadContext;
- union {
- BitField<0, 16, Flags> flags;
- BitField<16, 8, Severity> severity;
- BitField<24, 8, u32> verbosity;
- };
- u32_le payload_size;
-
- bool IsHeadLog() const {
- return flags & Flags::IsHead;
- }
- bool IsTailLog() const {
- return flags & Flags::IsTail;
- }
- };
- static_assert(sizeof(MessageHeader) == 0x18, "MessageHeader is incorrect size");
-
- /// Log field type
- enum class Field : u8 {
- Skip = 1,
- Message = 2,
- Line = 3,
- Filename = 4,
- Function = 5,
- Module = 6,
- Thread = 7,
- };
-
- /**
- * ILogger::Initialize service function
- * Inputs:
- * 0: 0x00000000
- * Outputs:
- * 0: ResultCode
- */
- void Initialize(Kernel::HLERequestContext& ctx) {
+ void Log(Kernel::HLERequestContext& ctx) {
// This function only succeeds - Get that out of the way
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
@@ -85,140 +38,70 @@ private:
Memory::ReadBlock(addr, &header, sizeof(MessageHeader));
addr += sizeof(MessageHeader);
- if (header.IsHeadLog()) {
- log_stream.str("");
- log_stream.clear();
- }
-
- // Parse out log metadata
- u32 line{};
- std::string module;
- std::string message;
- std::string filename;
- std::string function;
- std::string thread;
+ FieldMap fields;
while (addr < end_addr) {
- const Field field{static_cast<Field>(Memory::Read8(addr++))};
- const std::size_t length{Memory::Read8(addr++)};
+ const auto field = static_cast<Field>(Memory::Read8(addr++));
+ const auto length = Memory::Read8(addr++);
if (static_cast<Field>(Memory::Read8(addr)) == Field::Skip) {
++addr;
}
- switch (field) {
- case Field::Skip:
- break;
- case Field::Message:
- message = Memory::ReadCString(addr, length);
- break;
- case Field::Line:
- line = Memory::Read32(addr);
- break;
- case Field::Filename:
- filename = Memory::ReadCString(addr, length);
- break;
- case Field::Function:
- function = Memory::ReadCString(addr, length);
- break;
- case Field::Module:
- module = Memory::ReadCString(addr, length);
- break;
- case Field::Thread:
- thread = Memory::ReadCString(addr, length);
- break;
- }
+ SCOPE_EXIT({ addr += length; });
- addr += length;
- }
+ if (field == Field::Skip) {
+ continue;
+ }
- // Empty log - nothing to do here
- if (log_stream.str().empty() && message.empty()) {
- return;
+ std::vector<u8> data(length);
+ Memory::ReadBlock(addr, data.data(), length);
+ fields.emplace(field, std::move(data));
}
- // Format a nicely printable string out of the log metadata
- if (!filename.empty()) {
- log_stream << filename << ':';
- }
- if (!module.empty()) {
- log_stream << module << ':';
- }
- if (!function.empty()) {
- log_stream << function << ':';
- }
- if (line) {
- log_stream << std::to_string(line) << ':';
- }
- if (!thread.empty()) {
- log_stream << thread << ':';
- }
- if (log_stream.str().length() > 0 && log_stream.str().back() == ':') {
- log_stream << ' ';
- }
- log_stream << message;
-
- if (header.IsTailLog()) {
- switch (header.severity) {
- case MessageHeader::Severity::Trace:
- LOG_DEBUG(Debug_Emulated, "{}", log_stream.str());
- break;
- case MessageHeader::Severity::Info:
- LOG_INFO(Debug_Emulated, "{}", log_stream.str());
- break;
- case MessageHeader::Severity::Warning:
- LOG_WARNING(Debug_Emulated, "{}", log_stream.str());
- break;
- case MessageHeader::Severity::Error:
- LOG_ERROR(Debug_Emulated, "{}", log_stream.str());
- break;
- case MessageHeader::Severity::Critical:
- LOG_CRITICAL(Debug_Emulated, "{}", log_stream.str());
- break;
- }
- }
+ manager.Log({header, std::move(fields)});
}
- // This service function is intended to be used as a way to
- // redirect logging output to different destinations, however,
- // given we always want to see the logging output, it's sufficient
- // to do nothing and return success here.
void SetDestination(Kernel::HLERequestContext& ctx) {
- LOG_DEBUG(Service_LM, "called");
+ IPC::RequestParser rp{ctx};
+ const auto destination = rp.PopEnum<DestinationFlag>();
+
+ LOG_DEBUG(Service_LM, "called, destination={:08X}", static_cast<u32>(destination));
+
+ manager.SetDestination(destination);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
- std::ostringstream log_stream;
+ Manager& manager;
};
class LM final : public ServiceFramework<LM> {
public:
- explicit LM() : ServiceFramework{"lm"} {
+ explicit LM(Manager& manager) : ServiceFramework{"lm"}, manager(manager) {
+ // clang-format off
static const FunctionInfo functions[] = {
- {0x00000000, &LM::OpenLogger, "OpenLogger"},
+ {0, &LM::OpenLogger, "OpenLogger"},
};
+ // clang-format on
+
RegisterHandlers(functions);
}
- /**
- * LM::OpenLogger service function
- * Inputs:
- * 0: 0x00000000
- * Outputs:
- * 0: ResultCode
- */
+private:
void OpenLogger(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_LM, "called");
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushIpcInterface<ILogger>();
+ rb.PushIpcInterface<ILogger>(manager);
}
+
+ Manager& manager;
};
-void InstallInterfaces(SM::ServiceManager& service_manager) {
- std::make_shared<LM>()->InstallAsService(service_manager);
+void InstallInterfaces(Core::System& system) {
+ std::make_shared<LM>(system.GetLogManager())->InstallAsService(system.ServiceManager());
}
} // namespace Service::LM
diff --git a/src/core/hle/service/lm/lm.h b/src/core/hle/service/lm/lm.h
index 7806ae27b..d40410b5c 100644
--- a/src/core/hle/service/lm/lm.h
+++ b/src/core/hle/service/lm/lm.h
@@ -4,13 +4,13 @@
#pragma once
-namespace Service::SM {
-class ServiceManager;
+namespace Core {
+class System;
}
namespace Service::LM {
/// Registers all LM services with the specified service manager.
-void InstallInterfaces(SM::ServiceManager& service_manager);
+void InstallInterfaces(Core::System& system);
} // namespace Service::LM
diff --git a/src/core/hle/service/lm/manager.cpp b/src/core/hle/service/lm/manager.cpp
new file mode 100644
index 000000000..b67081b86
--- /dev/null
+++ b/src/core/hle/service/lm/manager.cpp
@@ -0,0 +1,133 @@
+// Copyright 2019 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/logging/log.h"
+#include "common/string_util.h"
+#include "core/hle/service/lm/manager.h"
+#include "core/reporter.h"
+
+namespace Service::LM {
+
+std::ostream& operator<<(std::ostream& os, DestinationFlag dest) {
+ std::vector<std::string> array;
+ const auto check_single_flag = [dest, &array](DestinationFlag check, std::string name) {
+ if ((static_cast<u32>(check) & static_cast<u32>(dest)) != 0) {
+ array.emplace_back(std::move(name));
+ }
+ };
+
+ check_single_flag(DestinationFlag::Default, "Default");
+ check_single_flag(DestinationFlag::UART, "UART");
+ check_single_flag(DestinationFlag::UARTSleeping, "UART (Sleeping)");
+
+ os << "[";
+ for (const auto& entry : array) {
+ os << entry << ", ";
+ }
+ return os << "]";
+}
+
+std::ostream& operator<<(std::ostream& os, MessageHeader::Severity severity) {
+ switch (severity) {
+ case MessageHeader::Severity::Trace:
+ return os << "Trace";
+ case MessageHeader::Severity::Info:
+ return os << "Info";
+ case MessageHeader::Severity::Warning:
+ return os << "Warning";
+ case MessageHeader::Severity::Error:
+ return os << "Error";
+ case MessageHeader::Severity::Critical:
+ return os << "Critical";
+ default:
+ return os << fmt::format("{:08X}", static_cast<u32>(severity));
+ }
+}
+
+std::ostream& operator<<(std::ostream& os, Field field) {
+ switch (field) {
+ case Field::Skip:
+ return os << "Skip";
+ case Field::Message:
+ return os << "Message";
+ case Field::Line:
+ return os << "Line";
+ case Field::Filename:
+ return os << "Filename";
+ case Field::Function:
+ return os << "Function";
+ case Field::Module:
+ return os << "Module";
+ case Field::Thread:
+ return os << "Thread";
+ default:
+ return os << fmt::format("{:08X}", static_cast<u32>(field));
+ }
+}
+
+std::string FormatField(Field type, const std::vector<u8>& data) {
+ switch (type) {
+ case Field::Skip:
+ return "";
+ case Field::Line:
+ if (data.size() >= sizeof(u32)) {
+ u32 line;
+ std::memcpy(&line, data.data(), sizeof(u32));
+ return fmt::format("{}", line);
+ }
+ return "[ERROR DECODING LINE NUMBER]";
+ case Field::Message:
+ case Field::Filename:
+ case Field::Function:
+ case Field::Module:
+ case Field::Thread:
+ return Common::StringFromFixedZeroTerminatedBuffer(
+ reinterpret_cast<const char*>(data.data()), data.size());
+ default:
+ UNIMPLEMENTED();
+ }
+}
+
+Manager::Manager(Core::Reporter& reporter) : reporter(reporter) {}
+
+Manager::~Manager() = default;
+
+void Manager::SetEnabled(bool enabled) {
+ this->enabled = enabled;
+}
+
+void Manager::SetDestination(DestinationFlag destination) {
+ this->destination = destination;
+}
+
+void Manager::Log(LogMessage message) {
+ if (message.header.IsHeadLog()) {
+ InitializeLog();
+ }
+
+ current_log.emplace_back(std::move(message));
+
+ if (current_log.back().header.IsTailLog()) {
+ FinalizeLog();
+ }
+}
+
+void Manager::Flush() {
+ FinalizeLog();
+}
+
+void Manager::InitializeLog() {
+ current_log.clear();
+
+ LOG_INFO(Service_LM, "Initialized new log session");
+}
+
+void Manager::FinalizeLog() {
+ reporter.SaveLogReport(static_cast<u32>(destination), std::move(current_log));
+
+ LOG_INFO(Service_LM, "Finalized current log session");
+}
+
+} // namespace Service::LM
diff --git a/src/core/hle/service/lm/manager.h b/src/core/hle/service/lm/manager.h
new file mode 100644
index 000000000..544e636ba
--- /dev/null
+++ b/src/core/hle/service/lm/manager.h
@@ -0,0 +1,106 @@
+// Copyright 2019 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <map>
+#include <ostream>
+#include <vector>
+#include "common/bit_field.h"
+#include "common/common_types.h"
+#include "common/swap.h"
+
+namespace Core {
+class Reporter;
+}
+
+namespace Service::LM {
+
+enum class DestinationFlag : u32 {
+ Default = 1,
+ UART = 2,
+ UARTSleeping = 4,
+
+ All = 0xFFFF,
+};
+
+struct MessageHeader {
+ enum Flags : u32_le {
+ IsHead = 1,
+ IsTail = 2,
+ };
+ enum Severity : u32_le {
+ Trace,
+ Info,
+ Warning,
+ Error,
+ Critical,
+ };
+
+ u64_le pid;
+ u64_le thread_context;
+ union {
+ BitField<0, 16, Flags> flags;
+ BitField<16, 8, Severity> severity;
+ BitField<24, 8, u32> verbosity;
+ };
+ u32_le payload_size;
+
+ bool IsHeadLog() const {
+ return flags & IsHead;
+ }
+ bool IsTailLog() const {
+ return flags & IsTail;
+ }
+};
+static_assert(sizeof(MessageHeader) == 0x18, "MessageHeader is incorrect size");
+
+enum class Field : u8 {
+ Skip = 1,
+ Message = 2,
+ Line = 3,
+ Filename = 4,
+ Function = 5,
+ Module = 6,
+ Thread = 7,
+};
+
+std::ostream& operator<<(std::ostream& os, DestinationFlag dest);
+std::ostream& operator<<(std::ostream& os, MessageHeader::Severity severity);
+std::ostream& operator<<(std::ostream& os, Field field);
+
+using FieldMap = std::map<Field, std::vector<u8>>;
+
+struct LogMessage {
+ MessageHeader header;
+ FieldMap fields;
+};
+
+std::string FormatField(Field type, const std::vector<u8>& data);
+
+class Manager {
+public:
+ explicit Manager(Core::Reporter& reporter);
+ ~Manager();
+
+ void SetEnabled(bool enabled);
+ void SetDestination(DestinationFlag destination);
+
+ void Log(LogMessage message);
+
+ void Flush();
+
+private:
+ void InitializeLog();
+ void FinalizeLog();
+
+ bool enabled = true;
+ DestinationFlag destination = DestinationFlag::All;
+
+ std::vector<LogMessage> current_log;
+
+ Core::Reporter& reporter;
+};
+
+} // namespace Service::LM
diff --git a/src/core/hle/service/ns/pl_u.cpp b/src/core/hle/service/ns/pl_u.cpp
index f64535237..23477315f 100644
--- a/src/core/hle/service/ns/pl_u.cpp
+++ b/src/core/hle/service/ns/pl_u.cpp
@@ -6,13 +6,6 @@
#include <cstring>
#include <vector>
-#include <FontChineseSimplified.h>
-#include <FontChineseTraditional.h>
-#include <FontExtendedChineseSimplified.h>
-#include <FontKorean.h>
-#include <FontNintendoExtended.h>
-#include <FontStandard.h>
-
#include "common/assert.h"
#include "common/common_paths.h"
#include "common/common_types.h"
@@ -24,7 +17,9 @@
#include "core/file_sys/nca_metadata.h"
#include "core/file_sys/registered_cache.h"
#include "core/file_sys/romfs.h"
+#include "core/file_sys/system_archive/system_archive.h"
#include "core/hle/ipc_helpers.h"
+#include "core/hle/kernel/physical_memory.h"
#include "core/hle/kernel/shared_memory.h"
#include "core/hle/service/filesystem/filesystem.h"
#include "core/hle/service/ns/pl_u.h"
@@ -94,15 +89,20 @@ static void DecryptSharedFont(const std::vector<u32>& input, Kernel::PhysicalMem
offset += transformed_font.size() * sizeof(u32);
}
-static void EncryptSharedFont(const std::vector<u8>& input, Kernel::PhysicalMemory& output,
- std::size_t& offset) {
- ASSERT_MSG(offset + input.size() + 8 < SHARED_FONT_MEM_SIZE, "Shared fonts exceeds 17mb!");
- const u32 KEY = EXPECTED_MAGIC ^ EXPECTED_RESULT;
- std::memcpy(output.data() + offset, &EXPECTED_RESULT, sizeof(u32)); // Magic header
- const u32 ENC_SIZE = static_cast<u32>(input.size()) ^ KEY;
- std::memcpy(output.data() + offset + sizeof(u32), &ENC_SIZE, sizeof(u32));
- std::memcpy(output.data() + offset + (sizeof(u32) * 2), input.data(), input.size());
- offset += input.size() + (sizeof(u32) * 2);
+void EncryptSharedFont(const std::vector<u32>& input, std::vector<u8>& output,
+ std::size_t& offset) {
+ ASSERT_MSG(offset + (input.size() * sizeof(u32)) < SHARED_FONT_MEM_SIZE,
+ "Shared fonts exceeds 17mb!");
+
+ const auto key = Common::swap32(EXPECTED_RESULT ^ EXPECTED_MAGIC);
+ std::vector<u32> transformed_font(input.size() + 2);
+ transformed_font[0] = Common::swap32(EXPECTED_MAGIC);
+ transformed_font[1] = Common::swap32(input.size() * sizeof(u32)) ^ key;
+ std::transform(input.begin(), input.end(), transformed_font.begin() + 2,
+ [key](u32 in) { return in ^ key; });
+ std::memcpy(output.data() + offset, transformed_font.data(),
+ transformed_font.size() * sizeof(u32));
+ offset += transformed_font.size() * sizeof(u32);
}
// Helper function to make BuildSharedFontsRawRegions a bit nicer
@@ -168,114 +168,49 @@ PL_U::PL_U(Core::System& system)
// Attempt to load shared font data from disk
const auto* nand = fsc.GetSystemNANDContents();
std::size_t offset = 0;
- // Rebuild shared fonts from data ncas
- if (nand->HasEntry(static_cast<u64>(FontArchives::Standard),
- FileSys::ContentRecordType::Data)) {
- impl->shared_font = std::make_shared<Kernel::PhysicalMemory>(SHARED_FONT_MEM_SIZE);
- for (auto font : SHARED_FONTS) {
- const auto nca =
- nand->GetEntry(static_cast<u64>(font.first), FileSys::ContentRecordType::Data);
- if (!nca) {
- LOG_ERROR(Service_NS, "Failed to find {:016X}! Skipping",
- static_cast<u64>(font.first));
- continue;
- }
- const auto romfs = nca->GetRomFS();
- if (!romfs) {
- LOG_ERROR(Service_NS, "{:016X} has no RomFS! Skipping",
- static_cast<u64>(font.first));
- continue;
- }
- const auto extracted_romfs = FileSys::ExtractRomFS(romfs);
- if (!extracted_romfs) {
- LOG_ERROR(Service_NS, "Failed to extract RomFS for {:016X}! Skipping",
- static_cast<u64>(font.first));
- continue;
- }
- const auto font_fp = extracted_romfs->GetFile(font.second);
- if (!font_fp) {
- LOG_ERROR(Service_NS, "{:016X} has no file \"{}\"! Skipping",
- static_cast<u64>(font.first), font.second);
- continue;
- }
- std::vector<u32> font_data_u32(font_fp->GetSize() / sizeof(u32));
- font_fp->ReadBytes<u32>(font_data_u32.data(), font_fp->GetSize());
- // We need to be BigEndian as u32s for the xor encryption
- std::transform(font_data_u32.begin(), font_data_u32.end(), font_data_u32.begin(),
- Common::swap32);
- FontRegion region{
- static_cast<u32>(offset + 8),
- static_cast<u32>((font_data_u32.size() * sizeof(u32)) -
- 8)}; // Font offset and size do not account for the header
- DecryptSharedFont(font_data_u32, *impl->shared_font, offset);
- impl->shared_font_regions.push_back(region);
+ // Rebuild shared fonts from data ncas or synthesize
+
+ impl->shared_font = std::make_shared<Kernel::PhysicalMemory>(SHARED_FONT_MEM_SIZE);
+ for (auto font : SHARED_FONTS) {
+ FileSys::VirtualFile romfs;
+ const auto nca =
+ nand->GetEntry(static_cast<u64>(font.first), FileSys::ContentRecordType::Data);
+ if (nca) {
+ romfs = nca->GetRomFS();
}
- } else {
- impl->shared_font = std::make_shared<Kernel::PhysicalMemory>(
- SHARED_FONT_MEM_SIZE); // Shared memory needs to always be allocated and a fixed size
-
- const std::string user_path = FileUtil::GetUserPath(FileUtil::UserPath::SysDataDir);
- const std::string filepath{user_path + SHARED_FONT};
+ if (!romfs) {
+ romfs = FileSys::SystemArchive::SynthesizeSystemArchive(static_cast<u64>(font.first));
+ }
- // Create path if not already created
- if (!FileUtil::CreateFullPath(filepath)) {
- LOG_ERROR(Service_NS, "Failed to create sharedfonts path \"{}\"!", filepath);
- return;
+ if (!romfs) {
+ LOG_ERROR(Service_NS, "Failed to find or synthesize {:016X}! Skipping",
+ static_cast<u64>(font.first));
+ continue;
}
- bool using_ttf = false;
- for (const char* font_ttf : SHARED_FONTS_TTF) {
- if (FileUtil::Exists(user_path + font_ttf)) {
- using_ttf = true;
- FileUtil::IOFile file(user_path + font_ttf, "rb");
- if (file.IsOpen()) {
- std::vector<u8> ttf_bytes(file.GetSize());
- file.ReadBytes<u8>(ttf_bytes.data(), ttf_bytes.size());
- FontRegion region{
- static_cast<u32>(offset + 8),
- static_cast<u32>(ttf_bytes.size())}; // Font offset and size do not account
- // for the header
- EncryptSharedFont(ttf_bytes, *impl->shared_font, offset);
- impl->shared_font_regions.push_back(region);
- } else {
- LOG_WARNING(Service_NS, "Unable to load font: {}", font_ttf);
- }
- } else if (using_ttf) {
- LOG_WARNING(Service_NS, "Unable to find font: {}", font_ttf);
- }
+ const auto extracted_romfs = FileSys::ExtractRomFS(romfs);
+ if (!extracted_romfs) {
+ LOG_ERROR(Service_NS, "Failed to extract RomFS for {:016X}! Skipping",
+ static_cast<u64>(font.first));
+ continue;
}
- if (using_ttf)
- return;
- FileUtil::IOFile file(filepath, "rb");
-
- if (file.IsOpen()) {
- // Read shared font data
- ASSERT(file.GetSize() == SHARED_FONT_MEM_SIZE);
- file.ReadBytes(impl->shared_font->data(), impl->shared_font->size());
- impl->BuildSharedFontsRawRegions(*impl->shared_font);
- } else {
- LOG_WARNING(Service_NS,
- "Shared Font file missing. Loading open source replacement from memory");
-
- // clang-format off
- const std::vector<std::vector<u8>> open_source_shared_fonts_ttf = {
- {std::begin(FontChineseSimplified), std::end(FontChineseSimplified)},
- {std::begin(FontChineseTraditional), std::end(FontChineseTraditional)},
- {std::begin(FontExtendedChineseSimplified), std::end(FontExtendedChineseSimplified)},
- {std::begin(FontKorean), std::end(FontKorean)},
- {std::begin(FontNintendoExtended), std::end(FontNintendoExtended)},
- {std::begin(FontStandard), std::end(FontStandard)},
- };
- // clang-format on
-
- for (const std::vector<u8>& font_ttf : open_source_shared_fonts_ttf) {
- const FontRegion region{static_cast<u32>(offset + 8),
- static_cast<u32>(font_ttf.size())};
- EncryptSharedFont(font_ttf, *impl->shared_font, offset);
- impl->shared_font_regions.push_back(region);
- }
+ const auto font_fp = extracted_romfs->GetFile(font.second);
+ if (!font_fp) {
+ LOG_ERROR(Service_NS, "{:016X} has no file \"{}\"! Skipping",
+ static_cast<u64>(font.first), font.second);
+ continue;
}
+ std::vector<u32> font_data_u32(font_fp->GetSize() / sizeof(u32));
+ font_fp->ReadBytes<u32>(font_data_u32.data(), font_fp->GetSize());
+ // We need to be BigEndian as u32s for the xor encryption
+ std::transform(font_data_u32.begin(), font_data_u32.end(), font_data_u32.begin(),
+ Common::swap32);
+ // Font offset and size do not account for the header
+ const FontRegion region{static_cast<u32>(offset + 8),
+ static_cast<u32>((font_data_u32.size() * sizeof(u32)) - 8)};
+ DecryptSharedFont(font_data_u32, *impl->shared_font, offset);
+ impl->shared_font_regions.push_back(region);
}
}
diff --git a/src/core/hle/service/ns/pl_u.h b/src/core/hle/service/ns/pl_u.h
index 1063f4204..27161bd7a 100644
--- a/src/core/hle/service/ns/pl_u.h
+++ b/src/core/hle/service/ns/pl_u.h
@@ -5,6 +5,7 @@
#pragma once
#include <memory>
+#include <vector>
#include "core/hle/service/service.h"
namespace Service {
@@ -15,6 +16,8 @@ class FileSystemController;
namespace NS {
+void EncryptSharedFont(const std::vector<u32>& input, std::vector<u8>& output, std::size_t& offset);
+
class PL_U final : public ServiceFramework<PL_U> {
public:
explicit PL_U(Core::System& system);
diff --git a/src/core/hle/service/nvdrv/devices/nvdisp_disp0.cpp b/src/core/hle/service/nvdrv/devices/nvdisp_disp0.cpp
index f764388bc..3f7b8e670 100644
--- a/src/core/hle/service/nvdrv/devices/nvdisp_disp0.cpp
+++ b/src/core/hle/service/nvdrv/devices/nvdisp_disp0.cpp
@@ -5,6 +5,7 @@
#include "common/assert.h"
#include "common/logging/log.h"
#include "core/core.h"
+#include "core/core_timing.h"
#include "core/hle/service/nvdrv/devices/nvdisp_disp0.h"
#include "core/hle/service/nvdrv/devices/nvmap.h"
#include "core/perf_stats.h"
@@ -38,7 +39,10 @@ void nvdisp_disp0::flip(u32 buffer_handle, u32 offset, u32 format, u32 width, u3
transform, crop_rect};
system.GetPerfStats().EndGameFrame();
+ system.GetPerfStats().EndSystemFrame();
system.GPU().SwapBuffers(&framebuffer);
+ system.FrameLimiter().DoFrameLimiting(system.CoreTiming().GetGlobalTimeUs());
+ system.GetPerfStats().BeginSystemFrame();
}
} // namespace Service::Nvidia::Devices
diff --git a/src/core/hle/service/nvdrv/devices/nvhost_ctrl.cpp b/src/core/hle/service/nvdrv/devices/nvhost_ctrl.cpp
index eb88fee1b..b27ee0502 100644
--- a/src/core/hle/service/nvdrv/devices/nvhost_ctrl.cpp
+++ b/src/core/hle/service/nvdrv/devices/nvhost_ctrl.cpp
@@ -63,16 +63,26 @@ u32 nvhost_ctrl::IocCtrlEventWait(const std::vector<u8>& input, std::vector<u8>&
return NvResult::BadParameter;
}
+ u32 event_id = params.value & 0x00FF;
+
+ if (event_id >= MaxNvEvents) {
+ std::memcpy(output.data(), &params, sizeof(params));
+ return NvResult::BadParameter;
+ }
+
+ auto event = events_interface.events[event_id];
auto& gpu = system.GPU();
// This is mostly to take into account unimplemented features. As synced
// gpu is always synced.
if (!gpu.IsAsync()) {
+ event.writable->Signal();
return NvResult::Success;
}
auto lock = gpu.LockSync();
const u32 current_syncpoint_value = gpu.GetSyncpointValue(params.syncpt_id);
const s32 diff = current_syncpoint_value - params.threshold;
if (diff >= 0) {
+ event.writable->Signal();
params.value = current_syncpoint_value;
std::memcpy(output.data(), &params, sizeof(params));
return NvResult::Success;
@@ -88,27 +98,6 @@ u32 nvhost_ctrl::IocCtrlEventWait(const std::vector<u8>& input, std::vector<u8>&
return NvResult::Timeout;
}
- u32 event_id;
- if (is_async) {
- event_id = params.value & 0x00FF;
- if (event_id >= MaxNvEvents) {
- std::memcpy(output.data(), &params, sizeof(params));
- return NvResult::BadParameter;
- }
- } else {
- if (ctrl.fresh_call) {
- const auto result = events_interface.GetFreeEvent();
- if (result) {
- event_id = *result;
- } else {
- LOG_CRITICAL(Service_NVDRV, "No Free Events available!");
- event_id = params.value & 0x00FF;
- }
- } else {
- event_id = ctrl.event_id;
- }
- }
-
EventState status = events_interface.status[event_id];
if (event_id < MaxNvEvents || status == EventState::Free || status == EventState::Registered) {
events_interface.SetEventStatus(event_id, EventState::Waiting);
@@ -120,7 +109,7 @@ u32 nvhost_ctrl::IocCtrlEventWait(const std::vector<u8>& input, std::vector<u8>&
params.value = ((params.syncpt_id & 0xfff) << 16) | 0x10000000;
}
params.value |= event_id;
- events_interface.events[event_id].writable->Clear();
+ event.writable->Clear();
gpu.RegisterSyncptInterrupt(params.syncpt_id, target_value);
if (!is_async && ctrl.fresh_call) {
ctrl.must_delay = true;
diff --git a/src/core/hle/service/nvdrv/interface.cpp b/src/core/hle/service/nvdrv/interface.cpp
index 5e0c23602..68d139cfb 100644
--- a/src/core/hle/service/nvdrv/interface.cpp
+++ b/src/core/hle/service/nvdrv/interface.cpp
@@ -134,7 +134,9 @@ void NVDRV::QueryEvent(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 3, 1};
rb.Push(RESULT_SUCCESS);
if (event_id < MaxNvEvents) {
- rb.PushCopyObjects(nvdrv->GetEvent(event_id));
+ auto event = nvdrv->GetEvent(event_id);
+ event->Clear();
+ rb.PushCopyObjects(event);
rb.Push<u32>(NvResult::Success);
} else {
rb.Push<u32>(0);
diff --git a/src/core/hle/service/nvdrv/nvdrv.cpp b/src/core/hle/service/nvdrv/nvdrv.cpp
index 307a7e928..7bfb99e34 100644
--- a/src/core/hle/service/nvdrv/nvdrv.cpp
+++ b/src/core/hle/service/nvdrv/nvdrv.cpp
@@ -40,8 +40,8 @@ Module::Module(Core::System& system) {
auto& kernel = system.Kernel();
for (u32 i = 0; i < MaxNvEvents; i++) {
std::string event_label = fmt::format("NVDRV::NvEvent_{}", i);
- events_interface.events[i] = Kernel::WritableEvent::CreateEventPair(
- kernel, Kernel::ResetType::Automatic, event_label);
+ events_interface.events[i] =
+ Kernel::WritableEvent::CreateEventPair(kernel, Kernel::ResetType::Manual, event_label);
events_interface.status[i] = EventState::Free;
events_interface.registered[i] = false;
}
diff --git a/src/core/hle/service/nvflinger/buffer_queue.cpp b/src/core/hle/service/nvflinger/buffer_queue.cpp
index e1a07d3ee..55b68eb0c 100644
--- a/src/core/hle/service/nvflinger/buffer_queue.cpp
+++ b/src/core/hle/service/nvflinger/buffer_queue.cpp
@@ -14,8 +14,8 @@
namespace Service::NVFlinger {
-BufferQueue::BufferQueue(u32 id, u64 layer_id) : id(id), layer_id(layer_id) {
- auto& kernel = Core::System::GetInstance().Kernel();
+BufferQueue::BufferQueue(Kernel::KernelCore& kernel, u32 id, u64 layer_id)
+ : id(id), layer_id(layer_id) {
buffer_wait_event = Kernel::WritableEvent::CreateEventPair(kernel, Kernel::ResetType::Manual,
"BufferQueue NativeHandle");
}
diff --git a/src/core/hle/service/nvflinger/buffer_queue.h b/src/core/hle/service/nvflinger/buffer_queue.h
index 356bedb81..8f9b18547 100644
--- a/src/core/hle/service/nvflinger/buffer_queue.h
+++ b/src/core/hle/service/nvflinger/buffer_queue.h
@@ -15,6 +15,10 @@
#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/nvdrv/nvdata.h"
+namespace Kernel {
+class KernelCore;
+}
+
namespace Service::NVFlinger {
struct IGBPBuffer {
@@ -44,7 +48,7 @@ public:
NativeWindowFormat = 2,
};
- BufferQueue(u32 id, u64 layer_id);
+ explicit BufferQueue(Kernel::KernelCore& kernel, u32 id, u64 layer_id);
~BufferQueue();
enum class BufferTransformFlags : u32 {
diff --git a/src/core/hle/service/nvflinger/nvflinger.cpp b/src/core/hle/service/nvflinger/nvflinger.cpp
index 2e4d707b9..cc9522aad 100644
--- a/src/core/hle/service/nvflinger/nvflinger.cpp
+++ b/src/core/hle/service/nvflinger/nvflinger.cpp
@@ -83,7 +83,7 @@ std::optional<u64> NVFlinger::CreateLayer(u64 display_id) {
const u64 layer_id = next_layer_id++;
const u32 buffer_queue_id = next_buffer_queue_id++;
- buffer_queues.emplace_back(buffer_queue_id, layer_id);
+ buffer_queues.emplace_back(system.Kernel(), buffer_queue_id, layer_id);
display->CreateLayer(layer_id, buffer_queues.back());
return layer_id;
}
@@ -187,14 +187,18 @@ void NVFlinger::Compose() {
MicroProfileFlip();
if (!buffer) {
- // There was no queued buffer to draw, render previous frame
- system.GetPerfStats().EndGameFrame();
- system.GPU().SwapBuffers({});
continue;
}
const auto& igbp_buffer = buffer->get().igbp_buffer;
+ const auto& gpu = system.GPU();
+ const auto& multi_fence = buffer->get().multi_fence;
+ for (u32 fence_id = 0; fence_id < multi_fence.num_fences; fence_id++) {
+ const auto& fence = multi_fence.fences[fence_id];
+ gpu.WaitFence(fence.id, fence.value);
+ }
+
// Now send the buffer to the GPU for drawing.
// TODO(Subv): Support more than just disp0. The display device selection is probably based
// on which display we're drawing (Default, Internal, External, etc)
diff --git a/src/core/hle/service/service.cpp b/src/core/hle/service/service.cpp
index f2c6fe9dc..7c5302017 100644
--- a/src/core/hle/service/service.cpp
+++ b/src/core/hle/service/service.cpp
@@ -226,7 +226,7 @@ void Init(std::shared_ptr<SM::ServiceManager>& sm, Core::System& system) {
LBL::InstallInterfaces(*sm);
LDN::InstallInterfaces(*sm);
LDR::InstallInterfaces(*sm, system);
- LM::InstallInterfaces(*sm);
+ LM::InstallInterfaces(system);
Migration::InstallInterfaces(*sm);
Mii::InstallInterfaces(*sm);
MM::InstallInterfaces(*sm);
diff --git a/src/core/hle/service/vi/vi.cpp b/src/core/hle/service/vi/vi.cpp
index 199b30635..611cecc20 100644
--- a/src/core/hle/service/vi/vi.cpp
+++ b/src/core/hle/service/vi/vi.cpp
@@ -45,7 +45,7 @@ struct DisplayInfo {
/// Whether or not the display has a limited number of layers.
u8 has_limited_layers{1};
- INSERT_PADDING_BYTES(7){};
+ INSERT_PADDING_BYTES(7);
/// Indicates the total amount of layers supported by the display.
/// @note This is only valid if has_limited_layers is set.