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