AMD64 - Refactor uio_resid and size_t assumptions.
[dragonfly.git] / sys / kern / sys_generic.c
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      @(#)sys_generic.c       8.5 (Berkeley) 1/21/94
39  * $FreeBSD: src/sys/kern/sys_generic.c,v 1.55.2.10 2001/03/17 10:39:32 peter Exp $
40  * $DragonFly: src/sys/kern/sys_generic.c,v 1.49 2008/05/05 22:09:44 dillon Exp $
41  */
42
43 #include "opt_ktrace.h"
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/sysproto.h>
48 #include <sys/filedesc.h>
49 #include <sys/filio.h>
50 #include <sys/fcntl.h>
51 #include <sys/file.h>
52 #include <sys/proc.h>
53 #include <sys/signalvar.h>
54 #include <sys/socketvar.h>
55 #include <sys/uio.h>
56 #include <sys/kernel.h>
57 #include <sys/kern_syscall.h>
58 #include <sys/malloc.h>
59 #include <sys/mapped_ioctl.h>
60 #include <sys/poll.h>
61 #include <sys/queue.h>
62 #include <sys/resourcevar.h>
63 #include <sys/sysctl.h>
64 #include <sys/sysent.h>
65 #include <sys/buf.h>
66 #ifdef KTRACE
67 #include <sys/ktrace.h>
68 #endif
69 #include <vm/vm.h>
70 #include <vm/vm_page.h>
71 #include <sys/file2.h>
72
73 #include <machine/limits.h>
74
75 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
76 static MALLOC_DEFINE(M_IOCTLMAP, "ioctlmap", "mapped ioctl handler buffer");
77 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
78 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
79
80 static int      doselect(int nd, fd_set *in, fd_set *ou, fd_set *ex,
81                         struct timeval *tv, int *res);
82 static int      pollscan (struct proc *, struct pollfd *, u_int, int *);
83 static int      selscan (struct proc *, fd_mask **, fd_mask **,
84                         int, int *);
85 static int      dofileread(int, struct file *, struct uio *, int, size_t *);
86 static int      dofilewrite(int, struct file *, struct uio *, int, size_t *);
87
88 /*
89  * Read system call.
90  *
91  * MPSAFE
92  */
93 int
94 sys_read(struct read_args *uap)
95 {
96         struct thread *td = curthread;
97         struct uio auio;
98         struct iovec aiov;
99         int error;
100
101         if ((ssize_t)uap->nbyte < 0)
102                 error = EINVAL;
103
104         aiov.iov_base = uap->buf;
105         aiov.iov_len = uap->nbyte;
106         auio.uio_iov = &aiov;
107         auio.uio_iovcnt = 1;
108         auio.uio_offset = -1;
109         auio.uio_resid = uap->nbyte;
110         auio.uio_rw = UIO_READ;
111         auio.uio_segflg = UIO_USERSPACE;
112         auio.uio_td = td;
113
114         error = kern_preadv(uap->fd, &auio, 0, &uap->sysmsg_szresult);
115         return(error);
116 }
117
118 /*
119  * Positioned (Pread) read system call
120  *
121  * MPSAFE
122  */
123 int
124 sys_extpread(struct extpread_args *uap)
125 {
126         struct thread *td = curthread;
127         struct uio auio;
128         struct iovec aiov;
129         int error;
130         int flags;
131
132         if ((ssize_t)uap->nbyte < 0)
133                 return(EINVAL);
134
135         aiov.iov_base = uap->buf;
136         aiov.iov_len = uap->nbyte;
137         auio.uio_iov = &aiov;
138         auio.uio_iovcnt = 1;
139         auio.uio_offset = uap->offset;
140         auio.uio_resid = uap->nbyte;
141         auio.uio_rw = UIO_READ;
142         auio.uio_segflg = UIO_USERSPACE;
143         auio.uio_td = td;
144
145         flags = uap->flags & O_FMASK;
146         if (uap->offset != (off_t)-1)
147                 flags |= O_FOFFSET;
148
149         error = kern_preadv(uap->fd, &auio, flags, &uap->sysmsg_szresult);
150         return(error);
151 }
152
153 /*
154  * Scatter read system call.
155  *
156  * MPSAFE
157  */
158 int
159 sys_readv(struct readv_args *uap)
160 {
161         struct thread *td = curthread;
162         struct uio auio;
163         struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
164         int error;
165
166         error = iovec_copyin(uap->iovp, &iov, aiov, uap->iovcnt,
167                              &auio.uio_resid);
168         if (error)
169                 return (error);
170         auio.uio_iov = iov;
171         auio.uio_iovcnt = uap->iovcnt;
172         auio.uio_offset = -1;
173         auio.uio_rw = UIO_READ;
174         auio.uio_segflg = UIO_USERSPACE;
175         auio.uio_td = td;
176
177         error = kern_preadv(uap->fd, &auio, 0, &uap->sysmsg_szresult);
178
179         iovec_free(&iov, aiov);
180         return (error);
181 }
182
183
184 /*
185  * Scatter positioned read system call.
186  *
187  * MPSAFE
188  */
189 int
190 sys_extpreadv(struct extpreadv_args *uap)
191 {
192         struct thread *td = curthread;
193         struct uio auio;
194         struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
195         int error;
196         int flags;
197
198         error = iovec_copyin(uap->iovp, &iov, aiov, uap->iovcnt,
199                              &auio.uio_resid);
200         if (error)
201                 return (error);
202         auio.uio_iov = iov;
203         auio.uio_iovcnt = uap->iovcnt;
204         auio.uio_offset = uap->offset;
205         auio.uio_rw = UIO_READ;
206         auio.uio_segflg = UIO_USERSPACE;
207         auio.uio_td = td;
208
209         flags = uap->flags & O_FMASK;
210         if (uap->offset != (off_t)-1)
211                 flags |= O_FOFFSET;
212
213         error = kern_preadv(uap->fd, &auio, flags, &uap->sysmsg_szresult);
214
215         iovec_free(&iov, aiov);
216         return(error);
217 }
218
219 /*
220  * MPSAFE
221  */
222 int
223 kern_preadv(int fd, struct uio *auio, int flags, size_t *res)
224 {
225         struct thread *td = curthread;
226         struct proc *p = td->td_proc;
227         struct file *fp;
228         int error;
229
230         KKASSERT(p);
231
232         fp = holdfp(p->p_fd, fd, FREAD);
233         if (fp == NULL)
234                 return (EBADF);
235         if (flags & O_FOFFSET && fp->f_type != DTYPE_VNODE) {
236                 error = ESPIPE;
237         } else {
238                 error = dofileread(fd, fp, auio, flags, res);
239         }
240         fdrop(fp);
241         return(error);
242 }
243
244 /*
245  * Common code for readv and preadv that reads data in
246  * from a file using the passed in uio, offset, and flags.
247  *
248  * MPALMOSTSAFE - ktrace needs help
249  */
250 static int
251 dofileread(int fd, struct file *fp, struct uio *auio, int flags, size_t *res)
252 {
253         struct thread *td = curthread;
254         int error;
255         size_t len;
256 #ifdef KTRACE
257         struct iovec *ktriov = NULL;
258         struct uio ktruio;
259 #endif
260
261 #ifdef KTRACE
262         /*
263          * if tracing, save a copy of iovec
264          */
265         if (KTRPOINT(td, KTR_GENIO))  {
266                 int iovlen = auio->uio_iovcnt * sizeof(struct iovec);
267
268                 MALLOC(ktriov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
269                 bcopy((caddr_t)auio->uio_iov, (caddr_t)ktriov, iovlen);
270                 ktruio = *auio;
271         }
272 #endif
273         len = auio->uio_resid;
274         error = fo_read(fp, auio, fp->f_cred, flags);
275         if (error) {
276                 if (auio->uio_resid != len && (error == ERESTART ||
277                     error == EINTR || error == EWOULDBLOCK))
278                         error = 0;
279         }
280 #ifdef KTRACE
281         if (ktriov != NULL) {
282                 if (error == 0) {
283                         ktruio.uio_iov = ktriov;
284                         ktruio.uio_resid = len - auio->uio_resid;
285                         get_mplock();
286                         ktrgenio(td->td_lwp, fd, UIO_READ, &ktruio, error);
287                         rel_mplock();
288                 }
289                 FREE(ktriov, M_TEMP);
290         }
291 #endif
292         if (error == 0)
293                 *res = len - auio->uio_resid;
294
295         return(error);
296 }
297
298 /*
299  * Write system call
300  *
301  * MPSAFE
302  */
303 int
304 sys_write(struct write_args *uap)
305 {
306         struct thread *td = curthread;
307         struct uio auio;
308         struct iovec aiov;
309         int error;
310
311         if ((ssize_t)uap->nbyte < 0)
312                 error = EINVAL;
313
314         aiov.iov_base = (void *)(uintptr_t)uap->buf;
315         aiov.iov_len = uap->nbyte;
316         auio.uio_iov = &aiov;
317         auio.uio_iovcnt = 1;
318         auio.uio_offset = -1;
319         auio.uio_resid = uap->nbyte;
320         auio.uio_rw = UIO_WRITE;
321         auio.uio_segflg = UIO_USERSPACE;
322         auio.uio_td = td;
323
324         error = kern_pwritev(uap->fd, &auio, 0, &uap->sysmsg_szresult);
325
326         return(error);
327 }
328
329 /*
330  * Pwrite system call
331  *
332  * MPSAFE
333  */
334 int
335 sys_extpwrite(struct extpwrite_args *uap)
336 {
337         struct thread *td = curthread;
338         struct uio auio;
339         struct iovec aiov;
340         int error;
341         int flags;
342
343         if ((ssize_t)uap->nbyte < 0)
344                 error = EINVAL;
345
346         aiov.iov_base = (void *)(uintptr_t)uap->buf;
347         aiov.iov_len = uap->nbyte;
348         auio.uio_iov = &aiov;
349         auio.uio_iovcnt = 1;
350         auio.uio_offset = uap->offset;
351         auio.uio_resid = uap->nbyte;
352         auio.uio_rw = UIO_WRITE;
353         auio.uio_segflg = UIO_USERSPACE;
354         auio.uio_td = td;
355
356         flags = uap->flags & O_FMASK;
357         if (uap->offset != (off_t)-1)
358                 flags |= O_FOFFSET;
359         error = kern_pwritev(uap->fd, &auio, flags, &uap->sysmsg_szresult);
360         return(error);
361 }
362
363 /*
364  * MPSAFE
365  */
366 int
367 sys_writev(struct writev_args *uap)
368 {
369         struct thread *td = curthread;
370         struct uio auio;
371         struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
372         int error;
373
374         error = iovec_copyin(uap->iovp, &iov, aiov, uap->iovcnt,
375                              &auio.uio_resid);
376         if (error)
377                 return (error);
378         auio.uio_iov = iov;
379         auio.uio_iovcnt = uap->iovcnt;
380         auio.uio_offset = -1;
381         auio.uio_rw = UIO_WRITE;
382         auio.uio_segflg = UIO_USERSPACE;
383         auio.uio_td = td;
384
385         error = kern_pwritev(uap->fd, &auio, 0, &uap->sysmsg_szresult);
386
387         iovec_free(&iov, aiov);
388         return (error);
389 }
390
391
392 /*
393  * Gather positioned write system call
394  *
395  * MPSAFE
396  */
397 int
398 sys_extpwritev(struct extpwritev_args *uap)
399 {
400         struct thread *td = curthread;
401         struct uio auio;
402         struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
403         int error;
404         int flags;
405
406         error = iovec_copyin(uap->iovp, &iov, aiov, uap->iovcnt,
407                              &auio.uio_resid);
408         if (error)
409                 return (error);
410         auio.uio_iov = iov;
411         auio.uio_iovcnt = uap->iovcnt;
412         auio.uio_offset = uap->offset;
413         auio.uio_rw = UIO_WRITE;
414         auio.uio_segflg = UIO_USERSPACE;
415         auio.uio_td = td;
416
417         flags = uap->flags & O_FMASK;
418         if (uap->offset != (off_t)-1)
419                 flags |= O_FOFFSET;
420
421         error = kern_pwritev(uap->fd, &auio, flags, &uap->sysmsg_szresult);
422
423         iovec_free(&iov, aiov);
424         return(error);
425 }
426
427 /*
428  * MPSAFE
429  */
430 int
431 kern_pwritev(int fd, struct uio *auio, int flags, size_t *res)
432 {
433         struct thread *td = curthread;
434         struct proc *p = td->td_proc;
435         struct file *fp;
436         int error;
437
438         KKASSERT(p);
439
440         fp = holdfp(p->p_fd, fd, FWRITE);
441         if (fp == NULL)
442                 return (EBADF);
443         else if ((flags & O_FOFFSET) && fp->f_type != DTYPE_VNODE) {
444                 error = ESPIPE;
445         } else {
446                 error = dofilewrite(fd, fp, auio, flags, res);
447         }
448         
449         fdrop(fp);
450         return (error);
451 }
452
453 /*
454  * Common code for writev and pwritev that writes data to
455  * a file using the passed in uio, offset, and flags.
456  *
457  * MPALMOSTSAFE - ktrace needs help
458  */
459 static int
460 dofilewrite(int fd, struct file *fp, struct uio *auio, int flags, size_t *res)
461 {       
462         struct thread *td = curthread;
463         struct lwp *lp = td->td_lwp;
464         int error;
465         size_t len;
466 #ifdef KTRACE
467         struct iovec *ktriov = NULL;
468         struct uio ktruio;
469 #endif
470
471 #ifdef KTRACE
472         /*
473          * if tracing, save a copy of iovec and uio
474          */
475         if (KTRPOINT(td, KTR_GENIO))  {
476                 int iovlen = auio->uio_iovcnt * sizeof(struct iovec);
477
478                 MALLOC(ktriov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
479                 bcopy((caddr_t)auio->uio_iov, (caddr_t)ktriov, iovlen);
480                 ktruio = *auio;
481         }
482 #endif
483         len = auio->uio_resid;
484         error = fo_write(fp, auio, fp->f_cred, flags);
485         if (error) {
486                 if (auio->uio_resid != len && (error == ERESTART ||
487                     error == EINTR || error == EWOULDBLOCK))
488                         error = 0;
489                 /* Socket layer is responsible for issuing SIGPIPE. */
490                 if (error == EPIPE) {
491                         get_mplock();
492                         lwpsignal(lp->lwp_proc, lp, SIGPIPE);
493                         rel_mplock();
494                 }
495         }
496 #ifdef KTRACE
497         if (ktriov != NULL) {
498                 if (error == 0) {
499                         ktruio.uio_iov = ktriov;
500                         ktruio.uio_resid = len - auio->uio_resid;
501                         get_mplock();
502                         ktrgenio(lp, fd, UIO_WRITE, &ktruio, error);
503                         rel_mplock();
504                 }
505                 FREE(ktriov, M_TEMP);
506         }
507 #endif
508         if (error == 0)
509                 *res = len - auio->uio_resid;
510
511         return(error);
512 }
513
514 /*
515  * Ioctl system call
516  */
517 /* ARGSUSED */
518 int
519 sys_ioctl(struct ioctl_args *uap)
520 {
521         return(mapped_ioctl(uap->fd, uap->com, uap->data, NULL));
522 }
523
524 struct ioctl_map_entry {
525         const char *subsys;
526         struct ioctl_map_range *cmd_ranges;
527         LIST_ENTRY(ioctl_map_entry) entries;
528 };
529
530 /*
531  * The true heart of all ioctl syscall handlers (native, emulation).
532  * If map != NULL, it will be searched for a matching entry for com,
533  * and appropriate conversions/conversion functions will be utilized.
534  */
535 int
536 mapped_ioctl(int fd, u_long com, caddr_t uspc_data, struct ioctl_map *map)
537 {
538         struct thread *td = curthread;
539         struct proc *p = td->td_proc;
540         struct ucred *cred;
541         struct file *fp;
542         struct ioctl_map_range *iomc = NULL;
543         int error;
544         u_int size;
545         u_long ocom = com;
546         caddr_t data, memp;
547         int tmp;
548 #define STK_PARAMS      128
549         union {
550             char stkbuf[STK_PARAMS];
551             long align;
552         } ubuf;
553
554         KKASSERT(p);
555         cred = p->p_ucred;
556
557         fp = holdfp(p->p_fd, fd, FREAD|FWRITE);
558         if (fp == NULL)
559                 return(EBADF);
560
561         if (map != NULL) {      /* obey translation map */
562                 u_long maskcmd;
563                 struct ioctl_map_entry *e;
564
565                 maskcmd = com & map->mask;
566
567                 LIST_FOREACH(e, &map->mapping, entries) {
568                         for (iomc = e->cmd_ranges; iomc->start != 0 ||
569                              iomc->maptocmd != 0 || iomc->wrapfunc != NULL ||
570                              iomc->mapfunc != NULL;
571                              iomc++) {
572                                 if (maskcmd >= iomc->start &&
573                                     maskcmd <= iomc->end)
574                                         break;
575                         }
576
577                         /* Did we find a match? */
578                         if (iomc->start != 0 || iomc->maptocmd != 0 ||
579                             iomc->wrapfunc != NULL || iomc->mapfunc != NULL)
580                                 break;
581                 }
582
583                 if (iomc == NULL ||
584                     (iomc->start == 0 && iomc->maptocmd == 0
585                      && iomc->wrapfunc == NULL && iomc->mapfunc == NULL)) {
586                         kprintf("%s: 'ioctl' fd=%d, cmd=0x%lx ('%c',%d) not implemented\n",
587                                map->sys, fd, maskcmd,
588                                (int)((maskcmd >> 8) & 0xff),
589                                (int)(maskcmd & 0xff));
590                         error = EINVAL;
591                         goto done;
592                 }
593
594                 /*
595                  * If it's a non-range one to one mapping, maptocmd should be
596                  * correct. If it's a ranged one to one mapping, we pass the
597                  * original value of com, and for a range mapped to a different
598                  * range, we always need a mapping function to translate the
599                  * ioctl to our native ioctl. Ex. 6500-65ff <-> 9500-95ff
600                  */
601                 if (iomc->start == iomc->end && iomc->maptocmd == iomc->maptoend) {
602                         com = iomc->maptocmd;
603                 } else if (iomc->start == iomc->maptocmd && iomc->end == iomc->maptoend) {
604                         if (iomc->mapfunc != NULL)
605                                 com = iomc->mapfunc(iomc->start, iomc->end,
606                                                     iomc->start, iomc->end,
607                                                     com, com);
608                 } else {
609                         if (iomc->mapfunc != NULL) {
610                                 com = iomc->mapfunc(iomc->start, iomc->end,
611                                                     iomc->maptocmd, iomc->maptoend,
612                                                     com, ocom);
613                         } else {
614                                 kprintf("%s: Invalid mapping for fd=%d, cmd=%#lx ('%c',%d)\n",
615                                        map->sys, fd, maskcmd,
616                                        (int)((maskcmd >> 8) & 0xff),
617                                        (int)(maskcmd & 0xff));
618                                 error = EINVAL;
619                                 goto done;
620                         }
621                 }
622         }
623
624         switch (com) {
625         case FIONCLEX:
626                 error = fclrfdflags(p->p_fd, fd, UF_EXCLOSE);
627                 goto done;
628         case FIOCLEX:
629                 error = fsetfdflags(p->p_fd, fd, UF_EXCLOSE);
630                 goto done;
631         }
632
633         /*
634          * Interpret high order word to find amount of data to be
635          * copied to/from the user's address space.
636          */
637         size = IOCPARM_LEN(com);
638         if (size > IOCPARM_MAX) {
639                 error = ENOTTY;
640                 goto done;
641         }
642
643         memp = NULL;
644         if (size > sizeof (ubuf.stkbuf)) {
645                 memp = kmalloc(size, M_IOCTLOPS, M_WAITOK);
646                 data = memp;
647         } else {
648                 data = ubuf.stkbuf;
649         }
650         if ((com & IOC_IN) != 0) {
651                 if (size != 0) {
652                         error = copyin(uspc_data, data, (size_t)size);
653                         if (error) {
654                                 if (memp != NULL)
655                                         kfree(memp, M_IOCTLOPS);
656                                 goto done;
657                         }
658                 } else {
659                         *(caddr_t *)data = uspc_data;
660                 }
661         } else if ((com & IOC_OUT) != 0 && size) {
662                 /*
663                  * Zero the buffer so the user always
664                  * gets back something deterministic.
665                  */
666                 bzero(data, (size_t)size);
667         } else if ((com & IOC_VOID) != 0) {
668                 *(caddr_t *)data = uspc_data;
669         }
670
671         switch (com) {
672         case FIONBIO:
673                 if ((tmp = *(int *)data))
674                         fp->f_flag |= FNONBLOCK;
675                 else
676                         fp->f_flag &= ~FNONBLOCK;
677                 error = 0;
678                 break;
679
680         case FIOASYNC:
681                 if ((tmp = *(int *)data))
682                         fp->f_flag |= FASYNC;
683                 else
684                         fp->f_flag &= ~FASYNC;
685                 error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp, cred);
686                 break;
687
688         default:
689                 /*
690                  *  If there is a override function,
691                  *  call it instead of directly routing the call
692                  */
693                 if (map != NULL && iomc->wrapfunc != NULL)
694                         error = iomc->wrapfunc(fp, com, ocom, data, cred);
695                 else
696                         error = fo_ioctl(fp, com, data, cred);
697                 /*
698                  * Copy any data to user, size was
699                  * already set and checked above.
700                  */
701                 if (error == 0 && (com & IOC_OUT) != 0 && size != 0)
702                         error = copyout(data, uspc_data, (size_t)size);
703                 break;
704         }
705         if (memp != NULL)
706                 kfree(memp, M_IOCTLOPS);
707 done:
708         fdrop(fp);
709         return(error);
710 }
711
712 int
713 mapped_ioctl_register_handler(struct ioctl_map_handler *he)
714 {
715         struct ioctl_map_entry *ne;
716
717         KKASSERT(he != NULL && he->map != NULL && he->cmd_ranges != NULL &&
718                  he->subsys != NULL && *he->subsys != '\0');
719
720         ne = kmalloc(sizeof(struct ioctl_map_entry), M_IOCTLMAP, M_WAITOK);
721
722         ne->subsys = he->subsys;
723         ne->cmd_ranges = he->cmd_ranges;
724
725         LIST_INSERT_HEAD(&he->map->mapping, ne, entries);
726
727         return(0);
728 }
729
730 int
731 mapped_ioctl_unregister_handler(struct ioctl_map_handler *he)
732 {
733         struct ioctl_map_entry *ne;
734
735         KKASSERT(he != NULL && he->map != NULL && he->cmd_ranges != NULL);
736
737         LIST_FOREACH(ne, &he->map->mapping, entries) {
738                 if (ne->cmd_ranges != he->cmd_ranges)
739                         continue;
740                 LIST_REMOVE(ne, entries);
741                 kfree(ne, M_IOCTLMAP);
742                 return(0);
743         }
744         return(EINVAL);
745 }
746
747 static int      nselcoll;       /* Select collisions since boot */
748 int     selwait;
749 SYSCTL_INT(_kern, OID_AUTO, nselcoll, CTLFLAG_RD, &nselcoll, 0, "");
750
751 /*
752  * Select system call.
753  */
754 int
755 sys_select(struct select_args *uap)
756 {
757         struct timeval ktv;
758         struct timeval *ktvp;
759         int error;
760
761         /*
762          * Get timeout if any.
763          */
764         if (uap->tv != NULL) {
765                 error = copyin(uap->tv, &ktv, sizeof (ktv));
766                 if (error)
767                         return (error);
768                 error = itimerfix(&ktv);
769                 if (error)
770                         return (error);
771                 ktvp = &ktv;
772         } else {
773                 ktvp = NULL;
774         }
775
776         /*
777          * Do real work.
778          */
779         error = doselect(uap->nd, uap->in, uap->ou, uap->ex, ktvp,
780                         &uap->sysmsg_result);
781
782         return (error);
783 }
784
785
786 /*
787  * Pselect system call.
788  */
789 int
790 sys_pselect(struct pselect_args *uap)
791 {
792         struct thread *td = curthread;
793         struct lwp *lp = td->td_lwp;
794         struct timespec kts;
795         struct timeval ktv;
796         struct timeval *ktvp;
797         sigset_t sigmask;
798         int error;
799
800         /*
801          * Get timeout if any and convert it.
802          * Round up during conversion to avoid timeout going off early.
803          */
804         if (uap->ts != NULL) {
805                 error = copyin(uap->ts, &kts, sizeof (kts));
806                 if (error)
807                         return (error);
808                 ktv.tv_sec = kts.tv_sec;
809                 ktv.tv_usec = (kts.tv_nsec + 999) / 1000;
810                 error = itimerfix(&ktv);
811                 if (error)
812                         return (error);
813                 ktvp = &ktv;
814         } else {
815                 ktvp = NULL;
816         }
817
818         /*
819          * Install temporary signal mask if any provided.
820          */
821         if (uap->sigmask != NULL) {
822                 error = copyin(uap->sigmask, &sigmask, sizeof(sigmask));
823                 if (error)
824                         return (error);
825                 lp->lwp_oldsigmask = lp->lwp_sigmask;
826                 SIG_CANTMASK(sigmask);
827                 lp->lwp_sigmask = sigmask;
828         }
829
830         /*
831          * Do real job.
832          */
833         error = doselect(uap->nd, uap->in, uap->ou, uap->ex, ktvp,
834                         &uap->sysmsg_result);
835
836         if (uap->sigmask != NULL) {
837                 /* doselect() responsible for turning ERESTART into EINTR */
838                 KKASSERT(error != ERESTART);
839                 if (error == EINTR) {
840                         /*
841                          * We can't restore the previous signal mask now
842                          * because it could block the signal that interrupted
843                          * us.  So make a note to restore it after executing
844                          * the handler.
845                          */
846                         lp->lwp_flag |= LWP_OLDMASK;
847                 } else {
848                         /*
849                          * No handler to run. Restore previous mask immediately.
850                          */
851                         lp->lwp_sigmask = lp->lwp_oldsigmask;
852                 }
853         }
854
855         return (error);
856 }
857
858 /*
859  * Common code for sys_select() and sys_pselect().
860  *
861  * in, out and ex are userland pointers.  tv must point to validated
862  * kernel-side timeout value or NULL for infinite timeout.  res must
863  * point to syscall return value.
864  */
865 static int
866 doselect(int nd, fd_set *in, fd_set *ou, fd_set *ex, struct timeval *tv,
867                 int *res)
868 {
869         struct lwp *lp = curthread->td_lwp;
870         struct proc *p = curproc;
871
872         /*
873          * The magic 2048 here is chosen to be just enough for FD_SETSIZE
874          * infds with the new FD_SETSIZE of 1024, and more than enough for
875          * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
876          * of 256.
877          */
878         fd_mask s_selbits[howmany(2048, NFDBITS)];
879         fd_mask *ibits[3], *obits[3], *selbits, *sbp;
880         struct timeval atv, rtv, ttv;
881         int ncoll, error, timo;
882         u_int nbufbytes, ncpbytes, nfdbits;
883
884         if (nd < 0)
885                 return (EINVAL);
886         if (nd > p->p_fd->fd_nfiles)
887                 nd = p->p_fd->fd_nfiles;   /* forgiving; slightly wrong */
888
889         /*
890          * Allocate just enough bits for the non-null fd_sets.  Use the
891          * preallocated auto buffer if possible.
892          */
893         nfdbits = roundup(nd, NFDBITS);
894         ncpbytes = nfdbits / NBBY;
895         nbufbytes = 0;
896         if (in != NULL)
897                 nbufbytes += 2 * ncpbytes;
898         if (ou != NULL)
899                 nbufbytes += 2 * ncpbytes;
900         if (ex != NULL)
901                 nbufbytes += 2 * ncpbytes;
902         if (nbufbytes <= sizeof s_selbits)
903                 selbits = &s_selbits[0];
904         else
905                 selbits = kmalloc(nbufbytes, M_SELECT, M_WAITOK);
906
907         /*
908          * Assign pointers into the bit buffers and fetch the input bits.
909          * Put the output buffers together so that they can be bzeroed
910          * together.
911          */
912         sbp = selbits;
913 #define getbits(name, x) \
914         do {                                                            \
915                 if (name == NULL)                                       \
916                         ibits[x] = NULL;                                \
917                 else {                                                  \
918                         ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp;   \
919                         obits[x] = sbp;                                 \
920                         sbp += ncpbytes / sizeof *sbp;                  \
921                         error = copyin(name, ibits[x], ncpbytes);       \
922                         if (error != 0)                                 \
923                                 goto done;                              \
924                 }                                                       \
925         } while (0)
926         getbits(in, 0);
927         getbits(ou, 1);
928         getbits(ex, 2);
929 #undef  getbits
930         if (nbufbytes != 0)
931                 bzero(selbits, nbufbytes / 2);
932
933         if (tv != NULL) {
934                 atv = *tv;
935                 getmicrouptime(&rtv);
936                 timevaladd(&atv, &rtv);
937         } else {
938                 atv.tv_sec = 0;
939                 atv.tv_usec = 0;
940         }
941         timo = 0;
942 retry:
943         ncoll = nselcoll;
944         lp->lwp_flag |= LWP_SELECT;
945         error = selscan(p, ibits, obits, nd, res);
946         if (error || *res)
947                 goto done;
948         if (atv.tv_sec || atv.tv_usec) {
949                 getmicrouptime(&rtv);
950                 if (timevalcmp(&rtv, &atv, >=))
951                         goto done;
952                 ttv = atv;
953                 timevalsub(&ttv, &rtv);
954                 timo = ttv.tv_sec > 24 * 60 * 60 ?
955                     24 * 60 * 60 * hz : tvtohz_high(&ttv);
956         }
957         crit_enter();
958         if ((lp->lwp_flag & LWP_SELECT) == 0 || nselcoll != ncoll) {
959                 crit_exit();
960                 goto retry;
961         }
962         lp->lwp_flag &= ~LWP_SELECT;
963
964         error = tsleep((caddr_t)&selwait, PCATCH, "select", timo);
965         
966         crit_exit();
967         if (error == 0)
968                 goto retry;
969 done:
970         lp->lwp_flag &= ~LWP_SELECT;
971         /* select is not restarted after signals... */
972         if (error == ERESTART)
973                 error = EINTR;
974         if (error == EWOULDBLOCK)
975                 error = 0;
976 #define putbits(name, x) \
977         if (name && (error2 = copyout(obits[x], name, ncpbytes))) \
978                 error = error2;
979         if (error == 0) {
980                 int error2;
981
982                 putbits(in, 0);
983                 putbits(ou, 1);
984                 putbits(ex, 2);
985 #undef putbits
986         }
987         if (selbits != &s_selbits[0])
988                 kfree(selbits, M_SELECT);
989         return (error);
990 }
991
992 static int
993 selscan(struct proc *p, fd_mask **ibits, fd_mask **obits, int nfd, int *res)
994 {
995         int msk, i, fd;
996         fd_mask bits;
997         struct file *fp;
998         int n = 0;
999         /* Note: backend also returns POLLHUP/POLLERR if appropriate. */
1000         static int flag[3] = { POLLRDNORM, POLLWRNORM, POLLRDBAND };
1001
1002         for (msk = 0; msk < 3; msk++) {
1003                 if (ibits[msk] == NULL)
1004                         continue;
1005                 for (i = 0; i < nfd; i += NFDBITS) {
1006                         bits = ibits[msk][i/NFDBITS];
1007                         /* ffs(int mask) not portable, fd_mask is long */
1008                         for (fd = i; bits && fd < nfd; fd++, bits >>= 1) {
1009                                 if (!(bits & 1))
1010                                         continue;
1011                                 fp = holdfp(p->p_fd, fd, -1);
1012                                 if (fp == NULL)
1013                                         return (EBADF);
1014                                 if (fo_poll(fp, flag[msk], fp->f_cred)) {
1015                                         obits[msk][(fd)/NFDBITS] |=
1016                                             ((fd_mask)1 << ((fd) % NFDBITS));
1017                                         n++;
1018                                 }
1019                                 fdrop(fp);
1020                         }
1021                 }
1022         }
1023         *res = n;
1024         return (0);
1025 }
1026
1027 /*
1028  * Poll system call.
1029  */
1030 int
1031 sys_poll(struct poll_args *uap)
1032 {
1033         struct pollfd *bits;
1034         struct pollfd smallbits[32];
1035         struct timeval atv, rtv, ttv;
1036         int ncoll, error = 0, timo;
1037         u_int nfds;
1038         size_t ni;
1039         struct lwp *lp = curthread->td_lwp;
1040         struct proc *p = curproc;
1041
1042         nfds = uap->nfds;
1043         /*
1044          * This is kinda bogus.  We have fd limits, but that is not
1045          * really related to the size of the pollfd array.  Make sure
1046          * we let the process use at least FD_SETSIZE entries and at
1047          * least enough for the current limits.  We want to be reasonably
1048          * safe, but not overly restrictive.
1049          */
1050         if (nfds > p->p_rlimit[RLIMIT_NOFILE].rlim_cur && nfds > FD_SETSIZE)
1051                 return (EINVAL);
1052         ni = nfds * sizeof(struct pollfd);
1053         if (ni > sizeof(smallbits))
1054                 bits = kmalloc(ni, M_TEMP, M_WAITOK);
1055         else
1056                 bits = smallbits;
1057         error = copyin(uap->fds, bits, ni);
1058         if (error)
1059                 goto done;
1060         if (uap->timeout != INFTIM) {
1061                 atv.tv_sec = uap->timeout / 1000;
1062                 atv.tv_usec = (uap->timeout % 1000) * 1000;
1063                 if (itimerfix(&atv)) {
1064                         error = EINVAL;
1065                         goto done;
1066                 }
1067                 getmicrouptime(&rtv);
1068                 timevaladd(&atv, &rtv);
1069         } else {
1070                 atv.tv_sec = 0;
1071                 atv.tv_usec = 0;
1072         }
1073         timo = 0;
1074 retry:
1075         ncoll = nselcoll;
1076         lp->lwp_flag |= LWP_SELECT;
1077         error = pollscan(p, bits, nfds, &uap->sysmsg_result);
1078         if (error || uap->sysmsg_result)
1079                 goto done;
1080         if (atv.tv_sec || atv.tv_usec) {
1081                 getmicrouptime(&rtv);
1082                 if (timevalcmp(&rtv, &atv, >=))
1083                         goto done;
1084                 ttv = atv;
1085                 timevalsub(&ttv, &rtv);
1086                 timo = ttv.tv_sec > 24 * 60 * 60 ?
1087                     24 * 60 * 60 * hz : tvtohz_high(&ttv);
1088         } 
1089         crit_enter();
1090         if ((lp->lwp_flag & LWP_SELECT) == 0 || nselcoll != ncoll) {
1091                 crit_exit();
1092                 goto retry;
1093         }
1094         lp->lwp_flag &= ~LWP_SELECT;
1095         error = tsleep((caddr_t)&selwait, PCATCH, "poll", timo);
1096         crit_exit();
1097         if (error == 0)
1098                 goto retry;
1099 done:
1100         lp->lwp_flag &= ~LWP_SELECT;
1101         /* poll is not restarted after signals... */
1102         if (error == ERESTART)
1103                 error = EINTR;
1104         if (error == EWOULDBLOCK)
1105                 error = 0;
1106         if (error == 0) {
1107                 error = copyout(bits, uap->fds, ni);
1108                 if (error)
1109                         goto out;
1110         }
1111 out:
1112         if (ni > sizeof(smallbits))
1113                 kfree(bits, M_TEMP);
1114         return (error);
1115 }
1116
1117 static int
1118 pollscan(struct proc *p, struct pollfd *fds, u_int nfd, int *res)
1119 {
1120         int i;
1121         struct file *fp;
1122         int n = 0;
1123
1124         for (i = 0; i < nfd; i++, fds++) {
1125                 if (fds->fd >= p->p_fd->fd_nfiles) {
1126                         fds->revents = POLLNVAL;
1127                         n++;
1128                 } else if (fds->fd < 0) {
1129                         fds->revents = 0;
1130                 } else {
1131                         fp = holdfp(p->p_fd, fds->fd, -1);
1132                         if (fp == NULL) {
1133                                 fds->revents = POLLNVAL;
1134                                 n++;
1135                         } else {
1136                                 /*
1137                                  * Note: backend also returns POLLHUP and
1138                                  * POLLERR if appropriate.
1139                                  */
1140                                 fds->revents = fo_poll(fp, fds->events,
1141                                                         fp->f_cred);
1142                                 if (fds->revents != 0)
1143                                         n++;
1144                                 fdrop(fp);
1145                         }
1146                 }
1147         }
1148         *res = n;
1149         return (0);
1150 }
1151
1152 /*
1153  * OpenBSD poll system call.
1154  * XXX this isn't quite a true representation..  OpenBSD uses select ops.
1155  */
1156 int
1157 sys_openbsd_poll(struct openbsd_poll_args *uap)
1158 {
1159         return (sys_poll((struct poll_args *)uap));
1160 }
1161
1162 /*ARGSUSED*/
1163 int
1164 seltrue(cdev_t dev, int events)
1165 {
1166         return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
1167 }
1168
1169 /*
1170  * Record a select request.  A global wait must be used since a process/thread
1171  * might go away after recording its request.
1172  */
1173 void
1174 selrecord(struct thread *selector, struct selinfo *sip)
1175 {
1176         struct proc *p;
1177         struct lwp *lp = NULL;
1178
1179         if (selector->td_lwp == NULL)
1180                 panic("selrecord: thread needs a process");
1181
1182         if (sip->si_pid == selector->td_proc->p_pid &&
1183             sip->si_tid == selector->td_lwp->lwp_tid)
1184                 return;
1185         if (sip->si_pid && (p = pfind(sip->si_pid)))
1186                 lp = lwp_rb_tree_RB_LOOKUP(&p->p_lwp_tree, sip->si_tid);
1187         if (lp != NULL && lp->lwp_wchan == (caddr_t)&selwait) {
1188                 sip->si_flags |= SI_COLL;
1189         } else {
1190                 sip->si_pid = selector->td_proc->p_pid;
1191                 sip->si_tid = selector->td_lwp->lwp_tid;
1192         }
1193 }
1194
1195 /*
1196  * Do a wakeup when a selectable event occurs.
1197  */
1198 void
1199 selwakeup(struct selinfo *sip)
1200 {
1201         struct proc *p;
1202         struct lwp *lp = NULL;
1203
1204         if (sip->si_pid == 0)
1205                 return;
1206         if (sip->si_flags & SI_COLL) {
1207                 nselcoll++;
1208                 sip->si_flags &= ~SI_COLL;
1209                 wakeup((caddr_t)&selwait);      /* YYY fixable */
1210         }
1211         p = pfind(sip->si_pid);
1212         sip->si_pid = 0;
1213         if (p == NULL)
1214                 return;
1215         lp = lwp_rb_tree_RB_LOOKUP(&p->p_lwp_tree, sip->si_tid);
1216         if (lp == NULL)
1217                 return;
1218
1219         crit_enter();
1220         if (lp->lwp_wchan == (caddr_t)&selwait) {
1221                 /*
1222                  * Flag the process to break the tsleep when
1223                  * setrunnable is called, but only call setrunnable
1224                  * here if the process is not in a stopped state.
1225                  */
1226                 lp->lwp_flag |= LWP_BREAKTSLEEP;
1227                 if (p->p_stat != SSTOP)
1228                         setrunnable(lp);
1229         } else if (lp->lwp_flag & LWP_SELECT) {
1230                 lp->lwp_flag &= ~LWP_SELECT;
1231         }
1232         crit_exit();
1233 }
1234