Scheduler.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  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, ProcessID& 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. ASSERT(m_blocker != nullptr);
  260. timespec now;
  261. now.tv_sec = now_sec,
  262. now.tv_nsec = now_usec * 1000ull;
  263. bool timed_out = m_blocker_timeout && now >= *m_blocker_timeout;
  264. if (timed_out || m_blocker->should_unblock(*this))
  265. unblock();
  266. return;
  267. }
  268. case Thread::Skip1SchedulerPass:
  269. set_state(Thread::Skip0SchedulerPasses);
  270. return;
  271. case Thread::Skip0SchedulerPasses:
  272. set_state(Thread::Runnable);
  273. return;
  274. }
  275. }
  276. void Scheduler::start()
  277. {
  278. ASSERT_INTERRUPTS_DISABLED();
  279. // We need to acquire our scheduler lock, which will be released
  280. // by the idle thread once control transferred there
  281. g_scheduler_lock.lock();
  282. auto& processor = Processor::current();
  283. processor.set_scheduler_data(*new SchedulerPerProcessorData());
  284. ASSERT(processor.is_initialized());
  285. auto& idle_thread = *processor.idle_thread();
  286. ASSERT(processor.current_thread() == &idle_thread);
  287. ASSERT(processor.idle_thread() == &idle_thread);
  288. idle_thread.set_ticks_left(time_slice_for(idle_thread));
  289. idle_thread.did_schedule();
  290. idle_thread.set_initialized(true);
  291. processor.init_context(idle_thread, false);
  292. idle_thread.set_state(Thread::Running);
  293. ASSERT(idle_thread.affinity() == (1u << processor.id()));
  294. processor.initialize_context_switching(idle_thread);
  295. ASSERT_NOT_REACHED();
  296. }
  297. bool Scheduler::pick_next()
  298. {
  299. ASSERT_INTERRUPTS_DISABLED();
  300. auto current_thread = Thread::current();
  301. auto now = time_since_boot();
  302. auto now_sec = now.tv_sec;
  303. auto now_usec = now.tv_usec;
  304. // Set the m_in_scheduler flag before acquiring the spinlock. This
  305. // prevents a recursive call into Scheduler::invoke_async upon
  306. // leaving the scheduler lock.
  307. ScopedCritical critical;
  308. Processor::current().get_scheduler_data().m_in_scheduler = true;
  309. ScopeGuard guard(
  310. []() {
  311. // We may be on a different processor after we got switched
  312. // back to this thread!
  313. auto& scheduler_data = Processor::current().get_scheduler_data();
  314. ASSERT(scheduler_data.m_in_scheduler);
  315. scheduler_data.m_in_scheduler = false;
  316. });
  317. ScopedSpinLock lock(g_scheduler_lock);
  318. if (current_thread->should_die() && current_thread->state() == Thread::Running) {
  319. // Rather than immediately killing threads, yanking the kernel stack
  320. // away from them (which can lead to e.g. reference leaks), we always
  321. // allow Thread::wait_on to return. This allows the kernel stack to
  322. // clean up and eventually we'll get here shortly before transitioning
  323. // back to user mode (from Processor::exit_trap). At this point we
  324. // no longer want to schedule this thread. We can't wait until
  325. // Scheduler::enter_current because we don't want to allow it to
  326. // transition back to user mode.
  327. #ifdef SCHEDULER_DEBUG
  328. dbg() << "Scheduler[" << Processor::current().id() << "]: Thread " << *current_thread << " is dying";
  329. #endif
  330. current_thread->set_state(Thread::Dying);
  331. }
  332. // Check and unblock threads whose wait conditions have been met.
  333. Scheduler::for_each_nonrunnable([&](Thread& thread) {
  334. thread.consider_unblock(now_sec, now_usec);
  335. return IterationDecision::Continue;
  336. });
  337. Process::for_each([&](Process& process) {
  338. if (process.is_dead()) {
  339. if (current_thread->process().pid() != process.pid() && (!process.ppid() || !Process::from_pid(process.ppid()))) {
  340. auto name = process.name();
  341. auto pid = process.pid();
  342. auto exit_status = Process::reap(process);
  343. dbg() << "Scheduler[" << Processor::current().id() << "]: Reaped unparented process " << name << "(" << pid.value() << "), exit status: " << exit_status.si_status;
  344. }
  345. return IterationDecision::Continue;
  346. }
  347. if (process.m_alarm_deadline && g_uptime > process.m_alarm_deadline) {
  348. process.m_alarm_deadline = 0;
  349. // FIXME: Should we observe this signal somehow?
  350. (void)process.send_signal(SIGALRM, nullptr);
  351. }
  352. return IterationDecision::Continue;
  353. });
  354. // Dispatch any pending signals.
  355. Thread::for_each_living([&](Thread& thread) -> IterationDecision {
  356. ScopedSpinLock lock(thread.get_lock());
  357. if (!thread.has_unmasked_pending_signals())
  358. return IterationDecision::Continue;
  359. // NOTE: dispatch_one_pending_signal() may unblock the process.
  360. bool was_blocked = thread.is_blocked();
  361. if (thread.dispatch_one_pending_signal() == ShouldUnblockThread::No)
  362. return IterationDecision::Continue;
  363. if (was_blocked) {
  364. #ifdef SCHEDULER_DEBUG
  365. dbg() << "Scheduler[" << Processor::current().id() << "]:Unblock " << thread << " due to signal";
  366. #endif
  367. ASSERT(thread.m_blocker != nullptr);
  368. thread.m_blocker->set_interrupted_by_signal();
  369. thread.unblock();
  370. }
  371. return IterationDecision::Continue;
  372. });
  373. #ifdef SCHEDULER_RUNNABLE_DEBUG
  374. dbg() << "Non-runnables:";
  375. Scheduler::for_each_nonrunnable([](Thread& thread) -> IterationDecision {
  376. if (thread.state() == Thread::Queued)
  377. 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");
  378. else if (thread.state() == Thread::Dying)
  379. dbg() << " " << String::format("%-12s", thread.state_string()) << " " << thread << " @ " << String::format("%w", thread.tss().cs) << ":" << String::format("%x", thread.tss().eip) << " Finalizable: " << thread.is_finalizable();
  380. else
  381. dbg() << " " << String::format("%-12s", thread.state_string()) << " " << thread << " @ " << String::format("%w", thread.tss().cs) << ":" << String::format("%x", thread.tss().eip);
  382. return IterationDecision::Continue;
  383. });
  384. dbg() << "Runnables:";
  385. Scheduler::for_each_runnable([](Thread& thread) -> IterationDecision {
  386. 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);
  387. return IterationDecision::Continue;
  388. });
  389. #endif
  390. Vector<Thread*, 128> sorted_runnables;
  391. for_each_runnable([&sorted_runnables](auto& thread) {
  392. if ((thread.affinity() & (1u << Processor::current().id())) != 0)
  393. sorted_runnables.append(&thread);
  394. return IterationDecision::Continue;
  395. });
  396. quick_sort(sorted_runnables, [](auto& a, auto& b) { return a->effective_priority() >= b->effective_priority(); });
  397. Thread* thread_to_schedule = nullptr;
  398. for (auto* thread : sorted_runnables) {
  399. if (thread->process().exec_tid() && thread->process().exec_tid() != thread->tid())
  400. continue;
  401. ASSERT(thread->state() == Thread::Runnable || thread->state() == Thread::Running);
  402. if (!thread_to_schedule) {
  403. thread->m_extra_priority = 0;
  404. thread_to_schedule = thread;
  405. } else {
  406. thread->m_extra_priority++;
  407. }
  408. }
  409. if (!thread_to_schedule)
  410. thread_to_schedule = Processor::current().idle_thread();
  411. #ifdef SCHEDULER_DEBUG
  412. dbg() << "Scheduler[" << Processor::current().id() << "]: Switch to " << *thread_to_schedule << " @ " << String::format("%04x:%08x", thread_to_schedule->tss().cs, thread_to_schedule->tss().eip);
  413. #endif
  414. // We need to leave our first critical section before switching context,
  415. // but since we're still holding the scheduler lock we're still in a critical section
  416. critical.leave();
  417. return context_switch(thread_to_schedule);
  418. }
  419. bool Scheduler::yield()
  420. {
  421. InterruptDisabler disabler;
  422. auto& proc = Processor::current();
  423. auto current_thread = Thread::current();
  424. #ifdef SCHEDULER_DEBUG
  425. dbg() << "Scheduler[" << proc.id() << "]: yielding thread " << *current_thread << " in_irq: " << proc.in_irq();
  426. #endif
  427. ASSERT(current_thread != nullptr);
  428. if (proc.in_irq() || proc.in_critical()) {
  429. // If we're handling an IRQ we can't switch context, or we're in
  430. // a critical section where we don't want to switch contexts, then
  431. // delay until exiting the trap or critical section
  432. proc.invoke_scheduler_async();
  433. return false;
  434. }
  435. if (!Scheduler::pick_next())
  436. return false;
  437. #ifdef SCHEDULER_DEBUG
  438. dbg() << "Scheduler[" << Processor::current().id() << "]: yield returns to thread " << *current_thread << " in_irq: " << Processor::current().in_irq();
  439. #endif
  440. return true;
  441. }
  442. bool Scheduler::donate_to(Thread* beneficiary, const char* reason)
  443. {
  444. ASSERT(beneficiary);
  445. // Set the m_in_scheduler flag before acquiring the spinlock. This
  446. // prevents a recursive call into Scheduler::invoke_async upon
  447. // leaving the scheduler lock.
  448. ScopedCritical critical;
  449. auto& proc = Processor::current();
  450. proc.get_scheduler_data().m_in_scheduler = true;
  451. ScopeGuard guard(
  452. []() {
  453. // We may be on a different processor after we got switched
  454. // back to this thread!
  455. auto& scheduler_data = Processor::current().get_scheduler_data();
  456. ASSERT(scheduler_data.m_in_scheduler);
  457. scheduler_data.m_in_scheduler = false;
  458. });
  459. ScopedSpinLock lock(g_scheduler_lock);
  460. ASSERT(!proc.in_irq());
  461. if (proc.in_critical()) {
  462. proc.invoke_scheduler_async();
  463. return false;
  464. }
  465. (void)reason;
  466. unsigned ticks_left = Thread::current()->ticks_left();
  467. if (!beneficiary || beneficiary->state() != Thread::Runnable || ticks_left <= 1)
  468. return Scheduler::yield();
  469. unsigned ticks_to_donate = min(ticks_left - 1, time_slice_for(*beneficiary));
  470. #ifdef SCHEDULER_DEBUG
  471. dbg() << "Scheduler[" << proc.id() << "]: Donating " << ticks_to_donate << " ticks to " << *beneficiary << ", reason=" << reason;
  472. #endif
  473. beneficiary->set_ticks_left(ticks_to_donate);
  474. Scheduler::context_switch(beneficiary);
  475. return false;
  476. }
  477. bool Scheduler::context_switch(Thread* thread)
  478. {
  479. thread->set_ticks_left(time_slice_for(*thread));
  480. thread->did_schedule();
  481. auto from_thread = Thread::current();
  482. if (from_thread == thread)
  483. return false;
  484. if (from_thread) {
  485. // If the last process hasn't blocked (still marked as running),
  486. // mark it as runnable for the next round.
  487. if (from_thread->state() == Thread::Running)
  488. from_thread->set_state(Thread::Runnable);
  489. #ifdef LOG_EVERY_CONTEXT_SWITCH
  490. dbg() << "Scheduler[" << Processor::current().id() << "]: " << *from_thread << " -> " << *thread << " [" << thread->priority() << "] " << String::format("%w", thread->tss().cs) << ":" << String::format("%x", thread->tss().eip);
  491. #endif
  492. }
  493. auto& proc = Processor::current();
  494. if (!thread->is_initialized()) {
  495. proc.init_context(*thread, false);
  496. thread->set_initialized(true);
  497. }
  498. thread->set_state(Thread::Running);
  499. // Mark it as active because we are using this thread. This is similar
  500. // to comparing it with Processor::current_thread, but when there are
  501. // multiple processors there's no easy way to check whether the thread
  502. // is actually still needed. This prevents accidental finalization when
  503. // a thread is no longer in Running state, but running on another core.
  504. thread->set_active(true);
  505. proc.switch_context(from_thread, thread);
  506. // NOTE: from_thread at this point reflects the thread we were
  507. // switched from, and thread reflects Thread::current()
  508. enter_current(*from_thread);
  509. ASSERT(thread == Thread::current());
  510. return true;
  511. }
  512. void Scheduler::enter_current(Thread& prev_thread)
  513. {
  514. ASSERT(g_scheduler_lock.is_locked());
  515. prev_thread.set_active(false);
  516. if (prev_thread.state() == Thread::Dying) {
  517. // If the thread we switched from is marked as dying, then notify
  518. // the finalizer. Note that as soon as we leave the scheduler lock
  519. // the finalizer may free from_thread!
  520. notify_finalizer();
  521. }
  522. }
  523. void Scheduler::leave_on_first_switch(u32 flags)
  524. {
  525. // This is called when a thread is swiched into for the first time.
  526. // At this point, enter_current has already be called, but because
  527. // Scheduler::context_switch is not in the call stack we need to
  528. // clean up and release locks manually here
  529. g_scheduler_lock.unlock(flags);
  530. auto& scheduler_data = Processor::current().get_scheduler_data();
  531. ASSERT(scheduler_data.m_in_scheduler);
  532. scheduler_data.m_in_scheduler = false;
  533. }
  534. void Scheduler::prepare_after_exec()
  535. {
  536. // This is called after exec() when doing a context "switch" into
  537. // the new process. This is called from Processor::assume_context
  538. ASSERT(g_scheduler_lock.own_lock());
  539. auto& scheduler_data = Processor::current().get_scheduler_data();
  540. ASSERT(!scheduler_data.m_in_scheduler);
  541. scheduler_data.m_in_scheduler = true;
  542. }
  543. void Scheduler::prepare_for_idle_loop()
  544. {
  545. // This is called when the CPU finished setting up the idle loop
  546. // and is about to run it. We need to acquire he scheduler lock
  547. ASSERT(!g_scheduler_lock.own_lock());
  548. g_scheduler_lock.lock();
  549. auto& scheduler_data = Processor::current().get_scheduler_data();
  550. ASSERT(!scheduler_data.m_in_scheduler);
  551. scheduler_data.m_in_scheduler = true;
  552. }
  553. Process* Scheduler::colonel()
  554. {
  555. ASSERT(s_colonel_process);
  556. return s_colonel_process;
  557. }
  558. void Scheduler::initialize()
  559. {
  560. ASSERT(&Processor::current() != nullptr); // sanity check
  561. Thread* idle_thread = nullptr;
  562. g_scheduler_data = new SchedulerData;
  563. g_finalizer_wait_queue = new WaitQueue;
  564. g_finalizer_has_work.store(false, AK::MemoryOrder::memory_order_release);
  565. s_colonel_process = &Process::create_kernel_process(idle_thread, "colonel", idle_loop, 1).leak_ref();
  566. ASSERT(s_colonel_process);
  567. ASSERT(idle_thread);
  568. idle_thread->set_priority(THREAD_PRIORITY_MIN);
  569. idle_thread->set_name("idle thread #0");
  570. set_idle_thread(idle_thread);
  571. }
  572. void Scheduler::set_idle_thread(Thread* idle_thread)
  573. {
  574. Processor::current().set_idle_thread(*idle_thread);
  575. Processor::current().set_current_thread(*idle_thread);
  576. }
  577. Thread* Scheduler::create_ap_idle_thread(u32 cpu)
  578. {
  579. ASSERT(cpu != 0);
  580. // This function is called on the bsp, but creates an idle thread for another AP
  581. ASSERT(Processor::current().id() == 0);
  582. ASSERT(s_colonel_process);
  583. Thread* idle_thread = s_colonel_process->create_kernel_thread(idle_loop, THREAD_PRIORITY_MIN, String::format("idle thread #%u", cpu), 1 << cpu, false);
  584. ASSERT(idle_thread);
  585. return idle_thread;
  586. }
  587. void Scheduler::timer_tick(const RegisterState& regs)
  588. {
  589. ASSERT_INTERRUPTS_DISABLED();
  590. ASSERT(Processor::current().in_irq());
  591. if (Processor::current().id() > 0)
  592. return;
  593. auto current_thread = Processor::current().current_thread();
  594. if (!current_thread)
  595. return;
  596. ++g_uptime;
  597. g_timeofday = TimeManagement::now_as_timeval();
  598. if (current_thread->process().is_profiling()) {
  599. SmapDisabler disabler;
  600. auto backtrace = current_thread->raw_backtrace(regs.ebp, regs.eip);
  601. auto& sample = Profiling::next_sample_slot();
  602. sample.pid = current_thread->process().pid();
  603. sample.tid = current_thread->tid();
  604. sample.timestamp = g_uptime;
  605. for (size_t i = 0; i < min(backtrace.size(), Profiling::max_stack_frame_count); ++i) {
  606. sample.frames[i] = backtrace[i];
  607. }
  608. }
  609. TimerQueue::the().fire();
  610. if (current_thread->tick())
  611. return;
  612. ASSERT_INTERRUPTS_DISABLED();
  613. ASSERT(Processor::current().in_irq());
  614. Processor::current().invoke_scheduler_async();
  615. }
  616. void Scheduler::invoke_async()
  617. {
  618. ASSERT_INTERRUPTS_DISABLED();
  619. auto& proc = Processor::current();
  620. ASSERT(!proc.in_irq());
  621. // Since this function is called when leaving critical sections (such
  622. // as a SpinLock), we need to check if we're not already doing this
  623. // to prevent recursion
  624. if (!proc.get_scheduler_data().m_in_scheduler)
  625. pick_next();
  626. }
  627. void Scheduler::notify_finalizer()
  628. {
  629. if (g_finalizer_has_work.exchange(true, AK::MemoryOrder::memory_order_acq_rel) == false)
  630. g_finalizer_wait_queue->wake_all();
  631. }
  632. void Scheduler::idle_loop()
  633. {
  634. dbg() << "Scheduler[" << Processor::current().id() << "]: idle loop running";
  635. ASSERT(are_interrupts_enabled());
  636. for (;;) {
  637. asm("hlt");
  638. if (Processor::current().id() == 0)
  639. yield();
  640. }
  641. }
  642. }