Scheduler.cpp 11 KB

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