1 #include "threads/thread.h"
6 #include "threads/interrupt.h"
7 #include "threads/intr-stubs.h"
8 #include "threads/mmu.h"
9 #include "threads/palloc.h"
10 #include "threads/switch.h"
11 #include "threads/synch.h"
13 #include "userprog/gdt.h"
16 /* Random value for struct thread's `magic' member.
17 Used to detect stack overflow. See the big comment at the top
18 of thread.h for details. */
19 #define THREAD_MAGIC 0xcd6abf4b
21 /* List of processes in THREAD_READY state, that is, processes
22 that are ready to run but not actually running. */
23 static struct list ready_list;
26 static struct thread *idle_thread;
28 /* Initial thread, the thread running init.c:main(). */
29 static struct thread *initial_thread;
31 /* Lock used by allocate_tid(). */
32 static struct lock tid_lock;
34 /* Stack frame for kernel_thread(). */
35 struct kernel_thread_frame
37 void *eip; /* Return address. */
38 thread_func *function; /* Function to call. */
39 void *aux; /* Auxiliary data for function. */
42 static void kernel_thread (thread_func *, void *aux);
44 static void idle (void *aux UNUSED);
45 static struct thread *running_thread (void);
46 static struct thread *next_thread_to_run (void);
47 static struct thread *new_thread (const char *name);
48 static void init_thread (struct thread *, const char *name);
49 static bool is_thread (struct thread *);
50 static void *alloc_frame (struct thread *, size_t size);
51 static void destroy_thread (struct thread *);
52 static void schedule (void);
53 void schedule_tail (struct thread *prev);
54 static tid_t allocate_tid (void);
56 /* Initializes the threading system by transforming the code
57 that's currently running into a thread. Note that this is
58 possible only because the loader was careful to put the bottom
59 of the stack at a page boundary; it won't work in general.
60 Also initializes the run queue.
62 After calling this function, be sure to initialize the page
63 allocator before trying to create any threads with
68 ASSERT (intr_get_level () == INTR_OFF);
70 lock_init (&tid_lock, "tid");
72 /* Set up a thread structure for the running thread. */
73 initial_thread = running_thread ();
74 init_thread (initial_thread, "main");
75 initial_thread->status = THREAD_RUNNING;
76 initial_thread->tid = allocate_tid ();
78 /* Initialize run queue. */
79 list_init (&ready_list);
82 /* Starts preemptive thread scheduling by enabling interrupts.
83 Also creates the idle thread. */
87 thread_create ("idle", idle, NULL);
91 /* Creates a new kernel thread named NAME, which executes
92 FUNCTION passing AUX as the argument, and adds it to the ready
93 queue. If thread_start() has been called, then the new thread
94 may be scheduled before thread_create() returns. It could
95 even exit before thread_create() returns. Use a semaphore or
96 some other form of synchronization if you need to ensure
97 ordering. Returns the thread identifier for the new thread,
98 or TID_ERROR if creation fails. */
100 thread_create (const char *name, thread_func *function, void *aux)
103 struct kernel_thread_frame *kf;
104 struct switch_entry_frame *ef;
105 struct switch_threads_frame *sf;
108 ASSERT (function != NULL);
110 t = new_thread (name);
113 tid = t->tid = allocate_tid ();
115 /* Stack frame for kernel_thread(). */
116 kf = alloc_frame (t, sizeof *kf);
118 kf->function = function;
121 /* Stack frame for switch_entry(). */
122 ef = alloc_frame (t, sizeof *ef);
123 ef->eip = (void (*) (void)) kernel_thread;
125 /* Stack frame for switch_threads(). */
126 sf = alloc_frame (t, sizeof *sf);
127 sf->eip = switch_entry;
129 /* Add to run queue. */
136 /* Starts a new thread running a user program loaded from
137 FILENAME, and adds it to the ready queue. If thread_start()
138 has been called, then new thread may be scheduled before
139 thread_execute() returns.*/
141 thread_execute (const char *filename)
144 struct intr_frame *if_;
145 struct switch_entry_frame *ef;
146 struct switch_threads_frame *sf;
147 void (*start) (void);
150 ASSERT (filename != NULL);
152 t = new_thread (filename);
155 tid = t->tid = allocate_tid ();
157 if (!addrspace_load (t, filename, &start))
158 PANIC ("%s: program load failed", filename);
160 /* Interrupt frame. */
161 if_ = alloc_frame (t, sizeof *if_);
166 if_->eflags = FLAG_IF | FLAG_MBS;
167 if_->esp = PHYS_BASE;
170 /* Stack frame for switch_entry(). */
171 ef = alloc_frame (t, sizeof *ef);
174 /* Stack frame for switch_threads(). */
175 sf = alloc_frame (t, sizeof *sf);
176 sf->eip = switch_entry;
178 /* Add to run queue. */
185 /* Transitions a blocked thread T from its current state to the
186 ready-to-run state. This is an error if T is not blocked.
187 (Use thread_yield() to make the running thread ready.) */
189 thread_unblock (struct thread *t)
191 enum intr_level old_level;
193 ASSERT (is_thread (t));
195 old_level = intr_disable ();
196 ASSERT (t->status == THREAD_BLOCKED);
197 list_push_back (&ready_list, &t->elem);
198 t->status = THREAD_READY;
199 intr_set_level (old_level);
202 /* Returns the name of the running thread. */
206 return thread_current ()->name;
209 /* Returns the running thread.
210 This is running_thread() plus a couple of sanity checks.
211 See the big comment at the top of thread.h for details. */
213 thread_current (void)
215 struct thread *t = running_thread ();
217 /* Make sure T is really a thread.
218 If either of these assertions fire, then your thread may
219 have overflowed its stack. Each thread has less than 4 kB
220 of stack, so a few big automatic arrays or moderate
221 recursion can cause stack overflow. */
222 ASSERT (is_thread (t));
223 ASSERT (t->status == THREAD_RUNNING);
228 /* Returns the running thread's tid. */
232 return thread_current ()->tid;
235 /* Deschedules the current thread and destroys it. Never
236 returns to the caller. */
240 ASSERT (!intr_context ());
242 /* Just set our status to dying and schedule another process.
243 We will be destroyed during the call to schedule_tail(). */
245 thread_current ()->status = THREAD_DYING;
250 /* Yields the CPU. The current thread is not put to sleep and
251 may be scheduled again immediately at the scheduler's whim. */
255 struct thread *cur = thread_current ();
256 enum intr_level old_level;
258 ASSERT (!intr_context ());
260 old_level = intr_disable ();
261 list_push_back (&ready_list, &cur->elem);
262 cur->status = THREAD_READY;
264 intr_set_level (old_level);
267 /* Puts the current thread to sleep. It will not be scheduled
268 again until awoken by thread_unblock().
270 This function must be called with interrupts turned off. It
271 is usually a better idea to use one of the synchronization
272 primitives in synch.h. */
276 ASSERT (!intr_context ());
277 ASSERT (intr_get_level () == INTR_OFF);
279 thread_current ()->status = THREAD_BLOCKED;
283 /* Idle thread. Executes when no other thread is ready to run. */
285 idle (void *aux UNUSED)
287 idle_thread = thread_current ();
291 /* Let someone else run. */
296 /* Use CPU `hlt' instruction to wait for interrupt. */
301 /* Function used as the basis for a kernel thread. */
303 kernel_thread (thread_func *function, void *aux)
305 ASSERT (function != NULL);
307 intr_enable (); /* The scheduler runs with interrupts off. */
308 function (aux); /* Execute the thread function. */
309 thread_exit (); /* If function() returns, kill the thread. */
312 /* Returns the running thread. */
314 running_thread (void)
318 /* Copy the CPU's stack pointer into `esp', and then round that
319 down to the start of a page. Because `struct thread' is
320 always at the beginning of a page and the stack pointer is
321 somewhere in the middle, this locates the curent thread. */
322 asm ("movl %%esp, %0\n" : "=g" (esp));
323 return pg_round_down (esp);
326 /* Returns true if T appears to point to a valid thread. */
328 is_thread (struct thread *t)
330 return t != NULL && t->magic == THREAD_MAGIC;
333 /* Creates a new thread named NAME and initializes its fields.
334 Returns the new thread if successful or a null pointer on
336 static struct thread *
337 new_thread (const char *name)
341 ASSERT (name != NULL);
343 t = palloc_get (PAL_ZERO);
345 init_thread (t, name);
350 /* Initializes T as a new, blocked thread named NAME. */
352 init_thread (struct thread *t, const char *name)
354 memset (t, 0, sizeof *t);
355 t->status = THREAD_BLOCKED;
356 strlcpy (t->name, name, sizeof t->name);
357 t->stack = (uint8_t *) t + PGSIZE;
358 t->magic = THREAD_MAGIC;
361 /* Allocates a SIZE-byte frame at the top of thread T's stack and
362 returns a pointer to the frame's base. */
364 alloc_frame (struct thread *t, size_t size)
366 /* Stack data is always allocated in word-size units. */
367 ASSERT (is_thread (t));
368 ASSERT (size % sizeof (uint32_t) == 0);
374 /* Chooses and returns the next thread to be scheduled. Should
375 return a thread from the run queue, unless the run queue is
376 empty. (If the running thread can continue running, then it
377 will be in the run queue.) If the run queue is empty, return
379 static struct thread *
380 next_thread_to_run (void)
382 if (list_empty (&ready_list))
385 return list_entry (list_pop_front (&ready_list), struct thread, elem);
388 /* Destroys T, which must be in the dying state and must not be
389 the running thread. */
391 destroy_thread (struct thread *t)
393 ASSERT (is_thread (t));
394 ASSERT (t->status == THREAD_DYING);
395 ASSERT (t != thread_current ());
398 addrspace_destroy (t);
400 if (t != initial_thread)
404 /* Completes a thread switch by activating the new thread's page
405 tables, and, if the previous thread is dying, destroying it.
407 At this function's invocation, we just switched from thread
408 PREV, the new thread is already running, and interrupts are
409 still disabled. This function is normally invoked by
410 thread_schedule() as its final action before returning, but
411 the first time a thread is scheduled it is called by
412 switch_entry() (see switch.S).
414 After this function and its caller returns, the thread switch
417 schedule_tail (struct thread *prev)
419 struct thread *cur = running_thread ();
421 ASSERT (intr_get_level () == INTR_OFF);
423 /* Mark us as running. */
424 cur->status = THREAD_RUNNING;
427 /* Activate the new address space. */
428 addrspace_activate (cur);
431 /* If the thread we switched from is dying, destroy it.
432 This must happen late because it's not a good idea to
433 e.g. destroy the page table you're currently using. */
434 if (prev != NULL && prev->status == THREAD_DYING)
435 destroy_thread (prev);
438 /* Schedules a new process. At entry, interrupts must be off and
439 the running process's state must have been changed from
440 running to some other state. This function finds another
441 thread to run and switches to it. */
445 struct thread *cur = running_thread ();
446 struct thread *next = next_thread_to_run ();
447 struct thread *prev = NULL;
449 ASSERT (intr_get_level () == INTR_OFF);
450 ASSERT (cur->status != THREAD_RUNNING);
451 ASSERT (is_thread (next));
454 prev = switch_threads (cur, next);
455 schedule_tail (prev);
458 /* Returns a tid to use for a new thread. */
462 static tid_t next_tid = 1;
465 lock_acquire (&tid_lock);
467 lock_release (&tid_lock);
472 /* Offset of `stack' member within `struct thread'.
473 Used by switch.S, which can't figure it out on its own. */
474 uint32_t thread_stack_ofs = offsetof (struct thread, stack);