]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/amd64/machdep.c
This commit was generated by cvs2svn to compensate for changes in r47136,
[FreeBSD/FreeBSD.git] / sys / amd64 / amd64 / machdep.c
1 /*-
2  * Copyright (c) 1992 Terrence R. Lambert.
3  * Copyright (c) 1982, 1987, 1990 The Regents of the University of California.
4  * All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * William Jolitz.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *      This product includes software developed by the University of
20  *      California, Berkeley and its contributors.
21  * 4. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *      from: @(#)machdep.c     7.4 (Berkeley) 6/3/91
38  *      $Id: machdep.c,v 1.334 1999/05/06 00:54:44 luoqi Exp $
39  */
40
41 #include "apm.h"
42 #include "ether.h"
43 #include "npx.h"
44 #include "opt_atalk.h"
45 #include "opt_cpu.h"
46 #include "opt_ddb.h"
47 #include "opt_inet.h"
48 #include "opt_ipx.h"
49 #include "opt_maxmem.h"
50 #include "opt_msgbuf.h"
51 #include "opt_perfmon.h"
52 #include "opt_smp.h"
53 #include "opt_sysvipc.h"
54 #include "opt_user_ldt.h"
55 #include "opt_userconfig.h"
56 #include "opt_vm86.h"
57
58 #include <sys/param.h>
59 #include <sys/systm.h>
60 #include <sys/sysproto.h>
61 #include <sys/signalvar.h>
62 #include <sys/kernel.h>
63 #include <sys/linker.h>
64 #include <sys/proc.h>
65 #include <sys/buf.h>
66 #include <sys/reboot.h>
67 #include <sys/callout.h>
68 #include <sys/malloc.h>
69 #include <sys/mbuf.h>
70 #include <sys/msgbuf.h>
71 #include <sys/sysent.h>
72 #include <sys/sysctl.h>
73 #include <sys/vmmeter.h>
74 #include <sys/bus.h>
75
76 #ifdef SYSVSHM
77 #include <sys/shm.h>
78 #endif
79
80 #ifdef SYSVMSG
81 #include <sys/msg.h>
82 #endif
83
84 #ifdef SYSVSEM
85 #include <sys/sem.h>
86 #endif
87
88 #include <vm/vm.h>
89 #include <vm/vm_param.h>
90 #include <vm/vm_prot.h>
91 #include <sys/lock.h>
92 #include <vm/vm_kern.h>
93 #include <vm/vm_object.h>
94 #include <vm/vm_page.h>
95 #include <vm/vm_map.h>
96 #include <vm/vm_pager.h>
97 #include <vm/vm_extern.h>
98
99 #include <sys/user.h>
100 #include <sys/exec.h>
101
102 #include <ddb/ddb.h>
103
104 #include <net/netisr.h>
105
106 #include <machine/cpu.h>
107 #include <machine/reg.h>
108 #include <machine/clock.h>
109 #include <machine/specialreg.h>
110 #include <machine/cons.h>
111 #include <machine/bootinfo.h>
112 #include <machine/ipl.h>
113 #include <machine/md_var.h>
114 #include <machine/pcb_ext.h>            /* pcb.h included via sys/user.h */
115 #ifdef SMP
116 #include <machine/smp.h>
117 #include <machine/globaldata.h>
118 #endif
119 #ifdef PERFMON
120 #include <machine/perfmon.h>
121 #endif
122
123 #ifdef OLD_BUS_ARCH
124 #include <i386/isa/isa_device.h>
125 #endif
126 #include <i386/isa/intr_machdep.h>
127 #ifndef VM86
128 #include <i386/isa/rtc.h>
129 #endif
130 #include <machine/random.h>
131 #include <sys/ptrace.h>
132
133 extern void init386 __P((int first));
134 extern void dblfault_handler __P((void));
135
136 extern void printcpuinfo(void); /* XXX header file */
137 extern void earlysetcpuclass(void);     /* same header file */
138 extern void finishidentcpu(void);
139 extern void panicifcpuunsupported(void);
140 extern void initializecpu(void);
141
142 static void cpu_startup __P((void *));
143 SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL)
144
145 static MALLOC_DEFINE(M_MBUF, "mbuf", "mbuf");
146
147 int     _udatasel, _ucodesel;
148 u_int   atdevbase;
149
150 #if defined(SWTCH_OPTIM_STATS)
151 extern int swtch_optim_stats;
152 SYSCTL_INT(_debug, OID_AUTO, swtch_optim_stats,
153         CTLFLAG_RD, &swtch_optim_stats, 0, "");
154 SYSCTL_INT(_debug, OID_AUTO, tlb_flush_count,
155         CTLFLAG_RD, &tlb_flush_count, 0, "");
156 #endif
157
158 #ifdef PC98
159 static int      ispc98 = 1;
160 #else
161 static int      ispc98 = 0;
162 #endif
163 SYSCTL_INT(_machdep, OID_AUTO, ispc98, CTLFLAG_RD, &ispc98, 0, "");
164
165 int physmem = 0;
166 int cold = 1;
167
168 static int
169 sysctl_hw_physmem SYSCTL_HANDLER_ARGS
170 {
171         int error = sysctl_handle_int(oidp, 0, ctob(physmem), req);
172         return (error);
173 }
174
175 SYSCTL_PROC(_hw, HW_PHYSMEM, physmem, CTLTYPE_INT|CTLFLAG_RD,
176         0, 0, sysctl_hw_physmem, "I", "");
177
178 static int
179 sysctl_hw_usermem SYSCTL_HANDLER_ARGS
180 {
181         int error = sysctl_handle_int(oidp, 0,
182                 ctob(physmem - cnt.v_wire_count), req);
183         return (error);
184 }
185
186 SYSCTL_PROC(_hw, HW_USERMEM, usermem, CTLTYPE_INT|CTLFLAG_RD,
187         0, 0, sysctl_hw_usermem, "I", "");
188
189 static int
190 sysctl_hw_availpages SYSCTL_HANDLER_ARGS
191 {
192         int error = sysctl_handle_int(oidp, 0,
193                 i386_btop(avail_end - avail_start), req);
194         return (error);
195 }
196
197 SYSCTL_PROC(_hw, OID_AUTO, availpages, CTLTYPE_INT|CTLFLAG_RD,
198         0, 0, sysctl_hw_availpages, "I", "");
199
200 static int
201 sysctl_machdep_msgbuf SYSCTL_HANDLER_ARGS
202 {
203         int error;
204
205         /* Unwind the buffer, so that it's linear (possibly starting with
206          * some initial nulls).
207          */
208         error=sysctl_handle_opaque(oidp,msgbufp->msg_ptr+msgbufp->msg_bufr,
209                 msgbufp->msg_size-msgbufp->msg_bufr,req);
210         if(error) return(error);
211         if(msgbufp->msg_bufr>0) {
212                 error=sysctl_handle_opaque(oidp,msgbufp->msg_ptr,
213                         msgbufp->msg_bufr,req);
214         }
215         return(error);
216 }
217
218 SYSCTL_PROC(_machdep, OID_AUTO, msgbuf, CTLTYPE_STRING|CTLFLAG_RD,
219         0, 0, sysctl_machdep_msgbuf, "A","Contents of kernel message buffer");
220
221 static int msgbuf_clear;
222
223 static int
224 sysctl_machdep_msgbuf_clear SYSCTL_HANDLER_ARGS
225 {
226         int error;
227         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
228                 req);
229         if (!error && req->newptr) {
230                 /* Clear the buffer and reset write pointer */
231                 bzero(msgbufp->msg_ptr,msgbufp->msg_size);
232                 msgbufp->msg_bufr=msgbufp->msg_bufx=0;
233                 msgbuf_clear=0;
234         }
235         return (error);
236 }
237
238 SYSCTL_PROC(_machdep, OID_AUTO, msgbuf_clear, CTLTYPE_INT|CTLFLAG_RW,
239         &msgbuf_clear, 0, sysctl_machdep_msgbuf_clear, "I",
240         "Clear kernel message buffer");
241
242 int bootverbose = 0, Maxmem = 0;
243 long dumplo;
244
245 vm_offset_t phys_avail[10];
246
247 /* must be 2 less so 0 0 can signal end of chunks */
248 #define PHYS_AVAIL_ARRAY_END ((sizeof(phys_avail) / sizeof(vm_offset_t)) - 2)
249
250 static vm_offset_t buffer_sva, buffer_eva;
251 vm_offset_t clean_sva, clean_eva;
252 static vm_offset_t pager_sva, pager_eva;
253 #if NNPX > 0
254 extern struct isa_driver npxdriver;
255 #endif
256
257 #define offsetof(type, member)  ((size_t)(&((type *)0)->member))
258
259 static void
260 cpu_startup(dummy)
261         void *dummy;
262 {
263         register unsigned i;
264         register caddr_t v;
265         vm_offset_t maxaddr;
266         vm_size_t size = 0;
267         int firstaddr;
268         vm_offset_t minaddr;
269
270         if (boothowto & RB_VERBOSE)
271                 bootverbose++;
272
273         /*
274          * Good {morning,afternoon,evening,night}.
275          */
276         printf(version);
277         earlysetcpuclass();
278         startrtclock();
279         printcpuinfo();
280         panicifcpuunsupported();
281 #ifdef PERFMON
282         perfmon_init();
283 #endif
284         printf("real memory  = %u (%uK bytes)\n", ptoa(Maxmem), ptoa(Maxmem) / 1024);
285         /*
286          * Display any holes after the first chunk of extended memory.
287          */
288         if (bootverbose) {
289                 int indx;
290
291                 printf("Physical memory chunk(s):\n");
292                 for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
293                         int size1 = phys_avail[indx + 1] - phys_avail[indx];
294
295                         printf("0x%08x - 0x%08x, %u bytes (%u pages)\n",
296                             phys_avail[indx], phys_avail[indx + 1] - 1, size1,
297                             size1 / PAGE_SIZE);
298                 }
299         }
300
301         /*
302          * Calculate callout wheel size
303          */
304         for (callwheelsize = 1, callwheelbits = 0;
305              callwheelsize < ncallout;
306              callwheelsize <<= 1, ++callwheelbits)
307                 ;
308         callwheelmask = callwheelsize - 1;
309
310         /*
311          * Allocate space for system data structures.
312          * The first available kernel virtual address is in "v".
313          * As pages of kernel virtual memory are allocated, "v" is incremented.
314          * As pages of memory are allocated and cleared,
315          * "firstaddr" is incremented.
316          * An index into the kernel page table corresponding to the
317          * virtual memory address maintained in "v" is kept in "mapaddr".
318          */
319
320         /*
321          * Make two passes.  The first pass calculates how much memory is
322          * needed and allocates it.  The second pass assigns virtual
323          * addresses to the various data structures.
324          */
325         firstaddr = 0;
326 again:
327         v = (caddr_t)firstaddr;
328
329 #define valloc(name, type, num) \
330             (name) = (type *)v; v = (caddr_t)((name)+(num))
331 #define valloclim(name, type, num, lim) \
332             (name) = (type *)v; v = (caddr_t)((lim) = ((name)+(num)))
333
334         valloc(callout, struct callout, ncallout);
335         valloc(callwheel, struct callout_tailq, callwheelsize);
336 #ifdef SYSVSHM
337         valloc(shmsegs, struct shmid_ds, shminfo.shmmni);
338 #endif
339 #ifdef SYSVSEM
340         valloc(sema, struct semid_ds, seminfo.semmni);
341         valloc(sem, struct sem, seminfo.semmns);
342         /* This is pretty disgusting! */
343         valloc(semu, int, (seminfo.semmnu * seminfo.semusz) / sizeof(int));
344 #endif
345 #ifdef SYSVMSG
346         valloc(msgpool, char, msginfo.msgmax);
347         valloc(msgmaps, struct msgmap, msginfo.msgseg);
348         valloc(msghdrs, struct msg, msginfo.msgtql);
349         valloc(msqids, struct msqid_ds, msginfo.msgmni);
350 #endif
351
352         if (nbuf == 0) {
353                 nbuf = 30;
354                 if( physmem > 1024)
355                         nbuf += min((physmem - 1024) / 8, 2048);
356         }
357         nswbuf = max(min(nbuf/4, 64), 16);
358
359         valloc(swbuf, struct buf, nswbuf);
360         valloc(buf, struct buf, nbuf);
361
362
363         /*
364          * End of first pass, size has been calculated so allocate memory
365          */
366         if (firstaddr == 0) {
367                 size = (vm_size_t)(v - firstaddr);
368                 firstaddr = (int)kmem_alloc(kernel_map, round_page(size));
369                 if (firstaddr == 0)
370                         panic("startup: no room for tables");
371                 goto again;
372         }
373
374         /*
375          * End of second pass, addresses have been assigned
376          */
377         if ((vm_size_t)(v - firstaddr) != size)
378                 panic("startup: table size inconsistency");
379
380         clean_map = kmem_suballoc(kernel_map, &clean_sva, &clean_eva,
381                         (nbuf*BKVASIZE) + (nswbuf*MAXPHYS) + pager_map_size);
382         buffer_map = kmem_suballoc(clean_map, &buffer_sva, &buffer_eva,
383                                 (nbuf*BKVASIZE));
384         pager_map = kmem_suballoc(clean_map, &pager_sva, &pager_eva,
385                                 (nswbuf*MAXPHYS) + pager_map_size);
386         pager_map->system_map = 1;
387         exec_map = kmem_suballoc(kernel_map, &minaddr, &maxaddr,
388                                 (16*(ARG_MAX+(PAGE_SIZE*3))));
389
390         /*
391          * Finally, allocate mbuf pool.  Since mclrefcnt is an off-size
392          * we use the more space efficient malloc in place of kmem_alloc.
393          */
394         {
395                 vm_offset_t mb_map_size;
396                 int xclusters;
397
398                 /* Allow override of NMBCLUSTERS from the kernel environment */
399                 if (getenv_int("kern.ipc.nmbclusters", &xclusters) && 
400                     xclusters > nmbclusters)
401                     nmbclusters = xclusters;
402
403                 mb_map_size = nmbufs * MSIZE + nmbclusters * MCLBYTES;
404                 mb_map_size = roundup2(mb_map_size, max(MCLBYTES, PAGE_SIZE));
405                 mclrefcnt = malloc(mb_map_size / MCLBYTES, M_MBUF, M_NOWAIT);
406                 bzero(mclrefcnt, mb_map_size / MCLBYTES);
407                 mb_map = kmem_suballoc(kmem_map, (vm_offset_t *)&mbutl, &maxaddr,
408                         mb_map_size);
409                 mb_map->system_map = 1;
410         }
411
412         /*
413          * Initialize callouts
414          */
415         SLIST_INIT(&callfree);
416         for (i = 0; i < ncallout; i++) {
417                 callout_init(&callout[i]);
418                 callout[i].c_flags = CALLOUT_LOCAL_ALLOC;
419                 SLIST_INSERT_HEAD(&callfree, &callout[i], c_links.sle);
420         }
421
422         for (i = 0; i < callwheelsize; i++) {
423                 TAILQ_INIT(&callwheel[i]);
424         }
425
426 #if defined(USERCONFIG)
427         userconfig();
428         cninit();               /* the preferred console may have changed */
429 #endif
430
431         printf("avail memory = %u (%uK bytes)\n", ptoa(cnt.v_free_count),
432             ptoa(cnt.v_free_count) / 1024);
433
434         /*
435          * Set up buffers, so they can be used to read disk labels.
436          */
437         bufinit();
438         vm_pager_bufferinit();
439
440 #ifdef SMP
441         /*
442          * OK, enough kmem_alloc/malloc state should be up, lets get on with it!
443          */
444         mp_start();                     /* fire up the APs and APICs */
445         mp_announce();
446 #endif  /* SMP */
447 }
448
449 int
450 register_netisr(num, handler)
451         int num;
452         netisr_t *handler;
453 {
454         
455         if (num < 0 || num >= (sizeof(netisrs)/sizeof(*netisrs)) ) {
456                 printf("register_netisr: bad isr number: %d\n", num);
457                 return (EINVAL);
458         }
459         netisrs[num] = handler;
460         return (0);
461 }
462
463 void
464 netisr_sysinit(data)
465         void *data;
466 {
467         const struct netisrtab *nit;
468
469         nit = (const struct netisrtab *)data;
470         register_netisr(nit->nit_num, nit->nit_isr);
471 }
472
473 /*
474  * Send an interrupt to process.
475  *
476  * Stack is set up to allow sigcode stored
477  * at top to call routine, followed by kcall
478  * to sigreturn routine below.  After sigreturn
479  * resets the signal mask, the stack, and the
480  * frame pointer, it returns to the user
481  * specified pc, psl.
482  */
483 void
484 sendsig(catcher, sig, mask, code)
485         sig_t catcher;
486         int sig, mask;
487         u_long code;
488 {
489         register struct proc *p = curproc;
490         register struct trapframe *regs;
491         register struct sigframe *fp;
492         struct sigframe sf;
493         struct sigacts *psp = p->p_sigacts;
494         int oonstack;
495
496         regs = p->p_md.md_regs;
497         oonstack = psp->ps_sigstk.ss_flags & SS_ONSTACK;
498         /*
499          * Allocate and validate space for the signal handler context.
500          */
501         if ((psp->ps_flags & SAS_ALTSTACK) && !oonstack &&
502             (psp->ps_sigonstack & sigmask(sig))) {
503                 fp = (struct sigframe *)(psp->ps_sigstk.ss_sp +
504                     psp->ps_sigstk.ss_size - sizeof(struct sigframe));
505                 psp->ps_sigstk.ss_flags |= SS_ONSTACK;
506         } else {
507                 fp = (struct sigframe *)regs->tf_esp - 1;
508         }
509
510         /*
511          * grow() will return FALSE if the fp will not fit inside the stack
512          *      and the stack can not be grown. useracc will return FALSE
513          *      if access is denied.
514          */
515         if ((grow_stack (p, (int)fp) == FALSE) ||
516             (useracc((caddr_t)fp, sizeof(struct sigframe), B_WRITE) == FALSE)) {
517                 /*
518                  * Process has trashed its stack; give it an illegal
519                  * instruction to halt it in its tracks.
520                  */
521                 SIGACTION(p, SIGILL) = SIG_DFL;
522                 sig = sigmask(SIGILL);
523                 p->p_sigignore &= ~sig;
524                 p->p_sigcatch &= ~sig;
525                 p->p_sigmask &= ~sig;
526                 psignal(p, SIGILL);
527                 return;
528         }
529
530         /*
531          * Build the argument list for the signal handler.
532          */
533         if (p->p_sysent->sv_sigtbl) {
534                 if (sig < p->p_sysent->sv_sigsize)
535                         sig = p->p_sysent->sv_sigtbl[sig];
536                 else
537                         sig = p->p_sysent->sv_sigsize + 1;
538         }
539         sf.sf_signum = sig;
540         sf.sf_code = code;
541         sf.sf_scp = &fp->sf_sc;
542         sf.sf_addr = (char *) regs->tf_err;
543         sf.sf_handler = catcher;
544
545         /* save scratch registers */
546         sf.sf_sc.sc_eax = regs->tf_eax;
547         sf.sf_sc.sc_ebx = regs->tf_ebx;
548         sf.sf_sc.sc_ecx = regs->tf_ecx;
549         sf.sf_sc.sc_edx = regs->tf_edx;
550         sf.sf_sc.sc_esi = regs->tf_esi;
551         sf.sf_sc.sc_edi = regs->tf_edi;
552         sf.sf_sc.sc_cs = regs->tf_cs;
553         sf.sf_sc.sc_ds = regs->tf_ds;
554         sf.sf_sc.sc_ss = regs->tf_ss;
555         sf.sf_sc.sc_es = regs->tf_es;
556         sf.sf_sc.sc_fs = regs->tf_fs;
557         sf.sf_sc.sc_isp = regs->tf_isp;
558
559         /*
560          * Build the signal context to be used by sigreturn.
561          */
562         sf.sf_sc.sc_onstack = oonstack;
563         sf.sf_sc.sc_mask = mask;
564         sf.sf_sc.sc_sp = regs->tf_esp;
565         sf.sf_sc.sc_fp = regs->tf_ebp;
566         sf.sf_sc.sc_pc = regs->tf_eip;
567         sf.sf_sc.sc_ps = regs->tf_eflags;
568         sf.sf_sc.sc_trapno = regs->tf_trapno;
569         sf.sf_sc.sc_err = regs->tf_err;
570
571 #ifdef VM86
572         /*
573          * If we're a vm86 process, we want to save the segment registers.
574          * We also change eflags to be our emulated eflags, not the actual
575          * eflags.
576          */
577         if (regs->tf_eflags & PSL_VM) {
578                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
579                 struct vm86_kernel *vm86 = &p->p_addr->u_pcb.pcb_ext->ext_vm86;
580
581                 sf.sf_sc.sc_gs = tf->tf_vm86_gs;
582                 sf.sf_sc.sc_fs = tf->tf_vm86_fs;
583                 sf.sf_sc.sc_es = tf->tf_vm86_es;
584                 sf.sf_sc.sc_ds = tf->tf_vm86_ds;
585
586                 if (vm86->vm86_has_vme == 0)
587                         sf.sf_sc.sc_ps = (tf->tf_eflags & ~(PSL_VIF | PSL_VIP))
588                             | (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
589
590                 /*
591                  * We should never have PSL_T set when returning from vm86
592                  * mode.  It may be set here if we deliver a signal before
593                  * getting to vm86 mode, so turn it off.
594                  *
595                  * Clear PSL_NT to inhibit T_TSSFLT faults on return from
596                  * syscalls made by the signal handler.  This just avoids
597                  * wasting time for our lazy fixup of such faults.  PSL_NT
598                  * does nothing in vm86 mode, but vm86 programs can set it
599                  * almost legitimately in probes for old cpu types.
600                  */
601                 tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_T | PSL_VIF | PSL_VIP);
602         }
603 #endif /* VM86 */
604
605         /*
606          * Copy the sigframe out to the user's stack.
607          */
608         if (copyout(&sf, fp, sizeof(struct sigframe)) != 0) {
609                 /*
610                  * Something is wrong with the stack pointer.
611                  * ...Kill the process.
612                  */
613                 sigexit(p, SIGILL);
614         }
615
616         regs->tf_esp = (int)fp;
617         regs->tf_eip = PS_STRINGS - *(p->p_sysent->sv_szsigcode);
618         regs->tf_cs = _ucodesel;
619         regs->tf_ds = _udatasel;
620         regs->tf_es = _udatasel;
621         regs->tf_fs = _udatasel;
622         regs->tf_ss = _udatasel;
623 }
624
625 /*
626  * System call to cleanup state after a signal
627  * has been taken.  Reset signal mask and
628  * stack state from context left by sendsig (above).
629  * Return to previous pc and psl as specified by
630  * context left by sendsig. Check carefully to
631  * make sure that the user has not modified the
632  * state to gain improper privileges.
633  */
634 int
635 sigreturn(p, uap)
636         struct proc *p;
637         struct sigreturn_args /* {
638                 struct sigcontext *sigcntxp;
639         } */ *uap;
640 {
641         register struct sigcontext *scp;
642         register struct sigframe *fp;
643         register struct trapframe *regs = p->p_md.md_regs;
644         int eflags;
645
646         /*
647          * (XXX old comment) regs->tf_esp points to the return address.
648          * The user scp pointer is above that.
649          * The return address is faked in the signal trampoline code
650          * for consistency.
651          */
652         scp = uap->sigcntxp;
653         fp = (struct sigframe *)
654              ((caddr_t)scp - offsetof(struct sigframe, sf_sc));
655
656         if (useracc((caddr_t)fp, sizeof (*fp), B_WRITE) == 0)
657                 return(EFAULT);
658
659         eflags = scp->sc_ps;
660 #ifdef VM86
661         if (eflags & PSL_VM) {
662                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
663                 struct vm86_kernel *vm86;
664
665                 /*
666                  * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
667                  * set up the vm86 area, and we can't enter vm86 mode.
668                  */
669                 if (p->p_addr->u_pcb.pcb_ext == 0)
670                         return (EINVAL);
671                 vm86 = &p->p_addr->u_pcb.pcb_ext->ext_vm86;
672                 if (vm86->vm86_inited == 0)
673                         return (EINVAL);
674
675                 /* go back to user mode if both flags are set */
676                 if ((eflags & PSL_VIP) && (eflags & PSL_VIF))
677                         trapsignal(p, SIGBUS, 0);
678
679                 if (vm86->vm86_has_vme) {
680                         eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
681                             (eflags & VME_USERCHANGE) | PSL_VM;
682                 } else {
683                         vm86->vm86_eflags = eflags;     /* save VIF, VIP */
684                         eflags = (tf->tf_eflags & ~VM_USERCHANGE) |                                         (eflags & VM_USERCHANGE) | PSL_VM;
685                 }
686                 tf->tf_vm86_ds = scp->sc_ds;
687                 tf->tf_vm86_es = scp->sc_es;
688                 tf->tf_vm86_fs = scp->sc_fs;
689                 tf->tf_vm86_gs = scp->sc_gs;
690                 tf->tf_ds = _udatasel;
691                 tf->tf_es = _udatasel;
692                 tf->tf_fs = _udatasel;
693         } else {
694 #endif /* VM86 */
695                 /*
696                  * Don't allow users to change privileged or reserved flags.
697                  */
698 #define EFLAGS_SECURE(ef, oef)  ((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
699                 /*
700                  * XXX do allow users to change the privileged flag PSL_RF.
701                  * The cpu sets PSL_RF in tf_eflags for faults.  Debuggers
702                  * should sometimes set it there too.  tf_eflags is kept in
703                  * the signal context during signal handling and there is no
704                  * other place to remember it, so the PSL_RF bit may be
705                  * corrupted by the signal handler without us knowing.
706                  * Corruption of the PSL_RF bit at worst causes one more or
707                  * one less debugger trap, so allowing it is fairly harmless.
708                  */
709                 if (!EFLAGS_SECURE(eflags & ~PSL_RF, regs->tf_eflags & ~PSL_RF)) {
710 #ifdef DEBUG
711                         printf("sigreturn: eflags = 0x%x\n", eflags);
712 #endif
713                         return(EINVAL);
714                 }
715
716                 /*
717                  * Don't allow users to load a valid privileged %cs.  Let the
718                  * hardware check for invalid selectors, excess privilege in
719                  * other selectors, invalid %eip's and invalid %esp's.
720                  */
721 #define CS_SECURE(cs)   (ISPL(cs) == SEL_UPL)
722                 if (!CS_SECURE(scp->sc_cs)) {
723 #ifdef DEBUG
724                         printf("sigreturn: cs = 0x%x\n", scp->sc_cs);
725 #endif
726                         trapsignal(p, SIGBUS, T_PROTFLT);
727                         return(EINVAL);
728                 }
729                 regs->tf_ds = scp->sc_ds;
730                 regs->tf_es = scp->sc_es;
731                 regs->tf_fs = scp->sc_fs;
732 #ifdef VM86
733         }
734 #endif
735
736         /* restore scratch registers */
737         regs->tf_eax = scp->sc_eax;
738         regs->tf_ebx = scp->sc_ebx;
739         regs->tf_ecx = scp->sc_ecx;
740         regs->tf_edx = scp->sc_edx;
741         regs->tf_esi = scp->sc_esi;
742         regs->tf_edi = scp->sc_edi;
743         regs->tf_cs = scp->sc_cs;
744         regs->tf_ss = scp->sc_ss;
745         regs->tf_isp = scp->sc_isp;
746
747         if (useracc((caddr_t)scp, sizeof (*scp), B_WRITE) == 0)
748                 return(EINVAL);
749
750         if (scp->sc_onstack & 01)
751                 p->p_sigacts->ps_sigstk.ss_flags |= SS_ONSTACK;
752         else
753                 p->p_sigacts->ps_sigstk.ss_flags &= ~SS_ONSTACK;
754         p->p_sigmask = scp->sc_mask & ~sigcantmask;
755         regs->tf_ebp = scp->sc_fp;
756         regs->tf_esp = scp->sc_sp;
757         regs->tf_eip = scp->sc_pc;
758         regs->tf_eflags = eflags;
759         return(EJUSTRETURN);
760 }
761
762 /*
763  * Machine dependent boot() routine
764  *
765  * I haven't seen anything to put here yet
766  * Possibly some stuff might be grafted back here from boot()
767  */
768 void
769 cpu_boot(int howto)
770 {
771 }
772
773 /*
774  * Shutdown the CPU as much as possible
775  */
776 void
777 cpu_halt(void)
778 {
779         for (;;)
780                 __asm__ ("hlt");
781 }
782
783 /*
784  * Clear registers on exec
785  */
786 void
787 setregs(p, entry, stack, ps_strings)
788         struct proc *p;
789         u_long entry;
790         u_long stack;
791         u_long ps_strings;
792 {
793         struct trapframe *regs = p->p_md.md_regs;
794         struct pcb *pcb = &p->p_addr->u_pcb;
795
796 #ifdef USER_LDT
797         /* was i386_user_cleanup() in NetBSD */
798         if (pcb->pcb_ldt) {
799                 if (pcb == curpcb) {
800                         lldt(_default_ldt);
801                         currentldt = _default_ldt;
802                 }
803                 kmem_free(kernel_map, (vm_offset_t)pcb->pcb_ldt,
804                         pcb->pcb_ldt_len * sizeof(union descriptor));
805                 pcb->pcb_ldt_len = (int)pcb->pcb_ldt = 0;
806         }
807 #endif
808   
809         bzero((char *)regs, sizeof(struct trapframe));
810         regs->tf_eip = entry;
811         regs->tf_esp = stack;
812         regs->tf_eflags = PSL_USER | (regs->tf_eflags & PSL_T);
813         regs->tf_ss = _udatasel;
814         regs->tf_ds = _udatasel;
815         regs->tf_es = _udatasel;
816         regs->tf_fs = _udatasel;
817         regs->tf_cs = _ucodesel;
818
819         /* PS_STRINGS value for BSD/OS binaries.  It is 0 for non-BSD/OS. */
820         regs->tf_ebx = ps_strings;
821
822         /* reset %gs as well */
823         pcb->pcb_gs = _udatasel;
824         if (pcb == curpcb) {
825                 load_gs(_udatasel);
826         }
827
828         /*
829          * Initialize the math emulator (if any) for the current process.
830          * Actually, just clear the bit that says that the emulator has
831          * been initialized.  Initialization is delayed until the process
832          * traps to the emulator (if it is done at all) mainly because
833          * emulators don't provide an entry point for initialization.
834          */
835         p->p_addr->u_pcb.pcb_flags &= ~FP_SOFTFP;
836
837         /*
838          * Arrange to trap the next npx or `fwait' instruction (see npx.c
839          * for why fwait must be trapped at least if there is an npx or an
840          * emulator).  This is mainly to handle the case where npx0 is not
841          * configured, since the npx routines normally set up the trap
842          * otherwise.  It should be done only at boot time, but doing it
843          * here allows modifying `npx_exists' for testing the emulator on
844          * systems with an npx.
845          */
846         load_cr0(rcr0() | CR0_MP | CR0_TS);
847
848 #if NNPX > 0
849         /* Initialize the npx (if any) for the current process. */
850         npxinit(__INITIAL_NPXCW__);
851 #endif
852
853       /*
854        * XXX - Linux emulator
855        * Make sure sure edx is 0x0 on entry. Linux binaries depend
856        * on it.
857        */
858       p->p_retval[1] = 0;
859 }
860
861 static int
862 sysctl_machdep_adjkerntz SYSCTL_HANDLER_ARGS
863 {
864         int error;
865         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
866                 req);
867         if (!error && req->newptr)
868                 resettodr();
869         return (error);
870 }
871
872 SYSCTL_PROC(_machdep, CPU_ADJKERNTZ, adjkerntz, CTLTYPE_INT|CTLFLAG_RW,
873         &adjkerntz, 0, sysctl_machdep_adjkerntz, "I", "");
874
875 SYSCTL_INT(_machdep, CPU_DISRTCSET, disable_rtc_set,
876         CTLFLAG_RW, &disable_rtc_set, 0, "");
877
878 SYSCTL_STRUCT(_machdep, CPU_BOOTINFO, bootinfo, 
879         CTLFLAG_RD, &bootinfo, bootinfo, "");
880
881 SYSCTL_INT(_machdep, CPU_WALLCLOCK, wall_cmos_clock,
882         CTLFLAG_RW, &wall_cmos_clock, 0, "");
883
884 /*
885  * Initialize 386 and configure to run kernel
886  */
887
888 /*
889  * Initialize segments & interrupt table
890  */
891
892 int _default_ldt;
893 #ifdef SMP
894 union descriptor gdt[NGDT * NCPU];      /* global descriptor table */
895 #else
896 union descriptor gdt[NGDT];             /* global descriptor table */
897 #endif
898 struct gate_descriptor idt[NIDT];       /* interrupt descriptor table */
899 union descriptor ldt[NLDT];             /* local descriptor table */
900 #ifdef SMP
901 /* table descriptors - used to load tables by microp */
902 struct region_descriptor r_gdt, r_idt;
903 #endif
904
905 #ifdef VM86
906 #ifndef SMP
907 extern struct segment_descriptor common_tssd, *tss_gdt;
908 #endif
909 int private_tss;                        /* flag indicating private tss */
910 #endif /* VM86 */
911
912 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
913 struct gate_descriptor *t_idt;
914 extern int has_f00f_bug;
915 #endif
916
917 static struct i386tss dblfault_tss;
918 static char dblfault_stack[PAGE_SIZE];
919
920 extern  struct user *proc0paddr;
921
922
923 /* software prototypes -- in more palatable form */
924 struct soft_segment_descriptor gdt_segs[] = {
925 /* GNULL_SEL    0 Null Descriptor */
926 {       0x0,                    /* segment base address  */
927         0x0,                    /* length */
928         0,                      /* segment type */
929         0,                      /* segment descriptor priority level */
930         0,                      /* segment descriptor present */
931         0, 0,
932         0,                      /* default 32 vs 16 bit size */
933         0                       /* limit granularity (byte/page units)*/ },
934 /* GCODE_SEL    1 Code Descriptor for kernel */
935 {       0x0,                    /* segment base address  */
936         0xfffff,                /* length - all address space */
937         SDT_MEMERA,             /* segment type */
938         0,                      /* segment descriptor priority level */
939         1,                      /* segment descriptor present */
940         0, 0,
941         1,                      /* default 32 vs 16 bit size */
942         1                       /* limit granularity (byte/page units)*/ },
943 /* GDATA_SEL    2 Data Descriptor for kernel */
944 {       0x0,                    /* segment base address  */
945         0xfffff,                /* length - all address space */
946         SDT_MEMRWA,             /* segment type */
947         0,                      /* segment descriptor priority level */
948         1,                      /* segment descriptor present */
949         0, 0,
950         1,                      /* default 32 vs 16 bit size */
951         1                       /* limit granularity (byte/page units)*/ },
952 /* GPRIV_SEL    3 SMP Per-Processor Private Data Descriptor */
953 {       0x0,                    /* segment base address  */
954         0xfffff,                /* length - all address space */
955         SDT_MEMRWA,             /* segment type */
956         0,                      /* segment descriptor priority level */
957         1,                      /* segment descriptor present */
958         0, 0,
959         1,                      /* default 32 vs 16 bit size */
960         1                       /* limit granularity (byte/page units)*/ },
961 /* GPROC0_SEL   4 Proc 0 Tss Descriptor */
962 {
963         0x0,                    /* segment base address */
964         sizeof(struct i386tss)-1,/* length - all address space */
965         SDT_SYS386TSS,          /* segment type */
966         0,                      /* segment descriptor priority level */
967         1,                      /* segment descriptor present */
968         0, 0,
969         0,                      /* unused - default 32 vs 16 bit size */
970         0                       /* limit granularity (byte/page units)*/ },
971 /* GLDT_SEL     5 LDT Descriptor */
972 {       (int) ldt,              /* segment base address  */
973         sizeof(ldt)-1,          /* length - all address space */
974         SDT_SYSLDT,             /* segment type */
975         SEL_UPL,                /* segment descriptor priority level */
976         1,                      /* segment descriptor present */
977         0, 0,
978         0,                      /* unused - default 32 vs 16 bit size */
979         0                       /* limit granularity (byte/page units)*/ },
980 /* GUSERLDT_SEL 6 User LDT Descriptor per process */
981 {       (int) ldt,              /* segment base address  */
982         (512 * sizeof(union descriptor)-1),             /* length */
983         SDT_SYSLDT,             /* segment type */
984         0,                      /* segment descriptor priority level */
985         1,                      /* segment descriptor present */
986         0, 0,
987         0,                      /* unused - default 32 vs 16 bit size */
988         0                       /* limit granularity (byte/page units)*/ },
989 /* GTGATE_SEL   7 Null Descriptor - Placeholder */
990 {       0x0,                    /* segment base address  */
991         0x0,                    /* length - all address space */
992         0,                      /* segment type */
993         0,                      /* segment descriptor priority level */
994         0,                      /* segment descriptor present */
995         0, 0,
996         0,                      /* default 32 vs 16 bit size */
997         0                       /* limit granularity (byte/page units)*/ },
998 /* GPANIC_SEL   8 Panic Tss Descriptor */
999 {       (int) &dblfault_tss,    /* segment base address  */
1000         sizeof(struct i386tss)-1,/* length - all address space */
1001         SDT_SYS386TSS,          /* segment type */
1002         0,                      /* segment descriptor priority level */
1003         1,                      /* segment descriptor present */
1004         0, 0,
1005         0,                      /* unused - default 32 vs 16 bit size */
1006         0                       /* limit granularity (byte/page units)*/ },
1007 /* GAPMCODE32_SEL 9 APM BIOS 32-bit interface (32bit Code) */
1008 {       0,                      /* segment base address (overwritten by APM)  */
1009         0xfffff,                /* length */
1010         SDT_MEMERA,             /* segment type */
1011         0,                      /* segment descriptor priority level */
1012         1,                      /* segment descriptor present */
1013         0, 0,
1014         1,                      /* default 32 vs 16 bit size */
1015         1                       /* limit granularity (byte/page units)*/ },
1016 /* GAPMCODE16_SEL 10 APM BIOS 32-bit interface (16bit Code) */
1017 {       0,                      /* segment base address (overwritten by APM)  */
1018         0xfffff,                /* length */
1019         SDT_MEMERA,             /* segment type */
1020         0,                      /* segment descriptor priority level */
1021         1,                      /* segment descriptor present */
1022         0, 0,
1023         0,                      /* default 32 vs 16 bit size */
1024         1                       /* limit granularity (byte/page units)*/ },
1025 /* GAPMDATA_SEL 11 APM BIOS 32-bit interface (Data) */
1026 {       0,                      /* segment base address (overwritten by APM) */
1027         0xfffff,                /* length */
1028         SDT_MEMRWA,             /* segment type */
1029         0,                      /* segment descriptor priority level */
1030         1,                      /* segment descriptor present */
1031         0, 0,
1032         1,                      /* default 32 vs 16 bit size */
1033         1                       /* limit granularity (byte/page units)*/ },
1034 };
1035
1036 static struct soft_segment_descriptor ldt_segs[] = {
1037         /* Null Descriptor - overwritten by call gate */
1038 {       0x0,                    /* segment base address  */
1039         0x0,                    /* length - all address space */
1040         0,                      /* segment type */
1041         0,                      /* segment descriptor priority level */
1042         0,                      /* segment descriptor present */
1043         0, 0,
1044         0,                      /* default 32 vs 16 bit size */
1045         0                       /* limit granularity (byte/page units)*/ },
1046         /* Null Descriptor - overwritten by call gate */
1047 {       0x0,                    /* segment base address  */
1048         0x0,                    /* length - all address space */
1049         0,                      /* segment type */
1050         0,                      /* segment descriptor priority level */
1051         0,                      /* segment descriptor present */
1052         0, 0,
1053         0,                      /* default 32 vs 16 bit size */
1054         0                       /* limit granularity (byte/page units)*/ },
1055         /* Null Descriptor - overwritten by call gate */
1056 {       0x0,                    /* segment base address  */
1057         0x0,                    /* length - all address space */
1058         0,                      /* segment type */
1059         0,                      /* segment descriptor priority level */
1060         0,                      /* segment descriptor present */
1061         0, 0,
1062         0,                      /* default 32 vs 16 bit size */
1063         0                       /* limit granularity (byte/page units)*/ },
1064         /* Code Descriptor for user */
1065 {       0x0,                    /* segment base address  */
1066         0xfffff,                /* length - all address space */
1067         SDT_MEMERA,             /* segment type */
1068         SEL_UPL,                /* segment descriptor priority level */
1069         1,                      /* segment descriptor present */
1070         0, 0,
1071         1,                      /* default 32 vs 16 bit size */
1072         1                       /* limit granularity (byte/page units)*/ },
1073         /* Null Descriptor - overwritten by call gate */
1074 {       0x0,                    /* segment base address  */
1075         0x0,                    /* length - all address space */
1076         0,                      /* segment type */
1077         0,                      /* segment descriptor priority level */
1078         0,                      /* segment descriptor present */
1079         0, 0,
1080         0,                      /* default 32 vs 16 bit size */
1081         0                       /* limit granularity (byte/page units)*/ },
1082         /* Data Descriptor for user */
1083 {       0x0,                    /* segment base address  */
1084         0xfffff,                /* length - all address space */
1085         SDT_MEMRWA,             /* segment type */
1086         SEL_UPL,                /* segment descriptor priority level */
1087         1,                      /* segment descriptor present */
1088         0, 0,
1089         1,                      /* default 32 vs 16 bit size */
1090         1                       /* limit granularity (byte/page units)*/ },
1091 };
1092
1093 void
1094 setidt(idx, func, typ, dpl, selec)
1095         int idx;
1096         inthand_t *func;
1097         int typ;
1098         int dpl;
1099         int selec;
1100 {
1101         struct gate_descriptor *ip;
1102
1103 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
1104         ip = (t_idt != NULL ? t_idt : idt) + idx;
1105 #else
1106         ip = idt + idx;
1107 #endif
1108         ip->gd_looffset = (int)func;
1109         ip->gd_selector = selec;
1110         ip->gd_stkcpy = 0;
1111         ip->gd_xx = 0;
1112         ip->gd_type = typ;
1113         ip->gd_dpl = dpl;
1114         ip->gd_p = 1;
1115         ip->gd_hioffset = ((int)func)>>16 ;
1116 }
1117
1118 #define IDTVEC(name)    __CONCAT(X,name)
1119
1120 extern inthand_t
1121         IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
1122         IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
1123         IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
1124         IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
1125         IDTVEC(syscall), IDTVEC(int0x80_syscall);
1126
1127 void
1128 sdtossd(sd, ssd)
1129         struct segment_descriptor *sd;
1130         struct soft_segment_descriptor *ssd;
1131 {
1132         ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
1133         ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
1134         ssd->ssd_type  = sd->sd_type;
1135         ssd->ssd_dpl   = sd->sd_dpl;
1136         ssd->ssd_p     = sd->sd_p;
1137         ssd->ssd_def32 = sd->sd_def32;
1138         ssd->ssd_gran  = sd->sd_gran;
1139 }
1140
1141 void
1142 init386(first)
1143         int first;
1144 {
1145         int x;
1146         unsigned biosbasemem, biosextmem;
1147         struct gate_descriptor *gdp;
1148         int gsel_tss;
1149 #if NNPX > 0
1150         int msize;
1151 #endif
1152
1153 #ifndef SMP
1154         /* table descriptors - used to load tables by microp */
1155         struct region_descriptor r_gdt, r_idt;
1156 #endif
1157         int pagesinbase, pagesinext;
1158         vm_offset_t target_page;
1159         int pa_indx, off;
1160         int speculative_mprobe;
1161
1162         /*
1163          * Prevent lowering of the ipl if we call tsleep() early.
1164          */
1165         safepri = cpl;
1166
1167         proc0.p_addr = proc0paddr;
1168
1169         atdevbase = ISA_HOLE_START + KERNBASE;
1170
1171         /*
1172          * make gdt memory segments, the code segment goes up to end of the
1173          * page with etext in it, the data segment goes to the end of
1174          * the address space
1175          */
1176         /*
1177          * XXX text protection is temporarily (?) disabled.  The limit was
1178          * i386_btop(round_page(etext)) - 1.
1179          */
1180         gdt_segs[GCODE_SEL].ssd_limit = i386_btop(0) - 1;
1181         gdt_segs[GDATA_SEL].ssd_limit = i386_btop(0) - 1;
1182 #ifdef SMP
1183         gdt_segs[GPRIV_SEL].ssd_limit =
1184                 i386_btop(sizeof(struct privatespace)) - 1;
1185         gdt_segs[GPRIV_SEL].ssd_base = (int) &SMP_prvspace[0];
1186         gdt_segs[GPROC0_SEL].ssd_base =
1187                 (int) &SMP_prvspace[0].globaldata.gd_common_tss;
1188         SMP_prvspace[0].globaldata.gd_prvspace = &SMP_prvspace[0];
1189 #else
1190         gdt_segs[GPRIV_SEL].ssd_limit = i386_btop(0) - 1;
1191         gdt_segs[GPROC0_SEL].ssd_base = (int) &common_tss;
1192 #endif
1193
1194         for (x = 0; x < NGDT; x++) {
1195 #ifdef BDE_DEBUGGER
1196                 /* avoid overwriting db entries with APM ones */
1197                 if (x >= GAPMCODE32_SEL && x <= GAPMDATA_SEL)
1198                         continue;
1199 #endif
1200                 ssdtosd(&gdt_segs[x], &gdt[x].sd);
1201         }
1202
1203         r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
1204         r_gdt.rd_base =  (int) gdt;
1205         lgdt(&r_gdt);
1206
1207         /* make ldt memory segments */
1208         /*
1209          * The data segment limit must not cover the user area because we
1210          * don't want the user area to be writable in copyout() etc. (page
1211          * level protection is lost in kernel mode on 386's).  Also, we
1212          * don't want the user area to be writable directly (page level
1213          * protection of the user area is not available on 486's with
1214          * CR0_WP set, because there is no user-read/kernel-write mode).
1215          *
1216          * XXX - VM_MAXUSER_ADDRESS is an end address, not a max.  And it
1217          * should be spelled ...MAX_USER...
1218          */
1219 #define VM_END_USER_RW_ADDRESS  VM_MAXUSER_ADDRESS
1220         /*
1221          * The code segment limit has to cover the user area until we move
1222          * the signal trampoline out of the user area.  This is safe because
1223          * the code segment cannot be written to directly.
1224          */
1225 #define VM_END_USER_R_ADDRESS   (VM_END_USER_RW_ADDRESS + UPAGES * PAGE_SIZE)
1226         ldt_segs[LUCODE_SEL].ssd_limit = i386_btop(VM_END_USER_R_ADDRESS) - 1;
1227         ldt_segs[LUDATA_SEL].ssd_limit = i386_btop(VM_END_USER_RW_ADDRESS) - 1;
1228         for (x = 0; x < sizeof ldt_segs / sizeof ldt_segs[0]; x++)
1229                 ssdtosd(&ldt_segs[x], &ldt[x].sd);
1230
1231         _default_ldt = GSEL(GLDT_SEL, SEL_KPL);
1232         lldt(_default_ldt);
1233 #ifdef USER_LDT
1234         currentldt = _default_ldt;
1235 #endif
1236
1237         /* exceptions */
1238         for (x = 0; x < NIDT; x++)
1239                 setidt(x, &IDTVEC(rsvd), SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1240         setidt(0, &IDTVEC(div),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1241         setidt(1, &IDTVEC(dbg),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1242         setidt(2, &IDTVEC(nmi),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1243         setidt(3, &IDTVEC(bpt),  SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1244         setidt(4, &IDTVEC(ofl),  SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1245         setidt(5, &IDTVEC(bnd),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1246         setidt(6, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1247         setidt(7, &IDTVEC(dna),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1248         setidt(8, 0,  SDT_SYSTASKGT, SEL_KPL, GSEL(GPANIC_SEL, SEL_KPL));
1249         setidt(9, &IDTVEC(fpusegm),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1250         setidt(10, &IDTVEC(tss),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1251         setidt(11, &IDTVEC(missing),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1252         setidt(12, &IDTVEC(stk),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1253         setidt(13, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1254         setidt(14, &IDTVEC(page),  SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1255         setidt(15, &IDTVEC(rsvd),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1256         setidt(16, &IDTVEC(fpu),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1257         setidt(17, &IDTVEC(align), SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1258         setidt(18, &IDTVEC(mchk),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1259         setidt(0x80, &IDTVEC(int0x80_syscall),
1260                         SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1261
1262         r_idt.rd_limit = sizeof(idt) - 1;
1263         r_idt.rd_base = (int) idt;
1264         lidt(&r_idt);
1265
1266         /*
1267          * Initialize the console before we print anything out.
1268          */
1269         cninit();
1270
1271 #include        "isa.h"
1272 #if     NISA >0
1273         isa_defaultirq();
1274 #endif
1275         rand_initialize();
1276
1277 #ifdef DDB
1278         kdb_init();
1279         if (boothowto & RB_KDB)
1280                 Debugger("Boot flags requested debugger");
1281 #endif
1282
1283         finishidentcpu();       /* Final stage of CPU initialization */
1284         setidt(6, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1285         setidt(13, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1286         initializecpu();        /* Initialize CPU registers */
1287
1288         /* make an initial tss so cpu can get interrupt stack on syscall! */
1289 #ifdef VM86
1290         common_tss.tss_esp0 = (int) proc0.p_addr + UPAGES*PAGE_SIZE - 16;
1291 #else
1292         common_tss.tss_esp0 = (int) proc0.p_addr + UPAGES*PAGE_SIZE;
1293 #endif /* VM86 */
1294         common_tss.tss_ss0 = GSEL(GDATA_SEL, SEL_KPL) ;
1295         common_tss.tss_ioopt = (sizeof common_tss) << 16;
1296         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
1297         ltr(gsel_tss);
1298 #ifdef VM86
1299         private_tss = 0;
1300         tss_gdt = &gdt[GPROC0_SEL].sd;
1301         common_tssd = *tss_gdt;
1302 #endif
1303
1304         dblfault_tss.tss_esp = dblfault_tss.tss_esp0 = dblfault_tss.tss_esp1 =
1305             dblfault_tss.tss_esp2 = (int) &dblfault_stack[sizeof(dblfault_stack)];
1306         dblfault_tss.tss_ss = dblfault_tss.tss_ss0 = dblfault_tss.tss_ss1 =
1307             dblfault_tss.tss_ss2 = GSEL(GDATA_SEL, SEL_KPL);
1308         dblfault_tss.tss_cr3 = (int)IdlePTD;
1309         dblfault_tss.tss_eip = (int) dblfault_handler;
1310         dblfault_tss.tss_eflags = PSL_KERNEL;
1311         dblfault_tss.tss_ds = dblfault_tss.tss_es =
1312             dblfault_tss.tss_gs = GSEL(GDATA_SEL, SEL_KPL);
1313         dblfault_tss.tss_fs = GSEL(GPRIV_SEL, SEL_KPL);
1314         dblfault_tss.tss_cs = GSEL(GCODE_SEL, SEL_KPL);
1315         dblfault_tss.tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
1316
1317 #ifdef VM86
1318         initial_bioscalls(&biosbasemem, &biosextmem);
1319 #else
1320
1321         /* Use BIOS values stored in RTC CMOS RAM, since probing
1322          * breaks certain 386 AT relics.
1323          */
1324         biosbasemem = rtcin(RTC_BASELO)+ (rtcin(RTC_BASEHI)<<8);
1325         biosextmem = rtcin(RTC_EXTLO)+ (rtcin(RTC_EXTHI)<<8);
1326 #endif
1327
1328         /*
1329          * If BIOS tells us that it has more than 640k in the basemem,
1330          *      don't believe it - set it to 640k.
1331          */
1332         if (biosbasemem > 640) {
1333                 printf("Preposterous RTC basemem of %uK, truncating to 640K\n",
1334                        biosbasemem);
1335                 biosbasemem = 640;
1336         }
1337         if (bootinfo.bi_memsizes_valid && bootinfo.bi_basemem > 640) {
1338                 printf("Preposterous BIOS basemem of %uK, truncating to 640K\n",
1339                        bootinfo.bi_basemem);
1340                 bootinfo.bi_basemem = 640;
1341         }
1342
1343         /*
1344          * Warn if the official BIOS interface disagrees with the RTC
1345          * interface used above about the amount of base memory or the
1346          * amount of extended memory.  Prefer the BIOS value for the base
1347          * memory.  This is necessary for machines that `steal' base
1348          * memory for use as BIOS memory, at least if we are going to use
1349          * the BIOS for apm.  Prefer the RTC value for extended memory.
1350          * Eventually the hackish interface shouldn't even be looked at.
1351          */
1352         if (bootinfo.bi_memsizes_valid) {
1353                 if (bootinfo.bi_basemem != biosbasemem) {
1354                         vm_offset_t pa;
1355
1356                         printf(
1357         "BIOS basemem (%uK) != RTC basemem (%uK), setting to BIOS value\n",
1358                                bootinfo.bi_basemem, biosbasemem);
1359                         biosbasemem = bootinfo.bi_basemem;
1360
1361                         /*
1362                          * XXX if biosbasemem is now < 640, there is `hole'
1363                          * between the end of base memory and the start of
1364                          * ISA memory.  The hole may be empty or it may
1365                          * contain BIOS code or data.  Map it read/write so
1366                          * that the BIOS can write to it.  (Memory from 0 to
1367                          * the physical end of the kernel is mapped read-only
1368                          * to begin with and then parts of it are remapped.
1369                          * The parts that aren't remapped form holes that
1370                          * remain read-only and are unused by the kernel.
1371                          * The base memory area is below the physical end of
1372                          * the kernel and right now forms a read-only hole.
1373                          * The part of it from PAGE_SIZE to
1374                          * (trunc_page(biosbasemem * 1024) - 1) will be
1375                          * remapped and used by the kernel later.)
1376                          *
1377                          * This code is similar to the code used in
1378                          * pmap_mapdev, but since no memory needs to be
1379                          * allocated we simply change the mapping.
1380                          */
1381                         for (pa = trunc_page(biosbasemem * 1024);
1382                              pa < ISA_HOLE_START; pa += PAGE_SIZE) {
1383                                 unsigned *pte;
1384
1385                                 pte = (unsigned *)vtopte(pa + KERNBASE);
1386                                 *pte = pa | PG_RW | PG_V;
1387                         }
1388                 }
1389                 if (bootinfo.bi_extmem != biosextmem)
1390                         printf("BIOS extmem (%uK) != RTC extmem (%uK)\n",
1391                                bootinfo.bi_extmem, biosextmem);
1392         }
1393
1394 #ifdef SMP
1395         /* make hole for AP bootstrap code */
1396         pagesinbase = mp_bootaddress(biosbasemem) / PAGE_SIZE;
1397 #else
1398         pagesinbase = biosbasemem * 1024 / PAGE_SIZE;
1399 #endif
1400
1401         pagesinext = biosextmem * 1024 / PAGE_SIZE;
1402
1403         /*
1404          * Special hack for chipsets that still remap the 384k hole when
1405          *      there's 16MB of memory - this really confuses people that
1406          *      are trying to use bus mastering ISA controllers with the
1407          *      "16MB limit"; they only have 16MB, but the remapping puts
1408          *      them beyond the limit.
1409          */
1410         /*
1411          * If extended memory is between 15-16MB (16-17MB phys address range),
1412          *      chop it to 15MB.
1413          */
1414         if ((pagesinext > 3840) && (pagesinext < 4096))
1415                 pagesinext = 3840;
1416
1417         /*
1418          * Maxmem isn't the "maximum memory", it's one larger than the
1419          * highest page of the physical address space.  It should be
1420          * called something like "Maxphyspage".
1421          */
1422         Maxmem = pagesinext + 0x100000/PAGE_SIZE;
1423         /*
1424          * Indicate that we wish to do a speculative search for memory beyond
1425          * the end of the reported size if the indicated amount is 64MB (0x4000
1426          * pages) - which is the largest amount that the BIOS/bootblocks can
1427          * currently report. If a specific amount of memory is indicated via
1428          * the MAXMEM option or the npx0 "msize", then don't do the speculative
1429          * memory probe.
1430          */
1431         if (Maxmem >= 0x4000)
1432                 speculative_mprobe = TRUE;
1433         else
1434                 speculative_mprobe = FALSE;
1435
1436 #ifdef MAXMEM
1437         Maxmem = MAXMEM/4;
1438         speculative_mprobe = FALSE;
1439 #endif
1440
1441 #if NNPX > 0
1442         if (resource_int_value("npx", 0, "msize", &msize) == 0) {
1443                 if (msize != 0) {
1444                         Maxmem = msize / 4;
1445                         speculative_mprobe = FALSE;
1446                 }
1447         }
1448 #endif
1449
1450 #ifdef SMP
1451         /* look for the MP hardware - needed for apic addresses */
1452         mp_probe();
1453 #endif
1454
1455         /* call pmap initialization to make new kernel address space */
1456         pmap_bootstrap (first, 0);
1457
1458         /*
1459          * Size up each available chunk of physical memory.
1460          */
1461
1462         /*
1463          * We currently don't bother testing base memory.
1464          * XXX  ...but we probably should.
1465          */
1466         pa_indx = 0;
1467         if (pagesinbase > 1) {
1468                 phys_avail[pa_indx++] = PAGE_SIZE;      /* skip first page of memory */
1469                 phys_avail[pa_indx] = ptoa(pagesinbase);/* memory up to the ISA hole */
1470                 physmem = pagesinbase - 1;
1471         } else {
1472                 /* point at first chunk end */
1473                 pa_indx++;
1474         }
1475
1476         for (target_page = avail_start; target_page < ptoa(Maxmem); target_page += PAGE_SIZE) {
1477                 int tmp, page_bad;
1478
1479                 page_bad = FALSE;
1480
1481                 /*
1482                  * map page into kernel: valid, read/write, non-cacheable
1483                  */
1484                 *(int *)CMAP1 = PG_V | PG_RW | PG_N | target_page;
1485                 invltlb();
1486
1487                 tmp = *(int *)CADDR1;
1488                 /*
1489                  * Test for alternating 1's and 0's
1490                  */
1491                 *(volatile int *)CADDR1 = 0xaaaaaaaa;
1492                 if (*(volatile int *)CADDR1 != 0xaaaaaaaa) {
1493                         page_bad = TRUE;
1494                 }
1495                 /*
1496                  * Test for alternating 0's and 1's
1497                  */
1498                 *(volatile int *)CADDR1 = 0x55555555;
1499                 if (*(volatile int *)CADDR1 != 0x55555555) {
1500                         page_bad = TRUE;
1501                 }
1502                 /*
1503                  * Test for all 1's
1504                  */
1505                 *(volatile int *)CADDR1 = 0xffffffff;
1506                 if (*(volatile int *)CADDR1 != 0xffffffff) {
1507                         page_bad = TRUE;
1508                 }
1509                 /*
1510                  * Test for all 0's
1511                  */
1512                 *(volatile int *)CADDR1 = 0x0;
1513                 if (*(volatile int *)CADDR1 != 0x0) {
1514                         /*
1515                          * test of page failed
1516                          */
1517                         page_bad = TRUE;
1518                 }
1519                 /*
1520                  * Restore original value.
1521                  */
1522                 *(int *)CADDR1 = tmp;
1523
1524                 /*
1525                  * Adjust array of valid/good pages.
1526                  */
1527                 if (page_bad == FALSE) {
1528                         /*
1529                          * If this good page is a continuation of the
1530                          * previous set of good pages, then just increase
1531                          * the end pointer. Otherwise start a new chunk.
1532                          * Note that "end" points one higher than end,
1533                          * making the range >= start and < end.
1534                          * If we're also doing a speculative memory
1535                          * test and we at or past the end, bump up Maxmem
1536                          * so that we keep going. The first bad page
1537                          * will terminate the loop.
1538                          */
1539                         if (phys_avail[pa_indx] == target_page) {
1540                                 phys_avail[pa_indx] += PAGE_SIZE;
1541                                 if (speculative_mprobe == TRUE &&
1542                                     phys_avail[pa_indx] >= (64*1024*1024))
1543                                         Maxmem++;
1544                         } else {
1545                                 pa_indx++;
1546                                 if (pa_indx == PHYS_AVAIL_ARRAY_END) {
1547                                         printf("Too many holes in the physical address space, giving up\n");
1548                                         pa_indx--;
1549                                         break;
1550                                 }
1551                                 phys_avail[pa_indx++] = target_page;    /* start */
1552                                 phys_avail[pa_indx] = target_page + PAGE_SIZE;  /* end */
1553                         }
1554                         physmem++;
1555                 }
1556         }
1557
1558         *(int *)CMAP1 = 0;
1559         invltlb();
1560
1561         /*
1562          * XXX
1563          * The last chunk must contain at least one page plus the message
1564          * buffer to avoid complicating other code (message buffer address
1565          * calculation, etc.).
1566          */
1567         while (phys_avail[pa_indx - 1] + PAGE_SIZE +
1568             round_page(MSGBUF_SIZE) >= phys_avail[pa_indx]) {
1569                 physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
1570                 phys_avail[pa_indx--] = 0;
1571                 phys_avail[pa_indx--] = 0;
1572         }
1573
1574         Maxmem = atop(phys_avail[pa_indx]);
1575
1576         /* Trim off space for the message buffer. */
1577         phys_avail[pa_indx] -= round_page(MSGBUF_SIZE);
1578
1579         avail_end = phys_avail[pa_indx];
1580
1581         /* now running on new page tables, configured,and u/iom is accessible */
1582
1583         /* Map the message buffer. */
1584         for (off = 0; off < round_page(MSGBUF_SIZE); off += PAGE_SIZE)
1585                 pmap_enter(kernel_pmap, (vm_offset_t)msgbufp + off,
1586                            avail_end + off, VM_PROT_ALL, TRUE);
1587
1588         msgbufinit(msgbufp, MSGBUF_SIZE);
1589
1590         /* make a call gate to reenter kernel with */
1591         gdp = &ldt[LSYS5CALLS_SEL].gd;
1592
1593         x = (int) &IDTVEC(syscall);
1594         gdp->gd_looffset = x++;
1595         gdp->gd_selector = GSEL(GCODE_SEL,SEL_KPL);
1596         gdp->gd_stkcpy = 1;
1597         gdp->gd_type = SDT_SYS386CGT;
1598         gdp->gd_dpl = SEL_UPL;
1599         gdp->gd_p = 1;
1600         gdp->gd_hioffset = ((int) &IDTVEC(syscall)) >>16;
1601
1602         /* XXX does this work? */
1603         ldt[LBSDICALLS_SEL] = ldt[LSYS5CALLS_SEL];
1604         ldt[LSOL26CALLS_SEL] = ldt[LSYS5CALLS_SEL];
1605
1606         /* transfer to user mode */
1607
1608         _ucodesel = LSEL(LUCODE_SEL, SEL_UPL);
1609         _udatasel = LSEL(LUDATA_SEL, SEL_UPL);
1610
1611         /* setup proc 0's pcb */
1612         proc0.p_addr->u_pcb.pcb_flags = 0;
1613         proc0.p_addr->u_pcb.pcb_cr3 = (int)IdlePTD;
1614 #ifdef SMP
1615         proc0.p_addr->u_pcb.pcb_mpnest = 1;
1616 #endif
1617 #ifdef VM86
1618         proc0.p_addr->u_pcb.pcb_ext = 0;
1619 #endif
1620
1621         /* Sigh, relocate physical addresses left from bootstrap */
1622         if (bootinfo.bi_modulep) {
1623                 preload_metadata = (caddr_t)bootinfo.bi_modulep + KERNBASE;
1624                 preload_bootstrap_relocate(KERNBASE);
1625         }
1626         if (bootinfo.bi_envp)
1627                 kern_envp = (caddr_t)bootinfo.bi_envp + KERNBASE;
1628 }
1629
1630 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
1631 static void f00f_hack(void *unused);
1632 SYSINIT(f00f_hack, SI_SUB_INTRINSIC, SI_ORDER_FIRST, f00f_hack, NULL);
1633
1634 static void
1635 f00f_hack(void *unused) {
1636 #ifndef SMP
1637         struct region_descriptor r_idt;
1638 #endif
1639         vm_offset_t tmp;
1640
1641         if (!has_f00f_bug)
1642                 return;
1643
1644         printf("Intel Pentium detected, installing workaround for F00F bug\n");
1645
1646         r_idt.rd_limit = sizeof(idt) - 1;
1647
1648         tmp = kmem_alloc(kernel_map, PAGE_SIZE * 2);
1649         if (tmp == 0)
1650                 panic("kmem_alloc returned 0");
1651         if (((unsigned int)tmp & (PAGE_SIZE-1)) != 0)
1652                 panic("kmem_alloc returned non-page-aligned memory");
1653         /* Put the first seven entries in the lower page */
1654         t_idt = (struct gate_descriptor*)(tmp + PAGE_SIZE - (7*8));
1655         bcopy(idt, t_idt, sizeof(idt));
1656         r_idt.rd_base = (int)t_idt;
1657         lidt(&r_idt);
1658         if (vm_map_protect(kernel_map, tmp, tmp + PAGE_SIZE,
1659                            VM_PROT_READ, FALSE) != KERN_SUCCESS)
1660                 panic("vm_map_protect failed");
1661         return;
1662 }
1663 #endif /* defined(I586_CPU) && !NO_F00F_HACK */
1664
1665 int
1666 ptrace_set_pc(p, addr)
1667         struct proc *p;
1668         unsigned long addr;
1669 {
1670         p->p_md.md_regs->tf_eip = addr;
1671         return (0);
1672 }
1673
1674 int
1675 ptrace_single_step(p)
1676         struct proc *p;
1677 {
1678         p->p_md.md_regs->tf_eflags |= PSL_T;
1679         return (0);
1680 }
1681
1682 int ptrace_read_u_check(p, addr, len)
1683         struct proc *p;
1684         vm_offset_t addr;
1685         size_t len;
1686 {
1687         vm_offset_t gap;
1688
1689         if ((vm_offset_t) (addr + len) < addr)
1690                 return EPERM;
1691         if ((vm_offset_t) (addr + len) <= sizeof(struct user))
1692                 return 0;
1693
1694         gap = (char *) p->p_md.md_regs - (char *) p->p_addr;
1695         
1696         if ((vm_offset_t) addr < gap)
1697                 return EPERM;
1698         if ((vm_offset_t) (addr + len) <= 
1699             (vm_offset_t) (gap + sizeof(struct trapframe)))
1700                 return 0;
1701         return EPERM;
1702 }
1703
1704 int ptrace_write_u(p, off, data)
1705         struct proc *p;
1706         vm_offset_t off;
1707         long data;
1708 {
1709         struct trapframe frame_copy;
1710         vm_offset_t min;
1711         struct trapframe *tp;
1712
1713         /*
1714          * Privileged kernel state is scattered all over the user area.
1715          * Only allow write access to parts of regs and to fpregs.
1716          */
1717         min = (char *)p->p_md.md_regs - (char *)p->p_addr;
1718         if (off >= min && off <= min + sizeof(struct trapframe) - sizeof(int)) {
1719                 tp = p->p_md.md_regs;
1720                 frame_copy = *tp;
1721                 *(int *)((char *)&frame_copy + (off - min)) = data;
1722                 if (!EFLAGS_SECURE(frame_copy.tf_eflags, tp->tf_eflags) ||
1723                     !CS_SECURE(frame_copy.tf_cs))
1724                         return (EINVAL);
1725                 *(int*)((char *)p->p_addr + off) = data;
1726                 return (0);
1727         }
1728         min = offsetof(struct user, u_pcb) + offsetof(struct pcb, pcb_savefpu);
1729         if (off >= min && off <= min + sizeof(struct save87) - sizeof(int)) {
1730                 *(int*)((char *)p->p_addr + off) = data;
1731                 return (0);
1732         }
1733         return (EFAULT);
1734 }
1735
1736 int
1737 fill_regs(p, regs)
1738         struct proc *p;
1739         struct reg *regs;
1740 {
1741         struct pcb *pcb;
1742         struct trapframe *tp;
1743
1744         tp = p->p_md.md_regs;
1745         regs->r_fs = tp->tf_fs;
1746         regs->r_es = tp->tf_es;
1747         regs->r_ds = tp->tf_ds;
1748         regs->r_edi = tp->tf_edi;
1749         regs->r_esi = tp->tf_esi;
1750         regs->r_ebp = tp->tf_ebp;
1751         regs->r_ebx = tp->tf_ebx;
1752         regs->r_edx = tp->tf_edx;
1753         regs->r_ecx = tp->tf_ecx;
1754         regs->r_eax = tp->tf_eax;
1755         regs->r_eip = tp->tf_eip;
1756         regs->r_cs = tp->tf_cs;
1757         regs->r_eflags = tp->tf_eflags;
1758         regs->r_esp = tp->tf_esp;
1759         regs->r_ss = tp->tf_ss;
1760         pcb = &p->p_addr->u_pcb;
1761         regs->r_gs = pcb->pcb_gs;
1762         return (0);
1763 }
1764
1765 int
1766 set_regs(p, regs)
1767         struct proc *p;
1768         struct reg *regs;
1769 {
1770         struct pcb *pcb;
1771         struct trapframe *tp;
1772
1773         tp = p->p_md.md_regs;
1774         if (!EFLAGS_SECURE(regs->r_eflags, tp->tf_eflags) ||
1775             !CS_SECURE(regs->r_cs))
1776                 return (EINVAL);
1777         tp->tf_fs = regs->r_fs;
1778         tp->tf_es = regs->r_es;
1779         tp->tf_ds = regs->r_ds;
1780         tp->tf_edi = regs->r_edi;
1781         tp->tf_esi = regs->r_esi;
1782         tp->tf_ebp = regs->r_ebp;
1783         tp->tf_ebx = regs->r_ebx;
1784         tp->tf_edx = regs->r_edx;
1785         tp->tf_ecx = regs->r_ecx;
1786         tp->tf_eax = regs->r_eax;
1787         tp->tf_eip = regs->r_eip;
1788         tp->tf_cs = regs->r_cs;
1789         tp->tf_eflags = regs->r_eflags;
1790         tp->tf_esp = regs->r_esp;
1791         tp->tf_ss = regs->r_ss;
1792         pcb = &p->p_addr->u_pcb;
1793         pcb->pcb_gs = regs->r_gs;
1794         return (0);
1795 }
1796
1797 int
1798 fill_fpregs(p, fpregs)
1799         struct proc *p;
1800         struct fpreg *fpregs;
1801 {
1802         bcopy(&p->p_addr->u_pcb.pcb_savefpu, fpregs, sizeof *fpregs);
1803         return (0);
1804 }
1805
1806 int
1807 set_fpregs(p, fpregs)
1808         struct proc *p;
1809         struct fpreg *fpregs;
1810 {
1811         bcopy(fpregs, &p->p_addr->u_pcb.pcb_savefpu, sizeof *fpregs);
1812         return (0);
1813 }
1814
1815 #ifndef DDB
1816 void
1817 Debugger(const char *msg)
1818 {
1819         printf("Debugger(\"%s\") called.\n", msg);
1820 }
1821 #endif /* no DDB */
1822
1823 #include <sys/disklabel.h>
1824
1825 /*
1826  * Determine the size of the transfer, and make sure it is
1827  * within the boundaries of the partition. Adjust transfer
1828  * if needed, and signal errors or early completion.
1829  */
1830 int
1831 bounds_check_with_label(struct buf *bp, struct disklabel *lp, int wlabel)
1832 {
1833         struct partition *p = lp->d_partitions + dkpart(bp->b_dev);
1834         int labelsect = lp->d_partitions[0].p_offset;
1835         int maxsz = p->p_size,
1836                 sz = (bp->b_bcount + DEV_BSIZE - 1) >> DEV_BSHIFT;
1837
1838         /* overwriting disk label ? */
1839         /* XXX should also protect bootstrap in first 8K */
1840         if (bp->b_blkno + p->p_offset <= LABELSECTOR + labelsect &&
1841 #if LABELSECTOR != 0
1842             bp->b_blkno + p->p_offset + sz > LABELSECTOR + labelsect &&
1843 #endif
1844             (bp->b_flags & B_READ) == 0 && wlabel == 0) {
1845                 bp->b_error = EROFS;
1846                 goto bad;
1847         }
1848
1849 #if     defined(DOSBBSECTOR) && defined(notyet)
1850         /* overwriting master boot record? */
1851         if (bp->b_blkno + p->p_offset <= DOSBBSECTOR &&
1852             (bp->b_flags & B_READ) == 0 && wlabel == 0) {
1853                 bp->b_error = EROFS;
1854                 goto bad;
1855         }
1856 #endif
1857
1858         /* beyond partition? */
1859         if (bp->b_blkno < 0 || bp->b_blkno + sz > maxsz) {
1860                 /* if exactly at end of disk, return an EOF */
1861                 if (bp->b_blkno == maxsz) {
1862                         bp->b_resid = bp->b_bcount;
1863                         return(0);
1864                 }
1865                 /* or truncate if part of it fits */
1866                 sz = maxsz - bp->b_blkno;
1867                 if (sz <= 0) {
1868                         bp->b_error = EINVAL;
1869                         goto bad;
1870                 }
1871                 bp->b_bcount = sz << DEV_BSHIFT;
1872         }
1873
1874         bp->b_pblkno = bp->b_blkno + p->p_offset;
1875         return(1);
1876
1877 bad:
1878         bp->b_flags |= B_ERROR;
1879         return(-1);
1880 }
1881
1882 #ifdef DDB
1883
1884 /*
1885  * Provide inb() and outb() as functions.  They are normally only
1886  * available as macros calling inlined functions, thus cannot be
1887  * called inside DDB.
1888  *
1889  * The actual code is stolen from <machine/cpufunc.h>, and de-inlined.
1890  */
1891
1892 #undef inb
1893 #undef outb
1894
1895 /* silence compiler warnings */
1896 u_char inb(u_int);
1897 void outb(u_int, u_char);
1898
1899 u_char
1900 inb(u_int port)
1901 {
1902         u_char  data;
1903         /*
1904          * We use %%dx and not %1 here because i/o is done at %dx and not at
1905          * %edx, while gcc generates inferior code (movw instead of movl)
1906          * if we tell it to load (u_short) port.
1907          */
1908         __asm __volatile("inb %%dx,%0" : "=a" (data) : "d" (port));
1909         return (data);
1910 }
1911
1912 void
1913 outb(u_int port, u_char data)
1914 {
1915         u_char  al;
1916         /*
1917          * Use an unnecessary assignment to help gcc's register allocator.
1918          * This make a large difference for gcc-1.40 and a tiny difference
1919          * for gcc-2.6.0.  For gcc-1.40, al had to be ``asm("ax")'' for
1920          * best results.  gcc-2.6.0 can't handle this.
1921          */
1922         al = data;
1923         __asm __volatile("outb %0,%%dx" : : "a" (al), "d" (port));
1924 }
1925
1926 #endif /* DDB */