Scheduler.cpp 19 KB

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