Scheduler.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. #include "Scheduler.h"
  2. #include "Process.h"
  3. #include "system.h"
  4. //#define LOG_EVERY_CONTEXT_SWITCH
  5. //#define SCHEDULER_DEBUG
  6. static const dword time_slice = 5; // *10 = 50ms
  7. Process* current;
  8. static Process* s_colonel_process;
  9. static bool s_in_yield;
  10. struct TaskRedirectionData {
  11. word selector;
  12. TSS32 tss;
  13. };
  14. static TaskRedirectionData s_redirection;
  15. bool Scheduler::pick_next()
  16. {
  17. ASSERT_INTERRUPTS_DISABLED();
  18. if (!current) {
  19. // XXX: The first ever context_switch() goes to the idle process.
  20. // This to setup a reliable place we can return to.
  21. return context_switch(*s_colonel_process);
  22. }
  23. // Check and unblock processes whose wait conditions have been met.
  24. Process::for_each([] (auto& process) {
  25. if (process.state() == Process::BlockedSleep) {
  26. if (process.wakeupTime() <= system.uptime)
  27. process.unblock();
  28. return true;
  29. }
  30. if (process.state() == Process::BlockedWait) {
  31. process.for_each_child([&process] (Process& child) {
  32. if (child.state() != Process::Dead)
  33. return true;
  34. if (process.waitee_pid() == -1 || process.waitee_pid() == child.pid()) {
  35. process.m_waitee_pid = child.pid();
  36. process.unblock();
  37. return false;
  38. }
  39. return true;
  40. });
  41. return true;
  42. }
  43. if (process.state() == Process::BlockedRead) {
  44. ASSERT(process.m_blocked_fd != -1);
  45. // FIXME: Block until the amount of data wanted is available.
  46. if (process.m_fds[process.m_blocked_fd].descriptor->can_read(process))
  47. process.unblock();
  48. return true;
  49. }
  50. if (process.state() == Process::BlockedWrite) {
  51. ASSERT(process.m_blocked_fd != -1);
  52. if (process.m_fds[process.m_blocked_fd].descriptor->can_write(process))
  53. process.unblock();
  54. return true;
  55. }
  56. if (process.state() == Process::BlockedSelect) {
  57. if (process.wakeup_requested()) {
  58. process.m_wakeup_requested = false;
  59. process.unblock();
  60. return true;
  61. }
  62. for (int fd : process.m_select_read_fds) {
  63. if (process.m_fds[fd].descriptor->can_read(process)) {
  64. process.unblock();
  65. return true;
  66. }
  67. }
  68. for (int fd : process.m_select_write_fds) {
  69. if (process.m_fds[fd].descriptor->can_write(process)) {
  70. process.unblock();
  71. return true;
  72. }
  73. }
  74. return true;
  75. }
  76. if (process.state() == Process::Skip1SchedulerPass) {
  77. process.set_state(Process::Skip0SchedulerPasses);
  78. return true;
  79. }
  80. if (process.state() == Process::Skip0SchedulerPasses) {
  81. process.set_state(Process::Runnable);
  82. return true;
  83. }
  84. if (process.state() == Process::Dead) {
  85. if (current != &process && !Process::from_pid(process.ppid())) {
  86. auto name = process.name();
  87. auto pid = process.pid();
  88. auto exit_status = Process::reap(process);
  89. dbgprintf("reaped unparented process %s(%u), exit status: %u\n", name.characters(), pid, exit_status);
  90. }
  91. return true;
  92. }
  93. return true;
  94. });
  95. // Dispatch any pending signals.
  96. // FIXME: Do we really need this to be a separate pass over the process list?
  97. Process::for_each_not_in_state(Process::Dead, [] (auto& process) {
  98. if (!process.has_unmasked_pending_signals())
  99. return true;
  100. // We know how to interrupt blocked processes, but if they are just executing
  101. // at some random point in the kernel, let them continue. They'll be in userspace
  102. // sooner or later and we can deliver the signal then.
  103. // FIXME: Maybe we could check when returning from a syscall if there's a pending
  104. // signal and dispatch it then and there? Would that be doable without the
  105. // syscall effectively being "interrupted" despite having completed?
  106. if (process.in_kernel() && !process.is_blocked())
  107. return true;
  108. // NOTE: dispatch_one_pending_signal() may unblock the process.
  109. bool was_blocked = process.is_blocked();
  110. if (!process.dispatch_one_pending_signal())
  111. return true;
  112. if (was_blocked) {
  113. dbgprintf("Unblock %s(%u) due to signal\n", process.name().characters(), process.pid());
  114. process.m_was_interrupted_while_blocked = true;
  115. process.unblock();
  116. }
  117. return true;
  118. });
  119. #ifdef SCHEDULER_DEBUG
  120. dbgprintf("Scheduler choices:\n");
  121. for (auto* process = g_processes->head(); process; process = process->next()) {
  122. //if (process->state() == Process::BlockedWait || process->state() == Process::BlockedSleep)
  123. // continue;
  124. dbgprintf("[K%x] % 12s %s(%u) @ %w:%x\n", process, toString(process->state()), process->name().characters(), process->pid(), process->tss().cs, process->tss().eip);
  125. }
  126. #endif
  127. auto* prevHead = g_processes->head();
  128. for (;;) {
  129. // Move head to tail.
  130. g_processes->append(g_processes->remove_head());
  131. auto* process = g_processes->head();
  132. if (process->state() == Process::Runnable || process->state() == Process::Running) {
  133. #ifdef SCHEDULER_DEBUG
  134. dbgprintf("switch to %s(%u) @ %w:%x\n", process->name().characters(), process->pid(), process->tss().cs, process->tss().eip);
  135. #endif
  136. return context_switch(*process);
  137. }
  138. if (process == prevHead) {
  139. // Back at process_head, nothing wants to run. Send in the colonel!
  140. return context_switch(*s_colonel_process);
  141. }
  142. }
  143. }
  144. bool Scheduler::yield()
  145. {
  146. ASSERT(!s_in_yield);
  147. s_in_yield = true;
  148. if (!current) {
  149. kprintf("PANIC: sched_yield() with !current");
  150. HANG;
  151. }
  152. //dbgprintf("%s<%u> yield()\n", current->name().characters(), current->pid());
  153. InterruptDisabler disabler;
  154. if (!pick_next()) {
  155. s_in_yield = false;
  156. return 1;
  157. }
  158. s_in_yield = false;
  159. //dbgprintf("yield() jumping to new process: %x (%s)\n", current->farPtr().selector, current->name().characters());
  160. switch_now();
  161. return 0;
  162. }
  163. void Scheduler::pick_next_and_switch_now()
  164. {
  165. bool someone_wants_to_run = pick_next();
  166. ASSERT(someone_wants_to_run);
  167. switch_now();
  168. }
  169. void Scheduler::switch_now()
  170. {
  171. Descriptor& descriptor = get_gdt_entry(current->selector());
  172. descriptor.type = 9;
  173. flush_gdt();
  174. asm("sti\n"
  175. "ljmp *(%%eax)\n"
  176. ::"a"(&current->farPtr())
  177. );
  178. }
  179. bool Scheduler::context_switch(Process& process)
  180. {
  181. process.set_ticks_left(time_slice);
  182. process.did_schedule();
  183. if (process.tss().cs & 3) {
  184. ++process.m_ticks_in_user;
  185. } else {
  186. ++process.m_ticks_in_kernel;
  187. }
  188. if (current == &process)
  189. return false;
  190. if (current) {
  191. // If the last process hasn't blocked (still marked as running),
  192. // mark it as runnable for the next round.
  193. if (current->state() == Process::Running)
  194. current->set_state(Process::Runnable);
  195. #ifdef LOG_EVERY_CONTEXT_SWITCH
  196. dbgprintf("Scheduler: %s(%u) -> %s(%u)\n", current->name().characters(), current->pid(), process.name().characters(), process.pid());
  197. #endif
  198. }
  199. current = &process;
  200. process.set_state(Process::Running);
  201. #ifdef COOL_GLOBALS
  202. g_cool_globals->current_pid = process.pid();
  203. #endif
  204. if (!process.selector()) {
  205. process.setSelector(gdt_alloc_entry());
  206. auto& descriptor = get_gdt_entry(process.selector());
  207. descriptor.setBase(&process.tss());
  208. descriptor.setLimit(0xffff);
  209. descriptor.dpl = 0;
  210. descriptor.segment_present = 1;
  211. descriptor.granularity = 1;
  212. descriptor.zero = 0;
  213. descriptor.operation_size = 1;
  214. descriptor.descriptor_type = 0;
  215. }
  216. auto& descriptor = get_gdt_entry(process.selector());
  217. descriptor.type = 11; // Busy TSS
  218. flush_gdt();
  219. return true;
  220. }
  221. int sched_yield()
  222. {
  223. return Scheduler::yield();
  224. }
  225. static void initialize_redirection()
  226. {
  227. auto& descriptor = get_gdt_entry(s_redirection.selector);
  228. descriptor.setBase(&s_redirection.tss);
  229. descriptor.setLimit(0xffff);
  230. descriptor.dpl = 0;
  231. descriptor.segment_present = 1;
  232. descriptor.granularity = 1;
  233. descriptor.zero = 0;
  234. descriptor.operation_size = 1;
  235. descriptor.descriptor_type = 0;
  236. descriptor.type = 9;
  237. flush_gdt();
  238. }
  239. void Scheduler::prepare_for_iret_to_new_process()
  240. {
  241. auto& descriptor = get_gdt_entry(s_redirection.selector);
  242. descriptor.type = 9;
  243. s_redirection.tss.backlink = current->selector();
  244. load_task_register(s_redirection.selector);
  245. }
  246. void Scheduler::prepare_to_modify_tss(Process& process)
  247. {
  248. // This ensures that a currently running process modifying its own TSS
  249. // in order to yield() and end up somewhere else doesn't just end up
  250. // right after the yield().
  251. if (current == &process)
  252. load_task_register(s_redirection.selector);
  253. }
  254. void Scheduler::initialize()
  255. {
  256. memset(&s_redirection, 0, sizeof(s_redirection));
  257. s_redirection.selector = gdt_alloc_entry();
  258. initialize_redirection();
  259. s_colonel_process = Process::create_kernel_process("colonel", nullptr);
  260. current = nullptr;
  261. s_in_yield = false;
  262. load_task_register(s_redirection.selector);
  263. }
  264. void Scheduler::timer_tick(RegisterDump& regs)
  265. {
  266. if (!current)
  267. return;
  268. system.uptime++;
  269. if (current->tick())
  270. return;
  271. current->tss().gs = regs.gs;
  272. current->tss().fs = regs.fs;
  273. current->tss().es = regs.es;
  274. current->tss().ds = regs.ds;
  275. current->tss().edi = regs.edi;
  276. current->tss().esi = regs.esi;
  277. current->tss().ebp = regs.ebp;
  278. current->tss().ebx = regs.ebx;
  279. current->tss().edx = regs.edx;
  280. current->tss().ecx = regs.ecx;
  281. current->tss().eax = regs.eax;
  282. current->tss().eip = regs.eip;
  283. current->tss().cs = regs.cs;
  284. current->tss().eflags = regs.eflags;
  285. // Compute process stack pointer.
  286. // Add 12 for CS, EIP, EFLAGS (interrupt mechanic)
  287. current->tss().esp = regs.esp + 12;
  288. current->tss().ss = regs.ss;
  289. if ((current->tss().cs & 3) != 0) {
  290. current->tss().ss = regs.ss_if_crossRing;
  291. current->tss().esp = regs.esp_if_crossRing;
  292. }
  293. if (!pick_next())
  294. return;
  295. prepare_for_iret_to_new_process();
  296. // Set the NT (nested task) flag.
  297. asm(
  298. "pushf\n"
  299. "orl $0x00004000, (%esp)\n"
  300. "popf\n"
  301. );
  302. }