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