Scheduler.cpp 21 KB

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