vm_machdep.c revision 200444
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 * All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * the Systems Programming Group of the University of Utah Computer
9 * Science Department, and William Jolitz.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 *    notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 *    must display the following acknowledgement:
21 *	This product includes software developed by the University of
22 *	California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 *    may be used to endorse or promote products derived from this software
25 *    without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * SUCH DAMAGE.
38 *
39 *	from: @(#)vm_machdep.c	7.3 (Berkeley) 5/13/91
40 *	Utah $Hdr: vm_machdep.c 1.16.1.1 89/06/23$
41 */
42
43#include <sys/cdefs.h>
44__FBSDID("$FreeBSD: head/sys/amd64/amd64/vm_machdep.c 200444 2009-12-12 20:11:31Z kib $");
45
46#include "opt_isa.h"
47#include "opt_cpu.h"
48#include "opt_compat.h"
49
50#include <sys/param.h>
51#include <sys/systm.h>
52#include <sys/bio.h>
53#include <sys/buf.h>
54#include <sys/kernel.h>
55#include <sys/ktr.h>
56#include <sys/lock.h>
57#include <sys/malloc.h>
58#include <sys/mbuf.h>
59#include <sys/mutex.h>
60#include <sys/pioctl.h>
61#include <sys/proc.h>
62#include <sys/sf_buf.h>
63#include <sys/smp.h>
64#include <sys/sysctl.h>
65#include <sys/sysent.h>
66#include <sys/unistd.h>
67#include <sys/vnode.h>
68#include <sys/vmmeter.h>
69
70#include <machine/cpu.h>
71#include <machine/md_var.h>
72#include <machine/pcb.h>
73#include <machine/specialreg.h>
74#include <machine/tss.h>
75
76#include <vm/vm.h>
77#include <vm/vm_extern.h>
78#include <vm/vm_kern.h>
79#include <vm/vm_page.h>
80#include <vm/vm_map.h>
81#include <vm/vm_param.h>
82
83#include <amd64/isa/isa.h>
84
85static void	cpu_reset_real(void);
86#ifdef SMP
87static void	cpu_reset_proxy(void);
88static u_int	cpu_reset_proxyid;
89static volatile u_int	cpu_reset_proxy_active;
90#endif
91
92/*
93 * Finish a fork operation, with process p2 nearly set up.
94 * Copy and update the pcb, set up the stack so that the child
95 * ready to run and return to user mode.
96 */
97void
98cpu_fork(td1, p2, td2, flags)
99	register struct thread *td1;
100	register struct proc *p2;
101	struct thread *td2;
102	int flags;
103{
104	register struct proc *p1;
105	struct pcb *pcb2;
106	struct mdproc *mdp1, *mdp2;
107	struct proc_ldt *pldt;
108	pmap_t pmap2;
109
110	p1 = td1->td_proc;
111	if ((flags & RFPROC) == 0) {
112		if ((flags & RFMEM) == 0) {
113			/* unshare user LDT */
114			mdp1 = &p1->p_md;
115			mtx_lock(&dt_lock);
116			if ((pldt = mdp1->md_ldt) != NULL &&
117			    pldt->ldt_refcnt > 1 &&
118			    user_ldt_alloc(p1, 1) == NULL)
119				panic("could not copy LDT");
120			mtx_unlock(&dt_lock);
121		}
122		return;
123	}
124
125	/* Ensure that p1's pcb is up to date. */
126	fpuexit(td1);
127
128	/* Point the pcb to the top of the stack */
129	pcb2 = (struct pcb *)(td2->td_kstack +
130	    td2->td_kstack_pages * PAGE_SIZE) - 1;
131	td2->td_pcb = pcb2;
132
133	/* Copy p1's pcb */
134	bcopy(td1->td_pcb, pcb2, sizeof(*pcb2));
135
136	/* Point mdproc and then copy over td1's contents */
137	mdp2 = &p2->p_md;
138	bcopy(&p1->p_md, mdp2, sizeof(*mdp2));
139
140	/*
141	 * Create a new fresh stack for the new process.
142	 * Copy the trap frame for the return to user mode as if from a
143	 * syscall.  This copies most of the user mode register values.
144	 */
145	td2->td_frame = (struct trapframe *)td2->td_pcb - 1;
146	bcopy(td1->td_frame, td2->td_frame, sizeof(struct trapframe));
147
148	td2->td_frame->tf_rax = 0;		/* Child returns zero */
149	td2->td_frame->tf_rflags &= ~PSL_C;	/* success */
150	td2->td_frame->tf_rdx = 1;
151
152	/*
153	 * If the parent process has the trap bit set (i.e. a debugger had
154	 * single stepped the process to the system call), we need to clear
155	 * the trap flag from the new frame unless the debugger had set PF_FORK
156	 * on the parent.  Otherwise, the child will receive a (likely
157	 * unexpected) SIGTRAP when it executes the first instruction after
158	 * returning  to userland.
159	 */
160	if ((p1->p_pfsflags & PF_FORK) == 0)
161		td2->td_frame->tf_rflags &= ~PSL_T;
162
163	/*
164	 * Set registers for trampoline to user mode.  Leave space for the
165	 * return address on stack.  These are the kernel mode register values.
166	 */
167	pmap2 = vmspace_pmap(p2->p_vmspace);
168	pcb2->pcb_cr3 = DMAP_TO_PHYS((vm_offset_t)pmap2->pm_pml4);
169	pcb2->pcb_r12 = (register_t)fork_return;	/* fork_trampoline argument */
170	pcb2->pcb_rbp = 0;
171	pcb2->pcb_rsp = (register_t)td2->td_frame - sizeof(void *);
172	pcb2->pcb_rbx = (register_t)td2;		/* fork_trampoline argument */
173	pcb2->pcb_rip = (register_t)fork_trampoline;
174	/*-
175	 * pcb2->pcb_dr*:	cloned above.
176	 * pcb2->pcb_savefpu:	cloned above.
177	 * pcb2->pcb_flags:	cloned above.
178	 * pcb2->pcb_onfault:	cloned above (always NULL here?).
179	 * pcb2->pcb_[fg]sbase:	cloned above
180	 */
181
182	/* Setup to release spin count in fork_exit(). */
183	td2->td_md.md_spinlock_count = 1;
184	td2->td_md.md_saved_flags = PSL_KERNEL | PSL_I;
185
186	/* As an i386, do not copy io permission bitmap. */
187	pcb2->pcb_tssp = NULL;
188
189	/* New segment registers. */
190	pcb2->pcb_full_iret = 1;
191
192	/* Copy the LDT, if necessary. */
193	mdp1 = &td1->td_proc->p_md;
194	mdp2 = &p2->p_md;
195	mtx_lock(&dt_lock);
196	if (mdp1->md_ldt != NULL) {
197		if (flags & RFMEM) {
198			mdp1->md_ldt->ldt_refcnt++;
199			mdp2->md_ldt = mdp1->md_ldt;
200			bcopy(&mdp1->md_ldt_sd, &mdp2->md_ldt_sd, sizeof(struct
201			    system_segment_descriptor));
202		} else {
203			mdp2->md_ldt = NULL;
204			mdp2->md_ldt = user_ldt_alloc(p2, 0);
205			if (mdp2->md_ldt == NULL)
206				panic("could not copy LDT");
207			amd64_set_ldt_data(td2, 0, max_ldt_segment,
208			    (struct user_segment_descriptor *)
209			    mdp1->md_ldt->ldt_base);
210		}
211	} else
212		mdp2->md_ldt = NULL;
213	mtx_unlock(&dt_lock);
214
215	/*
216	 * Now, cpu_switch() can schedule the new process.
217	 * pcb_rsp is loaded pointing to the cpu_switch() stack frame
218	 * containing the return address when exiting cpu_switch.
219	 * This will normally be to fork_trampoline(), which will have
220	 * %ebx loaded with the new proc's pointer.  fork_trampoline()
221	 * will set up a stack to call fork_return(p, frame); to complete
222	 * the return to user-mode.
223	 */
224}
225
226/*
227 * Intercept the return address from a freshly forked process that has NOT
228 * been scheduled yet.
229 *
230 * This is needed to make kernel threads stay in kernel mode.
231 */
232void
233cpu_set_fork_handler(td, func, arg)
234	struct thread *td;
235	void (*func)(void *);
236	void *arg;
237{
238	/*
239	 * Note that the trap frame follows the args, so the function
240	 * is really called like this:  func(arg, frame);
241	 */
242	td->td_pcb->pcb_r12 = (long) func;	/* function */
243	td->td_pcb->pcb_rbx = (long) arg;	/* first arg */
244}
245
246void
247cpu_exit(struct thread *td)
248{
249
250	/*
251	 * If this process has a custom LDT, release it.
252	 */
253	mtx_lock(&dt_lock);
254	if (td->td_proc->p_md.md_ldt != 0)
255		user_ldt_free(td);
256	else
257		mtx_unlock(&dt_lock);
258}
259
260void
261cpu_thread_exit(struct thread *td)
262{
263	struct pcb *pcb;
264
265	if (td == PCPU_GET(fpcurthread))
266		fpudrop();
267
268	pcb = td->td_pcb;
269
270	/* Disable any hardware breakpoints. */
271	if (pcb->pcb_flags & PCB_DBREGS) {
272		reset_dbregs();
273		pcb->pcb_flags &= ~PCB_DBREGS;
274	}
275}
276
277void
278cpu_thread_clean(struct thread *td)
279{
280	struct pcb *pcb;
281
282	pcb = td->td_pcb;
283
284	/*
285	 * Clean TSS/iomap
286	 */
287	if (pcb->pcb_tssp != NULL) {
288		kmem_free(kernel_map, (vm_offset_t)pcb->pcb_tssp,
289		    ctob(IOPAGES + 1));
290		pcb->pcb_tssp = NULL;
291	}
292}
293
294void
295cpu_thread_swapin(struct thread *td)
296{
297}
298
299void
300cpu_thread_swapout(struct thread *td)
301{
302}
303
304void
305cpu_thread_alloc(struct thread *td)
306{
307
308	td->td_pcb = (struct pcb *)(td->td_kstack +
309	    td->td_kstack_pages * PAGE_SIZE) - 1;
310	td->td_frame = (struct trapframe *)td->td_pcb - 1;
311}
312
313void
314cpu_thread_free(struct thread *td)
315{
316
317	cpu_thread_clean(td);
318}
319
320void
321cpu_set_syscall_retval(struct thread *td, int error)
322{
323
324	switch (error) {
325	case 0:
326		td->td_frame->tf_rax = td->td_retval[0];
327		td->td_frame->tf_rdx = td->td_retval[1];
328		td->td_frame->tf_rflags &= ~PSL_C;
329		break;
330
331	case ERESTART:
332		/*
333		 * Reconstruct pc, we know that 'syscall' is 2 bytes,
334		 * lcall $X,y is 7 bytes, int 0x80 is 2 bytes.
335		 * We saved this in tf_err.
336		 * We have to do a full context restore so that %r10
337		 * (which was holding the value of %rcx) is restored
338		 * for the next iteration.
339		 * r10 restore is only required for freebsd/amd64 processes,
340		 * but shall be innocent for any ia32 ABI.
341		 */
342		td->td_frame->tf_rip -= td->td_frame->tf_err;
343		td->td_frame->tf_r10 = td->td_frame->tf_rcx;
344		td->td_pcb->pcb_flags |= PCB_FULLCTX;
345		break;
346
347	case EJUSTRETURN:
348		break;
349
350	default:
351		if (td->td_proc->p_sysent->sv_errsize) {
352			if (error >= td->td_proc->p_sysent->sv_errsize)
353				error = -1;	/* XXX */
354			else
355				error = td->td_proc->p_sysent->sv_errtbl[error];
356		}
357		td->td_frame->tf_rax = error;
358		td->td_frame->tf_rflags |= PSL_C;
359		break;
360	}
361}
362
363/*
364 * Initialize machine state (pcb and trap frame) for a new thread about to
365 * upcall. Put enough state in the new thread's PCB to get it to go back
366 * userret(), where we can intercept it again to set the return (upcall)
367 * Address and stack, along with those from upcals that are from other sources
368 * such as those generated in thread_userret() itself.
369 */
370void
371cpu_set_upcall(struct thread *td, struct thread *td0)
372{
373	struct pcb *pcb2;
374
375	/* Point the pcb to the top of the stack. */
376	pcb2 = td->td_pcb;
377
378	/*
379	 * Copy the upcall pcb.  This loads kernel regs.
380	 * Those not loaded individually below get their default
381	 * values here.
382	 */
383	bcopy(td0->td_pcb, pcb2, sizeof(*pcb2));
384	pcb2->pcb_flags &= ~PCB_FPUINITDONE;
385	pcb2->pcb_full_iret = 1;
386
387	/*
388	 * Create a new fresh stack for the new thread.
389	 */
390	bcopy(td0->td_frame, td->td_frame, sizeof(struct trapframe));
391
392	/* If the current thread has the trap bit set (i.e. a debugger had
393	 * single stepped the process to the system call), we need to clear
394	 * the trap flag from the new frame. Otherwise, the new thread will
395	 * receive a (likely unexpected) SIGTRAP when it executes the first
396	 * instruction after returning to userland.
397	 */
398	td->td_frame->tf_rflags &= ~PSL_T;
399
400	/*
401	 * Set registers for trampoline to user mode.  Leave space for the
402	 * return address on stack.  These are the kernel mode register values.
403	 */
404	pcb2->pcb_r12 = (register_t)fork_return;	    /* trampoline arg */
405	pcb2->pcb_rbp = 0;
406	pcb2->pcb_rsp = (register_t)td->td_frame - sizeof(void *);	/* trampoline arg */
407	pcb2->pcb_rbx = (register_t)td;			    /* trampoline arg */
408	pcb2->pcb_rip = (register_t)fork_trampoline;
409	/*
410	 * If we didn't copy the pcb, we'd need to do the following registers:
411	 * pcb2->pcb_cr3:	cloned above.
412	 * pcb2->pcb_dr*:	cloned above.
413	 * pcb2->pcb_savefpu:	cloned above.
414	 * pcb2->pcb_onfault:	cloned above (always NULL here?).
415	 * pcb2->pcb_[fg]sbase: cloned above
416	 */
417
418	/* Setup to release spin count in fork_exit(). */
419	td->td_md.md_spinlock_count = 1;
420	td->td_md.md_saved_flags = PSL_KERNEL | PSL_I;
421}
422
423/*
424 * Set that machine state for performing an upcall that has to
425 * be done in thread_userret() so that those upcalls generated
426 * in thread_userret() itself can be done as well.
427 */
428void
429cpu_set_upcall_kse(struct thread *td, void (*entry)(void *), void *arg,
430	stack_t *stack)
431{
432
433	/*
434	 * Do any extra cleaning that needs to be done.
435	 * The thread may have optional components
436	 * that are not present in a fresh thread.
437	 * This may be a recycled thread so make it look
438	 * as though it's newly allocated.
439	 */
440	cpu_thread_clean(td);
441
442#ifdef COMPAT_IA32
443	if (td->td_proc->p_sysent->sv_flags & SV_ILP32) {
444		/*
445	 	 * Set the trap frame to point at the beginning of the uts
446		 * function.
447		 */
448		td->td_frame->tf_rbp = 0;
449		td->td_frame->tf_rsp =
450		   (((uintptr_t)stack->ss_sp + stack->ss_size - 4) & ~0x0f) - 4;
451		td->td_frame->tf_rip = (uintptr_t)entry;
452
453		/*
454		 * Pass the address of the mailbox for this kse to the uts
455		 * function as a parameter on the stack.
456		 */
457		suword32((void *)(td->td_frame->tf_rsp + sizeof(int32_t)),
458		    (uint32_t)(uintptr_t)arg);
459
460		return;
461	}
462#endif
463
464	/*
465	 * Set the trap frame to point at the beginning of the uts
466	 * function.
467	 */
468	td->td_frame->tf_rbp = 0;
469	td->td_frame->tf_rsp =
470	    ((register_t)stack->ss_sp + stack->ss_size) & ~0x0f;
471	td->td_frame->tf_rsp -= 8;
472	td->td_frame->tf_rip = (register_t)entry;
473	td->td_frame->tf_ds = _udatasel;
474	td->td_frame->tf_es = _udatasel;
475	td->td_frame->tf_fs = _ufssel;
476	td->td_frame->tf_gs = _ugssel;
477	td->td_frame->tf_flags = TF_HASSEGS;
478
479	/*
480	 * Pass the address of the mailbox for this kse to the uts
481	 * function as a parameter on the stack.
482	 */
483	td->td_frame->tf_rdi = (register_t)arg;
484}
485
486int
487cpu_set_user_tls(struct thread *td, void *tls_base)
488{
489
490	if ((u_int64_t)tls_base >= VM_MAXUSER_ADDRESS)
491		return (EINVAL);
492
493#ifdef COMPAT_IA32
494	if (td->td_proc->p_sysent->sv_flags & SV_ILP32) {
495		td->td_pcb->pcb_gsbase = (register_t)tls_base;
496		return (0);
497	}
498#endif
499	td->td_pcb->pcb_fsbase = (register_t)tls_base;
500	td->td_pcb->pcb_full_iret = 1;
501	return (0);
502}
503
504#ifdef SMP
505static void
506cpu_reset_proxy()
507{
508
509	cpu_reset_proxy_active = 1;
510	while (cpu_reset_proxy_active == 1)
511		;	/* Wait for other cpu to see that we've started */
512	stop_cpus((1<<cpu_reset_proxyid));
513	printf("cpu_reset_proxy: Stopped CPU %d\n", cpu_reset_proxyid);
514	DELAY(1000000);
515	cpu_reset_real();
516}
517#endif
518
519void
520cpu_reset()
521{
522#ifdef SMP
523	u_int cnt, map;
524
525	if (smp_active) {
526		map = PCPU_GET(other_cpus) & ~stopped_cpus;
527		if (map != 0) {
528			printf("cpu_reset: Stopping other CPUs\n");
529			stop_cpus(map);
530		}
531
532		if (PCPU_GET(cpuid) != 0) {
533			cpu_reset_proxyid = PCPU_GET(cpuid);
534			cpustop_restartfunc = cpu_reset_proxy;
535			cpu_reset_proxy_active = 0;
536			printf("cpu_reset: Restarting BSP\n");
537
538			/* Restart CPU #0. */
539			atomic_store_rel_int(&started_cpus, 1 << 0);
540
541			cnt = 0;
542			while (cpu_reset_proxy_active == 0 && cnt < 10000000)
543				cnt++;	/* Wait for BSP to announce restart */
544			if (cpu_reset_proxy_active == 0)
545				printf("cpu_reset: Failed to restart BSP\n");
546			enable_intr();
547			cpu_reset_proxy_active = 2;
548
549			while (1);
550			/* NOTREACHED */
551		}
552
553		DELAY(1000000);
554	}
555#endif
556	cpu_reset_real();
557	/* NOTREACHED */
558}
559
560static void
561cpu_reset_real()
562{
563	struct region_descriptor null_idt;
564	int b;
565
566	disable_intr();
567
568	/*
569	 * Attempt to do a CPU reset via the keyboard controller,
570	 * do not turn off GateA20, as any machine that fails
571	 * to do the reset here would then end up in no man's land.
572	 */
573	outb(IO_KBD + 4, 0xFE);
574	DELAY(500000);	/* wait 0.5 sec to see if that did it */
575
576	/*
577	 * Attempt to force a reset via the Reset Control register at
578	 * I/O port 0xcf9.  Bit 2 forces a system reset when it
579	 * transitions from 0 to 1.  Bit 1 selects the type of reset
580	 * to attempt: 0 selects a "soft" reset, and 1 selects a
581	 * "hard" reset.  We try a "hard" reset.  The first write sets
582	 * bit 1 to select a "hard" reset and clears bit 2.  The
583	 * second write forces a 0 -> 1 transition in bit 2 to trigger
584	 * a reset.
585	 */
586	outb(0xcf9, 0x2);
587	outb(0xcf9, 0x6);
588	DELAY(500000);  /* wait 0.5 sec to see if that did it */
589
590	/*
591	 * Attempt to force a reset via the Fast A20 and Init register
592	 * at I/O port 0x92.  Bit 1 serves as an alternate A20 gate.
593	 * Bit 0 asserts INIT# when set to 1.  We are careful to only
594	 * preserve bit 1 while setting bit 0.  We also must clear bit
595	 * 0 before setting it if it isn't already clear.
596	 */
597	b = inb(0x92);
598	if (b != 0xff) {
599		if ((b & 0x1) != 0)
600			outb(0x92, b & 0xfe);
601		outb(0x92, b | 0x1);
602		DELAY(500000);  /* wait 0.5 sec to see if that did it */
603	}
604
605	printf("No known reset method worked, attempting CPU shutdown\n");
606	DELAY(1000000);	/* wait 1 sec for printf to complete */
607
608	/* Wipe the IDT. */
609	null_idt.rd_limit = 0;
610	null_idt.rd_base = 0;
611	lidt(&null_idt);
612
613	/* "good night, sweet prince .... <THUNK!>" */
614	breakpoint();
615
616	/* NOTREACHED */
617	while(1);
618}
619
620/*
621 * Allocate an sf_buf for the given vm_page.  On this machine, however, there
622 * is no sf_buf object.  Instead, an opaque pointer to the given vm_page is
623 * returned.
624 */
625struct sf_buf *
626sf_buf_alloc(struct vm_page *m, int pri)
627{
628
629	return ((struct sf_buf *)m);
630}
631
632/*
633 * Free the sf_buf.  In fact, do nothing because there are no resources
634 * associated with the sf_buf.
635 */
636void
637sf_buf_free(struct sf_buf *sf)
638{
639}
640
641/*
642 * Software interrupt handler for queued VM system processing.
643 */
644void
645swi_vm(void *dummy)
646{
647	if (busdma_swi_pending != 0)
648		busdma_swi();
649}
650
651/*
652 * Tell whether this address is in some physical memory region.
653 * Currently used by the kernel coredump code in order to avoid
654 * dumping the ``ISA memory hole'' which could cause indefinite hangs,
655 * or other unpredictable behaviour.
656 */
657
658int
659is_physical_memory(vm_paddr_t addr)
660{
661
662#ifdef DEV_ISA
663	/* The ISA ``memory hole''. */
664	if (addr >= 0xa0000 && addr < 0x100000)
665		return 0;
666#endif
667
668	/*
669	 * stuff other tests for known memory-mapped devices (PCI?)
670	 * here
671	 */
672
673	return 1;
674}
675