1 /* See COPYRIGHT for copyright information. */
10 #include <arch/apic.h>
22 #include <ros/syscall.h>
23 #include <ros/error.h>
25 env_t *envs = NULL; // All environments
26 uint32_t num_envs = 0; // Number of envs
27 // TODO: make this a struct of info including the pointer and cacheline-align it
28 // This lets the kernel know what process is running on the core it traps into.
29 // A lot of the Env business, including this and its usage, will change when we
30 // redesign the env as a multi-process.
31 env_t* curenvs[MAX_NUM_CPUS] = {[0 ... (MAX_NUM_CPUS-1)] NULL};
32 static env_list_t env_free_list; // Free list
34 #define ENVGENSHIFT 12 // >= LOGNENV
37 // Converts an envid to an env pointer.
40 // 0 on success, -E_BAD_ENV on error.
41 // On success, sets *env_store to the environment.
42 // On error, sets *env_store to NULL.
45 envid2env(envid_t envid, env_t **env_store, bool checkperm)
48 env_t* curenv = curenvs[lapic_get_id()];
50 // If envid is zero, return the current environment.
56 // Look up the Env structure via the index part of the envid,
57 // then check the env_id field in that env_t
58 // to ensure that the envid is not stale
59 // (i.e., does not refer to a _previous_ environment
60 // that used the same slot in the envs[] array).
61 e = &envs[ENVX(envid)];
62 if (e->env_status == ENV_FREE || e->env_id != envid) {
67 // Check that the calling environment has legitimate permission
68 // to manipulate the specified environment.
69 // If checkperm is set, the specified environment
70 // must be either the current environment
71 // or an immediate child of the current environment.
72 if (checkperm && e != curenv && e->env_parent_id != curenv->env_id) {
82 // Mark all environments in 'envs' as free, set their env_ids to 0,
83 // and insert them into the env_free_list.
84 // Insert in reverse order, so that the first call to env_alloc()
91 LIST_INIT(&env_free_list);
92 for (i = NENV-1; i >= 0; i--) {
93 // these should already be set from when i memset'd the array to 0
94 envs[i].env_status = ENV_FREE;
96 LIST_INSERT_HEAD(&env_free_list, &envs[i], env_link);
101 // Initialize the kernel virtual memory layout for environment e.
102 // Allocate a page directory, set e->env_pgdir and e->env_cr3 accordingly,
103 // and initialize the kernel portion of the new environment's address space.
104 // Do NOT (yet) map anything into the user portion
105 // of the environment's virtual address space.
107 // Returns 0 on success, < 0 on error. Errors include:
108 // -E_NO_MEM if page directory or table could not be allocated.
111 env_setup_vm(env_t *e)
112 WRITES(e->env_pgdir, e->env_cr3, e->env_procinfo, e->env_procdata,
116 page_t *pgdir = NULL, *pginfo = NULL, *pgdata = NULL;
118 // Allocate pages for the page directory, shared info, and shared data pages
119 r = page_alloc(&pgdir);
120 r = page_alloc(&pginfo);
121 r = page_alloc(&pgdata);
128 // Now, set e->env_pgdir and e->env_cr3,
129 // and initialize the page directory.
132 // - The VA space of all envs is identical above UTOP
133 // (except at VPT and UVPT, which we've set below).
134 // (and not for UINFO either)
135 // See inc/memlayout.h for permissions and layout.
136 // Can you use boot_pgdir as a template? Hint: Yes.
137 // (Make sure you got the permissions right in Lab 2.)
138 // - The initial VA below UTOP is empty.
139 // - You do not need to make any more calls to page_alloc.
140 // - Note: pp_ref is not maintained for most physical pages
141 // mapped above UTOP -- but you do need to increment
142 // env_pgdir's pp_ref!
144 // need to up pgdir's reference, since it will never be done elsewhere
146 e->env_pgdir = page2kva(pgdir);
147 e->env_cr3 = page2pa(pgdir);
148 e->env_procinfo = page2kva(pginfo);
149 e->env_procdata = page2kva(pgdata);
151 memset(e->env_pgdir, 0, PGSIZE);
152 memset(e->env_procinfo, 0, PGSIZE);
153 memset(e->env_procdata, 0, PGSIZE);
155 // Initialize the generic syscall ring buffer
156 SHARED_RING_INIT((syscall_sring_t *SAFE)e->env_procdata);
157 // Initialize the backend of the ring buffer
158 BACK_RING_INIT(&e->env_sysbackring, (syscall_sring_t *SAFE)e->env_procdata,
161 // should be able to do this so long as boot_pgdir never has
162 // anything put below UTOP
163 memcpy(e->env_pgdir, boot_pgdir, PGSIZE);
165 // something like this. TODO, if you want
166 //memcpy(&e->env_pgdir[PDX(UTOP)], &boot_pgdir[PDX(UTOP)], PGSIZE - PDX(UTOP));
168 // assert(memcmp(e->env_pgdir, boot_pgdir, PGSIZE) == 0);
170 // VPT and UVPT map the env's own page table, with
171 // different permissions.
172 e->env_pgdir[PDX(VPT)] = e->env_cr3 | PTE_P | PTE_W;
173 e->env_pgdir[PDX(UVPT)] = e->env_cr3 | PTE_P | PTE_U;
175 // Insert the per-process info and data pages into this process's pgdir
176 // I don't want to do these two pages later (like with the stack), since
177 // the kernel wants to keep pointers to it easily.
178 // Could place all of this with a function that maps a shared memory page
179 // that can work between any two address spaces or something.
180 r = page_insert(e->env_pgdir, pginfo, (void*SNT)UINFO, PTE_U);
181 r = page_insert(e->env_pgdir, pgdata, (void*SNT)UDATA, PTE_U | PTE_W);
183 // note that we can't currently deallocate the pages created by
184 // pgdir_walk (inside insert). should be able to gather them up when
185 // we destroy environments and their page tables.
192 /* Shared page for all processes. Can't be trusted, but still very useful
193 * at this stage for us. Consider removing when we have real processes.
194 * (TODO). Note the page is alloced only the first time through
196 static page_t* shared_page = 0;
198 page_alloc(&shared_page);
199 // Up it, so it never goes away. One per user, plus one from page_alloc
200 // This is necessary, since it's in the per-process range of memory that
201 // gets freed during page_free.
202 shared_page->pp_ref++;
204 // Inserted into every process's address space at UGDATA
205 page_insert(e->env_pgdir, shared_page, (void*SNT)UGDATA, PTE_U | PTE_W);
211 // Allocates and initializes a new environment.
212 // On success, the new environment is stored in *newenv_store.
214 // Returns 0 on success, < 0 on failure. Errors include:
215 // -E_NO_FREE_ENV if all NENVS environments are allocated
216 // -E_NO_MEM on memory exhaustion
219 env_alloc(env_t **newenv_store, envid_t parent_id)
225 if (!(e = LIST_FIRST(&env_free_list)))
226 return -E_NO_FREE_ENV;
228 //memset((void*)e + sizeof(e->env_link), 0, sizeof(*e) - sizeof(e->env_link));
232 // Allocate and set up the page directory for this environment.
233 if ((r = env_setup_vm(e)) < 0)
236 // Generate an env_id for this environment.
237 generation = (e->env_id + (1 << ENVGENSHIFT)) & ~(NENV - 1);
238 if (generation <= 0) // Don't create a negative env_id.
239 generation = 1 << ENVGENSHIFT;
240 e->env_id = generation | (e - envs);
242 // Set the basic status variables.
244 e->env_parent_id = parent_id;
245 e->env_status = ENV_RUNNABLE;
249 // Clear out all the saved register state,
250 // to prevent the register values
251 // of a prior environment inhabiting this Env structure
252 // from "leaking" into our new environment.
253 memset(&e->env_tf, 0, sizeof(e->env_tf));
255 // Set up appropriate initial values for the segment registers.
256 // GD_UD is the user data segment selector in the GDT, and
257 // GD_UT is the user text segment selector (see inc/memlayout.h).
258 // The low 2 bits of each segment register contains the
259 // Requestor Privilege Level (RPL); 3 means user mode.
260 e->env_tf.tf_ds = GD_UD | 3;
261 e->env_tf.tf_es = GD_UD | 3;
262 e->env_tf.tf_ss = GD_UD | 3;
263 e->env_tf.tf_esp = USTACKTOP;
264 e->env_tf.tf_cs = GD_UT | 3;
265 // You will set e->env_tf.tf_eip later.
266 // set the env's EFLAGSs to have interrupts enabled
267 e->env_tf.tf_eflags |= 0x00000200; // bit 9 is the interrupts-enabled
269 // commit the allocation
270 LIST_REMOVE(e, env_link);
272 atomic_inc(&num_envs);
274 e->env_tscfreq = system_timing.tsc_freq;
275 // TODO: for now, the only info at procinfo is this env's struct
276 // note that we need to copy this over every time we make a change to env
277 // that we want userspace to see. also note that we don't even want to
278 // show them all of env, only specific things like PID, PPID, etc
279 memcpy(e->env_procinfo, e, sizeof(env_t));
281 env_t* curenv = curenvs[lapic_get_id()];
283 printk("[%08x] new env %08x\n", curenv ? curenv->env_id : 0, e->env_id);
289 // Allocate len bytes of physical memory for environment env,
290 // and map it at virtual address va in the environment's address space.
291 // Does not zero or otherwise initialize the mapped pages in any way.
292 // Pages should be writable by user and kernel.
293 // Panic if any allocation attempt fails.
296 segment_alloc(env_t *e, void *SNT va, size_t len)
298 void *SNT start, *SNT end;
304 start = ROUNDDOWN(va, PGSIZE);
305 end = ROUNDUP(va + len, PGSIZE);
307 panic("Wrap-around in memory allocation addresses!");
308 if ((uintptr_t)end > UTOP)
309 panic("Attempting to map above UTOP!");
310 // page_insert/pgdir_walk alloc a page and read/write to it via its address
311 // starting from pgdir (e's), so we need to be using e's pgdir
312 assert(e->env_cr3 == rcr3());
313 num_pages = PPN(end - start);
314 for (i = 0; i < num_pages; i++, start += PGSIZE) {
315 // skip if a page is already mapped. yes, page_insert will page_remove
316 // whatever page was already there, but if we are seg allocing adjacent
317 // regions, we don't want to destroy that old mapping/page
318 // though later on we are told we can ignore this...
319 pte = pgdir_walk(e->env_pgdir, start, 0);
320 if (pte && *pte & PTE_P)
322 if ((r = page_alloc(&page)) < 0)
323 panic("segment_alloc: %e", r);
324 page_insert(e->env_pgdir, page, start, PTE_U | PTE_W);
329 // Set up the initial program binary, stack, and processor flags
330 // for a user process.
331 // This function is ONLY called during kernel initialization,
332 // before running the first user-mode environment.
334 // This function loads all loadable segments from the ELF binary image
335 // into the environment's user memory, starting at the appropriate
336 // virtual addresses indicated in the ELF program header.
337 // At the same time it clears to zero any portions of these segments
338 // that are marked in the program header as being mapped
339 // but not actually present in the ELF file - i.e., the program's bss section.
341 // All this is very similar to what our boot loader does, except the boot
342 // loader also needs to read the code from disk. Take a look at
343 // boot/main.c to get ideas.
345 // Finally, this function maps one page for the program's initial stack.
347 // load_icode panics if it encounters problems.
348 // - How might load_icode fail? What might be wrong with the given input?
351 load_icode(env_t *e, uint8_t *COUNT(size) binary, size_t size)
354 // Load each program segment into virtual memory
355 // at the address specified in the ELF section header.
356 // You should only load segments with ph->p_type == ELF_PROG_LOAD.
357 // Each segment's virtual address can be found in ph->p_va
358 // and its size in memory can be found in ph->p_memsz.
359 // The ph->p_filesz bytes from the ELF binary, starting at
360 // 'binary + ph->p_offset', should be copied to virtual address
361 // ph->p_va. Any remaining memory bytes should be cleared to zero.
362 // (The ELF header should have ph->p_filesz <= ph->p_memsz.)
363 // Use functions from the previous lab to allocate and map pages.
365 // All page protection bits should be user read/write for now.
366 // ELF segments are not necessarily page-aligned, but you can
367 // assume for this function that no two segments will touch
368 // the same virtual page.
370 // You may find a function like segment_alloc useful.
372 // Loading the segments is much simpler if you can move data
373 // directly into the virtual addresses stored in the ELF binary.
374 // So which page directory should be in force during
378 // You must also do something with the program's entry point,
379 // to make sure that the environment starts executing there.
380 // What? (See env_run() and env_pop_tf() below.)
382 elf_t *elfhdr = (elf_t *)binary;
386 assert(elfhdr->e_magic == ELF_MAGIC);
387 // make sure we have proghdrs to load
388 assert(elfhdr->e_phnum);
390 // to actually access any pages alloc'd for this environment, we
391 // need to have the hardware use this environment's page tables.
392 // we can use e's tables as long as we want, since it has the same
393 // mappings for the kernel as does boot_pgdir
396 // TODO: how do we do a runtime COUNT?
398 proghdr_t* phdr = (proghdr_t*)(binary + elfhdr->e_phoff);
399 for (i = 0; i < elfhdr->e_phnum; i++, phdr++) {
400 // zra: TRUSTEDBLOCK until validation is done.
401 if (phdr->p_type != ELF_PROG_LOAD)
403 // TODO: validate elf header fields!
404 // seg alloc creates PTE_U|PTE_W pages. if you ever want to change
405 // this, there will be issues with overlapping sections
406 segment_alloc(e, (void*SNT)phdr->p_va, phdr->p_memsz);
407 memcpy((void*)phdr->p_va, binary + phdr->p_offset, phdr->p_filesz);
408 memset((void*)phdr->p_va + phdr->p_filesz, 0, phdr->p_memsz - phdr->p_filesz);
411 e->env_tf.tf_eip = elfhdr->e_entry;
413 // Now map one page for the program's initial stack
414 // at virtual address USTACKTOP - PGSIZE.
416 segment_alloc(e, (void*SNT)(USTACKTOP - PGSIZE), PGSIZE);
420 // Allocates a new env and loads the named elf binary into it.
422 env_t* env_create(uint8_t *binary, size_t size)
427 if ((r = env_alloc(&e, 0)) < 0)
428 panic("env_create: %e", r);
429 load_icode(e, binary, size);
434 // Frees env e and all memory it uses.
440 uint32_t pdeno, pteno;
443 // Note the environment's demise.
444 env_t* curenv = curenvs[lapic_get_id()];
445 cprintf("[%08x] free env %08x\n", curenv ? curenv->env_id : 0, e->env_id);
447 // Flush all mapped pages in the user portion of the address space
448 static_assert(UTOP % PTSIZE == 0);
449 for (pdeno = 0; pdeno < PDX(UTOP); pdeno++) {
451 // only look at mapped page tables
452 if (!(e->env_pgdir[pdeno] & PTE_P))
455 // find the pa and va of the page table
456 pa = PTE_ADDR(e->env_pgdir[pdeno]);
457 pt = (pte_t*COUNT(NPTENTRIES)) KADDR(pa);
459 // unmap all PTEs in this page table
460 for (pteno = 0; pteno <= PTX(~0); pteno++) {
461 if (pt[pteno] & PTE_P)
462 page_remove(e->env_pgdir, PGADDR(pdeno, pteno, 0));
465 // free the page table itself
466 e->env_pgdir[pdeno] = 0;
467 page_decref(pa2page(pa));
470 // Moved to page_decref
471 // need a known good pgdir before releasing the old one
474 // free the page directory
478 page_decref(pa2page(pa));
480 // return the environment to the free list
481 e->env_status = ENV_FREE;
482 LIST_INSERT_HEAD(&env_free_list, e, env_link);
486 * This allows the kernel to keep this process around, in case it is being used
487 * in some asynchronous processing.
488 * The refcnt should always be greater than 0 for processes that aren't dying.
489 * When refcnt is 0, the process is dying and should not allow any more increfs.
490 * TODO: Make sure this is never called from an interrupt handler (irq_save)
492 error_t env_incref(env_t* e)
500 spin_unlock(&e->lock);
505 * When the kernel is done with a process, it decrements its reference count.
506 * When the count hits 0, no one is using it and it should be freed.
507 * env_destroy calls this.
508 * TODO: Make sure this is never called from an interrupt handler (irq_save)
510 void env_decref(env_t* e)
512 // need a known good pgdir before releasing the old one
513 // sometimes env_free is called on a different core than decref
518 spin_unlock(&e->lock);
519 // if we hit 0, no one else will increment and we can check outside the lock
520 if (e->env_refcnt == 0)
526 // Frees environment e.
527 // If e was the current env, then runs a new environment (and does not return
531 env_destroy(env_t *e)
533 // TODO: race condition with env statuses, esp when running / destroying
534 e->env_status = ENV_DYING;
537 atomic_dec(&num_envs);
539 // for old envs that die on user cores. since env run never returns, cores
540 // never get back to their old hlt/relaxed/spin state, so we need to force
541 // them back to an idle function.
542 uint32_t id = lapic_get_id();
543 // There is no longer a curenv for this core. (TODO: Think about this.)
547 panic("should never see me");
549 // else we're core 0 and can do the usual
551 /* Instead of picking a new environment to run, or defaulting to the monitor
552 * like before, for now we'll hop into the manager() function, which
553 * dispatches jobs. Note that for now we start the manager from the top,
554 * and not from where we left off the last time we called manager. That
555 * would require us to save some context (and a stack to work on) here.
558 assert(0); // never get here
561 /* ugly, but for now just linearly search through all possible
562 * environments for a runnable one.
563 * the current *policy* is to round-robin the search
568 static int last_picked = 0;
570 for (int i = 0, j = last_picked + 1; i < NENV; i++, j = (j + 1) % NENV) {
572 // TODO: race here, if another core is just about to start this env.
573 // Fix it by setting the status in something like env_dispatch when
574 // we have multi-contexted processes
575 if (e && e->env_status == ENV_RUNNABLE) {
581 cprintf("Destroyed the only environment - nothing more to do!\n");
587 // Restores the register values in the Trapframe with the 'iret' instruction.
588 // This exits the kernel and starts executing some environment's code.
589 // This function does not return.
591 void env_pop_tf(trapframe_t *tf)
598 "\taddl $0x8,%%esp\n" /* skip tf_trapno and tf_errcode */
600 : : "g" (tf) : "memory");
601 panic("iret failed"); /* mostly to placate the compiler */
604 void env_pop_tf_sysexit(trapframe_t *tf)
611 "\tmovl %%ebp, %%ecx\n"
612 "\tmovl %%esi, %%edx\n"
614 : : "g" (tf) : "memory");
615 panic("sysexit failed"); /* mostly to placate the compiler */
619 // Context switch from curenv to env e.
620 // Note: if this is the first call to env_run, curenv is NULL.
621 // (This function does not return.)
626 // Step 1: If this is a context switch (a new environment is running),
627 // then set 'curenv' to the new environment,
628 // update its 'env_runs' counter, and
629 // and use lcr3() to switch to its address space.
630 // Step 2: Use env_pop_tf() to restore the environment's
631 // registers and drop into user mode in the
634 // Hint: This function loads the new environment's state from
635 // e->env_tf. Go back through the code you wrote above
636 // and make sure you have set the relevant parts of
637 // e->env_tf to sensible values.
639 // TODO: race here with env destroy on the status and refcnt
640 // Could up the refcnt and down it when a process is not running
641 e->env_status = ENV_RUNNING;
642 if (e != curenvs[lapic_get_id()]) {
643 curenvs[lapic_get_id()] = e;
648 // The first time through we need to set up
649 // ebp and esi because there is no corresponding
650 // sysenter call and we have not set them up yet
651 // for use by the env_pop_tf_sysexit() call that
653 if(e->env_runs == 1) {
654 e->env_tf.tf_regs.reg_ebp = e->env_tf.tf_esp;
655 e->env_tf.tf_regs.reg_esi = e->env_tf.tf_eip;
662 env_pop_tf_sysexit(&e->env_tf);
664 env_pop_tf(&e->env_tf);
668 /* This is the top-half of an interrupt handler, where the bottom half is
669 * env_run (which never returns). Just add it to the delayed work queue,
670 * which isn't really a queue yet.
672 void run_env_handler(trapframe_t *tf, void* data)
675 per_cpu_info_t *cpuinfo = &per_cpu_info[lapic_get_id()];
676 spin_lock_irqsave(&cpuinfo->lock);
677 { TRUSTEDBLOCK // TODO: how do we make this func_t cast work?
678 cpuinfo->delayed_work.func = (func_t)env_run;
679 cpuinfo->delayed_work.data = data;
681 spin_unlock_irqsave(&cpuinfo->lock);