]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/amd64/vm_machdep.c
amd64: partially depessimize cpu_fetch_syscall_args and cpu_set_syscall_retval
[FreeBSD/FreeBSD.git] / sys / amd64 / amd64 / vm_machdep.c
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 1982, 1986 The Regents of the University of California.
5  * Copyright (c) 1989, 1990 William Jolitz
6  * Copyright (c) 1994 John Dyson
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to Berkeley by
10  * the Systems Programming Group of the University of Utah Computer
11  * Science Department, and William Jolitz.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. All advertising materials mentioning features or use of this software
22  *    must display the following acknowledgement:
23  *      This product includes software developed by the University of
24  *      California, Berkeley and its contributors.
25  * 4. Neither the name of the University nor the names of its contributors
26  *    may be used to endorse or promote products derived from this software
27  *    without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39  * SUCH DAMAGE.
40  *
41  *      from: @(#)vm_machdep.c  7.3 (Berkeley) 5/13/91
42  *      Utah $Hdr: vm_machdep.c 1.16.1.1 89/06/23$
43  */
44
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
47
48 #include "opt_isa.h"
49 #include "opt_cpu.h"
50
51 #include <sys/param.h>
52 #include <sys/systm.h>
53 #include <sys/bio.h>
54 #include <sys/buf.h>
55 #include <sys/kernel.h>
56 #include <sys/ktr.h>
57 #include <sys/lock.h>
58 #include <sys/malloc.h>
59 #include <sys/mbuf.h>
60 #include <sys/mutex.h>
61 #include <sys/pioctl.h>
62 #include <sys/proc.h>
63 #include <sys/smp.h>
64 #include <sys/sysctl.h>
65 #include <sys/sysent.h>
66 #include <sys/unistd.h>
67 #include <sys/vnode.h>
68 #include <sys/vmmeter.h>
69
70 #include <machine/cpu.h>
71 #include <machine/md_var.h>
72 #include <machine/pcb.h>
73 #include <machine/smp.h>
74 #include <machine/specialreg.h>
75 #include <machine/tss.h>
76
77 #include <vm/vm.h>
78 #include <vm/vm_extern.h>
79 #include <vm/vm_kern.h>
80 #include <vm/vm_page.h>
81 #include <vm/vm_map.h>
82 #include <vm/vm_param.h>
83
84 _Static_assert(OFFSETOF_CURTHREAD == offsetof(struct pcpu, pc_curthread),
85     "OFFSETOF_CURTHREAD does not correspond with offset of pc_curthread.");
86 _Static_assert(OFFSETOF_CURPCB == offsetof(struct pcpu, pc_curpcb),
87     "OFFSETOF_CURPCB does not correspond with offset of pc_curpcb.");
88 _Static_assert(OFFSETOF_MONITORBUF == offsetof(struct pcpu, pc_monitorbuf),
89     "OFFSETOF_MONINORBUF does not correspond with offset of pc_monitorbuf.");
90
91 struct savefpu *
92 get_pcb_user_save_td(struct thread *td)
93 {
94         vm_offset_t p;
95
96         p = td->td_kstack + td->td_kstack_pages * PAGE_SIZE -
97             roundup2(cpu_max_ext_state_size, XSAVE_AREA_ALIGN);
98         KASSERT((p % XSAVE_AREA_ALIGN) == 0, ("Unaligned pcb_user_save area"));
99         return ((struct savefpu *)p);
100 }
101
102 struct savefpu *
103 get_pcb_user_save_pcb(struct pcb *pcb)
104 {
105         vm_offset_t p;
106
107         p = (vm_offset_t)(pcb + 1);
108         return ((struct savefpu *)p);
109 }
110
111 struct pcb *
112 get_pcb_td(struct thread *td)
113 {
114         vm_offset_t p;
115
116         p = td->td_kstack + td->td_kstack_pages * PAGE_SIZE -
117             roundup2(cpu_max_ext_state_size, XSAVE_AREA_ALIGN) -
118             sizeof(struct pcb);
119         return ((struct pcb *)p);
120 }
121
122 void *
123 alloc_fpusave(int flags)
124 {
125         void *res;
126         struct savefpu_ymm *sf;
127
128         res = malloc(cpu_max_ext_state_size, M_DEVBUF, flags);
129         if (use_xsave) {
130                 sf = (struct savefpu_ymm *)res;
131                 bzero(&sf->sv_xstate.sx_hd, sizeof(sf->sv_xstate.sx_hd));
132                 sf->sv_xstate.sx_hd.xstate_bv = xsave_mask;
133         }
134         return (res);
135 }
136
137 /*
138  * Finish a fork operation, with process p2 nearly set up.
139  * Copy and update the pcb, set up the stack so that the child
140  * ready to run and return to user mode.
141  */
142 void
143 cpu_fork(struct thread *td1, struct proc *p2, struct thread *td2, int flags)
144 {
145         struct proc *p1;
146         struct pcb *pcb2;
147         struct mdproc *mdp1, *mdp2;
148         struct proc_ldt *pldt;
149
150         p1 = td1->td_proc;
151         if ((flags & RFPROC) == 0) {
152                 if ((flags & RFMEM) == 0) {
153                         /* unshare user LDT */
154                         mdp1 = &p1->p_md;
155                         mtx_lock(&dt_lock);
156                         if ((pldt = mdp1->md_ldt) != NULL &&
157                             pldt->ldt_refcnt > 1 &&
158                             user_ldt_alloc(p1, 1) == NULL)
159                                 panic("could not copy LDT");
160                         mtx_unlock(&dt_lock);
161                 }
162                 return;
163         }
164
165         /* Ensure that td1's pcb is up to date. */
166         fpuexit(td1);
167         update_pcb_bases(td1->td_pcb);
168
169         /* Point the pcb to the top of the stack */
170         pcb2 = get_pcb_td(td2);
171         td2->td_pcb = pcb2;
172
173         /* Copy td1's pcb */
174         bcopy(td1->td_pcb, pcb2, sizeof(*pcb2));
175
176         /* Properly initialize pcb_save */
177         pcb2->pcb_save = get_pcb_user_save_pcb(pcb2);
178         bcopy(get_pcb_user_save_td(td1), get_pcb_user_save_pcb(pcb2),
179             cpu_max_ext_state_size);
180
181         /* Point mdproc and then copy over td1's contents */
182         mdp2 = &p2->p_md;
183         bcopy(&p1->p_md, mdp2, sizeof(*mdp2));
184
185         /*
186          * Create a new fresh stack for the new process.
187          * Copy the trap frame for the return to user mode as if from a
188          * syscall.  This copies most of the user mode register values.
189          */
190         td2->td_frame = (struct trapframe *)td2->td_pcb - 1;
191         bcopy(td1->td_frame, td2->td_frame, sizeof(struct trapframe));
192
193         td2->td_frame->tf_rax = 0;              /* Child returns zero */
194         td2->td_frame->tf_rflags &= ~PSL_C;     /* success */
195         td2->td_frame->tf_rdx = 1;
196
197         /*
198          * If the parent process has the trap bit set (i.e. a debugger had
199          * single stepped the process to the system call), we need to clear
200          * the trap flag from the new frame unless the debugger had set PF_FORK
201          * on the parent.  Otherwise, the child will receive a (likely
202          * unexpected) SIGTRAP when it executes the first instruction after
203          * returning  to userland.
204          */
205         if ((p1->p_pfsflags & PF_FORK) == 0)
206                 td2->td_frame->tf_rflags &= ~PSL_T;
207
208         /*
209          * Set registers for trampoline to user mode.  Leave space for the
210          * return address on stack.  These are the kernel mode register values.
211          */
212         pcb2->pcb_r12 = (register_t)fork_return;        /* fork_trampoline argument */
213         pcb2->pcb_rbp = 0;
214         pcb2->pcb_rsp = (register_t)td2->td_frame - sizeof(void *);
215         pcb2->pcb_rbx = (register_t)td2;                /* fork_trampoline argument */
216         pcb2->pcb_rip = (register_t)fork_trampoline;
217         /*-
218          * pcb2->pcb_dr*:       cloned above.
219          * pcb2->pcb_savefpu:   cloned above.
220          * pcb2->pcb_flags:     cloned above.
221          * pcb2->pcb_onfault:   cloned above (always NULL here?).
222          * pcb2->pcb_[fg]sbase: cloned above
223          */
224
225         /* Setup to release spin count in fork_exit(). */
226         td2->td_md.md_spinlock_count = 1;
227         td2->td_md.md_saved_flags = PSL_KERNEL | PSL_I;
228         td2->td_md.md_invl_gen.gen = 0;
229
230         /* As an i386, do not copy io permission bitmap. */
231         pcb2->pcb_tssp = NULL;
232
233         /* New segment registers. */
234         set_pcb_flags_raw(pcb2, PCB_FULL_IRET);
235
236         /* Copy the LDT, if necessary. */
237         mdp1 = &td1->td_proc->p_md;
238         mdp2 = &p2->p_md;
239         if (mdp1->md_ldt == NULL) {
240                 mdp2->md_ldt = NULL;
241                 return;
242         }
243         mtx_lock(&dt_lock);
244         if (mdp1->md_ldt != NULL) {
245                 if (flags & RFMEM) {
246                         mdp1->md_ldt->ldt_refcnt++;
247                         mdp2->md_ldt = mdp1->md_ldt;
248                         bcopy(&mdp1->md_ldt_sd, &mdp2->md_ldt_sd, sizeof(struct
249                             system_segment_descriptor));
250                 } else {
251                         mdp2->md_ldt = NULL;
252                         mdp2->md_ldt = user_ldt_alloc(p2, 0);
253                         if (mdp2->md_ldt == NULL)
254                                 panic("could not copy LDT");
255                         amd64_set_ldt_data(td2, 0, max_ldt_segment,
256                             (struct user_segment_descriptor *)
257                             mdp1->md_ldt->ldt_base);
258                 }
259         } else
260                 mdp2->md_ldt = NULL;
261         mtx_unlock(&dt_lock);
262
263         /*
264          * Now, cpu_switch() can schedule the new process.
265          * pcb_rsp is loaded pointing to the cpu_switch() stack frame
266          * containing the return address when exiting cpu_switch.
267          * This will normally be to fork_trampoline(), which will have
268          * %ebx loaded with the new proc's pointer.  fork_trampoline()
269          * will set up a stack to call fork_return(p, frame); to complete
270          * the return to user-mode.
271          */
272 }
273
274 /*
275  * Intercept the return address from a freshly forked process that has NOT
276  * been scheduled yet.
277  *
278  * This is needed to make kernel threads stay in kernel mode.
279  */
280 void
281 cpu_fork_kthread_handler(struct thread *td, void (*func)(void *), void *arg)
282 {
283         /*
284          * Note that the trap frame follows the args, so the function
285          * is really called like this:  func(arg, frame);
286          */
287         td->td_pcb->pcb_r12 = (long) func;      /* function */
288         td->td_pcb->pcb_rbx = (long) arg;       /* first arg */
289 }
290
291 void
292 cpu_exit(struct thread *td)
293 {
294
295         /*
296          * If this process has a custom LDT, release it.
297          */
298         if (td->td_proc->p_md.md_ldt != NULL)
299                 user_ldt_free(td);
300 }
301
302 void
303 cpu_thread_exit(struct thread *td)
304 {
305         struct pcb *pcb;
306
307         critical_enter();
308         if (td == PCPU_GET(fpcurthread))
309                 fpudrop();
310         critical_exit();
311
312         pcb = td->td_pcb;
313
314         /* Disable any hardware breakpoints. */
315         if (pcb->pcb_flags & PCB_DBREGS) {
316                 reset_dbregs();
317                 clear_pcb_flags(pcb, PCB_DBREGS);
318         }
319 }
320
321 void
322 cpu_thread_clean(struct thread *td)
323 {
324         struct pcb *pcb;
325
326         pcb = td->td_pcb;
327
328         /*
329          * Clean TSS/iomap
330          */
331         if (pcb->pcb_tssp != NULL) {
332                 pmap_pti_remove_kva((vm_offset_t)pcb->pcb_tssp,
333                     (vm_offset_t)pcb->pcb_tssp + ctob(IOPAGES + 1));
334                 kmem_free((vm_offset_t)pcb->pcb_tssp, ctob(IOPAGES + 1));
335                 pcb->pcb_tssp = NULL;
336         }
337 }
338
339 void
340 cpu_thread_swapin(struct thread *td)
341 {
342 }
343
344 void
345 cpu_thread_swapout(struct thread *td)
346 {
347 }
348
349 void
350 cpu_thread_alloc(struct thread *td)
351 {
352         struct pcb *pcb;
353         struct xstate_hdr *xhdr;
354
355         td->td_pcb = pcb = get_pcb_td(td);
356         td->td_frame = (struct trapframe *)pcb - 1;
357         pcb->pcb_save = get_pcb_user_save_pcb(pcb);
358         if (use_xsave) {
359                 xhdr = (struct xstate_hdr *)(pcb->pcb_save + 1);
360                 bzero(xhdr, sizeof(*xhdr));
361                 xhdr->xstate_bv = xsave_mask;
362         }
363 }
364
365 void
366 cpu_thread_free(struct thread *td)
367 {
368
369         cpu_thread_clean(td);
370 }
371
372 void
373 cpu_set_syscall_retval(struct thread *td, int error)
374 {
375         struct trapframe *frame;
376
377         frame = td->td_frame;
378         if (__predict_true(error == 0)) {
379                 frame->tf_rax = td->td_retval[0];
380                 frame->tf_rdx = td->td_retval[1];
381                 frame->tf_rflags &= ~PSL_C;
382                 return;
383         }
384
385         switch (error) {
386         case ERESTART:
387                 /*
388                  * Reconstruct pc, we know that 'syscall' is 2 bytes,
389                  * lcall $X,y is 7 bytes, int 0x80 is 2 bytes.
390                  * We saved this in tf_err.
391                  * %r10 (which was holding the value of %rcx) is restored
392                  * for the next iteration.
393                  * %r10 restore is only required for freebsd/amd64 processes,
394                  * but shall be innocent for any ia32 ABI.
395                  *
396                  * Require full context restore to get the arguments
397                  * in the registers reloaded at return to usermode.
398                  */
399                 frame->tf_rip -= frame->tf_err;
400                 frame->tf_r10 = frame->tf_rcx;
401                 set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
402                 break;
403
404         case EJUSTRETURN:
405                 break;
406
407         default:
408                 frame->tf_rax = SV_ABI_ERRNO(td->td_proc, error);
409                 frame->tf_rflags |= PSL_C;
410                 break;
411         }
412 }
413
414 /*
415  * Initialize machine state, mostly pcb and trap frame for a new
416  * thread, about to return to userspace.  Put enough state in the new
417  * thread's PCB to get it to go back to the fork_return(), which
418  * finalizes the thread state and handles peculiarities of the first
419  * return to userspace for the new thread.
420  */
421 void
422 cpu_copy_thread(struct thread *td, struct thread *td0)
423 {
424         struct pcb *pcb2;
425
426         /* Point the pcb to the top of the stack. */
427         pcb2 = td->td_pcb;
428
429         /*
430          * Copy the upcall pcb.  This loads kernel regs.
431          * Those not loaded individually below get their default
432          * values here.
433          */
434         update_pcb_bases(td0->td_pcb);
435         bcopy(td0->td_pcb, pcb2, sizeof(*pcb2));
436         clear_pcb_flags(pcb2, PCB_FPUINITDONE | PCB_USERFPUINITDONE |
437             PCB_KERNFPU);
438         pcb2->pcb_save = get_pcb_user_save_pcb(pcb2);
439         bcopy(get_pcb_user_save_td(td0), pcb2->pcb_save,
440             cpu_max_ext_state_size);
441         set_pcb_flags_raw(pcb2, PCB_FULL_IRET);
442
443         /*
444          * Create a new fresh stack for the new thread.
445          */
446         bcopy(td0->td_frame, td->td_frame, sizeof(struct trapframe));
447
448         /* If the current thread has the trap bit set (i.e. a debugger had
449          * single stepped the process to the system call), we need to clear
450          * the trap flag from the new frame. Otherwise, the new thread will
451          * receive a (likely unexpected) SIGTRAP when it executes the first
452          * instruction after returning to userland.
453          */
454         td->td_frame->tf_rflags &= ~PSL_T;
455
456         /*
457          * Set registers for trampoline to user mode.  Leave space for the
458          * return address on stack.  These are the kernel mode register values.
459          */
460         pcb2->pcb_r12 = (register_t)fork_return;            /* trampoline arg */
461         pcb2->pcb_rbp = 0;
462         pcb2->pcb_rsp = (register_t)td->td_frame - sizeof(void *);      /* trampoline arg */
463         pcb2->pcb_rbx = (register_t)td;                     /* trampoline arg */
464         pcb2->pcb_rip = (register_t)fork_trampoline;
465         /*
466          * If we didn't copy the pcb, we'd need to do the following registers:
467          * pcb2->pcb_dr*:       cloned above.
468          * pcb2->pcb_savefpu:   cloned above.
469          * pcb2->pcb_onfault:   cloned above (always NULL here?).
470          * pcb2->pcb_[fg]sbase: cloned above
471          */
472
473         /* Setup to release spin count in fork_exit(). */
474         td->td_md.md_spinlock_count = 1;
475         td->td_md.md_saved_flags = PSL_KERNEL | PSL_I;
476 }
477
478 /*
479  * Set that machine state for performing an upcall that starts
480  * the entry function with the given argument.
481  */
482 void
483 cpu_set_upcall(struct thread *td, void (*entry)(void *), void *arg,
484     stack_t *stack)
485 {
486
487         /* 
488          * Do any extra cleaning that needs to be done.
489          * The thread may have optional components
490          * that are not present in a fresh thread.
491          * This may be a recycled thread so make it look
492          * as though it's newly allocated.
493          */
494         cpu_thread_clean(td);
495
496 #ifdef COMPAT_FREEBSD32
497         if (SV_PROC_FLAG(td->td_proc, SV_ILP32)) {
498                 /*
499                  * Set the trap frame to point at the beginning of the entry
500                  * function.
501                  */
502                 td->td_frame->tf_rbp = 0;
503                 td->td_frame->tf_rsp =
504                    (((uintptr_t)stack->ss_sp + stack->ss_size - 4) & ~0x0f) - 4;
505                 td->td_frame->tf_rip = (uintptr_t)entry;
506
507                 /* Return address sentinel value to stop stack unwinding. */
508                 suword32((void *)td->td_frame->tf_rsp, 0);
509
510                 /* Pass the argument to the entry point. */
511                 suword32((void *)(td->td_frame->tf_rsp + sizeof(int32_t)),
512                     (uint32_t)(uintptr_t)arg);
513
514                 return;
515         }
516 #endif
517
518         /*
519          * Set the trap frame to point at the beginning of the uts
520          * function.
521          */
522         td->td_frame->tf_rbp = 0;
523         td->td_frame->tf_rsp =
524             ((register_t)stack->ss_sp + stack->ss_size) & ~0x0f;
525         td->td_frame->tf_rsp -= 8;
526         td->td_frame->tf_rip = (register_t)entry;
527         td->td_frame->tf_ds = _udatasel;
528         td->td_frame->tf_es = _udatasel;
529         td->td_frame->tf_fs = _ufssel;
530         td->td_frame->tf_gs = _ugssel;
531         td->td_frame->tf_flags = TF_HASSEGS;
532
533         /* Return address sentinel value to stop stack unwinding. */
534         suword((void *)td->td_frame->tf_rsp, 0);
535
536         /* Pass the argument to the entry point. */
537         td->td_frame->tf_rdi = (register_t)arg;
538 }
539
540 int
541 cpu_set_user_tls(struct thread *td, void *tls_base)
542 {
543         struct pcb *pcb;
544
545         if ((u_int64_t)tls_base >= VM_MAXUSER_ADDRESS)
546                 return (EINVAL);
547
548         pcb = td->td_pcb;
549         set_pcb_flags(pcb, PCB_FULL_IRET);
550 #ifdef COMPAT_FREEBSD32
551         if (SV_PROC_FLAG(td->td_proc, SV_ILP32)) {
552                 pcb->pcb_gsbase = (register_t)tls_base;
553                 return (0);
554         }
555 #endif
556         pcb->pcb_fsbase = (register_t)tls_base;
557         return (0);
558 }
559
560 /*
561  * Software interrupt handler for queued VM system processing.
562  */   
563 void  
564 swi_vm(void *dummy) 
565 {     
566         if (busdma_swi_pending != 0)
567                 busdma_swi();
568 }
569
570 /*
571  * Tell whether this address is in some physical memory region.
572  * Currently used by the kernel coredump code in order to avoid
573  * dumping the ``ISA memory hole'' which could cause indefinite hangs,
574  * or other unpredictable behaviour.
575  */
576
577 int
578 is_physical_memory(vm_paddr_t addr)
579 {
580
581 #ifdef DEV_ISA
582         /* The ISA ``memory hole''. */
583         if (addr >= 0xa0000 && addr < 0x100000)
584                 return 0;
585 #endif
586
587         /*
588          * stuff other tests for known memory-mapped devices (PCI?)
589          * here
590          */
591
592         return 1;
593 }