Merge branch 'vendor/OPENSSH'
[dragonfly.git] / sys / platform / vkernel / i386 / cpu_regs.c
1 /*-
2  * Copyright (c) 1992 Terrence R. Lambert.
3  * Copyright (C) 1994, David Greenman
4  * Copyright (c) 1982, 1987, 1990, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * William Jolitz.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      from: @(#)machdep.c     7.4 (Berkeley) 6/3/91
39  * $FreeBSD: src/sys/i386/i386/machdep.c,v 1.385.2.30 2003/05/31 08:48:05 alc Exp $
40  */
41
42 #include "use_npx.h"
43 #include "opt_compat.h"
44 #include "opt_ddb.h"
45 #include "opt_directio.h"
46 #include "opt_inet.h"
47 #include "opt_ipx.h"
48 #include "opt_msgbuf.h"
49 #include "opt_swap.h"
50
51 #include <sys/param.h>
52 #include <sys/systm.h>
53 #include <sys/sysproto.h>
54 #include <sys/signalvar.h>
55 #include <sys/kernel.h>
56 #include <sys/linker.h>
57 #include <sys/malloc.h>
58 #include <sys/proc.h>
59 #include <sys/buf.h>
60 #include <sys/reboot.h>
61 #include <sys/mbuf.h>
62 #include <sys/msgbuf.h>
63 #include <sys/sysent.h>
64 #include <sys/sysctl.h>
65 #include <sys/vmmeter.h>
66 #include <sys/bus.h>
67 #include <sys/upcall.h>
68 #include <sys/usched.h>
69 #include <sys/reg.h>
70
71 #include <vm/vm.h>
72 #include <vm/vm_param.h>
73 #include <sys/lock.h>
74 #include <vm/vm_kern.h>
75 #include <vm/vm_object.h>
76 #include <vm/vm_page.h>
77 #include <vm/vm_map.h>
78 #include <vm/vm_pager.h>
79 #include <vm/vm_extern.h>
80
81 #include <sys/thread2.h>
82 #include <sys/mplock2.h>
83
84 #include <sys/user.h>
85 #include <sys/exec.h>
86 #include <sys/cons.h>
87
88 #include <ddb/ddb.h>
89
90 #include <machine/cpu.h>
91 #include <machine/clock.h>
92 #include <machine/specialreg.h>
93 #include <machine/md_var.h>
94 #include <machine/pcb_ext.h>            /* pcb.h included via sys/user.h */
95 #include <machine/globaldata.h>         /* CPU_prvspace */
96 #include <machine/smp.h>
97 #ifdef PERFMON
98 #include <machine/perfmon.h>
99 #endif
100 #include <machine/cputypes.h>
101
102 #include <bus/isa/rtc.h>
103 #include <machine/vm86.h>
104 #include <sys/random.h>
105 #include <sys/ptrace.h>
106 #include <machine/sigframe.h>
107 #include <unistd.h>             /* umtx_* functions */
108 #include <pthread.h>            /* pthread_yield */
109
110 extern void dblfault_handler (void);
111
112 #ifndef CPU_DISABLE_SSE
113 static void set_fpregs_xmm (struct save87 *, struct savexmm *);
114 static void fill_fpregs_xmm (struct savexmm *, struct save87 *);
115 #endif /* CPU_DISABLE_SSE */
116 #ifdef DIRECTIO
117 extern void ffs_rawread_setup(void);
118 #endif /* DIRECTIO */
119
120 int64_t tsc_offsets[MAXCPU];
121
122 #if defined(SWTCH_OPTIM_STATS)
123 extern int swtch_optim_stats;
124 SYSCTL_INT(_debug, OID_AUTO, swtch_optim_stats,
125         CTLFLAG_RD, &swtch_optim_stats, 0, "");
126 SYSCTL_INT(_debug, OID_AUTO, tlb_flush_count,
127         CTLFLAG_RD, &tlb_flush_count, 0, "");
128 #endif
129
130 static int
131 sysctl_hw_physmem(SYSCTL_HANDLER_ARGS)
132 {
133         u_long pmem = ctob(physmem);
134
135         int error = sysctl_handle_long(oidp, &pmem, 0, req);
136         return (error);
137 }
138
139 SYSCTL_PROC(_hw, HW_PHYSMEM, physmem, CTLTYPE_ULONG|CTLFLAG_RD,
140         0, 0, sysctl_hw_physmem, "LU", "Total system memory in bytes (number of pages * page size)");
141
142 static int
143 sysctl_hw_usermem(SYSCTL_HANDLER_ARGS)
144 {
145         int error = sysctl_handle_int(oidp, 0,
146                 ctob((int)Maxmem - vmstats.v_wire_count), req);
147         return (error);
148 }
149
150 SYSCTL_PROC(_hw, HW_USERMEM, usermem, CTLTYPE_INT|CTLFLAG_RD,
151         0, 0, sysctl_hw_usermem, "IU", "");
152
153 SYSCTL_ULONG(_hw, OID_AUTO, availpages, CTLFLAG_RD, &Maxmem, 0, "");
154
155 #if 0
156
157 static int
158 sysctl_machdep_msgbuf(SYSCTL_HANDLER_ARGS)
159 {
160         int error;
161
162         /* Unwind the buffer, so that it's linear (possibly starting with
163          * some initial nulls).
164          */
165         error=sysctl_handle_opaque(oidp,msgbufp->msg_ptr+msgbufp->msg_bufr,
166                 msgbufp->msg_size-msgbufp->msg_bufr,req);
167         if(error) return(error);
168         if(msgbufp->msg_bufr>0) {
169                 error=sysctl_handle_opaque(oidp,msgbufp->msg_ptr,
170                         msgbufp->msg_bufr,req);
171         }
172         return(error);
173 }
174
175 SYSCTL_PROC(_machdep, OID_AUTO, msgbuf, CTLTYPE_STRING|CTLFLAG_RD,
176         0, 0, sysctl_machdep_msgbuf, "A","Contents of kernel message buffer");
177
178 static int msgbuf_clear;
179
180 static int
181 sysctl_machdep_msgbuf_clear(SYSCTL_HANDLER_ARGS)
182 {
183         int error;
184         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
185                 req);
186         if (!error && req->newptr) {
187                 /* Clear the buffer and reset write pointer */
188                 bzero(msgbufp->msg_ptr,msgbufp->msg_size);
189                 msgbufp->msg_bufr=msgbufp->msg_bufx=0;
190                 msgbuf_clear=0;
191         }
192         return (error);
193 }
194
195 SYSCTL_PROC(_machdep, OID_AUTO, msgbuf_clear, CTLTYPE_INT|CTLFLAG_RW,
196         &msgbuf_clear, 0, sysctl_machdep_msgbuf_clear, "I",
197         "Clear kernel message buffer");
198
199 #endif
200
201 /*
202  * Send an interrupt to process.
203  *
204  * Stack is set up to allow sigcode stored
205  * at top to call routine, followed by kcall
206  * to sigreturn routine below.  After sigreturn
207  * resets the signal mask, the stack, and the
208  * frame pointer, it returns to the user
209  * specified pc, psl.
210  */
211 void
212 sendsig(sig_t catcher, int sig, sigset_t *mask, u_long code)
213 {
214         struct lwp *lp = curthread->td_lwp;
215         struct proc *p = lp->lwp_proc;
216         struct trapframe *regs;
217         struct sigacts *psp = p->p_sigacts;
218         struct sigframe sf, *sfp;
219         int oonstack;
220
221         regs = lp->lwp_md.md_regs;
222         oonstack = (lp->lwp_sigstk.ss_flags & SS_ONSTACK) ? 1 : 0;
223
224         /* save user context */
225         bzero(&sf, sizeof(struct sigframe));
226         sf.sf_uc.uc_sigmask = *mask;
227         sf.sf_uc.uc_stack = lp->lwp_sigstk;
228         sf.sf_uc.uc_mcontext.mc_onstack = oonstack;
229         bcopy(regs, &sf.sf_uc.uc_mcontext.mc_gs, sizeof(struct trapframe));
230
231         /* make the size of the saved context visible to userland */
232         sf.sf_uc.uc_mcontext.mc_len = sizeof(sf.sf_uc.uc_mcontext); 
233
234         /* Allocate and validate space for the signal handler context. */
235         if ((lp->lwp_flags & LWP_ALTSTACK) != 0 && !oonstack &&
236             SIGISMEMBER(psp->ps_sigonstack, sig)) {
237                 sfp = (struct sigframe *)(lp->lwp_sigstk.ss_sp +
238                     lp->lwp_sigstk.ss_size - sizeof(struct sigframe));
239                 lp->lwp_sigstk.ss_flags |= SS_ONSTACK;
240         }
241         else
242                 sfp = (struct sigframe *)regs->tf_esp - 1;
243
244         /* Translate the signal is appropriate */
245         if (p->p_sysent->sv_sigtbl) {
246                 if (sig <= p->p_sysent->sv_sigsize)
247                         sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
248         }
249
250         /* Build the argument list for the signal handler. */
251         sf.sf_signum = sig;
252         sf.sf_ucontext = (register_t)&sfp->sf_uc;
253         if (SIGISMEMBER(psp->ps_siginfo, sig)) {
254                 /* Signal handler installed with SA_SIGINFO. */
255                 sf.sf_siginfo = (register_t)&sfp->sf_si;
256                 sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
257
258                 /* fill siginfo structure */
259                 sf.sf_si.si_signo = sig;
260                 sf.sf_si.si_code = code;
261                 sf.sf_si.si_addr = (void*)regs->tf_err;
262         }
263         else {
264                 /* Old FreeBSD-style arguments. */
265                 sf.sf_siginfo = code;
266                 sf.sf_addr = regs->tf_err;
267                 sf.sf_ahu.sf_handler = catcher;
268         }
269
270 #if 0
271         /*
272          * If we're a vm86 process, we want to save the segment registers.
273          * We also change eflags to be our emulated eflags, not the actual
274          * eflags.
275          */
276         if (regs->tf_eflags & PSL_VM) {
277                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
278                 struct vm86_kernel *vm86 = &lp->lwp_thread->td_pcb->pcb_ext->ext_vm86;
279
280                 sf.sf_uc.uc_mcontext.mc_gs = tf->tf_vm86_gs;
281                 sf.sf_uc.uc_mcontext.mc_fs = tf->tf_vm86_fs;
282                 sf.sf_uc.uc_mcontext.mc_es = tf->tf_vm86_es;
283                 sf.sf_uc.uc_mcontext.mc_ds = tf->tf_vm86_ds;
284
285                 if (vm86->vm86_has_vme == 0)
286                         sf.sf_uc.uc_mcontext.mc_eflags =
287                             (tf->tf_eflags & ~(PSL_VIF | PSL_VIP)) |
288                             (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
289
290                 /*
291                  * Clear PSL_NT to inhibit T_TSSFLT faults on return from
292                  * syscalls made by the signal handler.  This just avoids
293                  * wasting time for our lazy fixup of such faults.  PSL_NT
294                  * does nothing in vm86 mode, but vm86 programs can set it
295                  * almost legitimately in probes for old cpu types.
296                  */
297                 tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_VIF | PSL_VIP);
298         }
299 #endif
300         
301         /*
302          * Save the FPU state and reinit the FP unit
303          */
304         npxpush(&sf.sf_uc.uc_mcontext);
305
306         /*
307          * Copy the sigframe out to the user's stack.
308          */
309         if (copyout(&sf, sfp, sizeof(struct sigframe)) != 0) {
310                 /*
311                  * Something is wrong with the stack pointer.
312                  * ...Kill the process.
313                  */
314                 sigexit(lp, SIGILL);
315         }
316
317         regs->tf_esp = (int)sfp;
318         regs->tf_eip = PS_STRINGS - *(p->p_sysent->sv_szsigcode);
319
320         /*
321          * i386 abi specifies that the direction flag must be cleared
322          * on function entry
323          */
324         regs->tf_eflags &= ~(PSL_T|PSL_D);
325
326         regs->tf_cs = _ucodesel;
327         regs->tf_ds = _udatasel;
328         regs->tf_es = _udatasel;
329         if (regs->tf_trapno == T_PROTFLT) {
330                 regs->tf_fs = _udatasel;
331                 regs->tf_gs = _udatasel;
332         }
333         regs->tf_ss = _udatasel;
334 }
335
336 /*
337  * Sanitize the trapframe for a virtual kernel passing control to a custom
338  * VM context.
339  *
340  * Allow userland to set or maintain PSL_RF, the resume flag.  This flag
341  * basically controls whether the return PC should skip the first instruction
342  * (as in an explicit system call) or re-execute it (as in an exception).
343  */
344 int
345 cpu_sanitize_frame(struct trapframe *frame)
346 {
347         frame->tf_cs = _ucodesel;
348         frame->tf_ds = _udatasel;
349         frame->tf_es = _udatasel;
350 #if 0
351         frame->tf_fs = _udatasel;
352         frame->tf_gs = _udatasel;
353 #endif
354         frame->tf_ss = _udatasel;
355         frame->tf_eflags &= (PSL_RF | PSL_USERCHANGE);
356         frame->tf_eflags |= PSL_RESERVED_DEFAULT | PSL_I;
357         return(0);
358 }
359
360 int
361 cpu_sanitize_tls(struct savetls *tls)
362 {
363          struct segment_descriptor *desc;
364          int i;
365
366          for (i = 0; i < NGTLS; ++i) {
367                 desc = &tls->tls[i];
368                 if (desc->sd_dpl == 0 && desc->sd_type == 0)
369                         continue;
370                 if (desc->sd_def32 == 0)
371                         return(ENXIO);
372                 if (desc->sd_type != SDT_MEMRWA)
373                         return(ENXIO);
374                 if (desc->sd_dpl != SEL_UPL)
375                         return(ENXIO);
376                 if (desc->sd_xx != 0 || desc->sd_p != 1)
377                         return(ENXIO);
378          }
379          return(0);
380 }
381
382 /*
383  * sigreturn(ucontext_t *sigcntxp)
384  *
385  * System call to cleanup state after a signal
386  * has been taken.  Reset signal mask and
387  * stack state from context left by sendsig (above).
388  * Return to previous pc and psl as specified by
389  * context left by sendsig. Check carefully to
390  * make sure that the user has not modified the
391  * state to gain improper privileges.
392  *
393  * MPSAFE
394  */
395 #define EFL_SECURE(ef, oef)     ((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
396 #define CS_SECURE(cs)           (ISPL(cs) == SEL_UPL)
397
398 int
399 sys_sigreturn(struct sigreturn_args *uap)
400 {
401         struct lwp *lp = curthread->td_lwp;
402         struct trapframe *regs;
403         ucontext_t ucp;
404         int cs;
405         int eflags;
406         int error;
407
408         error = copyin(uap->sigcntxp, &ucp, sizeof(ucp));
409         if (error)
410                 return (error);
411
412         regs = lp->lwp_md.md_regs;
413         eflags = ucp.uc_mcontext.mc_eflags;
414
415 #if 0
416         if (eflags & PSL_VM) {
417                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
418                 struct vm86_kernel *vm86;
419
420                 /*
421                  * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
422                  * set up the vm86 area, and we can't enter vm86 mode.
423                  */
424                 if (lp->lwp_thread->td_pcb->pcb_ext == 0)
425                         return (EINVAL);
426                 vm86 = &lp->lwp_thread->td_pcb->pcb_ext->ext_vm86;
427                 if (vm86->vm86_inited == 0)
428                         return (EINVAL);
429
430                 /* go back to user mode if both flags are set */
431                 if ((eflags & PSL_VIP) && (eflags & PSL_VIF))
432                         trapsignal(lp->lwp_proc, SIGBUS, 0);
433
434                 if (vm86->vm86_has_vme) {
435                         eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
436                             (eflags & VME_USERCHANGE) | PSL_VM;
437                 } else {
438                         vm86->vm86_eflags = eflags;     /* save VIF, VIP */
439                         eflags = (tf->tf_eflags & ~VM_USERCHANGE) |                                         (eflags & VM_USERCHANGE) | PSL_VM;
440                 }
441                 bcopy(&ucp.uc_mcontext.mc_gs, tf, sizeof(struct trapframe));
442                 tf->tf_eflags = eflags;
443                 tf->tf_vm86_ds = tf->tf_ds;
444                 tf->tf_vm86_es = tf->tf_es;
445                 tf->tf_vm86_fs = tf->tf_fs;
446                 tf->tf_vm86_gs = tf->tf_gs;
447                 tf->tf_ds = _udatasel;
448                 tf->tf_es = _udatasel;
449 #if 0
450                 tf->tf_fs = _udatasel;
451                 tf->tf_gs = _udatasel;
452 #endif
453         } else 
454 #endif
455         {
456                 /*
457                  * Don't allow users to change privileged or reserved flags.
458                  */
459                 /*
460                  * XXX do allow users to change the privileged flag PSL_RF.
461                  * The cpu sets PSL_RF in tf_eflags for faults.  Debuggers
462                  * should sometimes set it there too.  tf_eflags is kept in
463                  * the signal context during signal handling and there is no
464                  * other place to remember it, so the PSL_RF bit may be
465                  * corrupted by the signal handler without us knowing.
466                  * Corruption of the PSL_RF bit at worst causes one more or
467                  * one less debugger trap, so allowing it is fairly harmless.
468                  */
469                 if (!EFL_SECURE(eflags & ~PSL_RF, regs->tf_eflags & ~PSL_RF)) {
470                         kprintf("sigreturn: eflags = 0x%x\n", eflags);
471                         return(EINVAL);
472                 }
473
474                 /*
475                  * Don't allow users to load a valid privileged %cs.  Let the
476                  * hardware check for invalid selectors, excess privilege in
477                  * other selectors, invalid %eip's and invalid %esp's.
478                  */
479                 cs = ucp.uc_mcontext.mc_cs;
480                 if (!CS_SECURE(cs)) {
481                         kprintf("sigreturn: cs = 0x%x\n", cs);
482                         trapsignal(lp, SIGBUS, T_PROTFLT);
483                         return(EINVAL);
484                 }
485                 bcopy(&ucp.uc_mcontext.mc_gs, regs, sizeof(struct trapframe));
486         }
487
488         /*
489          * Restore the FPU state from the frame
490          */
491         crit_enter();
492         npxpop(&ucp.uc_mcontext);
493
494         if (ucp.uc_mcontext.mc_onstack & 1)
495                 lp->lwp_sigstk.ss_flags |= SS_ONSTACK;
496         else
497                 lp->lwp_sigstk.ss_flags &= ~SS_ONSTACK;
498
499         lp->lwp_sigmask = ucp.uc_sigmask;
500         SIG_CANTMASK(lp->lwp_sigmask);
501         crit_exit();
502         return(EJUSTRETURN);
503 }
504
505 /*
506  * Stack frame on entry to function.  %eax will contain the function vector,
507  * %ecx will contain the function data.  flags, ecx, and eax will have 
508  * already been pushed on the stack.
509  */
510 struct upc_frame {
511         register_t      eax;
512         register_t      ecx;
513         register_t      edx;
514         register_t      flags;
515         register_t      oldip;
516 };
517
518 void
519 sendupcall(struct vmupcall *vu, int morepending)
520 {
521         struct lwp *lp = curthread->td_lwp;
522         struct trapframe *regs;
523         struct upcall upcall;
524         struct upc_frame upc_frame;
525         int     crit_count = 0;
526
527         /*
528          * If we are a virtual kernel running an emulated user process
529          * context, switch back to the virtual kernel context before
530          * trying to post the signal.
531          */
532         if (lp->lwp_vkernel && lp->lwp_vkernel->ve) {
533                 lp->lwp_md.md_regs->tf_trapno = 0;
534                 vkernel_trap(lp, lp->lwp_md.md_regs);
535         }
536
537         /*
538          * Get the upcall data structure
539          */
540         if (copyin(lp->lwp_upcall, &upcall, sizeof(upcall)) ||
541             copyin((char *)upcall.upc_uthread + upcall.upc_critoff, &crit_count, sizeof(int))
542         ) {
543                 vu->vu_pending = 0;
544                 kprintf("bad upcall address\n");
545                 return;
546         }
547
548         /*
549          * If the data structure is already marked pending or has a critical
550          * section count, mark the data structure as pending and return 
551          * without doing an upcall.  vu_pending is left set.
552          */
553         if (upcall.upc_pending || crit_count >= vu->vu_pending) {
554                 if (upcall.upc_pending < vu->vu_pending) {
555                         upcall.upc_pending = vu->vu_pending;
556                         copyout(&upcall.upc_pending, &lp->lwp_upcall->upc_pending,
557                                 sizeof(upcall.upc_pending));
558                 }
559                 return;
560         }
561
562         /*
563          * We can run this upcall now, clear vu_pending.
564          *
565          * Bump our critical section count and set or clear the
566          * user pending flag depending on whether more upcalls are
567          * pending.  The user will be responsible for calling 
568          * upc_dispatch(-1) to process remaining upcalls.
569          */
570         vu->vu_pending = 0;
571         upcall.upc_pending = morepending;
572         ++crit_count;
573         copyout(&upcall.upc_pending, &lp->lwp_upcall->upc_pending, 
574                 sizeof(upcall.upc_pending));
575         copyout(&crit_count, (char *)upcall.upc_uthread + upcall.upc_critoff,
576                 sizeof(int));
577
578         /*
579          * Construct a stack frame and issue the upcall
580          */
581         regs = lp->lwp_md.md_regs;
582         upc_frame.eax = regs->tf_eax;
583         upc_frame.ecx = regs->tf_ecx;
584         upc_frame.edx = regs->tf_edx;
585         upc_frame.flags = regs->tf_eflags;
586         upc_frame.oldip = regs->tf_eip;
587         if (copyout(&upc_frame, (void *)(regs->tf_esp - sizeof(upc_frame)),
588             sizeof(upc_frame)) != 0) {
589                 kprintf("bad stack on upcall\n");
590         } else {
591                 regs->tf_eax = (register_t)vu->vu_func;
592                 regs->tf_ecx = (register_t)vu->vu_data;
593                 regs->tf_edx = (register_t)lp->lwp_upcall;
594                 regs->tf_eip = (register_t)vu->vu_ctx;
595                 regs->tf_esp -= sizeof(upc_frame);
596         }
597 }
598
599 /*
600  * fetchupcall occurs in the context of a system call, which means that
601  * we have to return EJUSTRETURN in order to prevent eax and edx from
602  * being overwritten by the syscall return value.
603  *
604  * if vu is not NULL we return the new context in %edx, the new data in %ecx,
605  * and the function pointer in %eax.  
606  */
607 int
608 fetchupcall (struct vmupcall *vu, int morepending, void *rsp)
609 {
610         struct upc_frame upc_frame;
611         struct lwp *lp = curthread->td_lwp;
612         struct trapframe *regs;
613         int error;
614         struct upcall upcall;
615         int crit_count;
616
617         regs = lp->lwp_md.md_regs;
618
619         error = copyout(&morepending, &lp->lwp_upcall->upc_pending, sizeof(int));
620         if (error == 0) {
621             if (vu) {
622                 /*
623                  * This jumps us to the next ready context.
624                  */
625                 vu->vu_pending = 0;
626                 error = copyin(lp->lwp_upcall, &upcall, sizeof(upcall));
627                 crit_count = 0;
628                 if (error == 0)
629                         error = copyin((char *)upcall.upc_uthread + upcall.upc_critoff, &crit_count, sizeof(int));
630                 ++crit_count;
631                 if (error == 0)
632                         error = copyout(&crit_count, (char *)upcall.upc_uthread + upcall.upc_critoff, sizeof(int));
633                 regs->tf_eax = (register_t)vu->vu_func;
634                 regs->tf_ecx = (register_t)vu->vu_data;
635                 regs->tf_edx = (register_t)lp->lwp_upcall;
636                 regs->tf_eip = (register_t)vu->vu_ctx;
637                 regs->tf_esp = (register_t)rsp;
638             } else {
639                 /*
640                  * This returns us to the originally interrupted code.
641                  */
642                 error = copyin(rsp, &upc_frame, sizeof(upc_frame));
643                 regs->tf_eax = upc_frame.eax;
644                 regs->tf_ecx = upc_frame.ecx;
645                 regs->tf_edx = upc_frame.edx;
646                 regs->tf_eflags = (regs->tf_eflags & ~PSL_USERCHANGE) |
647                                 (upc_frame.flags & PSL_USERCHANGE);
648                 regs->tf_eip = upc_frame.oldip;
649                 regs->tf_esp = (register_t)((char *)rsp + sizeof(upc_frame));
650             }
651         }
652         if (error == 0)
653                 error = EJUSTRETURN;
654         return(error);
655 }
656
657 /*
658  * cpu_idle() represents the idle LWKT.  You cannot return from this function
659  * (unless you want to blow things up!).  Instead we look for runnable threads
660  * and loop or halt as appropriate.  Giant is not held on entry to the thread.
661  *
662  * The main loop is entered with a critical section held, we must release
663  * the critical section before doing anything else.  lwkt_switch() will
664  * check for pending interrupts due to entering and exiting its own 
665  * critical section.
666  *
667  * Note on cpu_idle_hlt:  On an SMP system we rely on a scheduler IPI
668  * to wake a HLTed cpu up.
669  */
670 static int      cpu_idle_hlt = 1;
671 static int      cpu_idle_hltcnt;
672 static int      cpu_idle_spincnt;
673 SYSCTL_INT(_machdep, OID_AUTO, cpu_idle_hlt, CTLFLAG_RW,
674     &cpu_idle_hlt, 0, "Idle loop HLT enable");
675 SYSCTL_INT(_machdep, OID_AUTO, cpu_idle_hltcnt, CTLFLAG_RW,
676     &cpu_idle_hltcnt, 0, "Idle loop entry halts");
677 SYSCTL_INT(_machdep, OID_AUTO, cpu_idle_spincnt, CTLFLAG_RW,
678     &cpu_idle_spincnt, 0, "Idle loop entry spins");
679
680 void
681 cpu_idle(void)
682 {
683         struct thread *td = curthread;
684         struct mdglobaldata *gd = mdcpu;
685         int reqflags;
686
687         crit_exit();
688         KKASSERT(td->td_critcount == 0);
689         cpu_enable_intr();
690         for (;;) {
691                 /*
692                  * See if there are any LWKTs ready to go.
693                  */
694                 lwkt_switch();
695
696                 /*
697                  * The idle loop halts only if no threads are scheduleable
698                  * and no signals have occured.
699                  */
700                 if (cpu_idle_hlt &&
701                     (td->td_gd->gd_reqflags & RQF_IDLECHECK_WK_MASK) == 0) {
702                         splz();
703                         KKASSERT(MP_LOCK_HELD() == 0);
704                         if ((td->td_gd->gd_reqflags & RQF_IDLECHECK_WK_MASK) == 0) {
705 #ifdef DEBUGIDLE
706                                 struct timeval tv1, tv2;
707                                 gettimeofday(&tv1, NULL);
708 #endif
709                                 reqflags = gd->mi.gd_reqflags &
710                                            ~RQF_IDLECHECK_WK_MASK;
711                                 umtx_sleep(&gd->mi.gd_reqflags, reqflags,
712                                            1000000);
713 #ifdef DEBUGIDLE
714                                 gettimeofday(&tv2, NULL);
715                                 if (tv2.tv_usec - tv1.tv_usec +
716                                     (tv2.tv_sec - tv1.tv_sec) * 1000000 
717                                     > 500000) {
718                                         kprintf("cpu %d idlelock %08x %08x\n",
719                                                 gd->mi.gd_cpuid,
720                                                 gd->mi.gd_reqflags,
721                                                 gd->gd_fpending);
722                                 }
723 #endif
724                         }
725                         ++cpu_idle_hltcnt;
726                 } else {
727                         splz();
728                         __asm __volatile("pause");
729                         ++cpu_idle_spincnt;
730                 }
731         }
732 }
733
734 /*
735  * Called by the spinlock code with or without a critical section held
736  * when a spinlock is found to be seriously constested.
737  *
738  * We need to enter a critical section to prevent signals from recursing
739  * into pthreads.
740  */
741 void
742 cpu_spinlock_contested(void)
743 {
744         cpu_pause();
745 }
746
747 /*
748  * Clear registers on exec
749  */
750 void
751 exec_setregs(u_long entry, u_long stack, u_long ps_strings)
752 {
753         struct thread *td = curthread;
754         struct lwp *lp = td->td_lwp;
755         struct trapframe *regs = lp->lwp_md.md_regs;
756         struct pcb *pcb = lp->lwp_thread->td_pcb;
757
758         /* was i386_user_cleanup() in NetBSD */
759         user_ldt_free(pcb);
760   
761         bzero((char *)regs, sizeof(struct trapframe));
762         regs->tf_eip = entry;
763         regs->tf_esp = stack;
764         regs->tf_eflags = PSL_USER | (regs->tf_eflags & PSL_T);
765         regs->tf_ss = 0;
766         regs->tf_ds = 0;
767         regs->tf_es = 0;
768         regs->tf_fs = 0;
769         regs->tf_gs = 0;
770         regs->tf_cs = 0;
771
772         /* PS_STRINGS value for BSD/OS binaries.  It is 0 for non-BSD/OS. */
773         regs->tf_ebx = ps_strings;
774
775         /*
776          * Reset the hardware debug registers if they were in use.
777          * They won't have any meaning for the newly exec'd process.  
778          */
779         if (pcb->pcb_flags & PCB_DBREGS) {
780                 pcb->pcb_dr0 = 0;
781                 pcb->pcb_dr1 = 0;
782                 pcb->pcb_dr2 = 0;
783                 pcb->pcb_dr3 = 0;
784                 pcb->pcb_dr6 = 0;
785                 pcb->pcb_dr7 = 0;
786                 if (pcb == td->td_pcb) {
787                         /*
788                          * Clear the debug registers on the running
789                          * CPU, otherwise they will end up affecting
790                          * the next process we switch to.
791                          */
792                         reset_dbregs();
793                 }
794                 pcb->pcb_flags &= ~PCB_DBREGS;
795         }
796
797         /*
798          * Initialize the math emulator (if any) for the current process.
799          * Actually, just clear the bit that says that the emulator has
800          * been initialized.  Initialization is delayed until the process
801          * traps to the emulator (if it is done at all) mainly because
802          * emulators don't provide an entry point for initialization.
803          */
804         pcb->pcb_flags &= ~FP_SOFTFP;
805
806         /*
807          * note: do not set CR0_TS here.  npxinit() must do it after clearing
808          * gd_npxthread.  Otherwise a preemptive interrupt thread may panic
809          * in npxdna().
810          */
811         crit_enter();
812 #if 0
813         load_cr0(rcr0() | CR0_MP);
814 #endif
815
816 #if NNPX > 0
817         /* Initialize the npx (if any) for the current process. */
818         npxinit(__INITIAL_NPXCW__);
819 #endif
820         crit_exit();
821
822         /*
823          * note: linux emulator needs edx to be 0x0 on entry, which is
824          * handled in execve simply by setting the 64 bit syscall
825          * return value to 0.
826          */
827 }
828
829 void
830 cpu_setregs(void)
831 {
832 #if 0
833         unsigned int cr0;
834
835         cr0 = rcr0();
836         cr0 |= CR0_NE;                  /* Done by npxinit() */
837         cr0 |= CR0_MP | CR0_TS;         /* Done at every execve() too. */
838         cr0 |= CR0_WP | CR0_AM;
839         load_cr0(cr0);
840         load_gs(_udatasel);
841 #endif
842 }
843
844 static int
845 sysctl_machdep_adjkerntz(SYSCTL_HANDLER_ARGS)
846 {
847         int error;
848         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
849                 req);
850         if (!error && req->newptr)
851                 resettodr();
852         return (error);
853 }
854
855 SYSCTL_PROC(_machdep, CPU_ADJKERNTZ, adjkerntz, CTLTYPE_INT|CTLFLAG_RW,
856         &adjkerntz, 0, sysctl_machdep_adjkerntz, "I", "");
857
858 extern u_long bootdev;          /* not a cdev_t - encoding is different */
859 SYSCTL_ULONG(_machdep, OID_AUTO, guessed_bootdev,
860         CTLFLAG_RD, &bootdev, 0, "Boot device (not in cdev_t format)");
861
862 /*
863  * Initialize 386 and configure to run kernel
864  */
865
866 /*
867  * Initialize segments & interrupt table
868  */
869
870 extern  struct user *proc0paddr;
871
872 #if 0
873
874 extern inthand_t
875         IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
876         IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
877         IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
878         IDTVEC(page), IDTVEC(mchk), IDTVEC(fpu), IDTVEC(align),
879         IDTVEC(xmm), IDTVEC(syscall),
880         IDTVEC(rsvd0);
881 extern inthand_t
882         IDTVEC(int0x80_syscall);
883
884 #endif
885
886 #ifdef DEBUG_INTERRUPTS
887 extern inthand_t *Xrsvdary[256];
888 #endif
889
890 int
891 ptrace_set_pc(struct lwp *lp, unsigned long addr)
892 {
893         lp->lwp_md.md_regs->tf_eip = addr;
894         return (0);
895 }
896
897 int
898 ptrace_single_step(struct lwp *lp)
899 {
900         lp->lwp_md.md_regs->tf_eflags |= PSL_T;
901         return (0);
902 }
903
904 int
905 fill_regs(struct lwp *lp, struct reg *regs)
906 {
907         struct trapframe *tp;
908
909         if ((tp = lp->lwp_md.md_regs) == NULL)
910                 return EINVAL;
911         regs->r_gs = tp->tf_gs;
912         regs->r_fs = tp->tf_fs;
913         regs->r_es = tp->tf_es;
914         regs->r_ds = tp->tf_ds;
915         regs->r_edi = tp->tf_edi;
916         regs->r_esi = tp->tf_esi;
917         regs->r_ebp = tp->tf_ebp;
918         regs->r_ebx = tp->tf_ebx;
919         regs->r_edx = tp->tf_edx;
920         regs->r_ecx = tp->tf_ecx;
921         regs->r_eax = tp->tf_eax;
922         regs->r_eip = tp->tf_eip;
923         regs->r_cs = tp->tf_cs;
924         regs->r_eflags = tp->tf_eflags;
925         regs->r_esp = tp->tf_esp;
926         regs->r_ss = tp->tf_ss;
927         return (0);
928 }
929
930 int
931 set_regs(struct lwp *lp, struct reg *regs)
932 {
933         struct trapframe *tp;
934
935         tp = lp->lwp_md.md_regs;
936         if (!EFL_SECURE(regs->r_eflags, tp->tf_eflags) ||
937             !CS_SECURE(regs->r_cs))
938                 return (EINVAL);
939         tp->tf_gs = regs->r_gs;
940         tp->tf_fs = regs->r_fs;
941         tp->tf_es = regs->r_es;
942         tp->tf_ds = regs->r_ds;
943         tp->tf_edi = regs->r_edi;
944         tp->tf_esi = regs->r_esi;
945         tp->tf_ebp = regs->r_ebp;
946         tp->tf_ebx = regs->r_ebx;
947         tp->tf_edx = regs->r_edx;
948         tp->tf_ecx = regs->r_ecx;
949         tp->tf_eax = regs->r_eax;
950         tp->tf_eip = regs->r_eip;
951         tp->tf_cs = regs->r_cs;
952         tp->tf_eflags = regs->r_eflags;
953         tp->tf_esp = regs->r_esp;
954         tp->tf_ss = regs->r_ss;
955         return (0);
956 }
957
958 #ifndef CPU_DISABLE_SSE
959 static void
960 fill_fpregs_xmm(struct savexmm *sv_xmm, struct save87 *sv_87)
961 {
962         struct env87 *penv_87 = &sv_87->sv_env;
963         struct envxmm *penv_xmm = &sv_xmm->sv_env;
964         int i;
965
966         /* FPU control/status */
967         penv_87->en_cw = penv_xmm->en_cw;
968         penv_87->en_sw = penv_xmm->en_sw;
969         penv_87->en_tw = penv_xmm->en_tw;
970         penv_87->en_fip = penv_xmm->en_fip;
971         penv_87->en_fcs = penv_xmm->en_fcs;
972         penv_87->en_opcode = penv_xmm->en_opcode;
973         penv_87->en_foo = penv_xmm->en_foo;
974         penv_87->en_fos = penv_xmm->en_fos;
975
976         /* FPU registers */
977         for (i = 0; i < 8; ++i)
978                 sv_87->sv_ac[i] = sv_xmm->sv_fp[i].fp_acc;
979 }
980
981 static void
982 set_fpregs_xmm(struct save87 *sv_87, struct savexmm *sv_xmm)
983 {
984         struct env87 *penv_87 = &sv_87->sv_env;
985         struct envxmm *penv_xmm = &sv_xmm->sv_env;
986         int i;
987
988         /* FPU control/status */
989         penv_xmm->en_cw = penv_87->en_cw;
990         penv_xmm->en_sw = penv_87->en_sw;
991         penv_xmm->en_tw = penv_87->en_tw;
992         penv_xmm->en_fip = penv_87->en_fip;
993         penv_xmm->en_fcs = penv_87->en_fcs;
994         penv_xmm->en_opcode = penv_87->en_opcode;
995         penv_xmm->en_foo = penv_87->en_foo;
996         penv_xmm->en_fos = penv_87->en_fos;
997
998         /* FPU registers */
999         for (i = 0; i < 8; ++i)
1000                 sv_xmm->sv_fp[i].fp_acc = sv_87->sv_ac[i];
1001 }
1002 #endif /* CPU_DISABLE_SSE */
1003
1004 int
1005 fill_fpregs(struct lwp *lp, struct fpreg *fpregs)
1006 {
1007         if (lp->lwp_thread == NULL || lp->lwp_thread->td_pcb == NULL)
1008                 return EINVAL;
1009 #ifndef CPU_DISABLE_SSE
1010         if (cpu_fxsr) {
1011                 fill_fpregs_xmm(&lp->lwp_thread->td_pcb->pcb_save.sv_xmm,
1012                                 (struct save87 *)fpregs);
1013                 return (0);
1014         }
1015 #endif /* CPU_DISABLE_SSE */
1016         bcopy(&lp->lwp_thread->td_pcb->pcb_save.sv_87, fpregs, sizeof *fpregs);
1017         return (0);
1018 }
1019
1020 int
1021 set_fpregs(struct lwp *lp, struct fpreg *fpregs)
1022 {
1023 #ifndef CPU_DISABLE_SSE
1024         if (cpu_fxsr) {
1025                 set_fpregs_xmm((struct save87 *)fpregs,
1026                                &lp->lwp_thread->td_pcb->pcb_save.sv_xmm);
1027                 return (0);
1028         }
1029 #endif /* CPU_DISABLE_SSE */
1030         bcopy(fpregs, &lp->lwp_thread->td_pcb->pcb_save.sv_87, sizeof *fpregs);
1031         return (0);
1032 }
1033
1034 int
1035 fill_dbregs(struct lwp *lp, struct dbreg *dbregs)
1036 {
1037         return (ENOSYS);
1038 }
1039
1040 int
1041 set_dbregs(struct lwp *lp, struct dbreg *dbregs)
1042 {
1043         return (ENOSYS);
1044 }
1045
1046 #if 0
1047 /*
1048  * Return > 0 if a hardware breakpoint has been hit, and the
1049  * breakpoint was in user space.  Return 0, otherwise.
1050  */
1051 int
1052 user_dbreg_trap(void)
1053 {
1054         u_int32_t dr7, dr6; /* debug registers dr6 and dr7 */
1055         u_int32_t bp;       /* breakpoint bits extracted from dr6 */
1056         int nbp;            /* number of breakpoints that triggered */
1057         caddr_t addr[4];    /* breakpoint addresses */
1058         int i;
1059         
1060         dr7 = rdr7();
1061         if ((dr7 & 0x000000ff) == 0) {
1062                 /*
1063                  * all GE and LE bits in the dr7 register are zero,
1064                  * thus the trap couldn't have been caused by the
1065                  * hardware debug registers
1066                  */
1067                 return 0;
1068         }
1069
1070         nbp = 0;
1071         dr6 = rdr6();
1072         bp = dr6 & 0x0000000f;
1073
1074         if (!bp) {
1075                 /*
1076                  * None of the breakpoint bits are set meaning this
1077                  * trap was not caused by any of the debug registers
1078                  */
1079                 return 0;
1080         }
1081
1082         /*
1083          * at least one of the breakpoints were hit, check to see
1084          * which ones and if any of them are user space addresses
1085          */
1086
1087         if (bp & 0x01) {
1088                 addr[nbp++] = (caddr_t)rdr0();
1089         }
1090         if (bp & 0x02) {
1091                 addr[nbp++] = (caddr_t)rdr1();
1092         }
1093         if (bp & 0x04) {
1094                 addr[nbp++] = (caddr_t)rdr2();
1095         }
1096         if (bp & 0x08) {
1097                 addr[nbp++] = (caddr_t)rdr3();
1098         }
1099
1100         for (i=0; i<nbp; i++) {
1101                 if (addr[i] <
1102                     (caddr_t)VM_MAX_USER_ADDRESS) {
1103                         /*
1104                          * addr[i] is in user space
1105                          */
1106                         return nbp;
1107                 }
1108         }
1109
1110         /*
1111          * None of the breakpoints are in user space.
1112          */
1113         return 0;
1114 }
1115
1116 #endif
1117
1118 void
1119 identcpu(void)
1120 {
1121         int regs[4];
1122
1123         do_cpuid(1, regs);
1124         cpu_feature = regs[3];
1125 }
1126
1127
1128 #ifndef DDB
1129 void
1130 Debugger(const char *msg)
1131 {
1132         kprintf("Debugger(\"%s\") called.\n", msg);
1133 }
1134 #endif /* no DDB */
1135