Scheduler.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  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/TemporaryChange.h>
  28. #include <Kernel/Devices/PIT.h>
  29. #include <Kernel/FileSystem/FileDescription.h>
  30. #include <Kernel/Net/Socket.h>
  31. #include <Kernel/Process.h>
  32. #include <Kernel/Profiling.h>
  33. #include <Kernel/RTC.h>
  34. #include <Kernel/Scheduler.h>
  35. #include <Kernel/TimerQueue.h>
  36. //#define LOG_EVERY_CONTEXT_SWITCH
  37. //#define SCHEDULER_DEBUG
  38. //#define SCHEDULER_RUNNABLE_DEBUG
  39. namespace Kernel {
  40. SchedulerData* g_scheduler_data;
  41. void Scheduler::init_thread(Thread& thread)
  42. {
  43. g_scheduler_data->m_nonrunnable_threads.append(thread);
  44. }
  45. void Scheduler::update_state_for_thread(Thread& thread)
  46. {
  47. ASSERT_INTERRUPTS_DISABLED();
  48. auto& list = g_scheduler_data->thread_list_for_state(thread.state());
  49. if (list.contains(thread))
  50. return;
  51. list.append(thread);
  52. }
  53. static u32 time_slice_for(const Thread& thread)
  54. {
  55. // One time slice unit == 1ms
  56. if (&thread == g_colonel)
  57. return 1;
  58. return 10;
  59. }
  60. Thread* g_finalizer;
  61. Thread* g_colonel;
  62. WaitQueue* g_finalizer_wait_queue;
  63. bool g_finalizer_has_work;
  64. static Process* s_colonel_process;
  65. u64 g_uptime;
  66. struct TaskRedirectionData {
  67. u16 selector;
  68. TSS32 tss;
  69. };
  70. static TaskRedirectionData s_redirection;
  71. static bool s_active;
  72. bool Scheduler::is_active()
  73. {
  74. return s_active;
  75. }
  76. Thread::JoinBlocker::JoinBlocker(Thread& joinee, void*& joinee_exit_value)
  77. : m_joinee(joinee)
  78. , m_joinee_exit_value(joinee_exit_value)
  79. {
  80. ASSERT(m_joinee.m_joiner == nullptr);
  81. m_joinee.m_joiner = Thread::current;
  82. Thread::current->m_joinee = &joinee;
  83. }
  84. bool Thread::JoinBlocker::should_unblock(Thread& joiner, time_t, long)
  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&, time_t, long)
  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&, time_t, long)
  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. if (description.is_socket()) {
  118. auto& socket = *description.socket();
  119. if (socket.has_send_timeout()) {
  120. timeval deadline = kgettimeofday();
  121. deadline.tv_sec += socket.send_timeout().tv_sec;
  122. deadline.tv_usec += socket.send_timeout().tv_usec;
  123. deadline.tv_sec += (socket.send_timeout().tv_usec / 1000000) * 1;
  124. deadline.tv_usec %= 1000000;
  125. m_deadline = deadline;
  126. }
  127. }
  128. }
  129. bool Thread::WriteBlocker::should_unblock(Thread&, time_t now_sec, long now_usec)
  130. {
  131. if (m_deadline.has_value()) {
  132. bool timed_out = now_sec > m_deadline.value().tv_sec || (now_sec == m_deadline.value().tv_sec && now_usec >= m_deadline.value().tv_usec);
  133. return timed_out || blocked_description().can_write();
  134. }
  135. return blocked_description().can_write();
  136. }
  137. Thread::ReadBlocker::ReadBlocker(const FileDescription& description)
  138. : FileDescriptionBlocker(description)
  139. {
  140. if (description.is_socket()) {
  141. auto& socket = *description.socket();
  142. if (socket.has_receive_timeout()) {
  143. timeval deadline = kgettimeofday();
  144. deadline.tv_sec += socket.receive_timeout().tv_sec;
  145. deadline.tv_usec += socket.receive_timeout().tv_usec;
  146. deadline.tv_sec += (socket.receive_timeout().tv_usec / 1000000) * 1;
  147. deadline.tv_usec %= 1000000;
  148. m_deadline = deadline;
  149. }
  150. }
  151. }
  152. bool Thread::ReadBlocker::should_unblock(Thread&, time_t now_sec, long now_usec)
  153. {
  154. if (m_deadline.has_value()) {
  155. bool timed_out = now_sec > m_deadline.value().tv_sec || (now_sec == m_deadline.value().tv_sec && now_usec >= m_deadline.value().tv_usec);
  156. return timed_out || blocked_description().can_read();
  157. }
  158. return blocked_description().can_read();
  159. }
  160. Thread::ConditionBlocker::ConditionBlocker(const char* state_string, Function<bool()>&& condition)
  161. : m_block_until_condition(move(condition))
  162. , m_state_string(state_string)
  163. {
  164. ASSERT(m_block_until_condition);
  165. }
  166. bool Thread::ConditionBlocker::should_unblock(Thread&, time_t, long)
  167. {
  168. return m_block_until_condition();
  169. }
  170. Thread::SleepBlocker::SleepBlocker(u64 wakeup_time)
  171. : m_wakeup_time(wakeup_time)
  172. {
  173. }
  174. bool Thread::SleepBlocker::should_unblock(Thread&, time_t, long)
  175. {
  176. return m_wakeup_time <= g_uptime;
  177. }
  178. Thread::SelectBlocker::SelectBlocker(const timeval& tv, bool select_has_timeout, const FDVector& read_fds, const FDVector& write_fds, const FDVector& except_fds)
  179. : m_select_timeout(tv)
  180. , m_select_has_timeout(select_has_timeout)
  181. , m_select_read_fds(read_fds)
  182. , m_select_write_fds(write_fds)
  183. , m_select_exceptional_fds(except_fds)
  184. {
  185. }
  186. bool Thread::SelectBlocker::should_unblock(Thread& thread, time_t now_sec, long now_usec)
  187. {
  188. if (m_select_has_timeout) {
  189. if (now_sec > m_select_timeout.tv_sec || (now_sec == m_select_timeout.tv_sec && now_usec >= m_select_timeout.tv_usec))
  190. return true;
  191. }
  192. auto& process = thread.process();
  193. for (int fd : m_select_read_fds) {
  194. if (!process.m_fds[fd])
  195. continue;
  196. if (process.m_fds[fd].description->can_read())
  197. return true;
  198. }
  199. for (int fd : m_select_write_fds) {
  200. if (!process.m_fds[fd])
  201. continue;
  202. if (process.m_fds[fd].description->can_write())
  203. return true;
  204. }
  205. return false;
  206. }
  207. Thread::WaitBlocker::WaitBlocker(int wait_options, pid_t& waitee_pid)
  208. : m_wait_options(wait_options)
  209. , m_waitee_pid(waitee_pid)
  210. {
  211. }
  212. bool Thread::WaitBlocker::should_unblock(Thread& thread, time_t, long)
  213. {
  214. bool should_unblock = false;
  215. if (m_waitee_pid != -1) {
  216. auto* peer = Process::from_pid(m_waitee_pid);
  217. if (!peer)
  218. return true;
  219. }
  220. thread.process().for_each_child([&](Process& child) {
  221. if (m_waitee_pid != -1 && m_waitee_pid != child.pid())
  222. return IterationDecision::Continue;
  223. bool child_exited = child.is_dead();
  224. bool child_stopped = child.thread_count() && child.any_thread().state() == Thread::State::Stopped;
  225. bool wait_finished = ((m_wait_options & WEXITED) && child_exited)
  226. || ((m_wait_options & WSTOPPED) && child_stopped);
  227. if (!wait_finished)
  228. return IterationDecision::Continue;
  229. m_waitee_pid = child.pid();
  230. should_unblock = true;
  231. return IterationDecision::Break;
  232. });
  233. return should_unblock;
  234. }
  235. Thread::SemiPermanentBlocker::SemiPermanentBlocker(Reason reason)
  236. : m_reason(reason)
  237. {
  238. }
  239. bool Thread::SemiPermanentBlocker::should_unblock(Thread&, time_t, long)
  240. {
  241. // someone else has to unblock us
  242. return false;
  243. }
  244. // Called by the scheduler on threads that are blocked for some reason.
  245. // Make a decision as to whether to unblock them or not.
  246. void Thread::consider_unblock(time_t now_sec, long now_usec)
  247. {
  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. if (m_blocker->should_unblock(*this, now_sec, now_usec))
  261. unblock();
  262. return;
  263. case Thread::Skip1SchedulerPass:
  264. set_state(Thread::Skip0SchedulerPasses);
  265. return;
  266. case Thread::Skip0SchedulerPasses:
  267. set_state(Thread::Runnable);
  268. return;
  269. }
  270. }
  271. bool Scheduler::pick_next()
  272. {
  273. ASSERT_INTERRUPTS_DISABLED();
  274. ASSERT(!s_active);
  275. TemporaryChange<bool> change(s_active, true);
  276. ASSERT(s_active);
  277. if (!Thread::current) {
  278. // XXX: The first ever context_switch() goes to the idle process.
  279. // This to setup a reliable place we can return to.
  280. return context_switch(*g_colonel);
  281. }
  282. struct timeval now;
  283. kgettimeofday(now);
  284. auto now_sec = now.tv_sec;
  285. auto now_usec = now.tv_usec;
  286. // Check and unblock threads whose wait conditions have been met.
  287. Scheduler::for_each_nonrunnable([&](Thread& thread) {
  288. thread.consider_unblock(now_sec, now_usec);
  289. return IterationDecision::Continue;
  290. });
  291. Process::for_each([&](Process& process) {
  292. if (process.is_dead()) {
  293. if (Process::current->pid() != process.pid() && (!process.ppid() || !Process::from_pid(process.ppid()))) {
  294. auto name = process.name();
  295. auto pid = process.pid();
  296. auto exit_status = Process::reap(process);
  297. dbg() << "Scheduler: Reaped unparented process " << name << "(" << pid << "), exit status: " << exit_status.si_status;
  298. }
  299. return IterationDecision::Continue;
  300. }
  301. if (process.m_alarm_deadline && g_uptime > process.m_alarm_deadline) {
  302. process.m_alarm_deadline = 0;
  303. process.send_signal(SIGALRM, nullptr);
  304. }
  305. return IterationDecision::Continue;
  306. });
  307. // Dispatch any pending signals.
  308. Thread::for_each_living([](Thread& thread) -> IterationDecision {
  309. if (!thread.has_unmasked_pending_signals())
  310. return IterationDecision::Continue;
  311. // FIXME: It would be nice if the Scheduler didn't have to worry about who is "current"
  312. // For now, avoid dispatching signals to "current" and do it in a scheduling pass
  313. // while some other process is interrupted. Otherwise a mess will be made.
  314. if (&thread == Thread::current)
  315. return IterationDecision::Continue;
  316. // We know how to interrupt blocked processes, but if they are just executing
  317. // at some random point in the kernel, let them continue.
  318. // Before returning to userspace from a syscall, we will block a thread if it has any
  319. // pending unmasked signals, allowing it to be dispatched then.
  320. if (thread.in_kernel() && !thread.is_blocked() && !thread.is_stopped())
  321. return IterationDecision::Continue;
  322. // NOTE: dispatch_one_pending_signal() may unblock the process.
  323. bool was_blocked = thread.is_blocked();
  324. if (thread.dispatch_one_pending_signal() == ShouldUnblockThread::No)
  325. return IterationDecision::Continue;
  326. if (was_blocked) {
  327. dbg() << "Unblock " << thread << " due to signal";
  328. ASSERT(thread.m_blocker != nullptr);
  329. thread.m_blocker->set_interrupted_by_signal();
  330. thread.unblock();
  331. }
  332. return IterationDecision::Continue;
  333. });
  334. #ifdef SCHEDULER_RUNNABLE_DEBUG
  335. dbg() << "Non-runnables:";
  336. Scheduler::for_each_nonrunnable([](Thread& thread) -> IterationDecision {
  337. dbg() << " " << String::format("%-12s", thread.state_string()) << " " << thread << " @ " << String::format("%w", thread.tss().cs) << ":" << String::format("%x", thread.tss().eip);
  338. return IterationDecision::Continue;
  339. });
  340. dbg() << "Runnables:";
  341. Scheduler::for_each_runnable([](Thread& thread) -> IterationDecision {
  342. 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);
  343. return IterationDecision::Continue;
  344. });
  345. #endif
  346. Vector<Thread*, 128> sorted_runnables;
  347. for_each_runnable([&sorted_runnables](auto& thread) {
  348. sorted_runnables.append(&thread);
  349. return IterationDecision::Continue;
  350. });
  351. quick_sort(sorted_runnables, [](auto& a, auto& b) { return a->effective_priority() >= b->effective_priority(); });
  352. Thread* thread_to_schedule = nullptr;
  353. for (auto* thread : sorted_runnables) {
  354. if (thread->process().is_being_inspected())
  355. continue;
  356. if (thread->process().exec_tid() && thread->process().exec_tid() != thread->tid())
  357. continue;
  358. ASSERT(thread->state() == Thread::Runnable || thread->state() == Thread::Running);
  359. if (!thread_to_schedule) {
  360. thread->m_extra_priority = 0;
  361. thread_to_schedule = thread;
  362. } else {
  363. thread->m_extra_priority++;
  364. }
  365. }
  366. if (!thread_to_schedule)
  367. thread_to_schedule = g_colonel;
  368. #ifdef SCHEDULER_DEBUG
  369. dbg() << "Scheduler: Switch to " << *thread_to_schedule << " @ " << String::format("%04x:%08x", thread_to_schedule->tss().cs, thread_to_schedule->tss().eip);
  370. #endif
  371. return context_switch(*thread_to_schedule);
  372. }
  373. bool Scheduler::donate_to(Thread* beneficiary, const char* reason)
  374. {
  375. InterruptDisabler disabler;
  376. if (!Thread::is_thread(beneficiary))
  377. return false;
  378. (void)reason;
  379. unsigned ticks_left = Thread::current->ticks_left();
  380. if (!beneficiary || beneficiary->state() != Thread::Runnable || ticks_left <= 1)
  381. return yield();
  382. unsigned ticks_to_donate = min(ticks_left - 1, time_slice_for(*beneficiary));
  383. #ifdef SCHEDULER_DEBUG
  384. dbg() << "Scheduler: Donating " << ticks_to_donate << " ticks to " << *beneficiary << ", reason=" << reason;
  385. #endif
  386. context_switch(*beneficiary);
  387. beneficiary->set_ticks_left(ticks_to_donate);
  388. switch_now();
  389. return false;
  390. }
  391. bool Scheduler::yield()
  392. {
  393. InterruptDisabler disabler;
  394. ASSERT(Thread::current);
  395. if (!pick_next())
  396. return false;
  397. switch_now();
  398. return true;
  399. }
  400. void Scheduler::pick_next_and_switch_now()
  401. {
  402. bool someone_wants_to_run = pick_next();
  403. ASSERT(someone_wants_to_run);
  404. switch_now();
  405. }
  406. void Scheduler::switch_now()
  407. {
  408. Descriptor& descriptor = get_gdt_entry(Thread::current->selector());
  409. descriptor.type = 9;
  410. asm("sti\n"
  411. "ljmp *(%%eax)\n" ::"a"(&Thread::current->far_ptr()));
  412. }
  413. bool Scheduler::context_switch(Thread& thread)
  414. {
  415. thread.set_ticks_left(time_slice_for(thread));
  416. thread.did_schedule();
  417. if (Thread::current == &thread)
  418. return false;
  419. if (Thread::current) {
  420. // If the last process hasn't blocked (still marked as running),
  421. // mark it as runnable for the next round.
  422. if (Thread::current->state() == Thread::Running)
  423. Thread::current->set_state(Thread::Runnable);
  424. asm volatile("fxsave %0"
  425. : "=m"(Thread::current->fpu_state()));
  426. #ifdef LOG_EVERY_CONTEXT_SWITCH
  427. dbg() << "Scheduler: " << *Thread::current << " -> " << thread << " [" << thread.priority() << "] " << String::format("%w", thread.tss().cs) << ":" << String::format("%x", thread.tss().eip);
  428. #endif
  429. }
  430. Thread::current = &thread;
  431. Process::current = &thread.process();
  432. thread.set_state(Thread::Running);
  433. asm volatile("fxrstor %0" ::"m"(Thread::current->fpu_state()));
  434. if (!thread.selector()) {
  435. thread.set_selector(gdt_alloc_entry());
  436. auto& descriptor = get_gdt_entry(thread.selector());
  437. descriptor.set_base(&thread.tss());
  438. descriptor.set_limit(sizeof(TSS32));
  439. descriptor.dpl = 0;
  440. descriptor.segment_present = 1;
  441. descriptor.granularity = 0;
  442. descriptor.zero = 0;
  443. descriptor.operation_size = 1;
  444. descriptor.descriptor_type = 0;
  445. }
  446. if (!thread.thread_specific_data().is_null()) {
  447. auto& descriptor = thread_specific_descriptor();
  448. descriptor.set_base(thread.thread_specific_data().as_ptr());
  449. descriptor.set_limit(sizeof(ThreadSpecificData*));
  450. }
  451. auto& descriptor = get_gdt_entry(thread.selector());
  452. descriptor.type = 11; // Busy TSS
  453. return true;
  454. }
  455. static void initialize_redirection()
  456. {
  457. auto& descriptor = get_gdt_entry(s_redirection.selector);
  458. descriptor.set_base(&s_redirection.tss);
  459. descriptor.set_limit(sizeof(TSS32));
  460. descriptor.dpl = 0;
  461. descriptor.segment_present = 1;
  462. descriptor.granularity = 0;
  463. descriptor.zero = 0;
  464. descriptor.operation_size = 1;
  465. descriptor.descriptor_type = 0;
  466. descriptor.type = 9;
  467. flush_gdt();
  468. }
  469. void Scheduler::prepare_for_iret_to_new_process()
  470. {
  471. auto& descriptor = get_gdt_entry(s_redirection.selector);
  472. descriptor.type = 9;
  473. s_redirection.tss.backlink = Thread::current->selector();
  474. load_task_register(s_redirection.selector);
  475. }
  476. void Scheduler::prepare_to_modify_tss(Thread& thread)
  477. {
  478. // This ensures that a currently running process modifying its own TSS
  479. // in order to yield() and end up somewhere else doesn't just end up
  480. // right after the yield().
  481. if (Thread::current == &thread)
  482. load_task_register(s_redirection.selector);
  483. }
  484. Process* Scheduler::colonel()
  485. {
  486. return s_colonel_process;
  487. }
  488. void Scheduler::initialize()
  489. {
  490. g_scheduler_data = new SchedulerData;
  491. g_finalizer_wait_queue = new WaitQueue;
  492. g_finalizer_has_work = false;
  493. s_redirection.selector = gdt_alloc_entry();
  494. initialize_redirection();
  495. s_colonel_process = Process::create_kernel_process(g_colonel, "colonel", nullptr);
  496. g_colonel->set_priority(THREAD_PRIORITY_MIN);
  497. load_task_register(s_redirection.selector);
  498. }
  499. void Scheduler::timer_tick(const RegisterState& regs)
  500. {
  501. if (!Thread::current)
  502. return;
  503. ++g_uptime;
  504. timeval tv;
  505. tv.tv_sec = RTC::boot_time() + PIT::the().seconds_since_boot();
  506. tv.tv_usec = PIT::the().ticks_this_second() * 1000;
  507. Process::update_info_page_timestamp(tv);
  508. if (Process::current->is_profiling()) {
  509. SmapDisabler disabler;
  510. auto backtrace = Thread::current->raw_backtrace(regs.ebp);
  511. auto& sample = Profiling::next_sample_slot();
  512. sample.pid = Process::current->pid();
  513. sample.tid = Thread::current->tid();
  514. sample.timestamp = g_uptime;
  515. for (size_t i = 0; i < min(backtrace.size(), Profiling::max_stack_frame_count); ++i) {
  516. sample.frames[i] = backtrace[i];
  517. }
  518. }
  519. TimerQueue::the().fire();
  520. if (Thread::current->tick())
  521. return;
  522. auto& outgoing_tss = Thread::current->tss();
  523. if (!pick_next())
  524. return;
  525. outgoing_tss.gs = regs.gs;
  526. outgoing_tss.fs = regs.fs;
  527. outgoing_tss.es = regs.es;
  528. outgoing_tss.ds = regs.ds;
  529. outgoing_tss.edi = regs.edi;
  530. outgoing_tss.esi = regs.esi;
  531. outgoing_tss.ebp = regs.ebp;
  532. outgoing_tss.ebx = regs.ebx;
  533. outgoing_tss.edx = regs.edx;
  534. outgoing_tss.ecx = regs.ecx;
  535. outgoing_tss.eax = regs.eax;
  536. outgoing_tss.eip = regs.eip;
  537. outgoing_tss.cs = regs.cs;
  538. outgoing_tss.eflags = regs.eflags;
  539. // Compute process stack pointer.
  540. // Add 16 for CS, EIP, EFLAGS, exception code (interrupt mechanic)
  541. outgoing_tss.esp = regs.esp + 16;
  542. outgoing_tss.ss = regs.ss;
  543. if ((outgoing_tss.cs & 3) != 0) {
  544. outgoing_tss.ss = regs.userspace_ss;
  545. outgoing_tss.esp = regs.userspace_esp;
  546. }
  547. prepare_for_iret_to_new_process();
  548. // Set the NT (nested task) flag.
  549. asm(
  550. "pushf\n"
  551. "orl $0x00004000, (%esp)\n"
  552. "popf\n");
  553. }
  554. static bool s_should_stop_idling = false;
  555. void Scheduler::stop_idling()
  556. {
  557. if (Thread::current != g_colonel)
  558. return;
  559. s_should_stop_idling = true;
  560. }
  561. void Scheduler::idle_loop()
  562. {
  563. for (;;) {
  564. asm("hlt");
  565. if (s_should_stop_idling) {
  566. s_should_stop_idling = false;
  567. yield();
  568. }
  569. }
  570. }
  571. }