Scheduler.cpp 19 KB

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