Scheduler.cpp 21 KB

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