1 /* See COPYRIGHT for copyright information. */
21 #include <ros/syscall.h>
23 env_t *envs = NULL; // All environments
24 // TODO: make this a struct of info including the pointer and cacheline-align it
25 // This lets the kernel know what process is running on the core it traps into.
26 // A lot of the Env business, including this and its usage, will change when we
27 // redesign the env as a multi-process.
28 env_t* curenvs[MAX_NUM_CPUS] = {[0 ... (MAX_NUM_CPUS-1)] NULL};
29 static env_list_t env_free_list; // Free list
31 #define ENVGENSHIFT 12 // >= LOGNENV
34 // Converts an envid to an env pointer.
37 // 0 on success, -E_BAD_ENV on error.
38 // On success, sets *env_store to the environment.
39 // On error, sets *env_store to NULL.
42 envid2env(envid_t envid, env_t **env_store, bool checkperm)
45 env_t* curenv = curenvs[lapic_get_id()];
47 // If envid is zero, return the current environment.
53 // Look up the Env structure via the index part of the envid,
54 // then check the env_id field in that env_t
55 // to ensure that the envid is not stale
56 // (i.e., does not refer to a _previous_ environment
57 // that used the same slot in the envs[] array).
58 e = &envs[ENVX(envid)];
59 if (e->env_status == ENV_FREE || e->env_id != envid) {
64 // Check that the calling environment has legitimate permission
65 // to manipulate the specified environment.
66 // If checkperm is set, the specified environment
67 // must be either the current environment
68 // or an immediate child of the current environment.
69 if (checkperm && e != curenv && e->env_parent_id != curenv->env_id) {
79 // Mark all environments in 'envs' as free, set their env_ids to 0,
80 // and insert them into the env_free_list.
81 // Insert in reverse order, so that the first call to env_alloc()
88 LIST_INIT(&env_free_list);
89 for (i = NENV-1; i >= 0; i--) {
90 // these should already be set from when i memset'd the array to 0
91 envs[i].env_status = ENV_FREE;
93 LIST_INSERT_HEAD(&env_free_list, &envs[i], env_link);
98 // Initialize the kernel virtual memory layout for environment e.
99 // Allocate a page directory, set e->env_pgdir and e->env_cr3 accordingly,
100 // and initialize the kernel portion of the new environment's address space.
101 // Do NOT (yet) map anything into the user portion
102 // of the environment's virtual address space.
104 // Returns 0 on success, < 0 on error. Errors include:
105 // -E_NO_MEM if page directory or table could not be allocated.
108 env_setup_vm(env_t *e)
111 page_t *pgdir = NULL, *pginfo = NULL, *pgdata = NULL;
113 // Allocate pages for the page directory, shared info, and shared data pages
114 r = page_alloc(&pgdir);
115 r = page_alloc(&pginfo);
116 r = page_alloc(&pgdata);
123 // Now, set e->env_pgdir and e->env_cr3,
124 // and initialize the page directory.
127 // - The VA space of all envs is identical above UTOP
128 // (except at VPT and UVPT, which we've set below).
129 // (and not for UINFO either)
130 // See inc/memlayout.h for permissions and layout.
131 // Can you use boot_pgdir as a template? Hint: Yes.
132 // (Make sure you got the permissions right in Lab 2.)
133 // - The initial VA below UTOP is empty.
134 // - You do not need to make any more calls to page_alloc.
135 // - Note: pp_ref is not maintained for most physical pages
136 // mapped above UTOP -- but you do need to increment
137 // env_pgdir's pp_ref!
139 // need to up pgdir's reference, since it will never be done elsewhere
141 e->env_pgdir = page2kva(pgdir);
142 e->env_cr3 = page2pa(pgdir);
143 e->env_procinfo = page2kva(pginfo);
144 e->env_procdata = page2kva(pgdata);
146 memset(e->env_pgdir, 0, PGSIZE);
147 memset(e->env_procinfo, 0, PGSIZE);
148 memset(e->env_procdata, 0, PGSIZE);
150 // Initialize the generic syscall ring buffer
151 SHARED_RING_INIT((syscall_sring_t*)e->env_procdata);
152 // Initialize the backend of the ring buffer
153 BACK_RING_INIT(&e->env_sysbackring, (syscall_sring_t*)e->env_procdata, PGSIZE);
155 // should be able to do this so long as boot_pgdir never has
156 // anything put below UTOP
157 memcpy(e->env_pgdir, boot_pgdir, PGSIZE);
159 // something like this. TODO, if you want
160 //memcpy(&e->env_pgdir[PDX(UTOP)], &boot_pgdir[PDX(UTOP)], PGSIZE - PDX(UTOP));
162 // assert(memcmp(e->env_pgdir, boot_pgdir, PGSIZE) == 0);
164 // VPT and UVPT map the env's own page table, with
165 // different permissions.
166 e->env_pgdir[PDX(VPT)] = e->env_cr3 | PTE_P | PTE_W;
167 e->env_pgdir[PDX(UVPT)] = e->env_cr3 | PTE_P | PTE_U;
169 // Insert the per-process info and data pages into this process's pgdir
170 // I don't want to do these two pages later (like with the stack), since
171 // the kernel wants to keep pointers to it easily.
172 // Could place all of this with a function that maps a shared memory page
173 // that can work between any two address spaces or something.
174 r = page_insert(e->env_pgdir, pginfo, (void*)UINFO, PTE_U);
175 r = page_insert(e->env_pgdir, pgdata, (void*)UDATA, PTE_U | PTE_W);
177 // note that we can't currently deallocate the pages created by
178 // pgdir_walk (inside insert). should be able to gather them up when
179 // we destroy environments and their page tables.
189 // Allocates and initializes a new environment.
190 // On success, the new environment is stored in *newenv_store.
192 // Returns 0 on success, < 0 on failure. Errors include:
193 // -E_NO_FREE_ENV if all NENVS environments are allocated
194 // -E_NO_MEM on memory exhaustion
197 env_alloc(env_t **newenv_store, envid_t parent_id)
203 if (!(e = LIST_FIRST(&env_free_list)))
204 return -E_NO_FREE_ENV;
206 // Allocate and set up the page directory for this environment.
207 if ((r = env_setup_vm(e)) < 0)
210 // Generate an env_id for this environment.
211 generation = (e->env_id + (1 << ENVGENSHIFT)) & ~(NENV - 1);
212 if (generation <= 0) // Don't create a negative env_id.
213 generation = 1 << ENVGENSHIFT;
214 e->env_id = generation | (e - envs);
216 // Set the basic status variables.
217 e->env_parent_id = parent_id;
218 e->env_status = ENV_RUNNABLE;
221 // Clear out all the saved register state,
222 // to prevent the register values
223 // of a prior environment inhabiting this Env structure
224 // from "leaking" into our new environment.
225 memset(&e->env_tf, 0, sizeof(e->env_tf));
227 // Set up appropriate initial values for the segment registers.
228 // GD_UD is the user data segment selector in the GDT, and
229 // GD_UT is the user text segment selector (see inc/memlayout.h).
230 // The low 2 bits of each segment register contains the
231 // Requestor Privilege Level (RPL); 3 means user mode.
232 e->env_tf.tf_ds = GD_UD | 3;
233 e->env_tf.tf_es = GD_UD | 3;
234 e->env_tf.tf_ss = GD_UD | 3;
235 e->env_tf.tf_esp = USTACKTOP;
236 e->env_tf.tf_cs = GD_UT | 3;
237 // You will set e->env_tf.tf_eip later.
238 // set the env's EFLAGSs to have interrupts enabled
239 e->env_tf.tf_eflags |= 0x00000200; // bit 9 is the interrupts-enabled
241 // commit the allocation
242 LIST_REMOVE(e, env_link);
245 e->env_tscfreq = system_timing.tsc_freq;
246 // TODO: for now, the only info at procinfo is this env's struct
247 // note that we need to copy this over every time we make a change to env
248 // that we want userspace to see. also note that we don't even want to
249 // show them all of env, only specific things like PID, PPID, etc
250 memcpy(e->env_procinfo, e, sizeof(env_t));
252 env_t* curenv = curenvs[lapic_get_id()];
254 cprintf("[%08x] new env %08x\n", curenv ? curenv->env_id : 0, e->env_id);
259 // Allocate len bytes of physical memory for environment env,
260 // and map it at virtual address va in the environment's address space.
261 // Does not zero or otherwise initialize the mapped pages in any way.
262 // Pages should be writable by user and kernel.
263 // Panic if any allocation attempt fails.
266 segment_alloc(env_t *e, void *va, size_t len)
274 start = ROUNDDOWN(va, PGSIZE);
275 end = ROUNDUP(va + len, PGSIZE);
277 panic("Wrap-around in memory allocation addresses!");
278 if ((uintptr_t)end > UTOP)
279 panic("Attempting to map above UTOP!");
280 // page_insert/pgdir_walk alloc a page and read/write to it via its address
281 // starting from pgdir (e's), so we need to be using e's pgdir
282 assert(e->env_cr3 == rcr3());
283 num_pages = PPN(end - start);
284 for (i = 0; i < num_pages; i++, start += PGSIZE) {
285 // skip if a page is already mapped. yes, page_insert will page_remove
286 // whatever page was already there, but if we are seg allocing adjacent
287 // regions, we don't want to destroy that old mapping/page
288 // though later on we are told we can ignore this...
289 pte = pgdir_walk(e->env_pgdir, start, 0);
290 if (pte && *pte & PTE_P)
292 if ((r = page_alloc(&page)) < 0)
293 panic("segment_alloc: %e", r);
294 page_insert(e->env_pgdir, page, start, PTE_U | PTE_W);
299 // Set up the initial program binary, stack, and processor flags
300 // for a user process.
301 // This function is ONLY called during kernel initialization,
302 // before running the first user-mode environment.
304 // This function loads all loadable segments from the ELF binary image
305 // into the environment's user memory, starting at the appropriate
306 // virtual addresses indicated in the ELF program header.
307 // At the same time it clears to zero any portions of these segments
308 // that are marked in the program header as being mapped
309 // but not actually present in the ELF file - i.e., the program's bss section.
311 // All this is very similar to what our boot loader does, except the boot
312 // loader also needs to read the code from disk. Take a look at
313 // boot/main.c to get ideas.
315 // Finally, this function maps one page for the program's initial stack.
317 // load_icode panics if it encounters problems.
318 // - How might load_icode fail? What might be wrong with the given input?
321 load_icode(env_t *e, uint8_t *binary, size_t size)
324 // Load each program segment into virtual memory
325 // at the address specified in the ELF section header.
326 // You should only load segments with ph->p_type == ELF_PROG_LOAD.
327 // Each segment's virtual address can be found in ph->p_va
328 // and its size in memory can be found in ph->p_memsz.
329 // The ph->p_filesz bytes from the ELF binary, starting at
330 // 'binary + ph->p_offset', should be copied to virtual address
331 // ph->p_va. Any remaining memory bytes should be cleared to zero.
332 // (The ELF header should have ph->p_filesz <= ph->p_memsz.)
333 // Use functions from the previous lab to allocate and map pages.
335 // All page protection bits should be user read/write for now.
336 // ELF segments are not necessarily page-aligned, but you can
337 // assume for this function that no two segments will touch
338 // the same virtual page.
340 // You may find a function like segment_alloc useful.
342 // Loading the segments is much simpler if you can move data
343 // directly into the virtual addresses stored in the ELF binary.
344 // So which page directory should be in force during
348 // You must also do something with the program's entry point,
349 // to make sure that the environment starts executing there.
350 // What? (See env_run() and env_pop_tf() below.)
352 elf_t *elfhdr = (elf_t *)binary;
356 assert(elfhdr->e_magic == ELF_MAGIC);
357 // make sure we have proghdrs to load
358 assert(elfhdr->e_phnum);
360 // to actually access any pages alloc'd for this environment, we
361 // need to have the hardware use this environment's page tables.
362 // we can use e's tables as long as we want, since it has the same
363 // mappings for the kernel as does boot_pgdir
366 proghdr_t *phdr = (proghdr_t *)(binary + elfhdr->e_phoff);
367 for (i = 0; i < elfhdr->e_phnum; i++, phdr++) {
368 if (phdr->p_type != ELF_PROG_LOAD)
370 // seg alloc creates PTE_U|PTE_W pages. if you ever want to change
371 // this, there will be issues with overlapping sections
372 segment_alloc(e, (void*)phdr->p_va, phdr->p_memsz);
373 memcpy((void*)phdr->p_va, binary + phdr->p_offset, phdr->p_filesz);
374 memset((void*)phdr->p_va + phdr->p_filesz, 0, phdr->p_memsz - phdr->p_filesz);
377 e->env_tf.tf_eip = elfhdr->e_entry;
379 // Now map one page for the program's initial stack
380 // at virtual address USTACKTOP - PGSIZE.
382 segment_alloc(e, (void*)(USTACKTOP - PGSIZE), PGSIZE);
386 // Allocates a new env and loads the named elf binary into it.
388 env_t* env_create(uint8_t *binary, size_t size)
393 if ((r = env_alloc(&e, 0)) < 0)
394 panic("env_create: %e", r);
395 load_icode(e, binary, size);
400 // Frees env e and all memory it uses.
406 uint32_t pdeno, pteno;
409 // Note the environment's demise.
410 env_t* curenv = curenvs[lapic_get_id()];
411 cprintf("[%08x] free env %08x\n", curenv ? curenv->env_id : 0, e->env_id);
413 // Flush all mapped pages in the user portion of the address space
414 static_assert(UTOP % PTSIZE == 0);
415 for (pdeno = 0; pdeno < PDX(UTOP); pdeno++) {
417 // only look at mapped page tables
418 if (!(e->env_pgdir[pdeno] & PTE_P))
421 // find the pa and va of the page table
422 pa = PTE_ADDR(e->env_pgdir[pdeno]);
423 pt = (pte_t*) KADDR(pa);
425 // unmap all PTEs in this page table
426 for (pteno = 0; pteno <= PTX(~0); pteno++) {
427 if (pt[pteno] & PTE_P)
428 page_remove(e->env_pgdir, PGADDR(pdeno, pteno, 0));
431 // free the page table itself
432 e->env_pgdir[pdeno] = 0;
433 page_decref(pa2page(pa));
436 // need a known good pgdir before releasing the old one
439 // free the page directory
443 page_decref(pa2page(pa));
445 // return the environment to the free list
446 e->env_status = ENV_FREE;
447 LIST_INSERT_HEAD(&env_free_list, e, env_link);
451 // Frees environment e.
452 // If e was the current env, then runs a new environment (and does not return
456 env_destroy(env_t *e)
461 // for old envs that die on user cores. since env run never returns, cores
462 // never get back to their old hlt/relaxed/spin state, so we need to force
463 // them back to an idle function.
464 uint32_t id = lapic_get_id();
465 // There is no longer a curenv for this core. (TODO: Think about this.)
469 panic("should never see me");
471 // else we're core 0 and can do the usual
473 /* Instead of picking a new environment to run, or defaulting to the monitor
474 * like before, for now we'll hop into the manager() function, which
475 * dispatches jobs. Note that for now we start the manager from the top,
476 * and not from where we left off the last time we called manager. That
477 * would require us to save some context (and a stack to work on) here.
480 assert(0); // never get here
482 // ugly, but for now just linearly search through all possible
483 // environments for a runnable one.
484 for (int i = 0; i < NENV; i++) {
486 // TODO: race here, if another core is just about to start this env.
487 // Fix it by setting the status in something like env_dispatch when
488 // we have multi-contexted processes
489 if (e && e->env_status == ENV_RUNNABLE)
492 cprintf("Destroyed the only environment - nothing more to do!\n");
499 // Restores the register values in the Trapframe with the 'iret' instruction.
500 // This exits the kernel and starts executing some environment's code.
501 // This function does not return.
504 env_pop_tf(trapframe_t *tf)
506 __asm __volatile("movl %0,%%esp\n"
510 "\taddl $0x8,%%esp\n" /* skip tf_trapno and tf_errcode */
512 : : "g" (tf) : "memory");
513 panic("iret failed"); /* mostly to placate the compiler */
517 // Context switch from curenv to env e.
518 // Note: if this is the first call to env_run, curenv is NULL.
519 // (This function does not return.)
524 // Step 1: If this is a context switch (a new environment is running),
525 // then set 'curenv' to the new environment,
526 // update its 'env_runs' counter, and
527 // and use lcr3() to switch to its address space.
528 // Step 2: Use env_pop_tf() to restore the environment's
529 // registers and drop into user mode in the
532 // Hint: This function loads the new environment's state from
533 // e->env_tf. Go back through the code you wrote above
534 // and make sure you have set the relevant parts of
535 // e->env_tf to sensible values.
537 e->env_status = ENV_RUNNING;
538 if (e != curenvs[lapic_get_id()]) {
539 curenvs[lapic_get_id()] = e;
543 env_pop_tf(&e->env_tf);