Task.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. #include "types.h"
  2. #include "Task.h"
  3. #include "kmalloc.h"
  4. #include "VGA.h"
  5. #include "StdLib.h"
  6. #include "i386.h"
  7. #include "system.h"
  8. #include <VirtualFileSystem/FileHandle.h>
  9. #include <VirtualFileSystem/VirtualFileSystem.h>
  10. #include "MemoryManager.h"
  11. Task* current;
  12. Task* s_kernelTask;
  13. static pid_t next_pid;
  14. static InlineLinkedList<Task>* s_tasks;
  15. static bool contextSwitch(Task*);
  16. static void redoKernelTaskTSS()
  17. {
  18. if (!s_kernelTask->selector())
  19. s_kernelTask->setSelector(allocateGDTEntry());
  20. auto& tssDescriptor = getGDTEntry(s_kernelTask->selector());
  21. tssDescriptor.setBase(&s_kernelTask->tss());
  22. tssDescriptor.setLimit(0xffff);
  23. tssDescriptor.dpl = 0;
  24. tssDescriptor.segment_present = 1;
  25. tssDescriptor.granularity = 1;
  26. tssDescriptor.zero = 0;
  27. tssDescriptor.operation_size = 1;
  28. tssDescriptor.descriptor_type = 0;
  29. tssDescriptor.type = 9;
  30. flushGDT();
  31. }
  32. void Task::prepForIRETToNewTask()
  33. {
  34. redoKernelTaskTSS();
  35. s_kernelTask->tss().backlink = current->selector();
  36. loadTaskRegister(s_kernelTask->selector());
  37. }
  38. void Task::initialize()
  39. {
  40. current = nullptr;
  41. next_pid = 0;
  42. s_tasks = new InlineLinkedList<Task>;
  43. s_kernelTask = new Task(0, "idle", IPC::Handle::Any, Task::Ring0);
  44. redoKernelTaskTSS();
  45. loadTaskRegister(s_kernelTask->selector());
  46. }
  47. #ifdef TASK_SANITY_CHECKS
  48. void Task::checkSanity(const char* msg)
  49. {
  50. char ch = current->name()[0];
  51. kprintf("<%p> %s{%u}%b [%d] :%b: sanity check <%s>\n",
  52. current->name().characters(),
  53. current->name().characters(),
  54. current->name().length(),
  55. current->name()[current->name().length() - 1],
  56. current->pid(), ch, msg ? msg : "");
  57. ASSERT((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'));
  58. }
  59. #endif
  60. void Task::allocateLDT()
  61. {
  62. ASSERT(!m_tss.ldt);
  63. static const WORD numLDTEntries = 4;
  64. WORD newLDTSelector = allocateGDTEntry();
  65. m_ldtEntries = new Descriptor[numLDTEntries];
  66. #if 0
  67. kprintf("new ldt selector = %x\n", newLDTSelector);
  68. kprintf("new ldt table at = %p\n", m_ldtEntries);
  69. kprintf("new ldt table size = %u\n", (numLDTEntries * 8) - 1);
  70. #endif
  71. Descriptor& ldt = getGDTEntry(newLDTSelector);
  72. ldt.setBase(m_ldtEntries);
  73. ldt.setLimit(numLDTEntries * 8 - 1);
  74. ldt.dpl = 0;
  75. ldt.segment_present = 1;
  76. ldt.granularity = 0;
  77. ldt.zero = 0;
  78. ldt.operation_size = 1;
  79. ldt.descriptor_type = 0;
  80. ldt.type = Descriptor::LDT;
  81. m_tss.ldt = newLDTSelector;
  82. }
  83. Task::Region* Task::allocateRegion(size_t size, String&& name)
  84. {
  85. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  86. auto zone = MemoryManager::the().createZone(PAGE_SIZE);
  87. ASSERT(zone);
  88. m_regions.append(make<Region>(m_nextRegion, size, move(zone), move(name)));
  89. m_nextRegion = m_nextRegion.offset(size).offset(16384);
  90. return m_regions.last().ptr();
  91. }
  92. Task::Task(void (*e)(), const char* n, IPC::Handle h, RingLevel ring)
  93. : m_name(n)
  94. , m_entry(e)
  95. , m_pid(next_pid++)
  96. , m_handle(h)
  97. , m_state(Runnable)
  98. , m_ring(ring)
  99. {
  100. m_nextRegion = LinearAddress(0x600000);
  101. Region* codeRegion = nullptr;
  102. if (!isRing0()) {
  103. codeRegion = allocateRegion(4096, "code");
  104. ASSERT(codeRegion);
  105. bool success = copyToZone(*codeRegion->zone, (void*)e, PAGE_SIZE);
  106. ASSERT(success);
  107. }
  108. memset(&m_tss, 0, sizeof(m_tss));
  109. memset(&m_ldtEntries, 0, sizeof(m_ldtEntries));
  110. if (ring == Ring3) {
  111. allocateLDT();
  112. }
  113. // Only IF is set when a task boots.
  114. m_tss.eflags = 0x0202;
  115. WORD dataSegment;
  116. WORD stackSegment;
  117. WORD codeSegment;
  118. if (ring == Ring0) {
  119. codeSegment = 0x08;
  120. dataSegment = 0x10;
  121. stackSegment = dataSegment;
  122. } else {
  123. codeSegment = 0x1b;
  124. dataSegment = 0x23;
  125. stackSegment = dataSegment;
  126. }
  127. m_tss.ds = dataSegment;
  128. m_tss.es = dataSegment;
  129. m_tss.fs = dataSegment;
  130. m_tss.gs = dataSegment;
  131. m_tss.ss = stackSegment;
  132. m_tss.cs = codeSegment;
  133. m_tss.cr3 = MemoryManager::the().pageDirectoryBase().get();
  134. if (isRing0()) {
  135. m_tss.eip = (DWORD)m_entry;
  136. } else {
  137. m_tss.eip = codeRegion->linearAddress.get();
  138. }
  139. kprintf("basically ready\n");
  140. // NOTE: Each task gets 16KB of stack.
  141. static const DWORD defaultStackSize = 16384;
  142. if (isRing0()) {
  143. // FIXME: This memory is leaked.
  144. // But uh, there's also no kernel task termination, so I guess it's not technically leaked...
  145. dword stackBottom = (dword)kmalloc(defaultStackSize);
  146. m_stackTop = (stackBottom + defaultStackSize) & 0xffffff8;
  147. m_tss.esp = m_stackTop;
  148. } else {
  149. auto* region = allocateRegion(defaultStackSize, "stack");
  150. ASSERT(region);
  151. m_stackTop = region->linearAddress.offset(defaultStackSize).get() & 0xfffffff8;
  152. m_tss.esp = m_stackTop;
  153. }
  154. if (ring == Ring3) {
  155. // Set up a separate stack for Ring0.
  156. // FIXME: Don't leak this stack either.
  157. m_kernelStack = kmalloc(defaultStackSize);
  158. DWORD ring0StackTop = ((DWORD)m_kernelStack + defaultStackSize) & 0xffffff8;
  159. m_tss.ss0 = 0x10;
  160. m_tss.esp0 = ring0StackTop;
  161. }
  162. // HACK: Ring2 SS in the TSS is the current PID.
  163. m_tss.ss2 = m_pid;
  164. m_farPtr.offset = 0x12345678;
  165. // Don't add task 0 (kernel dummy task) to task list.
  166. // FIXME: This doesn't belong in the constructor.
  167. if (m_pid == 0)
  168. return;
  169. // Add it to head of task list (meaning it's next to run too, ATM.)
  170. s_tasks->prepend(this);
  171. system.nprocess++;
  172. kprintf("Task %u (%s) spawned @ %p\n", m_pid, m_name.characters(), m_tss.eip);
  173. }
  174. Task::~Task()
  175. {
  176. system.nprocess--;
  177. delete [] m_ldtEntries;
  178. m_ldtEntries = nullptr;
  179. // FIXME: The task's kernel stack is currently leaked, because otherwise we GPF.
  180. // This obviously needs figuring out.
  181. #if 0
  182. if (m_kernelStack) {
  183. kfree(m_kernelStack);
  184. m_kernelStack = nullptr;
  185. }
  186. #endif
  187. }
  188. void Task::dumpRegions()
  189. {
  190. kprintf("Task %s(%u) regions:\n", name().characters(), pid());
  191. kprintf("BEGIN END SIZE NAME\n");
  192. for (auto& region : m_regions) {
  193. kprintf("%x -- %x %x %s\n",
  194. region->linearAddress.get(),
  195. region->linearAddress.offset(region->size - 1).get(),
  196. region->size,
  197. region->name.characters());
  198. }
  199. }
  200. void Task::taskDidCrash(Task* crashedTask)
  201. {
  202. // NOTE: This is called from an excepton handler, so interrupts are disabled.
  203. crashedTask->setState(Crashing);
  204. crashedTask->dumpRegions();
  205. s_tasks->remove(crashedTask);
  206. if (!scheduleNewTask()) {
  207. kprintf("Task::taskDidCrash: Failed to schedule a new task :(\n");
  208. HANG;
  209. }
  210. delete crashedTask;
  211. switchNow();
  212. }
  213. void yield()
  214. {
  215. if (!current) {
  216. kprintf( "PANIC: yield() with !current" );
  217. HANG;
  218. }
  219. //kprintf("%s<%u> yield()\n", current->name().characters(), current->pid());
  220. cli();
  221. if (!scheduleNewTask()) {
  222. sti();
  223. return;
  224. }
  225. //kprintf("yield() jumping to new task: %x (%s)\n", current->farPtr().selector, current->name().characters());
  226. switchNow();
  227. }
  228. void switchNow()
  229. {
  230. Descriptor& descriptor = getGDTEntry(current->selector());
  231. descriptor.type = 9;
  232. flushGDT();
  233. asm("sti\n"
  234. "ljmp *(%%eax)\n"
  235. ::"a"(&current->farPtr())
  236. );
  237. }
  238. bool scheduleNewTask()
  239. {
  240. if (!current) {
  241. // XXX: The first ever context_switch() goes to the idle task.
  242. // This to setup a reliable place we can return to.
  243. return contextSwitch(Task::kernelTask());
  244. }
  245. // Check and unblock tasks whose wait conditions have been met.
  246. for (auto* task = s_tasks->head(); task; task = task->next()) {
  247. if (task->state() == Task::BlockedReceive && (task->ipc.msg.isValid() || task->ipc.notifies)) {
  248. task->unblock();
  249. continue;
  250. }
  251. if (task->state() == Task::BlockedSend) {
  252. Task* peer = Task::fromIPCHandle(task->ipc.dst);
  253. if (peer && peer->state() == Task::BlockedReceive && peer->acceptsMessageFrom(*task)) {
  254. task->unblock();
  255. continue;
  256. }
  257. }
  258. if (task->state() == Task::BlockedSleep) {
  259. if (task->wakeupTime() <= system.uptime) {
  260. task->unblock();
  261. continue;
  262. }
  263. }
  264. }
  265. auto* prevHead = s_tasks->head();
  266. for (;;) {
  267. // Move head to tail.
  268. s_tasks->append(s_tasks->removeHead());
  269. auto* task = s_tasks->head();
  270. if (task->state() == Task::Runnable || task->state() == Task::Running) {
  271. //kprintf("switch to %s\n", task->name().characters());
  272. return contextSwitch(task);
  273. }
  274. if (task == prevHead) {
  275. // Back at task_head, nothing wants to run.
  276. return contextSwitch(Task::kernelTask());
  277. }
  278. }
  279. }
  280. static void drawSchedulerBanner(Task& task)
  281. {
  282. // FIXME: We need a kernel lock to do stuff like this :(
  283. //return;
  284. auto c = vga_get_cursor();
  285. auto a = vga_get_attr();
  286. vga_set_cursor(0, 50);
  287. vga_set_attr(0x20);
  288. kprintf(" ");
  289. kprintf(" ");
  290. kprintf(" ");
  291. vga_set_cursor(0, 50);
  292. kprintf("pid: %u ", task.pid());
  293. vga_set_cursor(0, 58);
  294. kprintf("%s", task.name().characters());
  295. vga_set_cursor(0, 65);
  296. kprintf("eip: %p", task.tss().eip);
  297. vga_set_attr(a);
  298. vga_set_cursor(c);
  299. }
  300. static bool contextSwitch(Task* t)
  301. {
  302. //kprintf("c_s to %s (same:%u)\n", t->name().characters(), current == t);
  303. t->setTicksLeft(5);
  304. if (current == t)
  305. return false;
  306. if (current) {
  307. // If the last task hasn't blocked (still marked as running),
  308. // mark it as runnable for the next round.
  309. if (current->state() == Task::Running)
  310. current->setState(Task::Runnable);
  311. bool success = MemoryManager::the().unmapRegionsForTask(*current);
  312. ASSERT(success);
  313. }
  314. bool success = MemoryManager::the().mapRegionsForTask(*t);
  315. ASSERT(success);
  316. current = t;
  317. t->setState(Task::Running);
  318. if (!t->selector())
  319. t->setSelector(allocateGDTEntry());
  320. auto& tssDescriptor = getGDTEntry(t->selector());
  321. tssDescriptor.limit_hi = 0;
  322. tssDescriptor.limit_lo = 0xFFFF;
  323. tssDescriptor.base_lo = (DWORD)(&t->tss()) & 0xFFFF;
  324. tssDescriptor.base_hi = ((DWORD)(&t->tss()) >> 16) & 0xFF;
  325. tssDescriptor.base_hi2 = ((DWORD)(&t->tss()) >> 24) & 0xFF;
  326. tssDescriptor.dpl = 0;
  327. tssDescriptor.segment_present = 1;
  328. tssDescriptor.granularity = 1;
  329. tssDescriptor.zero = 0;
  330. tssDescriptor.operation_size = 1;
  331. tssDescriptor.descriptor_type = 0;
  332. tssDescriptor.type = 11; // Busy TSS
  333. flushGDT();
  334. drawSchedulerBanner(*t);
  335. return true;
  336. }
  337. Task* Task::fromPID(pid_t pid)
  338. {
  339. for (auto* task = s_tasks->head(); task; task = task->next()) {
  340. if (task->pid() == pid)
  341. return task;
  342. }
  343. return nullptr;
  344. }
  345. Task* Task::fromIPCHandle(IPC::Handle handle)
  346. {
  347. for (auto* task = s_tasks->head(); task; task = task->next()) {
  348. if (task->handle() == handle)
  349. return task;
  350. }
  351. return nullptr;
  352. }
  353. FileHandle* Task::fileHandleIfExists(int fd)
  354. {
  355. if (fd < 0)
  356. return nullptr;
  357. if ((unsigned)fd < m_fileHandles.size())
  358. return m_fileHandles[fd].ptr();
  359. return nullptr;
  360. }
  361. int Task::sys$seek(int fd, int offset)
  362. {
  363. auto* handle = fileHandleIfExists(fd);
  364. if (!handle)
  365. return -1;
  366. return handle->seek(offset, SEEK_SET);
  367. }
  368. ssize_t Task::sys$read(int fd, void* outbuf, size_t nread)
  369. {
  370. Task::checkSanity("Task::sys$read");
  371. kprintf("Task::sys$read: called(%d, %p, %u)\n", fd, outbuf, nread);
  372. auto* handle = fileHandleIfExists(fd);
  373. kprintf("Task::sys$read: handle=%p\n", handle);
  374. if (!handle) {
  375. kprintf("Task::sys$read: handle not found :(\n");
  376. return -1;
  377. }
  378. kprintf("call read on handle=%p\n", handle);
  379. nread = handle->read((byte*)outbuf, nread);
  380. kprintf("called read\n");
  381. kprintf("Task::sys$read: nread=%u\n", nread);
  382. return nread;
  383. }
  384. int Task::sys$close(int fd)
  385. {
  386. auto* handle = fileHandleIfExists(fd);
  387. if (!handle)
  388. return -1;
  389. // FIXME: Implement.
  390. return 0;
  391. }
  392. int Task::sys$open(const char* path, size_t pathLength)
  393. {
  394. Task::checkSanity("sys$open");
  395. kprintf("Task::sys$open(): PID=%u, path=%s {%u}\n", m_pid, path, pathLength);
  396. auto* handle = current->openFile(String(path, pathLength));
  397. if (handle)
  398. return handle->fd();
  399. return -1;
  400. }
  401. FileHandle* Task::openFile(String&& path)
  402. {
  403. kprintf("calling vfs::open with vfs=%p, path='%s'\n", &VirtualFileSystem::the(), path.characters());
  404. auto handle = VirtualFileSystem::the().open(move(path));
  405. if (!handle) {
  406. kprintf("vfs::open() failed\n");
  407. return nullptr;
  408. }
  409. handle->setFD(m_fileHandles.size());
  410. kprintf("vfs::open() worked! handle=%p, fd=%d\n", handle.ptr(), handle->fd());
  411. m_fileHandles.append(move(handle)); // FIXME: allow non-move Vector::append
  412. kprintf("Task::openFile(): FileHandle{%p} fd=%d\n", handle.ptr(), handle->fd());
  413. return m_fileHandles.last().ptr();
  414. }
  415. int Task::sys$kill(pid_t pid, int sig)
  416. {
  417. (void) sig;
  418. if (pid == 0) {
  419. // FIXME: Send to same-group processes.
  420. ASSERT(pid != 0);
  421. }
  422. if (pid == -1) {
  423. // FIXME: Send to all processes.
  424. ASSERT(pid != -1);
  425. }
  426. ASSERT_NOT_REACHED();
  427. Task* peer = Task::fromPID(pid);
  428. if (!peer) {
  429. // errno = ESRCH;
  430. return -1;
  431. }
  432. #if 0
  433. send(peer->handle(), IPC::Message(SYS_KILL, DataBuffer::copy((BYTE*)&sig, sizeof(sig))));
  434. IPC::Message response = receive(peer->handle());
  435. return *(int*)response.data();
  436. #endif
  437. return -1;
  438. }
  439. uid_t Task::sys$getuid()
  440. {
  441. return m_uid;
  442. }
  443. bool Task::acceptsMessageFrom(Task& peer)
  444. {
  445. return !ipc.msg.isValid() && (ipc.src == IPC::Handle::Any || ipc.src == peer.handle());
  446. }
  447. void Task::unblock()
  448. {
  449. ASSERT(m_state != Task::Runnable && m_state != Task::Running);
  450. system.nblocked--;
  451. m_state = Task::Runnable;
  452. }
  453. void Task::block(Task::State state)
  454. {
  455. ASSERT(current->state() == Task::Running);
  456. system.nblocked++;
  457. current->setState(state);
  458. }
  459. void block(Task::State state)
  460. {
  461. current->block(state);
  462. yield();
  463. }
  464. void sleep(DWORD ticks)
  465. {
  466. ASSERT(current->state() == Task::Running);
  467. current->setWakeupTime(system.uptime + ticks);
  468. current->block(Task::BlockedSleep);
  469. yield();
  470. }
  471. void Task::sys$sleep(DWORD ticks)
  472. {
  473. ASSERT(this == current);
  474. sleep(ticks);
  475. }
  476. Task* Task::kernelTask()
  477. {
  478. ASSERT(s_kernelTask);
  479. return s_kernelTask;
  480. }
  481. void Task::setError(int error)
  482. {
  483. m_error = error;
  484. }
  485. Task::Region::Region(LinearAddress a, size_t s, RetainPtr<Zone>&& z, String&& n)
  486. : linearAddress(a)
  487. , size(s)
  488. , zone(move(z))
  489. , name(move(n))
  490. {
  491. }
  492. Task::Region::~Region()
  493. {
  494. }