Scheduler.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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("Non-runnables:\n");
  200. for (auto* thread = g_nonrunnable_threads->head(); thread; thread = thread->next()) {
  201. auto* process = &thread->process();
  202. 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);
  203. }
  204. dbgprintf("Runnables:\n");
  205. for (auto* thread = g_runnable_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. #endif
  210. if (g_runnable_threads->is_empty())
  211. return context_switch(s_colonel_process->main_thread());
  212. auto* previous_head = g_runnable_threads->head();
  213. for (;;) {
  214. // Move head to tail.
  215. g_runnable_threads->append(g_runnable_threads->remove_head());
  216. auto* thread = g_runnable_threads->head();
  217. if (!thread->process().is_being_inspected() && (thread->state() == Thread::Runnable || thread->state() == Thread::Running)) {
  218. #ifdef SCHEDULER_DEBUG
  219. kprintf("switch to %s(%u:%u) @ %w:%x\n", thread->process().name().characters(), thread->process().pid(), thread->tid(), thread->tss().cs, thread->tss().eip);
  220. #endif
  221. return context_switch(*thread);
  222. }
  223. if (thread == previous_head) {
  224. // Back at process_head, nothing wants to run. Send in the colonel!
  225. return context_switch(s_colonel_process->main_thread());
  226. }
  227. }
  228. }
  229. bool Scheduler::donate_to(Thread* beneficiary, const char* reason)
  230. {
  231. InterruptDisabler disabler;
  232. if (!Thread::is_thread(beneficiary))
  233. return false;
  234. (void)reason;
  235. unsigned ticks_left = current->ticks_left();
  236. if (!beneficiary || beneficiary->state() != Thread::Runnable || ticks_left <= 1)
  237. return yield();
  238. unsigned ticks_to_donate = min(ticks_left - 1, time_slice_for(beneficiary->process().priority()));
  239. #ifdef SCHEDULER_DEBUG
  240. 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);
  241. #endif
  242. context_switch(*beneficiary);
  243. beneficiary->set_ticks_left(ticks_to_donate);
  244. switch_now();
  245. return false;
  246. }
  247. bool Scheduler::yield()
  248. {
  249. InterruptDisabler disabler;
  250. ASSERT(current);
  251. // dbgprintf("%s(%u:%u) yield()\n", current->process().name().characters(), current->pid(), current->tid());
  252. if (!pick_next())
  253. return false;
  254. // dbgprintf("yield() jumping to new process: sel=%x, %s(%u:%u)\n", current->far_ptr().selector, current->process().name().characters(), current->pid(), current->tid());
  255. switch_now();
  256. return true;
  257. }
  258. void Scheduler::pick_next_and_switch_now()
  259. {
  260. bool someone_wants_to_run = pick_next();
  261. ASSERT(someone_wants_to_run);
  262. switch_now();
  263. }
  264. void Scheduler::switch_now()
  265. {
  266. Descriptor& descriptor = get_gdt_entry(current->selector());
  267. descriptor.type = 9;
  268. flush_gdt();
  269. asm("sti\n"
  270. "ljmp *(%%eax)\n"
  271. ::"a"(&current->far_ptr())
  272. );
  273. }
  274. bool Scheduler::context_switch(Thread& thread)
  275. {
  276. thread.set_ticks_left(time_slice_for(thread.process().priority()));
  277. thread.did_schedule();
  278. if (current == &thread)
  279. return false;
  280. if (current) {
  281. // If the last process hasn't blocked (still marked as running),
  282. // mark it as runnable for the next round.
  283. if (current->state() == Thread::Running)
  284. current->set_state(Thread::Runnable);
  285. #ifdef LOG_EVERY_CONTEXT_SWITCH
  286. dbgprintf("Scheduler: %s(%u:%u) -> %s(%u:%u) %w:%x\n",
  287. current->process().name().characters(), current->process().pid(), current->tid(),
  288. thread.process().name().characters(), thread.process().pid(), thread.tid(),
  289. thread.tss().cs, thread.tss().eip);
  290. #endif
  291. }
  292. current = &thread;
  293. thread.set_state(Thread::Running);
  294. if (!thread.selector()) {
  295. thread.set_selector(gdt_alloc_entry());
  296. auto& descriptor = get_gdt_entry(thread.selector());
  297. descriptor.set_base(&thread.tss());
  298. descriptor.set_limit(0xffff);
  299. descriptor.dpl = 0;
  300. descriptor.segment_present = 1;
  301. descriptor.granularity = 1;
  302. descriptor.zero = 0;
  303. descriptor.operation_size = 1;
  304. descriptor.descriptor_type = 0;
  305. }
  306. auto& descriptor = get_gdt_entry(thread.selector());
  307. descriptor.type = 11; // Busy TSS
  308. flush_gdt();
  309. return true;
  310. }
  311. static void initialize_redirection()
  312. {
  313. auto& descriptor = get_gdt_entry(s_redirection.selector);
  314. descriptor.set_base(&s_redirection.tss);
  315. descriptor.set_limit(0xffff);
  316. descriptor.dpl = 0;
  317. descriptor.segment_present = 1;
  318. descriptor.granularity = 1;
  319. descriptor.zero = 0;
  320. descriptor.operation_size = 1;
  321. descriptor.descriptor_type = 0;
  322. descriptor.type = 9;
  323. flush_gdt();
  324. }
  325. void Scheduler::prepare_for_iret_to_new_process()
  326. {
  327. auto& descriptor = get_gdt_entry(s_redirection.selector);
  328. descriptor.type = 9;
  329. s_redirection.tss.backlink = current->selector();
  330. load_task_register(s_redirection.selector);
  331. }
  332. void Scheduler::prepare_to_modify_tss(Thread& thread)
  333. {
  334. // This ensures that a currently running process modifying its own TSS
  335. // in order to yield() and end up somewhere else doesn't just end up
  336. // right after the yield().
  337. if (current == &thread)
  338. load_task_register(s_redirection.selector);
  339. }
  340. Process* Scheduler::colonel()
  341. {
  342. return s_colonel_process;
  343. }
  344. void Scheduler::initialize()
  345. {
  346. s_redirection.selector = gdt_alloc_entry();
  347. initialize_redirection();
  348. s_colonel_process = Process::create_kernel_process("colonel", nullptr);
  349. // Make sure the colonel uses a smallish time slice.
  350. s_colonel_process->set_priority(Process::IdlePriority);
  351. load_task_register(s_redirection.selector);
  352. }
  353. void Scheduler::timer_tick(RegisterDump& regs)
  354. {
  355. if (!current)
  356. return;
  357. ++g_uptime;
  358. if (s_beep_timeout && g_uptime > s_beep_timeout) {
  359. PCSpeaker::tone_off();
  360. s_beep_timeout = 0;
  361. }
  362. if (current->tick())
  363. return;
  364. current->tss().gs = regs.gs;
  365. current->tss().fs = regs.fs;
  366. current->tss().es = regs.es;
  367. current->tss().ds = regs.ds;
  368. current->tss().edi = regs.edi;
  369. current->tss().esi = regs.esi;
  370. current->tss().ebp = regs.ebp;
  371. current->tss().ebx = regs.ebx;
  372. current->tss().edx = regs.edx;
  373. current->tss().ecx = regs.ecx;
  374. current->tss().eax = regs.eax;
  375. current->tss().eip = regs.eip;
  376. current->tss().cs = regs.cs;
  377. current->tss().eflags = regs.eflags;
  378. // Compute process stack pointer.
  379. // Add 12 for CS, EIP, EFLAGS (interrupt mechanic)
  380. current->tss().esp = regs.esp + 12;
  381. current->tss().ss = regs.ss;
  382. if ((current->tss().cs & 3) != 0) {
  383. current->tss().ss = regs.ss_if_crossRing;
  384. current->tss().esp = regs.esp_if_crossRing;
  385. }
  386. if (!pick_next())
  387. return;
  388. prepare_for_iret_to_new_process();
  389. // Set the NT (nested task) flag.
  390. asm(
  391. "pushf\n"
  392. "orl $0x00004000, (%esp)\n"
  393. "popf\n"
  394. );
  395. }