Scheduler.cpp 12 KB

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