1 /*-
2  * Copyright (c) 1982, 1986 The Regents of the University of California.
3  * Copyright (c) 1989, 1990 William Jolitz
4  * Copyright (c) 1994 John Dyson
5  * Copyright (c) 2008 The DragonFly Project.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * the Systems Programming Group of the University of Utah Computer
10  * Science Department, and William Jolitz.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *	This product includes software developed by the University of
23  *	California, Berkeley and its contributors.
24  * 4. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  *
40  *	from: @(#)vm_machdep.c	7.3 (Berkeley) 5/13/91
41  *	Utah $Hdr: vm_machdep.c 1.16.1.1 89/06/23$
42  * $FreeBSD: src/sys/i386/i386/vm_machdep.c,v 1.132.2.9 2003/01/25 19:02:23 dillon Exp $
43  */
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/malloc.h>
48 #include <sys/proc.h>
49 #include <sys/buf.h>
50 #include <sys/interrupt.h>
51 #include <sys/vnode.h>
52 #include <sys/vmmeter.h>
53 #include <sys/kernel.h>
54 #include <sys/sysctl.h>
55 #include <sys/unistd.h>
56 #include <sys/lwp.h>
57 
58 #include <machine/clock.h>
59 #include <machine/cpu.h>
60 #include <machine/md_var.h>
61 #include <machine/smp.h>
62 #include <machine/pcb.h>
63 #include <machine/pcb_ext.h>
64 #include <machine/segments.h>
65 #include <machine/globaldata.h>	/* npxthread */
66 #include <machine/vmm.h>
67 
68 #include <vm/vm.h>
69 #include <vm/vm_param.h>
70 #include <sys/lock.h>
71 #include <vm/vm_kern.h>
72 #include <vm/vm_page.h>
73 #include <vm/vm_map.h>
74 #include <vm/vm_extern.h>
75 
76 #include <sys/thread2.h>
77 #include <sys/mplock2.h>
78 
79 #include <bus/isa/isa.h>
80 
81 static void	cpu_reset_real (void);
82 /*
83  * Finish a fork operation, with lwp lp2 nearly set up.
84  * Copy and update the pcb, set up the stack so that the child
85  * ready to run and return to user mode.
86  */
87 void
88 cpu_fork(struct lwp *lp1, struct lwp *lp2, int flags)
89 {
90 	struct pcb *pcb2;
91 
92 	if ((flags & RFPROC) == 0) {
93 		if ((flags & RFMEM) == 0) {
94 			/*
95 			 * Unshare user LDT.  > 1 test is MPSAFE.  While
96 			 * it can potentially race a 2->1 transition, the
97 			 * worst that happens is that we do an unnecessary
98 			 * ldt replacement.
99 			 */
100 			struct pcb *pcb1 = lp1->lwp_thread->td_pcb;
101 			struct pcb_ldt *pcb_ldt = pcb1->pcb_ldt;
102 
103 			if (pcb_ldt && pcb_ldt->ldt_refcnt > 1) {
104 				pcb_ldt = user_ldt_alloc(pcb1,pcb_ldt->ldt_len);
105 				user_ldt_free(pcb1);
106 				pcb1->pcb_ldt = pcb_ldt;
107 				set_user_ldt(pcb1);
108 			}
109 		}
110 		return;
111 	}
112 
113 	/* Ensure that lp1's pcb is up to date. */
114 	if (mdcpu->gd_npxthread == lp1->lwp_thread)
115 		npxsave(lp1->lwp_thread->td_savefpu);
116 
117 	/*
118 	 * Copy lp1's PCB.  This really only applies to the
119 	 * debug registers and FP state, but its faster to just copy the
120 	 * whole thing.  Because we only save the PCB at switchout time,
121 	 * the register state may not be current.
122 	 */
123 	pcb2 = lp2->lwp_thread->td_pcb;
124 	*pcb2 = *lp1->lwp_thread->td_pcb;
125 
126 	/*
127 	 * Create a new fresh stack for the new process.
128 	 * Copy the trap frame for the return to user mode as if from a
129 	 * syscall.  This copies the user mode register values.
130 	 *
131 	 * pcb_rsp must allocate an additional call-return pointer below
132 	 * the trap frame which will be restored by cpu_heavy_restore from
133 	 * PCB_RIP, and the thread's td_sp pointer must allocate an
134 	 * additonal two quadwords below the pcb_rsp call-return pointer to
135 	 * hold the LWKT restore function pointer and rflags.
136 	 *
137 	 * The LWKT restore function pointer must be set to cpu_heavy_restore,
138 	 * which is our standard heavy-weight process switch-in function.
139 	 * YYY eventually we should shortcut fork_return and fork_trampoline
140 	 * to use the LWKT restore function directly so we can get rid of
141 	 * all the extra crap we are setting up.
142 	 */
143 	lp2->lwp_md.md_regs = (struct trapframe *)pcb2 - 1;
144 	bcopy(lp1->lwp_md.md_regs, lp2->lwp_md.md_regs, sizeof(*lp2->lwp_md.md_regs));
145 
146 	/*
147 	 * Set registers for trampoline to user mode.  Leave space for the
148 	 * return address on stack.  These are the kernel mode register values.
149 	 */
150 	pcb2->pcb_cr3 = vtophys(vmspace_pmap(lp2->lwp_proc->p_vmspace)->pm_pml4);
151 	pcb2->pcb_rbx = (unsigned long)fork_return;	/* fork_trampoline argument */
152 	pcb2->pcb_rbp = 0;
153 	pcb2->pcb_rsp = (unsigned long)lp2->lwp_md.md_regs - sizeof(void *);
154 	pcb2->pcb_r12 = (unsigned long)lp2;		/* fork_trampoline argument */
155 	pcb2->pcb_r13 = 0;
156 	pcb2->pcb_r14 = 0;
157 	pcb2->pcb_r15 = 0;
158 	pcb2->pcb_rip = (unsigned long)fork_trampoline;
159 	lp2->lwp_thread->td_sp = (char *)(pcb2->pcb_rsp - sizeof(void *));
160 	*(u_int64_t *)lp2->lwp_thread->td_sp = PSL_USER;
161 	lp2->lwp_thread->td_sp -= sizeof(void *);
162 	*(void **)lp2->lwp_thread->td_sp = (void *)cpu_heavy_restore;
163 
164 	/*
165 	 * pcb2->pcb_ldt:	duplicated below, if necessary.
166 	 * pcb2->pcb_savefpu:	cloned above.
167 	 * pcb2->pcb_flags:	cloned above (always 0 here?).
168 	 * pcb2->pcb_onfault:	cloned above (always NULL here).
169 	 * pcb2->pcb_onfault_sp:cloned above (dont care)
170 	 */
171 
172 	/*
173 	 * XXX don't copy the i/o pages.  this should probably be fixed.
174 	 */
175 	pcb2->pcb_ext = NULL;
176 
177         /* Copy the LDT, if necessary. */
178         if (pcb2->pcb_ldt != NULL) {
179 		if (flags & RFMEM) {
180 			atomic_add_int(&pcb2->pcb_ldt->ldt_refcnt, 1);
181 		} else {
182 			pcb2->pcb_ldt = user_ldt_alloc(pcb2,
183 						       pcb2->pcb_ldt->ldt_len);
184 		}
185         }
186 	bcopy(&lp1->lwp_thread->td_tls, &lp2->lwp_thread->td_tls,
187 	      sizeof(lp2->lwp_thread->td_tls));
188 	/*
189 	 * Now, cpu_switch() can schedule the new lwp.
190 	 * pcb_rsp is loaded pointing to the cpu_switch() stack frame
191 	 * containing the return address when exiting cpu_switch.
192 	 * This will normally be to fork_trampoline(), which will have
193 	 * %rbx loaded with the new lwp's pointer.  fork_trampoline()
194 	 * will set up a stack to call fork_return(lp, frame); to complete
195 	 * the return to user-mode.
196 	 */
197 }
198 
199 /*
200  * Prepare new lwp to return to the address specified in params.
201  */
202 int
203 cpu_prepare_lwp(struct lwp *lp, struct lwp_params *params)
204 {
205 	struct trapframe *regs = lp->lwp_md.md_regs;
206 	void *bad_return = NULL;
207 	int error;
208 
209 	regs->tf_rip = (long)params->lwp_func;
210 	regs->tf_rsp = (long)params->lwp_stack;
211 	/* Set up argument for function call */
212 	regs->tf_rdi = (long)params->lwp_arg;
213 
214 	/*
215 	 * Set up fake return address.  As the lwp function may never return,
216 	 * we simply copy out a NULL pointer and force the lwp to receive
217 	 * a SIGSEGV if it returns anyways.
218 	 */
219 	regs->tf_rsp -= sizeof(void *);
220 	error = copyout(&bad_return, (void *)regs->tf_rsp, sizeof(bad_return));
221 	if (error)
222 		return (error);
223 
224 	if (lp->lwp_proc->p_vmm) {
225 		lp->lwp_thread->td_pcb->pcb_cr3 = KPML4phys;
226 		cpu_set_fork_handler(lp,
227 		    (void (*)(void *, struct trapframe *))vmm_lwp_return, lp);
228 	} else {
229 		cpu_set_fork_handler(lp,
230 		    (void (*)(void *, struct trapframe *))generic_lwp_return, lp);
231 	}
232 	return (0);
233 }
234 
235 /*
236  * Intercept the return address from a freshly forked process that has NOT
237  * been scheduled yet.
238  *
239  * This is needed to make kernel threads stay in kernel mode.
240  */
241 void
242 cpu_set_fork_handler(struct lwp *lp, void (*func)(void *, struct trapframe *),
243 		     void *arg)
244 {
245 	/*
246 	 * Note that the trap frame follows the args, so the function
247 	 * is really called like this:  func(arg, frame);
248 	 */
249 	lp->lwp_thread->td_pcb->pcb_rbx = (long)func;	/* function */
250 	lp->lwp_thread->td_pcb->pcb_r12 = (long)arg;	/* first arg */
251 }
252 
253 void
254 cpu_set_thread_handler(thread_t td, void (*rfunc)(void), void *func, void *arg)
255 {
256 	td->td_pcb->pcb_rbx = (long)func;
257 	td->td_pcb->pcb_r12 = (long)arg;
258 	td->td_switch = cpu_lwkt_switch;
259 	td->td_sp -= sizeof(void *);
260 	*(void **)td->td_sp = rfunc;	/* exit function on return */
261 	td->td_sp -= sizeof(void *);
262 	*(void **)td->td_sp = cpu_kthread_restore;
263 }
264 
265 void
266 cpu_lwp_exit(void)
267 {
268 	struct thread *td = curthread;
269 	struct pcb *pcb;
270 
271 	pcb = td->td_pcb;
272 
273 	/* Some i386 functionality was dropped */
274 	KKASSERT(pcb->pcb_ext == NULL);
275 
276 	/*
277 	 * disable all hardware breakpoints
278 	 */
279         if (pcb->pcb_flags & PCB_DBREGS) {
280                 reset_dbregs();
281                 pcb->pcb_flags &= ~PCB_DBREGS;
282         }
283 	td->td_gd->gd_cnt.v_swtch++;
284 
285 	crit_enter_quick(td);
286 	if (td->td_flags & TDF_TSLEEPQ)
287 		tsleep_remove(td);
288 	lwkt_deschedule_self(td);
289 	lwkt_remove_tdallq(td);
290 	cpu_thread_exit();
291 }
292 
293 /*
294  * Terminate the current thread.  The caller must have already acquired
295  * the thread's rwlock and placed it on a reap list or otherwise notified
296  * a reaper of its existance.  We set a special assembly switch function which
297  * releases td_rwlock after it has cleaned up the MMU state and switched
298  * out the stack.
299  *
300  * Must be caller from a critical section and with the thread descheduled.
301  */
302 void
303 cpu_thread_exit(void)
304 {
305 	npxexit();
306 	curthread->td_switch = cpu_exit_switch;
307 	curthread->td_flags |= TDF_EXITING;
308 	lwkt_switch();
309 	panic("cpu_thread_exit: lwkt_switch() unexpectedly returned");
310 }
311 
312 void
313 cpu_reset(void)
314 {
315 	cpu_reset_real();
316 }
317 
318 static void
319 cpu_reset_real(void)
320 {
321 	/*
322 	 * Attempt to do a CPU reset via the keyboard controller,
323 	 * do not turn off the GateA20, as any machine that fails
324 	 * to do the reset here would then end up in no man's land.
325 	 */
326 
327 #if !defined(BROKEN_KEYBOARD_RESET)
328 	outb(IO_KBD + 4, 0xFE);
329 	DELAY(500000);	/* wait 0.5 sec to see if that did it */
330 	kprintf("Keyboard reset did not work, attempting CPU shutdown\n");
331 	DELAY(1000000);	/* wait 1 sec for kprintf to complete */
332 #endif
333 #if 0 /* JG */
334 	/* force a shutdown by unmapping entire address space ! */
335 	bzero((caddr_t) PTD, PAGE_SIZE);
336 #endif
337 
338 	/* "good night, sweet prince .... <THUNK!>" */
339 	cpu_invltlb();
340 	/* NOTREACHED */
341 	while(1);
342 }
343 
344 /*
345  * Convert kernel VA to physical address
346  */
347 vm_paddr_t
348 kvtop(void *addr)
349 {
350 	vm_paddr_t pa;
351 
352 	pa = pmap_kextract((vm_offset_t)addr);
353 	if (pa == 0)
354 		panic("kvtop: zero page frame");
355 	return (pa);
356 }
357 
358 static void
359 swi_vm(void *arg, void *frame)
360 {
361 	if (busdma_swi_pending != 0)
362 		busdma_swi();
363 }
364 
365 static void
366 swi_vm_setup(void *arg)
367 {
368 	register_swi_mp(SWI_VM, swi_vm, NULL, "swi_vm", NULL, 0);
369 }
370 
371 SYSINIT(vm_setup, SI_BOOT2_MACHDEP, SI_ORDER_ANY, swi_vm_setup, NULL);
372 
373 /*
374  * platform-specific vmspace initialization (nothing for x86_64)
375  */
376 void
377 cpu_vmspace_alloc(struct vmspace *vm __unused)
378 {
379 }
380 
381 void
382 cpu_vmspace_free(struct vmspace *vm __unused)
383 {
384 }
385 
386 int
387 kvm_access_check(vm_offset_t saddr, vm_offset_t eaddr, int prot)
388 {
389 	vm_offset_t addr;
390 
391 	if (saddr < KvaStart)
392 		return EFAULT;
393 	if (eaddr >= KvaEnd)
394 		return EFAULT;
395 	for (addr = saddr; addr < eaddr; addr += PAGE_SIZE)  {
396 		if (pmap_kextract(addr) == 0)
397 			return EFAULT;
398 	}
399 	if (!kernacc((caddr_t)saddr, eaddr - saddr, prot))
400 		return EFAULT;
401 	return 0;
402 }
403 
404 #if 0
405 
406 void _test_frame_enter(struct trapframe *frame);
407 void _test_frame_exit(struct trapframe *frame);
408 
409 void
410 _test_frame_enter(struct trapframe *frame)
411 {
412 	thread_t td = curthread;
413 
414 	if (ISPL(frame->tf_cs) == SEL_UPL) {
415 		KKASSERT(td->td_lwp);
416                 KASSERT(td->td_lwp->lwp_md.md_regs == frame,
417                         ("_test_frame_exit: Frame mismatch %p %p",
418 			td->td_lwp->lwp_md.md_regs, frame));
419 	    td->td_lwp->lwp_saveusp = (void *)frame->tf_rsp;
420 	    td->td_lwp->lwp_saveupc = (void *)frame->tf_rip;
421 	}
422 	if ((char *)frame < td->td_kstack ||
423 	    (char *)frame > td->td_kstack + td->td_kstack_size) {
424 		panic("_test_frame_exit: frame not on kstack %p kstack=%p",
425 			frame, td->td_kstack);
426 	}
427 }
428 
429 void
430 _test_frame_exit(struct trapframe *frame)
431 {
432 	thread_t td = curthread;
433 
434 	if (ISPL(frame->tf_cs) == SEL_UPL) {
435 		KKASSERT(td->td_lwp);
436                 KASSERT(td->td_lwp->lwp_md.md_regs == frame,
437                         ("_test_frame_exit: Frame mismatch %p %p",
438 			td->td_lwp->lwp_md.md_regs, frame));
439 		if (td->td_lwp->lwp_saveusp != (void *)frame->tf_rsp) {
440 			kprintf("_test_frame_exit: %s:%d usp mismatch %p/%p\n",
441 				td->td_comm, td->td_proc->p_pid,
442 				td->td_lwp->lwp_saveusp,
443 				(void *)frame->tf_rsp);
444 		}
445 		if (td->td_lwp->lwp_saveupc != (void *)frame->tf_rip) {
446 			kprintf("_test_frame_exit: %s:%d upc mismatch %p/%p\n",
447 				td->td_comm, td->td_proc->p_pid,
448 				td->td_lwp->lwp_saveupc,
449 				(void *)frame->tf_rip);
450 		}
451 
452 		/*
453 		 * adulterate the fields to catch entries that
454 		 * don't run through test_frame_enter
455 		 */
456 		td->td_lwp->lwp_saveusp =
457 			(void *)~(intptr_t)td->td_lwp->lwp_saveusp;
458 		td->td_lwp->lwp_saveupc =
459 			(void *)~(intptr_t)td->td_lwp->lwp_saveupc;
460 	}
461 	if ((char *)frame < td->td_kstack ||
462 	    (char *)frame > td->td_kstack + td->td_kstack_size) {
463 		panic("_test_frame_exit: frame not on kstack %p kstack=%p",
464 			frame, td->td_kstack);
465 	}
466 }
467 
468 #endif
469