vm_machdep.c revision 60041
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 60041 2000-05-05 09:59:14Z phk $
42 */
43
44#include "npx.h"
45#include "opt_user_ldt.h"
46#ifdef PC98
47#include "opt_pc98.h"
48#endif
49
50#include <sys/param.h>
51#include <sys/systm.h>
52#include <sys/malloc.h>
53#include <sys/proc.h>
54#include <sys/bio.h>
55#include <sys/buf.h>
56#include <sys/vnode.h>
57#include <sys/vmmeter.h>
58#include <sys/kernel.h>
59#include <sys/sysctl.h>
60#include <sys/unistd.h>
61
62#include <machine/clock.h>
63#include <machine/cpu.h>
64#include <machine/md_var.h>
65#ifdef SMP
66#include <machine/smp.h>
67#endif
68#include <machine/pcb.h>
69#include <machine/pcb_ext.h>
70#include <machine/vm86.h>
71
72#include <vm/vm.h>
73#include <vm/vm_param.h>
74#include <sys/lock.h>
75#include <vm/vm_kern.h>
76#include <vm/vm_page.h>
77#include <vm/vm_map.h>
78#include <vm/vm_extern.h>
79
80#include <sys/user.h>
81
82#ifdef PC98
83#include <pc98/pc98/pc98.h>
84#else
85#include <i386/isa/isa.h>
86#endif
87
88static void	cpu_reset_real __P((void));
89#ifdef SMP
90static void	cpu_reset_proxy __P((void));
91static u_int	cpu_reset_proxyid;
92static volatile u_int	cpu_reset_proxy_active;
93#endif
94
95/*
96 * quick version of vm_fault
97 */
98int
99vm_fault_quick(v, prot)
100	caddr_t v;
101	int prot;
102{
103	int r;
104
105	if (prot & VM_PROT_WRITE)
106		r = subyte(v, fubyte(v));
107	else
108		r = fubyte(v);
109	return(r);
110}
111
112/*
113 * Finish a fork operation, with process p2 nearly set up.
114 * Copy and update the pcb, set up the stack so that the child
115 * ready to run and return to user mode.
116 */
117void
118cpu_fork(p1, p2, flags)
119	register struct proc *p1, *p2;
120	int flags;
121{
122	struct pcb *pcb2;
123
124	if ((flags & RFPROC) == 0) {
125#ifdef USER_LDT
126		if ((flags & RFMEM) == 0) {
127			/* unshare user LDT */
128			struct pcb *pcb1 = &p1->p_addr->u_pcb;
129			struct pcb_ldt *pcb_ldt = pcb1->pcb_ldt;
130			if (pcb_ldt && pcb_ldt->ldt_refcnt > 1) {
131				pcb_ldt = user_ldt_alloc(pcb1,pcb_ldt->ldt_len);
132				user_ldt_free(pcb1);
133				pcb1->pcb_ldt = pcb_ldt;
134				set_user_ldt(pcb1);
135			}
136		}
137#endif
138		return;
139	}
140
141#if NNPX > 0
142	/* Ensure that p1's pcb is up to date. */
143	if (npxproc == p1)
144		npxsave(&p1->p_addr->u_pcb.pcb_savefpu);
145#endif
146
147	/* Copy p1's pcb. */
148	p2->p_addr->u_pcb = p1->p_addr->u_pcb;
149	pcb2 = &p2->p_addr->u_pcb;
150
151	/*
152	 * Create a new fresh stack for the new process.
153	 * Copy the trap frame for the return to user mode as if from a
154	 * syscall.  This copies the user mode register values.
155	 */
156	p2->p_md.md_regs = (struct trapframe *)
157			   ((int)p2->p_addr + UPAGES * PAGE_SIZE - 16) - 1;
158	*p2->p_md.md_regs = *p1->p_md.md_regs;
159
160	/*
161	 * Set registers for trampoline to user mode.  Leave space for the
162	 * return address on stack.  These are the kernel mode register values.
163	 */
164	pcb2->pcb_cr3 = vtophys(vmspace_pmap(p2->p_vmspace)->pm_pdir);
165	pcb2->pcb_edi = p2->p_md.md_regs->tf_edi;
166	pcb2->pcb_esi = (int)fork_return;
167	pcb2->pcb_ebp = p2->p_md.md_regs->tf_ebp;
168	pcb2->pcb_esp = (int)p2->p_md.md_regs - sizeof(void *);
169	pcb2->pcb_ebx = (int)p2;
170	pcb2->pcb_eip = (int)fork_trampoline;
171	/*
172	 * pcb2->pcb_ldt:	duplicated below, if necessary.
173	 * pcb2->pcb_savefpu:	cloned above.
174	 * pcb2->pcb_flags:	cloned above (always 0 here?).
175	 * pcb2->pcb_onfault:	cloned above (always NULL here?).
176	 */
177
178#ifdef SMP
179	pcb2->pcb_mpnest = 1;
180#endif
181	/*
182	 * XXX don't copy the i/o pages.  this should probably be fixed.
183	 */
184	pcb2->pcb_ext = 0;
185
186#ifdef USER_LDT
187        /* Copy the LDT, if necessary. */
188        if (pcb2->pcb_ldt != 0) {
189		if (flags & RFMEM) {
190			pcb2->pcb_ldt->ldt_refcnt++;
191		} else {
192			pcb2->pcb_ldt = user_ldt_alloc(pcb2,
193				pcb2->pcb_ldt->ldt_len);
194		}
195        }
196#endif
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 proc_trampoline(), which will have
203	 * %ebx loaded with the new proc's pointer.  proc_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#if NNPX > 0
236	npxexit(p);
237#endif	/* NNPX */
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#ifdef USER_LDT
248	user_ldt_free(pcb);
249#endif
250        if (pcb->pcb_flags & PCB_DBREGS) {
251                /*
252                 * disable all hardware breakpoints
253                 */
254                reset_dbregs();
255                pcb->pcb_flags &= ~PCB_DBREGS;
256        }
257	cnt.v_swtch++;
258	cpu_switch(p);
259	panic("cpu_exit");
260}
261
262void
263cpu_wait(p)
264	struct proc *p;
265{
266	/* drop per-process resources */
267	pmap_dispose_proc(p);
268
269	/* and clean-out the vmspace */
270	vmspace_free(p->p_vmspace);
271}
272
273/*
274 * Dump the machine specific header information at the start of a core dump.
275 */
276int
277cpu_coredump(p, vp, cred)
278	struct proc *p;
279	struct vnode *vp;
280	struct ucred *cred;
281{
282	int error;
283	caddr_t tempuser;
284
285	tempuser = malloc(ctob(UPAGES), M_TEMP, M_WAITOK);
286	if (!tempuser)
287		return EINVAL;
288
289	bzero(tempuser, ctob(UPAGES));
290	bcopy(p->p_addr, tempuser, sizeof(struct user));
291	bcopy(p->p_md.md_regs,
292	      tempuser + ((caddr_t) p->p_md.md_regs - (caddr_t) p->p_addr),
293	      sizeof(struct trapframe));
294
295	error = vn_rdwr(UIO_WRITE, vp, (caddr_t) tempuser,
296			ctob(UPAGES),
297			(off_t)0, UIO_SYSSPACE, IO_NODELOCKED|IO_UNIT,
298			cred, (int *)NULL, p);
299
300	free(tempuser, M_TEMP);
301
302	return error;
303}
304
305#ifdef notyet
306static void
307setredzone(pte, vaddr)
308	u_short *pte;
309	caddr_t vaddr;
310{
311/* eventually do this by setting up an expand-down stack segment
312   for ss0: selector, allowing stack access down to top of u.
313   this means though that protection violations need to be handled
314   thru a double fault exception that must do an integral task
315   switch to a known good context, within which a dump can be
316   taken. a sensible scheme might be to save the initial context
317   used by sched (that has physical memory mapped 1:1 at bottom)
318   and take the dump while still in mapped mode */
319}
320#endif
321
322/*
323 * Convert kernel VA to physical address
324 */
325u_long
326kvtop(void *addr)
327{
328	vm_offset_t va;
329
330	va = pmap_kextract((vm_offset_t)addr);
331	if (va == 0)
332		panic("kvtop: zero page frame");
333	return((int)va);
334}
335
336/*
337 * Map an IO request into kernel virtual address space.
338 *
339 * All requests are (re)mapped into kernel VA space.
340 * Notice that we use b_bufsize for the size of the buffer
341 * to be mapped.  b_bcount might be modified by the driver.
342 */
343void
344vmapbuf(bp)
345	register struct buf *bp;
346{
347	register caddr_t addr, v, kva;
348	vm_offset_t pa;
349
350	if ((bp->b_flags & B_PHYS) == 0)
351		panic("vmapbuf");
352
353	for (v = bp->b_saveaddr, addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
354	    addr < bp->b_data + bp->b_bufsize;
355	    addr += PAGE_SIZE, v += PAGE_SIZE) {
356		/*
357		 * Do the vm_fault if needed; do the copy-on-write thing
358		 * when reading stuff off device into memory.
359		 */
360		vm_fault_quick(addr,
361			(bp->b_iocmd == BIO_READ)?(VM_PROT_READ|VM_PROT_WRITE):VM_PROT_READ);
362		pa = trunc_page(pmap_kextract((vm_offset_t) addr));
363		if (pa == 0)
364			panic("vmapbuf: page not present");
365		vm_page_hold(PHYS_TO_VM_PAGE(pa));
366		pmap_kenter((vm_offset_t) v, pa);
367	}
368
369	kva = bp->b_saveaddr;
370	bp->b_saveaddr = bp->b_data;
371	bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
372}
373
374/*
375 * Free the io map PTEs associated with this IO operation.
376 * We also invalidate the TLB entries and restore the original b_addr.
377 */
378void
379vunmapbuf(bp)
380	register struct buf *bp;
381{
382	register caddr_t addr;
383	vm_offset_t pa;
384
385	if ((bp->b_flags & B_PHYS) == 0)
386		panic("vunmapbuf");
387
388	for (addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
389	    addr < bp->b_data + bp->b_bufsize;
390	    addr += PAGE_SIZE) {
391		pa = trunc_page(pmap_kextract((vm_offset_t) addr));
392		pmap_kremove((vm_offset_t) addr);
393		vm_page_unhold(PHYS_TO_VM_PAGE(pa));
394	}
395
396	bp->b_data = bp->b_saveaddr;
397}
398
399/*
400 * Force reset the processor by invalidating the entire address space!
401 */
402
403#ifdef SMP
404static void
405cpu_reset_proxy()
406{
407	u_int saved_mp_lock;
408
409	cpu_reset_proxy_active = 1;
410	while (cpu_reset_proxy_active == 1)
411		;	 /* Wait for other cpu to disable interupts */
412	saved_mp_lock = mp_lock;
413	mp_lock = 1;
414	printf("cpu_reset_proxy: Grabbed mp lock for BSP\n");
415	cpu_reset_proxy_active = 3;
416	while (cpu_reset_proxy_active == 3)
417		;	/* Wait for other cpu to enable interrupts */
418	stop_cpus((1<<cpu_reset_proxyid));
419	printf("cpu_reset_proxy: Stopped CPU %d\n", cpu_reset_proxyid);
420	DELAY(1000000);
421	cpu_reset_real();
422}
423#endif
424
425void
426cpu_reset()
427{
428#ifdef SMP
429	if (smp_active == 0) {
430		cpu_reset_real();
431		/* NOTREACHED */
432	} else {
433
434		u_int map;
435		int cnt;
436		printf("cpu_reset called on cpu#%d\n",cpuid);
437
438		map = other_cpus & ~ stopped_cpus;
439
440		if (map != 0) {
441			printf("cpu_reset: Stopping other CPUs\n");
442			stop_cpus(map);		/* Stop all other CPUs */
443		}
444
445		if (cpuid == 0) {
446			DELAY(1000000);
447			cpu_reset_real();
448			/* NOTREACHED */
449		} else {
450			/* We are not BSP (CPU #0) */
451
452			cpu_reset_proxyid = cpuid;
453			cpustop_restartfunc = cpu_reset_proxy;
454			printf("cpu_reset: Restarting BSP\n");
455			started_cpus = (1<<0);		/* Restart CPU #0 */
456
457			cnt = 0;
458			while (cpu_reset_proxy_active == 0 && cnt < 10000000)
459				cnt++;	/* Wait for BSP to announce restart */
460			if (cpu_reset_proxy_active == 0)
461				printf("cpu_reset: Failed to restart BSP\n");
462			__asm __volatile("cli" : : : "memory");
463			cpu_reset_proxy_active = 2;
464			cnt = 0;
465			while (cpu_reset_proxy_active == 2 && cnt < 10000000)
466				cnt++;	/* Do nothing */
467			if (cpu_reset_proxy_active == 2) {
468				printf("cpu_reset: BSP did not grab mp lock\n");
469				cpu_reset_real();	/* XXX: Bogus ? */
470			}
471			cpu_reset_proxy_active = 4;
472			__asm __volatile("sti" : : : "memory");
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#ifdef SMP
571	if (try_mplock()) {
572#endif
573		s = splvm();
574		__asm __volatile("sti" : : : "memory");
575		zero_state = 0;
576		m = vm_page_list_find(PQ_FREE, free_rover, FALSE);
577		if (m != NULL && (m->flags & PG_ZERO) == 0) {
578			vm_page_queues[m->queue].lcnt--;
579			TAILQ_REMOVE(&vm_page_queues[m->queue].pl, m, pageq);
580			m->queue = PQ_NONE;
581			splx(s);
582			pmap_zero_page(VM_PAGE_TO_PHYS(m));
583			(void)splvm();
584			vm_page_flag_set(m, PG_ZERO);
585			m->queue = PQ_FREE + m->pc;
586			vm_page_queues[m->queue].lcnt++;
587			TAILQ_INSERT_TAIL(&vm_page_queues[m->queue].pl, m,
588			    pageq);
589			++vm_page_zero_count;
590			++cnt_prezero;
591			if (vm_page_zero_count >= ZIDLE_HI(cnt.v_free_count))
592				zero_state = 1;
593		}
594		free_rover = (free_rover + PQ_PRIME2) & PQ_L2_MASK;
595		splx(s);
596		__asm __volatile("cli" : : : "memory");
597#ifdef SMP
598		rel_mplock();
599#endif
600		return (1);
601#ifdef SMP
602	}
603#endif
604	/*
605	 * We have to enable interrupts for a moment if the try_mplock fails
606	 * in order to potentially take an IPI.   XXX this should be in
607	 * swtch.s
608	 */
609	__asm __volatile("sti; nop; cli" : : : "memory");
610	return (0);
611}
612
613/*
614 * Software interrupt handler for queued VM system processing.
615 */
616void
617swi_vm()
618{
619	if (busdma_swi_pending != 0)
620		busdma_swi();
621}
622
623/*
624 * Tell whether this address is in some physical memory region.
625 * Currently used by the kernel coredump code in order to avoid
626 * dumping the ``ISA memory hole'' which could cause indefinite hangs,
627 * or other unpredictable behaviour.
628 */
629
630#include "isa.h"
631
632int
633is_physical_memory(addr)
634	vm_offset_t addr;
635{
636
637#if NISA > 0
638	/* The ISA ``memory hole''. */
639	if (addr >= 0xa0000 && addr < 0x100000)
640		return 0;
641#endif
642
643	/*
644	 * stuff other tests for known memory-mapped devices (PCI?)
645	 * here
646	 */
647
648	return 1;
649}
650