Scheduler.cpp 14 KB

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