Scheduler.cpp 19 KB

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