Scheduler.cpp 11 KB

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