Scheduler.cpp 14 KB

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