Scheduler.cpp 19 KB

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