Scheduler.cpp 17 KB

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