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