Scheduler.cpp 13 KB

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