Scheduler.cpp 25 KB

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