Scheduler.cpp 14 KB

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