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