Scheduler.cpp 15 KB

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