Scheduler.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/QuickSort.h>
  27. #include <AK/ScopeGuard.h>
  28. #include <AK/TemporaryChange.h>
  29. #include <AK/Time.h>
  30. #include <Kernel/FileSystem/FileDescription.h>
  31. #include <Kernel/Net/Socket.h>
  32. #include <Kernel/Process.h>
  33. #include <Kernel/Profiling.h>
  34. #include <Kernel/RTC.h>
  35. #include <Kernel/Scheduler.h>
  36. #include <Kernel/Time/TimeManagement.h>
  37. #include <Kernel/TimerQueue.h>
  38. //#define LOG_EVERY_CONTEXT_SWITCH
  39. //#define SCHEDULER_DEBUG
  40. //#define SCHEDULER_RUNNABLE_DEBUG
  41. namespace Kernel {
  42. class SchedulerPerProcessorData {
  43. AK_MAKE_NONCOPYABLE(SchedulerPerProcessorData);
  44. AK_MAKE_NONMOVABLE(SchedulerPerProcessorData);
  45. public:
  46. SchedulerPerProcessorData() = default;
  47. Thread* m_pending_beneficiary { nullptr };
  48. const char* m_pending_donate_reason { nullptr };
  49. bool m_in_scheduler { true };
  50. };
  51. SchedulerData* g_scheduler_data;
  52. timeval g_timeofday;
  53. RecursiveSpinLock g_scheduler_lock;
  54. void Scheduler::init_thread(Thread& thread)
  55. {
  56. ASSERT(g_scheduler_data);
  57. g_scheduler_data->m_nonrunnable_threads.append(thread);
  58. }
  59. static u32 time_slice_for(const Thread& thread)
  60. {
  61. // One time slice unit == 1ms
  62. if (&thread == Processor::current().idle_thread())
  63. return 1;
  64. return 10;
  65. }
  66. timeval Scheduler::time_since_boot()
  67. {
  68. return { TimeManagement::the().seconds_since_boot(), (suseconds_t)TimeManagement::the().ticks_this_second() * 1000 };
  69. }
  70. Thread* g_finalizer;
  71. WaitQueue* g_finalizer_wait_queue;
  72. Atomic<bool> g_finalizer_has_work { false };
  73. static Process* s_colonel_process;
  74. u64 g_uptime;
  75. Thread::JoinBlocker::JoinBlocker(Thread& joinee, void*& joinee_exit_value)
  76. : m_joinee(joinee)
  77. , m_joinee_exit_value(joinee_exit_value)
  78. {
  79. ASSERT(m_joinee.m_joiner == nullptr);
  80. auto current_thread = Thread::current();
  81. m_joinee.m_joiner = current_thread;
  82. current_thread->m_joinee = &joinee;
  83. }
  84. bool Thread::JoinBlocker::should_unblock(Thread& joiner)
  85. {
  86. return !joiner.m_joinee;
  87. }
  88. Thread::FileDescriptionBlocker::FileDescriptionBlocker(const FileDescription& description)
  89. : m_blocked_description(description)
  90. {
  91. }
  92. const FileDescription& Thread::FileDescriptionBlocker::blocked_description() const
  93. {
  94. return m_blocked_description;
  95. }
  96. Thread::AcceptBlocker::AcceptBlocker(const FileDescription& description)
  97. : FileDescriptionBlocker(description)
  98. {
  99. }
  100. bool Thread::AcceptBlocker::should_unblock(Thread&)
  101. {
  102. auto& socket = *blocked_description().socket();
  103. return socket.can_accept();
  104. }
  105. Thread::ConnectBlocker::ConnectBlocker(const FileDescription& description)
  106. : FileDescriptionBlocker(description)
  107. {
  108. }
  109. bool Thread::ConnectBlocker::should_unblock(Thread&)
  110. {
  111. auto& socket = *blocked_description().socket();
  112. return socket.setup_state() == Socket::SetupState::Completed;
  113. }
  114. Thread::WriteBlocker::WriteBlocker(const FileDescription& description)
  115. : FileDescriptionBlocker(description)
  116. {
  117. }
  118. timespec* Thread::WriteBlocker::override_timeout(timespec* timeout)
  119. {
  120. auto& description = blocked_description();
  121. if (description.is_socket()) {
  122. auto& socket = *description.socket();
  123. if (socket.has_send_timeout()) {
  124. timeval_to_timespec(Scheduler::time_since_boot(), m_deadline);
  125. timespec_add_timeval(m_deadline, socket.send_timeout(), m_deadline);
  126. if (!timeout || m_deadline < *timeout)
  127. return &m_deadline;
  128. }
  129. }
  130. return timeout;
  131. }
  132. bool Thread::WriteBlocker::should_unblock(Thread&)
  133. {
  134. return blocked_description().can_write();
  135. }
  136. Thread::ReadBlocker::ReadBlocker(const FileDescription& description)
  137. : FileDescriptionBlocker(description)
  138. {
  139. }
  140. timespec* Thread::ReadBlocker::override_timeout(timespec* timeout)
  141. {
  142. auto& description = blocked_description();
  143. if (description.is_socket()) {
  144. auto& socket = *description.socket();
  145. if (socket.has_receive_timeout()) {
  146. timeval_to_timespec(Scheduler::time_since_boot(), m_deadline);
  147. timespec_add_timeval(m_deadline, socket.receive_timeout(), m_deadline);
  148. if (!timeout || m_deadline < *timeout)
  149. return &m_deadline;
  150. }
  151. }
  152. return timeout;
  153. }
  154. bool Thread::ReadBlocker::should_unblock(Thread&)
  155. {
  156. return blocked_description().can_read();
  157. }
  158. Thread::ConditionBlocker::ConditionBlocker(const char* state_string, Function<bool()>&& condition)
  159. : m_block_until_condition(move(condition))
  160. , m_state_string(state_string)
  161. {
  162. ASSERT(m_block_until_condition);
  163. }
  164. bool Thread::ConditionBlocker::should_unblock(Thread&)
  165. {
  166. return m_block_until_condition();
  167. }
  168. Thread::SleepBlocker::SleepBlocker(u64 wakeup_time)
  169. : m_wakeup_time(wakeup_time)
  170. {
  171. }
  172. bool Thread::SleepBlocker::should_unblock(Thread&)
  173. {
  174. return m_wakeup_time <= g_uptime;
  175. }
  176. Thread::SelectBlocker::SelectBlocker(const FDVector& read_fds, const FDVector& write_fds, const FDVector& except_fds)
  177. : m_select_read_fds(read_fds)
  178. , m_select_write_fds(write_fds)
  179. , m_select_exceptional_fds(except_fds)
  180. {
  181. }
  182. bool Thread::SelectBlocker::should_unblock(Thread& thread)
  183. {
  184. auto& process = thread.process();
  185. for (int fd : m_select_read_fds) {
  186. if (!process.m_fds[fd])
  187. continue;
  188. if (process.m_fds[fd].description()->can_read())
  189. return true;
  190. }
  191. for (int fd : m_select_write_fds) {
  192. if (!process.m_fds[fd])
  193. continue;
  194. if (process.m_fds[fd].description()->can_write())
  195. return true;
  196. }
  197. return false;
  198. }
  199. Thread::WaitBlocker::WaitBlocker(int wait_options, ProcessID& waitee_pid)
  200. : m_wait_options(wait_options)
  201. , m_waitee_pid(waitee_pid)
  202. {
  203. }
  204. bool Thread::WaitBlocker::should_unblock(Thread& thread)
  205. {
  206. bool should_unblock = m_wait_options & WNOHANG;
  207. if (m_waitee_pid != -1) {
  208. auto peer = Process::from_pid(m_waitee_pid);
  209. if (!peer)
  210. return true;
  211. }
  212. thread.process().for_each_child([&](Process& child) {
  213. if (m_waitee_pid != -1 && m_waitee_pid != child.pid())
  214. return IterationDecision::Continue;
  215. bool child_exited = child.is_dead();
  216. bool child_stopped = false;
  217. if (child.thread_count()) {
  218. child.for_each_thread([&](auto& child_thread) {
  219. if (child_thread.state() == Thread::State::Stopped && !child_thread.has_pending_signal(SIGCONT)) {
  220. child_stopped = true;
  221. return IterationDecision::Break;
  222. }
  223. return IterationDecision::Continue;
  224. });
  225. }
  226. bool fits_the_spec = ((m_wait_options & WEXITED) && child_exited)
  227. || ((m_wait_options & WSTOPPED) && child_stopped);
  228. if (!fits_the_spec)
  229. return IterationDecision::Continue;
  230. m_waitee_pid = child.pid();
  231. should_unblock = true;
  232. return IterationDecision::Break;
  233. });
  234. return should_unblock;
  235. }
  236. Thread::SemiPermanentBlocker::SemiPermanentBlocker(Reason reason)
  237. : m_reason(reason)
  238. {
  239. }
  240. bool Thread::SemiPermanentBlocker::should_unblock(Thread&)
  241. {
  242. // someone else has to unblock us
  243. return false;
  244. }
  245. // Called by the scheduler on threads that are blocked for some reason.
  246. // Make a decision as to whether to unblock them or not.
  247. void Thread::consider_unblock(time_t now_sec, long now_usec)
  248. {
  249. ScopedSpinLock lock(m_lock);
  250. switch (state()) {
  251. case Thread::Invalid:
  252. case Thread::Runnable:
  253. case Thread::Running:
  254. case Thread::Dead:
  255. case Thread::Stopped:
  256. case Thread::Queued:
  257. case Thread::Dying:
  258. /* don't know, don't care */
  259. return;
  260. case Thread::Blocked: {
  261. ASSERT(m_blocker != nullptr);
  262. timespec now;
  263. now.tv_sec = now_sec,
  264. now.tv_nsec = now_usec * 1000ull;
  265. bool timed_out = m_blocker_timeout && now >= *m_blocker_timeout;
  266. if (timed_out || m_blocker->should_unblock(*this))
  267. unblock();
  268. return;
  269. }
  270. }
  271. }
  272. void Scheduler::start()
  273. {
  274. ASSERT_INTERRUPTS_DISABLED();
  275. // We need to acquire our scheduler lock, which will be released
  276. // by the idle thread once control transferred there
  277. g_scheduler_lock.lock();
  278. auto& processor = Processor::current();
  279. processor.set_scheduler_data(*new SchedulerPerProcessorData());
  280. ASSERT(processor.is_initialized());
  281. auto& idle_thread = *processor.idle_thread();
  282. ASSERT(processor.current_thread() == &idle_thread);
  283. ASSERT(processor.idle_thread() == &idle_thread);
  284. idle_thread.set_ticks_left(time_slice_for(idle_thread));
  285. idle_thread.did_schedule();
  286. idle_thread.set_initialized(true);
  287. processor.init_context(idle_thread, false);
  288. idle_thread.set_state(Thread::Running);
  289. ASSERT(idle_thread.affinity() == (1u << processor.id()));
  290. processor.initialize_context_switching(idle_thread);
  291. ASSERT_NOT_REACHED();
  292. }
  293. bool Scheduler::pick_next()
  294. {
  295. ASSERT_INTERRUPTS_DISABLED();
  296. auto current_thread = Thread::current();
  297. auto now = time_since_boot();
  298. auto now_sec = now.tv_sec;
  299. auto now_usec = now.tv_usec;
  300. // Set the m_in_scheduler flag before acquiring the spinlock. This
  301. // prevents a recursive call into Scheduler::invoke_async upon
  302. // leaving the scheduler lock.
  303. ScopedCritical critical;
  304. auto& scheduler_data = Processor::current().get_scheduler_data();
  305. scheduler_data.m_in_scheduler = true;
  306. ScopeGuard guard(
  307. []() {
  308. // We may be on a different processor after we got switched
  309. // back to this thread!
  310. auto& scheduler_data = Processor::current().get_scheduler_data();
  311. ASSERT(scheduler_data.m_in_scheduler);
  312. scheduler_data.m_in_scheduler = false;
  313. });
  314. ScopedSpinLock lock(g_scheduler_lock);
  315. if (current_thread->should_die() && current_thread->state() == Thread::Running) {
  316. // Rather than immediately killing threads, yanking the kernel stack
  317. // away from them (which can lead to e.g. reference leaks), we always
  318. // allow Thread::wait_on to return. This allows the kernel stack to
  319. // clean up and eventually we'll get here shortly before transitioning
  320. // back to user mode (from Processor::exit_trap). At this point we
  321. // no longer want to schedule this thread. We can't wait until
  322. // Scheduler::enter_current because we don't want to allow it to
  323. // transition back to user mode.
  324. #ifdef SCHEDULER_DEBUG
  325. dbg() << "Scheduler[" << Processor::current().id() << "]: Thread " << *current_thread << " is dying";
  326. #endif
  327. current_thread->set_state(Thread::Dying);
  328. }
  329. // Check and unblock threads whose wait conditions have been met.
  330. Scheduler::for_each_nonrunnable([&](Thread& thread) {
  331. thread.consider_unblock(now_sec, now_usec);
  332. return IterationDecision::Continue;
  333. });
  334. Process::for_each([&](Process& process) {
  335. if (process.is_dead()) {
  336. if (current_thread->process().pid() != process.pid() && (!process.ppid() || !Process::from_pid(process.ppid()))) {
  337. auto name = process.name();
  338. auto pid = process.pid();
  339. auto exit_status = Process::reap(process);
  340. dbg() << "Scheduler[" << Processor::current().id() << "]: Reaped unparented process " << name << "(" << pid.value() << "), exit status: " << exit_status.si_status;
  341. }
  342. return IterationDecision::Continue;
  343. }
  344. if (process.m_alarm_deadline && g_uptime > process.m_alarm_deadline) {
  345. process.m_alarm_deadline = 0;
  346. // FIXME: Should we observe this signal somehow?
  347. (void)process.send_signal(SIGALRM, nullptr);
  348. }
  349. return IterationDecision::Continue;
  350. });
  351. // Dispatch any pending signals.
  352. Thread::for_each_living([&](Thread& thread) -> IterationDecision {
  353. ScopedSpinLock lock(thread.get_lock());
  354. if (!thread.has_unmasked_pending_signals())
  355. return IterationDecision::Continue;
  356. // NOTE: dispatch_one_pending_signal() may unblock the process.
  357. bool was_blocked = thread.is_blocked();
  358. if (thread.dispatch_one_pending_signal() == ShouldUnblockThread::No)
  359. return IterationDecision::Continue;
  360. if (was_blocked) {
  361. #ifdef SCHEDULER_DEBUG
  362. dbg() << "Scheduler[" << Processor::current().id() << "]:Unblock " << thread << " due to signal";
  363. #endif
  364. ASSERT(thread.m_blocker != nullptr);
  365. thread.m_blocker->set_interrupted_by_signal();
  366. thread.unblock();
  367. }
  368. return IterationDecision::Continue;
  369. });
  370. #ifdef SCHEDULER_RUNNABLE_DEBUG
  371. dbg() << "Non-runnables:";
  372. Scheduler::for_each_nonrunnable([](Thread& thread) -> IterationDecision {
  373. if (thread.state() == Thread::Queued)
  374. dbg() << " " << String::format("%-12s", thread.state_string()) << " " << thread << " @ " << String::format("%w", thread.tss().cs) << ":" << String::format("%x", thread.tss().eip) << " Reason: " << (thread.wait_reason() ? thread.wait_reason() : "none");
  375. else if (thread.state() == Thread::Dying)
  376. dbg() << " " << String::format("%-12s", thread.state_string()) << " " << thread << " @ " << String::format("%w", thread.tss().cs) << ":" << String::format("%x", thread.tss().eip) << " Finalizable: " << thread.is_finalizable();
  377. else
  378. dbg() << " " << String::format("%-12s", thread.state_string()) << " " << thread << " @ " << String::format("%w", thread.tss().cs) << ":" << String::format("%x", thread.tss().eip);
  379. return IterationDecision::Continue;
  380. });
  381. dbg() << "Runnables:";
  382. Scheduler::for_each_runnable([](Thread& thread) -> IterationDecision {
  383. dbg() << " " << String::format("%3u", thread.effective_priority()) << "/" << String::format("%2u", thread.priority()) << " " << String::format("%-12s", thread.state_string()) << " " << thread << " @ " << String::format("%w", thread.tss().cs) << ":" << String::format("%x", thread.tss().eip);
  384. return IterationDecision::Continue;
  385. });
  386. #endif
  387. Thread* thread_to_schedule = nullptr;
  388. Vector<Thread*, 128> sorted_runnables;
  389. for_each_runnable([&](auto& thread) {
  390. if ((thread.affinity() & (1u << Processor::current().id())) != 0)
  391. sorted_runnables.append(&thread);
  392. if (&thread == scheduler_data.m_pending_beneficiary) {
  393. thread_to_schedule = &thread;
  394. return IterationDecision::Break;
  395. }
  396. return IterationDecision::Continue;
  397. });
  398. if (thread_to_schedule) {
  399. // The thread we're supposed to donate to still exists
  400. const char* reason = scheduler_data.m_pending_donate_reason;
  401. scheduler_data.m_pending_beneficiary = nullptr;
  402. scheduler_data.m_pending_donate_reason = nullptr;
  403. // We need to leave our first critical section before switching context,
  404. // but since we're still holding the scheduler lock we're still in a critical section
  405. critical.leave();
  406. #ifdef SCHEDULER_DEBUG
  407. dbg() << "Processing pending donate to " << *thread_to_schedule << " reason=" << reason;
  408. #endif
  409. return donate_to_and_switch(thread_to_schedule, reason);
  410. }
  411. // Either we're not donating or the beneficiary disappeared.
  412. // Either way clear any pending information
  413. scheduler_data.m_pending_beneficiary = nullptr;
  414. scheduler_data.m_pending_donate_reason = nullptr;
  415. quick_sort(sorted_runnables, [](auto& a, auto& b) { return a->effective_priority() >= b->effective_priority(); });
  416. for (auto* thread : sorted_runnables) {
  417. if (thread->process().exec_tid() && thread->process().exec_tid() != thread->tid())
  418. continue;
  419. ASSERT(thread->state() == Thread::Runnable || thread->state() == Thread::Running);
  420. if (!thread_to_schedule) {
  421. thread->m_extra_priority = 0;
  422. thread_to_schedule = thread;
  423. } else {
  424. thread->m_extra_priority++;
  425. }
  426. }
  427. if (!thread_to_schedule)
  428. thread_to_schedule = Processor::current().idle_thread();
  429. #ifdef SCHEDULER_DEBUG
  430. dbg() << "Scheduler[" << Processor::current().id() << "]: Switch to " << *thread_to_schedule << " @ " << String::format("%04x:%08x", thread_to_schedule->tss().cs, thread_to_schedule->tss().eip);
  431. #endif
  432. // We need to leave our first critical section before switching context,
  433. // but since we're still holding the scheduler lock we're still in a critical section
  434. critical.leave();
  435. return context_switch(thread_to_schedule);
  436. }
  437. bool Scheduler::yield()
  438. {
  439. InterruptDisabler disabler;
  440. auto& proc = Processor::current();
  441. auto& scheduler_data = proc.get_scheduler_data();
  442. // Clear any pending beneficiary
  443. scheduler_data.m_pending_beneficiary = nullptr;
  444. scheduler_data.m_pending_donate_reason = nullptr;
  445. auto current_thread = Thread::current();
  446. #ifdef SCHEDULER_DEBUG
  447. dbg() << "Scheduler[" << proc.id() << "]: yielding thread " << *current_thread << " in_irq: " << proc.in_irq();
  448. #endif
  449. ASSERT(current_thread != nullptr);
  450. if (proc.in_irq() || proc.in_critical()) {
  451. // If we're handling an IRQ we can't switch context, or we're in
  452. // a critical section where we don't want to switch contexts, then
  453. // delay until exiting the trap or critical section
  454. proc.invoke_scheduler_async();
  455. return false;
  456. }
  457. if (!Scheduler::pick_next())
  458. return false;
  459. #ifdef SCHEDULER_DEBUG
  460. dbg() << "Scheduler[" << Processor::current().id() << "]: yield returns to thread " << *current_thread << " in_irq: " << Processor::current().in_irq();
  461. #endif
  462. return true;
  463. }
  464. bool Scheduler::donate_to_and_switch(Thread* beneficiary, const char* reason)
  465. {
  466. ASSERT(g_scheduler_lock.own_lock());
  467. auto& proc = Processor::current();
  468. ASSERT(proc.in_critical() == 1);
  469. (void)reason;
  470. unsigned ticks_left = Thread::current()->ticks_left();
  471. if (!beneficiary || beneficiary->state() != Thread::Runnable || ticks_left <= 1)
  472. return Scheduler::yield();
  473. unsigned ticks_to_donate = min(ticks_left - 1, time_slice_for(*beneficiary));
  474. #ifdef SCHEDULER_DEBUG
  475. dbg() << "Scheduler[" << proc.id() << "]: Donating " << ticks_to_donate << " ticks to " << *beneficiary << ", reason=" << reason;
  476. #endif
  477. beneficiary->set_ticks_left(ticks_to_donate);
  478. return Scheduler::context_switch(beneficiary);
  479. }
  480. bool Scheduler::donate_to(Thread* beneficiary, const char* reason)
  481. {
  482. ASSERT(beneficiary);
  483. if (beneficiary == Thread::current())
  484. return Scheduler::yield();
  485. // Set the m_in_scheduler flag before acquiring the spinlock. This
  486. // prevents a recursive call into Scheduler::invoke_async upon
  487. // leaving the scheduler lock.
  488. ScopedCritical critical;
  489. auto& proc = Processor::current();
  490. auto& scheduler_data = proc.get_scheduler_data();
  491. scheduler_data.m_in_scheduler = true;
  492. ScopeGuard guard(
  493. []() {
  494. // We may be on a different processor after we got switched
  495. // back to this thread!
  496. auto& scheduler_data = Processor::current().get_scheduler_data();
  497. ASSERT(scheduler_data.m_in_scheduler);
  498. scheduler_data.m_in_scheduler = false;
  499. });
  500. ASSERT(!proc.in_irq());
  501. if (proc.in_critical() > 1) {
  502. scheduler_data.m_pending_beneficiary = beneficiary; // Save the beneficiary
  503. scheduler_data.m_pending_donate_reason = reason;
  504. proc.invoke_scheduler_async();
  505. return false;
  506. }
  507. ScopedSpinLock lock(g_scheduler_lock);
  508. // "Leave" the critical section before switching context. Since we
  509. // still hold the scheduler lock, we're not actually leaving it.
  510. // Processor::switch_context expects Processor::in_critical() to be 1
  511. critical.leave();
  512. donate_to_and_switch(beneficiary, reason);
  513. return false;
  514. }
  515. bool Scheduler::context_switch(Thread* thread)
  516. {
  517. thread->set_ticks_left(time_slice_for(*thread));
  518. thread->did_schedule();
  519. auto from_thread = Thread::current();
  520. if (from_thread == thread)
  521. return false;
  522. if (from_thread) {
  523. // If the last process hasn't blocked (still marked as running),
  524. // mark it as runnable for the next round.
  525. if (from_thread->state() == Thread::Running)
  526. from_thread->set_state(Thread::Runnable);
  527. #ifdef LOG_EVERY_CONTEXT_SWITCH
  528. dbg() << "Scheduler[" << Processor::current().id() << "]: " << *from_thread << " -> " << *thread << " [" << thread->priority() << "] " << String::format("%w", thread->tss().cs) << ":" << String::format("%x", thread->tss().eip);
  529. #endif
  530. }
  531. auto& proc = Processor::current();
  532. if (!thread->is_initialized()) {
  533. proc.init_context(*thread, false);
  534. thread->set_initialized(true);
  535. }
  536. thread->set_state(Thread::Running);
  537. // Mark it as active because we are using this thread. This is similar
  538. // to comparing it with Processor::current_thread, but when there are
  539. // multiple processors there's no easy way to check whether the thread
  540. // is actually still needed. This prevents accidental finalization when
  541. // a thread is no longer in Running state, but running on another core.
  542. thread->set_active(true);
  543. proc.switch_context(from_thread, thread);
  544. // NOTE: from_thread at this point reflects the thread we were
  545. // switched from, and thread reflects Thread::current()
  546. enter_current(*from_thread);
  547. ASSERT(thread == Thread::current());
  548. return true;
  549. }
  550. void Scheduler::enter_current(Thread& prev_thread)
  551. {
  552. ASSERT(g_scheduler_lock.is_locked());
  553. prev_thread.set_active(false);
  554. if (prev_thread.state() == Thread::Dying) {
  555. // If the thread we switched from is marked as dying, then notify
  556. // the finalizer. Note that as soon as we leave the scheduler lock
  557. // the finalizer may free from_thread!
  558. notify_finalizer();
  559. }
  560. }
  561. void Scheduler::leave_on_first_switch(u32 flags)
  562. {
  563. // This is called when a thread is swiched into for the first time.
  564. // At this point, enter_current has already be called, but because
  565. // Scheduler::context_switch is not in the call stack we need to
  566. // clean up and release locks manually here
  567. g_scheduler_lock.unlock(flags);
  568. auto& scheduler_data = Processor::current().get_scheduler_data();
  569. ASSERT(scheduler_data.m_in_scheduler);
  570. scheduler_data.m_in_scheduler = false;
  571. }
  572. void Scheduler::prepare_after_exec()
  573. {
  574. // This is called after exec() when doing a context "switch" into
  575. // the new process. This is called from Processor::assume_context
  576. ASSERT(g_scheduler_lock.own_lock());
  577. auto& scheduler_data = Processor::current().get_scheduler_data();
  578. ASSERT(!scheduler_data.m_in_scheduler);
  579. scheduler_data.m_in_scheduler = true;
  580. }
  581. void Scheduler::prepare_for_idle_loop()
  582. {
  583. // This is called when the CPU finished setting up the idle loop
  584. // and is about to run it. We need to acquire he scheduler lock
  585. ASSERT(!g_scheduler_lock.own_lock());
  586. g_scheduler_lock.lock();
  587. auto& scheduler_data = Processor::current().get_scheduler_data();
  588. ASSERT(!scheduler_data.m_in_scheduler);
  589. scheduler_data.m_in_scheduler = true;
  590. }
  591. Process* Scheduler::colonel()
  592. {
  593. ASSERT(s_colonel_process);
  594. return s_colonel_process;
  595. }
  596. void Scheduler::initialize()
  597. {
  598. ASSERT(&Processor::current() != nullptr); // sanity check
  599. Thread* idle_thread = nullptr;
  600. g_scheduler_data = new SchedulerData;
  601. g_finalizer_wait_queue = new WaitQueue;
  602. g_finalizer_has_work.store(false, AK::MemoryOrder::memory_order_release);
  603. s_colonel_process = &Process::create_kernel_process(idle_thread, "colonel", idle_loop, 1).leak_ref();
  604. ASSERT(s_colonel_process);
  605. ASSERT(idle_thread);
  606. idle_thread->set_priority(THREAD_PRIORITY_MIN);
  607. idle_thread->set_name(StringView("idle thread #0"));
  608. set_idle_thread(idle_thread);
  609. }
  610. void Scheduler::set_idle_thread(Thread* idle_thread)
  611. {
  612. Processor::current().set_idle_thread(*idle_thread);
  613. Processor::current().set_current_thread(*idle_thread);
  614. }
  615. Thread* Scheduler::create_ap_idle_thread(u32 cpu)
  616. {
  617. ASSERT(cpu != 0);
  618. // This function is called on the bsp, but creates an idle thread for another AP
  619. ASSERT(Processor::current().id() == 0);
  620. ASSERT(s_colonel_process);
  621. Thread* idle_thread = s_colonel_process->create_kernel_thread(idle_loop, THREAD_PRIORITY_MIN, String::format("idle thread #%u", cpu), 1 << cpu, false);
  622. ASSERT(idle_thread);
  623. return idle_thread;
  624. }
  625. void Scheduler::timer_tick(const RegisterState& regs)
  626. {
  627. ASSERT_INTERRUPTS_DISABLED();
  628. ASSERT(Processor::current().in_irq());
  629. if (Processor::current().id() > 0)
  630. return;
  631. auto current_thread = Processor::current().current_thread();
  632. if (!current_thread)
  633. return;
  634. ++g_uptime;
  635. g_timeofday = TimeManagement::now_as_timeval();
  636. if (current_thread->process().is_profiling()) {
  637. SmapDisabler disabler;
  638. auto backtrace = current_thread->raw_backtrace(regs.ebp, regs.eip);
  639. auto& sample = Profiling::next_sample_slot();
  640. sample.pid = current_thread->process().pid();
  641. sample.tid = current_thread->tid();
  642. sample.timestamp = g_uptime;
  643. for (size_t i = 0; i < min(backtrace.size(), Profiling::max_stack_frame_count); ++i) {
  644. sample.frames[i] = backtrace[i];
  645. }
  646. }
  647. TimerQueue::the().fire();
  648. if (current_thread->tick())
  649. return;
  650. ASSERT_INTERRUPTS_DISABLED();
  651. ASSERT(Processor::current().in_irq());
  652. Processor::current().invoke_scheduler_async();
  653. }
  654. void Scheduler::invoke_async()
  655. {
  656. ASSERT_INTERRUPTS_DISABLED();
  657. auto& proc = Processor::current();
  658. ASSERT(!proc.in_irq());
  659. // Since this function is called when leaving critical sections (such
  660. // as a SpinLock), we need to check if we're not already doing this
  661. // to prevent recursion
  662. if (!proc.get_scheduler_data().m_in_scheduler)
  663. pick_next();
  664. }
  665. void Scheduler::notify_finalizer()
  666. {
  667. if (g_finalizer_has_work.exchange(true, AK::MemoryOrder::memory_order_acq_rel) == false)
  668. g_finalizer_wait_queue->wake_all();
  669. }
  670. void Scheduler::idle_loop()
  671. {
  672. dbg() << "Scheduler[" << Processor::current().id() << "]: idle loop running";
  673. ASSERT(are_interrupts_enabled());
  674. for (;;) {
  675. asm("hlt");
  676. if (Processor::current().id() == 0)
  677. yield();
  678. }
  679. }
  680. }