xref: /freebsd/sys/compat/linux/linux_misc.c (revision 89cb50c93385bb5d46f57839cf5ebe905ea61a69)
1 /*-
2  * Copyright (c) 2002 Doug Rabson
3  * Copyright (c) 1994-1995 Søren Schmidt
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer
11  *    in this position and unchanged.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. The name of the author may not be used to endorse or promote products
16  *    derived from this software without specific prior written permission
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include "opt_compat.h"
34 #if defined(KLD_MODULE)
35 #include "opt_global.h"
36 #endif
37 
38 #include <sys/param.h>
39 #include <sys/blist.h>
40 #include <sys/fcntl.h>
41 #if defined(__i386__)
42 #include <sys/imgact_aout.h>
43 #endif
44 #include <sys/jail.h>
45 #include <sys/kernel.h>
46 #include <sys/limits.h>
47 #include <sys/lock.h>
48 #include <sys/malloc.h>
49 #include <sys/mman.h>
50 #include <sys/mount.h>
51 #include <sys/mutex.h>
52 #include <sys/namei.h>
53 #include <sys/priv.h>
54 #include <sys/proc.h>
55 #include <sys/reboot.h>
56 #include <sys/racct.h>
57 #include <sys/random.h>
58 #include <sys/resourcevar.h>
59 #include <sys/sched.h>
60 #include <sys/sdt.h>
61 #include <sys/signalvar.h>
62 #include <sys/stat.h>
63 #include <sys/syscallsubr.h>
64 #include <sys/sysctl.h>
65 #include <sys/sysproto.h>
66 #include <sys/systm.h>
67 #include <sys/time.h>
68 #include <sys/vmmeter.h>
69 #include <sys/vnode.h>
70 #include <sys/wait.h>
71 #include <sys/cpuset.h>
72 #include <sys/uio.h>
73 
74 #include <security/mac/mac_framework.h>
75 
76 #include <vm/vm.h>
77 #include <vm/pmap.h>
78 #include <vm/vm_kern.h>
79 #include <vm/vm_map.h>
80 #include <vm/vm_extern.h>
81 #include <vm/vm_object.h>
82 #include <vm/swap_pager.h>
83 
84 #ifdef COMPAT_LINUX32
85 #include <machine/../linux32/linux.h>
86 #include <machine/../linux32/linux32_proto.h>
87 #else
88 #include <machine/../linux/linux.h>
89 #include <machine/../linux/linux_proto.h>
90 #endif
91 
92 #include <compat/linux/linux_dtrace.h>
93 #include <compat/linux/linux_file.h>
94 #include <compat/linux/linux_mib.h>
95 #include <compat/linux/linux_signal.h>
96 #include <compat/linux/linux_timer.h>
97 #include <compat/linux/linux_util.h>
98 #include <compat/linux/linux_sysproto.h>
99 #include <compat/linux/linux_emul.h>
100 #include <compat/linux/linux_misc.h>
101 
102 /**
103  * Special DTrace provider for the linuxulator.
104  *
105  * In this file we define the provider for the entire linuxulator. All
106  * modules (= files of the linuxulator) use it.
107  *
108  * We define a different name depending on the emulated bitsize, see
109  * ../../<ARCH>/linux{,32}/linux.h, e.g.:
110  *      native bitsize          = linuxulator
111  *      amd64, 32bit emulation  = linuxulator32
112  */
113 LIN_SDT_PROVIDER_DEFINE(LINUX_DTRACE);
114 
115 int stclohz;				/* Statistics clock frequency */
116 
117 static unsigned int linux_to_bsd_resource[LINUX_RLIM_NLIMITS] = {
118 	RLIMIT_CPU, RLIMIT_FSIZE, RLIMIT_DATA, RLIMIT_STACK,
119 	RLIMIT_CORE, RLIMIT_RSS, RLIMIT_NPROC, RLIMIT_NOFILE,
120 	RLIMIT_MEMLOCK, RLIMIT_AS
121 };
122 
123 struct l_sysinfo {
124 	l_long		uptime;		/* Seconds since boot */
125 	l_ulong		loads[3];	/* 1, 5, and 15 minute load averages */
126 #define LINUX_SYSINFO_LOADS_SCALE 65536
127 	l_ulong		totalram;	/* Total usable main memory size */
128 	l_ulong		freeram;	/* Available memory size */
129 	l_ulong		sharedram;	/* Amount of shared memory */
130 	l_ulong		bufferram;	/* Memory used by buffers */
131 	l_ulong		totalswap;	/* Total swap space size */
132 	l_ulong		freeswap;	/* swap space still available */
133 	l_ushort	procs;		/* Number of current processes */
134 	l_ushort	pads;
135 	l_ulong		totalbig;
136 	l_ulong		freebig;
137 	l_uint		mem_unit;
138 	char		_f[20-2*sizeof(l_long)-sizeof(l_int)];	/* padding */
139 };
140 
141 struct l_pselect6arg {
142 	l_uintptr_t	ss;
143 	l_size_t	ss_len;
144 };
145 
146 static int	linux_utimensat_nsec_valid(l_long);
147 
148 
149 int
150 linux_sysinfo(struct thread *td, struct linux_sysinfo_args *args)
151 {
152 	struct l_sysinfo sysinfo;
153 	vm_object_t object;
154 	int i, j;
155 	struct timespec ts;
156 
157 	bzero(&sysinfo, sizeof(sysinfo));
158 	getnanouptime(&ts);
159 	if (ts.tv_nsec != 0)
160 		ts.tv_sec++;
161 	sysinfo.uptime = ts.tv_sec;
162 
163 	/* Use the information from the mib to get our load averages */
164 	for (i = 0; i < 3; i++)
165 		sysinfo.loads[i] = averunnable.ldavg[i] *
166 		    LINUX_SYSINFO_LOADS_SCALE / averunnable.fscale;
167 
168 	sysinfo.totalram = physmem * PAGE_SIZE;
169 	sysinfo.freeram = sysinfo.totalram - vm_cnt.v_wire_count * PAGE_SIZE;
170 
171 	sysinfo.sharedram = 0;
172 	mtx_lock(&vm_object_list_mtx);
173 	TAILQ_FOREACH(object, &vm_object_list, object_list)
174 		if (object->shadow_count > 1)
175 			sysinfo.sharedram += object->resident_page_count;
176 	mtx_unlock(&vm_object_list_mtx);
177 
178 	sysinfo.sharedram *= PAGE_SIZE;
179 	sysinfo.bufferram = 0;
180 
181 	swap_pager_status(&i, &j);
182 	sysinfo.totalswap = i * PAGE_SIZE;
183 	sysinfo.freeswap = (i - j) * PAGE_SIZE;
184 
185 	sysinfo.procs = nprocs;
186 
187 	/* The following are only present in newer Linux kernels. */
188 	sysinfo.totalbig = 0;
189 	sysinfo.freebig = 0;
190 	sysinfo.mem_unit = 1;
191 
192 	return (copyout(&sysinfo, args->info, sizeof(sysinfo)));
193 }
194 
195 int
196 linux_alarm(struct thread *td, struct linux_alarm_args *args)
197 {
198 	struct itimerval it, old_it;
199 	u_int secs;
200 	int error;
201 
202 #ifdef DEBUG
203 	if (ldebug(alarm))
204 		printf(ARGS(alarm, "%u"), args->secs);
205 #endif
206 	secs = args->secs;
207 	/*
208 	 * Linux alarm() is always successful. Limit secs to INT32_MAX / 2
209 	 * to match kern_setitimer()'s limit to avoid error from it.
210 	 *
211 	 * XXX. Linux limit secs to INT_MAX on 32 and does not limit on 64-bit
212 	 * platforms.
213 	 */
214 	if (secs > INT32_MAX / 2)
215 		secs = INT32_MAX / 2;
216 
217 	it.it_value.tv_sec = secs;
218 	it.it_value.tv_usec = 0;
219 	timevalclear(&it.it_interval);
220 	error = kern_setitimer(td, ITIMER_REAL, &it, &old_it);
221 	KASSERT(error == 0, ("kern_setitimer returns %d", error));
222 
223 	if ((old_it.it_value.tv_sec == 0 && old_it.it_value.tv_usec > 0) ||
224 	    old_it.it_value.tv_usec >= 500000)
225 		old_it.it_value.tv_sec++;
226 	td->td_retval[0] = old_it.it_value.tv_sec;
227 	return (0);
228 }
229 
230 int
231 linux_brk(struct thread *td, struct linux_brk_args *args)
232 {
233 	struct vmspace *vm = td->td_proc->p_vmspace;
234 	vm_offset_t new, old;
235 	struct obreak_args /* {
236 		char * nsize;
237 	} */ tmp;
238 
239 #ifdef DEBUG
240 	if (ldebug(brk))
241 		printf(ARGS(brk, "%p"), (void *)(uintptr_t)args->dsend);
242 #endif
243 	old = (vm_offset_t)vm->vm_daddr + ctob(vm->vm_dsize);
244 	new = (vm_offset_t)args->dsend;
245 	tmp.nsize = (char *)new;
246 	if (((caddr_t)new > vm->vm_daddr) && !sys_obreak(td, &tmp))
247 		td->td_retval[0] = (long)new;
248 	else
249 		td->td_retval[0] = (long)old;
250 
251 	return (0);
252 }
253 
254 #if defined(__i386__)
255 /* XXX: what about amd64/linux32? */
256 
257 int
258 linux_uselib(struct thread *td, struct linux_uselib_args *args)
259 {
260 	struct nameidata ni;
261 	struct vnode *vp;
262 	struct exec *a_out;
263 	struct vattr attr;
264 	vm_offset_t vmaddr;
265 	unsigned long file_offset;
266 	unsigned long bss_size;
267 	char *library;
268 	ssize_t aresid;
269 	int error, locked, writecount;
270 
271 	LCONVPATHEXIST(td, args->library, &library);
272 
273 #ifdef DEBUG
274 	if (ldebug(uselib))
275 		printf(ARGS(uselib, "%s"), library);
276 #endif
277 
278 	a_out = NULL;
279 	locked = 0;
280 	vp = NULL;
281 
282 	NDINIT(&ni, LOOKUP, ISOPEN | FOLLOW | LOCKLEAF | AUDITVNODE1,
283 	    UIO_SYSSPACE, library, td);
284 	error = namei(&ni);
285 	LFREEPATH(library);
286 	if (error)
287 		goto cleanup;
288 
289 	vp = ni.ni_vp;
290 	NDFREE(&ni, NDF_ONLY_PNBUF);
291 
292 	/*
293 	 * From here on down, we have a locked vnode that must be unlocked.
294 	 * XXX: The code below largely duplicates exec_check_permissions().
295 	 */
296 	locked = 1;
297 
298 	/* Writable? */
299 	error = VOP_GET_WRITECOUNT(vp, &writecount);
300 	if (error != 0)
301 		goto cleanup;
302 	if (writecount != 0) {
303 		error = ETXTBSY;
304 		goto cleanup;
305 	}
306 
307 	/* Executable? */
308 	error = VOP_GETATTR(vp, &attr, td->td_ucred);
309 	if (error)
310 		goto cleanup;
311 
312 	if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
313 	    ((attr.va_mode & 0111) == 0) || (attr.va_type != VREG)) {
314 		/* EACCESS is what exec(2) returns. */
315 		error = ENOEXEC;
316 		goto cleanup;
317 	}
318 
319 	/* Sensible size? */
320 	if (attr.va_size == 0) {
321 		error = ENOEXEC;
322 		goto cleanup;
323 	}
324 
325 	/* Can we access it? */
326 	error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
327 	if (error)
328 		goto cleanup;
329 
330 	/*
331 	 * XXX: This should use vn_open() so that it is properly authorized,
332 	 * and to reduce code redundancy all over the place here.
333 	 * XXX: Not really, it duplicates far more of exec_check_permissions()
334 	 * than vn_open().
335 	 */
336 #ifdef MAC
337 	error = mac_vnode_check_open(td->td_ucred, vp, VREAD);
338 	if (error)
339 		goto cleanup;
340 #endif
341 	error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
342 	if (error)
343 		goto cleanup;
344 
345 	/* Pull in executable header into exec_map */
346 	error = vm_mmap(exec_map, (vm_offset_t *)&a_out, PAGE_SIZE,
347 	    VM_PROT_READ, VM_PROT_READ, 0, OBJT_VNODE, vp, 0);
348 	if (error)
349 		goto cleanup;
350 
351 	/* Is it a Linux binary ? */
352 	if (((a_out->a_magic >> 16) & 0xff) != 0x64) {
353 		error = ENOEXEC;
354 		goto cleanup;
355 	}
356 
357 	/*
358 	 * While we are here, we should REALLY do some more checks
359 	 */
360 
361 	/* Set file/virtual offset based on a.out variant. */
362 	switch ((int)(a_out->a_magic & 0xffff)) {
363 	case 0413:			/* ZMAGIC */
364 		file_offset = 1024;
365 		break;
366 	case 0314:			/* QMAGIC */
367 		file_offset = 0;
368 		break;
369 	default:
370 		error = ENOEXEC;
371 		goto cleanup;
372 	}
373 
374 	bss_size = round_page(a_out->a_bss);
375 
376 	/* Check various fields in header for validity/bounds. */
377 	if (a_out->a_text & PAGE_MASK || a_out->a_data & PAGE_MASK) {
378 		error = ENOEXEC;
379 		goto cleanup;
380 	}
381 
382 	/* text + data can't exceed file size */
383 	if (a_out->a_data + a_out->a_text > attr.va_size) {
384 		error = EFAULT;
385 		goto cleanup;
386 	}
387 
388 	/*
389 	 * text/data/bss must not exceed limits
390 	 * XXX - this is not complete. it should check current usage PLUS
391 	 * the resources needed by this library.
392 	 */
393 	PROC_LOCK(td->td_proc);
394 	if (a_out->a_text > maxtsiz ||
395 	    a_out->a_data + bss_size > lim_cur_proc(td->td_proc, RLIMIT_DATA) ||
396 	    racct_set(td->td_proc, RACCT_DATA, a_out->a_data +
397 	    bss_size) != 0) {
398 		PROC_UNLOCK(td->td_proc);
399 		error = ENOMEM;
400 		goto cleanup;
401 	}
402 	PROC_UNLOCK(td->td_proc);
403 
404 	/*
405 	 * Prevent more writers.
406 	 * XXX: Note that if any of the VM operations fail below we don't
407 	 * clear this flag.
408 	 */
409 	VOP_SET_TEXT(vp);
410 
411 	/*
412 	 * Lock no longer needed
413 	 */
414 	locked = 0;
415 	VOP_UNLOCK(vp, 0);
416 
417 	/*
418 	 * Check if file_offset page aligned. Currently we cannot handle
419 	 * misalinged file offsets, and so we read in the entire image
420 	 * (what a waste).
421 	 */
422 	if (file_offset & PAGE_MASK) {
423 #ifdef DEBUG
424 		printf("uselib: Non page aligned binary %lu\n", file_offset);
425 #endif
426 		/* Map text+data read/write/execute */
427 
428 		/* a_entry is the load address and is page aligned */
429 		vmaddr = trunc_page(a_out->a_entry);
430 
431 		/* get anon user mapping, read+write+execute */
432 		error = vm_map_find(&td->td_proc->p_vmspace->vm_map, NULL, 0,
433 		    &vmaddr, a_out->a_text + a_out->a_data, 0, VMFS_NO_SPACE,
434 		    VM_PROT_ALL, VM_PROT_ALL, 0);
435 		if (error)
436 			goto cleanup;
437 
438 		error = vn_rdwr(UIO_READ, vp, (void *)vmaddr, file_offset,
439 		    a_out->a_text + a_out->a_data, UIO_USERSPACE, 0,
440 		    td->td_ucred, NOCRED, &aresid, td);
441 		if (error != 0)
442 			goto cleanup;
443 		if (aresid != 0) {
444 			error = ENOEXEC;
445 			goto cleanup;
446 		}
447 	} else {
448 #ifdef DEBUG
449 		printf("uselib: Page aligned binary %lu\n", file_offset);
450 #endif
451 		/*
452 		 * for QMAGIC, a_entry is 20 bytes beyond the load address
453 		 * to skip the executable header
454 		 */
455 		vmaddr = trunc_page(a_out->a_entry);
456 
457 		/*
458 		 * Map it all into the process's space as a single
459 		 * copy-on-write "data" segment.
460 		 */
461 		error = vm_mmap(&td->td_proc->p_vmspace->vm_map, &vmaddr,
462 		    a_out->a_text + a_out->a_data, VM_PROT_ALL, VM_PROT_ALL,
463 		    MAP_PRIVATE | MAP_FIXED, OBJT_VNODE, vp, file_offset);
464 		if (error)
465 			goto cleanup;
466 	}
467 #ifdef DEBUG
468 	printf("mem=%08lx = %08lx %08lx\n", (long)vmaddr, ((long *)vmaddr)[0],
469 	    ((long *)vmaddr)[1]);
470 #endif
471 	if (bss_size != 0) {
472 		/* Calculate BSS start address */
473 		vmaddr = trunc_page(a_out->a_entry) + a_out->a_text +
474 		    a_out->a_data;
475 
476 		/* allocate some 'anon' space */
477 		error = vm_map_find(&td->td_proc->p_vmspace->vm_map, NULL, 0,
478 		    &vmaddr, bss_size, 0, VMFS_NO_SPACE, VM_PROT_ALL,
479 		    VM_PROT_ALL, 0);
480 		if (error)
481 			goto cleanup;
482 	}
483 
484 cleanup:
485 	/* Unlock vnode if needed */
486 	if (locked)
487 		VOP_UNLOCK(vp, 0);
488 
489 	/* Release the temporary mapping. */
490 	if (a_out)
491 		kmap_free_wakeup(exec_map, (vm_offset_t)a_out, PAGE_SIZE);
492 
493 	return (error);
494 }
495 
496 #endif	/* __i386__ */
497 
498 int
499 linux_select(struct thread *td, struct linux_select_args *args)
500 {
501 	l_timeval ltv;
502 	struct timeval tv0, tv1, utv, *tvp;
503 	int error;
504 
505 #ifdef DEBUG
506 	if (ldebug(select))
507 		printf(ARGS(select, "%d, %p, %p, %p, %p"), args->nfds,
508 		    (void *)args->readfds, (void *)args->writefds,
509 		    (void *)args->exceptfds, (void *)args->timeout);
510 #endif
511 
512 	/*
513 	 * Store current time for computation of the amount of
514 	 * time left.
515 	 */
516 	if (args->timeout) {
517 		if ((error = copyin(args->timeout, &ltv, sizeof(ltv))))
518 			goto select_out;
519 		utv.tv_sec = ltv.tv_sec;
520 		utv.tv_usec = ltv.tv_usec;
521 #ifdef DEBUG
522 		if (ldebug(select))
523 			printf(LMSG("incoming timeout (%jd/%ld)"),
524 			    (intmax_t)utv.tv_sec, utv.tv_usec);
525 #endif
526 
527 		if (itimerfix(&utv)) {
528 			/*
529 			 * The timeval was invalid.  Convert it to something
530 			 * valid that will act as it does under Linux.
531 			 */
532 			utv.tv_sec += utv.tv_usec / 1000000;
533 			utv.tv_usec %= 1000000;
534 			if (utv.tv_usec < 0) {
535 				utv.tv_sec -= 1;
536 				utv.tv_usec += 1000000;
537 			}
538 			if (utv.tv_sec < 0)
539 				timevalclear(&utv);
540 		}
541 		microtime(&tv0);
542 		tvp = &utv;
543 	} else
544 		tvp = NULL;
545 
546 	error = kern_select(td, args->nfds, args->readfds, args->writefds,
547 	    args->exceptfds, tvp, LINUX_NFDBITS);
548 
549 #ifdef DEBUG
550 	if (ldebug(select))
551 		printf(LMSG("real select returns %d"), error);
552 #endif
553 	if (error)
554 		goto select_out;
555 
556 	if (args->timeout) {
557 		if (td->td_retval[0]) {
558 			/*
559 			 * Compute how much time was left of the timeout,
560 			 * by subtracting the current time and the time
561 			 * before we started the call, and subtracting
562 			 * that result from the user-supplied value.
563 			 */
564 			microtime(&tv1);
565 			timevalsub(&tv1, &tv0);
566 			timevalsub(&utv, &tv1);
567 			if (utv.tv_sec < 0)
568 				timevalclear(&utv);
569 		} else
570 			timevalclear(&utv);
571 #ifdef DEBUG
572 		if (ldebug(select))
573 			printf(LMSG("outgoing timeout (%jd/%ld)"),
574 			    (intmax_t)utv.tv_sec, utv.tv_usec);
575 #endif
576 		ltv.tv_sec = utv.tv_sec;
577 		ltv.tv_usec = utv.tv_usec;
578 		if ((error = copyout(&ltv, args->timeout, sizeof(ltv))))
579 			goto select_out;
580 	}
581 
582 select_out:
583 #ifdef DEBUG
584 	if (ldebug(select))
585 		printf(LMSG("select_out -> %d"), error);
586 #endif
587 	return (error);
588 }
589 
590 int
591 linux_mremap(struct thread *td, struct linux_mremap_args *args)
592 {
593 	uintptr_t addr;
594 	size_t len;
595 	int error = 0;
596 
597 #ifdef DEBUG
598 	if (ldebug(mremap))
599 		printf(ARGS(mremap, "%p, %08lx, %08lx, %08lx"),
600 		    (void *)(uintptr_t)args->addr,
601 		    (unsigned long)args->old_len,
602 		    (unsigned long)args->new_len,
603 		    (unsigned long)args->flags);
604 #endif
605 
606 	if (args->flags & ~(LINUX_MREMAP_FIXED | LINUX_MREMAP_MAYMOVE)) {
607 		td->td_retval[0] = 0;
608 		return (EINVAL);
609 	}
610 
611 	/*
612 	 * Check for the page alignment.
613 	 * Linux defines PAGE_MASK to be FreeBSD ~PAGE_MASK.
614 	 */
615 	if (args->addr & PAGE_MASK) {
616 		td->td_retval[0] = 0;
617 		return (EINVAL);
618 	}
619 
620 	args->new_len = round_page(args->new_len);
621 	args->old_len = round_page(args->old_len);
622 
623 	if (args->new_len > args->old_len) {
624 		td->td_retval[0] = 0;
625 		return (ENOMEM);
626 	}
627 
628 	if (args->new_len < args->old_len) {
629 		addr = args->addr + args->new_len;
630 		len = args->old_len - args->new_len;
631 		error = kern_munmap(td, addr, len);
632 	}
633 
634 	td->td_retval[0] = error ? 0 : (uintptr_t)args->addr;
635 	return (error);
636 }
637 
638 #define LINUX_MS_ASYNC       0x0001
639 #define LINUX_MS_INVALIDATE  0x0002
640 #define LINUX_MS_SYNC        0x0004
641 
642 int
643 linux_msync(struct thread *td, struct linux_msync_args *args)
644 {
645 
646 	return (kern_msync(td, args->addr, args->len,
647 	    args->fl & ~LINUX_MS_SYNC));
648 }
649 
650 int
651 linux_time(struct thread *td, struct linux_time_args *args)
652 {
653 	struct timeval tv;
654 	l_time_t tm;
655 	int error;
656 
657 #ifdef DEBUG
658 	if (ldebug(time))
659 		printf(ARGS(time, "*"));
660 #endif
661 
662 	microtime(&tv);
663 	tm = tv.tv_sec;
664 	if (args->tm && (error = copyout(&tm, args->tm, sizeof(tm))))
665 		return (error);
666 	td->td_retval[0] = tm;
667 	return (0);
668 }
669 
670 struct l_times_argv {
671 	l_clock_t	tms_utime;
672 	l_clock_t	tms_stime;
673 	l_clock_t	tms_cutime;
674 	l_clock_t	tms_cstime;
675 };
676 
677 
678 /*
679  * Glibc versions prior to 2.2.1 always use hard-coded CLK_TCK value.
680  * Since 2.2.1 Glibc uses value exported from kernel via AT_CLKTCK
681  * auxiliary vector entry.
682  */
683 #define	CLK_TCK		100
684 
685 #define	CONVOTCK(r)	(r.tv_sec * CLK_TCK + r.tv_usec / (1000000 / CLK_TCK))
686 #define	CONVNTCK(r)	(r.tv_sec * stclohz + r.tv_usec / (1000000 / stclohz))
687 
688 #define	CONVTCK(r)	(linux_kernver(td) >= LINUX_KERNVER_2004000 ?		\
689 			    CONVNTCK(r) : CONVOTCK(r))
690 
691 int
692 linux_times(struct thread *td, struct linux_times_args *args)
693 {
694 	struct timeval tv, utime, stime, cutime, cstime;
695 	struct l_times_argv tms;
696 	struct proc *p;
697 	int error;
698 
699 #ifdef DEBUG
700 	if (ldebug(times))
701 		printf(ARGS(times, "*"));
702 #endif
703 
704 	if (args->buf != NULL) {
705 		p = td->td_proc;
706 		PROC_LOCK(p);
707 		PROC_STATLOCK(p);
708 		calcru(p, &utime, &stime);
709 		PROC_STATUNLOCK(p);
710 		calccru(p, &cutime, &cstime);
711 		PROC_UNLOCK(p);
712 
713 		tms.tms_utime = CONVTCK(utime);
714 		tms.tms_stime = CONVTCK(stime);
715 
716 		tms.tms_cutime = CONVTCK(cutime);
717 		tms.tms_cstime = CONVTCK(cstime);
718 
719 		if ((error = copyout(&tms, args->buf, sizeof(tms))))
720 			return (error);
721 	}
722 
723 	microuptime(&tv);
724 	td->td_retval[0] = (int)CONVTCK(tv);
725 	return (0);
726 }
727 
728 int
729 linux_newuname(struct thread *td, struct linux_newuname_args *args)
730 {
731 	struct l_new_utsname utsname;
732 	char osname[LINUX_MAX_UTSNAME];
733 	char osrelease[LINUX_MAX_UTSNAME];
734 	char *p;
735 
736 #ifdef DEBUG
737 	if (ldebug(newuname))
738 		printf(ARGS(newuname, "*"));
739 #endif
740 
741 	linux_get_osname(td, osname);
742 	linux_get_osrelease(td, osrelease);
743 
744 	bzero(&utsname, sizeof(utsname));
745 	strlcpy(utsname.sysname, osname, LINUX_MAX_UTSNAME);
746 	getcredhostname(td->td_ucred, utsname.nodename, LINUX_MAX_UTSNAME);
747 	getcreddomainname(td->td_ucred, utsname.domainname, LINUX_MAX_UTSNAME);
748 	strlcpy(utsname.release, osrelease, LINUX_MAX_UTSNAME);
749 	strlcpy(utsname.version, version, LINUX_MAX_UTSNAME);
750 	for (p = utsname.version; *p != '\0'; ++p)
751 		if (*p == '\n') {
752 			*p = '\0';
753 			break;
754 		}
755 	strlcpy(utsname.machine, linux_kplatform, LINUX_MAX_UTSNAME);
756 
757 	return (copyout(&utsname, args->buf, sizeof(utsname)));
758 }
759 
760 struct l_utimbuf {
761 	l_time_t l_actime;
762 	l_time_t l_modtime;
763 };
764 
765 int
766 linux_utime(struct thread *td, struct linux_utime_args *args)
767 {
768 	struct timeval tv[2], *tvp;
769 	struct l_utimbuf lut;
770 	char *fname;
771 	int error;
772 
773 	LCONVPATHEXIST(td, args->fname, &fname);
774 
775 #ifdef DEBUG
776 	if (ldebug(utime))
777 		printf(ARGS(utime, "%s, *"), fname);
778 #endif
779 
780 	if (args->times) {
781 		if ((error = copyin(args->times, &lut, sizeof lut))) {
782 			LFREEPATH(fname);
783 			return (error);
784 		}
785 		tv[0].tv_sec = lut.l_actime;
786 		tv[0].tv_usec = 0;
787 		tv[1].tv_sec = lut.l_modtime;
788 		tv[1].tv_usec = 0;
789 		tvp = tv;
790 	} else
791 		tvp = NULL;
792 
793 	error = kern_utimesat(td, AT_FDCWD, fname, UIO_SYSSPACE, tvp,
794 	    UIO_SYSSPACE);
795 	LFREEPATH(fname);
796 	return (error);
797 }
798 
799 int
800 linux_utimes(struct thread *td, struct linux_utimes_args *args)
801 {
802 	l_timeval ltv[2];
803 	struct timeval tv[2], *tvp = NULL;
804 	char *fname;
805 	int error;
806 
807 	LCONVPATHEXIST(td, args->fname, &fname);
808 
809 #ifdef DEBUG
810 	if (ldebug(utimes))
811 		printf(ARGS(utimes, "%s, *"), fname);
812 #endif
813 
814 	if (args->tptr != NULL) {
815 		if ((error = copyin(args->tptr, ltv, sizeof ltv))) {
816 			LFREEPATH(fname);
817 			return (error);
818 		}
819 		tv[0].tv_sec = ltv[0].tv_sec;
820 		tv[0].tv_usec = ltv[0].tv_usec;
821 		tv[1].tv_sec = ltv[1].tv_sec;
822 		tv[1].tv_usec = ltv[1].tv_usec;
823 		tvp = tv;
824 	}
825 
826 	error = kern_utimesat(td, AT_FDCWD, fname, UIO_SYSSPACE,
827 	    tvp, UIO_SYSSPACE);
828 	LFREEPATH(fname);
829 	return (error);
830 }
831 
832 static int
833 linux_utimensat_nsec_valid(l_long nsec)
834 {
835 
836 	if (nsec == LINUX_UTIME_OMIT || nsec == LINUX_UTIME_NOW)
837 		return (0);
838 	if (nsec >= 0 && nsec <= 999999999)
839 		return (0);
840 	return (1);
841 }
842 
843 int
844 linux_utimensat(struct thread *td, struct linux_utimensat_args *args)
845 {
846 	struct l_timespec l_times[2];
847 	struct timespec times[2], *timesp = NULL;
848 	char *path = NULL;
849 	int error, dfd, flags = 0;
850 
851 	dfd = (args->dfd == LINUX_AT_FDCWD) ? AT_FDCWD : args->dfd;
852 
853 #ifdef DEBUG
854 	if (ldebug(utimensat))
855 		printf(ARGS(utimensat, "%d, *"), dfd);
856 #endif
857 
858 	if (args->flags & ~LINUX_AT_SYMLINK_NOFOLLOW)
859 		return (EINVAL);
860 
861 	if (args->times != NULL) {
862 		error = copyin(args->times, l_times, sizeof(l_times));
863 		if (error != 0)
864 			return (error);
865 
866 		if (linux_utimensat_nsec_valid(l_times[0].tv_nsec) != 0 ||
867 		    linux_utimensat_nsec_valid(l_times[1].tv_nsec) != 0)
868 			return (EINVAL);
869 
870 		times[0].tv_sec = l_times[0].tv_sec;
871 		switch (l_times[0].tv_nsec)
872 		{
873 		case LINUX_UTIME_OMIT:
874 			times[0].tv_nsec = UTIME_OMIT;
875 			break;
876 		case LINUX_UTIME_NOW:
877 			times[0].tv_nsec = UTIME_NOW;
878 			break;
879 		default:
880 			times[0].tv_nsec = l_times[0].tv_nsec;
881 		}
882 
883 		times[1].tv_sec = l_times[1].tv_sec;
884 		switch (l_times[1].tv_nsec)
885 		{
886 		case LINUX_UTIME_OMIT:
887 			times[1].tv_nsec = UTIME_OMIT;
888 			break;
889 		case LINUX_UTIME_NOW:
890 			times[1].tv_nsec = UTIME_NOW;
891 			break;
892 		default:
893 			times[1].tv_nsec = l_times[1].tv_nsec;
894 			break;
895 		}
896 		timesp = times;
897 
898 		/* This breaks POSIX, but is what the Linux kernel does
899 		 * _on purpose_ (documented in the man page for utimensat(2)),
900 		 * so we must follow that behaviour. */
901 		if (times[0].tv_nsec == UTIME_OMIT &&
902 		    times[1].tv_nsec == UTIME_OMIT)
903 			return (0);
904 	}
905 
906 	if (args->pathname != NULL)
907 		LCONVPATHEXIST_AT(td, args->pathname, &path, dfd);
908 	else if (args->flags != 0)
909 		return (EINVAL);
910 
911 	if (args->flags & LINUX_AT_SYMLINK_NOFOLLOW)
912 		flags |= AT_SYMLINK_NOFOLLOW;
913 
914 	if (path == NULL)
915 		error = kern_futimens(td, dfd, timesp, UIO_SYSSPACE);
916 	else {
917 		error = kern_utimensat(td, dfd, path, UIO_SYSSPACE, timesp,
918 	    		UIO_SYSSPACE, flags);
919 		LFREEPATH(path);
920 	}
921 
922 	return (error);
923 }
924 
925 int
926 linux_futimesat(struct thread *td, struct linux_futimesat_args *args)
927 {
928 	l_timeval ltv[2];
929 	struct timeval tv[2], *tvp = NULL;
930 	char *fname;
931 	int error, dfd;
932 
933 	dfd = (args->dfd == LINUX_AT_FDCWD) ? AT_FDCWD : args->dfd;
934 	LCONVPATHEXIST_AT(td, args->filename, &fname, dfd);
935 
936 #ifdef DEBUG
937 	if (ldebug(futimesat))
938 		printf(ARGS(futimesat, "%s, *"), fname);
939 #endif
940 
941 	if (args->utimes != NULL) {
942 		if ((error = copyin(args->utimes, ltv, sizeof ltv))) {
943 			LFREEPATH(fname);
944 			return (error);
945 		}
946 		tv[0].tv_sec = ltv[0].tv_sec;
947 		tv[0].tv_usec = ltv[0].tv_usec;
948 		tv[1].tv_sec = ltv[1].tv_sec;
949 		tv[1].tv_usec = ltv[1].tv_usec;
950 		tvp = tv;
951 	}
952 
953 	error = kern_utimesat(td, dfd, fname, UIO_SYSSPACE, tvp, UIO_SYSSPACE);
954 	LFREEPATH(fname);
955 	return (error);
956 }
957 
958 int
959 linux_common_wait(struct thread *td, int pid, int *status,
960     int options, struct rusage *ru)
961 {
962 	int error, tmpstat;
963 
964 	error = kern_wait(td, pid, &tmpstat, options, ru);
965 	if (error)
966 		return (error);
967 
968 	if (status) {
969 		tmpstat &= 0xffff;
970 		if (WIFSIGNALED(tmpstat))
971 			tmpstat = (tmpstat & 0xffffff80) |
972 			    bsd_to_linux_signal(WTERMSIG(tmpstat));
973 		else if (WIFSTOPPED(tmpstat))
974 			tmpstat = (tmpstat & 0xffff00ff) |
975 			    (bsd_to_linux_signal(WSTOPSIG(tmpstat)) << 8);
976 		else if (WIFCONTINUED(tmpstat))
977 			tmpstat = 0xffff;
978 		error = copyout(&tmpstat, status, sizeof(int));
979 	}
980 
981 	return (error);
982 }
983 
984 #if defined(__i386__) || (defined(__amd64__) && defined(COMPAT_LINUX32))
985 int
986 linux_waitpid(struct thread *td, struct linux_waitpid_args *args)
987 {
988 	struct linux_wait4_args wait4_args;
989 
990 #ifdef DEBUG
991 	if (ldebug(waitpid))
992 		printf(ARGS(waitpid, "%d, %p, %d"),
993 		    args->pid, (void *)args->status, args->options);
994 #endif
995 
996 	wait4_args.pid = args->pid;
997 	wait4_args.status = args->status;
998 	wait4_args.options = args->options;
999 	wait4_args.rusage = NULL;
1000 
1001 	return (linux_wait4(td, &wait4_args));
1002 }
1003 #endif /* __i386__ || (__amd64__ && COMPAT_LINUX32) */
1004 
1005 int
1006 linux_wait4(struct thread *td, struct linux_wait4_args *args)
1007 {
1008 	int error, options;
1009 	struct rusage ru, *rup;
1010 
1011 #ifdef DEBUG
1012 	if (ldebug(wait4))
1013 		printf(ARGS(wait4, "%d, %p, %d, %p"),
1014 		    args->pid, (void *)args->status, args->options,
1015 		    (void *)args->rusage);
1016 #endif
1017 	if (args->options & ~(LINUX_WUNTRACED | LINUX_WNOHANG |
1018 	    LINUX_WCONTINUED | __WCLONE | __WNOTHREAD | __WALL))
1019 		return (EINVAL);
1020 
1021 	options = WEXITED;
1022 	linux_to_bsd_waitopts(args->options, &options);
1023 
1024 	if (args->rusage != NULL)
1025 		rup = &ru;
1026 	else
1027 		rup = NULL;
1028 	error = linux_common_wait(td, args->pid, args->status, options, rup);
1029 	if (error != 0)
1030 		return (error);
1031 	if (args->rusage != NULL)
1032 		error = linux_copyout_rusage(&ru, args->rusage);
1033 	return (error);
1034 }
1035 
1036 int
1037 linux_waitid(struct thread *td, struct linux_waitid_args *args)
1038 {
1039 	int status, options, sig;
1040 	struct __wrusage wru;
1041 	siginfo_t siginfo;
1042 	l_siginfo_t lsi;
1043 	idtype_t idtype;
1044 	struct proc *p;
1045 	int error;
1046 
1047 	options = 0;
1048 	linux_to_bsd_waitopts(args->options, &options);
1049 
1050 	if (options & ~(WNOHANG | WNOWAIT | WEXITED | WUNTRACED | WCONTINUED))
1051 		return (EINVAL);
1052 	if (!(options & (WEXITED | WUNTRACED | WCONTINUED)))
1053 		return (EINVAL);
1054 
1055 	switch (args->idtype) {
1056 	case LINUX_P_ALL:
1057 		idtype = P_ALL;
1058 		break;
1059 	case LINUX_P_PID:
1060 		if (args->id <= 0)
1061 			return (EINVAL);
1062 		idtype = P_PID;
1063 		break;
1064 	case LINUX_P_PGID:
1065 		if (args->id <= 0)
1066 			return (EINVAL);
1067 		idtype = P_PGID;
1068 		break;
1069 	default:
1070 		return (EINVAL);
1071 	}
1072 
1073 	error = kern_wait6(td, idtype, args->id, &status, options,
1074 	    &wru, &siginfo);
1075 	if (error != 0)
1076 		return (error);
1077 	if (args->rusage != NULL) {
1078 		error = linux_copyout_rusage(&wru.wru_children,
1079 		    args->rusage);
1080 		if (error != 0)
1081 			return (error);
1082 	}
1083 	if (args->info != NULL) {
1084 		p = td->td_proc;
1085 		if (td->td_retval[0] == 0)
1086 			bzero(&lsi, sizeof(lsi));
1087 		else {
1088 			sig = bsd_to_linux_signal(siginfo.si_signo);
1089 			siginfo_to_lsiginfo(&siginfo, &lsi, sig);
1090 		}
1091 		error = copyout(&lsi, args->info, sizeof(lsi));
1092 	}
1093 	td->td_retval[0] = 0;
1094 
1095 	return (error);
1096 }
1097 
1098 int
1099 linux_mknod(struct thread *td, struct linux_mknod_args *args)
1100 {
1101 	char *path;
1102 	int error;
1103 
1104 	LCONVPATHCREAT(td, args->path, &path);
1105 
1106 #ifdef DEBUG
1107 	if (ldebug(mknod))
1108 		printf(ARGS(mknod, "%s, %d, %ju"), path, args->mode,
1109 		    (uintmax_t)args->dev);
1110 #endif
1111 
1112 	switch (args->mode & S_IFMT) {
1113 	case S_IFIFO:
1114 	case S_IFSOCK:
1115 		error = kern_mkfifoat(td, AT_FDCWD, path, UIO_SYSSPACE,
1116 		    args->mode);
1117 		break;
1118 
1119 	case S_IFCHR:
1120 	case S_IFBLK:
1121 		error = kern_mknodat(td, AT_FDCWD, path, UIO_SYSSPACE,
1122 		    args->mode, args->dev);
1123 		break;
1124 
1125 	case S_IFDIR:
1126 		error = EPERM;
1127 		break;
1128 
1129 	case 0:
1130 		args->mode |= S_IFREG;
1131 		/* FALLTHROUGH */
1132 	case S_IFREG:
1133 		error = kern_openat(td, AT_FDCWD, path, UIO_SYSSPACE,
1134 		    O_WRONLY | O_CREAT | O_TRUNC, args->mode);
1135 		if (error == 0)
1136 			kern_close(td, td->td_retval[0]);
1137 		break;
1138 
1139 	default:
1140 		error = EINVAL;
1141 		break;
1142 	}
1143 	LFREEPATH(path);
1144 	return (error);
1145 }
1146 
1147 int
1148 linux_mknodat(struct thread *td, struct linux_mknodat_args *args)
1149 {
1150 	char *path;
1151 	int error, dfd;
1152 
1153 	dfd = (args->dfd == LINUX_AT_FDCWD) ? AT_FDCWD : args->dfd;
1154 	LCONVPATHCREAT_AT(td, args->filename, &path, dfd);
1155 
1156 #ifdef DEBUG
1157 	if (ldebug(mknodat))
1158 		printf(ARGS(mknodat, "%s, %d, %d"), path, args->mode, args->dev);
1159 #endif
1160 
1161 	switch (args->mode & S_IFMT) {
1162 	case S_IFIFO:
1163 	case S_IFSOCK:
1164 		error = kern_mkfifoat(td, dfd, path, UIO_SYSSPACE, args->mode);
1165 		break;
1166 
1167 	case S_IFCHR:
1168 	case S_IFBLK:
1169 		error = kern_mknodat(td, dfd, path, UIO_SYSSPACE, args->mode,
1170 		    args->dev);
1171 		break;
1172 
1173 	case S_IFDIR:
1174 		error = EPERM;
1175 		break;
1176 
1177 	case 0:
1178 		args->mode |= S_IFREG;
1179 		/* FALLTHROUGH */
1180 	case S_IFREG:
1181 		error = kern_openat(td, dfd, path, UIO_SYSSPACE,
1182 		    O_WRONLY | O_CREAT | O_TRUNC, args->mode);
1183 		if (error == 0)
1184 			kern_close(td, td->td_retval[0]);
1185 		break;
1186 
1187 	default:
1188 		error = EINVAL;
1189 		break;
1190 	}
1191 	LFREEPATH(path);
1192 	return (error);
1193 }
1194 
1195 /*
1196  * UGH! This is just about the dumbest idea I've ever heard!!
1197  */
1198 int
1199 linux_personality(struct thread *td, struct linux_personality_args *args)
1200 {
1201 	struct linux_pemuldata *pem;
1202 	struct proc *p = td->td_proc;
1203 	uint32_t old;
1204 
1205 #ifdef DEBUG
1206 	if (ldebug(personality))
1207 		printf(ARGS(personality, "%u"), args->per);
1208 #endif
1209 
1210 	PROC_LOCK(p);
1211 	pem = pem_find(p);
1212 	old = pem->persona;
1213 	if (args->per != 0xffffffff)
1214 		pem->persona = args->per;
1215 	PROC_UNLOCK(p);
1216 
1217 	td->td_retval[0] = old;
1218 	return (0);
1219 }
1220 
1221 struct l_itimerval {
1222 	l_timeval it_interval;
1223 	l_timeval it_value;
1224 };
1225 
1226 #define	B2L_ITIMERVAL(bip, lip) 					\
1227 	(bip)->it_interval.tv_sec = (lip)->it_interval.tv_sec;		\
1228 	(bip)->it_interval.tv_usec = (lip)->it_interval.tv_usec;	\
1229 	(bip)->it_value.tv_sec = (lip)->it_value.tv_sec;		\
1230 	(bip)->it_value.tv_usec = (lip)->it_value.tv_usec;
1231 
1232 int
1233 linux_setitimer(struct thread *td, struct linux_setitimer_args *uap)
1234 {
1235 	int error;
1236 	struct l_itimerval ls;
1237 	struct itimerval aitv, oitv;
1238 
1239 #ifdef DEBUG
1240 	if (ldebug(setitimer))
1241 		printf(ARGS(setitimer, "%p, %p"),
1242 		    (void *)uap->itv, (void *)uap->oitv);
1243 #endif
1244 
1245 	if (uap->itv == NULL) {
1246 		uap->itv = uap->oitv;
1247 		return (linux_getitimer(td, (struct linux_getitimer_args *)uap));
1248 	}
1249 
1250 	error = copyin(uap->itv, &ls, sizeof(ls));
1251 	if (error != 0)
1252 		return (error);
1253 	B2L_ITIMERVAL(&aitv, &ls);
1254 #ifdef DEBUG
1255 	if (ldebug(setitimer)) {
1256 		printf("setitimer: value: sec: %jd, usec: %ld\n",
1257 		    (intmax_t)aitv.it_value.tv_sec, aitv.it_value.tv_usec);
1258 		printf("setitimer: interval: sec: %jd, usec: %ld\n",
1259 		    (intmax_t)aitv.it_interval.tv_sec, aitv.it_interval.tv_usec);
1260 	}
1261 #endif
1262 	error = kern_setitimer(td, uap->which, &aitv, &oitv);
1263 	if (error != 0 || uap->oitv == NULL)
1264 		return (error);
1265 	B2L_ITIMERVAL(&ls, &oitv);
1266 
1267 	return (copyout(&ls, uap->oitv, sizeof(ls)));
1268 }
1269 
1270 int
1271 linux_getitimer(struct thread *td, struct linux_getitimer_args *uap)
1272 {
1273 	int error;
1274 	struct l_itimerval ls;
1275 	struct itimerval aitv;
1276 
1277 #ifdef DEBUG
1278 	if (ldebug(getitimer))
1279 		printf(ARGS(getitimer, "%p"), (void *)uap->itv);
1280 #endif
1281 	error = kern_getitimer(td, uap->which, &aitv);
1282 	if (error != 0)
1283 		return (error);
1284 	B2L_ITIMERVAL(&ls, &aitv);
1285 	return (copyout(&ls, uap->itv, sizeof(ls)));
1286 }
1287 
1288 #if defined(__i386__) || (defined(__amd64__) && defined(COMPAT_LINUX32))
1289 int
1290 linux_nice(struct thread *td, struct linux_nice_args *args)
1291 {
1292 	struct setpriority_args bsd_args;
1293 
1294 	bsd_args.which = PRIO_PROCESS;
1295 	bsd_args.who = 0;		/* current process */
1296 	bsd_args.prio = args->inc;
1297 	return (sys_setpriority(td, &bsd_args));
1298 }
1299 #endif /* __i386__ || (__amd64__ && COMPAT_LINUX32) */
1300 
1301 int
1302 linux_setgroups(struct thread *td, struct linux_setgroups_args *args)
1303 {
1304 	struct ucred *newcred, *oldcred;
1305 	l_gid_t *linux_gidset;
1306 	gid_t *bsd_gidset;
1307 	int ngrp, error;
1308 	struct proc *p;
1309 
1310 	ngrp = args->gidsetsize;
1311 	if (ngrp < 0 || ngrp >= ngroups_max + 1)
1312 		return (EINVAL);
1313 	linux_gidset = malloc(ngrp * sizeof(*linux_gidset), M_LINUX, M_WAITOK);
1314 	error = copyin(args->grouplist, linux_gidset, ngrp * sizeof(l_gid_t));
1315 	if (error)
1316 		goto out;
1317 	newcred = crget();
1318 	crextend(newcred, ngrp + 1);
1319 	p = td->td_proc;
1320 	PROC_LOCK(p);
1321 	oldcred = p->p_ucred;
1322 	crcopy(newcred, oldcred);
1323 
1324 	/*
1325 	 * cr_groups[0] holds egid. Setting the whole set from
1326 	 * the supplied set will cause egid to be changed too.
1327 	 * Keep cr_groups[0] unchanged to prevent that.
1328 	 */
1329 
1330 	if ((error = priv_check_cred(oldcred, PRIV_CRED_SETGROUPS, 0)) != 0) {
1331 		PROC_UNLOCK(p);
1332 		crfree(newcred);
1333 		goto out;
1334 	}
1335 
1336 	if (ngrp > 0) {
1337 		newcred->cr_ngroups = ngrp + 1;
1338 
1339 		bsd_gidset = newcred->cr_groups;
1340 		ngrp--;
1341 		while (ngrp >= 0) {
1342 			bsd_gidset[ngrp + 1] = linux_gidset[ngrp];
1343 			ngrp--;
1344 		}
1345 	} else
1346 		newcred->cr_ngroups = 1;
1347 
1348 	setsugid(p);
1349 	proc_set_cred(p, newcred);
1350 	PROC_UNLOCK(p);
1351 	crfree(oldcred);
1352 	error = 0;
1353 out:
1354 	free(linux_gidset, M_LINUX);
1355 	return (error);
1356 }
1357 
1358 int
1359 linux_getgroups(struct thread *td, struct linux_getgroups_args *args)
1360 {
1361 	struct ucred *cred;
1362 	l_gid_t *linux_gidset;
1363 	gid_t *bsd_gidset;
1364 	int bsd_gidsetsz, ngrp, error;
1365 
1366 	cred = td->td_ucred;
1367 	bsd_gidset = cred->cr_groups;
1368 	bsd_gidsetsz = cred->cr_ngroups - 1;
1369 
1370 	/*
1371 	 * cr_groups[0] holds egid. Returning the whole set
1372 	 * here will cause a duplicate. Exclude cr_groups[0]
1373 	 * to prevent that.
1374 	 */
1375 
1376 	if ((ngrp = args->gidsetsize) == 0) {
1377 		td->td_retval[0] = bsd_gidsetsz;
1378 		return (0);
1379 	}
1380 
1381 	if (ngrp < bsd_gidsetsz)
1382 		return (EINVAL);
1383 
1384 	ngrp = 0;
1385 	linux_gidset = malloc(bsd_gidsetsz * sizeof(*linux_gidset),
1386 	    M_LINUX, M_WAITOK);
1387 	while (ngrp < bsd_gidsetsz) {
1388 		linux_gidset[ngrp] = bsd_gidset[ngrp + 1];
1389 		ngrp++;
1390 	}
1391 
1392 	error = copyout(linux_gidset, args->grouplist, ngrp * sizeof(l_gid_t));
1393 	free(linux_gidset, M_LINUX);
1394 	if (error)
1395 		return (error);
1396 
1397 	td->td_retval[0] = ngrp;
1398 	return (0);
1399 }
1400 
1401 int
1402 linux_setrlimit(struct thread *td, struct linux_setrlimit_args *args)
1403 {
1404 	struct rlimit bsd_rlim;
1405 	struct l_rlimit rlim;
1406 	u_int which;
1407 	int error;
1408 
1409 #ifdef DEBUG
1410 	if (ldebug(setrlimit))
1411 		printf(ARGS(setrlimit, "%d, %p"),
1412 		    args->resource, (void *)args->rlim);
1413 #endif
1414 
1415 	if (args->resource >= LINUX_RLIM_NLIMITS)
1416 		return (EINVAL);
1417 
1418 	which = linux_to_bsd_resource[args->resource];
1419 	if (which == -1)
1420 		return (EINVAL);
1421 
1422 	error = copyin(args->rlim, &rlim, sizeof(rlim));
1423 	if (error)
1424 		return (error);
1425 
1426 	bsd_rlim.rlim_cur = (rlim_t)rlim.rlim_cur;
1427 	bsd_rlim.rlim_max = (rlim_t)rlim.rlim_max;
1428 	return (kern_setrlimit(td, which, &bsd_rlim));
1429 }
1430 
1431 #if defined(__i386__) || (defined(__amd64__) && defined(COMPAT_LINUX32))
1432 int
1433 linux_old_getrlimit(struct thread *td, struct linux_old_getrlimit_args *args)
1434 {
1435 	struct l_rlimit rlim;
1436 	struct rlimit bsd_rlim;
1437 	u_int which;
1438 
1439 #ifdef DEBUG
1440 	if (ldebug(old_getrlimit))
1441 		printf(ARGS(old_getrlimit, "%d, %p"),
1442 		    args->resource, (void *)args->rlim);
1443 #endif
1444 
1445 	if (args->resource >= LINUX_RLIM_NLIMITS)
1446 		return (EINVAL);
1447 
1448 	which = linux_to_bsd_resource[args->resource];
1449 	if (which == -1)
1450 		return (EINVAL);
1451 
1452 	lim_rlimit(td, which, &bsd_rlim);
1453 
1454 #ifdef COMPAT_LINUX32
1455 	rlim.rlim_cur = (unsigned int)bsd_rlim.rlim_cur;
1456 	if (rlim.rlim_cur == UINT_MAX)
1457 		rlim.rlim_cur = INT_MAX;
1458 	rlim.rlim_max = (unsigned int)bsd_rlim.rlim_max;
1459 	if (rlim.rlim_max == UINT_MAX)
1460 		rlim.rlim_max = INT_MAX;
1461 #else
1462 	rlim.rlim_cur = (unsigned long)bsd_rlim.rlim_cur;
1463 	if (rlim.rlim_cur == ULONG_MAX)
1464 		rlim.rlim_cur = LONG_MAX;
1465 	rlim.rlim_max = (unsigned long)bsd_rlim.rlim_max;
1466 	if (rlim.rlim_max == ULONG_MAX)
1467 		rlim.rlim_max = LONG_MAX;
1468 #endif
1469 	return (copyout(&rlim, args->rlim, sizeof(rlim)));
1470 }
1471 #endif /* __i386__ || (__amd64__ && COMPAT_LINUX32) */
1472 
1473 int
1474 linux_getrlimit(struct thread *td, struct linux_getrlimit_args *args)
1475 {
1476 	struct l_rlimit rlim;
1477 	struct rlimit bsd_rlim;
1478 	u_int which;
1479 
1480 #ifdef DEBUG
1481 	if (ldebug(getrlimit))
1482 		printf(ARGS(getrlimit, "%d, %p"),
1483 		    args->resource, (void *)args->rlim);
1484 #endif
1485 
1486 	if (args->resource >= LINUX_RLIM_NLIMITS)
1487 		return (EINVAL);
1488 
1489 	which = linux_to_bsd_resource[args->resource];
1490 	if (which == -1)
1491 		return (EINVAL);
1492 
1493 	lim_rlimit(td, which, &bsd_rlim);
1494 
1495 	rlim.rlim_cur = (l_ulong)bsd_rlim.rlim_cur;
1496 	rlim.rlim_max = (l_ulong)bsd_rlim.rlim_max;
1497 	return (copyout(&rlim, args->rlim, sizeof(rlim)));
1498 }
1499 
1500 int
1501 linux_sched_setscheduler(struct thread *td,
1502     struct linux_sched_setscheduler_args *args)
1503 {
1504 	struct sched_param sched_param;
1505 	struct thread *tdt;
1506 	int error, policy;
1507 
1508 #ifdef DEBUG
1509 	if (ldebug(sched_setscheduler))
1510 		printf(ARGS(sched_setscheduler, "%d, %d, %p"),
1511 		    args->pid, args->policy, (const void *)args->param);
1512 #endif
1513 
1514 	switch (args->policy) {
1515 	case LINUX_SCHED_OTHER:
1516 		policy = SCHED_OTHER;
1517 		break;
1518 	case LINUX_SCHED_FIFO:
1519 		policy = SCHED_FIFO;
1520 		break;
1521 	case LINUX_SCHED_RR:
1522 		policy = SCHED_RR;
1523 		break;
1524 	default:
1525 		return (EINVAL);
1526 	}
1527 
1528 	error = copyin(args->param, &sched_param, sizeof(sched_param));
1529 	if (error)
1530 		return (error);
1531 
1532 	tdt = linux_tdfind(td, args->pid, -1);
1533 	if (tdt == NULL)
1534 		return (ESRCH);
1535 
1536 	error = kern_sched_setscheduler(td, tdt, policy, &sched_param);
1537 	PROC_UNLOCK(tdt->td_proc);
1538 	return (error);
1539 }
1540 
1541 int
1542 linux_sched_getscheduler(struct thread *td,
1543     struct linux_sched_getscheduler_args *args)
1544 {
1545 	struct thread *tdt;
1546 	int error, policy;
1547 
1548 #ifdef DEBUG
1549 	if (ldebug(sched_getscheduler))
1550 		printf(ARGS(sched_getscheduler, "%d"), args->pid);
1551 #endif
1552 
1553 	tdt = linux_tdfind(td, args->pid, -1);
1554 	if (tdt == NULL)
1555 		return (ESRCH);
1556 
1557 	error = kern_sched_getscheduler(td, tdt, &policy);
1558 	PROC_UNLOCK(tdt->td_proc);
1559 
1560 	switch (policy) {
1561 	case SCHED_OTHER:
1562 		td->td_retval[0] = LINUX_SCHED_OTHER;
1563 		break;
1564 	case SCHED_FIFO:
1565 		td->td_retval[0] = LINUX_SCHED_FIFO;
1566 		break;
1567 	case SCHED_RR:
1568 		td->td_retval[0] = LINUX_SCHED_RR;
1569 		break;
1570 	}
1571 	return (error);
1572 }
1573 
1574 int
1575 linux_sched_get_priority_max(struct thread *td,
1576     struct linux_sched_get_priority_max_args *args)
1577 {
1578 	struct sched_get_priority_max_args bsd;
1579 
1580 #ifdef DEBUG
1581 	if (ldebug(sched_get_priority_max))
1582 		printf(ARGS(sched_get_priority_max, "%d"), args->policy);
1583 #endif
1584 
1585 	switch (args->policy) {
1586 	case LINUX_SCHED_OTHER:
1587 		bsd.policy = SCHED_OTHER;
1588 		break;
1589 	case LINUX_SCHED_FIFO:
1590 		bsd.policy = SCHED_FIFO;
1591 		break;
1592 	case LINUX_SCHED_RR:
1593 		bsd.policy = SCHED_RR;
1594 		break;
1595 	default:
1596 		return (EINVAL);
1597 	}
1598 	return (sys_sched_get_priority_max(td, &bsd));
1599 }
1600 
1601 int
1602 linux_sched_get_priority_min(struct thread *td,
1603     struct linux_sched_get_priority_min_args *args)
1604 {
1605 	struct sched_get_priority_min_args bsd;
1606 
1607 #ifdef DEBUG
1608 	if (ldebug(sched_get_priority_min))
1609 		printf(ARGS(sched_get_priority_min, "%d"), args->policy);
1610 #endif
1611 
1612 	switch (args->policy) {
1613 	case LINUX_SCHED_OTHER:
1614 		bsd.policy = SCHED_OTHER;
1615 		break;
1616 	case LINUX_SCHED_FIFO:
1617 		bsd.policy = SCHED_FIFO;
1618 		break;
1619 	case LINUX_SCHED_RR:
1620 		bsd.policy = SCHED_RR;
1621 		break;
1622 	default:
1623 		return (EINVAL);
1624 	}
1625 	return (sys_sched_get_priority_min(td, &bsd));
1626 }
1627 
1628 #define REBOOT_CAD_ON	0x89abcdef
1629 #define REBOOT_CAD_OFF	0
1630 #define REBOOT_HALT	0xcdef0123
1631 #define REBOOT_RESTART	0x01234567
1632 #define REBOOT_RESTART2	0xA1B2C3D4
1633 #define REBOOT_POWEROFF	0x4321FEDC
1634 #define REBOOT_MAGIC1	0xfee1dead
1635 #define REBOOT_MAGIC2	0x28121969
1636 #define REBOOT_MAGIC2A	0x05121996
1637 #define REBOOT_MAGIC2B	0x16041998
1638 
1639 int
1640 linux_reboot(struct thread *td, struct linux_reboot_args *args)
1641 {
1642 	struct reboot_args bsd_args;
1643 
1644 #ifdef DEBUG
1645 	if (ldebug(reboot))
1646 		printf(ARGS(reboot, "0x%x"), args->cmd);
1647 #endif
1648 
1649 	if (args->magic1 != REBOOT_MAGIC1)
1650 		return (EINVAL);
1651 
1652 	switch (args->magic2) {
1653 	case REBOOT_MAGIC2:
1654 	case REBOOT_MAGIC2A:
1655 	case REBOOT_MAGIC2B:
1656 		break;
1657 	default:
1658 		return (EINVAL);
1659 	}
1660 
1661 	switch (args->cmd) {
1662 	case REBOOT_CAD_ON:
1663 	case REBOOT_CAD_OFF:
1664 		return (priv_check(td, PRIV_REBOOT));
1665 	case REBOOT_HALT:
1666 		bsd_args.opt = RB_HALT;
1667 		break;
1668 	case REBOOT_RESTART:
1669 	case REBOOT_RESTART2:
1670 		bsd_args.opt = 0;
1671 		break;
1672 	case REBOOT_POWEROFF:
1673 		bsd_args.opt = RB_POWEROFF;
1674 		break;
1675 	default:
1676 		return (EINVAL);
1677 	}
1678 	return (sys_reboot(td, &bsd_args));
1679 }
1680 
1681 
1682 /*
1683  * The FreeBSD native getpid(2), getgid(2) and getuid(2) also modify
1684  * td->td_retval[1] when COMPAT_43 is defined. This clobbers registers that
1685  * are assumed to be preserved. The following lightweight syscalls fixes
1686  * this. See also linux_getgid16() and linux_getuid16() in linux_uid16.c
1687  *
1688  * linux_getpid() - MP SAFE
1689  * linux_getgid() - MP SAFE
1690  * linux_getuid() - MP SAFE
1691  */
1692 
1693 int
1694 linux_getpid(struct thread *td, struct linux_getpid_args *args)
1695 {
1696 
1697 #ifdef DEBUG
1698 	if (ldebug(getpid))
1699 		printf(ARGS(getpid, ""));
1700 #endif
1701 	td->td_retval[0] = td->td_proc->p_pid;
1702 
1703 	return (0);
1704 }
1705 
1706 int
1707 linux_gettid(struct thread *td, struct linux_gettid_args *args)
1708 {
1709 	struct linux_emuldata *em;
1710 
1711 #ifdef DEBUG
1712 	if (ldebug(gettid))
1713 		printf(ARGS(gettid, ""));
1714 #endif
1715 
1716 	em = em_find(td);
1717 	KASSERT(em != NULL, ("gettid: emuldata not found.\n"));
1718 
1719 	td->td_retval[0] = em->em_tid;
1720 
1721 	return (0);
1722 }
1723 
1724 
1725 int
1726 linux_getppid(struct thread *td, struct linux_getppid_args *args)
1727 {
1728 
1729 #ifdef DEBUG
1730 	if (ldebug(getppid))
1731 		printf(ARGS(getppid, ""));
1732 #endif
1733 
1734 	td->td_retval[0] = kern_getppid(td);
1735 	return (0);
1736 }
1737 
1738 int
1739 linux_getgid(struct thread *td, struct linux_getgid_args *args)
1740 {
1741 
1742 #ifdef DEBUG
1743 	if (ldebug(getgid))
1744 		printf(ARGS(getgid, ""));
1745 #endif
1746 
1747 	td->td_retval[0] = td->td_ucred->cr_rgid;
1748 	return (0);
1749 }
1750 
1751 int
1752 linux_getuid(struct thread *td, struct linux_getuid_args *args)
1753 {
1754 
1755 #ifdef DEBUG
1756 	if (ldebug(getuid))
1757 		printf(ARGS(getuid, ""));
1758 #endif
1759 
1760 	td->td_retval[0] = td->td_ucred->cr_ruid;
1761 	return (0);
1762 }
1763 
1764 
1765 int
1766 linux_getsid(struct thread *td, struct linux_getsid_args *args)
1767 {
1768 	struct getsid_args bsd;
1769 
1770 #ifdef DEBUG
1771 	if (ldebug(getsid))
1772 		printf(ARGS(getsid, "%i"), args->pid);
1773 #endif
1774 
1775 	bsd.pid = args->pid;
1776 	return (sys_getsid(td, &bsd));
1777 }
1778 
1779 int
1780 linux_nosys(struct thread *td, struct nosys_args *ignore)
1781 {
1782 
1783 	return (ENOSYS);
1784 }
1785 
1786 int
1787 linux_getpriority(struct thread *td, struct linux_getpriority_args *args)
1788 {
1789 	struct getpriority_args bsd_args;
1790 	int error;
1791 
1792 #ifdef DEBUG
1793 	if (ldebug(getpriority))
1794 		printf(ARGS(getpriority, "%i, %i"), args->which, args->who);
1795 #endif
1796 
1797 	bsd_args.which = args->which;
1798 	bsd_args.who = args->who;
1799 	error = sys_getpriority(td, &bsd_args);
1800 	td->td_retval[0] = 20 - td->td_retval[0];
1801 	return (error);
1802 }
1803 
1804 int
1805 linux_sethostname(struct thread *td, struct linux_sethostname_args *args)
1806 {
1807 	int name[2];
1808 
1809 #ifdef DEBUG
1810 	if (ldebug(sethostname))
1811 		printf(ARGS(sethostname, "*, %i"), args->len);
1812 #endif
1813 
1814 	name[0] = CTL_KERN;
1815 	name[1] = KERN_HOSTNAME;
1816 	return (userland_sysctl(td, name, 2, 0, 0, 0, args->hostname,
1817 	    args->len, 0, 0));
1818 }
1819 
1820 int
1821 linux_setdomainname(struct thread *td, struct linux_setdomainname_args *args)
1822 {
1823 	int name[2];
1824 
1825 #ifdef DEBUG
1826 	if (ldebug(setdomainname))
1827 		printf(ARGS(setdomainname, "*, %i"), args->len);
1828 #endif
1829 
1830 	name[0] = CTL_KERN;
1831 	name[1] = KERN_NISDOMAINNAME;
1832 	return (userland_sysctl(td, name, 2, 0, 0, 0, args->name,
1833 	    args->len, 0, 0));
1834 }
1835 
1836 int
1837 linux_exit_group(struct thread *td, struct linux_exit_group_args *args)
1838 {
1839 
1840 #ifdef DEBUG
1841 	if (ldebug(exit_group))
1842 		printf(ARGS(exit_group, "%i"), args->error_code);
1843 #endif
1844 
1845 	LINUX_CTR2(exit_group, "thread(%d) (%d)", td->td_tid,
1846 	    args->error_code);
1847 
1848 	/*
1849 	 * XXX: we should send a signal to the parent if
1850 	 * SIGNAL_EXIT_GROUP is set. We ignore that (temporarily?)
1851 	 * as it doesnt occur often.
1852 	 */
1853 	exit1(td, args->error_code, 0);
1854 		/* NOTREACHED */
1855 }
1856 
1857 #define _LINUX_CAPABILITY_VERSION  0x19980330
1858 
1859 struct l_user_cap_header {
1860 	l_int	version;
1861 	l_int	pid;
1862 };
1863 
1864 struct l_user_cap_data {
1865 	l_int	effective;
1866 	l_int	permitted;
1867 	l_int	inheritable;
1868 };
1869 
1870 int
1871 linux_capget(struct thread *td, struct linux_capget_args *args)
1872 {
1873 	struct l_user_cap_header luch;
1874 	struct l_user_cap_data lucd;
1875 	int error;
1876 
1877 	if (args->hdrp == NULL)
1878 		return (EFAULT);
1879 
1880 	error = copyin(args->hdrp, &luch, sizeof(luch));
1881 	if (error != 0)
1882 		return (error);
1883 
1884 	if (luch.version != _LINUX_CAPABILITY_VERSION) {
1885 		luch.version = _LINUX_CAPABILITY_VERSION;
1886 		error = copyout(&luch, args->hdrp, sizeof(luch));
1887 		if (error)
1888 			return (error);
1889 		return (EINVAL);
1890 	}
1891 
1892 	if (luch.pid)
1893 		return (EPERM);
1894 
1895 	if (args->datap) {
1896 		/*
1897 		 * The current implementation doesn't support setting
1898 		 * a capability (it's essentially a stub) so indicate
1899 		 * that no capabilities are currently set or available
1900 		 * to request.
1901 		 */
1902 		bzero (&lucd, sizeof(lucd));
1903 		error = copyout(&lucd, args->datap, sizeof(lucd));
1904 	}
1905 
1906 	return (error);
1907 }
1908 
1909 int
1910 linux_capset(struct thread *td, struct linux_capset_args *args)
1911 {
1912 	struct l_user_cap_header luch;
1913 	struct l_user_cap_data lucd;
1914 	int error;
1915 
1916 	if (args->hdrp == NULL || args->datap == NULL)
1917 		return (EFAULT);
1918 
1919 	error = copyin(args->hdrp, &luch, sizeof(luch));
1920 	if (error != 0)
1921 		return (error);
1922 
1923 	if (luch.version != _LINUX_CAPABILITY_VERSION) {
1924 		luch.version = _LINUX_CAPABILITY_VERSION;
1925 		error = copyout(&luch, args->hdrp, sizeof(luch));
1926 		if (error)
1927 			return (error);
1928 		return (EINVAL);
1929 	}
1930 
1931 	if (luch.pid)
1932 		return (EPERM);
1933 
1934 	error = copyin(args->datap, &lucd, sizeof(lucd));
1935 	if (error != 0)
1936 		return (error);
1937 
1938 	/* We currently don't support setting any capabilities. */
1939 	if (lucd.effective || lucd.permitted || lucd.inheritable) {
1940 		linux_msg(td,
1941 			  "capset effective=0x%x, permitted=0x%x, "
1942 			  "inheritable=0x%x is not implemented",
1943 			  (int)lucd.effective, (int)lucd.permitted,
1944 			  (int)lucd.inheritable);
1945 		return (EPERM);
1946 	}
1947 
1948 	return (0);
1949 }
1950 
1951 int
1952 linux_prctl(struct thread *td, struct linux_prctl_args *args)
1953 {
1954 	int error = 0, max_size;
1955 	struct proc *p = td->td_proc;
1956 	char comm[LINUX_MAX_COMM_LEN];
1957 	struct linux_emuldata *em;
1958 	int pdeath_signal;
1959 
1960 #ifdef DEBUG
1961 	if (ldebug(prctl))
1962 		printf(ARGS(prctl, "%d, %ju, %ju, %ju, %ju"), args->option,
1963 		    (uintmax_t)args->arg2, (uintmax_t)args->arg3,
1964 		    (uintmax_t)args->arg4, (uintmax_t)args->arg5);
1965 #endif
1966 
1967 	switch (args->option) {
1968 	case LINUX_PR_SET_PDEATHSIG:
1969 		if (!LINUX_SIG_VALID(args->arg2))
1970 			return (EINVAL);
1971 		em = em_find(td);
1972 		KASSERT(em != NULL, ("prctl: emuldata not found.\n"));
1973 		em->pdeath_signal = args->arg2;
1974 		break;
1975 	case LINUX_PR_GET_PDEATHSIG:
1976 		em = em_find(td);
1977 		KASSERT(em != NULL, ("prctl: emuldata not found.\n"));
1978 		pdeath_signal = em->pdeath_signal;
1979 		error = copyout(&pdeath_signal,
1980 		    (void *)(register_t)args->arg2,
1981 		    sizeof(pdeath_signal));
1982 		break;
1983 	case LINUX_PR_GET_KEEPCAPS:
1984 		/*
1985 		 * Indicate that we always clear the effective and
1986 		 * permitted capability sets when the user id becomes
1987 		 * non-zero (actually the capability sets are simply
1988 		 * always zero in the current implementation).
1989 		 */
1990 		td->td_retval[0] = 0;
1991 		break;
1992 	case LINUX_PR_SET_KEEPCAPS:
1993 		/*
1994 		 * Ignore requests to keep the effective and permitted
1995 		 * capability sets when the user id becomes non-zero.
1996 		 */
1997 		break;
1998 	case LINUX_PR_SET_NAME:
1999 		/*
2000 		 * To be on the safe side we need to make sure to not
2001 		 * overflow the size a linux program expects. We already
2002 		 * do this here in the copyin, so that we don't need to
2003 		 * check on copyout.
2004 		 */
2005 		max_size = MIN(sizeof(comm), sizeof(p->p_comm));
2006 		error = copyinstr((void *)(register_t)args->arg2, comm,
2007 		    max_size, NULL);
2008 
2009 		/* Linux silently truncates the name if it is too long. */
2010 		if (error == ENAMETOOLONG) {
2011 			/*
2012 			 * XXX: copyinstr() isn't documented to populate the
2013 			 * array completely, so do a copyin() to be on the
2014 			 * safe side. This should be changed in case
2015 			 * copyinstr() is changed to guarantee this.
2016 			 */
2017 			error = copyin((void *)(register_t)args->arg2, comm,
2018 			    max_size - 1);
2019 			comm[max_size - 1] = '\0';
2020 		}
2021 		if (error)
2022 			return (error);
2023 
2024 		PROC_LOCK(p);
2025 		strlcpy(p->p_comm, comm, sizeof(p->p_comm));
2026 		PROC_UNLOCK(p);
2027 		break;
2028 	case LINUX_PR_GET_NAME:
2029 		PROC_LOCK(p);
2030 		strlcpy(comm, p->p_comm, sizeof(comm));
2031 		PROC_UNLOCK(p);
2032 		error = copyout(comm, (void *)(register_t)args->arg2,
2033 		    strlen(comm) + 1);
2034 		break;
2035 	default:
2036 		error = EINVAL;
2037 		break;
2038 	}
2039 
2040 	return (error);
2041 }
2042 
2043 int
2044 linux_sched_setparam(struct thread *td,
2045     struct linux_sched_setparam_args *uap)
2046 {
2047 	struct sched_param sched_param;
2048 	struct thread *tdt;
2049 	int error;
2050 
2051 #ifdef DEBUG
2052 	if (ldebug(sched_setparam))
2053 		printf(ARGS(sched_setparam, "%d, *"), uap->pid);
2054 #endif
2055 
2056 	error = copyin(uap->param, &sched_param, sizeof(sched_param));
2057 	if (error)
2058 		return (error);
2059 
2060 	tdt = linux_tdfind(td, uap->pid, -1);
2061 	if (tdt == NULL)
2062 		return (ESRCH);
2063 
2064 	error = kern_sched_setparam(td, tdt, &sched_param);
2065 	PROC_UNLOCK(tdt->td_proc);
2066 	return (error);
2067 }
2068 
2069 int
2070 linux_sched_getparam(struct thread *td,
2071     struct linux_sched_getparam_args *uap)
2072 {
2073 	struct sched_param sched_param;
2074 	struct thread *tdt;
2075 	int error;
2076 
2077 #ifdef DEBUG
2078 	if (ldebug(sched_getparam))
2079 		printf(ARGS(sched_getparam, "%d, *"), uap->pid);
2080 #endif
2081 
2082 	tdt = linux_tdfind(td, uap->pid, -1);
2083 	if (tdt == NULL)
2084 		return (ESRCH);
2085 
2086 	error = kern_sched_getparam(td, tdt, &sched_param);
2087 	PROC_UNLOCK(tdt->td_proc);
2088 	if (error == 0)
2089 		error = copyout(&sched_param, uap->param,
2090 		    sizeof(sched_param));
2091 	return (error);
2092 }
2093 
2094 /*
2095  * Get affinity of a process.
2096  */
2097 int
2098 linux_sched_getaffinity(struct thread *td,
2099     struct linux_sched_getaffinity_args *args)
2100 {
2101 	int error;
2102 	struct thread *tdt;
2103 
2104 #ifdef DEBUG
2105 	if (ldebug(sched_getaffinity))
2106 		printf(ARGS(sched_getaffinity, "%d, %d, *"), args->pid,
2107 		    args->len);
2108 #endif
2109 	if (args->len < sizeof(cpuset_t))
2110 		return (EINVAL);
2111 
2112 	tdt = linux_tdfind(td, args->pid, -1);
2113 	if (tdt == NULL)
2114 		return (ESRCH);
2115 
2116 	PROC_UNLOCK(tdt->td_proc);
2117 
2118 	error = kern_cpuset_getaffinity(td, CPU_LEVEL_WHICH, CPU_WHICH_TID,
2119 	    tdt->td_tid, sizeof(cpuset_t), (cpuset_t *)args->user_mask_ptr);
2120 	if (error == 0)
2121 		td->td_retval[0] = sizeof(cpuset_t);
2122 
2123 	return (error);
2124 }
2125 
2126 /*
2127  *  Set affinity of a process.
2128  */
2129 int
2130 linux_sched_setaffinity(struct thread *td,
2131     struct linux_sched_setaffinity_args *args)
2132 {
2133 	struct thread *tdt;
2134 
2135 #ifdef DEBUG
2136 	if (ldebug(sched_setaffinity))
2137 		printf(ARGS(sched_setaffinity, "%d, %d, *"), args->pid,
2138 		    args->len);
2139 #endif
2140 	if (args->len < sizeof(cpuset_t))
2141 		return (EINVAL);
2142 
2143 	tdt = linux_tdfind(td, args->pid, -1);
2144 	if (tdt == NULL)
2145 		return (ESRCH);
2146 
2147 	PROC_UNLOCK(tdt->td_proc);
2148 
2149 	return (kern_cpuset_setaffinity(td, CPU_LEVEL_WHICH, CPU_WHICH_TID,
2150 	    tdt->td_tid, sizeof(cpuset_t), (cpuset_t *) args->user_mask_ptr));
2151 }
2152 
2153 struct linux_rlimit64 {
2154 	uint64_t	rlim_cur;
2155 	uint64_t	rlim_max;
2156 };
2157 
2158 int
2159 linux_prlimit64(struct thread *td, struct linux_prlimit64_args *args)
2160 {
2161 	struct rlimit rlim, nrlim;
2162 	struct linux_rlimit64 lrlim;
2163 	struct proc *p;
2164 	u_int which;
2165 	int flags;
2166 	int error;
2167 
2168 #ifdef DEBUG
2169 	if (ldebug(prlimit64))
2170 		printf(ARGS(prlimit64, "%d, %d, %p, %p"), args->pid,
2171 		    args->resource, (void *)args->new, (void *)args->old);
2172 #endif
2173 
2174 	if (args->resource >= LINUX_RLIM_NLIMITS)
2175 		return (EINVAL);
2176 
2177 	which = linux_to_bsd_resource[args->resource];
2178 	if (which == -1)
2179 		return (EINVAL);
2180 
2181 	if (args->new != NULL) {
2182 		/*
2183 		 * Note. Unlike FreeBSD where rlim is signed 64-bit Linux
2184 		 * rlim is unsigned 64-bit. FreeBSD treats negative limits
2185 		 * as INFINITY so we do not need a conversion even.
2186 		 */
2187 		error = copyin(args->new, &nrlim, sizeof(nrlim));
2188 		if (error != 0)
2189 			return (error);
2190 	}
2191 
2192 	flags = PGET_HOLD | PGET_NOTWEXIT;
2193 	if (args->new != NULL)
2194 		flags |= PGET_CANDEBUG;
2195 	else
2196 		flags |= PGET_CANSEE;
2197 	error = pget(args->pid, flags, &p);
2198 	if (error != 0)
2199 		return (error);
2200 
2201 	if (args->old != NULL) {
2202 		PROC_LOCK(p);
2203 		lim_rlimit_proc(p, which, &rlim);
2204 		PROC_UNLOCK(p);
2205 		if (rlim.rlim_cur == RLIM_INFINITY)
2206 			lrlim.rlim_cur = LINUX_RLIM_INFINITY;
2207 		else
2208 			lrlim.rlim_cur = rlim.rlim_cur;
2209 		if (rlim.rlim_max == RLIM_INFINITY)
2210 			lrlim.rlim_max = LINUX_RLIM_INFINITY;
2211 		else
2212 			lrlim.rlim_max = rlim.rlim_max;
2213 		error = copyout(&lrlim, args->old, sizeof(lrlim));
2214 		if (error != 0)
2215 			goto out;
2216 	}
2217 
2218 	if (args->new != NULL)
2219 		error = kern_proc_setrlimit(td, p, which, &nrlim);
2220 
2221  out:
2222 	PRELE(p);
2223 	return (error);
2224 }
2225 
2226 int
2227 linux_pselect6(struct thread *td, struct linux_pselect6_args *args)
2228 {
2229 	struct timeval utv, tv0, tv1, *tvp;
2230 	struct l_pselect6arg lpse6;
2231 	struct l_timespec lts;
2232 	struct timespec uts;
2233 	l_sigset_t l_ss;
2234 	sigset_t *ssp;
2235 	sigset_t ss;
2236 	int error;
2237 
2238 	ssp = NULL;
2239 	if (args->sig != NULL) {
2240 		error = copyin(args->sig, &lpse6, sizeof(lpse6));
2241 		if (error != 0)
2242 			return (error);
2243 		if (lpse6.ss_len != sizeof(l_ss))
2244 			return (EINVAL);
2245 		if (lpse6.ss != 0) {
2246 			error = copyin(PTRIN(lpse6.ss), &l_ss,
2247 			    sizeof(l_ss));
2248 			if (error != 0)
2249 				return (error);
2250 			linux_to_bsd_sigset(&l_ss, &ss);
2251 			ssp = &ss;
2252 		}
2253 	}
2254 
2255 	/*
2256 	 * Currently glibc changes nanosecond number to microsecond.
2257 	 * This mean losing precision but for now it is hardly seen.
2258 	 */
2259 	if (args->tsp != NULL) {
2260 		error = copyin(args->tsp, &lts, sizeof(lts));
2261 		if (error != 0)
2262 			return (error);
2263 		error = linux_to_native_timespec(&uts, &lts);
2264 		if (error != 0)
2265 			return (error);
2266 
2267 		TIMESPEC_TO_TIMEVAL(&utv, &uts);
2268 		if (itimerfix(&utv))
2269 			return (EINVAL);
2270 
2271 		microtime(&tv0);
2272 		tvp = &utv;
2273 	} else
2274 		tvp = NULL;
2275 
2276 	error = kern_pselect(td, args->nfds, args->readfds, args->writefds,
2277 	    args->exceptfds, tvp, ssp, LINUX_NFDBITS);
2278 
2279 	if (error == 0 && args->tsp != NULL) {
2280 		if (td->td_retval[0] != 0) {
2281 			/*
2282 			 * Compute how much time was left of the timeout,
2283 			 * by subtracting the current time and the time
2284 			 * before we started the call, and subtracting
2285 			 * that result from the user-supplied value.
2286 			 */
2287 
2288 			microtime(&tv1);
2289 			timevalsub(&tv1, &tv0);
2290 			timevalsub(&utv, &tv1);
2291 			if (utv.tv_sec < 0)
2292 				timevalclear(&utv);
2293 		} else
2294 			timevalclear(&utv);
2295 
2296 		TIMEVAL_TO_TIMESPEC(&utv, &uts);
2297 
2298 		error = native_to_linux_timespec(&lts, &uts);
2299 		if (error == 0)
2300 			error = copyout(&lts, args->tsp, sizeof(lts));
2301 	}
2302 
2303 	return (error);
2304 }
2305 
2306 int
2307 linux_ppoll(struct thread *td, struct linux_ppoll_args *args)
2308 {
2309 	struct timespec ts0, ts1;
2310 	struct l_timespec lts;
2311 	struct timespec uts, *tsp;
2312 	l_sigset_t l_ss;
2313 	sigset_t *ssp;
2314 	sigset_t ss;
2315 	int error;
2316 
2317 	if (args->sset != NULL) {
2318 		if (args->ssize != sizeof(l_ss))
2319 			return (EINVAL);
2320 		error = copyin(args->sset, &l_ss, sizeof(l_ss));
2321 		if (error)
2322 			return (error);
2323 		linux_to_bsd_sigset(&l_ss, &ss);
2324 		ssp = &ss;
2325 	} else
2326 		ssp = NULL;
2327 	if (args->tsp != NULL) {
2328 		error = copyin(args->tsp, &lts, sizeof(lts));
2329 		if (error)
2330 			return (error);
2331 		error = linux_to_native_timespec(&uts, &lts);
2332 		if (error != 0)
2333 			return (error);
2334 
2335 		nanotime(&ts0);
2336 		tsp = &uts;
2337 	} else
2338 		tsp = NULL;
2339 
2340 	error = kern_poll(td, args->fds, args->nfds, tsp, ssp);
2341 
2342 	if (error == 0 && args->tsp != NULL) {
2343 		if (td->td_retval[0]) {
2344 			nanotime(&ts1);
2345 			timespecsub(&ts1, &ts0);
2346 			timespecsub(&uts, &ts1);
2347 			if (uts.tv_sec < 0)
2348 				timespecclear(&uts);
2349 		} else
2350 			timespecclear(&uts);
2351 
2352 		error = native_to_linux_timespec(&lts, &uts);
2353 		if (error == 0)
2354 			error = copyout(&lts, args->tsp, sizeof(lts));
2355 	}
2356 
2357 	return (error);
2358 }
2359 
2360 #if defined(DEBUG) || defined(KTR)
2361 /* XXX: can be removed when every ldebug(...) and KTR stuff are removed. */
2362 
2363 #ifdef COMPAT_LINUX32
2364 #define	L_MAXSYSCALL	LINUX32_SYS_MAXSYSCALL
2365 #else
2366 #define	L_MAXSYSCALL	LINUX_SYS_MAXSYSCALL
2367 #endif
2368 
2369 u_char linux_debug_map[howmany(L_MAXSYSCALL, sizeof(u_char))];
2370 
2371 static int
2372 linux_debug(int syscall, int toggle, int global)
2373 {
2374 
2375 	if (global) {
2376 		char c = toggle ? 0 : 0xff;
2377 
2378 		memset(linux_debug_map, c, sizeof(linux_debug_map));
2379 		return (0);
2380 	}
2381 	if (syscall < 0 || syscall >= L_MAXSYSCALL)
2382 		return (EINVAL);
2383 	if (toggle)
2384 		clrbit(linux_debug_map, syscall);
2385 	else
2386 		setbit(linux_debug_map, syscall);
2387 	return (0);
2388 }
2389 #undef L_MAXSYSCALL
2390 
2391 /*
2392  * Usage: sysctl linux.debug=<syscall_nr>.<0/1>
2393  *
2394  *    E.g.: sysctl linux.debug=21.0
2395  *
2396  * As a special case, syscall "all" will apply to all syscalls globally.
2397  */
2398 #define LINUX_MAX_DEBUGSTR	16
2399 int
2400 linux_sysctl_debug(SYSCTL_HANDLER_ARGS)
2401 {
2402 	char value[LINUX_MAX_DEBUGSTR], *p;
2403 	int error, sysc, toggle;
2404 	int global = 0;
2405 
2406 	value[0] = '\0';
2407 	error = sysctl_handle_string(oidp, value, LINUX_MAX_DEBUGSTR, req);
2408 	if (error || req->newptr == NULL)
2409 		return (error);
2410 	for (p = value; *p != '\0' && *p != '.'; p++);
2411 	if (*p == '\0')
2412 		return (EINVAL);
2413 	*p++ = '\0';
2414 	sysc = strtol(value, NULL, 0);
2415 	toggle = strtol(p, NULL, 0);
2416 	if (strcmp(value, "all") == 0)
2417 		global = 1;
2418 	error = linux_debug(sysc, toggle, global);
2419 	return (error);
2420 }
2421 
2422 #endif /* DEBUG || KTR */
2423 
2424 int
2425 linux_sched_rr_get_interval(struct thread *td,
2426     struct linux_sched_rr_get_interval_args *uap)
2427 {
2428 	struct timespec ts;
2429 	struct l_timespec lts;
2430 	struct thread *tdt;
2431 	int error;
2432 
2433 	/*
2434 	 * According to man in case the invalid pid specified
2435 	 * EINVAL should be returned.
2436 	 */
2437 	if (uap->pid < 0)
2438 		return (EINVAL);
2439 
2440 	tdt = linux_tdfind(td, uap->pid, -1);
2441 	if (tdt == NULL)
2442 		return (ESRCH);
2443 
2444 	error = kern_sched_rr_get_interval_td(td, tdt, &ts);
2445 	PROC_UNLOCK(tdt->td_proc);
2446 	if (error != 0)
2447 		return (error);
2448 	error = native_to_linux_timespec(&lts, &ts);
2449 	if (error != 0)
2450 		return (error);
2451 	return (copyout(&lts, uap->interval, sizeof(lts)));
2452 }
2453 
2454 /*
2455  * In case when the Linux thread is the initial thread in
2456  * the thread group thread id is equal to the process id.
2457  * Glibc depends on this magic (assert in pthread_getattr_np.c).
2458  */
2459 struct thread *
2460 linux_tdfind(struct thread *td, lwpid_t tid, pid_t pid)
2461 {
2462 	struct linux_emuldata *em;
2463 	struct thread *tdt;
2464 	struct proc *p;
2465 
2466 	tdt = NULL;
2467 	if (tid == 0 || tid == td->td_tid) {
2468 		tdt = td;
2469 		PROC_LOCK(tdt->td_proc);
2470 	} else if (tid > PID_MAX)
2471 		tdt = tdfind(tid, pid);
2472 	else {
2473 		/*
2474 		 * Initial thread where the tid equal to the pid.
2475 		 */
2476 		p = pfind(tid);
2477 		if (p != NULL) {
2478 			if (SV_PROC_ABI(p) != SV_ABI_LINUX) {
2479 				/*
2480 				 * p is not a Linuxulator process.
2481 				 */
2482 				PROC_UNLOCK(p);
2483 				return (NULL);
2484 			}
2485 			FOREACH_THREAD_IN_PROC(p, tdt) {
2486 				em = em_find(tdt);
2487 				if (tid == em->em_tid)
2488 					return (tdt);
2489 			}
2490 			PROC_UNLOCK(p);
2491 		}
2492 		return (NULL);
2493 	}
2494 
2495 	return (tdt);
2496 }
2497 
2498 void
2499 linux_to_bsd_waitopts(int options, int *bsdopts)
2500 {
2501 
2502 	if (options & LINUX_WNOHANG)
2503 		*bsdopts |= WNOHANG;
2504 	if (options & LINUX_WUNTRACED)
2505 		*bsdopts |= WUNTRACED;
2506 	if (options & LINUX_WEXITED)
2507 		*bsdopts |= WEXITED;
2508 	if (options & LINUX_WCONTINUED)
2509 		*bsdopts |= WCONTINUED;
2510 	if (options & LINUX_WNOWAIT)
2511 		*bsdopts |= WNOWAIT;
2512 
2513 	if (options & __WCLONE)
2514 		*bsdopts |= WLINUXCLONE;
2515 }
2516 
2517 int
2518 linux_getrandom(struct thread *td, struct linux_getrandom_args *args)
2519 {
2520 	struct uio uio;
2521 	struct iovec iov;
2522 	int error;
2523 
2524 	if (args->flags & ~(LINUX_GRND_NONBLOCK|LINUX_GRND_RANDOM))
2525 		return (EINVAL);
2526 	if (args->count > INT_MAX)
2527 		args->count = INT_MAX;
2528 
2529 	iov.iov_base = args->buf;
2530 	iov.iov_len = args->count;
2531 
2532 	uio.uio_iov = &iov;
2533 	uio.uio_iovcnt = 1;
2534 	uio.uio_resid = iov.iov_len;
2535 	uio.uio_segflg = UIO_USERSPACE;
2536 	uio.uio_rw = UIO_READ;
2537 	uio.uio_td = td;
2538 
2539 	error = read_random_uio(&uio, args->flags & LINUX_GRND_NONBLOCK);
2540 	if (error == 0)
2541 		td->td_retval[0] = args->count - uio.uio_resid;
2542 	return (error);
2543 }
2544 
2545 int
2546 linux_mincore(struct thread *td, struct linux_mincore_args *args)
2547 {
2548 
2549 	/* Needs to be page-aligned */
2550 	if (args->start & PAGE_MASK)
2551 		return (EINVAL);
2552 	return (kern_mincore(td, args->start, args->len, args->vec));
2553 }
2554