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