Scheduler.cpp 18 KB

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