Scheduler.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. #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. }
  167. return true;
  168. });
  169. // Dispatch any pending signals.
  170. // FIXME: Do we really need this to be a separate pass over the process list?
  171. Thread::for_each_living([] (Thread& thread) {
  172. if (!thread.has_unmasked_pending_signals())
  173. return true;
  174. // FIXME: It would be nice if the Scheduler didn't have to worry about who is "current"
  175. // For now, avoid dispatching signals to "current" and do it in a scheduling pass
  176. // while some other process is interrupted. Otherwise a mess will be made.
  177. if (&thread == current)
  178. return true;
  179. // We know how to interrupt blocked processes, but if they are just executing
  180. // at some random point in the kernel, let them continue. They'll be in userspace
  181. // sooner or later and we can deliver the signal then.
  182. // FIXME: Maybe we could check when returning from a syscall if there's a pending
  183. // signal and dispatch it then and there? Would that be doable without the
  184. // syscall effectively being "interrupted" despite having completed?
  185. if (thread.in_kernel() && !thread.is_blocked() && !thread.is_stopped())
  186. return true;
  187. // NOTE: dispatch_one_pending_signal() may unblock the process.
  188. bool was_blocked = thread.is_blocked();
  189. if (thread.dispatch_one_pending_signal() == ShouldUnblockThread::No)
  190. return true;
  191. if (was_blocked) {
  192. dbgprintf("Unblock %s(%u) due to signal\n", thread.process().name().characters(), thread.pid());
  193. thread.m_was_interrupted_while_blocked = true;
  194. thread.unblock();
  195. }
  196. return true;
  197. });
  198. #ifdef SCHEDULER_DEBUG
  199. dbgprintf("Scheduler choices: (runnable threads: %p)\n", g_runnable_threads);
  200. for (auto* thread = g_runnable_threads->head(); thread; thread = thread->next()) {
  201. //if (process->state() == Thread::BlockedWait || process->state() == Thread::BlockedSleep)
  202. // continue;
  203. auto* process = &thread->process();
  204. 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);
  205. }
  206. #endif
  207. if (g_runnable_threads->is_empty())
  208. return context_switch(s_colonel_process->main_thread());
  209. auto* previous_head = g_runnable_threads->head();
  210. for (;;) {
  211. // Move head to tail.
  212. g_runnable_threads->append(g_runnable_threads->remove_head());
  213. auto* thread = g_runnable_threads->head();
  214. if (!thread->process().is_being_inspected() && (thread->state() == Thread::Runnable || thread->state() == Thread::Running)) {
  215. #ifdef SCHEDULER_DEBUG
  216. kprintf("switch to %s(%u:%u) @ %w:%x\n", thread->process().name().characters(), thread->process().pid(), thread->tid(), thread->tss().cs, thread->tss().eip);
  217. #endif
  218. return context_switch(*thread);
  219. }
  220. if (thread == previous_head) {
  221. // Back at process_head, nothing wants to run. Send in the colonel!
  222. return context_switch(s_colonel_process->main_thread());
  223. }
  224. }
  225. }
  226. bool Scheduler::donate_to(Thread* beneficiary, const char* reason)
  227. {
  228. InterruptDisabler disabler;
  229. if (!Thread::is_thread(beneficiary))
  230. return false;
  231. (void)reason;
  232. unsigned ticks_left = current->ticks_left();
  233. if (!beneficiary || beneficiary->state() != Thread::Runnable || ticks_left <= 1)
  234. return yield();
  235. unsigned ticks_to_donate = min(ticks_left - 1, time_slice_for(beneficiary->process().priority()));
  236. #ifdef SCHEDULER_DEBUG
  237. 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);
  238. #endif
  239. context_switch(*beneficiary);
  240. beneficiary->set_ticks_left(ticks_to_donate);
  241. switch_now();
  242. return false;
  243. }
  244. bool Scheduler::yield()
  245. {
  246. InterruptDisabler disabler;
  247. ASSERT(current);
  248. // dbgprintf("%s(%u:%u) yield()\n", current->process().name().characters(), current->pid(), current->tid());
  249. if (!pick_next())
  250. return false;
  251. // dbgprintf("yield() jumping to new process: sel=%x, %s(%u:%u)\n", current->far_ptr().selector, current->process().name().characters(), current->pid(), current->tid());
  252. switch_now();
  253. return true;
  254. }
  255. void Scheduler::pick_next_and_switch_now()
  256. {
  257. bool someone_wants_to_run = pick_next();
  258. ASSERT(someone_wants_to_run);
  259. switch_now();
  260. }
  261. void Scheduler::switch_now()
  262. {
  263. Descriptor& descriptor = get_gdt_entry(current->selector());
  264. descriptor.type = 9;
  265. flush_gdt();
  266. asm("sti\n"
  267. "ljmp *(%%eax)\n"
  268. ::"a"(&current->far_ptr())
  269. );
  270. }
  271. bool Scheduler::context_switch(Thread& thread)
  272. {
  273. thread.set_ticks_left(time_slice_for(thread.process().priority()));
  274. thread.did_schedule();
  275. if (current == &thread)
  276. return false;
  277. if (current) {
  278. // If the last process hasn't blocked (still marked as running),
  279. // mark it as runnable for the next round.
  280. if (current->state() == Thread::Running)
  281. current->set_state(Thread::Runnable);
  282. #ifdef LOG_EVERY_CONTEXT_SWITCH
  283. dbgprintf("Scheduler: %s(%u:%u) -> %s(%u:%u) %w:%x\n",
  284. current->process().name().characters(), current->process().pid(), current->tid(),
  285. thread.process().name().characters(), thread.process().pid(), thread.tid(),
  286. thread.tss().cs, thread.tss().eip);
  287. #endif
  288. }
  289. current = &thread;
  290. thread.set_state(Thread::Running);
  291. if (!thread.selector()) {
  292. thread.set_selector(gdt_alloc_entry());
  293. auto& descriptor = get_gdt_entry(thread.selector());
  294. descriptor.set_base(&thread.tss());
  295. descriptor.set_limit(0xffff);
  296. descriptor.dpl = 0;
  297. descriptor.segment_present = 1;
  298. descriptor.granularity = 1;
  299. descriptor.zero = 0;
  300. descriptor.operation_size = 1;
  301. descriptor.descriptor_type = 0;
  302. }
  303. auto& descriptor = get_gdt_entry(thread.selector());
  304. descriptor.type = 11; // Busy TSS
  305. flush_gdt();
  306. return true;
  307. }
  308. static void initialize_redirection()
  309. {
  310. auto& descriptor = get_gdt_entry(s_redirection.selector);
  311. descriptor.set_base(&s_redirection.tss);
  312. descriptor.set_limit(0xffff);
  313. descriptor.dpl = 0;
  314. descriptor.segment_present = 1;
  315. descriptor.granularity = 1;
  316. descriptor.zero = 0;
  317. descriptor.operation_size = 1;
  318. descriptor.descriptor_type = 0;
  319. descriptor.type = 9;
  320. flush_gdt();
  321. }
  322. void Scheduler::prepare_for_iret_to_new_process()
  323. {
  324. auto& descriptor = get_gdt_entry(s_redirection.selector);
  325. descriptor.type = 9;
  326. s_redirection.tss.backlink = current->selector();
  327. load_task_register(s_redirection.selector);
  328. }
  329. void Scheduler::prepare_to_modify_tss(Thread& thread)
  330. {
  331. // This ensures that a currently running process modifying its own TSS
  332. // in order to yield() and end up somewhere else doesn't just end up
  333. // right after the yield().
  334. if (current == &thread)
  335. load_task_register(s_redirection.selector);
  336. }
  337. Process* Scheduler::colonel()
  338. {
  339. return s_colonel_process;
  340. }
  341. void Scheduler::initialize()
  342. {
  343. s_redirection.selector = gdt_alloc_entry();
  344. initialize_redirection();
  345. s_colonel_process = Process::create_kernel_process("colonel", nullptr);
  346. // Make sure the colonel uses a smallish time slice.
  347. s_colonel_process->set_priority(Process::IdlePriority);
  348. load_task_register(s_redirection.selector);
  349. }
  350. void Scheduler::timer_tick(RegisterDump& regs)
  351. {
  352. if (!current)
  353. return;
  354. ++g_uptime;
  355. if (s_beep_timeout && g_uptime > s_beep_timeout) {
  356. PCSpeaker::tone_off();
  357. s_beep_timeout = 0;
  358. }
  359. if (current->tick())
  360. return;
  361. current->tss().gs = regs.gs;
  362. current->tss().fs = regs.fs;
  363. current->tss().es = regs.es;
  364. current->tss().ds = regs.ds;
  365. current->tss().edi = regs.edi;
  366. current->tss().esi = regs.esi;
  367. current->tss().ebp = regs.ebp;
  368. current->tss().ebx = regs.ebx;
  369. current->tss().edx = regs.edx;
  370. current->tss().ecx = regs.ecx;
  371. current->tss().eax = regs.eax;
  372. current->tss().eip = regs.eip;
  373. current->tss().cs = regs.cs;
  374. current->tss().eflags = regs.eflags;
  375. // Compute process stack pointer.
  376. // Add 12 for CS, EIP, EFLAGS (interrupt mechanic)
  377. current->tss().esp = regs.esp + 12;
  378. current->tss().ss = regs.ss;
  379. if ((current->tss().cs & 3) != 0) {
  380. current->tss().ss = regs.ss_if_crossRing;
  381. current->tss().esp = regs.esp_if_crossRing;
  382. }
  383. if (!pick_next())
  384. return;
  385. prepare_for_iret_to_new_process();
  386. // Set the NT (nested task) flag.
  387. asm(
  388. "pushf\n"
  389. "orl $0x00004000, (%esp)\n"
  390. "popf\n"
  391. );
  392. }