From fc2266130b450952777cd3a9e47adb36960de8e7 Mon Sep 17 00:00:00 2001
From: Subv <subv2112@gmail.com>
Date: Thu, 5 Jan 2017 14:14:22 -0500
Subject: [PATCH] Kernel: Don't attempt to yield execution in SleepThread(0) if
 there are no available threads to run.

With this we avoid an useless temporary deschedule of the current thread.
---
 src/core/hle/kernel/thread.cpp | 4 ++++
 src/core/hle/kernel/thread.h   | 5 +++++
 src/core/hle/svc.cpp           | 5 +++++
 3 files changed, 14 insertions(+)

diff --git a/src/core/hle/kernel/thread.cpp b/src/core/hle/kernel/thread.cpp
index 9109bd10ba..6cd9ff327d 100644
--- a/src/core/hle/kernel/thread.cpp
+++ b/src/core/hle/kernel/thread.cpp
@@ -556,6 +556,10 @@ SharedPtr<Thread> SetupMainThread(u32 entry_point, s32 priority) {
     return thread;
 }
 
+bool HaveReadyThreads() {
+    return ready_queue.get_first() != nullptr;
+}
+
 void Reschedule() {
     PriorityBoostStarvedThreads();
 
diff --git a/src/core/hle/kernel/thread.h b/src/core/hle/kernel/thread.h
index af72b76eab..13a29a0447 100644
--- a/src/core/hle/kernel/thread.h
+++ b/src/core/hle/kernel/thread.h
@@ -218,6 +218,11 @@ private:
  */
 SharedPtr<Thread> SetupMainThread(u32 entry_point, s32 priority);
 
+/**
+ * Returns whether there are any threads that are ready to run.
+ */
+bool HaveReadyThreads();
+
 /**
  * Reschedules to the next available thread (call after current thread is suspended)
  */
diff --git a/src/core/hle/svc.cpp b/src/core/hle/svc.cpp
index 855f3af822..50d35ab97a 100644
--- a/src/core/hle/svc.cpp
+++ b/src/core/hle/svc.cpp
@@ -849,6 +849,11 @@ static ResultCode CancelTimer(Kernel::Handle handle) {
 static void SleepThread(s64 nanoseconds) {
     LOG_TRACE(Kernel_SVC, "called nanoseconds=%lld", nanoseconds);
 
+    // Don't attempt to yield execution if there are no available threads to run,
+    // this way we avoid a useless reschedule to the idle thread.
+    if (nanoseconds == 0 && !Kernel::HaveReadyThreads())
+        return;
+
     // Sleep current thread and check for next thread to schedule
     Kernel::WaitCurrentThread_Sleep();