Scheduler.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. #include "Scheduler.h"
  2. #include "Process.h"
  3. #include "system.h"
  4. #include "RTC.h"
  5. #include "i8253.h"
  6. #include <AK/TemporaryChange.h>
  7. #include <Kernel/Alarm.h>
  8. //#define LOG_EVERY_CONTEXT_SWITCH
  9. //#define SCHEDULER_DEBUG
  10. static dword time_slice_for(Process::Priority priority)
  11. {
  12. // One time slice unit == 1ms
  13. switch (priority) {
  14. case Process::HighPriority:
  15. return 50;
  16. case Process::NormalPriority:
  17. return 15;
  18. case Process::LowPriority:
  19. return 5;
  20. }
  21. ASSERT_NOT_REACHED();
  22. }
  23. Thread* current;
  24. Thread* g_last_fpu_thread;
  25. Thread* g_finalizer;
  26. static Process* s_colonel_process;
  27. struct TaskRedirectionData {
  28. word selector;
  29. TSS32 tss;
  30. };
  31. static TaskRedirectionData s_redirection;
  32. static bool s_active;
  33. bool Scheduler::is_active()
  34. {
  35. return s_active;
  36. }
  37. bool Scheduler::pick_next()
  38. {
  39. ASSERT_INTERRUPTS_DISABLED();
  40. ASSERT(!s_active);
  41. TemporaryChange<bool> change(s_active, true);
  42. ASSERT(s_active);
  43. if (!current) {
  44. // XXX: The first ever context_switch() goes to the idle process.
  45. // This to setup a reliable place we can return to.
  46. return context_switch(s_colonel_process->main_thread());
  47. }
  48. auto now_sec = RTC::now();
  49. auto now_usec = (suseconds_t)((PIT::ticks_since_boot() % 1000) * 1000);
  50. // Check and unblock threads whose wait conditions have been met.
  51. Thread::for_each([&] (Thread& thread) {
  52. auto& process = thread.process();
  53. // dbgprintf("pick_next, checking on %s(%u:%u) in state %s\n", process.name().impl()->characters(), process.pid(), thread.tid(), to_string(thread.state()));
  54. if (thread.state() == Thread::BlockedSleep) {
  55. if (thread.wakeup_time() <= system.uptime)
  56. thread.unblock();
  57. return IterationDecision::Continue;
  58. }
  59. if (thread.state() == Thread::BlockedWait) {
  60. process.for_each_child([&] (Process& child) {
  61. if (child.state() != Thread::Dead)
  62. return true;
  63. if (thread.waitee_pid() == -1 || thread.waitee_pid() == child.pid()) {
  64. thread.m_waitee_pid = child.pid();
  65. thread.unblock();
  66. return false;
  67. }
  68. return true;
  69. });
  70. return IterationDecision::Continue;
  71. }
  72. if (thread.state() == Thread::BlockedRead) {
  73. ASSERT(thread.m_blocked_fd != -1);
  74. // FIXME: Block until the amount of data wanted is available.
  75. if (process.m_fds[thread.m_blocked_fd].descriptor->can_read(process))
  76. thread.unblock();
  77. return IterationDecision::Continue;
  78. }
  79. if (thread.state() == Thread::BlockedWrite) {
  80. ASSERT(thread.m_blocked_fd != -1);
  81. if (process.m_fds[thread.m_blocked_fd].descriptor->can_write(process))
  82. thread.unblock();
  83. return IterationDecision::Continue;
  84. }
  85. if (thread.state() == Thread::BlockedConnect) {
  86. ASSERT(thread.m_blocked_socket);
  87. if (thread.m_blocked_socket->is_connected())
  88. thread.unblock();
  89. return IterationDecision::Continue;
  90. }
  91. if (thread.state() == Thread::BlockedReceive) {
  92. ASSERT(thread.m_blocked_socket);
  93. auto& socket = *thread.m_blocked_socket;
  94. // FIXME: Block until the amount of data wanted is available.
  95. bool timed_out = now_sec > socket.receive_deadline().tv_sec || (now_sec == socket.receive_deadline().tv_sec && now_usec >= socket.receive_deadline().tv_usec);
  96. if (timed_out || socket.can_read(SocketRole::None)) {
  97. thread.unblock();
  98. thread.m_blocked_socket = nullptr;
  99. return IterationDecision::Continue;
  100. }
  101. return IterationDecision::Continue;
  102. }
  103. if (thread.state() == Thread::BlockedSelect) {
  104. if (thread.m_select_has_timeout) {
  105. if (now_sec > thread.m_select_timeout.tv_sec || (now_sec == thread.m_select_timeout.tv_sec && now_usec >= thread.m_select_timeout.tv_usec)) {
  106. thread.unblock();
  107. return IterationDecision::Continue;
  108. }
  109. }
  110. for (int fd : thread.m_select_read_fds) {
  111. if (process.m_fds[fd].descriptor->can_read(process)) {
  112. thread.unblock();
  113. return IterationDecision::Continue;
  114. }
  115. }
  116. for (int fd : thread.m_select_write_fds) {
  117. if (process.m_fds[fd].descriptor->can_write(process)) {
  118. thread.unblock();
  119. return IterationDecision::Continue;
  120. }
  121. }
  122. return IterationDecision::Continue;
  123. }
  124. if (thread.state() == Thread::BlockedSnoozing) {
  125. if (thread.m_snoozing_alarm->is_ringing()) {
  126. thread.m_snoozing_alarm = nullptr;
  127. thread.unblock();
  128. }
  129. return IterationDecision::Continue;
  130. }
  131. if (thread.state() == Thread::Skip1SchedulerPass) {
  132. thread.set_state(Thread::Skip0SchedulerPasses);
  133. return IterationDecision::Continue;
  134. }
  135. if (thread.state() == Thread::Skip0SchedulerPasses) {
  136. thread.set_state(Thread::Runnable);
  137. return IterationDecision::Continue;
  138. }
  139. if (thread.state() == Thread::Dying) {
  140. ASSERT(g_finalizer);
  141. if (g_finalizer->state() == Thread::BlockedLurking)
  142. g_finalizer->unblock();
  143. return IterationDecision::Continue;
  144. }
  145. return IterationDecision::Continue;
  146. });
  147. Process::for_each([&] (Process& process) {
  148. if (process.is_dead()) {
  149. if (current != &process.main_thread() && (!process.ppid() || !Process::from_pid(process.ppid()))) {
  150. auto name = process.name();
  151. auto pid = process.pid();
  152. auto exit_status = Process::reap(process);
  153. dbgprintf("reaped unparented process %s(%u), exit status: %u\n", name.characters(), pid, exit_status);
  154. }
  155. }
  156. return true;
  157. });
  158. // Dispatch any pending signals.
  159. // FIXME: Do we really need this to be a separate pass over the process list?
  160. Thread::for_each_living([] (Thread& thread) {
  161. if (!thread.has_unmasked_pending_signals())
  162. return true;
  163. // FIXME: It would be nice if the Scheduler didn't have to worry about who is "current"
  164. // For now, avoid dispatching signals to "current" and do it in a scheduling pass
  165. // while some other process is interrupted. Otherwise a mess will be made.
  166. if (&thread == current)
  167. return true;
  168. // We know how to interrupt blocked processes, but if they are just executing
  169. // at some random point in the kernel, let them continue. They'll be in userspace
  170. // sooner or later and we can deliver the signal then.
  171. // FIXME: Maybe we could check when returning from a syscall if there's a pending
  172. // signal and dispatch it then and there? Would that be doable without the
  173. // syscall effectively being "interrupted" despite having completed?
  174. if (thread.in_kernel() && !thread.is_blocked() && !thread.is_stopped())
  175. return true;
  176. // NOTE: dispatch_one_pending_signal() may unblock the process.
  177. bool was_blocked = thread.is_blocked();
  178. if (thread.dispatch_one_pending_signal() == ShouldUnblockThread::No)
  179. return true;
  180. if (was_blocked) {
  181. dbgprintf("Unblock %s(%u) due to signal\n", thread.process().name().characters(), thread.pid());
  182. thread.m_was_interrupted_while_blocked = true;
  183. thread.unblock();
  184. }
  185. return true;
  186. });
  187. #ifdef SCHEDULER_DEBUG
  188. dbgprintf("Scheduler choices:\n");
  189. for (auto* thread = g_threads->head(); thread; thread = thread->next()) {
  190. //if (process->state() == Thread::BlockedWait || process->state() == Thread::BlockedSleep)
  191. // continue;
  192. auto* process = &thread->process();
  193. dbgprintf("[K%x] % 12s %s(%u:%u) @ %w:%x\n", process, to_string(thread->state()), process->name().characters(), process->pid(), thread->tid(), thread->tss().cs, thread->tss().eip);
  194. }
  195. #endif
  196. auto* previous_head = g_threads->head();
  197. for (;;) {
  198. // Move head to tail.
  199. g_threads->append(g_threads->remove_head());
  200. auto* thread = g_threads->head();
  201. if (!thread->process().is_being_inspected() && (thread->state() == Thread::Runnable || thread->state() == Thread::Running)) {
  202. #ifdef SCHEDULER_DEBUG
  203. kprintf("switch to %s(%u:%u) @ %w:%x\n", thread->process().name().characters(), thread->process().pid(), thread->tid(), thread->tss().cs, thread->tss().eip);
  204. #endif
  205. return context_switch(*thread);
  206. }
  207. if (thread == previous_head) {
  208. // Back at process_head, nothing wants to run. Send in the colonel!
  209. return context_switch(s_colonel_process->main_thread());
  210. }
  211. }
  212. }
  213. bool Scheduler::donate_to(Thread* beneficiary, const char* reason)
  214. {
  215. (void)reason;
  216. unsigned ticks_left = current->ticks_left();
  217. if (!beneficiary || beneficiary->state() != Thread::Runnable || ticks_left <= 1) {
  218. return yield();
  219. }
  220. unsigned ticks_to_donate = min(ticks_left - 1, time_slice_for(beneficiary->process().priority()));
  221. #ifdef SCHEDULER_DEBUG
  222. 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);
  223. #endif
  224. context_switch(*beneficiary);
  225. beneficiary->set_ticks_left(ticks_to_donate);
  226. switch_now();
  227. return 0;
  228. }
  229. bool Scheduler::yield()
  230. {
  231. InterruptDisabler disabler;
  232. ASSERT(current);
  233. // dbgprintf("%s(%u:%u) yield()\n", current->process().name().characters(), current->pid(), current->tid());
  234. if (!pick_next())
  235. return 1;
  236. // dbgprintf("yield() jumping to new process: sel=%x, %s(%u:%u)\n", current->far_ptr().selector, current->process().name().characters(), current->pid(), current->tid());
  237. switch_now();
  238. return 0;
  239. }
  240. void Scheduler::pick_next_and_switch_now()
  241. {
  242. bool someone_wants_to_run = pick_next();
  243. ASSERT(someone_wants_to_run);
  244. switch_now();
  245. }
  246. void Scheduler::switch_now()
  247. {
  248. Descriptor& descriptor = get_gdt_entry(current->selector());
  249. descriptor.type = 9;
  250. flush_gdt();
  251. asm("sti\n"
  252. "ljmp *(%%eax)\n"
  253. ::"a"(&current->far_ptr())
  254. );
  255. }
  256. bool Scheduler::context_switch(Thread& thread)
  257. {
  258. thread.set_ticks_left(time_slice_for(thread.process().priority()));
  259. // FIXME(Thread): This is such a hack.
  260. if (&thread == &s_colonel_process->main_thread())
  261. thread.set_ticks_left(1);
  262. thread.did_schedule();
  263. if (current == &thread)
  264. return false;
  265. if (current) {
  266. // If the last process hasn't blocked (still marked as running),
  267. // mark it as runnable for the next round.
  268. if (current->state() == Thread::Running)
  269. current->set_state(Thread::Runnable);
  270. #ifdef LOG_EVERY_CONTEXT_SWITCH
  271. dbgprintf("Scheduler: %s(%u:%u) -> %s(%u:%u) %w:%x\n",
  272. current->process().name().characters(), current->process().pid(), current->tid(),
  273. thread.process().name().characters(), thread.process().pid(), thread.tid(),
  274. thread.tss().cs, thread.tss().eip);
  275. #endif
  276. }
  277. current = &thread;
  278. thread.set_state(Thread::Running);
  279. #ifdef COOL_GLOBALS
  280. g_cool_globals->current_pid = thread.process().pid();
  281. #endif
  282. if (!thread.selector()) {
  283. thread.set_selector(gdt_alloc_entry());
  284. auto& descriptor = get_gdt_entry(thread.selector());
  285. descriptor.set_base(&thread.tss());
  286. descriptor.set_limit(0xffff);
  287. descriptor.dpl = 0;
  288. descriptor.segment_present = 1;
  289. descriptor.granularity = 1;
  290. descriptor.zero = 0;
  291. descriptor.operation_size = 1;
  292. descriptor.descriptor_type = 0;
  293. }
  294. auto& descriptor = get_gdt_entry(thread.selector());
  295. descriptor.type = 11; // Busy TSS
  296. flush_gdt();
  297. return true;
  298. }
  299. static void initialize_redirection()
  300. {
  301. auto& descriptor = get_gdt_entry(s_redirection.selector);
  302. descriptor.set_base(&s_redirection.tss);
  303. descriptor.set_limit(0xffff);
  304. descriptor.dpl = 0;
  305. descriptor.segment_present = 1;
  306. descriptor.granularity = 1;
  307. descriptor.zero = 0;
  308. descriptor.operation_size = 1;
  309. descriptor.descriptor_type = 0;
  310. descriptor.type = 9;
  311. flush_gdt();
  312. }
  313. void Scheduler::prepare_for_iret_to_new_process()
  314. {
  315. auto& descriptor = get_gdt_entry(s_redirection.selector);
  316. descriptor.type = 9;
  317. s_redirection.tss.backlink = current->selector();
  318. load_task_register(s_redirection.selector);
  319. }
  320. void Scheduler::prepare_to_modify_tss(Thread& thread)
  321. {
  322. // This ensures that a currently running process modifying its own TSS
  323. // in order to yield() and end up somewhere else doesn't just end up
  324. // right after the yield().
  325. if (current == &thread)
  326. load_task_register(s_redirection.selector);
  327. }
  328. Process* Scheduler::colonel()
  329. {
  330. return s_colonel_process;
  331. }
  332. void Scheduler::initialize()
  333. {
  334. s_redirection.selector = gdt_alloc_entry();
  335. initialize_redirection();
  336. s_colonel_process = Process::create_kernel_process("colonel", nullptr);
  337. load_task_register(s_redirection.selector);
  338. }
  339. void Scheduler::timer_tick(RegisterDump& regs)
  340. {
  341. if (!current)
  342. return;
  343. system.uptime++;
  344. if (current->tick())
  345. return;
  346. current->tss().gs = regs.gs;
  347. current->tss().fs = regs.fs;
  348. current->tss().es = regs.es;
  349. current->tss().ds = regs.ds;
  350. current->tss().edi = regs.edi;
  351. current->tss().esi = regs.esi;
  352. current->tss().ebp = regs.ebp;
  353. current->tss().ebx = regs.ebx;
  354. current->tss().edx = regs.edx;
  355. current->tss().ecx = regs.ecx;
  356. current->tss().eax = regs.eax;
  357. current->tss().eip = regs.eip;
  358. current->tss().cs = regs.cs;
  359. current->tss().eflags = regs.eflags;
  360. // Compute process stack pointer.
  361. // Add 12 for CS, EIP, EFLAGS (interrupt mechanic)
  362. current->tss().esp = regs.esp + 12;
  363. current->tss().ss = regs.ss;
  364. if ((current->tss().cs & 3) != 0) {
  365. current->tss().ss = regs.ss_if_crossRing;
  366. current->tss().esp = regs.esp_if_crossRing;
  367. }
  368. if (!pick_next())
  369. return;
  370. prepare_for_iret_to_new_process();
  371. // Set the NT (nested task) flag.
  372. asm(
  373. "pushf\n"
  374. "orl $0x00004000, (%esp)\n"
  375. "popf\n"
  376. );
  377. }