bug in serve_close fixed.
[mit-jos.git] / kern / env.c
blob6895d67ef490ab59faede16be77feb1239c7199f
1 /* See COPYRIGHT for copyright information. */
3 #include <inc/x86.h>
4 #include <inc/mmu.h>
5 #include <inc/error.h>
6 #include <inc/string.h>
7 #include <inc/assert.h>
8 #include <inc/elf.h>
10 #include <kern/env.h>
11 #include <kern/pmap.h>
12 #include <kern/trap.h>
13 #include <kern/monitor.h>
14 #include <kern/sched.h>
16 struct Env *envs = NULL; // All environments
17 struct Env *curenv = NULL; // The current env
18 static struct Env_list env_free_list; // Free list
20 #define ENVGENSHIFT 12 // >= LOGNENV
23 // Converts an envid to an env pointer.
25 // RETURNS
26 // 0 on success, -E_BAD_ENV on error.
27 // On success, sets *penv to the environment.
28 // On error, sets *penv to NULL.
30 int
31 envid2env(envid_t envid, struct Env **env_store, bool checkperm)
33 struct Env *e;
35 // If envid is zero, return the current environment.
36 if (envid == 0) {
37 *env_store = curenv;
38 return 0;
41 // Look up the Env structure via the index part of the envid,
42 // then check the env_id field in that struct Env
43 // to ensure that the envid is not stale
44 // (i.e., does not refer to a _previous_ environment
45 // that used the same slot in the envs[] array).
46 e = &envs[ENVX(envid)];
47 if (e->env_status == ENV_FREE || e->env_id != envid) {
48 *env_store = 0;
49 return -E_BAD_ENV;
52 // Check that the calling environment has legitimate permission
53 // to manipulate the specified environment.
54 // If checkperm is set, the specified environment
55 // must be either the current environment
56 // or an immediate child of the current environment.
57 if (checkperm && e != curenv && e->env_parent_id != curenv->env_id) {
58 *env_store = 0;
59 return -E_BAD_ENV;
62 *env_store = e;
63 return 0;
67 // Mark all environments in 'envs' as free, set their env_ids to 0,
68 // and insert them into the env_free_list.
69 // Insert in reverse order, so that the first call to env_alloc()
70 // returns envs[0].
72 void
73 env_init(void)
75 // LAB 3: Your code here.
76 int i;
78 LIST_INIT(&env_free_list);
79 for (i = NENV-1; i >= 0; i--) {
80 envs[i].env_id = 0;
81 LIST_INSERT_HEAD(&env_free_list, &envs[i], env_link);
86 // Initialize the kernel virtual memory layout for environment e.
87 // Allocate a page directory, set e->env_pgdir and e->env_cr3 accordingly,
88 // and initialize the kernel portion of the new environment's address space.
89 // Do NOT (yet) map anything into the user portion
90 // of the environment's virtual address space.
92 // Returns 0 on success, < 0 on error. Errors include:
93 // -E_NO_MEM if page directory or table could not be allocated.
95 static int
96 env_setup_vm(struct Env *e)
98 int i, r;
99 struct Page *p = NULL;
101 // Allocate a page for the page directory
102 if ((r = page_alloc(&p)) < 0)
103 return r;
105 // Now, set e->env_pgdir and e->env_cr3,
106 // and initialize the page directory.
108 // Hint:
109 // - The VA space of all envs is identical above UTOP
110 // (except at VPT and UVPT, which we've set below).
111 // See inc/memlayout.h for permissions and layout.
112 // Can you use boot_pgdir as a template? Hint: Yes.
113 // (Make sure you got the permissions right in Lab 2.)
114 // - The initial VA below UTOP is empty.
115 // - You do not need to make any more calls to page_alloc.
116 // - Note: pp_ref is not maintained for most physical pages
117 // mapped above UTOP -- but you do need to increment
118 // env_pgdir's pp_ref!
119 // LAB 3: Your code here.
120 p->pp_ref++;
121 e->env_pgdir = page2kva(p);
122 e->env_cr3 = PADDR(e->env_pgdir);
123 memset(e->env_pgdir, 0, PDX(UTOP) * 4);
124 memmove(e->env_pgdir + PDX(UTOP), boot_pgdir + PDX(UTOP),
125 PGSIZE - PDX(UTOP) * 4);
127 // VPT and UVPT map the env's own page table, with
128 // different permissions.
129 e->env_pgdir[PDX(VPT)] = e->env_cr3 | PTE_P | PTE_W;
130 e->env_pgdir[PDX(UVPT)] = e->env_cr3 | PTE_P | PTE_U;
132 return 0;
136 // Allocates and initializes a new environment.
137 // On success, the new environment is stored in *newenv_store.
139 // Returns 0 on success, < 0 on failure. Errors include:
140 // -E_NO_FREE_ENV if all NENVS environments are allocated
141 // -E_NO_MEM on memory exhaustion
144 env_alloc(struct Env **newenv_store, envid_t parent_id)
146 int32_t generation;
147 int r;
148 struct Env *e;
150 if (!(e = LIST_FIRST(&env_free_list)))
151 return -E_NO_FREE_ENV;
153 // Allocate and set up the page directory for this environment.
154 if ((r = env_setup_vm(e)) < 0)
155 return r;
157 // Generate an env_id for this environment.
158 generation = (e->env_id + (1 << ENVGENSHIFT)) & ~(NENV - 1);
159 if (generation <= 0) // Don't create a negative env_id.
160 generation = 1 << ENVGENSHIFT;
161 e->env_id = generation | (e - envs);
163 // Set the basic status variables.
164 e->env_parent_id = parent_id;
165 e->env_status = ENV_RUNNABLE;
166 e->env_runs = 0;
168 // Clear out all the saved register state,
169 // to prevent the register values
170 // of a prior environment inhabiting this Env structure
171 // from "leaking" into our new environment.
172 memset(&e->env_tf, 0, sizeof(e->env_tf));
174 // Set up appropriate initial values for the segment registers.
175 // GD_UD is the user data segment selector in the GDT, and
176 // GD_UT is the user text segment selector (see inc/memlayout.h).
177 // The low 2 bits of each segment register contains the
178 // Requestor Privilege Level (RPL); 3 means user mode.
179 e->env_tf.tf_ds = GD_UD | 3;
180 e->env_tf.tf_es = GD_UD | 3;
181 e->env_tf.tf_ss = GD_UD | 3;
182 e->env_tf.tf_esp = USTACKTOP;
183 e->env_tf.tf_cs = GD_UT | 3;
184 // You will set e->env_tf.tf_eip later.
186 // Enable interrupts while in user mode.
187 // LAB 4: Your code here.
188 e->env_tf.tf_eflags |= FL_IF;
190 // Clear the page fault handler until user installs one.
191 e->env_pgfault_upcall = 0;
193 // Also clear the IPC receiving flag.
194 e->env_ipc_recving = 0;
196 // If this is the file server (e == &envs[1]) give it I/O privileges.
197 // LAB 5: Your code here.
198 if (e == &envs[1])
199 e->env_tf.tf_eflags |= FL_IOPL_3;
201 // commit the allocation
202 LIST_REMOVE(e, env_link);
203 *newenv_store = e;
205 // cprintf("[%08x] new env %08x\n", curenv ? curenv->env_id : 0, e->env_id);
206 return 0;
210 // Allocate len bytes of physical memory for environment env,
211 // and map it at virtual address va in the environment's address space.
212 // Does not zero or otherwise initialize the mapped pages in any way.
213 // Pages should be writable by user and kernel.
214 // Panic if any allocation attempt fails.
216 static void
217 segment_alloc(struct Env *e, void *va, size_t len)
219 // LAB 3: Your code here.
220 // (But only if you need it for load_icode.)
222 // Hint: It is easier to use segment_alloc if the caller can pass
223 // 'va' and 'len' values that are not page-aligned.
224 // You should round va down, and round len up.
225 struct Page *p;
226 void *va_end;
227 int r;
229 va_end = va + len;
230 va = ROUNDDOWN(va, PGSIZE);
231 while (va < va_end) {
232 if ((r = page_alloc(&p)) < 0)
233 panic("segment_alloc: %e", r);
235 if ((r = page_insert(e->env_pgdir, p, va, PTE_W |PTE_U)) < 0)
236 panic("segment_alloc: %e", r);
238 va += PGSIZE;
243 // Set up the initial program binary, stack, and processor flags
244 // for a user process.
245 // This function is ONLY called during kernel initialization,
246 // before running the first user-mode environment.
248 // This function loads all loadable segments from the ELF binary image
249 // into the environment's user memory, starting at the appropriate
250 // virtual addresses indicated in the ELF program header.
251 // At the same time it clears to zero any portions of these segments
252 // that are marked in the program header as being mapped
253 // but not actually present in the ELF file - i.e., the program's bss section.
255 // All this is very similar to what our boot loader does, except the boot
256 // loader also needs to read the code from disk. Take a look at
257 // boot/main.c to get ideas.
259 // Finally, this function maps one page for the program's initial stack.
261 // load_icode panics if it encounters problems.
262 // - How might load_icode fail? What might be wrong with the given input?
264 static void
265 load_icode(struct Env *e, uint8_t *binary, size_t size)
267 // Hints:
268 // Load each program segment into virtual memory
269 // at the address specified in the ELF section header.
270 // You should only load segments with ph->p_type == ELF_PROG_LOAD.
271 // Each segment's virtual address can be found in ph->p_va
272 // and its size in memory can be found in ph->p_memsz.
273 // The ph->p_filesz bytes from the ELF binary, starting at
274 // 'binary + ph->p_offset', should be copied to virtual address
275 // ph->p_va. Any remaining memory bytes should be cleared to zero.
276 // (The ELF header should have ph->p_filesz <= ph->p_memsz.)
277 // Use functions from the previous lab to allocate and map pages.
279 // All page protection bits should be user read/write for now.
280 // ELF segments are not necessarily page-aligned, but you can
281 // assume for this function that no two segments will touch
282 // the same virtual page.
284 // You may find a function like segment_alloc useful.
286 // Loading the segments is much simpler if you can move data
287 // directly into the virtual addresses stored in the ELF binary.
288 // So which page directory should be in force during
289 // this function?
291 // Hint:
292 // You must also do something with the program's entry point,
293 // to make sure that the environment starts executing there.
294 // What? (See env_run() and env_pop_tf() below.)
295 // LAB 3: Your code here.
296 struct Page *p;
297 struct Proghdr *ph;
298 int r, ph_num;
300 // basic sanity check for elf image
301 if (((struct Elf *)binary)->e_magic != ELF_MAGIC)
302 panic("load_icode: not an elf image!\n");
304 ph = (struct Proghdr *)(binary + ((struct Elf *)binary)->e_phoff);
305 ph_num = ((struct Elf *)binary)->e_phnum;
307 lcr3(e->env_cr3);
308 while (--ph_num >= 0) {
309 if (ph->p_type == ELF_PROG_LOAD) {
310 segment_alloc(e, (void *)ph->p_va, ph->p_memsz);
312 memmove((void *)ph->p_va, binary + ph->p_offset, ph->p_filesz);
313 memset((void *)(ph->p_va + ph->p_filesz), 0, ph->p_memsz - ph->p_filesz);
315 ph++;
317 lcr3(boot_cr3);
319 e->env_tf.tf_eip = ((struct Elf *)binary)->e_entry;
321 // Now map one page for the program's initial stack
322 // at virtual address USTACKTOP - PGSIZE.
323 // LAB 3: Your code here.
324 if ((r = page_alloc(&p)) < 0)
325 panic("load_icode: %e", r);
326 if ((r = page_insert(e->env_pgdir,
328 (void *)(USTACKTOP - PGSIZE),
329 PTE_W | PTE_U)) < 0)
330 panic("load_icode: %e", r);
334 // Allocates a new env and loads the named elf binary into it.
335 // This function is ONLY called during kernel initialization,
336 // before running the first user-mode environment.
337 // The new env's parent ID is set to 0.
339 // Where does the result go?
340 // By convention, envs[0] is the first environment allocated, so
341 // whoever calls env_create simply looks for the newly created
342 // environment there.
343 void
344 env_create(uint8_t *binary, size_t size)
346 // LAB 3: Your code here.
347 struct Env *e;
348 int r;
350 if ((r = env_alloc(&e, 0)) < 0)
351 panic("env_create: %e", r);
353 load_icode(e, binary, size);
357 // Frees env e and all memory it uses.
359 void
360 env_free(struct Env *e)
362 pte_t *pt;
363 uint32_t pdeno, pteno;
364 physaddr_t pa;
366 // If freeing the current environment, switch to boot_pgdir
367 // before freeing the page directory, just in case the page
368 // gets reused.
369 if (e == curenv)
370 lcr3(boot_cr3);
372 // Note the environment's demise.
373 // cprintf("[%08x] free env %08x\n", curenv ? curenv->env_id : 0, e->env_id);
375 // Flush all mapped pages in the user portion of the address space
376 static_assert(UTOP % PTSIZE == 0);
377 for (pdeno = 0; pdeno < PDX(UTOP); pdeno++) {
379 // only look at mapped page tables
380 if (!(e->env_pgdir[pdeno] & PTE_P))
381 continue;
383 // find the pa and va of the page table
384 pa = PTE_ADDR(e->env_pgdir[pdeno]);
385 pt = (pte_t*) KADDR(pa);
387 // unmap all PTEs in this page table
388 for (pteno = 0; pteno <= PTX(~0); pteno++) {
389 if (pt[pteno] & PTE_P)
390 page_remove(e->env_pgdir, PGADDR(pdeno, pteno, 0));
393 // free the page table itself
394 e->env_pgdir[pdeno] = 0;
395 page_decref(pa2page(pa));
398 // free the page directory
399 pa = e->env_cr3;
400 e->env_pgdir = 0;
401 e->env_cr3 = 0;
402 page_decref(pa2page(pa));
404 // return the environment to the free list
405 e->env_status = ENV_FREE;
406 LIST_INSERT_HEAD(&env_free_list, e, env_link);
410 // Frees environment e.
411 // If e was the current env, then runs a new environment (and does not return
412 // to the caller).
414 void
415 env_destroy(struct Env *e)
417 env_free(e);
419 if (curenv == e) {
420 curenv = NULL;
421 sched_yield();
427 // Restores the register values in the Trapframe with the 'iret' instruction.
428 // This exits the kernel and starts executing some environment's code.
429 // This function does not return.
431 void
432 env_pop_tf(struct Trapframe *tf)
434 __asm __volatile("movl %0,%%esp\n"
435 "\tpopal\n"
436 "\tpopl %%es\n"
437 "\tpopl %%ds\n"
438 "\taddl $0x8,%%esp\n" /* skip tf_trapno and tf_errcode */
439 "\tiret"
440 : : "g" (tf) : "memory");
441 panic("iret failed"); /* mostly to placate the compiler */
445 // Context switch from curenv to env e.
446 // Note: if this is the first call to env_run, curenv is NULL.
447 // (This function does not return.)
449 void
450 env_run(struct Env *e)
452 // Step 1: If this is a context switch (a new environment is running),
453 // then set 'curenv' to the new environment,
454 // update its 'env_runs' counter, and
455 // and use lcr3() to switch to its address space.
456 // Step 2: Use env_pop_tf() to restore the environment's
457 // registers and drop into user mode in the
458 // environment.
460 // Hint: This function loads the new environment's state from
461 // e->env_tf. Go back through the code you wrote above
462 // and make sure you have set the relevant parts of
463 // e->env_tf to sensible values.
465 // LAB 3: Your code here.
466 curenv = e;
467 e->env_runs++;
468 lcr3(e->env_cr3);
470 env_pop_tf(&e->env_tf);