1 /* See COPYRIGHT for copyright information. */
11 #include <arch/atomic.h>
21 #include <ros/syscall.h>
22 #include <ros/error.h>
24 env_t *envs = NULL; // All environments
25 uint32_t num_envs = 0; // Number of envs
26 // TODO: make this a struct of info including the pointer and cacheline-align it
27 // This lets the kernel know what process is running on the core it traps into.
28 // A lot of the Env business, including this and its usage, will change when we
29 // redesign the env as a multi-process.
30 env_t* curenvs[MAX_NUM_CPUS] = {[0 ... (MAX_NUM_CPUS-1)] NULL};
31 static env_list_t env_free_list; // Free list
33 #define ENVGENSHIFT 12 // >= LOGNENV
36 // Converts an envid to an env pointer.
39 // 0 on success, -E_BAD_ENV on error.
40 // On success, sets *env_store to the environment.
41 // On error, sets *env_store to NULL.
44 envid2env(envid_t envid, env_t **env_store, bool checkperm)
47 env_t* curenv = curenvs[lapic_get_id()];
49 // If envid is zero, return the current environment.
55 // Look up the Env structure via the index part of the envid,
56 // then check the env_id field in that env_t
57 // to ensure that the envid is not stale
58 // (i.e., does not refer to a _previous_ environment
59 // that used the same slot in the envs[] array).
60 e = &envs[ENVX(envid)];
61 if (e->env_status == ENV_FREE || e->env_id != envid) {
66 // Check that the calling environment has legitimate permission
67 // to manipulate the specified environment.
68 // If checkperm is set, the specified environment
69 // must be either the current environment
70 // or an immediate child of the current environment.
71 if (checkperm && e != curenv && e->env_parent_id != curenv->env_id) {
81 // Mark all environments in 'envs' as free, set their env_ids to 0,
82 // and insert them into the env_free_list.
83 // Insert in reverse order, so that the first call to env_alloc()
90 LIST_INIT(&env_free_list);
91 for (i = NENV-1; i >= 0; i--) {
92 // these should already be set from when i memset'd the array to 0
93 envs[i].env_status = ENV_FREE;
95 LIST_INSERT_HEAD(&env_free_list, &envs[i], env_link);
100 // Initialize the kernel virtual memory layout for environment e.
101 // Allocate a page directory, set e->env_pgdir and e->env_cr3 accordingly,
102 // and initialize the kernel portion of the new environment's address space.
103 // Do NOT (yet) map anything into the user portion
104 // of the environment's virtual address space.
106 // Returns 0 on success, < 0 on error. Errors include:
107 // -E_NO_MEM if page directory or table could not be allocated.
110 env_setup_vm(env_t *e)
113 page_t *pgdir = NULL, *pginfo = NULL, *pgdata = NULL;
115 // Allocate pages for the page directory, shared info, and shared data pages
116 r = page_alloc(&pgdir);
117 r = page_alloc(&pginfo);
118 r = page_alloc(&pgdata);
125 // Now, set e->env_pgdir and e->env_cr3,
126 // and initialize the page directory.
129 // - The VA space of all envs is identical above UTOP
130 // (except at VPT and UVPT, which we've set below).
131 // (and not for UINFO either)
132 // See inc/memlayout.h for permissions and layout.
133 // Can you use boot_pgdir as a template? Hint: Yes.
134 // (Make sure you got the permissions right in Lab 2.)
135 // - The initial VA below UTOP is empty.
136 // - You do not need to make any more calls to page_alloc.
137 // - Note: pp_ref is not maintained for most physical pages
138 // mapped above UTOP -- but you do need to increment
139 // env_pgdir's pp_ref!
141 // need to up pgdir's reference, since it will never be done elsewhere
143 e->env_pgdir = page2kva(pgdir);
144 e->env_cr3 = page2pa(pgdir);
145 e->env_procinfo = page2kva(pginfo);
146 e->env_procdata = page2kva(pgdata);
148 memset(e->env_pgdir, 0, PGSIZE);
149 memset(e->env_procinfo, 0, PGSIZE);
150 memset(e->env_procdata, 0, PGSIZE);
152 // Initialize the generic syscall ring buffer
153 SHARED_RING_INIT((syscall_sring_t*)e->env_procdata);
154 // Initialize the backend of the ring buffer
155 BACK_RING_INIT(&e->env_sysbackring, (syscall_sring_t*)e->env_procdata, PGSIZE);
157 // should be able to do this so long as boot_pgdir never has
158 // anything put below UTOP
159 memcpy(e->env_pgdir, boot_pgdir, PGSIZE);
161 // something like this. TODO, if you want
162 //memcpy(&e->env_pgdir[PDX(UTOP)], &boot_pgdir[PDX(UTOP)], PGSIZE - PDX(UTOP));
164 // assert(memcmp(e->env_pgdir, boot_pgdir, PGSIZE) == 0);
166 // VPT and UVPT map the env's own page table, with
167 // different permissions.
168 e->env_pgdir[PDX(VPT)] = e->env_cr3 | PTE_P | PTE_W;
169 e->env_pgdir[PDX(UVPT)] = e->env_cr3 | PTE_P | PTE_U;
171 // Insert the per-process info and data pages into this process's pgdir
172 // I don't want to do these two pages later (like with the stack), since
173 // the kernel wants to keep pointers to it easily.
174 // Could place all of this with a function that maps a shared memory page
175 // that can work between any two address spaces or something.
176 r = page_insert(e->env_pgdir, pginfo, (void*)UINFO, PTE_U);
177 r = page_insert(e->env_pgdir, pgdata, (void*)UDATA, PTE_U | PTE_W);
179 // note that we can't currently deallocate the pages created by
180 // pgdir_walk (inside insert). should be able to gather them up when
181 // we destroy environments and their page tables.
188 /* Shared page for all processes. Can't be trusted, but still very useful
189 * at this stage for us. Consider removing when we have real processes.
190 * (TODO). Note the page is alloced only the first time through
192 static page_t* shared_page = 0;
194 page_alloc(&shared_page);
195 // Up it, so it never goes away. One per user, plus one from page_alloc
196 // This is necessary, since it's in the per-process range of memory that
197 // gets freed during page_free.
198 shared_page->pp_ref++;
200 // Inserted into every process's address space at UGDATA
201 page_insert(e->env_pgdir, shared_page, (void*)UGDATA, PTE_U | PTE_W);
207 // Allocates and initializes a new environment.
208 // On success, the new environment is stored in *newenv_store.
210 // Returns 0 on success, < 0 on failure. Errors include:
211 // -E_NO_FREE_ENV if all NENVS environments are allocated
212 // -E_NO_MEM on memory exhaustion
215 env_alloc(env_t **newenv_store, envid_t parent_id)
221 if (!(e = LIST_FIRST(&env_free_list)))
222 return -E_NO_FREE_ENV;
224 memset((void*)e + sizeof(e->env_link), 0, sizeof(*e) - sizeof(e->env_link));
226 // Allocate and set up the page directory for this environment.
227 if ((r = env_setup_vm(e)) < 0)
230 // Generate an env_id for this environment.
231 generation = (e->env_id + (1 << ENVGENSHIFT)) & ~(NENV - 1);
232 if (generation <= 0) // Don't create a negative env_id.
233 generation = 1 << ENVGENSHIFT;
234 e->env_id = generation | (e - envs);
236 // Set the basic status variables.
237 e->env_parent_id = parent_id;
238 e->env_status = ENV_RUNNABLE;
242 // Clear out all the saved register state,
243 // to prevent the register values
244 // of a prior environment inhabiting this Env structure
245 // from "leaking" into our new environment.
246 memset(&e->env_tf, 0, sizeof(e->env_tf));
248 // Set up appropriate initial values for the segment registers.
249 // GD_UD is the user data segment selector in the GDT, and
250 // GD_UT is the user text segment selector (see inc/memlayout.h).
251 // The low 2 bits of each segment register contains the
252 // Requestor Privilege Level (RPL); 3 means user mode.
253 e->env_tf.tf_ds = GD_UD | 3;
254 e->env_tf.tf_es = GD_UD | 3;
255 e->env_tf.tf_ss = GD_UD | 3;
256 e->env_tf.tf_esp = USTACKTOP;
257 e->env_tf.tf_cs = GD_UT | 3;
258 // You will set e->env_tf.tf_eip later.
259 // set the env's EFLAGSs to have interrupts enabled
260 e->env_tf.tf_eflags |= 0x00000200; // bit 9 is the interrupts-enabled
262 // commit the allocation
263 LIST_REMOVE(e, env_link);
265 atomic_inc(&num_envs);
267 e->env_tscfreq = system_timing.tsc_freq;
268 // TODO: for now, the only info at procinfo is this env's struct
269 // note that we need to copy this over every time we make a change to env
270 // that we want userspace to see. also note that we don't even want to
271 // show them all of env, only specific things like PID, PPID, etc
272 memcpy(e->env_procinfo, e, sizeof(env_t));
274 env_t* curenv = curenvs[lapic_get_id()];
276 printk("[%08x] new env %08x\n", curenv ? curenv->env_id : 0, e->env_id);
281 // Allocate len bytes of physical memory for environment env,
282 // and map it at virtual address va in the environment's address space.
283 // Does not zero or otherwise initialize the mapped pages in any way.
284 // Pages should be writable by user and kernel.
285 // Panic if any allocation attempt fails.
288 segment_alloc(env_t *e, void *va, size_t len)
296 start = ROUNDDOWN(va, PGSIZE);
297 end = ROUNDUP(va + len, PGSIZE);
299 panic("Wrap-around in memory allocation addresses!");
300 if ((uintptr_t)end > UTOP)
301 panic("Attempting to map above UTOP!");
302 // page_insert/pgdir_walk alloc a page and read/write to it via its address
303 // starting from pgdir (e's), so we need to be using e's pgdir
304 assert(e->env_cr3 == rcr3());
305 num_pages = PPN(end - start);
306 for (i = 0; i < num_pages; i++, start += PGSIZE) {
307 // skip if a page is already mapped. yes, page_insert will page_remove
308 // whatever page was already there, but if we are seg allocing adjacent
309 // regions, we don't want to destroy that old mapping/page
310 // though later on we are told we can ignore this...
311 pte = pgdir_walk(e->env_pgdir, start, 0);
312 if (pte && *pte & PTE_P)
314 if ((r = page_alloc(&page)) < 0)
315 panic("segment_alloc: %e", r);
316 page_insert(e->env_pgdir, page, start, PTE_U | PTE_W);
321 // Set up the initial program binary, stack, and processor flags
322 // for a user process.
323 // This function is ONLY called during kernel initialization,
324 // before running the first user-mode environment.
326 // This function loads all loadable segments from the ELF binary image
327 // into the environment's user memory, starting at the appropriate
328 // virtual addresses indicated in the ELF program header.
329 // At the same time it clears to zero any portions of these segments
330 // that are marked in the program header as being mapped
331 // but not actually present in the ELF file - i.e., the program's bss section.
333 // All this is very similar to what our boot loader does, except the boot
334 // loader also needs to read the code from disk. Take a look at
335 // boot/main.c to get ideas.
337 // Finally, this function maps one page for the program's initial stack.
339 // load_icode panics if it encounters problems.
340 // - How might load_icode fail? What might be wrong with the given input?
343 load_icode(env_t *e, uint8_t *binary, size_t size)
346 // Load each program segment into virtual memory
347 // at the address specified in the ELF section header.
348 // You should only load segments with ph->p_type == ELF_PROG_LOAD.
349 // Each segment's virtual address can be found in ph->p_va
350 // and its size in memory can be found in ph->p_memsz.
351 // The ph->p_filesz bytes from the ELF binary, starting at
352 // 'binary + ph->p_offset', should be copied to virtual address
353 // ph->p_va. Any remaining memory bytes should be cleared to zero.
354 // (The ELF header should have ph->p_filesz <= ph->p_memsz.)
355 // Use functions from the previous lab to allocate and map pages.
357 // All page protection bits should be user read/write for now.
358 // ELF segments are not necessarily page-aligned, but you can
359 // assume for this function that no two segments will touch
360 // the same virtual page.
362 // You may find a function like segment_alloc useful.
364 // Loading the segments is much simpler if you can move data
365 // directly into the virtual addresses stored in the ELF binary.
366 // So which page directory should be in force during
370 // You must also do something with the program's entry point,
371 // to make sure that the environment starts executing there.
372 // What? (See env_run() and env_pop_tf() below.)
374 elf_t *elfhdr = (elf_t *)binary;
378 assert(elfhdr->e_magic == ELF_MAGIC);
379 // make sure we have proghdrs to load
380 assert(elfhdr->e_phnum);
382 // to actually access any pages alloc'd for this environment, we
383 // need to have the hardware use this environment's page tables.
384 // we can use e's tables as long as we want, since it has the same
385 // mappings for the kernel as does boot_pgdir
388 proghdr_t *phdr = (proghdr_t *)(binary + elfhdr->e_phoff);
389 for (i = 0; i < elfhdr->e_phnum; i++, phdr++) {
390 if (phdr->p_type != ELF_PROG_LOAD)
392 // seg alloc creates PTE_U|PTE_W pages. if you ever want to change
393 // this, there will be issues with overlapping sections
394 segment_alloc(e, (void*)phdr->p_va, phdr->p_memsz);
395 memcpy((void*)phdr->p_va, binary + phdr->p_offset, phdr->p_filesz);
396 memset((void*)phdr->p_va + phdr->p_filesz, 0, phdr->p_memsz - phdr->p_filesz);
399 e->env_tf.tf_eip = elfhdr->e_entry;
401 // Now map one page for the program's initial stack
402 // at virtual address USTACKTOP - PGSIZE.
404 segment_alloc(e, (void*)(USTACKTOP - PGSIZE), PGSIZE);
408 // Allocates a new env and loads the named elf binary into it.
410 env_t* env_create(uint8_t *binary, size_t size)
415 if ((r = env_alloc(&e, 0)) < 0)
416 panic("env_create: %e", r);
417 load_icode(e, binary, size);
422 // Frees env e and all memory it uses.
428 uint32_t pdeno, pteno;
431 // Note the environment's demise.
432 env_t* curenv = curenvs[lapic_get_id()];
433 cprintf("[%08x] free env %08x\n", curenv ? curenv->env_id : 0, e->env_id);
435 // Flush all mapped pages in the user portion of the address space
436 static_assert(UTOP % PTSIZE == 0);
437 for (pdeno = 0; pdeno < PDX(UTOP); pdeno++) {
439 // only look at mapped page tables
440 if (!(e->env_pgdir[pdeno] & PTE_P))
443 // find the pa and va of the page table
444 pa = PTE_ADDR(e->env_pgdir[pdeno]);
445 pt = (pte_t*) KADDR(pa);
447 // unmap all PTEs in this page table
448 for (pteno = 0; pteno <= PTX(~0); pteno++) {
449 if (pt[pteno] & PTE_P)
450 page_remove(e->env_pgdir, PGADDR(pdeno, pteno, 0));
453 // free the page table itself
454 e->env_pgdir[pdeno] = 0;
455 page_decref(pa2page(pa));
458 // Moved to page_decref
459 // need a known good pgdir before releasing the old one
462 // free the page directory
466 page_decref(pa2page(pa));
468 // return the environment to the free list
469 e->env_status = ENV_FREE;
470 LIST_INSERT_HEAD(&env_free_list, e, env_link);
474 * This allows the kernel to keep this process around, in case it is being used
475 * in some asynchronous processing.
476 * The refcnt should always be greater than 0 for processes that aren't dying.
477 * When refcnt is 0, the process is dying and should not allow any more increfs.
478 * TODO: Make sure this is never called from an interrupt handler (irq_save)
480 error_t env_incref(env_t* e)
488 spin_unlock(&e->lock);
493 * When the kernel is done with a process, it decrements its reference count.
494 * When the count hits 0, no one is using it and it should be freed.
495 * env_destroy calls this.
496 * TODO: Make sure this is never called from an interrupt handler (irq_save)
498 void env_decref(env_t* e)
500 // need a known good pgdir before releasing the old one
501 // sometimes env_free is called on a different core than decref
506 spin_unlock(&e->lock);
507 // if we hit 0, no one else will increment and we can check outside the lock
508 if (e->env_refcnt == 0)
514 // Frees environment e.
515 // If e was the current env, then runs a new environment (and does not return
519 env_destroy(env_t *e)
521 // TODO: race condition with env statuses, esp when running / destroying
522 e->env_status = ENV_DYING;
525 atomic_dec(&num_envs);
527 // for old envs that die on user cores. since env run never returns, cores
528 // never get back to their old hlt/relaxed/spin state, so we need to force
529 // them back to an idle function.
530 uint32_t id = lapic_get_id();
531 // There is no longer a curenv for this core. (TODO: Think about this.)
535 panic("should never see me");
537 // else we're core 0 and can do the usual
539 /* Instead of picking a new environment to run, or defaulting to the monitor
540 * like before, for now we'll hop into the manager() function, which
541 * dispatches jobs. Note that for now we start the manager from the top,
542 * and not from where we left off the last time we called manager. That
543 * would require us to save some context (and a stack to work on) here.
546 assert(0); // never get here
548 // ugly, but for now just linearly search through all possible
549 // environments for a runnable one.
550 for (int i = 0; i < NENV; i++) {
552 // TODO: race here, if another core is just about to start this env.
553 // Fix it by setting the status in something like env_dispatch when
554 // we have multi-contexted processes
555 if (e && e->env_status == ENV_RUNNABLE)
558 cprintf("Destroyed the only environment - nothing more to do!\n");
565 // Restores the register values in the Trapframe with the 'iret' instruction.
566 // This exits the kernel and starts executing some environment's code.
567 // This function does not return.
570 env_pop_tf(trapframe_t *tf)
572 __asm __volatile("movl %0,%%esp\n"
576 "\taddl $0x8,%%esp\n" /* skip tf_trapno and tf_errcode */
578 : : "g" (tf) : "memory");
579 panic("iret failed"); /* mostly to placate the compiler */
583 // Context switch from curenv to env e.
584 // Note: if this is the first call to env_run, curenv is NULL.
585 // (This function does not return.)
590 // Step 1: If this is a context switch (a new environment is running),
591 // then set 'curenv' to the new environment,
592 // update its 'env_runs' counter, and
593 // and use lcr3() to switch to its address space.
594 // Step 2: Use env_pop_tf() to restore the environment's
595 // registers and drop into user mode in the
598 // Hint: This function loads the new environment's state from
599 // e->env_tf. Go back through the code you wrote above
600 // and make sure you have set the relevant parts of
601 // e->env_tf to sensible values.
603 // TODO: race here with env destroy on the status and refcnt
604 // Could up the refcnt and down it when a process is not running
605 e->env_status = ENV_RUNNING;
606 if (e != curenvs[lapic_get_id()]) {
607 curenvs[lapic_get_id()] = e;
611 env_pop_tf(&e->env_tf);