Advertisement
Guest User

Untitled

a guest
Feb 19th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.86 KB | None | 0 0
  1. #include "threads/thread.h"
  2. #include <debug.h>
  3. #include <stddef.h>
  4. #include <random.h>
  5. #include <stdio.h>
  6. #include <string.h>
  7. #include "threads/flags.h"
  8. #include "threads/interrupt.h"
  9. #include "threads/intr-stubs.h"
  10. #include "threads/palloc.h"
  11. #include "threads/switch.h"
  12. #include "threads/synch.h"
  13. #include "threads/vaddr.h"
  14. #ifdef USERPROG
  15. #include "userprog/process.h"
  16. #endif
  17.  
  18. /* Random value for struct thread's `magic' member.
  19. Used to detect stack overflow. See the big comment at the top
  20. of thread.h for details. */
  21. #define THREAD_MAGIC 0xcd6abf4b
  22.  
  23. /* List of processes in THREAD_READY state, that is, processes
  24. that are ready to run but not actually running. */
  25. static struct list ready_list;
  26.  
  27. /* List of all processes. Processes are added to this list
  28. when they are first scheduled and removed when they exit. */
  29. static struct list all_list;
  30.  
  31. /* Idle thread. */
  32. static struct thread *idle_thread;
  33.  
  34. /* Initial thread, the thread running init.c:main(). */
  35. static struct thread *initial_thread;
  36.  
  37. /* Lock used by allocate_tid(). */
  38. static struct lock tid_lock;
  39.  
  40. /* Stack frame for kernel_thread(). */
  41. struct kernel_thread_frame
  42. {
  43. void *eip; /* Return address. */
  44. thread_func *function; /* Function to call. */
  45. void *aux; /* Auxiliary data for function. */
  46. };
  47.  
  48. /* Statistics. */
  49. static long long idle_ticks; /* # of timer ticks spent idle. */
  50. static long long kernel_ticks; /* # of timer ticks in kernel threads. */
  51. static long long user_ticks; /* # of timer ticks in user programs. */
  52.  
  53. /* Scheduling. */
  54. #define TIME_SLICE 4 /* # of timer ticks to give each thread. */
  55. static unsigned thread_ticks; /* # of timer ticks since last yield. */
  56.  
  57. /* If false (default), use round-robin scheduler.
  58. If true, use multi-level feedback queue scheduler.
  59. Controlled by kernel command-line option "-o mlfqs". */
  60. bool thread_mlfqs;
  61.  
  62. static void kernel_thread (thread_func *, void *aux);
  63.  
  64. static void idle (void *aux UNUSED);
  65. static struct thread *running_thread (void);
  66. static struct thread *next_thread_to_run (void);
  67. static void init_thread (struct thread *, const char *name, int priority);
  68. static bool is_thread (struct thread *) UNUSED;
  69. static void *alloc_frame (struct thread *, size_t size);
  70. static void schedule (void);
  71. void thread_schedule_tail (struct thread *prev);
  72. static tid_t allocate_tid (void);
  73.  
  74. /* Initializes the threading system by transforming the code
  75. that's currently running into a thread. This can't work in
  76. general and it is possible in this case only because loader.S
  77. was careful to put the bottom of the stack at a page boundary.
  78.  
  79. Also initializes the run queue and the tid lock.
  80.  
  81. After calling this function, be sure to initialize the page
  82. allocator before trying to create any threads with
  83. thread_create().
  84.  
  85. It is not safe to call thread_current() until this function
  86. finishes. */
  87. void
  88. thread_init (void)
  89. {
  90. ASSERT (intr_get_level () == INTR_OFF);
  91.  
  92. lock_init (&tid_lock);
  93. list_init (&ready_list);
  94. list_init (&all_list);
  95.  
  96. /* Set up a thread structure for the running thread. */
  97. initial_thread = running_thread ();
  98. init_thread (initial_thread, "main", PRI_DEFAULT);
  99. initial_thread->status = THREAD_RUNNING;
  100. initial_thread->tid = allocate_tid ();
  101. }
  102.  
  103. /* Starts preemptive thread scheduling by enabling interrupts.
  104. Also creates the idle thread. */
  105. void
  106. thread_start (void)
  107. {
  108. /* Create the idle thread. */
  109. struct semaphore idle_started;
  110. sema_init (&idle_started, 0);
  111. thread_create ("idle", PRI_MIN, idle, &idle_started);
  112.  
  113. /* Start preemptive thread scheduling. */
  114. intr_enable ();
  115.  
  116. /* Wait for the idle thread to initialize idle_thread. */
  117. sema_down (&idle_started);
  118. }
  119.  
  120. /* Called by the timer interrupt handler at each timer tick.
  121. Thus, this function runs in an external interrupt context. */
  122. void
  123. thread_tick (void)
  124. {
  125. struct thread *t = thread_current ();
  126.  
  127. /* Update statistics. */
  128. if (t == idle_thread)
  129. idle_ticks++;
  130. #ifdef USERPROG
  131. else if (t->pagedir != NULL)
  132. user_ticks++;
  133. #endif
  134. else
  135. kernel_ticks++;
  136.  
  137. /* Enforce preemption. */
  138. if (++thread_ticks >= TIME_SLICE)
  139. intr_yield_on_return ();
  140. }
  141.  
  142. /* Prints thread statistics. */
  143. void
  144. thread_print_stats (void)
  145. {
  146. printf ("Thread: %lld idle ticks, %lld kernel ticks, %lld user ticks\n",
  147. idle_ticks, kernel_ticks, user_ticks);
  148. }
  149.  
  150. /* Creates a new kernel thread named NAME with the given initial
  151. PRIORITY, which executes FUNCTION passing AUX as the argument,
  152. and adds it to the ready queue. Returns the thread identifier
  153. for the new thread, or TID_ERROR if creation fails.
  154.  
  155. If thread_start() has been called, then the new thread may be
  156. scheduled before thread_create() returns. It could even exit
  157. before thread_create() returns. Contrariwise, the original
  158. thread may run for any amount of time before the new thread is
  159. scheduled. Use a semaphore or some other form of
  160. synchronization if you need to ensure ordering.
  161.  
  162. The code provided sets the new thread's `priority' member to
  163. PRIORITY, but no actual priority scheduling is implemented.
  164. Priority scheduling is the goal of Problem 1-3. */
  165. tid_t
  166. thread_create (const char *name, int priority,
  167. thread_func *function, void *aux)
  168. {
  169. struct thread *t;
  170. struct kernel_thread_frame *kf;
  171. struct switch_entry_frame *ef;
  172. struct switch_threads_frame *sf;
  173. tid_t tid;
  174.  
  175. ASSERT (function != NULL);
  176.  
  177. /* Allocate thread. */
  178. t = palloc_get_page (PAL_ZERO);
  179. if (t == NULL)
  180. return TID_ERROR;
  181.  
  182. /* Initialize thread. */
  183. init_thread (t, name, priority);
  184. tid = t->tid = allocate_tid ();
  185.  
  186.  
  187. /* Stack frame for kernel_thread(). */
  188. kf = alloc_frame (t, sizeof *kf);
  189. kf->eip = NULL;
  190. kf->function = function;
  191. kf->aux = aux;
  192.  
  193. /* Stack frame for switch_entry(). */
  194. ef = alloc_frame (t, sizeof *ef);
  195. ef->eip = (void (*) (void)) kernel_thread;
  196.  
  197. /* Stack frame for switch_threads(). */
  198. sf = alloc_frame (t, sizeof *sf);
  199. sf->eip = switch_entry;
  200. sf->ebp = 0;
  201.  
  202. /* Add to run queue. */
  203. thread_unblock (t);
  204.  
  205. if(is_thread(thread_current())) {
  206. if(t->priority > thread_current()->priority) {
  207. thread_yield();
  208. }
  209. }
  210.  
  211. return tid;
  212. }
  213.  
  214. /* Puts the current thread to sleep. It will not be scheduled
  215. again until awoken by thread_unblock().
  216.  
  217. This function must be called with interrupts turned off. It
  218. is usually a better idea to use one of the synchronization
  219. primitives in synch.h. (For this class, you MUST use one of the
  220. synchronization primitives instead.) */
  221. void
  222. thread_block (void)
  223. {
  224. ASSERT (!intr_context ());
  225. ASSERT (intr_get_level () == INTR_OFF);
  226.  
  227. thread_current ()->status = THREAD_BLOCKED;
  228. schedule ();
  229. }
  230.  
  231. int
  232. compare_thread_priority(struct list_elem *elem,
  233. struct list_elem *e, void *aux){
  234.  
  235. struct thread *threadA = NULL;
  236. struct thread *threadB = NULL;
  237.  
  238. threadA = list_entry(elem, struct thread, elem);
  239. threadB = list_entry(e, struct thread, elem);
  240.  
  241. return threadA->priority > threadB->priority;
  242. }
  243.  
  244. int
  245. compare_blocked_thread_priority(struct list_elem *elem,
  246. struct list_elem *e, void *aux) {
  247.  
  248. struct thread *threadA = NULL;
  249. struct thread *threadB = NULL;
  250.  
  251. threadA = list_entry(elem, struct thread, blockedElem);
  252. threadB = list_entry(e, struct thread, blockedElem);
  253.  
  254. return threadA->priority > threadB->priority;
  255.  
  256. }
  257.  
  258.  
  259. /* Transitions a blocked thread T to the ready-to-run state.
  260. This is an error if T is not blocked. (Use thread_yield() to
  261. make the running thread ready.)
  262.  
  263. This function does not preempt the running thread. This can
  264. be important: if the caller had disabled interrupts itself,
  265. it may expect that it can atomically unblock a thread and
  266. update other data. */
  267. void
  268. thread_unblock (struct thread *t)
  269. {
  270. enum intr_level old_level;
  271.  
  272. ASSERT (is_thread (t));
  273.  
  274. old_level = intr_disable ();
  275. ASSERT (t->status == THREAD_BLOCKED);
  276. list_insert_ordered (&ready_list, &t->elem, compare_thread_priority, NULL);
  277. t->status = THREAD_READY;
  278. intr_set_level (old_level);
  279. }
  280.  
  281. /* Returns the name of the running thread. */
  282. const char *
  283. thread_name (void)
  284. {
  285. return thread_current ()->name;
  286. }
  287.  
  288. /* Returns the running thread.
  289. This is running_thread() plus a couple of sanity checks.
  290. See the big comment at the top of thread.h for details. */
  291. struct thread *
  292. thread_current (void)
  293. {
  294. struct thread *t = running_thread ();
  295.  
  296. /* Make sure T is really a thread.
  297. If either of these assertions fire, then your thread may
  298. have overflowed its stack. Each thread has less than 4 kB
  299. of stack, so a few big automatic arrays or moderate
  300. recursion can cause stack overflow. */
  301. ASSERT (is_thread (t));
  302. ASSERT (t->status == THREAD_RUNNING);
  303.  
  304. return t;
  305. }
  306.  
  307. /* Returns the running thread's tid. */
  308. tid_t
  309. thread_tid (void)
  310. {
  311. return thread_current ()->tid;
  312. }
  313.  
  314. /* Deschedules the current thread and destroys it. Never
  315. returns to the caller. */
  316. void
  317. thread_exit (void)
  318. {
  319. ASSERT (!intr_context ());
  320.  
  321. #ifdef USERPROG
  322. process_exit ();
  323. #endif
  324.  
  325. /* Remove thread from all threads list, set our status to dying,
  326. and schedule another process. That process will destroy us
  327. when it calls thread_schedule_tail(). */
  328. intr_disable ();
  329. list_remove (&thread_current()->allelem);
  330. thread_current ()->status = THREAD_DYING;
  331. schedule ();
  332. NOT_REACHED ();
  333. }
  334.  
  335. /* Yields the CPU. The current thread is not put to sleep and
  336. may be scheduled again immediately at the scheduler's whim. */
  337. void
  338. thread_yield (void)
  339. {
  340. struct thread *cur = thread_current ();
  341. enum intr_level old_level;
  342.  
  343. ASSERT (!intr_context ());
  344.  
  345. old_level = intr_disable ();
  346. if (cur != idle_thread)
  347. list_insert_ordered (&ready_list, &cur->elem,
  348. compare_thread_priority, NULL);
  349. cur->status = THREAD_READY;
  350. schedule ();
  351. intr_set_level (old_level);
  352. }
  353.  
  354. /* Invoke function 'func' on all threads, passing along 'aux'.
  355. This function must be called with interrupts off. */
  356. void
  357. thread_foreach (thread_action_func *func, void *aux)
  358. {
  359. struct list_elem *e;
  360.  
  361. ASSERT (intr_get_level () == INTR_OFF);
  362.  
  363. for (e = list_begin (&all_list); e != list_end (&all_list);
  364. e = list_next (e))
  365. {
  366. struct thread *t = list_entry (e, struct thread, allelem);
  367. func (t, aux);
  368. }
  369. }
  370.  
  371. /* Sets the current thread's priority to NEW_PRIORITY. */
  372. void
  373. thread_set_priority (int new_priority)
  374. {
  375.  
  376. enum intr_level old_level;
  377. old_level = intr_disable ();
  378.  
  379. struct thread *cur = thread_current();
  380. sema_init(&cur->s, 0);
  381. cur->priority = new_priority;
  382.  
  383. if(!list_empty(&ready_list)){
  384. if(list_entry(list_front(&ready_list), struct thread, elem)->priority
  385. > cur->priority) {
  386. thread_yield();
  387. }
  388. }
  389. sema_up(&cur->s);
  390. intr_set_level (old_level);
  391. }
  392.  
  393. /* Returns the current thread's priority. */
  394. int
  395. thread_get_priority (void)
  396. {
  397. return thread_current ()->priority;
  398. }
  399.  
  400. /* Sets the current thread's nice value to NICE. */
  401. void
  402. thread_set_nice (int nice UNUSED)
  403. {
  404. /* Not yet implemented. */
  405. }
  406.  
  407. /* Returns the current thread's nice value. */
  408. int
  409. thread_get_nice (void)
  410. {
  411. /* Not yet implemented. */
  412. return 0;
  413. }
  414.  
  415. /* Returns 100 times the system load average. */
  416. int
  417. thread_get_load_avg (void)
  418. {
  419. /* Not yet implemented. */
  420. return 0;
  421. }
  422.  
  423. /* Returns 100 times the current thread's recent_cpu value. */
  424. int
  425. thread_get_recent_cpu (void)
  426. {
  427. /* Not yet implemented. */
  428. return 0;
  429. }
  430. /* Idle thread. Executes when no other thread is ready to run.
  431.  
  432. The idle thread is initially put on the ready list by
  433. thread_start(). It will be scheduled once initially, at which
  434. point it initializes idle_thread, "up"s the semaphore passed
  435. to it to enable thread_start() to continue, and immediately
  436. blocks. After that, the idle thread never appears in the
  437. ready list. It is returned by next_thread_to_run() as a
  438. special case when the ready list is empty. */
  439. static void
  440. idle (void *idle_started_ UNUSED)
  441. {
  442. struct semaphore *idle_started = idle_started_;
  443. idle_thread = thread_current ();
  444. sema_up (idle_started);
  445.  
  446. for (;;)
  447. {
  448. /* Let someone else run. */
  449. intr_disable ();
  450. thread_block ();
  451.  
  452. /* Re-enable interrupts and wait for the next one.
  453.  
  454. The `sti' instruction disables interrupts until the
  455. completion of the next instruction, so these two
  456. instructions are executed atomically. This atomicity is
  457. important; otherwise, an interrupt could be handled
  458. between re-enabling interrupts and waiting for the next
  459. one to occur, wasting as much as one clock tick worth of
  460. time.
  461.  
  462. See [IA32-v2a] "HLT", [IA32-v2b] "STI", and [IA32-v3a]
  463. 7.11.1 "HLT Instruction". */
  464. asm volatile ("sti; hlt" : : : "memory");
  465. }
  466. }
  467.  
  468. /* Function used as the basis for a kernel thread. */
  469. static void
  470. kernel_thread (thread_func *function, void *aux)
  471. {
  472. ASSERT (function != NULL);
  473.  
  474. intr_enable (); /* The scheduler runs with interrupts off. */
  475. function (aux); /* Execute the thread function. */
  476. thread_exit (); /* If function() returns, kill the thread. */
  477. }
  478. /* Returns the running thread. */
  479. struct thread *
  480. running_thread (void)
  481. {
  482. uint32_t *esp;
  483.  
  484. /* Copy the CPU's stack pointer into `esp', and then round that
  485. down to the start of a page. Because `struct thread' is
  486. always at the beginning of a page and the stack pointer is
  487. somewhere in the middle, this locates the curent thread. */
  488. asm ("mov %%esp, %0" : "=g" (esp));
  489. return pg_round_down (esp);
  490. }
  491.  
  492. /* Returns true if T appears to point to a valid thread. */
  493. static bool
  494. is_thread (struct thread *t)
  495. {
  496. return t != NULL && t->magic == THREAD_MAGIC;
  497. }
  498.  
  499. /* Does basic initialization of T as a blocked thread named
  500. NAME. */
  501. static void
  502. init_thread (struct thread *t, const char *name, int priority)
  503. {
  504. enum intr_level old_level;
  505.  
  506. ASSERT (t != NULL);
  507. ASSERT (PRI_MIN <= priority && priority <= PRI_MAX);
  508. ASSERT (name != NULL);
  509.  
  510. memset (t, 0, sizeof *t);
  511. t->status = THREAD_BLOCKED;
  512. strlcpy (t->name, name, sizeof t->name);
  513. t->stack = (uint8_t *) t + PGSIZE;
  514. t->priority = priority;
  515. t->magic = THREAD_MAGIC;
  516.  
  517. old_level = intr_disable();
  518. list_push_back (&all_list, &t->allelem);
  519. intr_set_level(old_level);
  520. }
  521.  
  522. /* Allocates a SIZE-byte frame at the top of thread T's stack and
  523. returns a pointer to the frame's base. */
  524. static void *
  525. alloc_frame (struct thread *t, size_t size)
  526. {
  527. /* Stack data is always allocated in word-size units. */
  528. ASSERT (is_thread (t));
  529. ASSERT (size % sizeof (uint32_t) == 0);
  530.  
  531. t->stack -= size;
  532. return t->stack;
  533. }
  534.  
  535. /* Chooses and returns the next thread to be scheduled. Should
  536. return a thread from the run queue, unless the run queue is
  537. empty. (If the running thread can continue running, then it
  538. will be in the run queue.) If the run queue is empty, return
  539. idle_thread. */
  540. static struct thread *
  541. next_thread_to_run (void)
  542. {
  543. if (list_empty (&ready_list))
  544. return idle_thread;
  545. else
  546. return list_entry (list_pop_front (&ready_list), struct thread, elem);
  547. }
  548.  
  549. /* Completes a thread switch by activating the new thread's page
  550. tables, and, if the previous thread is dying, destroying it.
  551.  
  552. At this function's invocation, we just switched from thread
  553. PREV, the new thread is already running, and interrupts are
  554. still disabled. This function is normally invoked by
  555. thread_schedule() as its final action before returning, but
  556. the first time a thread is scheduled it is called by
  557. switch_entry() (see switch.S).
  558.  
  559. It's not safe to call printf() until the thread switch is
  560. complete. In practice that means that printf()s should be
  561. added at the end of the function.
  562.  
  563. After this function and its caller returns, the thread switch
  564. is complete. */
  565. void
  566. thread_schedule_tail (struct thread *prev)
  567. {
  568. struct thread *cur = running_thread ();
  569.  
  570. ASSERT (intr_get_level () == INTR_OFF);
  571.  
  572. /* Mark us as running. */
  573. cur->status = THREAD_RUNNING;
  574.  
  575. /* Start new time slice. */
  576. thread_ticks = 0;
  577.  
  578. #ifdef USERPROG
  579. /* Activate the new address space. */
  580. process_activate ();
  581. #endif
  582.  
  583. /* If the thread we switched from is dying, destroy its struct
  584. thread. This must happen late so that thread_exit() doesn't
  585. pull out the rug under itself. (We don't free
  586. initial_thread because its memory was not obtained via
  587. palloc().) */
  588. if (prev != NULL && prev->status == THREAD_DYING && prev != initial_thread)
  589. {
  590. ASSERT (prev != cur);
  591. palloc_free_page (prev);
  592. }
  593. }
  594.  
  595. /* Schedules a new process. At entry, interrupts must be off and
  596. the running process's state must have been changed from
  597. running to some other state. This function finds another
  598. thread to run and switches to it.
  599.  
  600. It's not safe to call printf() until thread_schedule_tail()
  601. has completed. */
  602. static void
  603. schedule (void)
  604. {
  605. struct thread *cur = running_thread ();
  606. struct thread *next = next_thread_to_run ();
  607. struct thread *prev = NULL;
  608.  
  609. ASSERT (intr_get_level () == INTR_OFF);
  610. ASSERT (cur->status != THREAD_RUNNING);
  611. ASSERT (is_thread (next));
  612.  
  613. if (cur != next)
  614. prev = switch_threads (cur, next);
  615. thread_schedule_tail (prev);
  616. }
  617.  
  618. /* Returns a tid to use for a new thread. */
  619. static tid_t
  620. allocate_tid (void)
  621. {
  622. static tid_t next_tid = 1;
  623. tid_t tid;
  624.  
  625. lock_acquire (&tid_lock);
  626. tid = next_tid++;
  627. lock_release (&tid_lock);
  628.  
  629. return tid;
  630. }
  631. /* Offset of `stack' member within `struct thread'.
  632. Used by switch.S, which can't figure it out on its own. */
  633. uint32_t thread_stack_ofs = offsetof (struct thread, stack);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement