Scheduler.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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. bool m_in_scheduler { true };
  48. };
  49. SchedulerData* g_scheduler_data;
  50. timeval g_timeofday;
  51. RecursiveSpinLock g_scheduler_lock;
  52. void Scheduler::init_thread(Thread& thread)
  53. {
  54. ASSERT(g_scheduler_data);
  55. g_scheduler_data->m_nonrunnable_threads.append(thread);
  56. }
  57. static u32 time_slice_for(const Thread& thread)
  58. {
  59. // One time slice unit == 1ms
  60. if (&thread == Processor::current().idle_thread())
  61. return 1;
  62. return 10;
  63. }
  64. timeval Scheduler::time_since_boot()
  65. {
  66. return { TimeManagement::the().seconds_since_boot(), (suseconds_t)TimeManagement::the().ticks_this_second() * 1000 };
  67. }
  68. Thread* g_finalizer;
  69. WaitQueue* g_finalizer_wait_queue;
  70. Atomic<bool> g_finalizer_has_work { false };
  71. static Process* s_colonel_process;
  72. u64 g_uptime;
  73. Thread::JoinBlocker::JoinBlocker(Thread& joinee, void*& joinee_exit_value)
  74. : m_joinee(joinee)
  75. , m_joinee_exit_value(joinee_exit_value)
  76. {
  77. ASSERT(m_joinee.m_joiner == nullptr);
  78. auto current_thread = Thread::current();
  79. m_joinee.m_joiner = current_thread;
  80. current_thread->m_joinee = &joinee;
  81. }
  82. bool Thread::JoinBlocker::should_unblock(Thread& joiner)
  83. {
  84. return !joiner.m_joinee;
  85. }
  86. Thread::FileDescriptionBlocker::FileDescriptionBlocker(const FileDescription& description)
  87. : m_blocked_description(description)
  88. {
  89. }
  90. const FileDescription& Thread::FileDescriptionBlocker::blocked_description() const
  91. {
  92. return m_blocked_description;
  93. }
  94. Thread::AcceptBlocker::AcceptBlocker(const FileDescription& description)
  95. : FileDescriptionBlocker(description)
  96. {
  97. }
  98. bool Thread::AcceptBlocker::should_unblock(Thread&)
  99. {
  100. auto& socket = *blocked_description().socket();
  101. return socket.can_accept();
  102. }
  103. Thread::ConnectBlocker::ConnectBlocker(const FileDescription& description)
  104. : FileDescriptionBlocker(description)
  105. {
  106. }
  107. bool Thread::ConnectBlocker::should_unblock(Thread&)
  108. {
  109. auto& socket = *blocked_description().socket();
  110. return socket.setup_state() == Socket::SetupState::Completed;
  111. }
  112. Thread::WriteBlocker::WriteBlocker(const FileDescription& description)
  113. : FileDescriptionBlocker(description)
  114. {
  115. }
  116. timespec* Thread::WriteBlocker::override_timeout(timespec* timeout)
  117. {
  118. auto& description = blocked_description();
  119. if (description.is_socket()) {
  120. auto& socket = *description.socket();
  121. if (socket.has_send_timeout()) {
  122. timeval_to_timespec(Scheduler::time_since_boot(), m_deadline);
  123. timespec_add_timeval(m_deadline, socket.send_timeout(), m_deadline);
  124. if (!timeout || m_deadline < *timeout)
  125. return &m_deadline;
  126. }
  127. }
  128. return timeout;
  129. }
  130. bool Thread::WriteBlocker::should_unblock(Thread&)
  131. {
  132. return blocked_description().can_write();
  133. }
  134. Thread::ReadBlocker::ReadBlocker(const FileDescription& description)
  135. : FileDescriptionBlocker(description)
  136. {
  137. }
  138. timespec* Thread::ReadBlocker::override_timeout(timespec* timeout)
  139. {
  140. auto& description = blocked_description();
  141. if (description.is_socket()) {
  142. auto& socket = *description.socket();
  143. if (socket.has_receive_timeout()) {
  144. timeval_to_timespec(Scheduler::time_since_boot(), m_deadline);
  145. timespec_add_timeval(m_deadline, socket.receive_timeout(), m_deadline);
  146. if (!timeout || m_deadline < *timeout)
  147. return &m_deadline;
  148. }
  149. }
  150. return timeout;
  151. }
  152. bool Thread::ReadBlocker::should_unblock(Thread&)
  153. {
  154. return blocked_description().can_read();
  155. }
  156. Thread::ConditionBlocker::ConditionBlocker(const char* state_string, Function<bool()>&& condition)
  157. : m_block_until_condition(move(condition))
  158. , m_state_string(state_string)
  159. {
  160. ASSERT(m_block_until_condition);
  161. }
  162. bool Thread::ConditionBlocker::should_unblock(Thread&)
  163. {
  164. return m_block_until_condition();
  165. }
  166. Thread::SleepBlocker::SleepBlocker(u64 wakeup_time)
  167. : m_wakeup_time(wakeup_time)
  168. {
  169. }
  170. bool Thread::SleepBlocker::should_unblock(Thread&)
  171. {
  172. return m_wakeup_time <= g_uptime;
  173. }
  174. Thread::SelectBlocker::SelectBlocker(const FDVector& read_fds, const FDVector& write_fds, const FDVector& except_fds)
  175. : m_select_read_fds(read_fds)
  176. , m_select_write_fds(write_fds)
  177. , m_select_exceptional_fds(except_fds)
  178. {
  179. }
  180. bool Thread::SelectBlocker::should_unblock(Thread& thread)
  181. {
  182. auto& process = thread.process();
  183. for (int fd : m_select_read_fds) {
  184. if (!process.m_fds[fd])
  185. continue;
  186. if (process.m_fds[fd].description()->can_read())
  187. return true;
  188. }
  189. for (int fd : m_select_write_fds) {
  190. if (!process.m_fds[fd])
  191. continue;
  192. if (process.m_fds[fd].description()->can_write())
  193. return true;
  194. }
  195. return false;
  196. }
  197. Thread::WaitBlocker::WaitBlocker(int wait_options, pid_t& waitee_pid)
  198. : m_wait_options(wait_options)
  199. , m_waitee_pid(waitee_pid)
  200. {
  201. }
  202. bool Thread::WaitBlocker::should_unblock(Thread& thread)
  203. {
  204. bool should_unblock = m_wait_options & WNOHANG;
  205. if (m_waitee_pid != -1) {
  206. auto peer = Process::from_pid(m_waitee_pid);
  207. if (!peer)
  208. return true;
  209. }
  210. thread.process().for_each_child([&](Process& child) {
  211. if (m_waitee_pid != -1 && m_waitee_pid != child.pid())
  212. return IterationDecision::Continue;
  213. bool child_exited = child.is_dead();
  214. bool child_stopped = false;
  215. if (child.thread_count()) {
  216. child.for_each_thread([&](auto& child_thread) {
  217. if (child_thread.state() == Thread::State::Stopped && !child_thread.has_pending_signal(SIGCONT)) {
  218. child_stopped = true;
  219. return IterationDecision::Break;
  220. }
  221. return IterationDecision::Continue;
  222. });
  223. }
  224. bool fits_the_spec = ((m_wait_options & WEXITED) && child_exited)
  225. || ((m_wait_options & WSTOPPED) && child_stopped);
  226. if (!fits_the_spec)
  227. return IterationDecision::Continue;
  228. m_waitee_pid = child.pid();
  229. should_unblock = true;
  230. return IterationDecision::Break;
  231. });
  232. return should_unblock;
  233. }
  234. Thread::SemiPermanentBlocker::SemiPermanentBlocker(Reason reason)
  235. : m_reason(reason)
  236. {
  237. }
  238. bool Thread::SemiPermanentBlocker::should_unblock(Thread&)
  239. {
  240. // someone else has to unblock us
  241. return false;
  242. }
  243. // Called by the scheduler on threads that are blocked for some reason.
  244. // Make a decision as to whether to unblock them or not.
  245. void Thread::consider_unblock(time_t now_sec, long now_usec)
  246. {
  247. ScopedSpinLock lock(m_lock);
  248. switch (state()) {
  249. case Thread::Invalid:
  250. case Thread::Runnable:
  251. case Thread::Running:
  252. case Thread::Dead:
  253. case Thread::Stopped:
  254. case Thread::Queued:
  255. case Thread::Dying:
  256. /* don't know, don't care */
  257. return;
  258. case Thread::Blocked:
  259. {
  260. ASSERT(m_blocker != nullptr);
  261. timespec now;
  262. now.tv_sec = now_sec,
  263. now.tv_nsec = now_usec * 1000ull;
  264. bool timed_out = m_blocker_timeout && now >= *m_blocker_timeout;
  265. if (timed_out || m_blocker->should_unblock(*this))
  266. unblock();
  267. return;
  268. }
  269. case Thread::Skip1SchedulerPass:
  270. set_state(Thread::Skip0SchedulerPasses);
  271. return;
  272. case Thread::Skip0SchedulerPasses:
  273. set_state(Thread::Runnable);
  274. return;
  275. }
  276. }
  277. void Scheduler::start()
  278. {
  279. ASSERT_INTERRUPTS_DISABLED();
  280. // We need to acquire our scheduler lock, which will be released
  281. // by the idle thread once control transferred there
  282. g_scheduler_lock.lock();
  283. auto& processor = Processor::current();
  284. processor.set_scheduler_data(*new SchedulerPerProcessorData());
  285. ASSERT(processor.is_initialized());
  286. auto& idle_thread = *processor.idle_thread();
  287. ASSERT(processor.current_thread() == &idle_thread);
  288. ASSERT(processor.idle_thread() == &idle_thread);
  289. idle_thread.set_ticks_left(time_slice_for(idle_thread));
  290. idle_thread.did_schedule();
  291. idle_thread.set_initialized(true);
  292. processor.init_context(idle_thread, false);
  293. idle_thread.set_state(Thread::Running);
  294. ASSERT(idle_thread.affinity() == (1u << processor.id()));
  295. processor.initialize_context_switching(idle_thread);
  296. ASSERT_NOT_REACHED();
  297. }
  298. bool Scheduler::pick_next()
  299. {
  300. ASSERT_INTERRUPTS_DISABLED();
  301. auto current_thread = Thread::current();
  302. auto now = time_since_boot();
  303. auto now_sec = now.tv_sec;
  304. auto now_usec = now.tv_usec;
  305. // Set the m_in_scheduler flag before acquiring the spinlock. This
  306. // prevents a recursive call into Scheduler::invoke_async upon
  307. // leaving the scheduler lock.
  308. ScopedCritical critical;
  309. Processor::current().get_scheduler_data().m_in_scheduler = true;
  310. ScopeGuard guard(
  311. []() {
  312. // We may be on a different processor after we got switched
  313. // back to this thread!
  314. auto& scheduler_data = Processor::current().get_scheduler_data();
  315. ASSERT(scheduler_data.m_in_scheduler);
  316. scheduler_data.m_in_scheduler = false;
  317. });
  318. ScopedSpinLock lock(g_scheduler_lock);
  319. // Check and unblock threads whose wait conditions have been met.
  320. Scheduler::for_each_nonrunnable([&](Thread& thread) {
  321. thread.consider_unblock(now_sec, now_usec);
  322. return IterationDecision::Continue;
  323. });
  324. Process::for_each([&](Process& process) {
  325. if (process.is_dead()) {
  326. if (current_thread->process().pid() != process.pid() && (!process.ppid() || !Process::from_pid(process.ppid()))) {
  327. auto name = process.name();
  328. auto pid = process.pid();
  329. auto exit_status = Process::reap(process);
  330. dbg() << "Scheduler[" << Processor::current().id() << "]: Reaped unparented process " << name << "(" << pid << "), exit status: " << exit_status.si_status;
  331. }
  332. return IterationDecision::Continue;
  333. }
  334. if (process.m_alarm_deadline && g_uptime > process.m_alarm_deadline) {
  335. process.m_alarm_deadline = 0;
  336. process.send_signal(SIGALRM, nullptr);
  337. }
  338. return IterationDecision::Continue;
  339. });
  340. // Dispatch any pending signals.
  341. Thread::for_each_living([&](Thread& thread) -> IterationDecision {
  342. ScopedSpinLock lock(thread.get_lock());
  343. if (!thread.has_unmasked_pending_signals())
  344. return IterationDecision::Continue;
  345. // NOTE: dispatch_one_pending_signal() may unblock the process.
  346. bool was_blocked = thread.is_blocked();
  347. if (thread.dispatch_one_pending_signal() == ShouldUnblockThread::No)
  348. return IterationDecision::Continue;
  349. if (was_blocked) {
  350. #ifdef SCHEDULER_DEBUG
  351. dbg() << "Scheduler[" << Processor::current().id() << "]:Unblock " << thread << " due to signal";
  352. #endif
  353. ASSERT(thread.m_blocker != nullptr);
  354. thread.m_blocker->set_interrupted_by_signal();
  355. thread.unblock();
  356. }
  357. return IterationDecision::Continue;
  358. });
  359. #ifdef SCHEDULER_RUNNABLE_DEBUG
  360. dbg() << "Non-runnables:";
  361. Scheduler::for_each_nonrunnable([](Thread& thread) -> IterationDecision {
  362. if (thread.state() == Thread::Queued)
  363. 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");
  364. else if (thread.state() == Thread::Dying)
  365. dbg() << " " << String::format("%-12s", thread.state_string()) << " " << thread << " @ " << String::format("%w", thread.tss().cs) << ":" << String::format("%x", thread.tss().eip) << " Finalizable: " << thread.is_finalizable();
  366. else
  367. dbg() << " " << String::format("%-12s", thread.state_string()) << " " << thread << " @ " << String::format("%w", thread.tss().cs) << ":" << String::format("%x", thread.tss().eip);
  368. return IterationDecision::Continue;
  369. });
  370. dbg() << "Runnables:";
  371. Scheduler::for_each_runnable([](Thread& thread) -> IterationDecision {
  372. 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);
  373. return IterationDecision::Continue;
  374. });
  375. #endif
  376. Vector<Thread*, 128> sorted_runnables;
  377. for_each_runnable([&sorted_runnables](auto& thread) {
  378. if ((thread.affinity() & (1u << Processor::current().id())) != 0)
  379. sorted_runnables.append(&thread);
  380. return IterationDecision::Continue;
  381. });
  382. quick_sort(sorted_runnables, [](auto& a, auto& b) { return a->effective_priority() >= b->effective_priority(); });
  383. Thread* thread_to_schedule = nullptr;
  384. for (auto* thread : sorted_runnables) {
  385. if (thread->process().exec_tid() && thread->process().exec_tid() != thread->tid())
  386. continue;
  387. ASSERT(thread->state() == Thread::Runnable || thread->state() == Thread::Running);
  388. if (!thread_to_schedule) {
  389. thread->m_extra_priority = 0;
  390. thread_to_schedule = thread;
  391. } else {
  392. thread->m_extra_priority++;
  393. }
  394. }
  395. if (!thread_to_schedule)
  396. thread_to_schedule = Processor::current().idle_thread();
  397. #ifdef SCHEDULER_DEBUG
  398. dbg() << "Scheduler[" << Processor::current().id() << "]: Switch to " << *thread_to_schedule << " @ " << String::format("%04x:%08x", thread_to_schedule->tss().cs, thread_to_schedule->tss().eip);
  399. #endif
  400. // We need to leave our first critical section before switching context,
  401. // but since we're still holding the scheduler lock we're still in a critical section
  402. critical.leave();
  403. return context_switch(thread_to_schedule);
  404. }
  405. bool Scheduler::yield()
  406. {
  407. InterruptDisabler disabler;
  408. auto& proc = Processor::current();
  409. auto current_thread = Thread::current();
  410. #ifdef SCHEDULER_DEBUG
  411. dbg() << "Scheduler[" << proc.id() << "]: yielding thread " << *current_thread << " in_irq: " << proc.in_irq();
  412. #endif
  413. ASSERT(current_thread != nullptr);
  414. if (proc.in_irq() || proc.in_critical()) {
  415. // If we're handling an IRQ we can't switch context, or we're in
  416. // a critical section where we don't want to switch contexts, then
  417. // delay until exiting the trap or critical section
  418. proc.invoke_scheduler_async();
  419. return false;
  420. }
  421. if (!Scheduler::pick_next())
  422. return false;
  423. #ifdef SCHEDULER_DEBUG
  424. dbg() << "Scheduler[" << Processor::current().id() << "]: yield returns to thread " << *current_thread << " in_irq: " << Processor::current().in_irq();
  425. #endif
  426. return true;
  427. }
  428. bool Scheduler::donate_to(Thread* beneficiary, const char* reason)
  429. {
  430. ASSERT(beneficiary);
  431. // Set the m_in_scheduler flag before acquiring the spinlock. This
  432. // prevents a recursive call into Scheduler::invoke_async upon
  433. // leaving the scheduler lock.
  434. ScopedCritical critical;
  435. auto& proc = Processor::current();
  436. proc.get_scheduler_data().m_in_scheduler = true;
  437. ScopeGuard guard(
  438. []() {
  439. // We may be on a different processor after we got switched
  440. // back to this thread!
  441. auto& scheduler_data = Processor::current().get_scheduler_data();
  442. ASSERT(scheduler_data.m_in_scheduler);
  443. scheduler_data.m_in_scheduler = false;
  444. });
  445. ScopedSpinLock lock(g_scheduler_lock);
  446. ASSERT(!proc.in_irq());
  447. if (proc.in_critical()) {
  448. proc.invoke_scheduler_async();
  449. return false;
  450. }
  451. (void)reason;
  452. unsigned ticks_left = Thread::current()->ticks_left();
  453. if (!beneficiary || beneficiary->state() != Thread::Runnable || ticks_left <= 1)
  454. return Scheduler::yield();
  455. unsigned ticks_to_donate = min(ticks_left - 1, time_slice_for(*beneficiary));
  456. #ifdef SCHEDULER_DEBUG
  457. dbg() << "Scheduler[" << proc.id() << "]: Donating " << ticks_to_donate << " ticks to " << *beneficiary << ", reason=" << reason;
  458. #endif
  459. beneficiary->set_ticks_left(ticks_to_donate);
  460. Scheduler::context_switch(beneficiary);
  461. return false;
  462. }
  463. bool Scheduler::context_switch(Thread* thread)
  464. {
  465. thread->set_ticks_left(time_slice_for(*thread));
  466. thread->did_schedule();
  467. auto from_thread = Thread::current();
  468. if (from_thread == thread)
  469. return false;
  470. if (from_thread) {
  471. // If the last process hasn't blocked (still marked as running),
  472. // mark it as runnable for the next round.
  473. if (from_thread->state() == Thread::Running)
  474. from_thread->set_state(Thread::Runnable);
  475. #ifdef LOG_EVERY_CONTEXT_SWITCH
  476. dbg() << "Scheduler[" << Processor::current().id() << "]: " << *from_thread << " -> " << *thread << " [" << thread->priority() << "] " << String::format("%w", thread->tss().cs) << ":" << String::format("%x", thread->tss().eip);
  477. #endif
  478. }
  479. auto& proc = Processor::current();
  480. if (!thread->is_initialized()) {
  481. proc.init_context(*thread, false);
  482. thread->set_initialized(true);
  483. }
  484. thread->set_state(Thread::Running);
  485. // Mark it as active because we are using this thread. This is similar
  486. // to comparing it with Processor::current_thread, but when there are
  487. // multiple processors there's no easy way to check whether the thread
  488. // is actually still needed. This prevents accidental finalization when
  489. // a thread is no longer in Running state, but running on another core.
  490. thread->set_active(true);
  491. proc.switch_context(from_thread, thread);
  492. // NOTE: from_thread at this point reflects the thread we were
  493. // switched from, and thread reflects Thread::current()
  494. enter_current(*from_thread);
  495. ASSERT(thread == Thread::current());
  496. return true;
  497. }
  498. void Scheduler::enter_current(Thread& prev_thread)
  499. {
  500. ASSERT(g_scheduler_lock.is_locked());
  501. prev_thread.set_active(false);
  502. if (prev_thread.state() == Thread::Dying) {
  503. // If the thread we switched from is marked as dying, then notify
  504. // the finalizer. Note that as soon as we leave the scheduler lock
  505. // the finalizer may free from_thread!
  506. notify_finalizer();
  507. }
  508. }
  509. void Scheduler::leave_on_first_switch(u32 flags)
  510. {
  511. // This is called when a thread is swiched into for the first time.
  512. // At this point, enter_current has already be called, but because
  513. // Scheduler::context_switch is not in the call stack we need to
  514. // clean up and release locks manually here
  515. g_scheduler_lock.unlock(flags);
  516. auto& scheduler_data = Processor::current().get_scheduler_data();
  517. ASSERT(scheduler_data.m_in_scheduler);
  518. scheduler_data.m_in_scheduler = false;
  519. }
  520. void Scheduler::prepare_after_exec()
  521. {
  522. // This is called after exec() when doing a context "switch" into
  523. // the new process. This is called from Processor::assume_context
  524. ASSERT(g_scheduler_lock.own_lock());
  525. auto& scheduler_data = Processor::current().get_scheduler_data();
  526. ASSERT(!scheduler_data.m_in_scheduler);
  527. scheduler_data.m_in_scheduler = true;
  528. }
  529. void Scheduler::prepare_for_idle_loop()
  530. {
  531. // This is called when the CPU finished setting up the idle loop
  532. // and is about to run it. We need to acquire he scheduler lock
  533. ASSERT(!g_scheduler_lock.own_lock());
  534. g_scheduler_lock.lock();
  535. auto& scheduler_data = Processor::current().get_scheduler_data();
  536. ASSERT(!scheduler_data.m_in_scheduler);
  537. scheduler_data.m_in_scheduler = true;
  538. }
  539. Process* Scheduler::colonel()
  540. {
  541. ASSERT(s_colonel_process);
  542. return s_colonel_process;
  543. }
  544. void Scheduler::initialize()
  545. {
  546. ASSERT(&Processor::current() != nullptr); // sanity check
  547. Thread* idle_thread = nullptr;
  548. g_scheduler_data = new SchedulerData;
  549. g_finalizer_wait_queue = new WaitQueue;
  550. g_finalizer_has_work.store(false, AK::MemoryOrder::memory_order_release);
  551. s_colonel_process = &Process::create_kernel_process(idle_thread, "colonel", idle_loop, 1).leak_ref();
  552. ASSERT(s_colonel_process);
  553. ASSERT(idle_thread);
  554. idle_thread->set_priority(THREAD_PRIORITY_MIN);
  555. idle_thread->set_name("idle thread #0");
  556. set_idle_thread(idle_thread);
  557. }
  558. void Scheduler::set_idle_thread(Thread* idle_thread)
  559. {
  560. Processor::current().set_idle_thread(*idle_thread);
  561. Processor::current().set_current_thread(*idle_thread);
  562. }
  563. Thread* Scheduler::create_ap_idle_thread(u32 cpu)
  564. {
  565. ASSERT(cpu != 0);
  566. // This function is called on the bsp, but creates an idle thread for another AP
  567. ASSERT(Processor::current().id() == 0);
  568. ASSERT(s_colonel_process);
  569. Thread* idle_thread = s_colonel_process->create_kernel_thread(idle_loop, THREAD_PRIORITY_MIN, String::format("idle thread #%u", cpu), 1 << cpu, false);
  570. ASSERT(idle_thread);
  571. return idle_thread;
  572. }
  573. void Scheduler::timer_tick(const RegisterState& regs)
  574. {
  575. ASSERT_INTERRUPTS_DISABLED();
  576. ASSERT(Processor::current().in_irq());
  577. if (Processor::current().id() > 0)
  578. return;
  579. auto current_thread = Processor::current().current_thread();
  580. if (!current_thread)
  581. return;
  582. ++g_uptime;
  583. g_timeofday = TimeManagement::now_as_timeval();
  584. if (current_thread->process().is_profiling()) {
  585. SmapDisabler disabler;
  586. auto backtrace = current_thread->raw_backtrace(regs.ebp, regs.eip);
  587. auto& sample = Profiling::next_sample_slot();
  588. sample.pid = current_thread->process().pid();
  589. sample.tid = current_thread->tid();
  590. sample.timestamp = g_uptime;
  591. for (size_t i = 0; i < min(backtrace.size(), Profiling::max_stack_frame_count); ++i) {
  592. sample.frames[i] = backtrace[i];
  593. }
  594. }
  595. TimerQueue::the().fire();
  596. if (current_thread->tick())
  597. return;
  598. ASSERT_INTERRUPTS_DISABLED();
  599. ASSERT(Processor::current().in_irq());
  600. Processor::current().invoke_scheduler_async();
  601. }
  602. void Scheduler::invoke_async()
  603. {
  604. ASSERT_INTERRUPTS_DISABLED();
  605. auto& proc = Processor::current();
  606. ASSERT(!proc.in_irq());
  607. // Since this function is called when leaving critical sections (such
  608. // as a SpinLock), we need to check if we're not already doing this
  609. // to prevent recursion
  610. if (!proc.get_scheduler_data().m_in_scheduler)
  611. pick_next();
  612. }
  613. void Scheduler::notify_finalizer()
  614. {
  615. if (g_finalizer_has_work.exchange(true, AK::MemoryOrder::memory_order_acq_rel) == false)
  616. g_finalizer_wait_queue->wake_all();
  617. }
  618. void Scheduler::idle_loop()
  619. {
  620. dbg() << "Scheduler[" << Processor::current().id() << "]: idle loop running";
  621. ASSERT(are_interrupts_enabled());
  622. for (;;) {
  623. asm("hlt");
  624. if (Processor::current().id() == 0)
  625. yield();
  626. }
  627. }
  628. }