summaryrefslogtreecommitdiffstats
path: root/src/core/hle/kernel
diff options
context:
space:
mode:
Diffstat (limited to 'src/core/hle/kernel')
-rw-r--r--src/core/hle/kernel/address_arbiter.cpp33
-rw-r--r--src/core/hle/kernel/address_arbiter.h2
-rw-r--r--src/core/hle/kernel/event.cpp16
-rw-r--r--src/core/hle/kernel/kernel.cpp32
-rw-r--r--src/core/hle/kernel/kernel.h26
-rw-r--r--src/core/hle/kernel/mutex.cpp23
-rw-r--r--src/core/hle/kernel/semaphore.cpp10
-rw-r--r--src/core/hle/kernel/shared_memory.cpp4
-rw-r--r--src/core/hle/kernel/thread.cpp438
-rw-r--r--src/core/hle/kernel/thread.h115
-rw-r--r--src/core/hle/kernel/timer.cpp144
-rw-r--r--src/core/hle/kernel/timer.h47
12 files changed, 530 insertions, 360 deletions
diff --git a/src/core/hle/kernel/address_arbiter.cpp b/src/core/hle/kernel/address_arbiter.cpp
index 736bbc36a..b7434aaf2 100644
--- a/src/core/hle/kernel/address_arbiter.cpp
+++ b/src/core/hle/kernel/address_arbiter.cpp
@@ -29,35 +29,56 @@ public:
////////////////////////////////////////////////////////////////////////////////////////////////////
/// Arbitrate an address
-ResultCode ArbitrateAddress(Handle handle, ArbitrationType type, u32 address, s32 value) {
+ResultCode ArbitrateAddress(Handle handle, ArbitrationType type, u32 address, s32 value, u64 nanoseconds) {
+ Object* object = Kernel::g_handle_table.GetGeneric(handle).get();
+ if (object == nullptr)
+ return InvalidHandle(ErrorModule::Kernel);
+
switch (type) {
// Signal thread(s) waiting for arbitrate address...
case ArbitrationType::Signal:
// Negative value means resume all threads
if (value < 0) {
- ArbitrateAllThreads(handle, address);
+ ArbitrateAllThreads(object, address);
} else {
// Resume first N threads
for(int i = 0; i < value; i++)
- ArbitrateHighestPriorityThread(handle, address);
+ ArbitrateHighestPriorityThread(object, address);
}
break;
// Wait current thread (acquire the arbiter)...
case ArbitrationType::WaitIfLessThan:
if ((s32)Memory::Read32(address) <= value) {
- Kernel::WaitCurrentThread(WAITTYPE_ARB, handle, address);
+ Kernel::WaitCurrentThread(WAITTYPE_ARB, object, address);
+ HLE::Reschedule(__func__);
+ }
+ break;
+ case ArbitrationType::WaitIfLessThanWithTimeout:
+ if ((s32)Memory::Read32(address) <= value) {
+ Kernel::WaitCurrentThread(WAITTYPE_ARB, object, address);
+ Kernel::WakeThreadAfterDelay(GetCurrentThread(), nanoseconds);
HLE::Reschedule(__func__);
}
break;
-
case ArbitrationType::DecrementAndWaitIfLessThan:
{
s32 memory_value = Memory::Read32(address) - 1;
Memory::Write32(address, memory_value);
if (memory_value <= value) {
- Kernel::WaitCurrentThread(WAITTYPE_ARB, handle, address);
+ Kernel::WaitCurrentThread(WAITTYPE_ARB, object, address);
+ HLE::Reschedule(__func__);
+ }
+ break;
+ }
+ case ArbitrationType::DecrementAndWaitIfLessThanWithTimeout:
+ {
+ s32 memory_value = Memory::Read32(address) - 1;
+ Memory::Write32(address, memory_value);
+ if (memory_value <= value) {
+ Kernel::WaitCurrentThread(WAITTYPE_ARB, object, address);
+ Kernel::WakeThreadAfterDelay(GetCurrentThread(), nanoseconds);
HLE::Reschedule(__func__);
}
break;
diff --git a/src/core/hle/kernel/address_arbiter.h b/src/core/hle/kernel/address_arbiter.h
index 030e7ad7b..3ffd465a2 100644
--- a/src/core/hle/kernel/address_arbiter.h
+++ b/src/core/hle/kernel/address_arbiter.h
@@ -28,7 +28,7 @@ enum class ArbitrationType : u32 {
};
/// Arbitrate an address
-ResultCode ArbitrateAddress(Handle handle, ArbitrationType type, u32 address, s32 value);
+ResultCode ArbitrateAddress(Handle handle, ArbitrationType type, u32 address, s32 value, u64 nanoseconds);
/// Create an address arbiter
Handle CreateAddressArbiter(const std::string& name = "Unknown");
diff --git a/src/core/hle/kernel/event.cpp b/src/core/hle/kernel/event.cpp
index e43c3ee4e..271190dbe 100644
--- a/src/core/hle/kernel/event.cpp
+++ b/src/core/hle/kernel/event.cpp
@@ -33,11 +33,11 @@ public:
ResultVal<bool> WaitSynchronization() override {
bool wait = locked;
if (locked) {
- Handle thread = GetCurrentThreadHandle();
+ Handle thread = GetCurrentThread()->GetHandle();
if (std::find(waiting_threads.begin(), waiting_threads.end(), thread) == waiting_threads.end()) {
waiting_threads.push_back(thread);
}
- Kernel::WaitCurrentThread(WAITTYPE_EVENT, GetHandle());
+ Kernel::WaitCurrentThread(WAITTYPE_EVENT, this);
}
if (reset_type != RESETTYPE_STICKY && !permanent_locked) {
locked = true;
@@ -53,7 +53,7 @@ public:
* @return Result of operation, 0 on success, otherwise error code
*/
ResultCode SetPermanentLock(Handle handle, const bool permanent_locked) {
- Event* evt = g_handle_table.Get<Event>(handle);
+ Event* evt = g_handle_table.Get<Event>(handle).get();
if (evt == nullptr) return InvalidHandle(ErrorModule::Kernel);
evt->permanent_locked = permanent_locked;
@@ -67,7 +67,7 @@ ResultCode SetPermanentLock(Handle handle, const bool permanent_locked) {
* @return Result of operation, 0 on success, otherwise error code
*/
ResultCode SetEventLocked(const Handle handle, const bool locked) {
- Event* evt = g_handle_table.Get<Event>(handle);
+ Event* evt = g_handle_table.Get<Event>(handle).get();
if (evt == nullptr) return InvalidHandle(ErrorModule::Kernel);
if (!evt->permanent_locked) {
@@ -82,13 +82,15 @@ ResultCode SetEventLocked(const Handle handle, const bool locked) {
* @return Result of operation, 0 on success, otherwise error code
*/
ResultCode SignalEvent(const Handle handle) {
- Event* evt = g_handle_table.Get<Event>(handle);
+ Event* evt = g_handle_table.Get<Event>(handle).get();
if (evt == nullptr) return InvalidHandle(ErrorModule::Kernel);
// Resume threads waiting for event to signal
bool event_caught = false;
for (size_t i = 0; i < evt->waiting_threads.size(); ++i) {
- ResumeThreadFromWait( evt->waiting_threads[i]);
+ Thread* thread = Kernel::g_handle_table.Get<Thread>(evt->waiting_threads[i]).get();
+ if (thread != nullptr)
+ thread->ResumeFromWait();
// If any thread is signalled awake by this event, assume the event was "caught" and reset
// the event. This will result in the next thread waiting on the event to block. Otherwise,
@@ -110,7 +112,7 @@ ResultCode SignalEvent(const Handle handle) {
* @return Result of operation, 0 on success, otherwise error code
*/
ResultCode ClearEvent(Handle handle) {
- Event* evt = g_handle_table.Get<Event>(handle);
+ Event* evt = g_handle_table.Get<Event>(handle).get();
if (evt == nullptr) return InvalidHandle(ErrorModule::Kernel);
if (!evt->permanent_locked) {
diff --git a/src/core/hle/kernel/kernel.cpp b/src/core/hle/kernel/kernel.cpp
index ae2c11a1c..d3684896f 100644
--- a/src/core/hle/kernel/kernel.cpp
+++ b/src/core/hle/kernel/kernel.cpp
@@ -6,13 +6,15 @@
#include "common/common.h"
+#include "core/arm/arm_interface.h"
#include "core/core.h"
#include "core/hle/kernel/kernel.h"
#include "core/hle/kernel/thread.h"
+#include "core/hle/kernel/timer.h"
namespace Kernel {
-Handle g_main_thread = 0;
+SharedPtr<Thread> g_main_thread = nullptr;
HandleTable g_handle_table;
u64 g_program_id = 0;
@@ -21,7 +23,7 @@ HandleTable::HandleTable() {
Clear();
}
-ResultVal<Handle> HandleTable::Create(Object* obj) {
+ResultVal<Handle> HandleTable::Create(SharedPtr<Object> obj) {
_dbg_assert_(Kernel, obj != nullptr);
u16 slot = next_free_slot;
@@ -37,22 +39,23 @@ ResultVal<Handle> HandleTable::Create(Object* obj) {
// CTR-OS doesn't use generation 0, so skip straight to 1.
if (next_generation >= (1 << 15)) next_generation = 1;
+ Handle handle = generation | (slot << 15);
+ if (obj->handle == INVALID_HANDLE)
+ obj->handle = handle;
+
generations[slot] = generation;
- intrusive_ptr_add_ref(obj);
- objects[slot] = obj;
+ objects[slot] = std::move(obj);
- Handle handle = generation | (slot << 15);
- obj->handle = handle;
return MakeResult<Handle>(handle);
}
ResultVal<Handle> HandleTable::Duplicate(Handle handle) {
- Object* object = GetGeneric(handle);
+ SharedPtr<Object> object = GetGeneric(handle);
if (object == nullptr) {
LOG_ERROR(Kernel, "Tried to duplicate invalid handle: %08X", handle);
return ERR_INVALID_HANDLE;
}
- return Create(object);
+ return Create(std::move(object));
}
ResultCode HandleTable::Close(Handle handle) {
@@ -62,7 +65,6 @@ ResultCode HandleTable::Close(Handle handle) {
size_t slot = GetSlot(handle);
u16 generation = GetGeneration(handle);
- intrusive_ptr_release(objects[slot]);
objects[slot] = nullptr;
generations[generation] = next_free_slot;
@@ -77,10 +79,9 @@ bool HandleTable::IsValid(Handle handle) const {
return slot < MAX_COUNT && objects[slot] != nullptr && generations[slot] == generation;
}
-Object* HandleTable::GetGeneric(Handle handle) const {
+SharedPtr<Object> HandleTable::GetGeneric(Handle handle) const {
if (handle == CurrentThread) {
- // TODO(yuriks) Directly return the pointer once this is possible.
- handle = GetCurrentThreadHandle();
+ return GetCurrentThread();
} else if (handle == CurrentProcess) {
LOG_ERROR(Kernel, "Current process (%08X) pseudo-handle not supported", CurrentProcess);
return nullptr;
@@ -95,8 +96,6 @@ Object* HandleTable::GetGeneric(Handle handle) const {
void HandleTable::Clear() {
for (size_t i = 0; i < MAX_COUNT; ++i) {
generations[i] = i + 1;
- if (objects[i] != nullptr)
- intrusive_ptr_release(objects[i]);
objects[i] = nullptr;
}
next_free_slot = 0;
@@ -105,12 +104,13 @@ void HandleTable::Clear() {
/// Initialize the kernel
void Init() {
Kernel::ThreadingInit();
+ Kernel::TimersInit();
}
/// Shutdown the kernel
void Shutdown() {
Kernel::ThreadingShutdown();
-
+ Kernel::TimersShutdown();
g_handle_table.Clear(); // Free all kernel objects
}
@@ -123,7 +123,7 @@ bool LoadExec(u32 entry_point) {
Core::g_app_core->SetPC(entry_point);
// 0x30 is the typical main thread priority I've seen used so far
- g_main_thread = Kernel::SetupMainThread(0x30);
+ g_main_thread = Kernel::SetupMainThread(0x30, Kernel::DEFAULT_STACK_SIZE);
// Setup the idle thread
Kernel::SetupIdleThread();
diff --git a/src/core/hle/kernel/kernel.h b/src/core/hle/kernel/kernel.h
index 7f86fd07d..5e5217b78 100644
--- a/src/core/hle/kernel/kernel.h
+++ b/src/core/hle/kernel/kernel.h
@@ -4,6 +4,8 @@
#pragma once
+#include <boost/intrusive_ptr.hpp>
+
#include <array>
#include <string>
#include "common/common.h"
@@ -16,6 +18,8 @@ const Handle INVALID_HANDLE = 0;
namespace Kernel {
+class Thread;
+
// TODO: Verify code
const ResultCode ERR_OUT_OF_HANDLES(ErrorDescription::OutOfMemory, ErrorModule::Kernel,
ErrorSummary::OutOfResource, ErrorLevel::Temporary);
@@ -39,6 +43,7 @@ enum class HandleType : u32 {
Process = 8,
AddressArbiter = 9,
Semaphore = 10,
+ Timer = 11
};
enum {
@@ -49,7 +54,7 @@ class HandleTable;
class Object : NonCopyable {
friend class HandleTable;
- u32 handle;
+ u32 handle = INVALID_HANDLE;
public:
virtual ~Object() {}
Handle GetHandle() const { return handle; }
@@ -73,7 +78,7 @@ private:
unsigned int ref_count = 0;
};
-// Special functions that will later be used by boost::instrusive_ptr to do automatic ref-counting
+// Special functions used by boost::instrusive_ptr to do automatic ref-counting
inline void intrusive_ptr_add_ref(Object* object) {
++object->ref_count;
}
@@ -84,6 +89,9 @@ inline void intrusive_ptr_release(Object* object) {
}
}
+template <typename T>
+using SharedPtr = boost::intrusive_ptr<T>;
+
/**
* This class allows the creation of Handles, which are references to objects that can be tested
* for validity and looked up. Here they are used to pass references to kernel objects to/from the
@@ -116,7 +124,7 @@ public:
* @return The created Handle or one of the following errors:
* - `ERR_OUT_OF_HANDLES`: the maximum number of handles has been exceeded.
*/
- ResultVal<Handle> Create(Object* obj);
+ ResultVal<Handle> Create(SharedPtr<Object> obj);
/**
* Returns a new handle that points to the same object as the passed in handle.
@@ -140,7 +148,7 @@ public:
* Looks up a handle.
* @returns Pointer to the looked-up object, or `nullptr` if the handle is not valid.
*/
- Object* GetGeneric(Handle handle) const;
+ SharedPtr<Object> GetGeneric(Handle handle) const;
/**
* Looks up a handle while verifying its type.
@@ -148,10 +156,10 @@ public:
* type differs from the handle type `T::HANDLE_TYPE`.
*/
template <class T>
- T* Get(Handle handle) const {
- Object* object = GetGeneric(handle);
+ SharedPtr<T> Get(Handle handle) const {
+ SharedPtr<Object> object = GetGeneric(handle);
if (object != nullptr && object->GetHandleType() == T::HANDLE_TYPE) {
- return static_cast<T*>(object);
+ return boost::static_pointer_cast<T>(std::move(object));
}
return nullptr;
}
@@ -170,7 +178,7 @@ private:
static u16 GetGeneration(Handle handle) { return handle & 0x7FFF; }
/// Stores the Object referenced by the handle or null if the slot is empty.
- std::array<Object*, MAX_COUNT> objects;
+ std::array<SharedPtr<Object>, MAX_COUNT> objects;
/**
* The value of `next_generation` when the handle was created, used to check for validity. For
@@ -189,7 +197,7 @@ private:
};
extern HandleTable g_handle_table;
-extern Handle g_main_thread;
+extern SharedPtr<Thread> g_main_thread;
/// The ID code of the currently running game
/// TODO(Subv): This variable should not be here,
diff --git a/src/core/hle/kernel/mutex.cpp b/src/core/hle/kernel/mutex.cpp
index 3dfeffc9b..853a5dd74 100644
--- a/src/core/hle/kernel/mutex.cpp
+++ b/src/core/hle/kernel/mutex.cpp
@@ -40,14 +40,21 @@ static MutexMap g_mutex_held_locks;
* @param mutex Mutex that is to be acquired
* @param thread Thread that will acquired
*/
-void MutexAcquireLock(Mutex* mutex, Handle thread = GetCurrentThreadHandle()) {
+void MutexAcquireLock(Mutex* mutex, Handle thread = GetCurrentThread()->GetHandle()) {
g_mutex_held_locks.insert(std::make_pair(thread, mutex->GetHandle()));
mutex->lock_thread = thread;
}
-bool ReleaseMutexForThread(Mutex* mutex, Handle thread) {
- MutexAcquireLock(mutex, thread);
- Kernel::ResumeThreadFromWait(thread);
+bool ReleaseMutexForThread(Mutex* mutex, Handle thread_handle) {
+ MutexAcquireLock(mutex, thread_handle);
+
+ Thread* thread = Kernel::g_handle_table.Get<Thread>(thread_handle).get();
+ if (thread == nullptr) {
+ LOG_ERROR(Kernel, "Called with invalid handle: %08X", thread_handle);
+ return false;
+ }
+
+ thread->ResumeFromWait();
return true;
}
@@ -87,7 +94,7 @@ void ReleaseThreadMutexes(Handle thread) {
// Release every mutex that the thread holds, and resume execution on the waiting threads
for (MutexMap::iterator iter = locked.first; iter != locked.second; ++iter) {
- Mutex* mutex = g_handle_table.Get<Mutex>(iter->second);
+ Mutex* mutex = g_handle_table.Get<Mutex>(iter->second).get();
ResumeWaitingThread(mutex);
}
@@ -115,7 +122,7 @@ bool ReleaseMutex(Mutex* mutex) {
* @param handle Handle to mutex to release
*/
ResultCode ReleaseMutex(Handle handle) {
- Mutex* mutex = Kernel::g_handle_table.Get<Mutex>(handle);
+ Mutex* mutex = Kernel::g_handle_table.Get<Mutex>(handle).get();
if (mutex == nullptr) return InvalidHandle(ErrorModule::Kernel);
if (!ReleaseMutex(mutex)) {
@@ -168,8 +175,8 @@ Handle CreateMutex(bool initial_locked, const std::string& name) {
ResultVal<bool> Mutex::WaitSynchronization() {
bool wait = locked;
if (locked) {
- waiting_threads.push_back(GetCurrentThreadHandle());
- Kernel::WaitCurrentThread(WAITTYPE_MUTEX, GetHandle());
+ waiting_threads.push_back(GetCurrentThread()->GetHandle());
+ Kernel::WaitCurrentThread(WAITTYPE_MUTEX, this);
} else {
// Lock the mutex when the first thread accesses it
locked = true;
diff --git a/src/core/hle/kernel/semaphore.cpp b/src/core/hle/kernel/semaphore.cpp
index 6bc8066a6..88ec9a104 100644
--- a/src/core/hle/kernel/semaphore.cpp
+++ b/src/core/hle/kernel/semaphore.cpp
@@ -37,8 +37,8 @@ public:
bool wait = !IsAvailable();
if (wait) {
- Kernel::WaitCurrentThread(WAITTYPE_SEMA, GetHandle());
- waiting_threads.push(GetCurrentThreadHandle());
+ Kernel::WaitCurrentThread(WAITTYPE_SEMA, this);
+ waiting_threads.push(GetCurrentThread()->GetHandle());
} else {
--available_count;
}
@@ -70,7 +70,7 @@ ResultCode CreateSemaphore(Handle* handle, s32 initial_count,
}
ResultCode ReleaseSemaphore(s32* count, Handle handle, s32 release_count) {
- Semaphore* semaphore = g_handle_table.Get<Semaphore>(handle);
+ Semaphore* semaphore = g_handle_table.Get<Semaphore>(handle).get();
if (semaphore == nullptr)
return InvalidHandle(ErrorModule::Kernel);
@@ -84,7 +84,9 @@ ResultCode ReleaseSemaphore(s32* count, Handle handle, s32 release_count) {
// Notify some of the threads that the semaphore has been released
// stop once the semaphore is full again or there are no more waiting threads
while (!semaphore->waiting_threads.empty() && semaphore->IsAvailable()) {
- Kernel::ResumeThreadFromWait(semaphore->waiting_threads.front());
+ Thread* thread = Kernel::g_handle_table.Get<Thread>(semaphore->waiting_threads.front()).get();
+ if (thread != nullptr)
+ thread->ResumeFromWait();
semaphore->waiting_threads.pop();
--semaphore->available_count;
}
diff --git a/src/core/hle/kernel/shared_memory.cpp b/src/core/hle/kernel/shared_memory.cpp
index cea1f6fa1..5368e4728 100644
--- a/src/core/hle/kernel/shared_memory.cpp
+++ b/src/core/hle/kernel/shared_memory.cpp
@@ -61,7 +61,7 @@ ResultCode MapSharedMemory(u32 handle, u32 address, MemoryPermission permissions
return ResultCode(ErrorDescription::InvalidAddress, ErrorModule::Kernel,
ErrorSummary::InvalidArgument, ErrorLevel::Permanent);
}
- SharedMemory* shared_memory = Kernel::g_handle_table.Get<SharedMemory>(handle);
+ SharedMemory* shared_memory = Kernel::g_handle_table.Get<SharedMemory>(handle).get();
if (shared_memory == nullptr) return InvalidHandle(ErrorModule::Kernel);
shared_memory->base_address = address;
@@ -72,7 +72,7 @@ ResultCode MapSharedMemory(u32 handle, u32 address, MemoryPermission permissions
}
ResultVal<u8*> GetSharedMemoryPointer(Handle handle, u32 offset) {
- SharedMemory* shared_memory = Kernel::g_handle_table.Get<SharedMemory>(handle);
+ SharedMemory* shared_memory = Kernel::g_handle_table.Get<SharedMemory>(handle).get();
if (shared_memory == nullptr) return InvalidHandle(ErrorModule::Kernel);
if (0 != shared_memory->base_address)
diff --git a/src/core/hle/kernel/thread.cpp b/src/core/hle/kernel/thread.cpp
index 58fb62e89..bc86a7c59 100644
--- a/src/core/hle/kernel/thread.cpp
+++ b/src/core/hle/kernel/thread.cpp
@@ -10,6 +10,7 @@
#include "common/common.h"
#include "common/thread_queue_list.h"
+#include "core/arm/arm_interface.h"
#include "core/core.h"
#include "core/core_timing.h"
#include "core/hle/hle.h"
@@ -21,68 +22,25 @@
namespace Kernel {
-class Thread : public Kernel::Object {
-public:
-
- std::string GetName() const override { return name; }
- std::string GetTypeName() const override { return "Thread"; }
-
- static const HandleType HANDLE_TYPE = HandleType::Thread;
- HandleType GetHandleType() const override { return HANDLE_TYPE; }
-
- inline bool IsRunning() const { return (status & THREADSTATUS_RUNNING) != 0; }
- inline bool IsStopped() const { return (status & THREADSTATUS_DORMANT) != 0; }
- inline bool IsReady() const { return (status & THREADSTATUS_READY) != 0; }
- inline bool IsWaiting() const { return (status & THREADSTATUS_WAIT) != 0; }
- inline bool IsSuspended() const { return (status & THREADSTATUS_SUSPEND) != 0; }
- inline bool IsIdle() const { return idle; }
-
- ResultVal<bool> WaitSynchronization() override {
- const bool wait = status != THREADSTATUS_DORMANT;
- if (wait) {
- Handle thread = GetCurrentThreadHandle();
- if (std::find(waiting_threads.begin(), waiting_threads.end(), thread) == waiting_threads.end()) {
- waiting_threads.push_back(thread);
- }
- WaitCurrentThread(WAITTYPE_THREADEND, this->GetHandle());
+ResultVal<bool> Thread::WaitSynchronization() {
+ const bool wait = status != THREADSTATUS_DORMANT;
+ if (wait) {
+ Thread* thread = GetCurrentThread();
+ if (std::find(waiting_threads.begin(), waiting_threads.end(), thread) == waiting_threads.end()) {
+ waiting_threads.push_back(thread);
}
-
- return MakeResult<bool>(wait);
+ WaitCurrentThread(WAITTYPE_THREADEND, this);
}
- ThreadContext context;
-
- u32 thread_id;
-
- u32 status;
- u32 entry_point;
- u32 stack_top;
- u32 stack_size;
-
- s32 initial_priority;
- s32 current_priority;
-
- s32 processor_id;
-
- WaitType wait_type;
- Handle wait_handle;
- VAddr wait_address;
-
- std::vector<Handle> waiting_threads;
-
- std::string name;
-
- /// Whether this thread is intended to never actually be executed, i.e. always idle
- bool idle = false;
-};
+ return MakeResult<bool>(wait);
+}
// Lists all thread ids that aren't deleted/etc.
-static std::vector<Handle> thread_queue;
+static std::vector<SharedPtr<Thread>> thread_list;
// Lists only ready thread ids.
-static Common::ThreadQueueList<Handle, THREADPRIO_LOWEST+1> thread_ready_queue;
+static Common::ThreadQueueList<Thread*, THREADPRIO_LOWEST+1> thread_ready_queue;
-static Handle current_thread_handle;
static Thread* current_thread;
static const u32 INITIAL_THREAD_ID = 1; ///< The first available thread id at startup
@@ -92,30 +50,9 @@ Thread* GetCurrentThread() {
return current_thread;
}
-/// Gets the current thread handle
-Handle GetCurrentThreadHandle() {
- return GetCurrentThread()->GetHandle();
-}
-
-/// Sets the current thread
-inline void SetCurrentThread(Thread* t) {
- current_thread = t;
- current_thread_handle = t->GetHandle();
-}
-
-/// Saves the current CPU context
-void SaveContext(ThreadContext& ctx) {
- Core::g_app_core->SaveContext(ctx);
-}
-
-/// Loads a CPU context
-void LoadContext(ThreadContext& ctx) {
- Core::g_app_core->LoadContext(ctx);
-}
-
/// Resets a thread
-void ResetThread(Thread* t, u32 arg, s32 lowest_priority) {
- memset(&t->context, 0, sizeof(ThreadContext));
+static void ResetThread(Thread* t, u32 arg, s32 lowest_priority) {
+ memset(&t->context, 0, sizeof(Core::ThreadContext));
t->context.cpu_registers[0] = arg;
t->context.pc = t->context.reg_15 = t->entry_point;
@@ -131,22 +68,21 @@ void ResetThread(Thread* t, u32 arg, s32 lowest_priority) {
t->current_priority = t->initial_priority;
}
t->wait_type = WAITTYPE_NONE;
- t->wait_handle = 0;
+ t->wait_object = nullptr;
t->wait_address = 0;
}
/// Change a thread to "ready" state
-void ChangeReadyState(Thread* t, bool ready) {
- Handle handle = t->GetHandle();
+static void ChangeReadyState(Thread* t, bool ready) {
if (t->IsReady()) {
if (!ready) {
- thread_ready_queue.remove(t->current_priority, handle);
+ thread_ready_queue.remove(t->current_priority, t);
}
} else if (ready) {
if (t->IsRunning()) {
- thread_ready_queue.push_front(t->current_priority, handle);
+ thread_ready_queue.push_front(t->current_priority, t);
} else {
- thread_ready_queue.push_back(t->current_priority, handle);
+ thread_ready_queue.push_back(t->current_priority, t);
}
t->status = THREADSTATUS_READY;
}
@@ -158,43 +94,36 @@ static bool CheckWaitType(const Thread* thread, WaitType type) {
}
/// Check if a thread is blocking on a specified wait type with a specified handle
-static bool CheckWaitType(const Thread* thread, WaitType type, Handle wait_handle) {
- return CheckWaitType(thread, type) && (wait_handle == thread->wait_handle);
+static bool CheckWaitType(const Thread* thread, WaitType type, Object* wait_object) {
+ return CheckWaitType(thread, type) && wait_object == thread->wait_object;
}
/// Check if a thread is blocking on a specified wait type with a specified handle and address
-static bool CheckWaitType(const Thread* thread, WaitType type, Handle wait_handle, VAddr wait_address) {
- return CheckWaitType(thread, type, wait_handle) && (wait_address == thread->wait_address);
+static bool CheckWaitType(const Thread* thread, WaitType type, Object* wait_object, VAddr wait_address) {
+ return CheckWaitType(thread, type, wait_object) && (wait_address == thread->wait_address);
}
/// Stops the current thread
-ResultCode StopThread(Handle handle, const char* reason) {
- Thread* thread = g_handle_table.Get<Thread>(handle);
- if (thread == nullptr) return InvalidHandle(ErrorModule::Kernel);
-
+void Thread::Stop(const char* reason) {
// Release all the mutexes that this thread holds
- ReleaseThreadMutexes(handle);
-
- ChangeReadyState(thread, false);
- thread->status = THREADSTATUS_DORMANT;
- for (Handle waiting_handle : thread->waiting_threads) {
- Thread* waiting_thread = g_handle_table.Get<Thread>(waiting_handle);
+ ReleaseThreadMutexes(GetHandle());
- if (CheckWaitType(waiting_thread, WAITTYPE_THREADEND, handle))
- ResumeThreadFromWait(waiting_handle);
+ ChangeReadyState(this, false);
+ status = THREADSTATUS_DORMANT;
+ for (auto& waiting_thread : waiting_threads) {
+ if (CheckWaitType(waiting_thread.get(), WAITTYPE_THREADEND, this))
+ waiting_thread->ResumeFromWait();
}
- thread->waiting_threads.clear();
+ waiting_threads.clear();
// Stopped threads are never waiting.
- thread->wait_type = WAITTYPE_NONE;
- thread->wait_handle = 0;
- thread->wait_address = 0;
-
- return RESULT_SUCCESS;
+ wait_type = WAITTYPE_NONE;
+ wait_object = nullptr;
+ wait_address = 0;
}
/// Changes a threads state
-void ChangeThreadState(Thread* t, ThreadStatus new_status) {
+static void ChangeThreadState(Thread* t, ThreadStatus new_status) {
if (!t || t->status == new_status) {
return;
}
@@ -209,46 +138,44 @@ void ChangeThreadState(Thread* t, ThreadStatus new_status) {
}
/// Arbitrate the highest priority thread that is waiting
-Handle ArbitrateHighestPriorityThread(u32 arbiter, u32 address) {
- Handle highest_priority_thread = 0;
+Thread* ArbitrateHighestPriorityThread(Object* arbiter, u32 address) {
+ Thread* highest_priority_thread = nullptr;
s32 priority = THREADPRIO_LOWEST;
// Iterate through threads, find highest priority thread that is waiting to be arbitrated...
- for (Handle handle : thread_queue) {
- Thread* thread = g_handle_table.Get<Thread>(handle);
-
- if (!CheckWaitType(thread, WAITTYPE_ARB, arbiter, address))
+ for (auto& thread : thread_list) {
+ if (!CheckWaitType(thread.get(), WAITTYPE_ARB, arbiter, address))
continue;
if (thread == nullptr)
continue; // TODO(yuriks): Thread handle will hang around forever. Should clean up.
if(thread->current_priority <= priority) {
- highest_priority_thread = handle;
+ highest_priority_thread = thread.get();
priority = thread->current_priority;
}
}
+
// If a thread was arbitrated, resume it
- if (0 != highest_priority_thread)
- ResumeThreadFromWait(highest_priority_thread);
+ if (nullptr != highest_priority_thread) {
+ highest_priority_thread->ResumeFromWait();
+ }
return highest_priority_thread;
}
/// Arbitrate all threads currently waiting
-void ArbitrateAllThreads(u32 arbiter, u32 address) {
+void ArbitrateAllThreads(Object* arbiter, u32 address) {
// Iterate through threads, find highest priority thread that is waiting to be arbitrated...
- for (Handle handle : thread_queue) {
- Thread* thread = g_handle_table.Get<Thread>(handle);
-
- if (CheckWaitType(thread, WAITTYPE_ARB, arbiter, address))
- ResumeThreadFromWait(handle);
+ for (auto& thread : thread_list) {
+ if (CheckWaitType(thread.get(), WAITTYPE_ARB, arbiter, address))
+ thread->ResumeFromWait();
}
}
/// Calls a thread by marking it as "ready" (note: will not actually execute until current thread yields)
-void CallThread(Thread* t) {
+static void CallThread(Thread* t) {
// Stop waiting
if (t->wait_type != WAITTYPE_NONE) {
t->wait_type = WAITTYPE_NONE;
@@ -257,12 +184,12 @@ void CallThread(Thread* t) {
}
/// Switches CPU context to that of the specified thread
-void SwitchContext(Thread* t) {
+static void SwitchContext(Thread* t) {
Thread* cur = GetCurrentThread();
// Save context for current thread
if (cur) {
- SaveContext(cur->context);
+ Core::g_app_core->SaveContext(cur->context);
if (cur->IsRunning()) {
ChangeReadyState(cur, true);
@@ -270,19 +197,19 @@ void SwitchContext(Thread* t) {
}
// Load context of new thread
if (t) {
- SetCurrentThread(t);
+ current_thread = t;
ChangeReadyState(t, false);
t->status = (t->status | THREADSTATUS_RUNNING) & ~THREADSTATUS_READY;
t->wait_type = WAITTYPE_NONE;
- LoadContext(t->context);
+ Core::g_app_core->LoadContext(t->context);
} else {
- SetCurrentThread(nullptr);
+ current_thread = nullptr;
}
}
/// Gets the next thread that is ready to be run by priority
-Thread* NextThread() {
- Handle next;
+static Thread* NextThread() {
+ Thread* next;
Thread* cur = GetCurrentThread();
if (cur && cur->IsRunning()) {
@@ -293,63 +220,111 @@ Thread* NextThread() {
if (next == 0) {
return nullptr;
}
- return Kernel::g_handle_table.Get<Thread>(next);
+ return next;
}
-void WaitCurrentThread(WaitType wait_type, Handle wait_handle) {
+void WaitCurrentThread(WaitType wait_type, Object* wait_object) {
Thread* thread = GetCurrentThread();
thread->wait_type = wait_type;
- thread->wait_handle = wait_handle;
+ thread->wait_object = wait_object;
ChangeThreadState(thread, ThreadStatus(THREADSTATUS_WAIT | (thread->status & THREADSTATUS_SUSPEND)));
}
-void WaitCurrentThread(WaitType wait_type, Handle wait_handle, VAddr wait_address) {
- WaitCurrentThread(wait_type, wait_handle);
+void WaitCurrentThread(WaitType wait_type, Object* wait_object, VAddr wait_address) {
+ WaitCurrentThread(wait_type, wait_object);
GetCurrentThread()->wait_address = wait_address;
}
+/// Event type for the thread wake up event
+static int ThreadWakeupEventType = -1;
+
+/// Callback that will wake up the thread it was scheduled for
+static void ThreadWakeupCallback(u64 parameter, int cycles_late) {
+ Handle handle = static_cast<Handle>(parameter);
+ SharedPtr<Thread> thread = Kernel::g_handle_table.Get<Thread>(handle);
+ if (thread == nullptr) {
+ LOG_ERROR(Kernel, "Thread doesn't exist %u", handle);
+ return;
+ }
+
+ thread->ResumeFromWait();
+}
+
+
+void WakeThreadAfterDelay(Thread* thread, s64 nanoseconds) {
+ // Don't schedule a wakeup if the thread wants to wait forever
+ if (nanoseconds == -1)
+ return;
+ _dbg_assert_(Kernel, thread != nullptr);
+
+ u64 microseconds = nanoseconds / 1000;
+ CoreTiming::ScheduleEvent(usToCycles(microseconds), ThreadWakeupEventType, thread->GetHandle());
+}
+
/// Resumes a thread from waiting by marking it as "ready"
-void ResumeThreadFromWait(Handle handle) {
- Thread* thread = Kernel::g_handle_table.Get<Thread>(handle);
- if (thread) {
- thread->status &= ~THREADSTATUS_WAIT;
- thread->wait_handle = 0;
- thread->wait_type = WAITTYPE_NONE;
- if (!(thread->status & (THREADSTATUS_WAITSUSPEND | THREADSTATUS_DORMANT | THREADSTATUS_DEAD))) {
- ChangeReadyState(thread, true);
- }
+void Thread::ResumeFromWait() {
+ // Cancel any outstanding wakeup events
+ CoreTiming::UnscheduleEvent(ThreadWakeupEventType, GetHandle());
+
+ status &= ~THREADSTATUS_WAIT;
+ wait_object = nullptr;
+ wait_type = WAITTYPE_NONE;
+ if (!(status & (THREADSTATUS_WAITSUSPEND | THREADSTATUS_DORMANT | THREADSTATUS_DEAD))) {
+ ChangeReadyState(this, true);
}
}
/// Prints the thread queue for debugging purposes
-void DebugThreadQueue() {
+static void DebugThreadQueue() {
Thread* thread = GetCurrentThread();
if (!thread) {
return;
}
- LOG_DEBUG(Kernel, "0x%02X 0x%08X (current)", thread->current_priority, GetCurrentThreadHandle());
- for (u32 i = 0; i < thread_queue.size(); i++) {
- Handle handle = thread_queue[i];
- s32 priority = thread_ready_queue.contains(handle);
+ LOG_DEBUG(Kernel, "0x%02X 0x%08X (current)", thread->current_priority, GetCurrentThread()->GetHandle());
+ for (auto& t : thread_list) {
+ s32 priority = thread_ready_queue.contains(t.get());
if (priority != -1) {
- LOG_DEBUG(Kernel, "0x%02X 0x%08X", priority, handle);
+ LOG_DEBUG(Kernel, "0x%02X 0x%08X", priority, t->GetHandle());
}
}
}
-/// Creates a new thread
-Thread* CreateThread(Handle& handle, const char* name, u32 entry_point, s32 priority,
- s32 processor_id, u32 stack_top, int stack_size) {
+ResultVal<SharedPtr<Thread>> Thread::Create(std::string name, VAddr entry_point, s32 priority,
+ u32 arg, s32 processor_id, VAddr stack_top, u32 stack_size) {
+ if (stack_size < 0x200) {
+ LOG_ERROR(Kernel, "(name=%s): invalid stack_size=0x%08X", name.c_str(), stack_size);
+ // TODO: Verify error
+ return ResultCode(ErrorDescription::InvalidSize, ErrorModule::Kernel,
+ ErrorSummary::InvalidArgument, ErrorLevel::Permanent);
+ }
- _assert_msg_(KERNEL, (priority >= THREADPRIO_HIGHEST && priority <= THREADPRIO_LOWEST),
- "priority=%d, outside of allowable range!", priority)
+ if (priority < THREADPRIO_HIGHEST || priority > THREADPRIO_LOWEST) {
+ s32 new_priority = CLAMP(priority, THREADPRIO_HIGHEST, THREADPRIO_LOWEST);
+ LOG_WARNING(Kernel_SVC, "(name=%s): invalid priority=%d, clamping to %d",
+ name.c_str(), priority, new_priority);
+ // TODO(bunnei): Clamping to a valid priority is not necessarily correct behavior... Confirm
+ // validity of this
+ priority = new_priority;
+ }
+
+ if (!Memory::GetPointer(entry_point)) {
+ LOG_ERROR(Kernel_SVC, "(name=%s): invalid entry %08x", name.c_str(), entry_point);
+ // TODO: Verify error
+ return ResultCode(ErrorDescription::InvalidAddress, ErrorModule::Kernel,
+ ErrorSummary::InvalidArgument, ErrorLevel::Permanent);
+ }
- Thread* thread = new Thread;
+ SharedPtr<Thread> thread(new Thread);
- // TOOD(yuriks): Fix error reporting
- handle = Kernel::g_handle_table.Create(thread).ValueOr(INVALID_HANDLE);
+ // TODO(yuriks): Thread requires a handle to be inserted into the various scheduling queues for
+ // the time being. Create a handle here, it will be copied to the handle field in
+ // the object and use by the rest of the code. This should be removed when other
+ // code doesn't rely on the handle anymore.
+ ResultVal<Handle> handle = Kernel::g_handle_table.Create(thread);
+ if (handle.Failed())
+ return handle.Code();
- thread_queue.push_back(handle);
+ thread_list.push_back(thread);
thread_ready_queue.prepare(priority);
thread->thread_id = next_thread_id++;
@@ -360,69 +335,18 @@ Thread* CreateThread(Handle& handle, const char* name, u32 entry_point, s32 prio
thread->initial_priority = thread->current_priority = priority;
thread->processor_id = processor_id;
thread->wait_type = WAITTYPE_NONE;
- thread->wait_handle = 0;
+ thread->wait_object = nullptr;
thread->wait_address = 0;
- thread->name = name;
-
- return thread;
-}
-
-/// Creates a new thread - wrapper for external user
-Handle CreateThread(const char* name, u32 entry_point, s32 priority, u32 arg, s32 processor_id,
- u32 stack_top, int stack_size) {
-
- if (name == nullptr) {
- LOG_ERROR(Kernel_SVC, "nullptr name");
- return -1;
- }
- if ((u32)stack_size < 0x200) {
- LOG_ERROR(Kernel_SVC, "(name=%s): invalid stack_size=0x%08X", name,
- stack_size);
- return -1;
- }
- if (priority < THREADPRIO_HIGHEST || priority > THREADPRIO_LOWEST) {
- s32 new_priority = CLAMP(priority, THREADPRIO_HIGHEST, THREADPRIO_LOWEST);
- LOG_WARNING(Kernel_SVC, "(name=%s): invalid priority=%d, clamping to %d",
- name, priority, new_priority);
- // TODO(bunnei): Clamping to a valid priority is not necessarily correct behavior... Confirm
- // validity of this
- priority = new_priority;
- }
- if (!Memory::GetPointer(entry_point)) {
- LOG_ERROR(Kernel_SVC, "(name=%s): invalid entry %08x", name, entry_point);
- return -1;
- }
- Handle handle;
- Thread* thread = CreateThread(handle, name, entry_point, priority, processor_id, stack_top,
- stack_size);
+ thread->name = std::move(name);
- ResetThread(thread, arg, 0);
- CallThread(thread);
+ ResetThread(thread.get(), arg, 0);
+ CallThread(thread.get());
- return handle;
-}
-
-/// Get the priority of the thread specified by handle
-ResultVal<u32> GetThreadPriority(const Handle handle) {
- Thread* thread = g_handle_table.Get<Thread>(handle);
- if (thread == nullptr) return InvalidHandle(ErrorModule::Kernel);
-
- return MakeResult<u32>(thread->current_priority);
+ return MakeResult<SharedPtr<Thread>>(std::move(thread));
}
/// Set the priority of the thread specified by handle
-ResultCode SetThreadPriority(Handle handle, s32 priority) {
- Thread* thread = nullptr;
- if (!handle) {
- thread = GetCurrentThread(); // TODO(bunnei): Is this correct behavior?
- } else {
- thread = g_handle_table.Get<Thread>(handle);
- if (thread == nullptr) {
- return InvalidHandle(ErrorModule::Kernel);
- }
- }
- _assert_msg_(KERNEL, (thread != nullptr), "called, but thread is nullptr!");
-
+void Thread::SetPriority(s32 priority) {
// If priority is invalid, clamp to valid range
if (priority < THREADPRIO_HIGHEST || priority > THREADPRIO_LOWEST) {
s32 new_priority = CLAMP(priority, THREADPRIO_HIGHEST, THREADPRIO_LOWEST);
@@ -433,38 +357,39 @@ ResultCode SetThreadPriority(Handle handle, s32 priority) {
}
// Change thread priority
- s32 old = thread->current_priority;
- thread_ready_queue.remove(old, handle);
- thread->current_priority = priority;
- thread_ready_queue.prepare(thread->current_priority);
+ s32 old = current_priority;
+ thread_ready_queue.remove(old, this);
+ current_priority = priority;
+ thread_ready_queue.prepare(current_priority);
// Change thread status to "ready" and push to ready queue
- if (thread->IsRunning()) {
- thread->status = (thread->status & ~THREADSTATUS_RUNNING) | THREADSTATUS_READY;
+ if (IsRunning()) {
+ status = (status & ~THREADSTATUS_RUNNING) | THREADSTATUS_READY;
}
- if (thread->IsReady()) {
- thread_ready_queue.push_back(thread->current_priority, handle);
+ if (IsReady()) {
+ thread_ready_queue.push_back(current_priority, this);
}
-
- return RESULT_SUCCESS;
}
Handle SetupIdleThread() {
- Handle handle;
- Thread* thread = CreateThread(handle, "idle", 0, THREADPRIO_LOWEST, THREADPROCESSORID_0, 0, 0);
+ // We need to pass a few valid values to get around parameter checking in Thread::Create.
+ auto thread_res = Thread::Create("idle", Memory::KERNEL_MEMORY_VADDR, THREADPRIO_LOWEST, 0,
+ THREADPROCESSORID_0, 0, Kernel::DEFAULT_STACK_SIZE);
+ _dbg_assert_(Kernel, thread_res.Succeeded());
+ SharedPtr<Thread> thread = std::move(*thread_res);
+
thread->idle = true;
- CallThread(thread);
- return handle;
+ CallThread(thread.get());
+ return thread->GetHandle();
}
-Handle SetupMainThread(s32 priority, int stack_size) {
- Handle handle;
-
+SharedPtr<Thread> SetupMainThread(s32 priority, u32 stack_size) {
// Initialize new "main" thread
- Thread* thread = CreateThread(handle, "main", Core::g_app_core->GetPC(), priority,
- THREADPROCESSORID_0, Memory::SCRATCHPAD_VADDR_END, stack_size);
-
- ResetThread(thread, 0, 0);
+ auto thread_res = Thread::Create("main", Core::g_app_core->GetPC(), priority, 0,
+ THREADPROCESSORID_0, Memory::SCRATCHPAD_VADDR_END, stack_size);
+ // TODO(yuriks): Propagate error
+ _dbg_assert_(Kernel, thread_res.Succeeded());
+ SharedPtr<Thread> thread = std::move(*thread_res);
// If running another thread already, set it to "ready" state
Thread* cur = GetCurrentThread();
@@ -473,11 +398,11 @@ Handle SetupMainThread(s32 priority, int stack_size) {
}
// Run new "main" thread
- SetCurrentThread(thread);
+ current_thread = thread.get();
thread->status = THREADSTATUS_RUNNING;
- LoadContext(thread->context);
+ Core::g_app_core->LoadContext(thread->context);
- return handle;
+ return thread;
}
@@ -493,46 +418,19 @@ void Reschedule() {
} else {
LOG_TRACE(Kernel, "cannot context switch from 0x%08X, no higher priority thread!", prev->GetHandle());
- for (Handle handle : thread_queue) {
- Thread* thread = g_handle_table.Get<Thread>(handle);
+ for (auto& thread : thread_list) {
LOG_TRACE(Kernel, "\thandle=0x%08X prio=0x%02X, status=0x%08X wait_type=0x%08X wait_handle=0x%08X",
- thread->GetHandle(), thread->current_priority, thread->status, thread->wait_type, thread->wait_handle);
+ thread->GetHandle(), thread->current_priority, thread->status, thread->wait_type,
+ (thread->wait_object ? thread->wait_object->GetHandle() : INVALID_HANDLE));
}
}
-
- // TODO(bunnei): Hack - There is no timing mechanism yet to wake up a thread if it has been put
- // to sleep. So, we'll just immediately set it to "ready" again after an attempted context
- // switch has occurred. This results in the current thread yielding on a sleep once, and then it
- // will immediately be placed back in the queue for execution.
-
- if (CheckWaitType(prev, WAITTYPE_SLEEP))
- ResumeThreadFromWait(prev->GetHandle());
-}
-
-bool IsIdleThread(Handle handle) {
- Thread* thread = g_handle_table.Get<Thread>(handle);
- if (!thread) {
- LOG_ERROR(Kernel, "Thread not found %u", handle);
- return false;
- }
- return thread->IsIdle();
-}
-
-ResultCode GetThreadId(u32* thread_id, Handle handle) {
- Thread* thread = g_handle_table.Get<Thread>(handle);
- if (thread == nullptr)
- return ResultCode(ErrorDescription::InvalidHandle, ErrorModule::OS,
- ErrorSummary::WrongArgument, ErrorLevel::Permanent);
-
- *thread_id = thread->thread_id;
-
- return RESULT_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ThreadingInit() {
next_thread_id = INITIAL_THREAD_ID;
+ ThreadWakeupEventType = CoreTiming::RegisterEvent("ThreadWakeupCallback", ThreadWakeupCallback);
}
void ThreadingShutdown() {
diff --git a/src/core/hle/kernel/thread.h b/src/core/hle/kernel/thread.h
index dfe92d162..284dec400 100644
--- a/src/core/hle/kernel/thread.h
+++ b/src/core/hle/kernel/thread.h
@@ -4,8 +4,12 @@
#pragma once
+#include <string>
+#include <vector>
+
#include "common/common_types.h"
+#include "core/core.h"
#include "core/mem_map.h"
#include "core/hle/kernel/kernel.h"
@@ -43,66 +47,107 @@ enum WaitType {
WAITTYPE_MUTEX,
WAITTYPE_SYNCH,
WAITTYPE_ARB,
+ WAITTYPE_TIMER,
};
namespace Kernel {
-/// Creates a new thread - wrapper for external user
-Handle CreateThread(const char* name, u32 entry_point, s32 priority, u32 arg, s32 processor_id,
- u32 stack_top, int stack_size=Kernel::DEFAULT_STACK_SIZE);
+class Thread : public Kernel::Object {
+public:
+ static ResultVal<SharedPtr<Thread>> Create(std::string name, VAddr entry_point, s32 priority,
+ u32 arg, s32 processor_id, VAddr stack_top, u32 stack_size);
-/// Sets up the primary application thread
-Handle SetupMainThread(s32 priority, int stack_size=Kernel::DEFAULT_STACK_SIZE);
+ std::string GetName() const override { return name; }
+ std::string GetTypeName() const override { return "Thread"; }
-/// Reschedules to the next available thread (call after current thread is suspended)
-void Reschedule();
+ static const HandleType HANDLE_TYPE = HandleType::Thread;
+ HandleType GetHandleType() const override { return HANDLE_TYPE; }
-/// Stops the current thread
-ResultCode StopThread(Handle thread, const char* reason);
+ inline bool IsRunning() const { return (status & THREADSTATUS_RUNNING) != 0; }
+ inline bool IsStopped() const { return (status & THREADSTATUS_DORMANT) != 0; }
+ inline bool IsReady() const { return (status & THREADSTATUS_READY) != 0; }
+ inline bool IsWaiting() const { return (status & THREADSTATUS_WAIT) != 0; }
+ inline bool IsSuspended() const { return (status & THREADSTATUS_SUSPEND) != 0; }
+ inline bool IsIdle() const { return idle; }
-/**
- * Retrieves the ID of the specified thread handle
- * @param thread_id Will contain the output thread id
- * @param handle Handle to the thread we want
- * @return Whether the function was successful or not
- */
-ResultCode GetThreadId(u32* thread_id, Handle handle);
+ ResultVal<bool> WaitSynchronization() override;
+
+ s32 GetPriority() const { return current_priority; }
+ void SetPriority(s32 priority);
+
+ u32 GetThreadId() const { return thread_id; }
+
+ void Stop(const char* reason);
+ /// Resumes a thread from waiting by marking it as "ready".
+ void ResumeFromWait();
+
+ Core::ThreadContext context;
+
+ u32 thread_id;
+
+ u32 status;
+ u32 entry_point;
+ u32 stack_top;
+ u32 stack_size;
+
+ s32 initial_priority;
+ s32 current_priority;
+
+ s32 processor_id;
+
+ WaitType wait_type;
+ Object* wait_object;
+ VAddr wait_address;
-/// Resumes a thread from waiting by marking it as "ready"
-void ResumeThreadFromWait(Handle handle);
+ std::vector<SharedPtr<Thread>> waiting_threads;
+
+ std::string name;
+
+ /// Whether this thread is intended to never actually be executed, i.e. always idle
+ bool idle = false;
+
+private:
+ Thread() = default;
+};
+
+/// Sets up the primary application thread
+SharedPtr<Thread> SetupMainThread(s32 priority, u32 stack_size);
+
+/// Reschedules to the next available thread (call after current thread is suspended)
+void Reschedule();
/// Arbitrate the highest priority thread that is waiting
-Handle ArbitrateHighestPriorityThread(u32 arbiter, u32 address);
+Thread* ArbitrateHighestPriorityThread(Object* arbiter, u32 address);
/// Arbitrate all threads currently waiting...
-void ArbitrateAllThreads(u32 arbiter, u32 address);
+void ArbitrateAllThreads(Object* arbiter, u32 address);
-/// Gets the current thread handle
-Handle GetCurrentThreadHandle();
+/// Gets the current thread
+Thread* GetCurrentThread();
/**
* Puts the current thread in the wait state for the given type
* @param wait_type Type of wait
- * @param wait_handle Handle of Kernel object that we are waiting on, defaults to current thread
+ * @param wait_object Kernel object that we are waiting on, defaults to current thread
+ */
+void WaitCurrentThread(WaitType wait_type, Object* wait_object = GetCurrentThread());
+
+/**
+ * Schedules an event to wake up the specified thread after the specified delay.
+ * @param handle The thread handle.
+ * @param nanoseconds The time this thread will be allowed to sleep for.
*/
-void WaitCurrentThread(WaitType wait_type, Handle wait_handle=GetCurrentThreadHandle());
+void WakeThreadAfterDelay(Thread* thread, s64 nanoseconds);
/**
* Puts the current thread in the wait state for the given type
* @param wait_type Type of wait
- * @param wait_handle Handle of Kernel object that we are waiting on, defaults to current thread
+ * @param wait_object Kernel object that we are waiting on
* @param wait_address Arbitration address used to resume from wait
*/
-void WaitCurrentThread(WaitType wait_type, Handle wait_handle, VAddr wait_address);
+void WaitCurrentThread(WaitType wait_type, Object* wait_object, VAddr wait_address);
-/// Put current thread in a wait state - on WaitSynchronization
-void WaitThread_Synchronization();
-/// Get the priority of the thread specified by handle
-ResultVal<u32> GetThreadPriority(const Handle handle);
-
-/// Set the priority of the thread specified by handle
-ResultCode SetThreadPriority(Handle handle, s32 priority);
/**
* Sets up the idle thread, this is a thread that is intended to never execute instructions,
@@ -111,10 +156,6 @@ ResultCode SetThreadPriority(Handle handle, s32 priority);
* @returns The handle of the idle thread
*/
Handle SetupIdleThread();
-
-/// Whether the current thread is an idle thread
-bool IsIdleThread(Handle thread);
-
/// Initialize threading
void ThreadingInit();
diff --git a/src/core/hle/kernel/timer.cpp b/src/core/hle/kernel/timer.cpp
new file mode 100644
index 000000000..3b0452d4d
--- /dev/null
+++ b/src/core/hle/kernel/timer.cpp
@@ -0,0 +1,144 @@
+// Copyright 2015 Citra Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <set>
+
+#include "common/common.h"
+
+#include "core/core_timing.h"
+#include "core/hle/kernel/kernel.h"
+#include "core/hle/kernel/timer.h"
+#include "core/hle/kernel/thread.h"
+
+namespace Kernel {
+
+class Timer : public Object {
+public:
+ std::string GetTypeName() const override { return "Timer"; }
+ std::string GetName() const override { return name; }
+
+ static const HandleType HANDLE_TYPE = HandleType::Timer;
+ HandleType GetHandleType() const override { return HANDLE_TYPE; }
+
+ ResetType reset_type; ///< The ResetType of this timer
+
+ bool signaled; ///< Whether the timer has been signaled or not
+ std::set<Handle> waiting_threads; ///< Threads that are waiting for the timer
+ std::string name; ///< Name of timer (optional)
+
+ u64 initial_delay; ///< The delay until the timer fires for the first time
+ u64 interval_delay; ///< The delay until the timer fires after the first time
+
+ ResultVal<bool> WaitSynchronization() override {
+ bool wait = !signaled;
+ if (wait) {
+ waiting_threads.insert(GetCurrentThread()->GetHandle());
+ Kernel::WaitCurrentThread(WAITTYPE_TIMER, this);
+ }
+ return MakeResult<bool>(wait);
+ }
+};
+
+/**
+ * Creates a timer.
+ * @param handle Reference to handle for the newly created timer
+ * @param reset_type ResetType describing how to create timer
+ * @param name Optional name of timer
+ * @return Newly created Timer object
+ */
+Timer* CreateTimer(Handle& handle, const ResetType reset_type, const std::string& name) {
+ Timer* timer = new Timer;
+
+ handle = Kernel::g_handle_table.Create(timer).ValueOr(INVALID_HANDLE);
+
+ timer->reset_type = reset_type;
+ timer->signaled = false;
+ timer->name = name;
+ timer->initial_delay = 0;
+ timer->interval_delay = 0;
+ return timer;
+}
+
+ResultCode CreateTimer(Handle* handle, const ResetType reset_type, const std::string& name) {
+ CreateTimer(*handle, reset_type, name);
+ return RESULT_SUCCESS;
+}
+
+ResultCode ClearTimer(Handle handle) {
+ SharedPtr<Timer> timer = Kernel::g_handle_table.Get<Timer>(handle);
+
+ if (timer == nullptr)
+ return InvalidHandle(ErrorModule::Kernel);
+
+ timer->signaled = false;
+ return RESULT_SUCCESS;
+}
+
+/// The event type of the generic timer callback event
+static int TimerCallbackEventType = -1;
+
+/// The timer callback event, called when a timer is fired
+static void TimerCallback(u64 timer_handle, int cycles_late) {
+ SharedPtr<Timer> timer = Kernel::g_handle_table.Get<Timer>(timer_handle);
+
+ if (timer == nullptr) {
+ LOG_CRITICAL(Kernel, "Callback fired for invalid timer %u", timer_handle);
+ return;
+ }
+
+ LOG_TRACE(Kernel, "Timer %u fired", timer_handle);
+
+ timer->signaled = true;
+
+ // Resume all waiting threads
+ for (Handle thread_handle : timer->waiting_threads) {
+ if (SharedPtr<Thread> thread = Kernel::g_handle_table.Get<Thread>(thread_handle))
+ thread->ResumeFromWait();
+ }
+
+ timer->waiting_threads.clear();
+
+ if (timer->reset_type == RESETTYPE_ONESHOT)
+ timer->signaled = false;
+
+ if (timer->interval_delay != 0) {
+ // Reschedule the timer with the interval delay
+ u64 interval_microseconds = timer->interval_delay / 1000;
+ CoreTiming::ScheduleEvent(usToCycles(interval_microseconds) - cycles_late,
+ TimerCallbackEventType, timer_handle);
+ }
+}
+
+ResultCode SetTimer(Handle handle, s64 initial, s64 interval) {
+ SharedPtr<Timer> timer = Kernel::g_handle_table.Get<Timer>(handle);
+
+ if (timer == nullptr)
+ return InvalidHandle(ErrorModule::Kernel);
+
+ timer->initial_delay = initial;
+ timer->interval_delay = interval;
+
+ u64 initial_microseconds = initial / 1000;
+ CoreTiming::ScheduleEvent(usToCycles(initial_microseconds), TimerCallbackEventType, handle);
+ return RESULT_SUCCESS;
+}
+
+ResultCode CancelTimer(Handle handle) {
+ SharedPtr<Timer> timer = Kernel::g_handle_table.Get<Timer>(handle);
+
+ if (timer == nullptr)
+ return InvalidHandle(ErrorModule::Kernel);
+
+ CoreTiming::UnscheduleEvent(TimerCallbackEventType, handle);
+ return RESULT_SUCCESS;
+}
+
+void TimersInit() {
+ TimerCallbackEventType = CoreTiming::RegisterEvent("TimerCallback", TimerCallback);
+}
+
+void TimersShutdown() {
+}
+
+} // namespace
diff --git a/src/core/hle/kernel/timer.h b/src/core/hle/kernel/timer.h
new file mode 100644
index 000000000..f8aa66b60
--- /dev/null
+++ b/src/core/hle/kernel/timer.h
@@ -0,0 +1,47 @@
+// Copyright 2015 Citra Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include "common/common_types.h"
+
+#include "core/hle/kernel/kernel.h"
+#include "core/hle/svc.h"
+
+namespace Kernel {
+
+/**
+ * Cancels a timer
+ * @param handle Handle of the timer to cancel
+ */
+ResultCode CancelTimer(Handle handle);
+
+/**
+ * Starts a timer with the specified initial delay and interval
+ * @param handle Handle of the timer to start
+ * @param initial Delay until the timer is first fired
+ * @param interval Delay until the timer is fired after the first time
+ */
+ResultCode SetTimer(Handle handle, s64 initial, s64 interval);
+
+/**
+ * Clears a timer
+ * @param handle Handle of the timer to clear
+ */
+ResultCode ClearTimer(Handle handle);
+
+/**
+ * Creates a timer
+ * @param Handle to newly created Timer object
+ * @param reset_type ResetType describing how to create the timer
+ * @param name Optional name of timer
+ * @return ResultCode of the error
+ */
+ResultCode CreateTimer(Handle* handle, const ResetType reset_type, const std::string& name="Unknown");
+
+/// Initializes the required variables for timers
+void TimersInit();
+/// Tears down the timer variables
+void TimersShutdown();
+} // namespace