vm_machdep.c revision 72746
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 * $FreeBSD: head/sys/amd64/amd64/vm_machdep.c 72746 2001-02-20 05:26:15Z jhb $
42 */
43
44#include "opt_npx.h"
45#include "opt_user_ldt.h"
46#ifdef PC98
47#include "opt_pc98.h"
48#endif
49#include "opt_reset.h"
50#include "opt_isa.h"
51
52#include <sys/param.h>
53#include <sys/systm.h>
54#include <sys/malloc.h>
55#include <sys/proc.h>
56#include <sys/bio.h>
57#include <sys/buf.h>
58#include <sys/vnode.h>
59#include <sys/vmmeter.h>
60#include <sys/kernel.h>
61#include <sys/ktr.h>
62#include <sys/mutex.h>
63#include <sys/sysctl.h>
64#include <sys/unistd.h>
65
66#include <machine/cpu.h>
67#include <machine/md_var.h>
68#ifdef SMP
69#include <machine/smp.h>
70#endif
71#include <machine/pcb.h>
72#include <machine/pcb_ext.h>
73#include <machine/vm86.h>
74
75#include <vm/vm.h>
76#include <vm/vm_param.h>
77#include <sys/lock.h>
78#include <vm/vm_kern.h>
79#include <vm/vm_page.h>
80#include <vm/vm_map.h>
81#include <vm/vm_extern.h>
82
83#include <sys/user.h>
84
85#ifdef PC98
86#include <pc98/pc98/pc98.h>
87#else
88#include <i386/isa/isa.h>
89#endif
90
91static void	cpu_reset_real __P((void));
92#ifdef SMP
93static void	cpu_reset_proxy __P((void));
94static u_int	cpu_reset_proxyid;
95static volatile u_int	cpu_reset_proxy_active;
96#endif
97extern int	_ucodesel, _udatasel;
98
99/*
100 * quick version of vm_fault
101 */
102int
103vm_fault_quick(v, prot)
104	caddr_t v;
105	int prot;
106{
107	int r;
108
109	if (prot & VM_PROT_WRITE)
110		r = subyte(v, fubyte(v));
111	else
112		r = fubyte(v);
113	return(r);
114}
115
116/*
117 * Finish a fork operation, with process p2 nearly set up.
118 * Copy and update the pcb, set up the stack so that the child
119 * ready to run and return to user mode.
120 */
121void
122cpu_fork(p1, p2, flags)
123	register struct proc *p1, *p2;
124	int flags;
125{
126	struct pcb *pcb2;
127
128	if ((flags & RFPROC) == 0) {
129#ifdef USER_LDT
130		if ((flags & RFMEM) == 0) {
131			/* unshare user LDT */
132			struct pcb *pcb1 = &p1->p_addr->u_pcb;
133			struct pcb_ldt *pcb_ldt = pcb1->pcb_ldt;
134			if (pcb_ldt && pcb_ldt->ldt_refcnt > 1) {
135				pcb_ldt = user_ldt_alloc(pcb1,pcb_ldt->ldt_len);
136				user_ldt_free(pcb1);
137				pcb1->pcb_ldt = pcb_ldt;
138				set_user_ldt(pcb1);
139			}
140		}
141#endif
142		return;
143	}
144
145#ifdef DEV_NPX
146	/* Ensure that p1's pcb is up to date. */
147	if (PCPU_GET(npxproc) == p1)
148		npxsave(&p1->p_addr->u_pcb.pcb_savefpu);
149#endif
150
151	/* Copy p1's pcb. */
152	p2->p_addr->u_pcb = p1->p_addr->u_pcb;
153	pcb2 = &p2->p_addr->u_pcb;
154
155	/*
156	 * Create a new fresh stack for the new process.
157	 * Copy the trap frame for the return to user mode as if from a
158	 * syscall.  This copies the user mode register values.
159	 */
160	p2->p_md.md_regs = (struct trapframe *)
161			   ((int)p2->p_addr + UPAGES * PAGE_SIZE - 16) - 1;
162	bcopy(p1->p_md.md_regs, p2->p_md.md_regs, sizeof(*p2->p_md.md_regs));
163
164	p2->p_md.md_regs->tf_eax = 0;		/* Child returns zero */
165	p2->p_md.md_regs->tf_eflags &= ~PSL_C;	/* success */
166	p2->p_md.md_regs->tf_edx = 1;
167
168	/*
169	 * Set registers for trampoline to user mode.  Leave space for the
170	 * return address on stack.  These are the kernel mode register values.
171	 */
172	pcb2->pcb_cr3 = vtophys(vmspace_pmap(p2->p_vmspace)->pm_pdir);
173	pcb2->pcb_edi = 0;
174	pcb2->pcb_esi = (int)fork_return;	/* fork_trampoline argument */
175	pcb2->pcb_ebp = 0;
176	pcb2->pcb_esp = (int)p2->p_md.md_regs - sizeof(void *);
177	pcb2->pcb_ebx = (int)p2;		/* fork_trampoline argument */
178	pcb2->pcb_eip = (int)fork_trampoline;
179	/*
180	 * pcb2->pcb_ldt:	duplicated below, if necessary.
181	 * pcb2->pcb_savefpu:	cloned above.
182	 * pcb2->pcb_flags:	cloned above (always 0 here?).
183	 * pcb2->pcb_onfault:	cloned above (always NULL here?).
184	 */
185
186	/*
187	 * XXX don't copy the i/o pages.  this should probably be fixed.
188	 */
189	pcb2->pcb_ext = 0;
190
191#ifdef USER_LDT
192        /* Copy the LDT, if necessary. */
193        if (pcb2->pcb_ldt != 0) {
194		if (flags & RFMEM) {
195			pcb2->pcb_ldt->ldt_refcnt++;
196		} else {
197			pcb2->pcb_ldt = user_ldt_alloc(pcb2,
198				pcb2->pcb_ldt->ldt_len);
199		}
200        }
201#endif
202
203	/*
204	 * Now, cpu_switch() can schedule the new process.
205	 * pcb_esp is loaded pointing to the cpu_switch() stack frame
206	 * containing the return address when exiting cpu_switch.
207	 * This will normally be to fork_trampoline(), which will have
208	 * %ebx loaded with the new proc's pointer.  fork_trampoline()
209	 * will set up a stack to call fork_return(p, frame); to complete
210	 * the return to user-mode.
211	 */
212}
213
214/*
215 * Intercept the return address from a freshly forked process that has NOT
216 * been scheduled yet.
217 *
218 * This is needed to make kernel threads stay in kernel mode.
219 */
220void
221cpu_set_fork_handler(p, func, arg)
222	struct proc *p;
223	void (*func) __P((void *));
224	void *arg;
225{
226	/*
227	 * Note that the trap frame follows the args, so the function
228	 * is really called like this:  func(arg, frame);
229	 */
230	p->p_addr->u_pcb.pcb_esi = (int) func;	/* function */
231	p->p_addr->u_pcb.pcb_ebx = (int) arg;	/* first arg */
232}
233
234void
235cpu_exit(p)
236	register struct proc *p;
237{
238	struct pcb *pcb = &p->p_addr->u_pcb;
239
240#ifdef DEV_NPX
241	npxexit(p);
242#endif
243	if (pcb->pcb_ext != 0) {
244	        /*
245		 * XXX do we need to move the TSS off the allocated pages
246		 * before freeing them?  (not done here)
247		 */
248		kmem_free(kernel_map, (vm_offset_t)pcb->pcb_ext,
249		    ctob(IOPAGES + 1));
250		pcb->pcb_ext = 0;
251	}
252#ifdef USER_LDT
253	user_ldt_free(pcb);
254#endif
255        if (pcb->pcb_flags & PCB_DBREGS) {
256                /*
257                 * disable all hardware breakpoints
258                 */
259                reset_dbregs();
260                pcb->pcb_flags &= ~PCB_DBREGS;
261        }
262	mtx_lock_spin(&sched_lock);
263	mtx_unlock_flags(&Giant, MTX_NOSWITCH);
264	mtx_assert(&Giant, MA_NOTOWNED);
265
266	/*
267	 * We have to wait until after releasing all locks before
268	 * changing p_stat.  If we block on a mutex then we will be
269	 * back at SRUN when we resume and our parent will never
270	 * harvest us.
271	 */
272	p->p_stat = SZOMB;
273
274	mp_fixme("assumption: p_pptr won't change at this time");
275	wakeup(p->p_pptr);
276
277	cnt.v_swtch++;
278	cpu_throw();
279	panic("cpu_exit");
280}
281
282void
283cpu_wait(p)
284	struct proc *p;
285{
286	/* drop per-process resources */
287	pmap_dispose_proc(p);
288
289	/* and clean-out the vmspace */
290	vmspace_free(p->p_vmspace);
291}
292
293/*
294 * Dump the machine specific header information at the start of a core dump.
295 */
296int
297cpu_coredump(p, vp, cred)
298	struct proc *p;
299	struct vnode *vp;
300	struct ucred *cred;
301{
302	int error;
303	caddr_t tempuser;
304
305	tempuser = malloc(ctob(UPAGES), M_TEMP, M_WAITOK | M_ZERO);
306	if (!tempuser)
307		return EINVAL;
308
309	bcopy(p->p_addr, tempuser, sizeof(struct user));
310	bcopy(p->p_md.md_regs,
311	      tempuser + ((caddr_t) p->p_md.md_regs - (caddr_t) p->p_addr),
312	      sizeof(struct trapframe));
313
314	error = vn_rdwr(UIO_WRITE, vp, (caddr_t) tempuser,
315			ctob(UPAGES),
316			(off_t)0, UIO_SYSSPACE, IO_NODELOCKED|IO_UNIT,
317			cred, (int *)NULL, p);
318
319	free(tempuser, M_TEMP);
320
321	return error;
322}
323
324#ifdef notyet
325static void
326setredzone(pte, vaddr)
327	u_short *pte;
328	caddr_t vaddr;
329{
330/* eventually do this by setting up an expand-down stack segment
331   for ss0: selector, allowing stack access down to top of u.
332   this means though that protection violations need to be handled
333   thru a double fault exception that must do an integral task
334   switch to a known good context, within which a dump can be
335   taken. a sensible scheme might be to save the initial context
336   used by sched (that has physical memory mapped 1:1 at bottom)
337   and take the dump while still in mapped mode */
338}
339#endif
340
341/*
342 * Convert kernel VA to physical address
343 */
344u_long
345kvtop(void *addr)
346{
347	vm_offset_t va;
348
349	va = pmap_kextract((vm_offset_t)addr);
350	if (va == 0)
351		panic("kvtop: zero page frame");
352	return((int)va);
353}
354
355/*
356 * Map an IO request into kernel virtual address space.
357 *
358 * All requests are (re)mapped into kernel VA space.
359 * Notice that we use b_bufsize for the size of the buffer
360 * to be mapped.  b_bcount might be modified by the driver.
361 */
362void
363vmapbuf(bp)
364	register struct buf *bp;
365{
366	register caddr_t addr, v, kva;
367	vm_offset_t pa;
368
369	if ((bp->b_flags & B_PHYS) == 0)
370		panic("vmapbuf");
371
372	for (v = bp->b_saveaddr, addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
373	    addr < bp->b_data + bp->b_bufsize;
374	    addr += PAGE_SIZE, v += PAGE_SIZE) {
375		/*
376		 * Do the vm_fault if needed; do the copy-on-write thing
377		 * when reading stuff off device into memory.
378		 */
379		vm_fault_quick(addr,
380			(bp->b_iocmd == BIO_READ)?(VM_PROT_READ|VM_PROT_WRITE):VM_PROT_READ);
381		pa = trunc_page(pmap_kextract((vm_offset_t) addr));
382		if (pa == 0)
383			panic("vmapbuf: page not present");
384		vm_page_hold(PHYS_TO_VM_PAGE(pa));
385		pmap_kenter((vm_offset_t) v, pa);
386	}
387
388	kva = bp->b_saveaddr;
389	bp->b_saveaddr = bp->b_data;
390	bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
391}
392
393/*
394 * Free the io map PTEs associated with this IO operation.
395 * We also invalidate the TLB entries and restore the original b_addr.
396 */
397void
398vunmapbuf(bp)
399	register struct buf *bp;
400{
401	register caddr_t addr;
402	vm_offset_t pa;
403
404	if ((bp->b_flags & B_PHYS) == 0)
405		panic("vunmapbuf");
406
407	for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
408	    addr < bp->b_data + bp->b_bufsize;
409	    addr += PAGE_SIZE) {
410		pa = trunc_page(pmap_kextract((vm_offset_t) addr));
411		pmap_kremove((vm_offset_t) addr);
412		vm_page_unhold(PHYS_TO_VM_PAGE(pa));
413	}
414
415	bp->b_data = bp->b_saveaddr;
416}
417
418/*
419 * Force reset the processor by invalidating the entire address space!
420 */
421
422#ifdef SMP
423static void
424cpu_reset_proxy()
425{
426
427	cpu_reset_proxy_active = 1;
428	while (cpu_reset_proxy_active == 1)
429		;	 /* Wait for other cpu to see that we've started */
430	stop_cpus((1<<cpu_reset_proxyid));
431	printf("cpu_reset_proxy: Stopped CPU %d\n", cpu_reset_proxyid);
432	DELAY(1000000);
433	cpu_reset_real();
434}
435#endif
436
437void
438cpu_reset()
439{
440#ifdef SMP
441	if (smp_active == 0) {
442		cpu_reset_real();
443		/* NOTREACHED */
444	} else {
445
446		u_int map;
447		int cnt;
448		printf("cpu_reset called on cpu#%d\n", PCPU_GET(cpuid));
449
450		map = PCPU_GET(other_cpus) & ~ stopped_cpus;
451
452		if (map != 0) {
453			printf("cpu_reset: Stopping other CPUs\n");
454			stop_cpus(map);		/* Stop all other CPUs */
455		}
456
457		if (PCPU_GET(cpuid) == 0) {
458			DELAY(1000000);
459			cpu_reset_real();
460			/* NOTREACHED */
461		} else {
462			/* We are not BSP (CPU #0) */
463
464			cpu_reset_proxyid = PCPU_GET(cpuid);
465			cpustop_restartfunc = cpu_reset_proxy;
466			cpu_reset_proxy_active = 0;
467			printf("cpu_reset: Restarting BSP\n");
468			started_cpus = (1<<0);		/* Restart CPU #0 */
469
470			cnt = 0;
471			while (cpu_reset_proxy_active == 0 && cnt < 10000000)
472				cnt++;	/* Wait for BSP to announce restart */
473			if (cpu_reset_proxy_active == 0)
474				printf("cpu_reset: Failed to restart BSP\n");
475			enable_intr();
476			cpu_reset_proxy_active = 2;
477
478			while (1);
479			/* NOTREACHED */
480		}
481	}
482#else
483	cpu_reset_real();
484#endif
485}
486
487static void
488cpu_reset_real()
489{
490
491#ifdef PC98
492	/*
493	 * Attempt to do a CPU reset via CPU reset port.
494	 */
495	disable_intr();
496	if ((inb(0x35) & 0xa0) != 0xa0) {
497		outb(0x37, 0x0f);		/* SHUT0 = 0. */
498		outb(0x37, 0x0b);		/* SHUT1 = 0. */
499	}
500	outb(0xf0, 0x00);		/* Reset. */
501#else
502	/*
503	 * Attempt to do a CPU reset via the keyboard controller,
504	 * do not turn of the GateA20, as any machine that fails
505	 * to do the reset here would then end up in no man's land.
506	 */
507
508#if !defined(BROKEN_KEYBOARD_RESET)
509	outb(IO_KBD + 4, 0xFE);
510	DELAY(500000);	/* wait 0.5 sec to see if that did it */
511	printf("Keyboard reset did not work, attempting CPU shutdown\n");
512	DELAY(1000000);	/* wait 1 sec for printf to complete */
513#endif
514#endif /* PC98 */
515	/* force a shutdown by unmapping entire address space ! */
516	bzero((caddr_t) PTD, PAGE_SIZE);
517
518	/* "good night, sweet prince .... <THUNK!>" */
519	invltlb();
520	/* NOTREACHED */
521	while(1);
522}
523
524int
525grow_stack(p, sp)
526	struct proc *p;
527	u_int sp;
528{
529	int rv;
530
531	rv = vm_map_growstack (p, sp);
532	if (rv != KERN_SUCCESS)
533		return (0);
534
535	return (1);
536}
537
538SYSCTL_DECL(_vm_stats_misc);
539
540static int cnt_prezero;
541
542SYSCTL_INT(_vm_stats_misc, OID_AUTO,
543	cnt_prezero, CTLFLAG_RD, &cnt_prezero, 0, "");
544
545/*
546 * Implement the pre-zeroed page mechanism.
547 * This routine is called from the idle loop.
548 */
549
550#define ZIDLE_LO(v)	((v) * 2 / 3)
551#define ZIDLE_HI(v)	((v) * 4 / 5)
552
553int
554vm_page_zero_idle()
555{
556	static int free_rover;
557	static int zero_state;
558	vm_page_t m;
559	int s;
560
561	/*
562	 * Attempt to maintain approximately 1/2 of our free pages in a
563	 * PG_ZERO'd state.   Add some hysteresis to (attempt to) avoid
564	 * generally zeroing a page when the system is near steady-state.
565	 * Otherwise we might get 'flutter' during disk I/O / IPC or
566	 * fast sleeps.  We also do not want to be continuously zeroing
567	 * pages because doing so may flush our L1 and L2 caches too much.
568	 */
569
570	if (zero_state && vm_page_zero_count >= ZIDLE_LO(cnt.v_free_count))
571		return(0);
572	if (vm_page_zero_count >= ZIDLE_HI(cnt.v_free_count))
573		return(0);
574
575	if (mtx_trylock(&Giant)) {
576		s = splvm();
577		zero_state = 0;
578		m = vm_page_list_find(PQ_FREE, free_rover, FALSE);
579		if (m != NULL && (m->flags & PG_ZERO) == 0) {
580			vm_page_queues[m->queue].lcnt--;
581			TAILQ_REMOVE(&vm_page_queues[m->queue].pl, m, pageq);
582			m->queue = PQ_NONE;
583			splx(s);
584			pmap_zero_page(VM_PAGE_TO_PHYS(m));
585			(void)splvm();
586			vm_page_flag_set(m, PG_ZERO);
587			m->queue = PQ_FREE + m->pc;
588			vm_page_queues[m->queue].lcnt++;
589			TAILQ_INSERT_TAIL(&vm_page_queues[m->queue].pl, m,
590			    pageq);
591			++vm_page_zero_count;
592			++cnt_prezero;
593			if (vm_page_zero_count >= ZIDLE_HI(cnt.v_free_count))
594				zero_state = 1;
595		}
596		free_rover = (free_rover + PQ_PRIME2) & PQ_L2_MASK;
597		splx(s);
598		mtx_unlock(&Giant);
599		return (1);
600	}
601	return (0);
602}
603
604/*
605 * Software interrupt handler for queued VM system processing.
606 */
607void
608swi_vm(void *dummy)
609{
610	if (busdma_swi_pending != 0)
611		busdma_swi();
612}
613
614/*
615 * Tell whether this address is in some physical memory region.
616 * Currently used by the kernel coredump code in order to avoid
617 * dumping the ``ISA memory hole'' which could cause indefinite hangs,
618 * or other unpredictable behaviour.
619 */
620
621int
622is_physical_memory(addr)
623	vm_offset_t addr;
624{
625
626#ifdef DEV_ISA
627	/* The ISA ``memory hole''. */
628	if (addr >= 0xa0000 && addr < 0x100000)
629		return 0;
630#endif
631
632	/*
633	 * stuff other tests for known memory-mapped devices (PCI?)
634	 * here
635	 */
636
637	return 1;
638}
639