Task.cpp 13 KB

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