xref: /freebsd/sys/amd64/linux/linux_sysvec.c (revision f374ba41f55c1a127303d92d830dd58eef2f5243)
1 /*-
2  * Copyright (c) 2004 Tim J. Robbins
3  * Copyright (c) 2003 Peter Wemm
4  * Copyright (c) 2002 Doug Rabson
5  * Copyright (c) 1998-1999 Andrew Gallatin
6  * Copyright (c) 1994-1996 Søren Schmidt
7  * All rights reserved.
8  * Copyright (c) 2013, 2021 Dmitry Chagin <dchagin@FreeBSD.org>
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  *    in this position and unchanged.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. The name of the author may not be used to endorse or promote products
20  *    derived from this software without specific prior written permission
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #define	__ELF_WORD_SIZE	64
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/exec.h>
42 #include <sys/fcntl.h>
43 #include <sys/imgact.h>
44 #include <sys/imgact_elf.h>
45 #include <sys/kernel.h>
46 #include <sys/ktr.h>
47 #include <sys/lock.h>
48 #include <sys/malloc.h>
49 #include <sys/module.h>
50 #include <sys/mutex.h>
51 #include <sys/proc.h>
52 #include <sys/resourcevar.h>
53 #include <sys/stddef.h>
54 #include <sys/signalvar.h>
55 #include <sys/syscallsubr.h>
56 #include <sys/sysctl.h>
57 #include <sys/sysent.h>
58 #include <sys/sysproto.h>
59 #include <sys/vnode.h>
60 #include <sys/eventhandler.h>
61 
62 #include <vm/vm.h>
63 #include <vm/pmap.h>
64 #include <vm/vm_extern.h>
65 #include <vm/vm_map.h>
66 #include <vm/vm_object.h>
67 #include <vm/vm_page.h>
68 #include <vm/vm_param.h>
69 
70 #include <machine/cpu.h>
71 #include <machine/md_var.h>
72 #include <machine/pcb.h>
73 #include <machine/specialreg.h>
74 #include <machine/trap.h>
75 
76 #include <x86/linux/linux_x86.h>
77 #include <amd64/linux/linux.h>
78 #include <amd64/linux/linux_proto.h>
79 #include <compat/linux/linux_elf.h>
80 #include <compat/linux/linux_emul.h>
81 #include <compat/linux/linux_fork.h>
82 #include <compat/linux/linux_ioctl.h>
83 #include <compat/linux/linux_mib.h>
84 #include <compat/linux/linux_misc.h>
85 #include <compat/linux/linux_signal.h>
86 #include <compat/linux/linux_sysproto.h>
87 #include <compat/linux/linux_util.h>
88 #include <compat/linux/linux_vdso.h>
89 
90 #include <x86/linux/linux_x86_sigframe.h>
91 
92 MODULE_VERSION(linux64, 1);
93 
94 #define	LINUX_VDSOPAGE_SIZE	PAGE_SIZE * 2
95 #define	LINUX_VDSOPAGE_LA48	(VM_MAXUSER_ADDRESS_LA48 - \
96 				    LINUX_VDSOPAGE_SIZE)
97 #define	LINUX_SHAREDPAGE_LA48	(LINUX_VDSOPAGE_LA48 - PAGE_SIZE)
98 				/*
99 				 * PAGE_SIZE - the size
100 				 * of the native SHAREDPAGE
101 				 */
102 #define	LINUX_USRSTACK_LA48	LINUX_SHAREDPAGE_LA48
103 #define	LINUX_PS_STRINGS_LA48	(LINUX_USRSTACK_LA48 - \
104 				    sizeof(struct ps_strings))
105 
106 static int linux_szsigcode;
107 static vm_object_t linux_vdso_obj;
108 static char *linux_vdso_mapping;
109 extern char _binary_linux_vdso_so_o_start;
110 extern char _binary_linux_vdso_so_o_end;
111 static vm_offset_t linux_vdso_base;
112 
113 extern struct sysent linux_sysent[LINUX_SYS_MAXSYSCALL];
114 extern const char *linux_syscallnames[];
115 
116 SET_DECLARE(linux_ioctl_handler_set, struct linux_ioctl_handler);
117 
118 static void	linux_vdso_install(const void *param);
119 static void	linux_vdso_deinstall(const void *param);
120 static void	linux_vdso_reloc(char *mapping, Elf_Addr offset);
121 static void	linux_set_syscall_retval(struct thread *td, int error);
122 static int	linux_fetch_syscall_args(struct thread *td);
123 static void	linux_exec_setregs(struct thread *td, struct image_params *imgp,
124 		    uintptr_t stack);
125 static void	linux_exec_sysvec_init(void *param);
126 static int	linux_on_exec_vmspace(struct proc *p,
127 		    struct image_params *imgp);
128 static void	linux_set_fork_retval(struct thread *td);
129 static int	linux_vsyscall(struct thread *td);
130 
131 LINUX_VDSO_SYM_INTPTR(linux_rt_sigcode);
132 LINUX_VDSO_SYM_CHAR(linux_platform);
133 LINUX_VDSO_SYM_INTPTR(kern_timekeep_base);
134 LINUX_VDSO_SYM_INTPTR(kern_tsc_selector);
135 LINUX_VDSO_SYM_INTPTR(kern_cpu_selector);
136 
137 static int
138 linux_fetch_syscall_args(struct thread *td)
139 {
140 	struct proc *p;
141 	struct trapframe *frame;
142 	struct syscall_args *sa;
143 
144 	p = td->td_proc;
145 	frame = td->td_frame;
146 	sa = &td->td_sa;
147 
148 	sa->args[0] = frame->tf_rdi;
149 	sa->args[1] = frame->tf_rsi;
150 	sa->args[2] = frame->tf_rdx;
151 	sa->args[3] = frame->tf_rcx;
152 	sa->args[4] = frame->tf_r8;
153 	sa->args[5] = frame->tf_r9;
154 	sa->code = frame->tf_rax;
155 	sa->original_code = sa->code;
156 
157 	if (sa->code >= p->p_sysent->sv_size)
158 		/* nosys */
159 		sa->callp = &p->p_sysent->sv_table[p->p_sysent->sv_size - 1];
160 	else
161 		sa->callp = &p->p_sysent->sv_table[sa->code];
162 
163 	td->td_retval[0] = 0;
164 	return (0);
165 }
166 
167 static void
168 linux_set_syscall_retval(struct thread *td, int error)
169 {
170 	struct trapframe *frame;
171 
172 	frame = td->td_frame;
173 
174 	switch (error) {
175 	case 0:
176 		frame->tf_rax = td->td_retval[0];
177 		frame->tf_r10 = frame->tf_rcx;
178 		break;
179 
180 	case ERESTART:
181 		/*
182 		 * Reconstruct pc, we know that 'syscall' is 2 bytes,
183 		 * lcall $X,y is 7 bytes, int 0x80 is 2 bytes.
184 		 * We saved this in tf_err.
185 		 *
186 		 */
187 		frame->tf_rip -= frame->tf_err;
188 		frame->tf_r10 = frame->tf_rcx;
189 		break;
190 
191 	case EJUSTRETURN:
192 		break;
193 
194 	default:
195 		frame->tf_rax = bsd_to_linux_errno(error);
196 		frame->tf_r10 = frame->tf_rcx;
197 		break;
198 	}
199 
200 	/*
201 	 * Differently from FreeBSD native ABI, on Linux only %rcx
202 	 * and %r11 values are not preserved across the syscall.
203 	 * Require full context restore to get all registers except
204 	 * those two restored at return to usermode.
205 	 *
206 	 * XXX: Would be great to be able to avoid PCB_FULL_IRET
207 	 *      for the error == 0 case.
208 	 */
209 	set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
210 }
211 
212 static void
213 linux_set_fork_retval(struct thread *td)
214 {
215 	struct trapframe *frame = td->td_frame;
216 
217 	frame->tf_rax = 0;
218 }
219 
220 static int
221 linux_copyout_auxargs(struct image_params *imgp, uintptr_t base)
222 {
223 	Elf_Auxargs *args;
224 	Elf_Auxinfo *argarray, *pos;
225 	struct proc *p;
226 	int error, issetugid;
227 
228 	p = imgp->proc;
229 	args = (Elf64_Auxargs *)imgp->auxargs;
230 	argarray = pos = malloc(LINUX_AT_COUNT * sizeof(*pos), M_TEMP,
231 	    M_WAITOK | M_ZERO);
232 
233 	issetugid = p->p_flag & P_SUGID ? 1 : 0;
234 	AUXARGS_ENTRY(pos, LINUX_AT_SYSINFO_EHDR, linux_vdso_base);
235 	AUXARGS_ENTRY(pos, LINUX_AT_HWCAP, cpu_feature);
236 	AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
237 	AUXARGS_ENTRY(pos, LINUX_AT_CLKTCK, stclohz);
238 	AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
239 	AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
240 	AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
241 	AUXARGS_ENTRY(pos, AT_BASE, args->base);
242 	AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
243 	AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
244 	AUXARGS_ENTRY(pos, AT_UID, imgp->proc->p_ucred->cr_ruid);
245 	AUXARGS_ENTRY(pos, AT_EUID, imgp->proc->p_ucred->cr_svuid);
246 	AUXARGS_ENTRY(pos, AT_GID, imgp->proc->p_ucred->cr_rgid);
247 	AUXARGS_ENTRY(pos, AT_EGID, imgp->proc->p_ucred->cr_svgid);
248 	AUXARGS_ENTRY(pos, LINUX_AT_SECURE, issetugid);
249 	AUXARGS_ENTRY_PTR(pos, LINUX_AT_RANDOM, imgp->canary);
250 	AUXARGS_ENTRY(pos, LINUX_AT_HWCAP2, 0);
251 	if (imgp->execpathp != 0)
252 		AUXARGS_ENTRY_PTR(pos, LINUX_AT_EXECFN, imgp->execpathp);
253 	if (args->execfd != -1)
254 		AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
255 	AUXARGS_ENTRY(pos, LINUX_AT_PLATFORM, PTROUT(linux_platform));
256 	AUXARGS_ENTRY(pos, AT_NULL, 0);
257 
258 	free(imgp->auxargs, M_TEMP);
259 	imgp->auxargs = NULL;
260 	KASSERT(pos - argarray <= LINUX_AT_COUNT, ("Too many auxargs"));
261 
262 	error = copyout(argarray, (void *)base,
263 	    sizeof(*argarray) * LINUX_AT_COUNT);
264 	free(argarray, M_TEMP);
265 	return (error);
266 }
267 
268 /*
269  * Reset registers to default values on exec.
270  */
271 static void
272 linux_exec_setregs(struct thread *td, struct image_params *imgp,
273     uintptr_t stack)
274 {
275 	struct trapframe *regs;
276 	struct pcb *pcb;
277 	register_t saved_rflags;
278 
279 	regs = td->td_frame;
280 	pcb = td->td_pcb;
281 
282 	if (td->td_proc->p_md.md_ldt != NULL)
283 		user_ldt_free(td);
284 
285 	pcb->pcb_fsbase = 0;
286 	pcb->pcb_gsbase = 0;
287 	clear_pcb_flags(pcb, PCB_32BIT);
288 	pcb->pcb_initial_fpucw = __LINUX_NPXCW__;
289 	set_pcb_flags(pcb, PCB_FULL_IRET);
290 
291 	saved_rflags = regs->tf_rflags & PSL_T;
292 	bzero((char *)regs, sizeof(struct trapframe));
293 	regs->tf_rip = imgp->entry_addr;
294 	regs->tf_rsp = stack;
295 	regs->tf_rflags = PSL_USER | saved_rflags;
296 	regs->tf_ss = _udatasel;
297 	regs->tf_cs = _ucodesel;
298 	regs->tf_ds = _udatasel;
299 	regs->tf_es = _udatasel;
300 	regs->tf_fs = _ufssel;
301 	regs->tf_gs = _ugssel;
302 	regs->tf_flags = TF_HASSEGS;
303 
304 	x86_clear_dbregs(pcb);
305 
306 	/*
307 	 * Drop the FP state if we hold it, so that the process gets a
308 	 * clean FP state if it uses the FPU again.
309 	 */
310 	fpstate_drop(td);
311 }
312 
313 /*
314  * Copied from amd64/amd64/machdep.c
315  */
316 int
317 linux_rt_sigreturn(struct thread *td, struct linux_rt_sigreturn_args *args)
318 {
319 	struct proc *p;
320 	struct l_rt_sigframe sf;
321 	struct l_sigcontext *context;
322 	struct trapframe *regs;
323 	mcontext_t mc;
324 	unsigned long rflags;
325 	sigset_t bmask;
326 	int error, i;
327 	ksiginfo_t ksi;
328 
329 	regs = td->td_frame;
330 	error = copyin((void *)regs->tf_rbx, &sf, sizeof(sf));
331 	if (error != 0)
332 		return (error);
333 
334 	p = td->td_proc;
335 	context = &sf.sf_uc.uc_mcontext;
336 	rflags = context->sc_rflags;
337 
338 	/*
339 	 * Don't allow users to change privileged or reserved flags.
340 	 */
341 	/*
342 	 * XXX do allow users to change the privileged flag PSL_RF.
343 	 * The cpu sets PSL_RF in tf_rflags for faults.  Debuggers
344 	 * should sometimes set it there too.  tf_rflags is kept in
345 	 * the signal context during signal handling and there is no
346 	 * other place to remember it, so the PSL_RF bit may be
347 	 * corrupted by the signal handler without us knowing.
348 	 * Corruption of the PSL_RF bit at worst causes one more or
349 	 * one less debugger trap, so allowing it is fairly harmless.
350 	 */
351 	if (!EFL_SECURE(rflags & ~PSL_RF, regs->tf_rflags & ~PSL_RF)) {
352 		uprintf("pid %d comm %s linux mangled rflags %#lx\n",
353 		    p->p_pid, p->p_comm, rflags);
354 		return (EINVAL);
355 	}
356 
357 	/*
358 	 * Don't allow users to load a valid privileged %cs.  Let the
359 	 * hardware check for invalid selectors, excess privilege in
360 	 * other selectors, invalid %eip's and invalid %esp's.
361 	 */
362 	if (!CS_SECURE(context->sc_cs)) {
363 		uprintf("pid %d comm %s linux mangled cs %#x\n",
364 		    p->p_pid, p->p_comm, context->sc_cs);
365 		ksiginfo_init_trap(&ksi);
366 		ksi.ksi_signo = SIGBUS;
367 		ksi.ksi_code = BUS_OBJERR;
368 		ksi.ksi_trapno = T_PROTFLT;
369 		ksi.ksi_addr = (void *)regs->tf_rip;
370 		trapsignal(td, &ksi);
371 		return (EINVAL);
372 	}
373 
374 	linux_to_bsd_sigset(&sf.sf_uc.uc_sigmask, &bmask);
375 	kern_sigprocmask(td, SIG_SETMASK, &bmask, NULL, 0);
376 
377 	regs->tf_rdi    = context->sc_rdi;
378 	regs->tf_rsi    = context->sc_rsi;
379 	regs->tf_rdx    = context->sc_rdx;
380 	regs->tf_rbp    = context->sc_rbp;
381 	regs->tf_rbx    = context->sc_rbx;
382 	regs->tf_rcx    = context->sc_rcx;
383 	regs->tf_rax    = context->sc_rax;
384 	regs->tf_rip    = context->sc_rip;
385 	regs->tf_rsp    = context->sc_rsp;
386 	regs->tf_r8     = context->sc_r8;
387 	regs->tf_r9     = context->sc_r9;
388 	regs->tf_r10    = context->sc_r10;
389 	regs->tf_r11    = context->sc_r11;
390 	regs->tf_r12    = context->sc_r12;
391 	regs->tf_r13    = context->sc_r13;
392 	regs->tf_r14    = context->sc_r14;
393 	regs->tf_r15    = context->sc_r15;
394 	regs->tf_cs     = context->sc_cs;
395 	regs->tf_err    = context->sc_err;
396 	regs->tf_rflags = rflags;
397 
398 	if (sf.sf_uc.uc_mcontext.sc_fpstate != NULL) {
399 		struct savefpu *svfp = (struct savefpu *)mc.mc_fpstate;
400 
401 		bzero(&mc, sizeof(mc));
402 		mc.mc_ownedfp = _MC_FPOWNED_FPU;
403 		mc.mc_fpformat = _MC_FPFMT_XMM;
404 
405 		svfp->sv_env.en_cw = sf.sf_fs.cwd;
406 		svfp->sv_env.en_sw = sf.sf_fs.swd;
407 		svfp->sv_env.en_tw = sf.sf_fs.twd;
408 		svfp->sv_env.en_opcode = sf.sf_fs.fop;
409 		svfp->sv_env.en_rip = sf.sf_fs.rip;
410 		svfp->sv_env.en_rdp = sf.sf_fs.rdp;
411 		svfp->sv_env.en_mxcsr = sf.sf_fs.mxcsr;
412 		svfp->sv_env.en_mxcsr_mask = sf.sf_fs.mxcsr_mask;
413 		/* FPU registers */
414 		for (i = 0; i < nitems(svfp->sv_fp); ++i)
415 			bcopy(&sf.sf_fs.st[i], svfp->sv_fp[i].fp_acc.fp_bytes,
416 			    sizeof(svfp->sv_fp[i].fp_acc.fp_bytes));
417 		/* SSE registers */
418 		for (i = 0; i < nitems(svfp->sv_xmm); ++i)
419 			bcopy(&sf.sf_fs.xmm[i], svfp->sv_xmm[i].xmm_bytes,
420 			    sizeof(svfp->sv_xmm[i].xmm_bytes));
421 		error = set_fpcontext(td, &mc, NULL, 0);
422 		if (error != 0) {
423 			uprintf("pid %d comm %s linux can't restore fpu state %d\n",
424 			    p->p_pid, p->p_comm, error);
425 			return (error);
426 		}
427 	}
428 
429 	set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
430 	return (EJUSTRETURN);
431 }
432 
433 /*
434  * copied from amd64/amd64/machdep.c
435  *
436  * Send an interrupt to process.
437  */
438 static void
439 linux_rt_sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
440 {
441 	struct l_rt_sigframe sf, *sfp;
442 	struct proc *p;
443 	struct thread *td;
444 	struct sigacts *psp;
445 	caddr_t sp;
446 	struct trapframe *regs;
447 	struct savefpu *svfp;
448 	mcontext_t mc;
449 	int sig, code;
450 	int oonstack, issiginfo, i;
451 
452 	td = curthread;
453 	p = td->td_proc;
454 	PROC_LOCK_ASSERT(p, MA_OWNED);
455 	sig = linux_translate_traps(ksi->ksi_signo, ksi->ksi_trapno);
456 	psp = p->p_sigacts;
457 	issiginfo = SIGISMEMBER(psp->ps_siginfo, sig);
458 	code = ksi->ksi_code;
459 	mtx_assert(&psp->ps_mtx, MA_OWNED);
460 	regs = td->td_frame;
461 	oonstack = sigonstack(regs->tf_rsp);
462 
463 	LINUX_CTR4(rt_sendsig, "%p, %d, %p, %u",
464 	    catcher, sig, mask, code);
465 
466 	bzero(&sf, sizeof(sf));
467 	sf.sf_uc.uc_stack.ss_sp = PTROUT(td->td_sigstk.ss_sp);
468 	sf.sf_uc.uc_stack.ss_size = td->td_sigstk.ss_size;
469 	sf.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK)
470 	    ? ((oonstack) ? LINUX_SS_ONSTACK : 0) : LINUX_SS_DISABLE;
471 
472 	/* Allocate space for the signal handler context. */
473 	if ((td->td_pflags & TDP_ALTSTACK) != 0 && !oonstack &&
474 	    SIGISMEMBER(psp->ps_sigonstack, sig)) {
475 		sp = (caddr_t)td->td_sigstk.ss_sp + td->td_sigstk.ss_size;
476 	} else
477 		sp = (caddr_t)regs->tf_rsp - 128;
478 
479 	mtx_unlock(&psp->ps_mtx);
480 	PROC_UNLOCK(p);
481 
482 	/* Make room, keeping the stack aligned. */
483 	sp -= sizeof(struct l_rt_sigframe);
484 	sfp = (struct l_rt_sigframe *)((unsigned long)sp & ~0xFul);
485 
486 	/* Save user context. */
487 	bsd_to_linux_sigset(mask, &sf.sf_uc.uc_sigmask);
488 	sf.sf_uc.uc_mcontext.sc_mask   = sf.sf_uc.uc_sigmask;
489 	sf.sf_uc.uc_mcontext.sc_rdi    = regs->tf_rdi;
490 	sf.sf_uc.uc_mcontext.sc_rsi    = regs->tf_rsi;
491 	sf.sf_uc.uc_mcontext.sc_rdx    = regs->tf_rdx;
492 	sf.sf_uc.uc_mcontext.sc_rbp    = regs->tf_rbp;
493 	sf.sf_uc.uc_mcontext.sc_rbx    = regs->tf_rbx;
494 	sf.sf_uc.uc_mcontext.sc_rcx    = regs->tf_rcx;
495 	sf.sf_uc.uc_mcontext.sc_rax    = regs->tf_rax;
496 	sf.sf_uc.uc_mcontext.sc_rip    = regs->tf_rip;
497 	sf.sf_uc.uc_mcontext.sc_rsp    = regs->tf_rsp;
498 	sf.sf_uc.uc_mcontext.sc_r8     = regs->tf_r8;
499 	sf.sf_uc.uc_mcontext.sc_r9     = regs->tf_r9;
500 	sf.sf_uc.uc_mcontext.sc_r10    = regs->tf_r10;
501 	sf.sf_uc.uc_mcontext.sc_r11    = regs->tf_r11;
502 	sf.sf_uc.uc_mcontext.sc_r12    = regs->tf_r12;
503 	sf.sf_uc.uc_mcontext.sc_r13    = regs->tf_r13;
504 	sf.sf_uc.uc_mcontext.sc_r14    = regs->tf_r14;
505 	sf.sf_uc.uc_mcontext.sc_r15    = regs->tf_r15;
506 	sf.sf_uc.uc_mcontext.sc_cs     = regs->tf_cs;
507 	sf.sf_uc.uc_mcontext.sc_rflags = regs->tf_rflags;
508 	sf.sf_uc.uc_mcontext.sc_err    = regs->tf_err;
509 	sf.sf_uc.uc_mcontext.sc_trapno = bsd_to_linux_trapcode(code);
510 	sf.sf_uc.uc_mcontext.sc_cr2    = (register_t)ksi->ksi_addr;
511 
512 	get_fpcontext(td, &mc, NULL, NULL);
513 	KASSERT(mc.mc_fpformat != _MC_FPFMT_NODEV, ("fpu not present"));
514 	svfp = (struct savefpu *)mc.mc_fpstate;
515 
516 	sf.sf_fs.cwd = svfp->sv_env.en_cw;
517 	sf.sf_fs.swd = svfp->sv_env.en_sw;
518 	sf.sf_fs.twd = svfp->sv_env.en_tw;
519 	sf.sf_fs.fop = svfp->sv_env.en_opcode;
520 	sf.sf_fs.rip = svfp->sv_env.en_rip;
521 	sf.sf_fs.rdp = svfp->sv_env.en_rdp;
522 	sf.sf_fs.mxcsr = svfp->sv_env.en_mxcsr;
523 	sf.sf_fs.mxcsr_mask = svfp->sv_env.en_mxcsr_mask;
524 	/* FPU registers */
525 	for (i = 0; i < nitems(svfp->sv_fp); ++i)
526 		bcopy(svfp->sv_fp[i].fp_acc.fp_bytes, &sf.sf_fs.st[i],
527 		    sizeof(svfp->sv_fp[i].fp_acc.fp_bytes));
528 	/* SSE registers */
529 	for (i = 0; i < nitems(svfp->sv_xmm); ++i)
530 		bcopy(svfp->sv_xmm[i].xmm_bytes, &sf.sf_fs.xmm[i],
531 		    sizeof(svfp->sv_xmm[i].xmm_bytes));
532 	sf.sf_uc.uc_mcontext.sc_fpstate = (struct l_fpstate *)((caddr_t)sfp +
533 	    offsetof(struct l_rt_sigframe, sf_fs));
534 
535 	/* Translate the signal. */
536 	sig = bsd_to_linux_signal(sig);
537 	/* Fill in POSIX parts. */
538 	siginfo_to_lsiginfo(&ksi->ksi_info, &sf.sf_si, sig);
539 
540 	/* Copy the sigframe out to the user's stack. */
541 	if (copyout(&sf, sfp, sizeof(*sfp)) != 0) {
542 		uprintf("pid %d comm %s has trashed its stack, killing\n",
543 		    p->p_pid, p->p_comm);
544 		PROC_LOCK(p);
545 		sigexit(td, SIGILL);
546 	}
547 
548 	fpstate_drop(td);
549 	/* Build the argument list for the signal handler. */
550 	regs->tf_rdi = sig;			/* arg 1 in %rdi */
551 	regs->tf_rax = 0;
552 	if (issiginfo) {
553 		regs->tf_rsi = (register_t)&sfp->sf_si;	/* arg 2 in %rsi */
554 		regs->tf_rdx = (register_t)&sfp->sf_uc;	/* arg 3 in %rdx */
555 	} else {
556 		regs->tf_rsi = 0;
557 		regs->tf_rdx = 0;
558 	}
559 	regs->tf_rcx = (register_t)catcher;
560 	regs->tf_rsp = (long)sfp;
561 	regs->tf_rip = linux_rt_sigcode;
562 	regs->tf_rflags &= ~(PSL_T | PSL_D);
563 	regs->tf_cs = _ucodesel;
564 	set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
565 	PROC_LOCK(p);
566 	mtx_lock(&psp->ps_mtx);
567 }
568 
569 #define	LINUX_VSYSCALL_START		(-10UL << 20)
570 #define	LINUX_VSYSCALL_SZ		1024
571 
572 const unsigned long linux_vsyscall_vector[] = {
573 	LINUX_SYS_gettimeofday,
574 	LINUX_SYS_linux_time,
575 	LINUX_SYS_linux_getcpu,
576 };
577 
578 static int
579 linux_vsyscall(struct thread *td)
580 {
581 	struct trapframe *frame;
582 	uint64_t retqaddr;
583 	int code, traced;
584 	int error;
585 
586 	frame = td->td_frame;
587 
588 	/* Check %rip for vsyscall area. */
589 	if (__predict_true(frame->tf_rip < LINUX_VSYSCALL_START))
590 		return (EINVAL);
591 	if ((frame->tf_rip & (LINUX_VSYSCALL_SZ - 1)) != 0)
592 		return (EINVAL);
593 	code = (frame->tf_rip - LINUX_VSYSCALL_START) / LINUX_VSYSCALL_SZ;
594 	if (code >= nitems(linux_vsyscall_vector))
595 		return (EINVAL);
596 
597 	/*
598 	 * vsyscall called as callq *(%rax), so we must
599 	 * use return address from %rsp and also fixup %rsp.
600 	 */
601 	error = copyin((void *)frame->tf_rsp, &retqaddr, sizeof(retqaddr));
602 	if (error)
603 		return (error);
604 
605 	frame->tf_rip = retqaddr;
606 	frame->tf_rax = linux_vsyscall_vector[code];
607 	frame->tf_rsp += 8;
608 
609 	traced = (frame->tf_flags & PSL_T);
610 
611 	amd64_syscall(td, traced);
612 
613 	return (0);
614 }
615 
616 struct sysentvec elf_linux_sysvec = {
617 	.sv_size	= LINUX_SYS_MAXSYSCALL,
618 	.sv_table	= linux_sysent,
619 	.sv_fixup	= __elfN(freebsd_fixup),
620 	.sv_sendsig	= linux_rt_sendsig,
621 	.sv_sigcode	= &_binary_linux_vdso_so_o_start,
622 	.sv_szsigcode	= &linux_szsigcode,
623 	.sv_name	= "Linux ELF64",
624 	.sv_coredump	= elf64_coredump,
625 	.sv_elf_core_osabi = ELFOSABI_NONE,
626 	.sv_elf_core_abi_vendor = LINUX_ABI_VENDOR,
627 	.sv_elf_core_prepare_notes = linux64_prepare_notes,
628 	.sv_imgact_try	= linux_exec_imgact_try,
629 	.sv_minsigstksz	= LINUX_MINSIGSTKSZ,
630 	.sv_minuser	= VM_MIN_ADDRESS,
631 	.sv_maxuser	= VM_MAXUSER_ADDRESS_LA48,
632 	.sv_usrstack	= LINUX_USRSTACK_LA48,
633 	.sv_psstrings	= LINUX_PS_STRINGS_LA48,
634 	.sv_psstringssz	= sizeof(struct ps_strings),
635 	.sv_stackprot	= VM_PROT_ALL,
636 	.sv_copyout_auxargs = linux_copyout_auxargs,
637 	.sv_copyout_strings = __linuxN(copyout_strings),
638 	.sv_setregs	= linux_exec_setregs,
639 	.sv_fixlimit	= NULL,
640 	.sv_maxssiz	= NULL,
641 	.sv_flags	= SV_ABI_LINUX | SV_LP64 | SV_SHP | SV_SIG_DISCIGN |
642 	    SV_SIG_WAITNDQ | SV_TIMEKEEP,
643 	.sv_set_syscall_retval = linux_set_syscall_retval,
644 	.sv_fetch_syscall_args = linux_fetch_syscall_args,
645 	.sv_syscallnames = linux_syscallnames,
646 	.sv_shared_page_base = LINUX_SHAREDPAGE_LA48,
647 	.sv_shared_page_len = PAGE_SIZE,
648 	.sv_schedtail	= linux_schedtail,
649 	.sv_thread_detach = linux_thread_detach,
650 	.sv_trap	= linux_vsyscall,
651 	.sv_onexec	= linux_on_exec_vmspace,
652 	.sv_onexit	= linux_on_exit,
653 	.sv_ontdexit	= linux_thread_dtor,
654 	.sv_setid_allowed = &linux_setid_allowed_query,
655 	.sv_set_fork_retval = linux_set_fork_retval,
656 };
657 
658 static int
659 linux_on_exec_vmspace(struct proc *p, struct image_params *imgp)
660 {
661 	int error;
662 
663 	error = linux_map_vdso(p, linux_vdso_obj, linux_vdso_base,
664 	    LINUX_VDSOPAGE_SIZE, imgp);
665 	if (error == 0)
666 		linux_on_exec(p, imgp);
667 	return (error);
668 }
669 
670 /*
671  * linux_vdso_install() and linux_exec_sysvec_init() must be called
672  * after exec_sysvec_init() which is SI_SUB_EXEC (SI_ORDER_ANY).
673  */
674 static void
675 linux_exec_sysvec_init(void *param)
676 {
677 	l_uintptr_t *ktimekeep_base, *ktsc_selector;
678 	struct sysentvec *sv;
679 	ptrdiff_t tkoff;
680 
681 	sv = param;
682 	amd64_lower_shared_page(sv);
683 	/* Fill timekeep_base */
684 	exec_sysvec_init(sv);
685 
686 	tkoff = kern_timekeep_base - linux_vdso_base;
687 	ktimekeep_base = (l_uintptr_t *)(linux_vdso_mapping + tkoff);
688 	*ktimekeep_base = sv->sv_shared_page_base + sv->sv_timekeep_offset;
689 
690 	tkoff = kern_tsc_selector - linux_vdso_base;
691 	ktsc_selector = (l_uintptr_t *)(linux_vdso_mapping + tkoff);
692 	*ktsc_selector = linux_vdso_tsc_selector_idx();
693 	if (bootverbose)
694 		printf("Linux x86-64 vDSO tsc_selector: %lu\n", *ktsc_selector);
695 
696 	tkoff = kern_cpu_selector - linux_vdso_base;
697 	ktsc_selector = (l_uintptr_t *)(linux_vdso_mapping + tkoff);
698 	*ktsc_selector = linux_vdso_cpu_selector_idx();
699 	if (bootverbose)
700 		printf("Linux x86-64 vDSO cpu_selector: %lu\n", *ktsc_selector);
701 }
702 SYSINIT(elf_linux_exec_sysvec_init, SI_SUB_EXEC + 1, SI_ORDER_ANY,
703     linux_exec_sysvec_init, &elf_linux_sysvec);
704 
705 static void
706 linux_vdso_install(const void *param)
707 {
708 	char *vdso_start = &_binary_linux_vdso_so_o_start;
709 	char *vdso_end = &_binary_linux_vdso_so_o_end;
710 
711 	linux_szsigcode = vdso_end - vdso_start;
712 	MPASS(linux_szsigcode <= LINUX_VDSOPAGE_SIZE);
713 
714 	linux_vdso_base = LINUX_VDSOPAGE_LA48;
715 	if (hw_lower_amd64_sharedpage != 0)
716 		linux_vdso_base -= PAGE_SIZE;
717 
718 	__elfN(linux_vdso_fixup)(vdso_start, linux_vdso_base);
719 
720 	linux_vdso_obj = __elfN(linux_shared_page_init)
721 	    (&linux_vdso_mapping, LINUX_VDSOPAGE_SIZE);
722 	bcopy(vdso_start, linux_vdso_mapping, linux_szsigcode);
723 
724 	linux_vdso_reloc(linux_vdso_mapping, linux_vdso_base);
725 }
726 SYSINIT(elf_linux_vdso_init, SI_SUB_EXEC + 1, SI_ORDER_FIRST,
727     linux_vdso_install, NULL);
728 
729 static void
730 linux_vdso_deinstall(const void *param)
731 {
732 
733 	__elfN(linux_shared_page_fini)(linux_vdso_obj,
734 	    linux_vdso_mapping, LINUX_VDSOPAGE_SIZE);
735 }
736 SYSUNINIT(elf_linux_vdso_uninit, SI_SUB_EXEC, SI_ORDER_FIRST,
737     linux_vdso_deinstall, NULL);
738 
739 static void
740 linux_vdso_reloc(char *mapping, Elf_Addr offset)
741 {
742 	const Elf_Ehdr *ehdr;
743 	const Elf_Shdr *shdr;
744 	Elf64_Addr *where, val;
745 	Elf_Size rtype, symidx;
746 	const Elf_Rela *rela;
747 	Elf_Addr addr, addend;
748 	int relacnt;
749 	int i, j;
750 
751 	MPASS(offset != 0);
752 
753 	relacnt = 0;
754 	ehdr = (const Elf_Ehdr *)mapping;
755 	shdr = (const Elf_Shdr *)(mapping + ehdr->e_shoff);
756 	for (i = 0; i < ehdr->e_shnum; i++)
757 	{
758 		switch (shdr[i].sh_type) {
759 		case SHT_REL:
760 			printf("Linux x86_64 vDSO: unexpected Rel section\n");
761 			break;
762 		case SHT_RELA:
763 			rela = (const Elf_Rela *)(mapping + shdr[i].sh_offset);
764 			relacnt = shdr[i].sh_size / sizeof(*rela);
765 		}
766 	}
767 
768 	for (j = 0; j < relacnt; j++, rela++) {
769 		where = (Elf_Addr *)(mapping + rela->r_offset);
770 		addend = rela->r_addend;
771 		rtype = ELF_R_TYPE(rela->r_info);
772 		symidx = ELF_R_SYM(rela->r_info);
773 
774 		switch (rtype) {
775 		case R_X86_64_NONE:	/* none */
776 			break;
777 
778 		case R_X86_64_RELATIVE:	/* B + A */
779 			addr = (Elf_Addr)(offset + addend);
780 			val = addr;
781 			if (*where != val)
782 				*where = val;
783 			break;
784 		case R_X86_64_IRELATIVE:
785 			printf("Linux x86_64 vDSO: unexpected ifunc relocation, "
786 			    "symbol index %ld\n", symidx);
787 			break;
788 		default:
789 			printf("Linux x86_64 vDSO: unexpected relocation type %ld, "
790 			    "symbol index %ld\n", rtype, symidx);
791 		}
792 	}
793 }
794 
795 static Elf_Brandnote linux64_brandnote = {
796 	.hdr.n_namesz	= sizeof(GNU_ABI_VENDOR),
797 	.hdr.n_descsz	= 16,
798 	.hdr.n_type	= 1,
799 	.vendor		= GNU_ABI_VENDOR,
800 	.flags		= BN_TRANSLATE_OSREL,
801 	.trans_osrel	= linux_trans_osrel
802 };
803 
804 static Elf64_Brandinfo linux_glibc2brand = {
805 	.brand		= ELFOSABI_LINUX,
806 	.machine	= EM_X86_64,
807 	.compat_3_brand	= "Linux",
808 	.emul_path	= linux_emul_path,
809 	.interp_path	= "/lib64/ld-linux-x86-64.so.2",
810 	.sysvec		= &elf_linux_sysvec,
811 	.interp_newpath	= NULL,
812 	.brand_note	= &linux64_brandnote,
813 	.flags		= BI_CAN_EXEC_DYN | BI_BRAND_NOTE
814 };
815 
816 static Elf64_Brandinfo linux_glibc2brandshort = {
817 	.brand		= ELFOSABI_LINUX,
818 	.machine	= EM_X86_64,
819 	.compat_3_brand	= "Linux",
820 	.emul_path	= linux_emul_path,
821 	.interp_path	= "/lib64/ld-linux.so.2",
822 	.sysvec		= &elf_linux_sysvec,
823 	.interp_newpath	= NULL,
824 	.brand_note	= &linux64_brandnote,
825 	.flags		= BI_CAN_EXEC_DYN | BI_BRAND_NOTE
826 };
827 
828 static Elf64_Brandinfo linux_muslbrand = {
829 	.brand		= ELFOSABI_LINUX,
830 	.machine	= EM_X86_64,
831 	.compat_3_brand	= "Linux",
832 	.emul_path	= linux_emul_path,
833 	.interp_path	= "/lib/ld-musl-x86_64.so.1",
834 	.sysvec		= &elf_linux_sysvec,
835 	.interp_newpath	= NULL,
836 	.brand_note	= &linux64_brandnote,
837 	.flags		= BI_CAN_EXEC_DYN | BI_BRAND_NOTE |
838 			    LINUX_BI_FUTEX_REQUEUE
839 };
840 
841 Elf64_Brandinfo *linux_brandlist[] = {
842 	&linux_glibc2brand,
843 	&linux_glibc2brandshort,
844 	&linux_muslbrand,
845 	NULL
846 };
847 
848 static int
849 linux64_elf_modevent(module_t mod, int type, void *data)
850 {
851 	Elf64_Brandinfo **brandinfo;
852 	int error;
853 	struct linux_ioctl_handler **lihp;
854 
855 	error = 0;
856 
857 	switch(type) {
858 	case MOD_LOAD:
859 		for (brandinfo = &linux_brandlist[0]; *brandinfo != NULL;
860 		     ++brandinfo)
861 			if (elf64_insert_brand_entry(*brandinfo) < 0)
862 				error = EINVAL;
863 		if (error == 0) {
864 			SET_FOREACH(lihp, linux_ioctl_handler_set)
865 				linux_ioctl_register_handler(*lihp);
866 			stclohz = (stathz ? stathz : hz);
867 			if (bootverbose)
868 				printf("Linux x86-64 ELF exec handler installed\n");
869 		} else
870 			printf("cannot insert Linux x86-64 ELF brand handler\n");
871 		break;
872 	case MOD_UNLOAD:
873 		for (brandinfo = &linux_brandlist[0]; *brandinfo != NULL;
874 		     ++brandinfo)
875 			if (elf64_brand_inuse(*brandinfo))
876 				error = EBUSY;
877 		if (error == 0) {
878 			for (brandinfo = &linux_brandlist[0];
879 			     *brandinfo != NULL; ++brandinfo)
880 				if (elf64_remove_brand_entry(*brandinfo) < 0)
881 					error = EINVAL;
882 		}
883 		if (error == 0) {
884 			SET_FOREACH(lihp, linux_ioctl_handler_set)
885 				linux_ioctl_unregister_handler(*lihp);
886 			if (bootverbose)
887 				printf("Linux x86_64 ELF exec handler removed\n");
888 		} else
889 			printf("Could not deinstall Linux x86_64 ELF interpreter entry\n");
890 		break;
891 	default:
892 		return (EOPNOTSUPP);
893 	}
894 	return (error);
895 }
896 
897 static moduledata_t linux64_elf_mod = {
898 	"linux64elf",
899 	linux64_elf_modevent,
900 	0
901 };
902 
903 DECLARE_MODULE_TIED(linux64elf, linux64_elf_mod, SI_SUB_EXEC, SI_ORDER_ANY);
904 MODULE_DEPEND(linux64elf, linux_common, 1, 1, 1);
905 FEATURE(linux64, "Linux 64bit support");
906